repo_name
string
path
string
copies
string
size
string
content
string
license
string
DutchDanny/samsung-gt-P7510-ics-3.1.10
arch/mips/txx9/generic/irq_tx4939.c
7679
5522
/* * TX4939 irq routines * Based on linux/arch/mips/kernel/irq_txx9.c, * and RBTX49xx patch from CELF patch archive. * * Copyright 2001, 2003-2005 MontaVista Software Inc. * Author: MontaVista Software, Inc. * ahennessy@mvista.com * source@mvista.com * Copyright (C) 2000-2001,2005-2007 Toshiba Corporation * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ /* * TX4939 defines 64 IRQs. * Similer to irq_txx9.c but different register layouts. */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/types.h> #include <asm/irq_cpu.h> #include <asm/txx9irq.h> #include <asm/txx9/tx4939.h> /* IRCER : Int. Control Enable */ #define TXx9_IRCER_ICE 0x00000001 /* IRCR : Int. Control */ #define TXx9_IRCR_LOW 0x00000000 #define TXx9_IRCR_HIGH 0x00000001 #define TXx9_IRCR_DOWN 0x00000002 #define TXx9_IRCR_UP 0x00000003 #define TXx9_IRCR_EDGE(cr) ((cr) & 0x00000002) /* IRSCR : Int. Status Control */ #define TXx9_IRSCR_EIClrE 0x00000100 #define TXx9_IRSCR_EIClr_MASK 0x0000000f /* IRCSR : Int. Current Status */ #define TXx9_IRCSR_IF 0x00010000 #define irc_dlevel 0 #define irc_elevel 1 static struct { unsigned char level; unsigned char mode; } tx4939irq[TX4939_NUM_IR] __read_mostly; static void tx4939_irq_unmask(struct irq_data *d) { unsigned int irq_nr = d->irq - TXX9_IRQ_BASE; u32 __iomem *lvlp; int ofs; if (irq_nr < 32) { irq_nr--; lvlp = &tx4939_ircptr->lvl[(irq_nr % 16) / 2].r; } else { irq_nr -= 32; lvlp = &tx4939_ircptr->lvl[8 + (irq_nr % 16) / 2].r; } ofs = (irq_nr & 16) + (irq_nr & 1) * 8; __raw_writel((__raw_readl(lvlp) & ~(0xff << ofs)) | (tx4939irq[irq_nr].level << ofs), lvlp); } static inline void tx4939_irq_mask(struct irq_data *d) { unsigned int irq_nr = d->irq - TXX9_IRQ_BASE; u32 __iomem *lvlp; int ofs; if (irq_nr < 32) { irq_nr--; lvlp = &tx4939_ircptr->lvl[(irq_nr % 16) / 2].r; } else { irq_nr -= 32; lvlp = &tx4939_ircptr->lvl[8 + (irq_nr % 16) / 2].r; } ofs = (irq_nr & 16) + (irq_nr & 1) * 8; __raw_writel((__raw_readl(lvlp) & ~(0xff << ofs)) | (irc_dlevel << ofs), lvlp); mmiowb(); } static void tx4939_irq_mask_ack(struct irq_data *d) { unsigned int irq_nr = d->irq - TXX9_IRQ_BASE; tx4939_irq_mask(d); if (TXx9_IRCR_EDGE(tx4939irq[irq_nr].mode)) { irq_nr--; /* clear edge detection */ __raw_writel((TXx9_IRSCR_EIClrE | (irq_nr & 0xf)) << (irq_nr & 0x10), &tx4939_ircptr->edc.r); } } static int tx4939_irq_set_type(struct irq_data *d, unsigned int flow_type) { unsigned int irq_nr = d->irq - TXX9_IRQ_BASE; u32 cr; u32 __iomem *crp; int ofs; int mode; if (flow_type & IRQF_TRIGGER_PROBE) return 0; switch (flow_type & IRQF_TRIGGER_MASK) { case IRQF_TRIGGER_RISING: mode = TXx9_IRCR_UP; break; case IRQF_TRIGGER_FALLING: mode = TXx9_IRCR_DOWN; break; case IRQF_TRIGGER_HIGH: mode = TXx9_IRCR_HIGH; break; case IRQF_TRIGGER_LOW: mode = TXx9_IRCR_LOW; break; default: return -EINVAL; } if (irq_nr < 32) { irq_nr--; crp = &tx4939_ircptr->dm[(irq_nr & 8) >> 3].r; } else { irq_nr -= 32; crp = &tx4939_ircptr->dm2[((irq_nr & 8) >> 3)].r; } ofs = (((irq_nr & 16) >> 1) | (irq_nr & (8 - 1))) * 2; cr = __raw_readl(crp); cr &= ~(0x3 << ofs); cr |= (mode & 0x3) << ofs; __raw_writel(cr, crp); tx4939irq[irq_nr].mode = mode; return 0; } static struct irq_chip tx4939_irq_chip = { .name = "TX4939", .irq_ack = tx4939_irq_mask_ack, .irq_mask = tx4939_irq_mask, .irq_mask_ack = tx4939_irq_mask_ack, .irq_unmask = tx4939_irq_unmask, .irq_set_type = tx4939_irq_set_type, }; static int tx4939_irq_set_pri(int irc_irq, int new_pri) { int old_pri; if ((unsigned int)irc_irq >= TX4939_NUM_IR) return 0; old_pri = tx4939irq[irc_irq].level; tx4939irq[irc_irq].level = new_pri; return old_pri; } void __init tx4939_irq_init(void) { int i; mips_cpu_irq_init(); /* disable interrupt control */ __raw_writel(0, &tx4939_ircptr->den.r); __raw_writel(0, &tx4939_ircptr->maskint.r); __raw_writel(0, &tx4939_ircptr->maskext.r); /* irq_base + 0 is not used */ for (i = 1; i < TX4939_NUM_IR; i++) { tx4939irq[i].level = 4; /* middle level */ tx4939irq[i].mode = TXx9_IRCR_LOW; irq_set_chip_and_handler(TXX9_IRQ_BASE + i, &tx4939_irq_chip, handle_level_irq); } /* mask all IRC interrupts */ __raw_writel(0, &tx4939_ircptr->msk.r); for (i = 0; i < 16; i++) __raw_writel(0, &tx4939_ircptr->lvl[i].r); /* setup IRC interrupt mode (Low Active) */ for (i = 0; i < 2; i++) __raw_writel(0, &tx4939_ircptr->dm[i].r); for (i = 0; i < 2; i++) __raw_writel(0, &tx4939_ircptr->dm2[i].r); /* enable interrupt control */ __raw_writel(TXx9_IRCER_ICE, &tx4939_ircptr->den.r); __raw_writel(irc_elevel, &tx4939_ircptr->msk.r); irq_set_chained_handler(MIPS_CPU_IRQ_BASE + TX4939_IRC_INT, handle_simple_irq); /* raise priority for errors, timers, sio */ tx4939_irq_set_pri(TX4939_IR_WTOERR, 7); tx4939_irq_set_pri(TX4939_IR_PCIERR, 7); tx4939_irq_set_pri(TX4939_IR_PCIPME, 7); for (i = 0; i < TX4939_NUM_IR_TMR; i++) tx4939_irq_set_pri(TX4939_IR_TMR(i), 6); for (i = 0; i < TX4939_NUM_IR_SIO; i++) tx4939_irq_set_pri(TX4939_IR_SIO(i), 5); } int tx4939_irq(void) { u32 csr = __raw_readl(&tx4939_ircptr->cs.r); if (likely(!(csr & TXx9_IRCSR_IF))) return TXX9_IRQ_BASE + (csr & (TX4939_NUM_IR - 1)); return -1; }
gpl-2.0
GlitchKernel/Glitch-i9300
fs/nfsd/nfs3acl.c
9215
6488
/* * Process version 3 NFSACL requests. * * Copyright (C) 2002-2003 Andreas Gruenbacher <agruen@suse.de> */ #include "nfsd.h" /* FIXME: nfsacl.h is a broken header */ #include <linux/nfsacl.h> #include <linux/gfp.h> #include "cache.h" #include "xdr3.h" #include "vfs.h" #define RETURN_STATUS(st) { resp->status = (st); return (st); } /* * NULL call. */ static __be32 nfsd3_proc_null(struct svc_rqst *rqstp, void *argp, void *resp) { return nfs_ok; } /* * Get the Access and/or Default ACL of a file. */ static __be32 nfsd3_proc_getacl(struct svc_rqst * rqstp, struct nfsd3_getaclargs *argp, struct nfsd3_getaclres *resp) { svc_fh *fh; struct posix_acl *acl; __be32 nfserr = 0; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP); if (nfserr) RETURN_STATUS(nfserr); if (argp->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT)) RETURN_STATUS(nfserr_inval); resp->mask = argp->mask; if (resp->mask & (NFS_ACL|NFS_ACLCNT)) { acl = nfsd_get_posix_acl(fh, ACL_TYPE_ACCESS); if (IS_ERR(acl)) { int err = PTR_ERR(acl); if (err == -ENODATA || err == -EOPNOTSUPP) acl = NULL; else { nfserr = nfserrno(err); goto fail; } } if (acl == NULL) { /* Solaris returns the inode's minimum ACL. */ struct inode *inode = fh->fh_dentry->d_inode; acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL); } resp->acl_access = acl; } if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) { /* Check how Solaris handles requests for the Default ACL of a non-directory! */ acl = nfsd_get_posix_acl(fh, ACL_TYPE_DEFAULT); if (IS_ERR(acl)) { int err = PTR_ERR(acl); if (err == -ENODATA || err == -EOPNOTSUPP) acl = NULL; else { nfserr = nfserrno(err); goto fail; } } resp->acl_default = acl; } /* resp->acl_{access,default} are released in nfs3svc_release_getacl. */ RETURN_STATUS(0); fail: posix_acl_release(resp->acl_access); posix_acl_release(resp->acl_default); RETURN_STATUS(nfserr); } /* * Set the Access and/or Default ACL of a file. */ static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd3_attrstat *resp) { svc_fh *fh; __be32 nfserr = 0; fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (!nfserr) { nfserr = nfserrno( nfsd_set_posix_acl( fh, ACL_TYPE_ACCESS, argp->acl_access) ); } if (!nfserr) { nfserr = nfserrno( nfsd_set_posix_acl( fh, ACL_TYPE_DEFAULT, argp->acl_default) ); } /* argp->acl_{access,default} may have been allocated in nfs3svc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); RETURN_STATUS(nfserr); } /* * XDR decode functions */ static int nfs3svc_decode_getaclargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_getaclargs *args) { if (!(p = nfs3svc_decode_fh(p, &args->fh))) return 0; args->mask = ntohl(*p); p++; return xdr_argsize_check(rqstp, p); } static int nfs3svc_decode_setaclargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_setaclargs *args) { struct kvec *head = rqstp->rq_arg.head; unsigned int base; int n; if (!(p = nfs3svc_decode_fh(p, &args->fh))) return 0; args->mask = ntohl(*p++); if (args->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT) || !xdr_argsize_check(rqstp, p)) return 0; base = (char *)p - (char *)head->iov_base; n = nfsacl_decode(&rqstp->rq_arg, base, NULL, (args->mask & NFS_ACL) ? &args->acl_access : NULL); if (n > 0) n = nfsacl_decode(&rqstp->rq_arg, base + n, NULL, (args->mask & NFS_DFACL) ? &args->acl_default : NULL); return (n > 0); } /* * XDR encode functions */ /* GETACL */ static int nfs3svc_encode_getaclres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_getaclres *resp) { struct dentry *dentry = resp->fh.fh_dentry; p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0 && dentry && dentry->d_inode) { struct inode *inode = dentry->d_inode; struct kvec *head = rqstp->rq_res.head; unsigned int base; int n; int w; *p++ = htonl(resp->mask); if (!xdr_ressize_check(rqstp, p)) return 0; base = (char *)p - (char *)head->iov_base; rqstp->rq_res.page_len = w = nfsacl_size( (resp->mask & NFS_ACL) ? resp->acl_access : NULL, (resp->mask & NFS_DFACL) ? resp->acl_default : NULL); while (w > 0) { if (!rqstp->rq_respages[rqstp->rq_resused++]) return 0; w -= PAGE_SIZE; } n = nfsacl_encode(&rqstp->rq_res, base, inode, resp->acl_access, resp->mask & NFS_ACL, 0); if (n > 0) n = nfsacl_encode(&rqstp->rq_res, base + n, inode, resp->acl_default, resp->mask & NFS_DFACL, NFS_ACL_DEFAULT); if (n <= 0) return 0; } else if (!xdr_ressize_check(rqstp, p)) return 0; return 1; } /* SETACL */ static int nfs3svc_encode_setaclres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_attrstat *resp) { p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh); return xdr_ressize_check(rqstp, p); } /* * XDR release functions */ static int nfs3svc_release_getacl(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_getaclres *resp) { fh_put(&resp->fh); posix_acl_release(resp->acl_access); posix_acl_release(resp->acl_default); return 1; } #define nfs3svc_decode_voidargs NULL #define nfs3svc_release_void NULL #define nfsd3_setaclres nfsd3_attrstat #define nfsd3_voidres nfsd3_voidargs struct nfsd3_voidargs { int dummy; }; #define PROC(name, argt, rest, relt, cache, respsize) \ { (svc_procfunc) nfsd3_proc_##name, \ (kxdrproc_t) nfs3svc_decode_##argt##args, \ (kxdrproc_t) nfs3svc_encode_##rest##res, \ (kxdrproc_t) nfs3svc_release_##relt, \ sizeof(struct nfsd3_##argt##args), \ sizeof(struct nfsd3_##rest##res), \ 0, \ cache, \ respsize, \ } #define ST 1 /* status*/ #define AT 21 /* attributes */ #define pAT (1+AT) /* post attributes - conditional */ #define ACL (1+NFS_ACL_MAX_ENTRIES*3) /* Access Control List */ static struct svc_procedure nfsd_acl_procedures3[] = { PROC(null, void, void, void, RC_NOCACHE, ST), PROC(getacl, getacl, getacl, getacl, RC_NOCACHE, ST+1+2*(1+ACL)), PROC(setacl, setacl, setacl, fhandle, RC_NOCACHE, ST+pAT), }; struct svc_version nfsd_acl_version3 = { .vs_vers = 3, .vs_nproc = 3, .vs_proc = nfsd_acl_procedures3, .vs_dispatch = nfsd_dispatch, .vs_xdrsize = NFS3_SVC_XDRSIZE, .vs_hidden = 0, };
gpl-2.0
GustavoRD78/78Kernel-5.1.1-23.4.A.0.546
drivers/media/rc/keymaps/rc-avermedia-rm-ks.c
9215
2336
/* * AverMedia RM-KS remote controller keytable * * Copyright (C) 2010 Antti Palosaari <crope@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <media/rc-map.h> #include <linux/module.h> /* Initial keytable is from Jose Alberto Reguero <jareguero@telefonica.net> and Felipe Morales Moreno <felipe.morales.moreno@gmail.com> */ /* FIXME: mappings are not 100% correct? */ static struct rc_map_table avermedia_rm_ks[] = { { 0x0501, KEY_POWER2 }, { 0x0502, KEY_CHANNELUP }, { 0x0503, KEY_CHANNELDOWN }, { 0x0504, KEY_VOLUMEUP }, { 0x0505, KEY_VOLUMEDOWN }, { 0x0506, KEY_MUTE }, { 0x0507, KEY_RIGHT }, { 0x0508, KEY_RED }, { 0x0509, KEY_1 }, { 0x050a, KEY_2 }, { 0x050b, KEY_3 }, { 0x050c, KEY_4 }, { 0x050d, KEY_5 }, { 0x050e, KEY_6 }, { 0x050f, KEY_7 }, { 0x0510, KEY_8 }, { 0x0511, KEY_9 }, { 0x0512, KEY_0 }, { 0x0513, KEY_AUDIO }, { 0x0515, KEY_EPG }, { 0x0516, KEY_PLAY }, { 0x0517, KEY_RECORD }, { 0x0518, KEY_STOP }, { 0x051c, KEY_BACK }, { 0x051d, KEY_FORWARD }, { 0x054d, KEY_LEFT }, { 0x0556, KEY_ZOOM }, }; static struct rc_map_list avermedia_rm_ks_map = { .map = { .scan = avermedia_rm_ks, .size = ARRAY_SIZE(avermedia_rm_ks), .rc_type = RC_TYPE_NEC, .name = RC_MAP_AVERMEDIA_RM_KS, } }; static int __init init_rc_map_avermedia_rm_ks(void) { return rc_map_register(&avermedia_rm_ks_map); } static void __exit exit_rc_map_avermedia_rm_ks(void) { rc_map_unregister(&avermedia_rm_ks_map); } module_init(init_rc_map_avermedia_rm_ks) module_exit(exit_rc_map_avermedia_rm_ks) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
gpl-2.0
CmptrGk/kernel-msm
drivers/input/misc/gpio_axis.c
9983
5861
/* drivers/input/misc/gpio_axis.c * * Copyright (C) 2007 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/kernel.h> #include <linux/gpio.h> #include <linux/gpio_event.h> #include <linux/interrupt.h> #include <linux/slab.h> struct gpio_axis_state { struct gpio_event_input_devs *input_devs; struct gpio_event_axis_info *info; uint32_t pos; }; uint16_t gpio_axis_4bit_gray_map_table[] = { [0x0] = 0x0, [0x1] = 0x1, /* 0000 0001 */ [0x3] = 0x2, [0x2] = 0x3, /* 0011 0010 */ [0x6] = 0x4, [0x7] = 0x5, /* 0110 0111 */ [0x5] = 0x6, [0x4] = 0x7, /* 0101 0100 */ [0xc] = 0x8, [0xd] = 0x9, /* 1100 1101 */ [0xf] = 0xa, [0xe] = 0xb, /* 1111 1110 */ [0xa] = 0xc, [0xb] = 0xd, /* 1010 1011 */ [0x9] = 0xe, [0x8] = 0xf, /* 1001 1000 */ }; uint16_t gpio_axis_4bit_gray_map(struct gpio_event_axis_info *info, uint16_t in) { return gpio_axis_4bit_gray_map_table[in]; } uint16_t gpio_axis_5bit_singletrack_map_table[] = { [0x10] = 0x00, [0x14] = 0x01, [0x1c] = 0x02, /* 10000 10100 11100 */ [0x1e] = 0x03, [0x1a] = 0x04, [0x18] = 0x05, /* 11110 11010 11000 */ [0x08] = 0x06, [0x0a] = 0x07, [0x0e] = 0x08, /* 01000 01010 01110 */ [0x0f] = 0x09, [0x0d] = 0x0a, [0x0c] = 0x0b, /* 01111 01101 01100 */ [0x04] = 0x0c, [0x05] = 0x0d, [0x07] = 0x0e, /* 00100 00101 00111 */ [0x17] = 0x0f, [0x16] = 0x10, [0x06] = 0x11, /* 10111 10110 00110 */ [0x02] = 0x12, [0x12] = 0x13, [0x13] = 0x14, /* 00010 10010 10011 */ [0x1b] = 0x15, [0x0b] = 0x16, [0x03] = 0x17, /* 11011 01011 00011 */ [0x01] = 0x18, [0x09] = 0x19, [0x19] = 0x1a, /* 00001 01001 11001 */ [0x1d] = 0x1b, [0x15] = 0x1c, [0x11] = 0x1d, /* 11101 10101 10001 */ }; uint16_t gpio_axis_5bit_singletrack_map( struct gpio_event_axis_info *info, uint16_t in) { return gpio_axis_5bit_singletrack_map_table[in]; } static void gpio_event_update_axis(struct gpio_axis_state *as, int report) { struct gpio_event_axis_info *ai = as->info; int i; int change; uint16_t state = 0; uint16_t pos; uint16_t old_pos = as->pos; for (i = ai->count - 1; i >= 0; i--) state = (state << 1) | gpio_get_value(ai->gpio[i]); pos = ai->map(ai, state); if (ai->flags & GPIOEAF_PRINT_RAW) pr_info("axis %d-%d raw %x, pos %d -> %d\n", ai->type, ai->code, state, old_pos, pos); if (report && pos != old_pos) { if (ai->type == EV_REL) { change = (ai->decoded_size + pos - old_pos) % ai->decoded_size; if (change > ai->decoded_size / 2) change -= ai->decoded_size; if (change == ai->decoded_size / 2) { if (ai->flags & GPIOEAF_PRINT_EVENT) pr_info("axis %d-%d unknown direction, " "pos %d -> %d\n", ai->type, ai->code, old_pos, pos); change = 0; /* no closest direction */ } if (ai->flags & GPIOEAF_PRINT_EVENT) pr_info("axis %d-%d change %d\n", ai->type, ai->code, change); input_report_rel(as->input_devs->dev[ai->dev], ai->code, change); } else { if (ai->flags & GPIOEAF_PRINT_EVENT) pr_info("axis %d-%d now %d\n", ai->type, ai->code, pos); input_event(as->input_devs->dev[ai->dev], ai->type, ai->code, pos); } input_sync(as->input_devs->dev[ai->dev]); } as->pos = pos; } static irqreturn_t gpio_axis_irq_handler(int irq, void *dev_id) { struct gpio_axis_state *as = dev_id; gpio_event_update_axis(as, 1); return IRQ_HANDLED; } int gpio_event_axis_func(struct gpio_event_input_devs *input_devs, struct gpio_event_info *info, void **data, int func) { int ret; int i; int irq; struct gpio_event_axis_info *ai; struct gpio_axis_state *as; ai = container_of(info, struct gpio_event_axis_info, info); if (func == GPIO_EVENT_FUNC_SUSPEND) { for (i = 0; i < ai->count; i++) disable_irq(gpio_to_irq(ai->gpio[i])); return 0; } if (func == GPIO_EVENT_FUNC_RESUME) { for (i = 0; i < ai->count; i++) enable_irq(gpio_to_irq(ai->gpio[i])); return 0; } if (func == GPIO_EVENT_FUNC_INIT) { *data = as = kmalloc(sizeof(*as), GFP_KERNEL); if (as == NULL) { ret = -ENOMEM; goto err_alloc_axis_state_failed; } as->input_devs = input_devs; as->info = ai; if (ai->dev >= input_devs->count) { pr_err("gpio_event_axis: bad device index %d >= %d " "for %d:%d\n", ai->dev, input_devs->count, ai->type, ai->code); ret = -EINVAL; goto err_bad_device_index; } input_set_capability(input_devs->dev[ai->dev], ai->type, ai->code); if (ai->type == EV_ABS) { input_set_abs_params(input_devs->dev[ai->dev], ai->code, 0, ai->decoded_size - 1, 0, 0); } for (i = 0; i < ai->count; i++) { ret = gpio_request(ai->gpio[i], "gpio_event_axis"); if (ret < 0) goto err_request_gpio_failed; ret = gpio_direction_input(ai->gpio[i]); if (ret < 0) goto err_gpio_direction_input_failed; ret = irq = gpio_to_irq(ai->gpio[i]); if (ret < 0) goto err_get_irq_num_failed; ret = request_irq(irq, gpio_axis_irq_handler, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "gpio_event_axis", as); if (ret < 0) goto err_request_irq_failed; } gpio_event_update_axis(as, 0); return 0; } ret = 0; as = *data; for (i = ai->count - 1; i >= 0; i--) { free_irq(gpio_to_irq(ai->gpio[i]), as); err_request_irq_failed: err_get_irq_num_failed: err_gpio_direction_input_failed: gpio_free(ai->gpio[i]); err_request_gpio_failed: ; } err_bad_device_index: kfree(as); *data = NULL; err_alloc_axis_state_failed: return ret; }
gpl-2.0
Luquidtester/DirtyKernel-3x-ION
drivers/staging/tidspbridge/rmgr/pwr.c
11007
4672
/* * pwr.c * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * PWR API for controlling DSP power states. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* ----------------------------------- Host OS */ #include <dspbridge/host_os.h> /* ----------------------------------- This */ #include <dspbridge/pwr.h> /* ----------------------------------- Resource Manager */ #include <dspbridge/devdefs.h> #include <dspbridge/drv.h> /* ----------------------------------- Platform Manager */ #include <dspbridge/dev.h> /* ----------------------------------- Link Driver */ #include <dspbridge/dspioctl.h> /* * ======== pwr_sleep_dsp ======== * Send command to DSP to enter sleep state. */ int pwr_sleep_dsp(const u32 sleep_code, const u32 timeout) { struct bridge_drv_interface *intf_fxns; struct bridge_dev_context *dw_context; int status = -EPERM; struct dev_object *hdev_obj = NULL; u32 ioctlcode = 0; u32 arg = timeout; for (hdev_obj = (struct dev_object *)drv_get_first_dev_object(); hdev_obj != NULL; hdev_obj = (struct dev_object *)drv_get_next_dev_object((u32) hdev_obj)) { if (dev_get_bridge_context(hdev_obj, (struct bridge_dev_context **) &dw_context)) { continue; } if (dev_get_intf_fxns(hdev_obj, (struct bridge_drv_interface **) &intf_fxns)) { continue; } if (sleep_code == PWR_DEEPSLEEP) ioctlcode = BRDIOCTL_DEEPSLEEP; else if (sleep_code == PWR_EMERGENCYDEEPSLEEP) ioctlcode = BRDIOCTL_EMERGENCYSLEEP; else status = -EINVAL; if (status != -EINVAL) { status = (*intf_fxns->dev_cntrl) (dw_context, ioctlcode, (void *)&arg); } } return status; } /* * ======== pwr_wake_dsp ======== * Send command to DSP to wake it from sleep. */ int pwr_wake_dsp(const u32 timeout) { struct bridge_drv_interface *intf_fxns; struct bridge_dev_context *dw_context; int status = -EPERM; struct dev_object *hdev_obj = NULL; u32 arg = timeout; for (hdev_obj = (struct dev_object *)drv_get_first_dev_object(); hdev_obj != NULL; hdev_obj = (struct dev_object *)drv_get_next_dev_object ((u32) hdev_obj)) { if (!(dev_get_bridge_context(hdev_obj, (struct bridge_dev_context **)&dw_context))) { if (!(dev_get_intf_fxns(hdev_obj, (struct bridge_drv_interface **)&intf_fxns))) { status = (*intf_fxns->dev_cntrl) (dw_context, BRDIOCTL_WAKEUP, (void *)&arg); } } } return status; } /* * ======== pwr_pm_pre_scale======== * Sends pre-notification message to DSP. */ int pwr_pm_pre_scale(u16 voltage_domain, u32 level) { struct bridge_drv_interface *intf_fxns; struct bridge_dev_context *dw_context; int status = -EPERM; struct dev_object *hdev_obj = NULL; u32 arg[2]; arg[0] = voltage_domain; arg[1] = level; for (hdev_obj = (struct dev_object *)drv_get_first_dev_object(); hdev_obj != NULL; hdev_obj = (struct dev_object *)drv_get_next_dev_object ((u32) hdev_obj)) { if (!(dev_get_bridge_context(hdev_obj, (struct bridge_dev_context **)&dw_context))) { if (!(dev_get_intf_fxns(hdev_obj, (struct bridge_drv_interface **)&intf_fxns))) { status = (*intf_fxns->dev_cntrl) (dw_context, BRDIOCTL_PRESCALE_NOTIFY, (void *)&arg); } } } return status; } /* * ======== pwr_pm_post_scale======== * Sends post-notification message to DSP. */ int pwr_pm_post_scale(u16 voltage_domain, u32 level) { struct bridge_drv_interface *intf_fxns; struct bridge_dev_context *dw_context; int status = -EPERM; struct dev_object *hdev_obj = NULL; u32 arg[2]; arg[0] = voltage_domain; arg[1] = level; for (hdev_obj = (struct dev_object *)drv_get_first_dev_object(); hdev_obj != NULL; hdev_obj = (struct dev_object *)drv_get_next_dev_object ((u32) hdev_obj)) { if (!(dev_get_bridge_context(hdev_obj, (struct bridge_dev_context **)&dw_context))) { if (!(dev_get_intf_fxns(hdev_obj, (struct bridge_drv_interface **)&intf_fxns))) { status = (*intf_fxns->dev_cntrl) (dw_context, BRDIOCTL_POSTSCALE_NOTIFY, (void *)&arg); } } } return status; }
gpl-2.0
crewrktablets/rk3x_kernel_3.10
sound/drivers/vx/vx_uer.c
12799
7857
/* * Driver for Digigram VX soundcards * * IEC958 stuff * * Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/delay.h> #include <sound/core.h> #include <sound/vx_core.h> #include "vx_cmd.h" /* * vx_modify_board_clock - tell the board that its clock has been modified * @sync: DSP needs to resynchronize its FIFO */ static int vx_modify_board_clock(struct vx_core *chip, int sync) { struct vx_rmh rmh; vx_init_rmh(&rmh, CMD_MODIFY_CLOCK); /* Ask the DSP to resynchronize its FIFO. */ if (sync) rmh.Cmd[0] |= CMD_MODIFY_CLOCK_S_BIT; return vx_send_msg(chip, &rmh); } /* * vx_modify_board_inputs - resync audio inputs */ static int vx_modify_board_inputs(struct vx_core *chip) { struct vx_rmh rmh; vx_init_rmh(&rmh, CMD_RESYNC_AUDIO_INPUTS); rmh.Cmd[0] |= 1 << 0; /* reference: AUDIO 0 */ return vx_send_msg(chip, &rmh); } /* * vx_read_one_cbit - read one bit from UER config * @index: the bit index * returns 0 or 1. */ static int vx_read_one_cbit(struct vx_core *chip, int index) { unsigned long flags; int val; spin_lock_irqsave(&chip->lock, flags); if (chip->type >= VX_TYPE_VXPOCKET) { vx_outb(chip, CSUER, 1); /* read */ vx_outb(chip, RUER, index & XX_UER_CBITS_OFFSET_MASK); val = (vx_inb(chip, RUER) >> 7) & 0x01; } else { vx_outl(chip, CSUER, 1); /* read */ vx_outl(chip, RUER, index & XX_UER_CBITS_OFFSET_MASK); val = (vx_inl(chip, RUER) >> 7) & 0x01; } spin_unlock_irqrestore(&chip->lock, flags); return val; } /* * vx_write_one_cbit - write one bit to UER config * @index: the bit index * @val: bit value, 0 or 1 */ static void vx_write_one_cbit(struct vx_core *chip, int index, int val) { unsigned long flags; val = !!val; /* 0 or 1 */ spin_lock_irqsave(&chip->lock, flags); if (vx_is_pcmcia(chip)) { vx_outb(chip, CSUER, 0); /* write */ vx_outb(chip, RUER, (val << 7) | (index & XX_UER_CBITS_OFFSET_MASK)); } else { vx_outl(chip, CSUER, 0); /* write */ vx_outl(chip, RUER, (val << 7) | (index & XX_UER_CBITS_OFFSET_MASK)); } spin_unlock_irqrestore(&chip->lock, flags); } /* * vx_read_uer_status - read the current UER status * @mode: pointer to store the UER mode, VX_UER_MODE_XXX * * returns the frequency of UER, or 0 if not sync, * or a negative error code. */ static int vx_read_uer_status(struct vx_core *chip, unsigned int *mode) { int val, freq; /* Default values */ freq = 0; /* Read UER status */ if (vx_is_pcmcia(chip)) val = vx_inb(chip, CSUER); else val = vx_inl(chip, CSUER); if (val < 0) return val; /* If clock is present, read frequency */ if (val & VX_SUER_CLOCK_PRESENT_MASK) { switch (val & VX_SUER_FREQ_MASK) { case VX_SUER_FREQ_32KHz_MASK: freq = 32000; break; case VX_SUER_FREQ_44KHz_MASK: freq = 44100; break; case VX_SUER_FREQ_48KHz_MASK: freq = 48000; break; } } if (val & VX_SUER_DATA_PRESENT_MASK) /* bit 0 corresponds to consumer/professional bit */ *mode = vx_read_one_cbit(chip, 0) ? VX_UER_MODE_PROFESSIONAL : VX_UER_MODE_CONSUMER; else *mode = VX_UER_MODE_NOT_PRESENT; return freq; } /* * compute the sample clock value from frequency * * The formula is as follows: * * HexFreq = (dword) ((double) ((double) 28224000 / (double) Frequency)) * switch ( HexFreq & 0x00000F00 ) * case 0x00000100: ; * case 0x00000200: * case 0x00000300: HexFreq -= 0x00000201 ; * case 0x00000400: * case 0x00000500: * case 0x00000600: * case 0x00000700: HexFreq = (dword) (((double) 28224000 / (double) (Frequency*2)) - 1) * default : HexFreq = (dword) ((double) 28224000 / (double) (Frequency*4)) - 0x000001FF */ static int vx_calc_clock_from_freq(struct vx_core *chip, int freq) { int hexfreq; if (snd_BUG_ON(freq <= 0)) return 0; hexfreq = (28224000 * 10) / freq; hexfreq = (hexfreq + 5) / 10; /* max freq = 55125 Hz */ if (snd_BUG_ON(hexfreq <= 0x00000200)) return 0; if (hexfreq <= 0x03ff) return hexfreq - 0x00000201; if (hexfreq <= 0x07ff) return (hexfreq / 2) - 1; if (hexfreq <= 0x0fff) return (hexfreq / 4) + 0x000001ff; return 0x5fe; /* min freq = 6893 Hz */ } /* * vx_change_clock_source - change the clock source * @source: the new source */ static void vx_change_clock_source(struct vx_core *chip, int source) { unsigned long flags; /* we mute DAC to prevent clicks */ vx_toggle_dac_mute(chip, 1); spin_lock_irqsave(&chip->lock, flags); chip->ops->set_clock_source(chip, source); chip->clock_source = source; spin_unlock_irqrestore(&chip->lock, flags); /* unmute */ vx_toggle_dac_mute(chip, 0); } /* * set the internal clock */ void vx_set_internal_clock(struct vx_core *chip, unsigned int freq) { int clock; unsigned long flags; /* Get real clock value */ clock = vx_calc_clock_from_freq(chip, freq); snd_printdd(KERN_DEBUG "set internal clock to 0x%x from freq %d\n", clock, freq); spin_lock_irqsave(&chip->lock, flags); if (vx_is_pcmcia(chip)) { vx_outb(chip, HIFREQ, (clock >> 8) & 0x0f); vx_outb(chip, LOFREQ, clock & 0xff); } else { vx_outl(chip, HIFREQ, (clock >> 8) & 0x0f); vx_outl(chip, LOFREQ, clock & 0xff); } spin_unlock_irqrestore(&chip->lock, flags); } /* * set the iec958 status bits * @bits: 32-bit status bits */ void vx_set_iec958_status(struct vx_core *chip, unsigned int bits) { int i; if (chip->chip_status & VX_STAT_IS_STALE) return; for (i = 0; i < 32; i++) vx_write_one_cbit(chip, i, bits & (1 << i)); } /* * vx_set_clock - change the clock and audio source if necessary */ int vx_set_clock(struct vx_core *chip, unsigned int freq) { int src_changed = 0; if (chip->chip_status & VX_STAT_IS_STALE) return 0; /* change the audio source if possible */ vx_sync_audio_source(chip); if (chip->clock_mode == VX_CLOCK_MODE_EXTERNAL || (chip->clock_mode == VX_CLOCK_MODE_AUTO && chip->audio_source == VX_AUDIO_SRC_DIGITAL)) { if (chip->clock_source != UER_SYNC) { vx_change_clock_source(chip, UER_SYNC); mdelay(6); src_changed = 1; } } else if (chip->clock_mode == VX_CLOCK_MODE_INTERNAL || (chip->clock_mode == VX_CLOCK_MODE_AUTO && chip->audio_source != VX_AUDIO_SRC_DIGITAL)) { if (chip->clock_source != INTERNAL_QUARTZ) { vx_change_clock_source(chip, INTERNAL_QUARTZ); src_changed = 1; } if (chip->freq == freq) return 0; vx_set_internal_clock(chip, freq); if (src_changed) vx_modify_board_inputs(chip); } if (chip->freq == freq) return 0; chip->freq = freq; vx_modify_board_clock(chip, 1); return 0; } /* * vx_change_frequency - called from interrupt handler */ int vx_change_frequency(struct vx_core *chip) { int freq; if (chip->chip_status & VX_STAT_IS_STALE) return 0; if (chip->clock_source == INTERNAL_QUARTZ) return 0; /* * Read the real UER board frequency */ freq = vx_read_uer_status(chip, &chip->uer_detected); if (freq < 0) return freq; /* * The frequency computed by the DSP is good and * is different from the previous computed. */ if (freq == 48000 || freq == 44100 || freq == 32000) chip->freq_detected = freq; return 0; }
gpl-2.0
fmes/complex-sim
avl-2.0/src/tavl.c
1
28272
/* Produced by texiweb from libavl.w on 2002/01/06 at 19:10. */ /* libavl - library for manipulation of binary trees. Copyright (C) 1998-2002 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. The author may be contacted at <blp@gnu.org> on the Internet, or as Ben Pfaff, 12167 Airport Rd, DeWitt MI 48820, USA through more mundane means. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "tavl.h" /* Creates and returns a new table with comparison function |compare| using parameter |param| and memory allocator |allocator|. Returns |NULL| if memory allocation failed. */ struct tavl_table * tavl_create (tavl_comparison_func *compare, void *param, struct libavl_allocator *allocator) { struct tavl_table *tree; assert (compare != NULL); if (allocator == NULL) allocator = &tavl_allocator_default; tree = allocator->libavl_malloc (allocator, sizeof *tree); if (tree == NULL) return NULL; tree->tavl_root = NULL; tree->tavl_compare = compare; tree->tavl_param = param; tree->tavl_alloc = allocator; tree->tavl_count = 0; return tree; } /* Search |tree| for an item matching |item|, and return it if found. Otherwise return |NULL|. */ void * tavl_find (const struct tavl_table *tree, const void *item) { const struct tavl_node *p; assert (tree != NULL && item != NULL); p = tree->tavl_root; if (p == NULL) return NULL; for (;;) { int cmp, dir; cmp = tree->tavl_compare (item, p->tavl_data, tree->tavl_param); if (cmp == 0) return p->tavl_data; dir = cmp > 0; if (p->tavl_tag[dir] == TAVL_CHILD) p = p->tavl_link[dir]; else return NULL; } } /* Inserts |item| into |tree| and returns a pointer to |item|'s address. If a duplicate item is found in the tree, returns a pointer to the duplicate without inserting |item|. Returns |NULL| in case of memory allocation failure. */ void ** tavl_probe (struct tavl_table *tree, void *item) { struct tavl_node *y, *z; /* Top node to update balance factor, and parent. */ struct tavl_node *p, *q; /* Iterator, and parent. */ struct tavl_node *n; /* Newly inserted node. */ struct tavl_node *w; /* New root of rebalanced subtree. */ int dir; /* Direction to descend. */ unsigned char da[TAVL_MAX_HEIGHT]; /* Cached comparison results. */ int k = 0; /* Number of cached results. */ assert (tree != NULL && item != NULL); z = (struct tavl_node *) &tree->tavl_root; y = tree->tavl_root; if (y != NULL) { for (q = z, p = y; ; q = p, p = p->tavl_link[dir]) { int cmp = tree->tavl_compare (item, p->tavl_data, tree->tavl_param); if (cmp == 0) return &p->tavl_data; if (p->tavl_balance != 0) z = q, y = p, k = 0; da[k++] = dir = cmp > 0; if (p->tavl_tag[dir] == TAVL_THREAD) break; } } else { p = z; dir = 0; } n = tree->tavl_alloc->libavl_malloc (tree->tavl_alloc, sizeof *n); if (n == NULL) return NULL; tree->tavl_count++; n->tavl_data = item; n->tavl_tag[0] = n->tavl_tag[1] = TAVL_THREAD; n->tavl_link[dir] = p->tavl_link[dir]; if (tree->tavl_root != NULL) { p->tavl_tag[dir] = TAVL_CHILD; n->tavl_link[!dir] = p; } else n->tavl_link[1] = NULL; p->tavl_link[dir] = n; n->tavl_balance = 0; if (tree->tavl_root == n) return &n->tavl_data; for (p = y, k = 0; p != n; p = p->tavl_link[da[k]], k++) if (da[k] == 0) p->tavl_balance--; else p->tavl_balance++; if (y->tavl_balance == -2) { struct tavl_node *x = y->tavl_link[0]; if (x->tavl_balance == -1) { w = x; if (x->tavl_tag[1] == TAVL_THREAD) { x->tavl_tag[1] = TAVL_CHILD; y->tavl_tag[0] = TAVL_THREAD; y->tavl_link[0] = x; } else y->tavl_link[0] = x->tavl_link[1]; x->tavl_link[1] = y; x->tavl_balance = y->tavl_balance = 0; } else { assert (x->tavl_balance == +1); w = x->tavl_link[1]; x->tavl_link[1] = w->tavl_link[0]; w->tavl_link[0] = x; y->tavl_link[0] = w->tavl_link[1]; w->tavl_link[1] = y; if (w->tavl_balance == -1) x->tavl_balance = 0, y->tavl_balance = +1; else if (w->tavl_balance == 0) x->tavl_balance = y->tavl_balance = 0; else /* |w->tavl_balance == +1| */ x->tavl_balance = -1, y->tavl_balance = 0; w->tavl_balance = 0; if (w->tavl_tag[0] == TAVL_THREAD) { x->tavl_tag[1] = TAVL_THREAD; x->tavl_link[1] = w; w->tavl_tag[0] = TAVL_CHILD; } if (w->tavl_tag[1] == TAVL_THREAD) { y->tavl_tag[0] = TAVL_THREAD; y->tavl_link[0] = w; w->tavl_tag[1] = TAVL_CHILD; } } } else if (y->tavl_balance == +2) { struct tavl_node *x = y->tavl_link[1]; if (x->tavl_balance == +1) { w = x; if (x->tavl_tag[0] == TAVL_THREAD) { x->tavl_tag[0] = TAVL_CHILD; y->tavl_tag[1] = TAVL_THREAD; y->tavl_link[1] = x; } else y->tavl_link[1] = x->tavl_link[0]; x->tavl_link[0] = y; x->tavl_balance = y->tavl_balance = 0; } else { assert (x->tavl_balance == -1); w = x->tavl_link[0]; x->tavl_link[0] = w->tavl_link[1]; w->tavl_link[1] = x; y->tavl_link[1] = w->tavl_link[0]; w->tavl_link[0] = y; if (w->tavl_balance == +1) x->tavl_balance = 0, y->tavl_balance = -1; else if (w->tavl_balance == 0) x->tavl_balance = y->tavl_balance = 0; else /* |w->tavl_balance == -1| */ x->tavl_balance = +1, y->tavl_balance = 0; w->tavl_balance = 0; if (w->tavl_tag[0] == TAVL_THREAD) { y->tavl_tag[1] = TAVL_THREAD; y->tavl_link[1] = w; w->tavl_tag[0] = TAVL_CHILD; } if (w->tavl_tag[1] == TAVL_THREAD) { x->tavl_tag[0] = TAVL_THREAD; x->tavl_link[0] = w; w->tavl_tag[1] = TAVL_CHILD; } } } else return &n->tavl_data; z->tavl_link[y != z->tavl_link[0]] = w; return &n->tavl_data; } /* Inserts |item| into |table|. Returns |NULL| if |item| was successfully inserted or if a memory allocation error occurred. Otherwise, returns the duplicate item. */ void * tavl_insert (struct tavl_table *table, void *item) { void **p = tavl_probe (table, item); return p == NULL || *p == item ? NULL : *p; } /* Inserts |item| into |table|, replacing any duplicate item. Returns |NULL| if |item| was inserted without replacing a duplicate, or if a memory allocation error occurred. Otherwise, returns the item that was replaced. */ void * tavl_replace (struct tavl_table *table, void *item) { void **p = tavl_probe (table, item); if (p == NULL || *p == item) return NULL; else { void *r = *p; *p = item; return r; } } /* Returns the parent of |node| within |tree|, or a pointer to |tavl_root| if |s| is the root of the tree. */ static struct tavl_node * find_parent (struct tavl_table *tree, struct tavl_node *node) { if (node != tree->tavl_root) { struct tavl_node *x, *y; for (x = y = node; ; x = x->tavl_link[0], y = y->tavl_link[1]) if (y->tavl_tag[1] == TAVL_THREAD) { struct tavl_node *p = y->tavl_link[1]; if (p == NULL || p->tavl_link[0] != node) { while (x->tavl_tag[0] == TAVL_CHILD) x = x->tavl_link[0]; p = x->tavl_link[0]; } return p; } else if (x->tavl_tag[0] == TAVL_THREAD) { struct tavl_node *p = x->tavl_link[0]; if (p == NULL || p->tavl_link[1] != node) { while (y->tavl_tag[1] == TAVL_CHILD) y = y->tavl_link[1]; p = y->tavl_link[1]; } return p; } } else return (struct tavl_node *) &tree->tavl_root; } /* Deletes from |tree| and returns an item matching |item|. Returns a null pointer if no matching item found. */ void * tavl_delete (struct tavl_table *tree, const void *item) { struct tavl_node *p; /* Traverses tree to find node to delete. */ struct tavl_node *q; /* Parent of |p|. */ int dir; /* Index into |q->tavl_link[]| to get |p|. */ int cmp; /* Result of comparison between |item| and |p|. */ assert (tree != NULL && item != NULL); if (tree->tavl_root == NULL) return NULL; p = (struct tavl_node *) &tree->tavl_root; for (cmp = -1; cmp != 0; cmp = tree->tavl_compare (item, p->tavl_data, tree->tavl_param)) { dir = cmp > 0; q = p; if (p->tavl_tag[dir] == TAVL_THREAD) return NULL; p = p->tavl_link[dir]; } item = p->tavl_data; if (p->tavl_tag[1] == TAVL_THREAD) { if (p->tavl_tag[0] == TAVL_CHILD) { struct tavl_node *t = p->tavl_link[0]; while (t->tavl_tag[1] == TAVL_CHILD) t = t->tavl_link[1]; t->tavl_link[1] = p->tavl_link[1]; q->tavl_link[dir] = p->tavl_link[0]; } else { q->tavl_link[dir] = p->tavl_link[dir]; if (q != (struct tavl_node *) &tree->tavl_root) q->tavl_tag[dir] = TAVL_THREAD; } } else { struct tavl_node *r = p->tavl_link[1]; if (r->tavl_tag[0] == TAVL_THREAD) { r->tavl_link[0] = p->tavl_link[0]; r->tavl_tag[0] = p->tavl_tag[0]; if (r->tavl_tag[0] == TAVL_CHILD) { struct tavl_node *t = r->tavl_link[0]; while (t->tavl_tag[1] == TAVL_CHILD) t = t->tavl_link[1]; t->tavl_link[1] = r; } q->tavl_link[dir] = r; r->tavl_balance = p->tavl_balance; q = r; dir = 1; } else { struct tavl_node *s; for (;;) { s = r->tavl_link[0]; if (s->tavl_tag[0] == TAVL_THREAD) break; r = s; } if (s->tavl_tag[1] == TAVL_CHILD) r->tavl_link[0] = s->tavl_link[1]; else { r->tavl_link[0] = s; r->tavl_tag[0] = TAVL_THREAD; } s->tavl_link[0] = p->tavl_link[0]; if (p->tavl_tag[0] == TAVL_CHILD) { struct tavl_node *t = p->tavl_link[0]; while (t->tavl_tag[1] == TAVL_CHILD) t = t->tavl_link[1]; t->tavl_link[1] = s; s->tavl_tag[0] = TAVL_CHILD; } s->tavl_link[1] = p->tavl_link[1]; s->tavl_tag[1] = TAVL_CHILD; q->tavl_link[dir] = s; s->tavl_balance = p->tavl_balance; q = r; dir = 0; } } tree->tavl_alloc->libavl_free (tree->tavl_alloc, p); while (q != (struct tavl_node *) &tree->tavl_root) { struct tavl_node *y = q; q = find_parent (tree, y); if (dir == 0) { dir = q->tavl_link[0] != y; y->tavl_balance++; if (y->tavl_balance == +1) break; else if (y->tavl_balance == +2) { struct tavl_node *x = y->tavl_link[1]; assert (x != NULL); if (x->tavl_balance == -1) { struct tavl_node *w; assert (x->tavl_balance == -1); w = x->tavl_link[0]; x->tavl_link[0] = w->tavl_link[1]; w->tavl_link[1] = x; y->tavl_link[1] = w->tavl_link[0]; w->tavl_link[0] = y; if (w->tavl_balance == +1) x->tavl_balance = 0, y->tavl_balance = -1; else if (w->tavl_balance == 0) x->tavl_balance = y->tavl_balance = 0; else /* |w->tavl_balance == -1| */ x->tavl_balance = +1, y->tavl_balance = 0; w->tavl_balance = 0; if (w->tavl_tag[0] == TAVL_THREAD) { y->tavl_tag[1] = TAVL_THREAD; y->tavl_link[1] = w; w->tavl_tag[0] = TAVL_CHILD; } if (w->tavl_tag[1] == TAVL_THREAD) { x->tavl_tag[0] = TAVL_THREAD; x->tavl_link[0] = w; w->tavl_tag[1] = TAVL_CHILD; } q->tavl_link[dir] = w; } else { q->tavl_link[dir] = x; if (x->tavl_balance == 0) { y->tavl_link[1] = x->tavl_link[0]; x->tavl_link[0] = y; x->tavl_balance = -1; y->tavl_balance = +1; break; } else /* |x->tavl_balance == +1| */ { if (x->tavl_tag[0] == TAVL_CHILD) y->tavl_link[1] = x->tavl_link[0]; else { y->tavl_tag[1] = TAVL_THREAD; x->tavl_tag[0] = TAVL_CHILD; } x->tavl_link[0] = y; y->tavl_balance = x->tavl_balance = 0; } } } } else { dir = q->tavl_link[0] != y; y->tavl_balance--; if (y->tavl_balance == -1) break; else if (y->tavl_balance == -2) { struct tavl_node *x = y->tavl_link[0]; assert (x != NULL); if (x->tavl_balance == +1) { struct tavl_node *w; assert (x->tavl_balance == +1); w = x->tavl_link[1]; x->tavl_link[1] = w->tavl_link[0]; w->tavl_link[0] = x; y->tavl_link[0] = w->tavl_link[1]; w->tavl_link[1] = y; if (w->tavl_balance == -1) x->tavl_balance = 0, y->tavl_balance = +1; else if (w->tavl_balance == 0) x->tavl_balance = y->tavl_balance = 0; else /* |w->tavl_balance == +1| */ x->tavl_balance = -1, y->tavl_balance = 0; w->tavl_balance = 0; if (w->tavl_tag[0] == TAVL_THREAD) { x->tavl_tag[1] = TAVL_THREAD; x->tavl_link[1] = w; w->tavl_tag[0] = TAVL_CHILD; } if (w->tavl_tag[1] == TAVL_THREAD) { y->tavl_tag[0] = TAVL_THREAD; y->tavl_link[0] = w; w->tavl_tag[1] = TAVL_CHILD; } q->tavl_link[dir] = w; } else { q->tavl_link[dir] = x; if (x->tavl_balance == 0) { y->tavl_link[0] = x->tavl_link[1]; x->tavl_link[1] = y; x->tavl_balance = +1; y->tavl_balance = -1; break; } else /* |x->tavl_balance == -1| */ { if (x->tavl_tag[1] == TAVL_CHILD) y->tavl_link[0] = x->tavl_link[1]; else { y->tavl_tag[0] = TAVL_THREAD; x->tavl_tag[1] = TAVL_CHILD; } x->tavl_link[1] = y; y->tavl_balance = x->tavl_balance = 0; } } } } } tree->tavl_count--; return (void *) item; } /* Initializes |trav| for use with |tree| and selects the null node. */ void tavl_t_init (struct tavl_traverser *trav, struct tavl_table *tree) { trav->tavl_table = tree; trav->tavl_node = NULL; } /* Initializes |trav| for |tree|. Returns data item in |tree| with the least value, or |NULL| if |tree| is empty. */ void * tavl_t_first (struct tavl_traverser *trav, struct tavl_table *tree) { assert (tree != NULL && trav != NULL); trav->tavl_table = tree; trav->tavl_node = tree->tavl_root; if (trav->tavl_node != NULL) { while (trav->tavl_node->tavl_tag[0] == TAVL_CHILD) trav->tavl_node = trav->tavl_node->tavl_link[0]; return trav->tavl_node->tavl_data; } else return NULL; } /* Initializes |trav| for |tree|. Returns data item in |tree| with the greatest value, or |NULL| if |tree| is empty. */ void * tavl_t_last (struct tavl_traverser *trav, struct tavl_table *tree) { assert (tree != NULL && trav != NULL); trav->tavl_table = tree; trav->tavl_node = tree->tavl_root; if (trav->tavl_node != NULL) { while (trav->tavl_node->tavl_tag[1] == TAVL_CHILD) trav->tavl_node = trav->tavl_node->tavl_link[1]; return trav->tavl_node->tavl_data; } else return NULL; } /* Searches for |item| in |tree|. If found, initializes |trav| to the item found and returns the item as well. If there is no matching item, initializes |trav| to the null item and returns |NULL|. */ void * tavl_t_find (struct tavl_traverser *trav, struct tavl_table *tree, void *item) { struct tavl_node *p; assert (trav != NULL && tree != NULL && item != NULL); trav->tavl_table = tree; trav->tavl_node = NULL; p = tree->tavl_root; if (p == NULL) return NULL; for (;;) { int cmp, dir; cmp = tree->tavl_compare (item, p->tavl_data, tree->tavl_param); if (cmp == 0) { trav->tavl_node = p; return p->tavl_data; } dir = cmp > 0; if (p->tavl_tag[dir] == TAVL_CHILD) p = p->tavl_link[dir]; else return NULL; } } /* Attempts to insert |item| into |tree|. If |item| is inserted successfully, it is returned and |trav| is initialized to its location. If a duplicate is found, it is returned and |trav| is initialized to its location. No replacement of the item occurs. If a memory allocation failure occurs, |NULL| is returned and |trav| is initialized to the null item. */ void * tavl_t_insert (struct tavl_traverser *trav, struct tavl_table *tree, void *item) { void **p; assert (trav != NULL && tree != NULL && item != NULL); p = tavl_probe (tree, item); if (p != NULL) { trav->tavl_table = tree; trav->tavl_node = ((struct tavl_node *) ((char *) p - offsetof (struct tavl_node, tavl_data))); return *p; } else { tavl_t_init (trav, tree); return NULL; } } /* Initializes |trav| to have the same current node as |src|. */ void * tavl_t_copy (struct tavl_traverser *trav, const struct tavl_traverser *src) { assert (trav != NULL && src != NULL); trav->tavl_table = src->tavl_table; trav->tavl_node = src->tavl_node; return trav->tavl_node != NULL ? trav->tavl_node->tavl_data : NULL; } /* Returns the next data item in inorder within the tree being traversed with |trav|, or if there are no more data items returns |NULL|. */ void * tavl_t_next (struct tavl_traverser *trav) { assert (trav != NULL); if (trav->tavl_node == NULL) return tavl_t_first (trav, trav->tavl_table); else if (trav->tavl_node->tavl_tag[1] == TAVL_THREAD) { trav->tavl_node = trav->tavl_node->tavl_link[1]; return trav->tavl_node != NULL ? trav->tavl_node->tavl_data : NULL; } else { trav->tavl_node = trav->tavl_node->tavl_link[1]; while (trav->tavl_node->tavl_tag[0] == TAVL_CHILD) trav->tavl_node = trav->tavl_node->tavl_link[0]; return trav->tavl_node->tavl_data; } } /* Returns the previous data item in inorder within the tree being traversed with |trav|, or if there are no more data items returns |NULL|. */ void * tavl_t_prev (struct tavl_traverser *trav) { assert (trav != NULL); if (trav->tavl_node == NULL) return tavl_t_last (trav, trav->tavl_table); else if (trav->tavl_node->tavl_tag[0] == TAVL_THREAD) { trav->tavl_node = trav->tavl_node->tavl_link[0]; return trav->tavl_node != NULL ? trav->tavl_node->tavl_data : NULL; } else { trav->tavl_node = trav->tavl_node->tavl_link[0]; while (trav->tavl_node->tavl_tag[1] == TAVL_CHILD) trav->tavl_node = trav->tavl_node->tavl_link[1]; return trav->tavl_node->tavl_data; } } /* Returns |trav|'s current item. */ void * tavl_t_cur (struct tavl_traverser *trav) { assert (trav != NULL); return trav->tavl_node != NULL ? trav->tavl_node->tavl_data : NULL; } /* Replaces the current item in |trav| by |new| and returns the item replaced. |trav| must not have the null item selected. The new item must not upset the ordering of the tree. */ void * tavl_t_replace (struct tavl_traverser *trav, void *new) { struct tavl_node *old; assert (trav != NULL && trav->tavl_node != NULL && new != NULL); old = trav->tavl_node->tavl_data; trav->tavl_node->tavl_data = new; return old; } /* Creates a new node as a child of |dst| on side |dir|. Copies data and |tavl_balance| from |src| into the new node, applying |copy()|, if non-null. Returns nonzero only if fully successful. Regardless of success, integrity of the tree structure is assured, though failure may leave a null pointer in a |tavl_data| member. */ static int copy_node (struct tavl_table *tree, struct tavl_node *dst, int dir, const struct tavl_node *src, tavl_copy_func *copy) { struct tavl_node *new = tree->tavl_alloc->libavl_malloc (tree->tavl_alloc, sizeof *new); if (new == NULL) return 0; new->tavl_link[dir] = dst->tavl_link[dir]; new->tavl_tag[dir] = TAVL_THREAD; new->tavl_link[!dir] = dst; new->tavl_tag[!dir] = TAVL_THREAD; dst->tavl_link[dir] = new; dst->tavl_tag[dir] = TAVL_CHILD; new->tavl_balance = src->tavl_balance; if (copy == NULL) new->tavl_data = src->tavl_data; else { new->tavl_data = copy (src->tavl_data, tree->tavl_param); if (new->tavl_data == NULL) return 0; } return 1; } static void copy_error_recovery (struct tavl_node *p, struct tavl_table *new, tavl_item_func *destroy) { new->tavl_root = p; if (p != NULL) { while (p->tavl_tag[1] == TAVL_CHILD) p = p->tavl_link[1]; p->tavl_link[1] = NULL; } tavl_destroy (new, destroy); } /* Copies |org| to a newly created tree, which is returned. If |copy != NULL|, each data item in |org| is first passed to |copy|, and the return values are inserted into the tree, with |NULL| return values taken as indications of failure. On failure, destroys the partially created new tree, applying |destroy|, if non-null, to each item in the new tree so far, and returns |NULL|. If |allocator != NULL|, it is used for allocation in the new tree. Otherwise, the same allocator used for |org| is used. */ struct tavl_table * tavl_copy (const struct tavl_table *org, tavl_copy_func *copy, tavl_item_func *destroy, struct libavl_allocator *allocator) { struct tavl_table *new; const struct tavl_node *p; struct tavl_node *q; struct tavl_node rp, rq; assert (org != NULL); new = tavl_create (org->tavl_compare, org->tavl_param, allocator != NULL ? allocator : org->tavl_alloc); if (new == NULL) return NULL; new->tavl_count = org->tavl_count; if (new->tavl_count == 0) return new; p = &rp; rp.tavl_link[0] = org->tavl_root; rp.tavl_tag[0] = TAVL_CHILD; q = &rq; rq.tavl_link[0] = NULL; rq.tavl_tag[0] = TAVL_THREAD; for (;;) { if (p->tavl_tag[0] == TAVL_CHILD) { if (!copy_node (new, q, 0, p->tavl_link[0], copy)) { copy_error_recovery (rq.tavl_link[0], new, destroy); return NULL; } p = p->tavl_link[0]; q = q->tavl_link[0]; } else { while (p->tavl_tag[1] == TAVL_THREAD) { p = p->tavl_link[1]; if (p == NULL) { q->tavl_link[1] = NULL; new->tavl_root = rq.tavl_link[0]; return new; } q = q->tavl_link[1]; } p = p->tavl_link[1]; q = q->tavl_link[1]; } if (p->tavl_tag[1] == TAVL_CHILD) if (!copy_node (new, q, 1, p->tavl_link[1], copy)) { copy_error_recovery (rq.tavl_link[0], new, destroy); return NULL; } } } /* Frees storage allocated for |tree|. If |destroy != NULL|, applies it to each data item in inorder. */ void tavl_destroy (struct tavl_table *tree, tavl_item_func *destroy) { struct tavl_node *p; /* Current node. */ struct tavl_node *n; /* Next node. */ p = tree->tavl_root; if (p != NULL) while (p->tavl_tag[0] == TAVL_CHILD) p = p->tavl_link[0]; while (p != NULL) { n = p->tavl_link[1]; if (p->tavl_tag[1] == TAVL_CHILD) while (n->tavl_tag[0] == TAVL_CHILD) n = n->tavl_link[0]; if (destroy != NULL && p->tavl_data != NULL) destroy (p->tavl_data, tree->tavl_param); tree->tavl_alloc->libavl_free (tree->tavl_alloc, p); p = n; } tree->tavl_alloc->libavl_free (tree->tavl_alloc, tree); } /* Allocates |size| bytes of space using |malloc()|. Returns a null pointer if allocation fails. */ void * tavl_malloc (struct libavl_allocator *allocator, size_t size) { assert (allocator != NULL && size > 0); return malloc (size); } /* Frees |block|. */ void tavl_free (struct libavl_allocator *allocator, void *block) { assert (allocator != NULL && block != NULL); free (block); } /* Default memory allocator that uses |malloc()| and |free()|. */ struct libavl_allocator tavl_allocator_default = { tavl_malloc, tavl_free }; #undef NDEBUG #include <assert.h> /* Asserts that |tavl_insert()| succeeds at inserting |item| into |table|. */ void (tavl_assert_insert) (struct tavl_table *table, void *item) { void **p = tavl_probe (table, item); assert (p != NULL && *p == item); } /* Asserts that |tavl_delete()| really removes |item| from |table|, and returns the removed item. */ void * (tavl_assert_delete) (struct tavl_table *table, void *item) { void *p = tavl_delete (table, item); assert (p != NULL); return p; }
gpl-3.0
rktrlng/rt2d
projects/demo/scene18.cpp
1
6168
/** * This file is part of a demo that shows how to use RT2D, a 2D OpenGL framework. * * - Copyright 2017 Rik Teerling <rik@onandoffables.com> * - Initial commit * * https://en.wikipedia.org/wiki/Maze_generation_algorithm * recursive backtracker */ #include "scene18.h" Scene18::Scene18() : SuperScene() { srand((unsigned)time(nullptr)); t.start(); text[0]->message("Scene18: Maze generation [SPACE]=reset"); gridwidth = 32; gridheight = 32; cellwidth = 16; cellheight = 16; // create grid grid = new BasicEntity(); //grid->addGrid("assets/mazewalls.tga", 4, 4, gridwidth, gridheight, cellwidth, cellheight); grid->addGrid("assets/mazeroads.tga", 4, 4, gridwidth, gridheight, cellwidth, cellheight); // center on screen Point2 pos = Point2(SWIDTH/2-(gridwidth*cellwidth)/2, SHEIGHT/2-(gridheight*cellheight)/2); grid->position = pos; layers[0]->addChild(grid); this->reset(); } Scene18::~Scene18() { layers[0]->removeChild(grid); delete grid; } void Scene18::update(float deltaTime) { // ############################################################### // Make SuperScene do what it needs to do // - Escape key stops Scene // ############################################################### SuperScene::update(deltaTime); //text[0]->message(""); // clear title //text[1]->message(""); // clear fps message //text[2]->message(""); // clear [/] next scene text[3]->message(""); // clear <esc> to quit text[5]->message(""); text[6]->message(""); text[10]->message(""); // clear player click count message if (input()->getKeyDown(KeyCode::Space)) { reset(); } static bool backtracking = false; if (t.seconds() > 0.005f) { // loop over grid and draw each sprite std::vector<Sprite*> spritebatch = grid->spritebatch(); int counter = 0; int unvisitedcounter = 0; for (int y=0; y<gridheight ; y++) { for (int x=0; x<gridwidth; x++) { // draw the correct cell int fr = (int) cells[counter]->walls.to_ulong(); spritebatch[counter]->frame(fr); // check visited, keep counter if (cells[counter]->visited) { spritebatch[counter]->color = WHITE; } else { //grid->spritebatch()[counter]->color = GREEN; unvisitedcounter++; } // color current cell if (cells[counter] == current) { if (backtracking) { spritebatch[counter]->color = RED; } else { spritebatch[counter]->color = BLUE; } } counter++; } } spritebatch[0]->color = WHITE; // first cell // no more unvisited cells. We're done. if (unvisitedcounter == 0) { text[2]->message("done!"); this->export_grid(); } else { text[2]->message("generating..."); } // make 'current' find the next place to be current->visited = true; // STEP 1: while there is a neighbour... MCell* next = this->getRandomUnvisitedNeighbour(current); if (next != nullptr) { // there's still an unvisited neighbour. We're not stuck backtracking = false; next->visited = true; // STEP 2 stack.push_back(current); // drop a breadcrumb on the stack // STEP 3 this->removeWalls(current, next); // break through the wall // STEP 4 current = next; } else { // we're stuck! backtrack our steps... backtracking = true; if (stack.size() > 0) { current = stack.back(); // make previous our current cell stack.pop_back(); // remove from the stack (eat the breadcrumb) } } t.start(); } } void Scene18::export_grid() { static int first_time = 1; if (first_time == 1) { first_time = 0; std::cout << "export " << cells.size() << std::endl; int counter = 0; for (int y=0; y<gridheight; y++) { for (int x=0; x<gridwidth; x++) { int fr = (int) cells[counter]->walls.to_ulong(); if (fr < 10) { std::cout << " "; } std::cout << fr << ","; counter++; } std::cout << std::endl; } } } void Scene18::removeWalls(MCell* c, MCell* n) { int dx = c->col - n->col; if (dx == 1) { c->walls[3] = 0; // left n->walls[1] = 0; // right } else if (dx == -1) { c->walls[1] = 0; n->walls[3] = 0; } int dy = c->row - n->row; if (dy == 1) { c->walls[0] = 0; // top n->walls[2] = 0; // bottom } else if (dy == -1) { c->walls[2] = 0; n->walls[0] = 0; } } int getindex(int x, int y, int w, int h) { if ( x>=0 && x<w && y>=0 && y<h) { int i = (y * w) + x; return i; } return -1; } MCell* Scene18::getRandomUnvisitedNeighbour(MCell* mc) { // keep a list of possible neighbours std::vector<MCell*> neighbours; int x = mc->col; int y = mc->row; int index = 0; // look right index = getindex(x+1,y,gridwidth,gridheight); if( index != -1 ) { if (!cells[index]->visited) { neighbours.push_back(cells[index]); } } // look left index = getindex(x-1,y,gridwidth,gridheight); if( index != -1 ) { if (!cells[index]->visited) { neighbours.push_back(cells[index]); } } // look down index = getindex(x,y+1,gridwidth,gridheight); if( index != -1 ) { if (!cells[index]->visited) { neighbours.push_back(cells[index]); } } // look up index = getindex(x,y-1,gridwidth,gridheight); if( index != -1 ) { if (!cells[index]->visited) { neighbours.push_back(cells[index]); } } // there's a valid neighbour! if (neighbours.size() > 0) { // pick one from the list int r = rand()%neighbours.size(); return neighbours[r]; } // no neighbours return nullptr; } void Scene18::clear() { int s = cells.size(); if (s>0) { for (int i = 0; i < s; i++) { delete cells[i]; // we did 'new' when we pushed the cell cells[i] = nullptr; } cells.clear(); } stack.clear(); // just a list of pointers to some cells. Don't delete here. } void Scene18::reset() { this->clear(); // create all cells and init grid int counter = 0; for (int y=0; y<gridheight ; y++) { for (int x=0; x<gridwidth; x++) { MCell* mc = new MCell(); mc->col = x; mc->row = y; mc->walls = 15; // 0b1111 all walls mc->visited = false; cells.push_back(mc); int fr = (int) cells[counter]->walls.to_ulong(); grid->spritebatch()[counter]->frame(fr); grid->spritebatch()[counter]->color = GRAY; counter++; } } current = cells[0]; }
gpl-3.0
KangDroid/Marlin
Marlin/src/gcode/control/M997.cpp
1
1051
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../gcode.h" #if ENABLED(PLATFORM_M997_SUPPORT) /** * M997: Perform in-application firmware update */ void GcodeSuite::M997() { flashFirmware(parser.intval('S')); } #endif
gpl-3.0
n7mobile/asn1scc.IDE
src/libraries/tests/modulemetadataparser_tests.cpp
1
7499
/**************************************************************************** ** ** Copyright (C) 2017-2019 N7 Space sp. z o. o. ** Contact: http://n7space.com ** ** This file is part of ASN.1/ACN Plugin for QtCreator. ** ** Plugin was developed under a programme and funded by ** European Space Agency. ** ** This Plugin is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This Plugin is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #include "modulemetadataparser_tests.h" #include <QtTest> using namespace Asn1Acn::Internal::Libraries::Tests; ModuleMetadataParserTests::ModuleMetadataParserTests(QObject *parent) : QObject(parent) , m_parsedData(std::make_unique<Metadata::Module>("BadName", "BadDesc")) {} void ModuleMetadataParserTests::test_emptyFile() { parsingFails(""); } void ModuleMetadataParserTests::test_malformedJson() { parsingFails(R"( { "name": "xxxx", )"); } void ModuleMetadataParserTests::test_wrongJsonType() { parsingFails("[]"); } void ModuleMetadataParserTests::test_emptyObject() { parsingFails("{}"); } void ModuleMetadataParserTests::test_emptyModule() { parse(R"({"name": "SomeName", "description": "SomeDesc"})"); QCOMPARE(m_parsedData->name(), QLatin1Literal("SomeName")); QCOMPARE(m_parsedData->description(), QLatin1Literal("SomeDesc")); QCOMPARE(static_cast<int>(m_parsedData->submodules().size()), 0); } void ModuleMetadataParserTests::test_emptySubmodule() { parse(R"({ "name": "SomeName", "submodules": [ { "name": "SubmoduleName", "description": "SubmoduleDesc" } ] })"); QCOMPARE(static_cast<int>(m_parsedData->submodules().size()), 1); const auto submodule = m_parsedData->submodules().at(0).get(); QCOMPARE(submodule->name(), QLatin1Literal("SubmoduleName")); QCOMPARE(submodule->description(), QLatin1Literal("SubmoduleDesc")); QCOMPARE(static_cast<int>(submodule->elements().size()), 0); } void ModuleMetadataParserTests::test_emptyElement() { parse(R"({ "name": "SomeName", "submodules": [ { "name": "SubmoduleName", "elements": [ { "name": "ElementName", "description": "ElementDesc" } ] } ] })"); QCOMPARE(static_cast<int>(m_parsedData->submodules().size()), 1); const auto submodule = m_parsedData->submodules().at(0).get(); QCOMPARE(static_cast<int>(submodule->elements().size()), 1); const auto element = submodule->elements().at(0).get(); QCOMPARE(element->name(), QLatin1Literal("ElementName")); QCOMPARE(element->description(), QLatin1Literal("ElementDesc")); QCOMPARE(element->asn1Files().size(), 0); QCOMPARE(element->additionalFiles().size(), 0); QCOMPARE(element->conflicts().size(), 0); QCOMPARE(element->requirements().size(), 0); } void ModuleMetadataParserTests::test_completeElement() { parse(R"({ "name": "SomeName", "submodules": [ { "name": "SubmoduleName", "elements": [ { "name": "ElementName", "asn1Files": ["f1", "f2", "f3"], "additionalFiles": ["a1", "a2", "a3"], "conflicts": ["c1", "c2"], "requires": ["r1"] } ] } ] })"); QCOMPARE(static_cast<int>(m_parsedData->submodules().size()), 1); const auto submodule = m_parsedData->submodules().at(0).get(); QCOMPARE(static_cast<int>(submodule->elements().size()), 1); const auto element = submodule->elements().at(0).get(); QCOMPARE(element->asn1Files(), (QStringList{"f1", "f2", "f3"})); QCOMPARE(element->additionalFiles(), (QStringList{"a1", "a2", "a3"})); QCOMPARE(element->conflicts().size(), 2); QCOMPARE(element->conflicts().at(0).element(), QStringLiteral("c1")); QCOMPARE(element->conflicts().at(0).submodule(), QStringLiteral("SubmoduleName")); QCOMPARE(element->conflicts().at(0).module(), QStringLiteral("SomeName")); QCOMPARE(element->conflicts().at(1).element(), QStringLiteral("c2")); QCOMPARE(element->conflicts().at(1).submodule(), QStringLiteral("SubmoduleName")); QCOMPARE(element->conflicts().at(1).module(), QStringLiteral("SomeName")); QCOMPARE(element->requirements().size(), 1); QCOMPARE(element->requirements().at(0).element(), QStringLiteral("r1")); QCOMPARE(element->requirements().at(0).submodule(), QStringLiteral("SubmoduleName")); QCOMPARE(element->requirements().at(0).module(), QStringLiteral("SomeName")); } void ModuleMetadataParserTests::test_complexReferences() { parse(R"({ "name": "SomeName", "submodules": [ { "name": "SubmoduleName", "elements": [ { "name": "ElementName", "asn1Files": ["f1"], "conflicts": [{ "module": "OtherModule", "submodule": "OtherSubmodule", "element": "ConflictingElement" }], "requires": [{ "submodule": "LocalSubmodule", "element": "RequiredElement" }] } ] } ] })"); const auto submodule = m_parsedData->submodules().at(0).get(); const auto element = submodule->elements().at(0).get(); QCOMPARE(element->conflicts().size(), 1); QCOMPARE(element->conflicts().at(0).element(), QStringLiteral("ConflictingElement")); QCOMPARE(element->conflicts().at(0).submodule(), QStringLiteral("OtherSubmodule")); QCOMPARE(element->conflicts().at(0).module(), QStringLiteral("OtherModule")); QCOMPARE(element->requirements().size(), 1); QCOMPARE(element->requirements().at(0).element(), QStringLiteral("RequiredElement")); QCOMPARE(element->requirements().at(0).submodule(), QStringLiteral("LocalSubmodule")); QCOMPARE(element->requirements().at(0).module(), QStringLiteral("SomeName")); } void ModuleMetadataParserTests::parsingFails(const QString &jsonData) { ModuleMetadataParser parser(jsonData.toUtf8()); try { parser.parse(); QFAIL("Parsing should fail"); } catch (const ModuleMetadataParser::Error &err) { QVERIFY(QLatin1String(err.what()).size() > 0); } } void ModuleMetadataParserTests::parse(const QString &jsonData) { ModuleMetadataParser parser(jsonData.toUtf8()); m_parsedData = parser.parse(); }
gpl-3.0
pa23/mixan
sources/tmpfiles.cpp
1
5105
/* mixan Analysis of granular material mixes and emulsions. File: tmpfiles.cpp Copyright (C) 2012-2015 Artem Petrov <pa2311@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QPixmap> #include <QVector> #include <QDir> #include <QMessageBox> #include <QThread> #include <QtConcurrentMap> #include <QFutureWatcher> #include <QProgressDialog> #include "tmpfiles.h" #include "granules.h" #include <memory> using std::shared_ptr; void saveGraphics(const QPixmap &pixmap1, const QString &path) { QDir tempDir; if ( !tempDir.exists(path) ) { if ( !tempDir.mkpath(path) ) { QMessageBox::warning(0, "mixan", QObject::tr("Can not create temporary " "directory!")); } } if ( !pixmap1.save(path + QDir::separator() + "graphic_0.png") ) { QMessageBox::warning(0, "mixan", QObject::tr("Can not save pixmap to file!")); } } void saveHistograms(const QVector<QImage> &histograms, const QString &path) { QDir tempDir; if ( !tempDir.exists(path) ) { if ( !tempDir.mkpath(path) ) { QMessageBox::warning( 0, "mixan", QObject::tr("Can not create temporary " "directory!")); } } for ( ptrdiff_t n=0; n<histograms.size(); n++ ) { if ( !histograms[n].save(path + QDir::separator() + "histogram_" + QString::number(n) + ".png") ) { QMessageBox::warning( 0, "mixan", QObject::tr("Can not save image to file!")); } } } const QVector< shared_ptr<Granules> > *tmp_granules_tf = 0; const QString *tmp_path_tf = 0; void realSavingImages(ptrdiff_t &iter) { if ( !tmp_granules_tf->at(iter)->resImage().save( *tmp_path_tf + QDir::separator() + "granules_image_" + QString::number(iter) + ".png" ) ) { QMessageBox::warning( 0, "mixan", QObject::tr("Can not save pixmap to file!") ); } } void saveImages(const QVector< shared_ptr<Granules> > &granules, const QString &path) { QDir tempDir; if ( !tempDir.exists(path) ) { if ( !tempDir.mkpath(path) ) { QMessageBox::warning( 0, "mixan", QObject::tr("Can not create temporary directory!") ); } return; } // tmp_granules_tf = &granules; tmp_path_tf = &path; // shared_ptr<QProgressDialog> progressDialog = shared_ptr<QProgressDialog>(new QProgressDialog()); progressDialog->setWindowTitle("mixan: progress"); shared_ptr< QFutureWatcher<void> > futureWatcher = shared_ptr< QFutureWatcher<void> >(new QFutureWatcher<void>); QObject::connect(futureWatcher.get(), SIGNAL(finished()), progressDialog.get(), SLOT(reset()) ); QObject::connect(progressDialog.get(), SIGNAL(canceled()), futureWatcher.get(), SLOT(cancel()) ); QObject::connect(futureWatcher.get(), SIGNAL(progressRangeChanged(int,int)), progressDialog.get(), SLOT(setRange(int,int)) ); QObject::connect(futureWatcher.get(), SIGNAL(progressValueChanged(int)), progressDialog.get(), SLOT(setValue(int)) ); QVector<ptrdiff_t> iterations; for ( ptrdiff_t n=0; n<tmp_granules_tf->size(); n++ ) { iterations.push_back(n); } progressDialog->setLabelText(QObject::tr("Saving temporary image files. " "Please wait...")); futureWatcher->setFuture(QtConcurrent::map(iterations, &realSavingImages)); progressDialog->exec(); futureWatcher->waitForFinished(); }
gpl-3.0
jrcatbagan/z80asm
parse.c
1
25475
// File: parse.c // Created: 17, May 2014 /* Copyright (C) 2014 Jarielle Catbagan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "defines.h" #include "parse.h" void parse_instruction(FILE *file_handle, char *buffer, line_status_t *line_status, instruction_parameters_t **instruction_set, uint16_t *location_counter, symboltable_t **symboltable_list, uint8_t symboltable_currentsize, char ***symbolstracked_list, uint8_t *symbolstracked_currentsize, uint8_t *symbolstracked_actualsize) { char *instruction, operand1[20], operand2[20]; uint8_t operand1_type = NONE, operand2_type = NONE, n_operands; int c, mainindex, subindex; status_t status; data_status_t data_status; instruction = buffer; n_operands = 0; if(*line_status == ENDOFFILE_DETECTED || *line_status == COMMNTDELIM_DETECTED || *line_status == NEWLINE_DETECTED || *line_status == CARRIAGERETURN_DETECTED) { operand1_type = NONE; operand2_type = NONE; } else { extract_operands(file_handle, operand1, operand2, line_status, &n_operands); if(n_operands == 0) { operand1_type = NONE; operand2_type = NONE; } else if(n_operands == 1) { operand1_type = parse_operandtype(operand1, symboltable_list, symboltable_currentsize, symbolstracked_list, symbolstracked_currentsize, symbolstracked_actualsize); operand2_type = NONE; } else { //n_operands == 2 operand1_type = parse_operandtype(operand1, symboltable_list, symboltable_currentsize, symbolstracked_list, symbolstracked_currentsize, symbolstracked_actualsize); operand2_type = parse_operandtype(operand2, symboltable_list, symboltable_currentsize, symbolstracked_list, symbolstracked_currentsize, symbolstracked_actualsize); } } data_status = testif_instructionexistent(instruction, instruction_set, operand1_type, operand2_type, &mainindex, &subindex); if(data_status != VALID) { STDERR("invalid operands detected"); EFAILURE; } else { *location_counter += instruction_set[mainindex][subindex].instruction_length; } } uint8_t parse_operandtype(char *operand, symboltable_t **symboltable_list, uint8_t symboltable_currentsize, char ***symbolstracked_list, uint8_t *symbolstracked_currentsize, uint8_t *symbolstracked_actualsize) { uint8_t operand_type; data_status_t data_status; uint8_t byte_length; int8_t index; operand_type = NONE; index = strlen(operand) - 1; if(operand[0] == '(' && operand[index] == ')') { data_status = testif_memlocvalid(operand); if(data_status == VALID) operand_type = MEMORY_16_BIT; else { data_status = testif_indexregwoffset(operand, &operand_type); if(data_status == INVALID) operand_type = NONE; } } if(operand_type == NONE) { data_status = testif_numvalid(operand, &byte_length); if(data_status == VALID) if(byte_length == 1) operand_type = VALUE_8_BIT; else operand_type = VALUE_16_BIT; } if(operand_type == NONE) { data_status = testif_symbolexistent(operand, *symboltable_list, symboltable_currentsize, &operand_type); if(data_status == INVALID) { data_status = checkif_symbolworthy(operand); /* Must check if the symbol adheres to the rules of containing appropriate characters to be a valid symbol. */ if(data_status == VALID) { //operand is symbol worthy operand_type = MEMORY_16_BIT; data_status = track_symbol(operand, symbolstracked_list, symbolstracked_currentsize, symbolstracked_actualsize); if(data_status == INVALID) { free(*symboltable_list); free(*symbolstracked_list); STDERR("symbols could not be tracked\n"); EFAILURE; } } else { operand_type = INVALID_TYPE; } } } return operand_type; } data_status_t testif_memlocvalid(char* operand) { data_status_t data_status; int index, boundary; data_status = VALIDITY_UNKNOWN; index = strlen(operand) - 2; if(operand[index] == 'H' || operand[index] == 'h') { boundary = strlen(operand) - 2; for(index = 1; index < boundary; ++index) if((operand[index] < '0' || operand[index] > '9') && (operand[index] < 'A' || operand[index] > 'F') && (operand[index] < 'a' || operand[index] > 'f')) data_status = INVALID; } else { boundary = strlen(operand) - 1; for(index = 1; index < boundary; ++index) if((operand[index] < '0' || operand[index] > '9')) data_status = INVALID; } if(data_status == VALIDITY_UNKNOWN) data_status = VALID; return data_status; } data_status_t testif_symbolexistent(char *symbol, symboltable_t *symboltable_list, uint8_t symboltable_currentsize, uint8_t *type) { int index; data_status_t data_status; data_status = VALIDITY_UNKNOWN; for(index = 0; index < symboltable_currentsize; ++index) { if(!strcmp(symboltable_list[index].name, symbol)) { *type = symboltable_list[index].value_type; data_status = VALID; } } if(data_status == VALIDITY_UNKNOWN) data_status = INVALID; return data_status; } data_status_t checkif_symbolworthy(char *operand) { data_status_t data_status; int index, boundary; boundary = strlen(operand); data_status = VALIDITY_UNKNOWN; if((operand[0] < 'A' || operand[0] > 'Z') && (operand[0] < 'a' || operand[0] > 'z') && operand[0] != '_') data_status = INVALID; for(index = 1; index < boundary; ++index) { if((operand[index] < '0' || operand[index] > '9') && operand[index] != '_' && (operand[index] < 'A' || operand[index] > 'Z') && (operand[index] < 'a' || operand[index] > 'z')) data_status = INVALID; } if(data_status != INVALID) data_status = VALID; return data_status; } data_status_t testif_instructionexistent(char *instruction, instruction_parameters_t **instruction_set, uint8_t operand1_type, uint8_t operand2_type, int *index1, int *index2) { int mainindex, subindex; loop_status_t loop_status; data_status_t data_status; loop_status = CONTINUE; mainindex = instruction[0] - 65; subindex = 0; data_status = VALIDITY_UNKNOWN; while(instruction_set[mainindex][subindex].instruction_name != NULL && loop_status == CONTINUE) { if((!strcmp(instruction_set[mainindex][subindex].instruction_name, instruction)) && instruction_set[mainindex][subindex].operand_type[0] == operand1_type && instruction_set[mainindex][subindex].operand_type[1] == operand2_type) { data_status = VALID; loop_status = EXIT; *index1 = mainindex; *index2 = subindex; } else { ++subindex; } } if(data_status == VALIDITY_UNKNOWN) data_status = INVALID; return data_status; } void handle_label(char *label, symboltable_t **symboltable_list, uint16_t location_counter, uint8_t *symboltable_currentsize, uint8_t *symboltable_actualsize) { int index, mainindex; uint8_t value[2]; label[(strlen(label) - 1)] = '\0'; value[0] = (uint8_t) location_counter; value[1] = (uint8_t) (location_counter >> 8); storein_symboltable(label, MEMORY_16_BIT, 2, value, symboltable_list, symboltable_currentsize, symboltable_actualsize); } void handle_directive(FILE *file_handle, char *directive, symboltable_t **symboltable_list, uint16_t *location_counter, uint8_t *symboltable_currentsize, uint8_t *symboltable_actualsize, line_status_t *line_status) { status_t status; char dir_arg1[20], dir_arg2[20]; data_status_t data_status, symbol_status, value_status; uint8_t byte_length, value_type; char value_toconvert[20]; uint8_t value[2]; int index, boundary; uint8_t type; if(!strcmp("ORG", directive)) { status = extract_dirarg(file_handle, 1, line_status, dir_arg1, NULL); data_status = testif_numvalid(dir_arg1, &byte_length); if(data_status == VALID) *location_counter = asciistr_to16bitnum(dir_arg1); else { free(*symboltable_list); STDERR("assigning invalid value to location counter\n"); EFAILURE; } } else if(!strcmp("EQU", directive)) { status = extract_dirarg(file_handle, 2, line_status, dir_arg1, dir_arg2); symbol_status = checkif_symbolworthy(dir_arg1); if(symbol_status != VALID) { free(*symboltable_list); STDERR("invalid EQU symbol\n"); EFAILURE; } value_status = parse_equvalue(dir_arg2, &type); if(value_status == VALID) { if(type == MEMORY_16_BIT) { index = 1; boundary = strlen(dir_arg2) - 1; for(; index < boundary; ++index) value_toconvert[index - 1] = dir_arg2[index]; value_toconvert[index - 1] = '\0'; value[0] = (uint8_t) asciistr_to16bitnum(value_toconvert); value[1] = (uint8_t) (asciistr_to16bitnum(value_toconvert) >> 8); byte_length = 2; } else if(type == VALUE_16_BIT) { value[0] = (uint8_t) asciistr_to16bitnum(dir_arg2); value[1] = (uint8_t) (asciistr_to16bitnum(dir_arg2) >> 8); byte_length = 2; } else { value[0] = (uint8_t) asciistr_to16bitnum(dir_arg2); byte_length = 1; } storein_symboltable(dir_arg1, type, byte_length, value, symboltable_list, symboltable_currentsize, symboltable_actualsize); } else { data_status = testif_symbolexistent(dir_arg2, *symboltable_list, *symboltable_currentsize, &type); if(data_status == VALID) { get_symbolparams(dir_arg2, *symboltable_list, *symboltable_currentsize, &byte_length, value); storein_symboltable(dir_arg1, type, byte_length, value, symboltable_list, symboltable_currentsize, symboltable_actualsize); } else { STDERR("could not store symbol\n"); } } } } status_t extract_dirarg(FILE *file_handle, uint8_t extract_ndirargs, line_status_t *line_status, char *dir_arg1, char *dir_arg2) { int index, c; char buffer[20]; status_t status; uint8_t byte_length; do { c = fgetc(file_handle); } while(c != EOF && (c == ' ' || c == '\t')); if(c == EOF || c== '\n' || c== '\r' || c == ';') { status = ERROR; } else { index = 0; do { buffer[index++] = c; c = fgetc(file_handle); } while(c != EOF && c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != ';'); buffer[index] = '\0'; status = NO_ERROR; strcpy(dir_arg1, buffer); if(c == EOF) *line_status = ENDOFFILE_DETECTED; else if(c == '\n') *line_status = NEWLINE_DETECTED; else if(c == '\r') *line_status = CARRIAGERETURN_DETECTED; else if(c == ';') *line_status = COMMNTDELIM_DETECTED; else *line_status = NONE_DETECTED; } if(status == NO_ERROR) { if(extract_ndirargs == 2) { do { c = fgetc(file_handle); } while(c != EOF && (c == ' ' || c == '\t')); if(c == EOF || c == '\n' || c == '\r' || c == ';') { status = ERROR; } else { index = 0; do { buffer[index++] = c; c = fgetc(file_handle); } while(c != EOF && c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != ';'); buffer[index] = '\0'; status = NO_ERROR; strcpy(dir_arg2, buffer); if(c == EOF) *line_status = ENDOFFILE_DETECTED; else if(c == '\n') *line_status = NEWLINE_DETECTED; else if(c == '\r') *line_status = CARRIAGERETURN_DETECTED; else if(c == ';') *line_status = COMMNTDELIM_DETECTED; else *line_status = NONE_DETECTED; } } else { status = NO_ERROR; } } return status; } data_status_t parse_equvalue(char *value, uint8_t *type) { int index; data_status_t value_status; uint8_t byte_length; index = strlen(value) - 1; value_status = VALIDITY_UNKNOWN; if(value[0] == '(' && value[index] == ')') { value_status = testif_memlocvalid(value); if(value_status == VALID) *type = MEMORY_16_BIT; } if(value_status != VALID) { value_status = testif_numvalid(value, &byte_length); if(value_status == VALID) if(byte_length == 1) *type = VALUE_8_BIT; else *type = VALUE_16_BIT; } return value_status; } data_status_t track_symbol(char *symbol, char ***symbolstracked_list, uint8_t *symbolstracked_currentsize, uint8_t *symbolstracked_actualsize) { int index, size; enum symbol_status_t {NOT_FOUND = 0, FOUND} symbol_status; char **symbolstracked_newlist; data_status_t data_status; symbol_status = NOT_FOUND; for(index = 0; index < *symbolstracked_currentsize; ++index) { if(!strcmp((*symbolstracked_list)[index], symbol)) symbol_status = FOUND; } if(symbol_status == NOT_FOUND) { if(*symbolstracked_currentsize == *symbolstracked_actualsize) { symbolstracked_newlist = realloc(*symbolstracked_list, (*symbolstracked_actualsize + 10) * sizeof(*symbolstracked_newlist)); if(symbolstracked_newlist == NULL) data_status = INVALID; else { *symbolstracked_list = symbolstracked_newlist; *symbolstracked_actualsize += 10; } } index = (*symbolstracked_currentsize)++; size = strlen(symbol) + 1; (*symbolstracked_list)[index] = malloc(size * sizeof(*((*symbolstracked_list)[index]))); if((*symbolstracked_list)[index] == NULL) data_status = INVALID; else { strcpy((*symbolstracked_list)[index], symbol); } } return data_status; } status_t validate_symbolstracked(char **symbolstracked_list, symboltable_t *symboltable_list, uint8_t symbolstracked_currentsize, uint8_t symboltable_currentsize) { int index1, index2; status_t status; data_status_t data_status; status = NO_ERROR; for(index1 = 0; index1 < symbolstracked_currentsize; ++index1) { data_status = INVALID; for(index2 = 0; index2 < symboltable_currentsize; ++index2) { if(!strcmp(symboltable_list[index2].name, symbolstracked_list[index1])) data_status = VALID; } if(data_status != VALID) status = ERROR; } return status; } void get_symbolparams(char *symbol, symboltable_t *symboltable_list, uint8_t symboltable_currentsize, uint8_t *byte_length, uint8_t value[]) { int index1, index2; for(index1 = 0; index1 < symboltable_currentsize; ++index1) { if(!strcmp(symbol, symboltable_list[index1].name)) { *byte_length = symboltable_list[index1].value_nbytes; for(index2 = 0; index2 < *byte_length; ++ index2) value[index2] = symboltable_list[index1].value[index2]; } } } data_status_t testif_indexregwoffset(char *operand, uint8_t *operand_type) { int index, boundary, index2; char buffer[10]; enum indexreg_type_t {NO_INDEXREG = 0, IX, IY} indexreg_type; data_status_t data_status; index = 1; boundary = strlen(operand) - 1; index2 = 0; while(operand[index] >= 'A' && operand[index] <= 'Z') { buffer[index2] = operand[index]; ++index; ++index2; } buffer[index2] = '\0'; if(!strcmp(buffer, "IX")) indexreg_type = IX; else if(!strcmp(buffer, "IY")) indexreg_type = IY; else indexreg_type = NO_INDEXREG; if(indexreg_type != NO_INDEXREG) { while(operand[index] == ' ' || operand[index] == '\t') ++index; if(operand[index] == '+') { ++index; while(operand[index] == ' ' || operand[index] == '\t') ++index; index2 = 0; while(operand[index] != ')') { buffer[index2] = operand[index]; ++index2; ++index; } data_status = VALID; if(buffer[index2 - 1] == 'H' || buffer[index2 - 1] == 'h') index2 = index2 - 1; for(index = 0; index < index2; ++index) { if((buffer[index] < '0' || buffer[index] > '9') && (buffer[index] < 'A' || buffer[index] > 'F') && (buffer[index] < 'a' || buffer[index] > 'f')) data_status = INVALID; } if(data_status == VALID) { if(indexreg_type == IX) *operand_type = IX_REGISTER_WOFFSET; else { *operand_type = IY_REGISTER_WOFFSET; } } } else data_status = INVALID; } else data_status = INVALID; return data_status; }
gpl-3.0
aj-m/dBittorrent
include/libtransmission/rpc-server.c
1
30994
/* * This file Copyright (C) 2008-2014 Mnemosyne LLC * * It may be used under the GNU GPL versions 2 or 3 * or any future license endorsed by Mnemosyne LLC. * */ #include <assert.h> #include <errno.h> #include <string.h> /* memcpy */ #include <zlib.h> #include <event2/buffer.h> #include <event2/event.h> #include <event2/http.h> #include <event2/http_struct.h> /* TODO: eventually remove this */ #include "transmission.h" #include "crypto.h" /* tr_ssha1_matches () */ #include "crypto-utils.h" /* tr_rand_buffer () */ #include "error.h" #include "fdlimit.h" #include "list.h" #include "log.h" #include "net.h" #include "platform.h" /* tr_getWebClientDir () */ #include "ptrarray.h" #include "rpcimpl.h" #include "rpc-server.h" #include "session.h" #include "session-id.h" #include "trevent.h" #include "utils.h" #include "variant.h" #include "web.h" /* session-id is used to make cross-site request forgery attacks difficult. * Don't disable this feature unless you really know what you're doing! * http://en.wikipedia.org/wiki/Cross-site_request_forgery * http://shiflett.org/articles/cross-site-request-forgeries * http://www.webappsec.org/lists/websecurity/archive/2008-04/msg00037.html */ #define REQUIRE_SESSION_ID #define MY_NAME "RPC Server" #define MY_REALM "Transmission" #define TR_N_ELEMENTS(ary) (sizeof (ary) / sizeof (*ary)) struct tr_rpc_server { bool isEnabled; bool isPasswordEnabled; bool isWhitelistEnabled; tr_port port; char * url; struct in_addr bindAddress; struct evhttp * httpd; struct event * start_retry_timer; int start_retry_counter; tr_session * session; char * username; char * password; char * whitelistStr; tr_list * whitelist; bool isStreamInitialized; z_stream stream; }; #define dbgmsg(...) \ do { \ if (tr_logGetDeepEnabled ()) \ tr_logAddDeep (__FILE__, __LINE__, MY_NAME, __VA_ARGS__); \ } while (0) /*** **** ***/ static const char * get_current_session_id (struct tr_rpc_server * server) { return tr_session_id_get_current (server->session->session_id); } /** *** **/ static void send_simple_response (struct evhttp_request * req, int code, const char * text) { const char * code_text = tr_webGetResponseStr (code); struct evbuffer * body = evbuffer_new (); evbuffer_add_printf (body, "<h1>%d: %s</h1>", code, code_text); if (text) evbuffer_add_printf (body, "%s", text); evhttp_send_reply (req, code, code_text, body); evbuffer_free (body); } struct tr_mimepart { char * headers; size_t headers_len; char * body; size_t body_len; }; static void tr_mimepart_free (struct tr_mimepart * p) { tr_free (p->body); tr_free (p->headers); tr_free (p); } static void extract_parts_from_multipart (const struct evkeyvalq * headers, struct evbuffer * body, tr_ptrArray * setme_parts) { const char * content_type = evhttp_find_header (headers, "Content-Type"); const char * in = (const char*) evbuffer_pullup (body, -1); size_t inlen = evbuffer_get_length (body); const char * boundary_key = "boundary="; const char * boundary_key_begin = content_type ? strstr (content_type, boundary_key) : NULL; const char * boundary_val = boundary_key_begin ? boundary_key_begin + strlen (boundary_key) : "arglebargle"; char * boundary = tr_strdup_printf ("--%s", boundary_val); const size_t boundary_len = strlen (boundary); const char * delim = tr_memmem (in, inlen, boundary, boundary_len); while (delim) { size_t part_len; const char * part = delim + boundary_len; inlen -= (part - in); in = part; delim = tr_memmem (in, inlen, boundary, boundary_len); part_len = delim ? (size_t)(delim - part) : inlen; if (part_len) { const char * rnrn = tr_memmem (part, part_len, "\r\n\r\n", 4); if (rnrn) { struct tr_mimepart * p = tr_new (struct tr_mimepart, 1); p->headers_len = (size_t) (rnrn - part); p->headers = tr_strndup (part, p->headers_len); p->body_len = (size_t) ((part + part_len) - (rnrn + 4)); p->body = tr_strndup (rnrn+4, p->body_len); tr_ptrArrayAppend (setme_parts, p); } } } tr_free (boundary); } static void handle_upload (struct evhttp_request * req, struct tr_rpc_server * server) { if (req->type != EVHTTP_REQ_POST) { send_simple_response (req, 405, NULL); } else { int i; int n; bool hasSessionId = false; tr_ptrArray parts = TR_PTR_ARRAY_INIT; const char * query = strchr (req->uri, '?'); const bool paused = query && strstr (query + 1, "paused=true"); extract_parts_from_multipart (req->input_headers, req->input_buffer, &parts); n = tr_ptrArraySize (&parts); /* first look for the session id */ for (i=0; i<n; ++i) { struct tr_mimepart * p = tr_ptrArrayNth (&parts, i); if (tr_memmem (p->headers, p->headers_len, TR_RPC_SESSION_ID_HEADER, strlen (TR_RPC_SESSION_ID_HEADER))) break; } if (i<n) { const struct tr_mimepart * p = tr_ptrArrayNth (&parts, i); const char * ours = get_current_session_id (server); const size_t ourlen = strlen (ours); hasSessionId = ourlen <= p->body_len && memcmp (p->body, ours, ourlen) == 0; } if (!hasSessionId) { int code = 409; const char * codetext = tr_webGetResponseStr (code); struct evbuffer * body = evbuffer_new (); evbuffer_add_printf (body, "%s", "{ \"success\": false, \"msg\": \"Bad Session-Id\" }");; evhttp_send_reply (req, code, codetext, body); evbuffer_free (body); } else for (i=0; i<n; ++i) { struct tr_mimepart * p = tr_ptrArrayNth (&parts, i); size_t body_len = p->body_len; tr_variant top, *args; tr_variant test; bool have_source = false; char * body = p->body; if (body_len >= 2 && memcmp (&body[body_len - 2], "\r\n", 2) == 0) body_len -= 2; tr_variantInitDict (&top, 2); tr_variantDictAddStr (&top, TR_KEY_method, "torrent-add"); args = tr_variantDictAddDict (&top, TR_KEY_arguments, 2); tr_variantDictAddBool (args, TR_KEY_paused, paused); if (tr_urlIsValid (body, body_len)) { tr_variantDictAddRaw (args, TR_KEY_filename, body, body_len); have_source = true; } else if (!tr_variantFromBenc (&test, body, body_len)) { char * b64 = tr_base64_encode (body, body_len, NULL); tr_variantDictAddStr (args, TR_KEY_metainfo, b64); tr_free (b64); have_source = true; } if (have_source) tr_rpc_request_exec_json (server->session, &top, NULL, NULL); tr_variantFree (&top); } tr_ptrArrayDestruct (&parts, (PtrArrayForeachFunc)tr_mimepart_free); /* send "success" response */ { int code = HTTP_OK; const char * codetext = tr_webGetResponseStr (code); struct evbuffer * body = evbuffer_new (); evbuffer_add_printf (body, "%s", "{ \"success\": true, \"msg\": \"Torrent Added\" }");; evhttp_send_reply (req, code, codetext, body); evbuffer_free (body); } } } /*** **** ***/ static const char* mimetype_guess (const char * path) { unsigned int i; const struct { const char * suffix; const char * mime_type; } types[] = { /* these are the ones we need for serving the web client's files... */ { "css", "text/css" }, { "gif", "image/gif" }, { "html", "text/html" }, { "ico", "image/vnd.microsoft.icon" }, { "js", "application/javascript" }, { "png", "image/png" } }; const char * dot = strrchr (path, '.'); for (i = 0; dot && i < TR_N_ELEMENTS (types); ++i) if (strcmp (dot + 1, types[i].suffix) == 0) return types[i].mime_type; return "application/octet-stream"; } static void add_response (struct evhttp_request * req, struct tr_rpc_server * server, struct evbuffer * out, struct evbuffer * content) { const char * key = "Accept-Encoding"; const char * encoding = evhttp_find_header (req->input_headers, key); const int do_compress = encoding && strstr (encoding, "gzip"); if (!do_compress) { evbuffer_add_buffer (out, content); } else { int state; struct evbuffer_iovec iovec[1]; void * content_ptr = evbuffer_pullup (content, -1); const size_t content_len = evbuffer_get_length (content); if (!server->isStreamInitialized) { int compressionLevel; server->isStreamInitialized = true; server->stream.zalloc = (alloc_func) Z_NULL; server->stream.zfree = (free_func) Z_NULL; server->stream.opaque = (voidpf) Z_NULL; /* zlib's manual says: "Add 16 to windowBits to write a simple gzip header * and trailer around the compressed data instead of a zlib wrapper." */ #ifdef TR_LIGHTWEIGHT compressionLevel = Z_DEFAULT_COMPRESSION; #else compressionLevel = Z_BEST_COMPRESSION; #endif deflateInit2 (&server->stream, compressionLevel, Z_DEFLATED, 15+16, 8, Z_DEFAULT_STRATEGY); } server->stream.next_in = content_ptr; server->stream.avail_in = content_len; /* allocate space for the raw data and call deflate () just once -- * we won't use the deflated data if it's longer than the raw data, * so it's okay to let deflate () run out of output buffer space */ evbuffer_reserve_space (out, content_len, iovec, 1); server->stream.next_out = iovec[0].iov_base; server->stream.avail_out = iovec[0].iov_len; state = deflate (&server->stream, Z_FINISH); if (state == Z_STREAM_END) { iovec[0].iov_len -= server->stream.avail_out; #if 0 fprintf (stderr, "compressed response is %.2f of original (raw==%zu bytes; compressed==%zu)\n", (double)evbuffer_get_length (out)/content_len, content_len, evbuffer_get_length (out)); #endif evhttp_add_header (req->output_headers, "Content-Encoding", "gzip"); } else { memcpy (iovec[0].iov_base, content_ptr, content_len); iovec[0].iov_len = content_len; } evbuffer_commit_space (out, iovec, 1); deflateReset (&server->stream); } } static void add_time_header (struct evkeyvalq * headers, const char * key, time_t value) { /* According to RFC 2616 this must follow RFC 1123's date format, so use gmtime instead of localtime... */ char buf[128]; struct tm tm = *gmtime (&value); strftime (buf, sizeof (buf), "%a, %d %b %Y %H:%M:%S GMT", &tm); evhttp_add_header (headers, key, buf); } static void evbuffer_ref_cleanup_tr_free (const void * data UNUSED, size_t datalen UNUSED, void * extra) { tr_free (extra); } static void serve_file (struct evhttp_request * req, struct tr_rpc_server * server, const char * filename) { if (req->type != EVHTTP_REQ_GET) { evhttp_add_header (req->output_headers, "Allow", "GET"); send_simple_response (req, 405, NULL); } else { void * file; size_t file_len; tr_error * error = NULL; file_len = 0; file = tr_loadFile (filename, &file_len, &error); if (file == NULL) { char * tmp = tr_strdup_printf ("%s (%s)", filename, error->message); send_simple_response (req, HTTP_NOTFOUND, tmp); tr_free (tmp); tr_error_free (error); } else { struct evbuffer * content; struct evbuffer * out; const time_t now = tr_time (); content = evbuffer_new (); evbuffer_add_reference (content, file, file_len, evbuffer_ref_cleanup_tr_free, file); out = evbuffer_new (); evhttp_add_header (req->output_headers, "Content-Type", mimetype_guess (filename)); add_time_header (req->output_headers, "Date", now); add_time_header (req->output_headers, "Expires", now+ (24*60*60)); add_response (req, server, out, content); evhttp_send_reply (req, HTTP_OK, "OK", out); evbuffer_free (out); evbuffer_free (content); } } } static void handle_web_client (struct evhttp_request * req, struct tr_rpc_server * server) { const char * webClientDir = tr_getWebClientDir (server->session); if (!webClientDir || !*webClientDir) { send_simple_response (req, HTTP_NOTFOUND, "<p>Couldn't find Transmission's web interface files!</p>" "<p>Users: to tell Transmission where to look, " "set the TRANSMISSION_WEB_HOME environment " "variable to the folder where the web interface's " "index.html is located.</p>" "<p>Package Builders: to set a custom default at compile time, " "#define PACKAGE_DATA_DIR in libtransmission/platform.c " "or tweak tr_getClutchDir () by hand.</p>"); } else { char * pch; char * subpath; subpath = tr_strdup (req->uri + strlen (server->url) + 4); if ((pch = strchr (subpath, '?'))) *pch = '\0'; if (strstr (subpath, "..")) { send_simple_response (req, HTTP_NOTFOUND, "<p>Tsk, tsk.</p>"); } else { char * filename = tr_strdup_printf ("%s%s%s", webClientDir, TR_PATH_DELIMITER_STR, *subpath != '\0' ? subpath : "index.html"); serve_file (req, server, filename); tr_free (filename); } tr_free (subpath); } } struct rpc_response_data { struct evhttp_request * req; struct tr_rpc_server * server; }; static void rpc_response_func (tr_session * session UNUSED, tr_variant * response, void * user_data) { struct rpc_response_data * data = user_data; struct evbuffer * response_buf = tr_variantToBuf (response, TR_VARIANT_FMT_JSON_LEAN); struct evbuffer * buf = evbuffer_new (); add_response (data->req, data->server, buf, response_buf); evhttp_add_header (data->req->output_headers, "Content-Type", "application/json; charset=UTF-8"); evhttp_send_reply (data->req, HTTP_OK, "OK", buf); evbuffer_free (buf); evbuffer_free (response_buf); tr_free (data); } static void handle_rpc_from_json (struct evhttp_request * req, struct tr_rpc_server * server, const char * json, size_t json_len) { tr_variant top; bool have_content = tr_variantFromJson (&top, json, json_len) == 0; struct rpc_response_data * data; data = tr_new0 (struct rpc_response_data, 1); data->req = req; data->server = server; tr_rpc_request_exec_json (server->session, have_content ? &top : NULL, rpc_response_func, data); if (have_content) tr_variantFree (&top); } static void handle_rpc (struct evhttp_request * req, struct tr_rpc_server * server) { const char * q; if (req->type == EVHTTP_REQ_POST) { handle_rpc_from_json (req, server, (const char *) evbuffer_pullup (req->input_buffer, -1), evbuffer_get_length (req->input_buffer)); } else if ((req->type == EVHTTP_REQ_GET) && ((q = strchr (req->uri, '?')))) { struct rpc_response_data * data = tr_new0 (struct rpc_response_data, 1); data->req = req; data->server = server; tr_rpc_request_exec_uri (server->session, q + 1, TR_BAD_SIZE, rpc_response_func, data); } else { send_simple_response (req, 405, NULL); } } static bool isAddressAllowed (const tr_rpc_server * server, const char * address) { tr_list * l; if (!server->isWhitelistEnabled) return true; for (l=server->whitelist; l!=NULL; l=l->next) if (tr_wildmat (address, l->data)) return true; return false; } static bool test_session_id (struct tr_rpc_server * server, struct evhttp_request * req) { const char * ours = get_current_session_id (server); const char * theirs = evhttp_find_header (req->input_headers, TR_RPC_SESSION_ID_HEADER); const bool success = theirs != NULL && strcmp (theirs, ours) == 0; return success; } static void handle_request (struct evhttp_request * req, void * arg) { struct tr_rpc_server * server = arg; if (req && req->evcon) { const char * auth; char * user = NULL; char * pass = NULL; evhttp_add_header (req->output_headers, "Server", MY_REALM); auth = evhttp_find_header (req->input_headers, "Authorization"); if (auth && !evutil_ascii_strncasecmp (auth, "basic ", 6)) { size_t plen; char * p = tr_base64_decode_str (auth + 6, &plen); if (p != NULL) { if (plen > 0 && (pass = strchr (p, ':')) != NULL) { user = p; *pass++ = '\0'; } else { tr_free (p); } } } if (!isAddressAllowed (server, req->remote_host)) { send_simple_response (req, 403, "<p>Unauthorized IP Address.</p>" "<p>Either disable the IP address whitelist or add your address to it.</p>" "<p>If you're editing settings.json, see the 'rpc-whitelist' and 'rpc-whitelist-enabled' entries.</p>" "<p>If you're still using ACLs, use a whitelist instead. See the transmission-daemon manpage for details.</p>"); } else if (server->isPasswordEnabled && (pass == NULL || user == NULL || strcmp (server->username, user) != 0 || !tr_ssha1_matches (server->password, pass))) { evhttp_add_header (req->output_headers, "WWW-Authenticate", "Basic realm=\"" MY_REALM "\""); send_simple_response (req, 401, "Unauthorized User"); } else if (strncmp (req->uri, server->url, strlen (server->url)) != 0) { char * location = tr_strdup_printf ("%sweb/", server->url); evhttp_add_header (req->output_headers, "Location", location); send_simple_response (req, HTTP_MOVEPERM, NULL); tr_free (location); } else if (strncmp (req->uri + strlen (server->url), "web/", 4) == 0) { handle_web_client (req, server); } else if (strcmp (req->uri + strlen (server->url), "upload") == 0) { handle_upload (req, server); } #ifdef REQUIRE_SESSION_ID else if (!test_session_id (server, req)) { const char * sessionId = get_current_session_id (server); char * tmp = tr_strdup_printf ( "<p>Your request had an invalid session-id header.</p>" "<p>To fix this, follow these steps:" "<ol><li> When reading a response, get its X-Transmission-Session-Id header and remember it" "<li> Add the updated header to your outgoing requests" "<li> When you get this 409 error message, resend your request with the updated header" "</ol></p>" "<p>This requirement has been added to help prevent " "<a href=\"http://en.wikipedia.org/wiki/Cross-site_request_forgery\">CSRF</a> " "attacks.</p>" "<p><code>%s: %s</code></p>", TR_RPC_SESSION_ID_HEADER, sessionId); evhttp_add_header (req->output_headers, TR_RPC_SESSION_ID_HEADER, sessionId); send_simple_response (req, 409, tmp); tr_free (tmp); } #endif else if (strncmp (req->uri + strlen (server->url), "rpc", 3) == 0) { handle_rpc (req, server); } else { send_simple_response (req, HTTP_NOTFOUND, req->uri); } tr_free (user); } } enum { SERVER_START_RETRY_COUNT = 10, SERVER_START_RETRY_DELAY_STEP = 3, SERVER_START_RETRY_DELAY_INCREMENT = 5, SERVER_START_RETRY_MAX_DELAY = 60 }; static void startServer (void * vserver); static void rpc_server_on_start_retry (evutil_socket_t fd UNUSED, short type UNUSED, void * context) { startServer (context); } static int rpc_server_start_retry (tr_rpc_server * server) { int retry_delay = (server->start_retry_counter / SERVER_START_RETRY_DELAY_STEP + 1) * SERVER_START_RETRY_DELAY_INCREMENT; retry_delay = MIN (retry_delay, SERVER_START_RETRY_MAX_DELAY); if (server->start_retry_timer == NULL) server->start_retry_timer = evtimer_new (server->session->event_base, rpc_server_on_start_retry, server); tr_timerAdd (server->start_retry_timer, retry_delay, 0); ++server->start_retry_counter; return retry_delay; } static void rpc_server_start_retry_cancel (tr_rpc_server * server) { if (server->start_retry_timer != NULL) { event_free (server->start_retry_timer); server->start_retry_timer = NULL; } server->start_retry_counter = 0; } static void startServer (void * vserver) { tr_rpc_server * server = vserver; if (server->httpd != NULL) return; struct evhttp * httpd = evhttp_new (server->session->event_base); const char * address = tr_rpcGetBindAddress (server); const int port = server->port; if (evhttp_bind_socket (httpd, address, port) == -1) { evhttp_free (httpd); if (server->start_retry_counter < SERVER_START_RETRY_COUNT) { const int retry_delay = rpc_server_start_retry (server); tr_logAddNamedDbg (MY_NAME, "Unable to bind to %s:%d, retrying in %d seconds", address, port, retry_delay); return; } tr_logAddNamedError (MY_NAME, "Unable to bind to %s:%d after %d attempts, giving up", address, port, SERVER_START_RETRY_COUNT); } else { evhttp_set_gencb (httpd, handle_request, server); server->httpd = httpd; tr_logAddNamedDbg (MY_NAME, "Started listening on %s:%d", address, port); } rpc_server_start_retry_cancel (server); } static void stopServer (tr_rpc_server * server) { rpc_server_start_retry_cancel (server); struct evhttp * httpd = server->httpd; if (httpd == NULL) return; const char * address = tr_rpcGetBindAddress (server); const int port = server->port; server->httpd = NULL; evhttp_free (httpd); tr_logAddNamedDbg (MY_NAME, "Stopped listening on %s:%d", address, port); } static void onEnabledChanged (void * vserver) { tr_rpc_server * server = vserver; if (!server->isEnabled) stopServer (server); else startServer (server); } void tr_rpcSetEnabled (tr_rpc_server * server, bool isEnabled) { server->isEnabled = isEnabled; tr_runInEventThread (server->session, onEnabledChanged, server); } bool tr_rpcIsEnabled (const tr_rpc_server * server) { return server->isEnabled; } static void restartServer (void * vserver) { tr_rpc_server * server = vserver; if (server->isEnabled) { stopServer (server); startServer (server); } } void tr_rpcSetPort (tr_rpc_server * server, tr_port port) { assert (server != NULL); if (server->port != port) { server->port = port; if (server->isEnabled) tr_runInEventThread (server->session, restartServer, server); } } tr_port tr_rpcGetPort (const tr_rpc_server * server) { return server->port; } void tr_rpcSetUrl (tr_rpc_server * server, const char * url) { char * tmp = server->url; server->url = tr_strdup (url); dbgmsg ("setting our URL to [%s]", server->url); tr_free (tmp); } const char* tr_rpcGetUrl (const tr_rpc_server * server) { return server->url ? server->url : ""; } void tr_rpcSetWhitelist (tr_rpc_server * server, const char * whitelistStr) { void * tmp; const char * walk; /* keep the string */ tmp = server->whitelistStr; server->whitelistStr = tr_strdup (whitelistStr); tr_free (tmp); /* clear out the old whitelist entries */ while ((tmp = tr_list_pop_front (&server->whitelist))) tr_free (tmp); /* build the new whitelist entries */ for (walk=whitelistStr; walk && *walk;) { const char * delimiters = " ,;"; const size_t len = strcspn (walk, delimiters); char * token = tr_strndup (walk, len); tr_list_append (&server->whitelist, token); if (strcspn (token, "+-") < len) tr_logAddNamedInfo (MY_NAME, "Adding address to whitelist: %s (And it has a '+' or '-'! Are you using an old ACL by mistake?)", token); else tr_logAddNamedInfo (MY_NAME, "Adding address to whitelist: %s", token); if (walk[len]=='\0') break; walk += len + 1; } } const char* tr_rpcGetWhitelist (const tr_rpc_server * server) { return server->whitelistStr ? server->whitelistStr : ""; } void tr_rpcSetWhitelistEnabled (tr_rpc_server * server, bool isEnabled) { assert (tr_isBool (isEnabled)); server->isWhitelistEnabled = isEnabled; } bool tr_rpcGetWhitelistEnabled (const tr_rpc_server * server) { return server->isWhitelistEnabled; } /**** ***** PASSWORD ****/ void tr_rpcSetUsername (tr_rpc_server * server, const char * username) { char * tmp = server->username; server->username = tr_strdup (username); dbgmsg ("setting our Username to [%s]", server->username); tr_free (tmp); } const char* tr_rpcGetUsername (const tr_rpc_server * server) { return server->username ? server->username : ""; } void tr_rpcSetPassword (tr_rpc_server * server, const char * password) { tr_free (server->password); if (*password != '{') server->password = tr_ssha1 (password); else server->password = strdup (password); dbgmsg ("setting our Password to [%s]", server->password); } const char* tr_rpcGetPassword (const tr_rpc_server * server) { return server->password ? server->password : "" ; } void tr_rpcSetPasswordEnabled (tr_rpc_server * server, bool isEnabled) { server->isPasswordEnabled = isEnabled; dbgmsg ("setting 'password enabled' to %d", (int)isEnabled); } bool tr_rpcIsPasswordEnabled (const tr_rpc_server * server) { return server->isPasswordEnabled; } const char * tr_rpcGetBindAddress (const tr_rpc_server * server) { tr_address addr; addr.type = TR_AF_INET; addr.addr.addr4 = server->bindAddress; return tr_address_to_string (&addr); } /**** ***** LIFE CYCLE ****/ static void closeServer (void * vserver) { void * tmp; tr_rpc_server * s = vserver; stopServer (s); while ((tmp = tr_list_pop_front (&s->whitelist))) tr_free (tmp); if (s->isStreamInitialized) deflateEnd (&s->stream); tr_free (s->url); tr_free (s->whitelistStr); tr_free (s->username); tr_free (s->password); tr_free (s); } void tr_rpcClose (tr_rpc_server ** ps) { tr_runInEventThread ((*ps)->session, closeServer, *ps); *ps = NULL; } static void missing_settings_key (const tr_quark q) { const char * str = tr_quark_get_string (q, NULL); tr_logAddNamedError (MY_NAME, _("Couldn't find settings key \"%s\""), str); } tr_rpc_server * tr_rpcInit (tr_session * session, tr_variant * settings) { tr_rpc_server * s; bool boolVal; int64_t i; const char * str; tr_quark key; tr_address address; s = tr_new0 (tr_rpc_server, 1); s->session = session; key = TR_KEY_rpc_enabled; if (!tr_variantDictFindBool (settings, key, &boolVal)) missing_settings_key (key); else s->isEnabled = boolVal; key = TR_KEY_rpc_port; if (!tr_variantDictFindInt (settings, key, &i)) missing_settings_key (key); else s->port = i; key = TR_KEY_rpc_url; if (!tr_variantDictFindStr (settings, key, &str, NULL)) missing_settings_key (key); else s->url = tr_strdup (str); key = TR_KEY_rpc_whitelist_enabled; if (!tr_variantDictFindBool (settings, key, &boolVal)) missing_settings_key (key); else tr_rpcSetWhitelistEnabled (s, boolVal); key = TR_KEY_rpc_authentication_required; if (!tr_variantDictFindBool (settings, key, &boolVal)) missing_settings_key (key); else tr_rpcSetPasswordEnabled (s, boolVal); key = TR_KEY_rpc_whitelist; if (!tr_variantDictFindStr (settings, key, &str, NULL) && str) missing_settings_key (key); else tr_rpcSetWhitelist (s, str); key = TR_KEY_rpc_username; if (!tr_variantDictFindStr (settings, key, &str, NULL)) missing_settings_key (key); else tr_rpcSetUsername (s, str); key = TR_KEY_rpc_password; if (!tr_variantDictFindStr (settings, key, &str, NULL)) missing_settings_key (key); else tr_rpcSetPassword (s, str); key = TR_KEY_rpc_bind_address; if (!tr_variantDictFindStr (settings, key, &str, NULL)) { missing_settings_key (key); address = tr_inaddr_any; } else if (!tr_address_from_string (&address, str)) { tr_logAddNamedError (MY_NAME, _("%s is not a valid address"), str); address = tr_inaddr_any; } else if (address.type != TR_AF_INET) { tr_logAddNamedError (MY_NAME, _("%s is not an IPv4 address. RPC listeners must be IPv4"), str); address = tr_inaddr_any; } s->bindAddress = address.addr.addr4; if (s->isEnabled) { tr_logAddNamedInfo (MY_NAME, _("Serving RPC and Web requests on port 127.0.0.1:%d%s"), (int) s->port, s->url); tr_runInEventThread (session, startServer, s); if (s->isWhitelistEnabled) tr_logAddNamedInfo (MY_NAME, "%s", _("Whitelist enabled")); if (s->isPasswordEnabled) tr_logAddNamedInfo (MY_NAME, "%s", _("Password required")); } return s; }
gpl-3.0
usbxyz/CAN-Bootloader
firmware/stm32f405/bootloader/User/can_bootloader.c
1
12984
/** ****************************************************************************** * @file can_bootloader.c * $Author: wdluo $ * $Revision: 17 $ * $Date:: 2012-07-06 11:16:48 +0800 #$ * @brief »ùÓÚCAN×ÜÏßµÄBootloader³ÌÐò. ****************************************************************************** * @attention * *<h3><center>&copy; Copyright 2009-2012, ViewTool</center> *<center><a href="http:\\www.viewtool.com">http://www.viewtool.com</a></center> *<center>All Rights Reserved</center></h3> * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "can_bootloader.h" #include "crc16.h" #include "delay.h" /* Private typedef -----------------------------------------------------------*/ typedef void (*pFunction)(void); /* Private define ------------------------------------------------------------*/ /* Base address of the Flash sectors */ #define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base @ of Sector 0, 16 Kbytes */ #define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08004000) /* Base @ of Sector 1, 16 Kbytes */ #define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08008000) /* Base @ of Sector 2, 16 Kbytes */ #define ADDR_FLASH_SECTOR_3 ((uint32_t)0x0800C000) /* Base @ of Sector 3, 16 Kbytes */ #define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08010000) /* Base @ of Sector 4, 64 Kbytes */ #define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08020000) /* Base @ of Sector 5, 128 Kbytes */ #define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08040000) /* Base @ of Sector 6, 128 Kbytes */ #define ADDR_FLASH_SECTOR_7 ((uint32_t)0x08060000) /* Base @ of Sector 7, 128 Kbytes */ #define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08080000) /* Base @ of Sector 8, 128 Kbytes */ #define ADDR_FLASH_SECTOR_9 ((uint32_t)0x080A0000) /* Base @ of Sector 9, 128 Kbytes */ #define ADDR_FLASH_SECTOR_10 ((uint32_t)0x080C0000) /* Base @ of Sector 10, 128 Kbytes */ #define ADDR_FLASH_SECTOR_11 ((uint32_t)0x080E0000) /* Base @ of Sector 11, 128 Kbytes */ /* Private macro -------------------------------------------------------------*/ extern CBL_CMD_LIST CMD_List; /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief Gets the sector of a given address * @param None * @retval The sector of a given address */ uint32_t GetSector(uint32_t Address) { uint32_t sector = 0; if((Address < ADDR_FLASH_SECTOR_1) && (Address >= ADDR_FLASH_SECTOR_0)) { sector = FLASH_Sector_0; } else if((Address < ADDR_FLASH_SECTOR_2) && (Address >= ADDR_FLASH_SECTOR_1)) { sector = FLASH_Sector_1; } else if((Address < ADDR_FLASH_SECTOR_3) && (Address >= ADDR_FLASH_SECTOR_2)) { sector = FLASH_Sector_2; } else if((Address < ADDR_FLASH_SECTOR_4) && (Address >= ADDR_FLASH_SECTOR_3)) { sector = FLASH_Sector_3; } else if((Address < ADDR_FLASH_SECTOR_5) && (Address >= ADDR_FLASH_SECTOR_4)) { sector = FLASH_Sector_4; } else if((Address < ADDR_FLASH_SECTOR_6) && (Address >= ADDR_FLASH_SECTOR_5)) { sector = FLASH_Sector_5; } else if((Address < ADDR_FLASH_SECTOR_7) && (Address >= ADDR_FLASH_SECTOR_6)) { sector = FLASH_Sector_6; } else if((Address < ADDR_FLASH_SECTOR_8) && (Address >= ADDR_FLASH_SECTOR_7)) { sector = FLASH_Sector_7; } else if((Address < ADDR_FLASH_SECTOR_9) && (Address >= ADDR_FLASH_SECTOR_8)) { sector = FLASH_Sector_8; } else if((Address < ADDR_FLASH_SECTOR_10) && (Address >= ADDR_FLASH_SECTOR_9)) { sector = FLASH_Sector_9; } else if((Address < ADDR_FLASH_SECTOR_11) && (Address >= ADDR_FLASH_SECTOR_10)) { sector = FLASH_Sector_10; } else/*(Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_11))*/ { sector = FLASH_Sector_11; } return sector; } /** * @brief ½«Êý¾ÝÉÕдµ½Ö¸¶¨µØÖ·µÄFlashÖÐ ¡£ * @param Address FlashÆðʼµØÖ·¡£ * @param Data Êý¾Ý´æ´¢ÇøÆðʼµØÖ·¡£ * @param DataNum Êý¾Ý×Ö½ÚÊý¡£ * @retval Êý¾ÝÉÕд״̬¡£ */ FLASH_Status CAN_BOOT_ProgramDatatoFlash(uint32_t StartAddr,uint8_t *pData,uint32_t DataNum) { FLASH_Status FLASHStatus=FLASH_COMPLETE; uint32_t *pDataTemp=(uint32_t *)pData; uint32_t i; if(StartAddr<APP_EXE_FLAG_START_ADDR){ return FLASH_ERROR_PGS; } /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); for(i=0;i<(DataNum>>2);i++) { FLASHStatus = FLASH_ProgramWord(StartAddr, *pDataTemp); if (FLASHStatus == FLASH_COMPLETE){ StartAddr += 4; pDataTemp++; }else{ return FLASHStatus; } } return FLASHStatus; } /** * @brief ²Á³öÖ¸¶¨ÉÈÇøÇø¼äµÄFlashÊý¾Ý ¡£ * @param StartPage ÆðʼÉÈÇøµØÖ· * @param EndPage ½áÊøÉÈÇøµØÖ· * @retval ÉÈÇø²Á³ö״̬ */ FLASH_Status CAN_BOOT_ErasePage(uint32_t StartAddr,uint32_t EndAddr) { uint32_t i; FLASH_Status FLASHStatus=FLASH_COMPLETE; uint32_t StartSector, EndSector; uint32_t SectorCounter=0; /* Get the number of the start and end sectors */ StartSector = GetSector(StartAddr); EndSector = GetSector(EndAddr); if(StartAddr<APP_EXE_FLAG_START_ADDR){ return FLASH_ERROR_PGS; } /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); for (SectorCounter = StartSector; SectorCounter <= EndSector; SectorCounter += 8) { /* Device voltage range supposed to be [2.7V to 3.6V], the operation will be done by word */ FLASHStatus = FLASH_EraseSector(SectorCounter, VoltageRange_3); if (FLASHStatus != FLASH_COMPLETE) { return FLASHStatus; } } return FLASHStatus; } /** * @brief »ñÈ¡½ÚµãµØÖ·ÐÅÏ¢ * @param None * @retval ½ÚµãµØÖ·¡£ */ uint16_t CAN_BOOT_GetAddrData(void) { return Read_CAN_Address(); } /** * @brief ¿ØÖƳÌÐòÌø×ªµ½Ö¸¶¨Î»ÖÿªÊ¼Ö´ÐÐ ¡£ * @param Addr ³ÌÐòÖ´ÐеØÖ·¡£ * @retval ³ÌÐòÌø×ª×´Ì¬¡£ */ void CAN_BOOT_JumpToApplication(uint32_t Addr) { static pFunction Jump_To_Application; __IO uint32_t JumpAddress; __set_PRIMASK(1);//¹Ø±ÕËùÓÐÖÐ¶Ï /* Test if user code is programmed starting from address "ApplicationAddress" */ if (((*(__IO uint32_t*)Addr) & 0x2FFE0000 ) == 0x20000000) { /* Jump to user application */ JumpAddress = *(__IO uint32_t*) (Addr + 4); Jump_To_Application = (pFunction) JumpAddress; /* Initialize user application's Stack Pointer */ __set_MSP(*(__IO uint32_t*)Addr); Jump_To_Application(); } } /** * @brief Ö´ÐÐÖ÷»úÏ·¢µÄÃüÁî * @param pRxMessage CAN×ÜÏßÏûÏ¢ * @retval ÎÞ */ void CAN_BOOT_ExecutiveCommand(CanRxMsg *pRxMessage) { CanTxMsg TxMessage; uint8_t ret,i; uint8_t can_cmd = (pRxMessage->ExtId)&CMD_MASK;//IDµÄbit0~bit3λΪÃüÁîÂë uint16_t can_addr = (pRxMessage->ExtId >> CMD_WIDTH);//IDµÄbit4~bit15λΪ½ÚµãµØÖ· uint32_t BaudRate; uint16_t crc_data; uint32_t addr_offset; uint32_t exe_type; uint32_t FlashSize; static uint32_t start_addr = APP_START_ADDR; static uint32_t data_size=0; static uint32_t data_index=0; __align(4) static uint8_t data_temp[1028]; //ÅжϽÓÊÕµÄÊý¾ÝµØÖ·ÊÇ·ñºÍ±¾½ÚµãµØÖ·Æ¥Å䣬Èô²»Æ¥ÅäÔòÖ±½Ó·µ»Ø£¬²»×öÈκÎÊÂÇé if((can_addr!=CAN_BOOT_GetAddrData())&&(can_addr!=0)){ return; } TxMessage.DLC = 0; TxMessage.ExtId = 0; TxMessage.IDE = CAN_Id_Extended; TxMessage.RTR = CAN_RTR_Data; //CMD_List.Erase£¬²Á³ýFlashÖеÄÊý¾Ý£¬ÐèÒª²Á³ýµÄFlash´óС´æ´¢ÔÚData[0]µ½Data[3]ÖÐ //¸ÃÃüÁî±ØÐëÔÚBootloader³ÌÐòÖÐʵÏÖ£¬ÔÚAPP³ÌÐòÖпÉÒÔ²»ÓÃʵÏÖ if(can_cmd == CMD_List.Erase){ __set_PRIMASK(1); FLASH_Unlock(); FlashSize = (pRxMessage->Data[0]<<24)|(pRxMessage->Data[1]<<16)|(pRxMessage->Data[2]<<8)|(pRxMessage->Data[3]<<0); ret = CAN_BOOT_ErasePage(APP_EXE_FLAG_START_ADDR,APP_START_ADDR+FlashSize); FLASH_Lock(); __set_PRIMASK(0); if(can_addr != 0x00){ if(ret==FLASH_COMPLETE){ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdSuccess; }else{ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdFaild; } TxMessage.DLC = 0; CAN_WriteData(&TxMessage); } start_addr = APP_START_ADDR; return; } //CMD_List.SetBaudRate£¬ÉèÖÃ½Úµã²¨ÌØÂÊ£¬¾ßÌå²¨ÌØÂÊÐÅÏ¢´æ´¢ÔÚData[0]µ½Data[3]ÖÐ //¸ü¸Ä²¨ÌØÂʺó£¬ÊÊÅäÆ÷Ò²ÐèÒª¸ü¸ÄΪÏàͬµÄ²¨ÌØÂÊ£¬·ñÔò²»ÄÜÕý³£Í¨ÐÅ if(can_cmd == CMD_List.SetBaudRate){ __set_PRIMASK(1); BaudRate = (pRxMessage->Data[0]<<24)|(pRxMessage->Data[1]<<16)|(pRxMessage->Data[2]<<8)|(pRxMessage->Data[3]<<0); __set_PRIMASK(0); CAN_Configuration(BaudRate); if(can_addr != 0x00){ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdSuccess; TxMessage.DLC = 0; delay_ms(20); CAN_WriteData(&TxMessage); } return; } //CMD_List.WriteInfo£¬ÉèÖÃдFlashÊý¾ÝµÄÏà¹ØÐÅÏ¢£¬±ÈÈçÊý¾ÝÆðʼµØÖ·£¬Êý¾Ý´óС //Êý¾ÝÆ«ÒÆµØÖ·´æ´¢ÔÚData[0]µ½Data[3]ÖУ¬Êý¾Ý´óС´æ´¢ÔÚData[4]µ½Data[7]ÖУ¬¸Ãº¯Êý±ØÐëÔÚBootloader³ÌÐòÖÐʵÏÖ£¬APP³ÌÐò¿ÉÒÔ²»ÓÃʵÏÖ if(can_cmd == CMD_List.WriteInfo){ __set_PRIMASK(1); addr_offset = (pRxMessage->Data[0]<<24)|(pRxMessage->Data[1]<<16)|(pRxMessage->Data[2]<<8)|(pRxMessage->Data[3]<<0); start_addr = APP_START_ADDR+addr_offset; data_size = (pRxMessage->Data[4]<<24)|(pRxMessage->Data[5]<<16)|(pRxMessage->Data[6]<<8)|(pRxMessage->Data[7]<<0); data_index = 0; __set_PRIMASK(0); if(can_addr != 0x00){ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdSuccess; TxMessage.DLC = 0; CAN_WriteData(&TxMessage); } } //CMD_List.Write£¬ÏȽ«Êý¾Ý´æ´¢ÔÚ±¾µØ»º³åÇøÖУ¬È»ºó¼ÆËãÊý¾ÝµÄCRC£¬ÈôУÑéÕýÈ·ÔòдÊý¾Ýµ½FlashÖÐ //ÿ´ÎÖ´ÐиÃÊý¾Ý£¬Êý¾Ý»º³åÇøµÄÊý¾Ý×Ö½ÚÊý»áÔö¼ÓpRxMessage->DLC×Ö½Ú£¬µ±Êý¾ÝÁ¿´ïµ½data_size£¨°üº¬2×Ö½ÚCRCУÑéÂ룩×Ö½Úºó //¶ÔÊý¾Ý½øÐÐCRCУÑ飬ÈôÊý¾ÝУÑéÎÞÎó£¬Ôò½«Êý¾ÝдÈëFlashÖÐ //¸Ãº¯ÊýÔÚBootloader³ÌÐòÖбØÐëʵÏÖ£¬APP³ÌÐò¿ÉÒÔ²»ÓÃʵÏÖ if(can_cmd == CMD_List.Write){ if((data_index<data_size)&&(data_index<1026)){ __set_PRIMASK(1); for(i=0;i<pRxMessage->DLC;i++){ data_temp[data_index++] = pRxMessage->Data[i]; } __set_PRIMASK(0); } if((data_index>=data_size)||(data_index>=1026)){ crc_data = crc16_ccitt(data_temp,data_size-2);//¶Ô½ÓÊÕµ½µÄÊý¾Ý×öCRCУÑ飬±£Ö¤Êý¾ÝÍêÕûÐÔ if(crc_data==((data_temp[data_size-2]<<8)|(data_temp[data_size-1]))){ __set_PRIMASK(1); FLASH_Unlock(); ret = CAN_BOOT_ProgramDatatoFlash(start_addr,data_temp,data_size-2); FLASH_Lock(); __set_PRIMASK(0); if(can_addr != 0x00){ if(ret==FLASH_COMPLETE){ crc_data = crc16_ccitt((const unsigned char*)(start_addr),data_size-2);//ÔٴζÔдÈëFlashÖеÄÊý¾Ý½øÐÐCRCУÑ飬ȷ±£Ð´ÈëFlashµÄÊý¾ÝÎÞÎó if(crc_data!=((data_temp[data_size-2]<<8)|(data_temp[data_size-1]))){ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdFaild; }else{ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdSuccess; } }else{ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdFaild; } TxMessage.DLC = 0; CAN_WriteData(&TxMessage); } }else{ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdFaild; TxMessage.DLC = 0; CAN_WriteData(&TxMessage); } } return; } //CMD_List.Check£¬½ÚµãÔÚÏß¼ì²â //½ÚµãÊÕµ½¸ÃÃüÁîºó·µ»Ø¹Ì¼þ°æ±¾ÐÅÏ¢ºÍ¹Ì¼þÀàÐÍ£¬¸ÃÃüÁîÔÚBootloader³ÌÐòºÍAPP³ÌÐò¶¼±ØÐëʵÏÖ if(can_cmd == CMD_List.Check){ if(can_addr != 0x00){ TxMessage.ExtId = (CAN_BOOT_GetAddrData()<<CMD_WIDTH)|CMD_List.CmdSuccess; TxMessage.Data[0] = 0;//Ö÷°æ±¾ºÅ£¬Á½×Ö½Ú TxMessage.Data[1] = 1; TxMessage.Data[2] = 0;//´Î°æ±¾ºÅ£¬Á½×Ö½Ú TxMessage.Data[3] = 0; TxMessage.Data[4] = (uint8_t)(FW_TYPE>>24); TxMessage.Data[5] = (uint8_t)(FW_TYPE>>16); TxMessage.Data[6] = (uint8_t)(FW_TYPE>>8); TxMessage.Data[7] = (uint8_t)(FW_TYPE>>0); TxMessage.DLC = 8; CAN_WriteData(&TxMessage); } return; } //CMD_List.Excute£¬¿ØÖƳÌÐòÌø×ªµ½Ö¸¶¨µØÖ·Ö´ÐÐ //¸ÃÃüÁîÔÚBootloaderºÍAPP³ÌÐòÖж¼±ØÐëʵÏÖ if(can_cmd == CMD_List.Excute){ exe_type = (pRxMessage->Data[0]<<24)|(pRxMessage->Data[1]<<16)|(pRxMessage->Data[2]<<8)|(pRxMessage->Data[3]<<0); if(exe_type == CAN_BL_APP){ if((*((uint32_t *)APP_START_ADDR)!=0xFFFFFFFF)){ CAN_BOOT_JumpToApplication(APP_START_ADDR); } } return; } } /*********************************END OF FILE**********************************/
gpl-3.0
ChristopheJacquet/PiFmRds
src/pi_fm_rds.c
1
19741
/* * PiFmRds - FM/RDS transmitter for the Raspberry Pi * Copyright (C) 2014, 2015 Christophe Jacquet, F8FTK * Copyright (C) 2012, 2015 Richard Hirst * Copyright (C) 2012 Oliver Mattos and Oskar Weigl * * See https://github.com/ChristopheJacquet/PiFmRds * * PI-FM-RDS: RaspberryPi FM transmitter, with RDS. * * This file contains the VHF FM modulator. All credit goes to the original * authors, Oliver Mattos and Oskar Weigl for the original idea, and to * Richard Hirst for using the Pi's DMA engine, which reduced CPU usage * dramatically. * * I (Christophe Jacquet) have adapted their idea to transmitting samples * at 228 kHz, allowing to build the 57 kHz subcarrier for RDS BPSK data. * * To make it work on the Raspberry Pi 2, I used a fix by Richard Hirst * (again) to request memory using Broadcom's mailbox interface. This fix * was published for ServoBlaster here: * https://www.raspberrypi.org/forums/viewtopic.php?p=699651#p699651 * * Never use this to transmit VHF-FM data through an antenna, as it is * illegal in most countries. This code is for testing purposes only. * Always connect a shielded transmission line from the RaspberryPi directly * to a radio receiver, so as *not* to emit radio waves. * * --------------------------------------------------------------------------- * These are the comments from Richard Hirst's version: * * RaspberryPi based FM transmitter. For the original idea, see: * * http://www.icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter * * All credit to Oliver Mattos and Oskar Weigl for creating the original code. * * I have taken their idea and reworked it to use the Pi DMA engine, so * reducing the CPU overhead for playing a .wav file from 100% to about 1.6%. * * I have implemented this in user space, using an idea I picked up from Joan * on the Raspberry Pi forums - credit to Joan for the DMA from user space * idea. * * The idea of feeding the PWM FIFO in order to pace DMA control blocks comes * from ServoBlaster, and I take credit for that :-) * * This code uses DMA channel 0 and the PWM hardware, with no regard for * whether something else might be trying to use it at the same time (such as * the 3.5mm jack audio driver). * * I know nothing much about sound, subsampling, or FM broadcasting, so it is * quite likely the sound quality produced by this code can be improved by * someone who knows what they are doing. There may be issues realting to * caching, as the user space process just writes to its virtual address space, * and expects the DMA controller to see the data; it seems to work for me * though. * * NOTE: THIS CODE MAY WELL CRASH YOUR PI, TRASH YOUR FILE SYSTEMS, AND * POTENTIALLY EVEN DAMAGE YOUR HARDWARE. THIS IS BECAUSE IT STARTS UP THE DMA * CONTROLLER USING MEMORY OWNED BY A USER PROCESS. IF THAT USER PROCESS EXITS * WITHOUT STOPPING THE DMA CONTROLLER, ALL HELL COULD BREAK LOOSE AS THE * MEMORY GETS REALLOCATED TO OTHER PROCESSES WHILE THE DMA CONTROLLER IS STILL * USING IT. I HAVE ATTEMPTED TO MINIMISE ANY RISK BY CATCHING SIGNALS AND * RESETTING THE DMA CONTROLLER BEFORE EXITING, BUT YOU HAVE BEEN WARNED. I * ACCEPT NO LIABILITY OR RESPONSIBILITY FOR ANYTHING THAT HAPPENS AS A RESULT * OF YOU RUNNING THIS CODE. IF IT BREAKS, YOU GET TO KEEP ALL THE PIECES. * * NOTE ALSO: THIS MAY BE ILLEGAL IN YOUR COUNTRY. HERE ARE SOME COMMENTS * FROM MORE KNOWLEDGEABLE PEOPLE ON THE FORUM: * * "Just be aware that in some countries FM broadcast and especially long * distance FM broadcast could get yourself into trouble with the law, stray FM * broadcasts over Airband aviation is also strictly forbidden." * * "A low pass filter is really really required for this as it has strong * harmonics at the 3rd, 5th 7th and 9th which sit in licensed and rather * essential bands, ie GSM, HAM, emergency services and others. Polluting these * frequencies is immoral and dangerous, whereas "breaking in" on FM bands is * just plain illegal." * * "Don't get caught, this GPIO use has the potential to exceed the legal * limits by about 2000% with a proper aerial." * * * As for the original code, this code is released under the GPL. * * Richard Hirst <richardghirst@gmail.com> December 2012 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <stdarg.h> #include <stdint.h> #include <math.h> #include <time.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <sndfile.h> #include "rds.h" #include "fm_mpx.h" #include "control_pipe.h" #include "mailbox.h" #define MBFILE DEVICE_FILE_NAME /* From mailbox.h */ #if (RASPI)==1 #define PERIPH_VIRT_BASE 0x20000000 #define PERIPH_PHYS_BASE 0x7e000000 #define DRAM_PHYS_BASE 0x40000000 #define MEM_FLAG 0x0c #define PLLFREQ 500000000. #elif (RASPI)==2 #define PERIPH_VIRT_BASE 0x3f000000 #define PERIPH_PHYS_BASE 0x7e000000 #define DRAM_PHYS_BASE 0xc0000000 #define MEM_FLAG 0x04 #define PLLFREQ 500000000. #elif (RASPI)==4 #define PERIPH_VIRT_BASE 0xfe000000 #define PERIPH_PHYS_BASE 0x7e000000 #define DRAM_PHYS_BASE 0xc0000000 #define MEM_FLAG 0x04 #define PLLFREQ 750000000. #else #error Unknown Raspberry Pi version (variable RASPI) #endif #define NUM_SAMPLES 50000 #define NUM_CBS (NUM_SAMPLES * 2) #define BCM2708_DMA_NO_WIDE_BURSTS (1<<26) #define BCM2708_DMA_WAIT_RESP (1<<3) #define BCM2708_DMA_D_DREQ (1<<6) #define BCM2708_DMA_PER_MAP(x) ((x)<<16) #define BCM2708_DMA_END (1<<1) #define BCM2708_DMA_RESET (1<<31) #define BCM2708_DMA_INT (1<<2) #define DMA_CS (0x00/4) #define DMA_CONBLK_AD (0x04/4) #define DMA_DEBUG (0x20/4) #define DMA_BASE_OFFSET 0x00007000 #define DMA_LEN 0x24 #define PWM_BASE_OFFSET 0x0020C000 #define PWM_LEN 0x28 #define CLK_BASE_OFFSET 0x00101000 #define CLK_LEN 0xA8 #define GPIO_BASE_OFFSET 0x00200000 #define GPIO_LEN 0x100 #define DMA_VIRT_BASE (PERIPH_VIRT_BASE + DMA_BASE_OFFSET) #define PWM_VIRT_BASE (PERIPH_VIRT_BASE + PWM_BASE_OFFSET) #define CLK_VIRT_BASE (PERIPH_VIRT_BASE + CLK_BASE_OFFSET) #define GPIO_VIRT_BASE (PERIPH_VIRT_BASE + GPIO_BASE_OFFSET) #define PCM_VIRT_BASE (PERIPH_VIRT_BASE + PCM_BASE_OFFSET) #define PWM_PHYS_BASE (PERIPH_PHYS_BASE + PWM_BASE_OFFSET) #define PCM_PHYS_BASE (PERIPH_PHYS_BASE + PCM_BASE_OFFSET) #define GPIO_PHYS_BASE (PERIPH_PHYS_BASE + GPIO_BASE_OFFSET) #define PWM_CTL (0x00/4) #define PWM_DMAC (0x08/4) #define PWM_RNG1 (0x10/4) #define PWM_FIFO (0x18/4) #define PWMCLK_CNTL 40 #define PWMCLK_DIV 41 #define CM_GP0DIV (0x7e101074) #define GPCLK_CNTL (0x70/4) #define GPCLK_DIV (0x74/4) #define PWMCTL_MODE1 (1<<1) #define PWMCTL_PWEN1 (1<<0) #define PWMCTL_CLRF (1<<6) #define PWMCTL_USEF1 (1<<5) #define PWMDMAC_ENAB (1<<31) // I think this means it requests as soon as there is one free slot in the FIFO // which is what we want as burst DMA would mess up our timing. #define PWMDMAC_THRSHLD ((15<<8)|(15<<0)) #define GPFSEL0 (0x00/4) // The deviation specifies how wide the signal is. Use 25.0 for WBFM // (broadcast radio) and about 3.5 for NBFM (walkie-talkie style radio) #define DEVIATION 25.0 typedef struct { uint32_t info, src, dst, length, stride, next, pad[2]; } dma_cb_t; #define BUS_TO_PHYS(x) ((x)&~0xC0000000) static struct { int handle; /* From mbox_open() */ unsigned mem_ref; /* From mem_alloc() */ unsigned bus_addr; /* From mem_lock() */ uint8_t *virt_addr; /* From mapmem() */ } mbox; static volatile uint32_t *pwm_reg; static volatile uint32_t *clk_reg; static volatile uint32_t *dma_reg; static volatile uint32_t *gpio_reg; struct control_data_s { dma_cb_t cb[NUM_CBS]; uint32_t sample[NUM_SAMPLES]; }; #define PAGE_SIZE 4096 #define PAGE_SHIFT 12 #define NUM_PAGES ((sizeof(struct control_data_s) + PAGE_SIZE - 1) >> PAGE_SHIFT) static struct control_data_s *ctl; static void udelay(int us) { struct timespec ts = { 0, us * 1000 }; nanosleep(&ts, NULL); } static void terminate(int num) { // Stop outputting and generating the clock. if (clk_reg && gpio_reg && mbox.virt_addr) { // Set GPIO4 to be an output (instead of ALT FUNC 0, which is the clock). gpio_reg[GPFSEL0] = (gpio_reg[GPFSEL0] & ~(7 << 12)) | (1 << 12); // Disable the clock generator. clk_reg[GPCLK_CNTL] = 0x5A; } if (dma_reg && mbox.virt_addr) { dma_reg[DMA_CS] = BCM2708_DMA_RESET; udelay(10); } fm_mpx_close(); close_control_pipe(); if (mbox.virt_addr != NULL) { unmapmem(mbox.virt_addr, NUM_PAGES * 4096); mem_unlock(mbox.handle, mbox.mem_ref); mem_free(mbox.handle, mbox.mem_ref); } printf("Terminating: cleanly deactivated the DMA engine and killed the carrier.\n"); exit(num); } static void fatal(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); terminate(0); } static uint32_t mem_virt_to_phys(void *virt) { uint32_t offset = (uint8_t *)virt - mbox.virt_addr; return mbox.bus_addr + offset; } static uint32_t mem_phys_to_virt(uint32_t phys) { return phys - (uint32_t)mbox.bus_addr + (uint32_t)mbox.virt_addr; } static void * map_peripheral(uint32_t base, uint32_t len) { int fd = open("/dev/mem", O_RDWR | O_SYNC); void * vaddr; if (fd < 0) fatal("Failed to open /dev/mem: %m.\n"); vaddr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, base); if (vaddr == MAP_FAILED) fatal("Failed to map peripheral at 0x%08x: %m.\n", base); close(fd); return vaddr; } #define SUBSIZE 1 #define DATA_SIZE 5000 int tx(uint32_t carrier_freq, char *audio_file, uint16_t pi, char *ps, char *rt, float ppm, char *control_pipe) { // Catch all signals possible - it is vital we kill the DMA engine // on process exit! for (int i = 0; i < 64; i++) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = terminate; sigaction(i, &sa, NULL); } dma_reg = map_peripheral(DMA_VIRT_BASE, DMA_LEN); pwm_reg = map_peripheral(PWM_VIRT_BASE, PWM_LEN); clk_reg = map_peripheral(CLK_VIRT_BASE, CLK_LEN); gpio_reg = map_peripheral(GPIO_VIRT_BASE, GPIO_LEN); // Use the mailbox interface to the VC to ask for physical memory. mbox.handle = mbox_open(); if (mbox.handle < 0) fatal("Failed to open mailbox. Check kernel support for vcio / BCM2708 mailbox.\n"); printf("Allocating physical memory: size = %d ", NUM_PAGES * 4096); if(! (mbox.mem_ref = mem_alloc(mbox.handle, NUM_PAGES * 4096, 4096, MEM_FLAG))) { fatal("Could not allocate memory.\n"); } // TODO: How do we know that succeeded? printf("mem_ref = %u ", mbox.mem_ref); if(! (mbox.bus_addr = mem_lock(mbox.handle, mbox.mem_ref))) { fatal("Could not lock memory.\n"); } printf("bus_addr = %x ", mbox.bus_addr); if(! (mbox.virt_addr = mapmem(BUS_TO_PHYS(mbox.bus_addr), NUM_PAGES * 4096))) { fatal("Could not map memory.\n"); } printf("virt_addr = %p\n", mbox.virt_addr); // GPIO4 needs to be ALT FUNC 0 to output the clock gpio_reg[GPFSEL0] = (gpio_reg[GPFSEL0] & ~(7 << 12)) | (4 << 12); // Program GPCLK to use MASH setting 1, so fractional dividers work clk_reg[GPCLK_CNTL] = 0x5A << 24 | 6; udelay(100); clk_reg[GPCLK_CNTL] = 0x5A << 24 | 1 << 9 | 1 << 4 | 6; ctl = (struct control_data_s *) mbox.virt_addr; dma_cb_t *cbp = ctl->cb; uint32_t phys_sample_dst = CM_GP0DIV; uint32_t phys_pwm_fifo_addr = PWM_PHYS_BASE + 0x18; // Calculate the frequency control word // The fractional part is stored in the lower 12 bits uint32_t freq_ctl = ((float)(PLLFREQ / carrier_freq)) * ( 1 << 12 ); for (int i = 0; i < NUM_SAMPLES; i++) { ctl->sample[i] = 0x5a << 24 | freq_ctl; // Silence // Write a frequency sample cbp->info = BCM2708_DMA_NO_WIDE_BURSTS | BCM2708_DMA_WAIT_RESP; cbp->src = mem_virt_to_phys(ctl->sample + i); cbp->dst = phys_sample_dst; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; // Delay cbp->info = BCM2708_DMA_NO_WIDE_BURSTS | BCM2708_DMA_WAIT_RESP | BCM2708_DMA_D_DREQ | BCM2708_DMA_PER_MAP(5); cbp->src = mem_virt_to_phys(mbox.virt_addr); cbp->dst = phys_pwm_fifo_addr; cbp->length = 4; cbp->stride = 0; cbp->next = mem_virt_to_phys(cbp + 1); cbp++; } cbp--; cbp->next = mem_virt_to_phys(mbox.virt_addr); // Here we define the rate at which we want to update the GPCLK control // register. // // Set the range to 2 bits. PLLD is at 500 MHz, therefore to get 228 kHz // we need a divisor of 500000000 / 2000 / 228 = 1096.491228 // // This is 1096 + 2012*2^-12 theoretically // // However the fractional part may have to be adjusted to take the actual // frequency of your Pi's oscillator into account. For example on my Pi, // the fractional part should be 1916 instead of 2012 to get exactly // 228 kHz. However RDS decoding is still okay even at 2012. // // So we use the 'ppm' parameter to compensate for the oscillator error float divider = (PLLFREQ/(2000*228*(1.+ppm/1.e6))); uint32_t idivider = (uint32_t) divider; uint32_t fdivider = (uint32_t) ((divider - idivider)*pow(2, 12)); printf("ppm corr is %.4f, divider is %.4f (%d + %d*2^-12) [nominal 1096.4912].\n", ppm, divider, idivider, fdivider); pwm_reg[PWM_CTL] = 0; udelay(10); clk_reg[PWMCLK_CNTL] = 0x5A000006; // Source=PLLD and disable udelay(100); // theorically : 1096 + 2012*2^-12 clk_reg[PWMCLK_DIV] = 0x5A000000 | (idivider<<12) | fdivider; udelay(100); clk_reg[PWMCLK_CNTL] = 0x5A000216; // Source=PLLD and enable + MASH filter 1 udelay(100); pwm_reg[PWM_RNG1] = 2; udelay(10); pwm_reg[PWM_DMAC] = PWMDMAC_ENAB | PWMDMAC_THRSHLD; udelay(10); pwm_reg[PWM_CTL] = PWMCTL_CLRF; udelay(10); pwm_reg[PWM_CTL] = PWMCTL_USEF1 | PWMCTL_PWEN1; udelay(10); // Initialise the DMA dma_reg[DMA_CS] = BCM2708_DMA_RESET; udelay(10); dma_reg[DMA_CS] = BCM2708_DMA_INT | BCM2708_DMA_END; dma_reg[DMA_CONBLK_AD] = mem_virt_to_phys(ctl->cb); dma_reg[DMA_DEBUG] = 7; // clear debug error flags dma_reg[DMA_CS] = 0x10880001; // go, mid priority, wait for outstanding writes uint32_t last_cb = (uint32_t)ctl->cb; // Data structures for baseband data float data[DATA_SIZE]; int data_len = 0; int data_index = 0; // Initialize the baseband generator if(fm_mpx_open(audio_file, DATA_SIZE) < 0) return 1; // Initialize the RDS modulator char myps[9] = {0}; set_rds_pi(pi); set_rds_rt(rt); uint16_t count = 0; uint16_t count2 = 0; int varying_ps = 0; if(ps) { set_rds_ps(ps); printf("PI: %04X, PS: \"%s\".\n", pi, ps); } else { printf("PI: %04X, PS: <Varying>.\n", pi); varying_ps = 1; } printf("RT: \"%s\"\n", rt); // Initialize the control pipe reader if(control_pipe) { if(open_control_pipe(control_pipe) == 0) { printf("Reading control commands on %s.\n", control_pipe); } else { printf("Failed to open control pipe: %s.\n", control_pipe); control_pipe = NULL; } } printf("Starting to transmit on %3.1f MHz.\n", carrier_freq/1e6); for (;;) { // Default (varying) PS if(varying_ps) { if(count == 512) { snprintf(myps, 9, "%08d", count2); set_rds_ps(myps); count2++; } if(count == 1024) { set_rds_ps("RPi-Live"); count = 0; } count++; } if(control_pipe && poll_control_pipe() == CONTROL_PIPE_PS_SET) { varying_ps = 0; } usleep(5000); uint32_t cur_cb = mem_phys_to_virt(dma_reg[DMA_CONBLK_AD]); int last_sample = (last_cb - (uint32_t)mbox.virt_addr) / (sizeof(dma_cb_t) * 2); int this_sample = (cur_cb - (uint32_t)mbox.virt_addr) / (sizeof(dma_cb_t) * 2); int free_slots = this_sample - last_sample; if (free_slots < 0) free_slots += NUM_SAMPLES; while (free_slots >= SUBSIZE) { // get more baseband samples if necessary if(data_len == 0) { if( fm_mpx_get_samples(data) < 0 ) { terminate(0); } data_len = DATA_SIZE; data_index = 0; } float dval = data[data_index] * (DEVIATION / 10.); data_index++; data_len--; int intval = (int)((floor)(dval)); //int frac = (int)((dval - (float)intval) * SUBSIZE); ctl->sample[last_sample++] = (0x5A << 24 | freq_ctl) + intval; //(frac > j ? intval + 1 : intval); if (last_sample == NUM_SAMPLES) last_sample = 0; free_slots -= SUBSIZE; } last_cb = (uint32_t)mbox.virt_addr + last_sample * sizeof(dma_cb_t) * 2; } return 0; } int main(int argc, char **argv) { char *audio_file = NULL; char *control_pipe = NULL; uint32_t carrier_freq = 107900000; char *ps = NULL; char *rt = "PiFmRds: live FM-RDS transmission from the RaspberryPi"; uint16_t pi = 0x1234; float ppm = 0; // Parse command-line arguments for(int i=1; i<argc; i++) { char *arg = argv[i]; char *param = NULL; if(arg[0] == '-' && i+1 < argc) param = argv[i+1]; if((strcmp("-wav", arg)==0 || strcmp("-audio", arg)==0) && param != NULL) { i++; audio_file = param; } else if(strcmp("-freq", arg)==0 && param != NULL) { i++; carrier_freq = 1e6 * atof(param); if(carrier_freq < 76e6 || carrier_freq > 108e6) fatal("Incorrect frequency specification. Must be in megahertz, of the form 107.9, between 76 and 108.\n"); } else if(strcmp("-pi", arg)==0 && param != NULL) { i++; pi = (uint16_t) strtol(param, NULL, 16); } else if(strcmp("-ps", arg)==0 && param != NULL) { i++; ps = param; } else if(strcmp("-rt", arg)==0 && param != NULL) { i++; rt = param; } else if(strcmp("-ppm", arg)==0 && param != NULL) { i++; ppm = atof(param); } else if(strcmp("-ctl", arg)==0 && param != NULL) { i++; control_pipe = param; } else { fatal("Unrecognised argument: %s.\n" "Syntax: pi_fm_rds [-freq freq] [-audio file] [-ppm ppm_error] [-pi pi_code]\n" " [-ps ps_text] [-rt rt_text] [-ctl control_pipe]\n", arg); } } int errcode = tx(carrier_freq, audio_file, pi, ps, rt, ppm, control_pipe); terminate(errcode); }
gpl-3.0
mywave/WAM
src/print/read_spectra_file.f90
1
10677
SUBROUTINE READ_SPECTRA_FILE (IUNIT, IEOF) ! ---------------------------------------------------------------------------- ! ! ! ! READ_SPECTRA_FILE - READS A SPECTRUM FROM WAVE MODEL OUTPUT FILE ! ! ! ! M. DE LAS HERAS KNMI/PCM FEBRUARY 1990 ! ! H. GUNTHER HZG DECEMBER 2010 RE-ORGANISED ! ! ! ! ! ! PURPOSE. ! ! -------- ! ! ! ! POST PROCESSING ROUTINE FOR WAVE MODEL. ! ! READ SPECTRA FROM WAMODEL OUTPUT FILE ! ! ! ! METHOD. ! ! ------- ! ! ! ! UNFORMATTED READ. ! ! ! ! REFERENCE. ! ! ---------- ! ! ! ! NONE. ! ! ! ! ---------------------------------------------------------------------------- ! ! ! ! EXTERNALS. ! ! ---------- ! USE WAM_GENERAL_MODULE, ONLY: & & ABORT1 !! TERMINATES PROCESSING. ! ---------------------------------------------------------------------------- ! ! ! ! MODULE VARIABLES. ! ! ----------------- ! USE WAM_FILE_MODULE, ONLY: IU06 USE WAM_PRINT_MODULE, ONLY: KL, ML, CO, FR, THETA, & & SPEC_LAT, SPEC_LON, SPEC_DATE, & & NOUT_S, PFLAG_S, & & SPEC, U10, UDIR, US, DEPTH, CSPEED, CDIR, & & HS, PPER, MPER, TM1, TM2, MDIR, SPRE, TAUW, & & SPEC_SEA, & & HS_SEA, PPER_SEA, MPER_SEA, TM1_SEA, TM2_SEA, & & MDIR_SEA, SPRE_SEA, & & SPEC_SWELL, & & HS_SWELL, PPER_SWELL, MPER_SWELL, TM1_SWELL, & & TM2_SWELL, MDIR_SWELL, SPRE_SWELL IMPLICIT NONE ! ---------------------------------------------------------------------------- ! ! ! ! INTERFACE VARIABLES. ! ! -------------------- ! INTEGER, INTENT(IN) :: IUNIT !! INPUT UNIT. LOGICAL, INTENT(OUT) :: IEOF !! .TRUE. IF END OF FILE ENCOUNTED. ! ---------------------------------------------------------------------------- ! ! ! ! LOCAL VARIABLES. ! ! ---------------- ! INTEGER :: I, IOS REAL :: XANG, XFRE, TH1, FR1 REAL, PARAMETER :: RAD = 3.1415927/180. ! ---------------------------------------------------------------------------- ! ! ! ! 1. DATA HEADER FROM WAVE MODEL SPECTRA OUTPUT. ! ! ------------------------------------------- ! IEOF = .FALSE. READ (IUNIT,IOSTAT=IOS) SPEC_LON, SPEC_LAT, SPEC_DATE, XANG, XFRE, TH1, FR1, CO IF (IOS.LT.0) THEN IEOF = .TRUE. RETURN ELSE IF (IOS.GT.0) THEN WRITE(IU06,*) '***********************************************' WRITE(IU06,*) '* *' WRITE(IU06,*) '* FATAL ERROR IN SUB. READ_SPECTRA_FILE *' WRITE(IU06,*) '* ===================================== *' WRITE(IU06,*) '* *' WRITE(IU06,*) '* READ ERROR IN FIRST HEADER RECORD *' WRITE(IU06,*) '* FROM WAM SPECTRA OUTPUT FILE. *' WRITE(IU06,*) '* IOSTAT = ', IOS WRITE(IU06,*) '* *' WRITE(IU06,*) '* PROGRAM ABORTS. PROGRAM ABORTS. *' WRITE(IU06,*) '***********************************************' CALL ABORT1 END IF READ (IUNIT, IOSTAT=IOS) PFLAG_S(1:NOUT_S) IF (IOS.NE.0) THEN WRITE(IU06,*) '***********************************************' WRITE(IU06,*) '* *' WRITE(IU06,*) '* FATAL ERROR IN SUB. READ_SPECTRA_FILE *' WRITE(IU06,*) '* ===================================== *' WRITE(IU06,*) '* *' WRITE(IU06,*) '* READ ERROR IN SECOND HEADER RECDRD *' WRITE(IU06,*) '* FROM WAM SPECTRA OUTPUT FILE. *' WRITE(IU06,*) '* IOSTAT = ', IOS WRITE(IU06,*) '* *' WRITE(IU06,*) '* PROGRAM ABORTS. PROGRAM ABORTS. *' WRITE(IU06,*) '***********************************************' CALL ABORT1 END IF KL = NINT(XANG) ML = NINT(XFRE) READ (IUNIT, IOSTAT=IOS) U10, UDIR, US, DEPTH, CSPEED, CDIR IF (IOS.NE.0) THEN WRITE(IU06,*) '***********************************************' WRITE(IU06,*) '* *' WRITE(IU06,*) '* FATAL ERROR IN SUB. READ_SPECTRA_FILE *' WRITE(IU06,*) '* ===================================== *' WRITE(IU06,*) '* *' WRITE(IU06,*) '* READ ERROR IN THIRD HEADER RECDRD *' WRITE(IU06,*) '* FROM WAM SPECTRA OUTPUT FILE. *' WRITE(IU06,*) '* IOSTAT = ', IOS WRITE(IU06,*) '* *' WRITE(IU06,*) '* PROGRAM ABORTS. PROGRAM ABORTS. *' WRITE(IU06,*) '***********************************************' CALL ABORT1 END IF ! ---------------------------------------------------------------------------- ! ! ! ! 2. CHECK ARRAYS. ! ! ------------- ! IF (KL.LE.0 .OR. ML.LE.0) THEN WRITE(IU06,*) '***********************************************' WRITE(IU06,*) '* *' WRITE(IU06,*) '* FATAL ERROR IN SUB. READ_SPECTRA_FILE *' WRITE(IU06,*) '* ===================================== *' WRITE(IU06,*) '* *' WRITE(IU06,*) '* NUMBER OF FREQUENCIES AND/OR DIRECTIONS *' WRITE(IU06,*) '* IS NOT POSITIVE. *' WRITE(IU06,*) '* CHECK USER INPUT FOR FILE NAME *' WRITE(IU06,*) '* *' WRITE(IU06,*) '* PROGRAM ABORTS. PROGRAM ABORTS. *' WRITE(IU06,*) '***********************************************' CALL ABORT1 END IF IF (.NOT.ALLOCATED(FR) ) THEN ALLOCATE (FR(1:ML)) FR(1) = FR1 !! COMPUTE FREQUENCIES. DO I=2,ML FR(I) = CO*FR(I-1) END DO END IF IF (.NOT.ALLOCATED(THETA)) THEN ALLOCATE (THETA(1:KL)) !! COMPUTE DIRECTIONS. DO I = 1, KL THETA(I) = (TH1 + REAL(I-1)*360./XANG)*RAD END DO END IF IF (PFLAG_S(1).AND..NOT.ALLOCATED(SPEC) ) ALLOCATE (SPEC(1:KL,1:ML)) IF (PFLAG_S(2).AND..NOT.ALLOCATED(SPEC_SEA) ) ALLOCATE (SPEC_SEA(1:KL,1:ML)) IF (PFLAG_S(3).AND..NOT.ALLOCATED(SPEC_SWELL)) ALLOCATE (SPEC_SWELL(1:KL,1:ML)) ! ---------------------------------------------------------------------------- ! ! ! ! 3. SPECTRA FROM WAVE MODEL SPECTRA OUTPUT. ! ! --------------------------------------- ! IF (PFLAG_S(1)) THEN READ(IUNIT, IOSTAT=IOS) HS, PPER, MPER, TM1, TM2, MDIR, SPRE READ(IUNIT, IOSTAT=IOS) SPEC END IF IF (PFLAG_S(2)) THEN READ(IUNIT, IOSTAT=IOS) HS_SEA, PPER_SEA, MPER_SEA, TM1_SEA, TM2_SEA, & & MDIR_SEA, SPRE_SEA READ(IUNIT, IOSTAT=IOS) SPEC_SEA END IF IF (PFLAG_S(3)) THEN READ(IUNIT, IOSTAT=IOS) HS_SWELL, PPER_SWELL, MPER_SWELL, TM1_SWELL, & & TM2_SWELL, MDIR_SWELL, SPRE_SWELL READ(IUNIT, IOSTAT=IOS) SPEC_SWELL END IF IF (IOS.NE.0) THEN WRITE(IU06,*) '***********************************************' WRITE(IU06,*) '* *' WRITE(IU06,*) '* FATAL ERROR IN SUB. READ_SPECTRA_FILE *' WRITE(IU06,*) '* ===================================== *' WRITE(IU06,*) '* *' WRITE(IU06,*) '* READ ERROR IN SPECTRA DATA RECDRD *' WRITE(IU06,*) '* FROM WAM SPECTRA OUTPUT FILE. *' WRITE(IU06,*) '* IOSTAT = ', IOS WRITE(IU06,*) '* *' WRITE(IU06,*) '* PROGRAM ABORTS. PROGRAM ABORTS. *' WRITE(IU06,*) '***********************************************' CALL ABORT1 END IF END SUBROUTINE READ_SPECTRA_FILE
gpl-3.0
barnex/gsl
internal/matrix_view.c
1
3860
#include "config.h" #include "gsl_gsl_errno.h" #include "gsl_gsl_matrix.h" #include "matrix_view.h" #define BASE_GSL_COMPLEX_LONG #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_GSL_COMPLEX_LONG #define BASE_GSL_COMPLEX #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_GSL_COMPLEX #define BASE_GSL_COMPLEX_FLOAT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_GSL_COMPLEX_FLOAT #define BASE_LONG_DOUBLE #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_LONG_DOUBLE #define BASE_DOUBLE #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_FLOAT #define BASE_ULONG #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_ULONG #define BASE_LONG #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_LONG #define BASE_UINT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_UINT #define BASE_INT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_INT #define BASE_USHORT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_USHORT #define BASE_SHORT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_SHORT #define BASE_UCHAR #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_UCHAR #define BASE_CHAR #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_CHAR #define USE_QUALIFIER #define QUALIFIER const #define BASE_GSL_COMPLEX_LONG #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_GSL_COMPLEX_LONG #define BASE_GSL_COMPLEX #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_GSL_COMPLEX #define BASE_GSL_COMPLEX_FLOAT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_GSL_COMPLEX_FLOAT #define BASE_LONG_DOUBLE #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_LONG_DOUBLE #define BASE_DOUBLE #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_FLOAT #define BASE_ULONG #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_ULONG #define BASE_LONG #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_LONG #define BASE_UINT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_UINT #define BASE_INT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_INT #define BASE_USHORT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_USHORT #define BASE_SHORT #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_SHORT #define BASE_UCHAR #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_UCHAR #define BASE_CHAR #include "templates_on.h" #include "matrix_view_source.c.inc" #include "templates_off.h" #undef BASE_CHAR
gpl-3.0
qaisjp/mtasa-blue
vendor/curl/lib/easy.c
1
33301
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /* * See comment in curl_memory.h for the explanation of this sanity check. */ #ifdef CURLX_NO_MEMORY_CALLBACKS #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined" #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "vtls/vtls.h" #include "url.h" #include "getinfo.h" #include "hostip.h" #include "share.h" #include "strdup.h" #include "progress.h" #include "easyif.h" #include "multiif.h" #include "select.h" #include "sendf.h" /* for failf function prototype */ #include "connect.h" /* for Curl_getconnectinfo */ #include "slist.h" #include "mime.h" #include "amigaos.h" #include "non-ascii.h" #include "warnless.h" #include "multiif.h" #include "sigpipe.h" #include "vssh/ssh.h" #include "setopt.h" #include "http_digest.h" #include "system_win32.h" #include "http2.h" #include "dynbuf.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* true globals -- for curl_global_init() and curl_global_cleanup() */ static unsigned int initialized; static long init_flags; /* * strdup (and other memory functions) is redefined in complicated * ways, but at this point it must be defined as the system-supplied strdup * so the callback pointer is initialized correctly. */ #if defined(_WIN32_WCE) #define system_strdup _strdup #elif !defined(HAVE_STRDUP) #define system_strdup curlx_strdup #else #define system_strdup strdup #endif #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__) # pragma warning(disable:4232) /* MSVC extension, dllimport identity */ #endif #ifndef __SYMBIAN32__ /* * If a memory-using function (like curl_getenv) is used before * curl_global_init() is called, we need to have these pointers set already. */ curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc; curl_free_callback Curl_cfree = (curl_free_callback)free; curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc; curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup; curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif #else /* * Symbian OS doesn't support initialization to code in writable static data. * Initialization will occur in the curl_global_init() call. */ curl_malloc_callback Curl_cmalloc; curl_free_callback Curl_cfree; curl_realloc_callback Curl_crealloc; curl_strdup_callback Curl_cstrdup; curl_calloc_callback Curl_ccalloc; #endif #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__) # pragma warning(default:4232) /* MSVC extension, dllimport identity */ #endif /** * curl_global_init() globally initializes curl given a bitwise set of the * different features of what to initialize. */ static CURLcode global_init(long flags, bool memoryfuncs) { if(initialized++) return CURLE_OK; if(memoryfuncs) { /* Setup the default memory functions here (again) */ Curl_cmalloc = (curl_malloc_callback)malloc; Curl_cfree = (curl_free_callback)free; Curl_crealloc = (curl_realloc_callback)realloc; Curl_cstrdup = (curl_strdup_callback)system_strdup; Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif } if(!Curl_ssl_init()) { DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n")); goto fail; } #ifdef WIN32 if(Curl_win32_init(flags)) { DEBUGF(fprintf(stderr, "Error: win32_init failed\n")); goto fail; } #endif #ifdef __AMIGA__ if(!Curl_amiga_init()) { DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n")); goto fail; } #endif #ifdef NETWARE if(netware_init()) { DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n")); } #endif if(Curl_resolver_global_init()) { DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n")); goto fail; } #if defined(USE_SSH) if(Curl_ssh_init()) { goto fail; } #endif #ifdef USE_WOLFSSH if(WS_SUCCESS != wolfSSH_Init()) { DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n")); return CURLE_FAILED_INIT; } #endif init_flags = flags; return CURLE_OK; fail: initialized--; /* undo the increase */ return CURLE_FAILED_INIT; } /** * curl_global_init() globally initializes curl given a bitwise set of the * different features of what to initialize. */ CURLcode curl_global_init(long flags) { return global_init(flags, TRUE); } /* * curl_global_init_mem() globally initializes curl and also registers the * user provided callback routines. */ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c) { /* Invalid input, return immediately */ if(!m || !f || !r || !s || !c) return CURLE_FAILED_INIT; if(initialized) { /* Already initialized, don't do it again, but bump the variable anyway to work like curl_global_init() and require the same amount of cleanup calls. */ initialized++; return CURLE_OK; } /* set memory functions before global_init() in case it wants memory functions */ Curl_cmalloc = m; Curl_cfree = f; Curl_cstrdup = s; Curl_crealloc = r; Curl_ccalloc = c; /* Call the actual init function, but without setting */ return global_init(flags, FALSE); } /** * curl_global_cleanup() globally cleanups curl, uses the value of * "init_flags" to determine what needs to be cleaned up and what doesn't. */ void curl_global_cleanup(void) { if(!initialized) return; if(--initialized) return; Curl_ssl_cleanup(); Curl_resolver_global_cleanup(); #ifdef WIN32 Curl_win32_cleanup(init_flags); #endif Curl_amiga_cleanup(); Curl_ssh_cleanup(); #ifdef USE_WOLFSSH (void)wolfSSH_Cleanup(); #endif init_flags = 0; } /* * curl_easy_init() is the external interface to alloc, setup and init an * easy handle that is returned. If anything goes wrong, NULL is returned. */ struct Curl_easy *curl_easy_init(void) { CURLcode result; struct Curl_easy *data; /* Make sure we inited the global SSL stuff */ if(!initialized) { result = curl_global_init(CURL_GLOBAL_DEFAULT); if(result) { /* something in the global init failed, return nothing */ DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n")); return NULL; } } /* We use curl_open() with undefined URL so far */ result = Curl_open(&data); if(result) { DEBUGF(fprintf(stderr, "Error: Curl_open failed\n")); return NULL; } return data; } #ifdef CURLDEBUG struct socketmonitor { struct socketmonitor *next; /* the next node in the list or NULL */ struct pollfd socket; /* socket info of what to monitor */ }; struct events { long ms; /* timeout, run the timeout function when reached */ bool msbump; /* set TRUE when timeout is set by callback */ int num_sockets; /* number of nodes in the monitor list */ struct socketmonitor *list; /* list of sockets to monitor */ int running_handles; /* store the returned number */ }; /* events_timer * * Callback that gets called with a new value when the timeout should be * updated. */ static int events_timer(struct Curl_multi *multi, /* multi handle */ long timeout_ms, /* see above */ void *userp) /* private callback pointer */ { struct events *ev = userp; (void)multi; if(timeout_ms == -1) /* timeout removed */ timeout_ms = 0; else if(timeout_ms == 0) /* timeout is already reached! */ timeout_ms = 1; /* trigger asap */ ev->ms = timeout_ms; ev->msbump = TRUE; return 0; } /* poll2cselect * * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones */ static int poll2cselect(int pollmask) { int omask = 0; if(pollmask & POLLIN) omask |= CURL_CSELECT_IN; if(pollmask & POLLOUT) omask |= CURL_CSELECT_OUT; if(pollmask & POLLERR) omask |= CURL_CSELECT_ERR; return omask; } /* socketcb2poll * * convert from libcurl' CURL_POLL_* bit definitions to poll()'s */ static short socketcb2poll(int pollmask) { short omask = 0; if(pollmask & CURL_POLL_IN) omask |= POLLIN; if(pollmask & CURL_POLL_OUT) omask |= POLLOUT; return omask; } /* events_socket * * Callback that gets called with information about socket activity to * monitor. */ static int events_socket(struct Curl_easy *easy, /* easy handle */ curl_socket_t s, /* socket */ int what, /* see above */ void *userp, /* private callback pointer */ void *socketp) /* private socket pointer */ { struct events *ev = userp; struct socketmonitor *m; struct socketmonitor *prev = NULL; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) easy; #endif (void)socketp; m = ev->list; while(m) { if(m->socket.fd == s) { if(what == CURL_POLL_REMOVE) { struct socketmonitor *nxt = m->next; /* remove this node from the list of monitored sockets */ if(prev) prev->next = nxt; else ev->list = nxt; free(m); m = nxt; infof(easy, "socket cb: socket %d REMOVED\n", s); } else { /* The socket 's' is already being monitored, update the activity mask. Convert from libcurl bitmask to the poll one. */ m->socket.events = socketcb2poll(what); infof(easy, "socket cb: socket %d UPDATED as %s%s\n", s, (what&CURL_POLL_IN)?"IN":"", (what&CURL_POLL_OUT)?"OUT":""); } break; } prev = m; m = m->next; /* move to next node */ } if(!m) { if(what == CURL_POLL_REMOVE) { /* this happens a bit too often, libcurl fix perhaps? */ /* fprintf(stderr, "%s: socket %d asked to be REMOVED but not present!\n", __func__, s); */ } else { m = malloc(sizeof(struct socketmonitor)); if(m) { m->next = ev->list; m->socket.fd = s; m->socket.events = socketcb2poll(what); m->socket.revents = 0; ev->list = m; infof(easy, "socket cb: socket %d ADDED as %s%s\n", s, (what&CURL_POLL_IN)?"IN":"", (what&CURL_POLL_OUT)?"OUT":""); } else return CURLE_OUT_OF_MEMORY; } } return 0; } /* * events_setup() * * Do the multi handle setups that only event-based transfers need. */ static void events_setup(struct Curl_multi *multi, struct events *ev) { /* timer callback */ curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer); curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev); /* socket callback */ curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket); curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev); } /* wait_or_timeout() * * waits for activity on any of the given sockets, or the timeout to trigger. */ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) { bool done = FALSE; CURLMcode mcode = CURLM_OK; CURLcode result = CURLE_OK; while(!done) { CURLMsg *msg; struct socketmonitor *m; struct pollfd *f; struct pollfd fds[4]; int numfds = 0; int pollrc; int i; struct curltime before; struct curltime after; /* populate the fds[] array */ for(m = ev->list, f = &fds[0]; m; m = m->next) { f->fd = m->socket.fd; f->events = m->socket.events; f->revents = 0; /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */ f++; numfds++; } /* get the time stamp to use to figure out how long poll takes */ before = Curl_now(); /* wait for activity or timeout */ pollrc = Curl_poll(fds, numfds, ev->ms); after = Curl_now(); ev->msbump = FALSE; /* reset here */ if(0 == pollrc) { /* timeout! */ ev->ms = 0; /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */ mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, &ev->running_handles); } else if(pollrc > 0) { /* loop over the monitored sockets to see which ones had activity */ for(i = 0; i< numfds; i++) { if(fds[i].revents) { /* socket activity, tell libcurl */ int act = poll2cselect(fds[i].revents); /* convert */ infof(multi->easyp, "call curl_multi_socket_action(socket %d)\n", fds[i].fd); mcode = curl_multi_socket_action(multi, fds[i].fd, act, &ev->running_handles); } } if(!ev->msbump) { /* If nothing updated the timeout, we decrease it by the spent time. * If it was updated, it has the new timeout time stored already. */ timediff_t timediff = Curl_timediff(after, before); if(timediff > 0) { if(timediff > ev->ms) ev->ms = 0; else ev->ms -= (long)timediff; } } } else return CURLE_RECV_ERROR; if(mcode) return CURLE_URL_MALFORMAT; /* we don't really care about the "msgs_in_queue" value returned in the second argument */ msg = curl_multi_info_read(multi, &pollrc); if(msg) { result = msg->data.result; done = TRUE; } } return result; } /* easy_events() * * Runs a transfer in a blocking manner using the events-based API */ static CURLcode easy_events(struct Curl_multi *multi) { /* this struct is made static to allow it to be used after this function returns and curl_multi_remove_handle() is called */ static struct events evs = {2, FALSE, 0, NULL, 0}; /* if running event-based, do some further multi inits */ events_setup(multi, &evs); return wait_or_timeout(multi, &evs); } #else /* CURLDEBUG */ /* when not built with debug, this function doesn't exist */ #define easy_events(x) CURLE_NOT_BUILT_IN #endif static CURLcode easy_transfer(struct Curl_multi *multi) { bool done = FALSE; CURLMcode mcode = CURLM_OK; CURLcode result = CURLE_OK; while(!done && !mcode) { int still_running = 0; mcode = curl_multi_poll(multi, NULL, 0, 1000, NULL); if(!mcode) mcode = curl_multi_perform(multi, &still_running); /* only read 'still_running' if curl_multi_perform() return OK */ if(!mcode && !still_running) { int rc; CURLMsg *msg = curl_multi_info_read(multi, &rc); if(msg) { result = msg->data.result; done = TRUE; } } } /* Make sure to return some kind of error if there was a multi problem */ if(mcode) { result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : /* The other multi errors should never happen, so return something suitably generic */ CURLE_BAD_FUNCTION_ARGUMENT; } return result; } /* * easy_perform() is the external interface that performs a blocking * transfer as previously setup. * * CONCEPT: This function creates a multi handle, adds the easy handle to it, * runs curl_multi_perform() until the transfer is done, then detaches the * easy handle, destroys the multi handle and returns the easy handle's return * code. * * REALITY: it can't just create and destroy the multi handle that easily. It * needs to keep it around since if this easy handle is used again by this * function, the same multi handle must be re-used so that the same pools and * caches can be used. * * DEBUG: if 'events' is set TRUE, this function will use a replacement engine * instead of curl_multi_perform() and use curl_multi_socket_action(). */ static CURLcode easy_perform(struct Curl_easy *data, bool events) { struct Curl_multi *multi; CURLMcode mcode; CURLcode result = CURLE_OK; SIGPIPE_VARIABLE(pipe_st); if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.errorbuffer) /* clear this as early as possible */ data->set.errorbuffer[0] = 0; if(data->multi) { failf(data, "easy handle already used in multi handle"); return CURLE_FAILED_INIT; } if(data->multi_easy) multi = data->multi_easy; else { /* this multi handle will only ever have a single easy handled attached to it, so make it use minimal hashes */ multi = Curl_multi_handle(1, 3); if(!multi) return CURLE_OUT_OF_MEMORY; data->multi_easy = multi; } if(multi->in_callback) return CURLE_RECURSIVE_API_CALL; /* Copy the MAXCONNECTS option to the multi handle */ curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects); mcode = curl_multi_add_handle(multi, data); if(mcode) { curl_multi_cleanup(multi); data->multi_easy = NULL; if(mcode == CURLM_OUT_OF_MEMORY) return CURLE_OUT_OF_MEMORY; return CURLE_FAILED_INIT; } sigpipe_ignore(data, &pipe_st); /* run the transfer */ result = events ? easy_events(multi) : easy_transfer(multi); /* ignoring the return code isn't nice, but atm we can't really handle a failure here, room for future improvement! */ (void)curl_multi_remove_handle(multi, data); sigpipe_restore(&pipe_st); /* The multi handle is kept alive, owned by the easy handle */ return result; } /* * curl_easy_perform() is the external interface that performs a blocking * transfer as previously setup. */ CURLcode curl_easy_perform(struct Curl_easy *data) { return easy_perform(data, FALSE); } #ifdef CURLDEBUG /* * curl_easy_perform_ev() is the external interface that performs a blocking * transfer using the event-based API internally. */ CURLcode curl_easy_perform_ev(struct Curl_easy *data) { return easy_perform(data, TRUE); } #endif /* * curl_easy_cleanup() is the external interface to cleaning/freeing the given * easy handle. */ void curl_easy_cleanup(struct Curl_easy *data) { SIGPIPE_VARIABLE(pipe_st); if(!data) return; sigpipe_ignore(data, &pipe_st); Curl_close(&data); sigpipe_restore(&pipe_st); } /* * curl_easy_getinfo() is an external interface that allows an app to retrieve * information from a performed transfer and similar. */ #undef curl_easy_getinfo CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; void *paramp; CURLcode result; va_start(arg, info); paramp = va_arg(arg, void *); result = Curl_getinfo(data, info, paramp); va_end(arg); return result; } static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src) { CURLcode result = CURLE_OK; enum dupstring i; enum dupblob j; /* Copy src->set into dst->set first, then deal with the strings afterwards */ dst->set = src->set; Curl_mime_initpart(&dst->set.mimepost, dst); /* clear all string pointers first */ memset(dst->set.str, 0, STRING_LAST * sizeof(char *)); /* duplicate all strings */ for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) { result = Curl_setstropt(&dst->set.str[i], src->set.str[i]); if(result) return result; } /* clear all blob pointers first */ memset(dst->set.blobs, 0, BLOB_LAST * sizeof(struct curl_blob *)); /* duplicate all blobs */ for(j = (enum dupblob)0; j < BLOB_LAST; j++) { result = Curl_setblobopt(&dst->set.blobs[j], src->set.blobs[j]); /* Curl_setstropt return CURLE_BAD_FUNCTION_ARGUMENT with blob */ if(result) return result; } /* duplicate memory areas pointed to */ i = STRING_COPYPOSTFIELDS; if(src->set.postfieldsize && src->set.str[i]) { /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */ dst->set.str[i] = Curl_memdup(src->set.str[i], curlx_sotouz(src->set.postfieldsize)); if(!dst->set.str[i]) return CURLE_OUT_OF_MEMORY; /* point to the new copy */ dst->set.postfields = dst->set.str[i]; } /* Duplicate mime data. */ result = Curl_mime_duppart(&dst->set.mimepost, &src->set.mimepost); if(src->set.resolve) dst->change.resolve = dst->set.resolve; return result; } /* * curl_easy_duphandle() is an external interface to allow duplication of a * given input easy handle. The returned handle will be a new working handle * with all options set exactly as the input source handle. */ struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data) { struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy)); if(NULL == outcurl) goto fail; /* * We setup a few buffers we need. We should probably make them * get setup on-demand in the code, as that would probably decrease * the likeliness of us forgetting to init a buffer here in the future. */ outcurl->set.buffer_size = data->set.buffer_size; /* copy all userdefined values */ if(dupset(outcurl, data)) goto fail; Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER); /* the connection cache is setup on demand */ outcurl->state.conn_cache = NULL; outcurl->state.lastconnect_id = -1; outcurl->progress.flags = data->progress.flags; outcurl->progress.callback = data->progress.callback; if(data->cookies) { /* If cookies are enabled in the parent handle, we enable them in the clone as well! */ outcurl->cookies = Curl_cookie_init(data, data->cookies->filename, outcurl->cookies, data->set.cookiesession); if(!outcurl->cookies) goto fail; } /* duplicate all values in 'change' */ if(data->change.cookielist) { outcurl->change.cookielist = Curl_slist_duplicate(data->change.cookielist); if(!outcurl->change.cookielist) goto fail; } if(data->change.url) { outcurl->change.url = strdup(data->change.url); if(!outcurl->change.url) goto fail; outcurl->change.url_alloc = TRUE; } if(data->change.referer) { outcurl->change.referer = strdup(data->change.referer); if(!outcurl->change.referer) goto fail; outcurl->change.referer_alloc = TRUE; } /* Reinitialize an SSL engine for the new handle * note: the engine name has already been copied by dupset */ if(outcurl->set.str[STRING_SSL_ENGINE]) { if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE])) goto fail; } /* Clone the resolver handle, if present, for the new handle */ if(Curl_resolver_duphandle(outcurl, &outcurl->state.resolver, data->state.resolver)) goto fail; #ifdef USE_ARES { CURLcode rc; rc = Curl_set_dns_servers(outcurl, data->set.str[STRING_DNS_SERVERS]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; rc = Curl_set_dns_interface(outcurl, data->set.str[STRING_DNS_INTERFACE]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; rc = Curl_set_dns_local_ip4(outcurl, data->set.str[STRING_DNS_LOCAL_IP4]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; rc = Curl_set_dns_local_ip6(outcurl, data->set.str[STRING_DNS_LOCAL_IP6]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; } #endif /* USE_ARES */ Curl_convert_setup(outcurl); Curl_initinfo(outcurl); outcurl->magic = CURLEASY_MAGIC_NUMBER; /* we reach this point and thus we are OK */ return outcurl; fail: if(outcurl) { curl_slist_free_all(outcurl->change.cookielist); outcurl->change.cookielist = NULL; Curl_safefree(outcurl->state.buffer); Curl_dyn_free(&outcurl->state.headerb); Curl_safefree(outcurl->change.url); Curl_safefree(outcurl->change.referer); Curl_freeset(outcurl); free(outcurl); } return NULL; } /* * curl_easy_reset() is an external interface that allows an app to re- * initialize a session handle to the default values. */ void curl_easy_reset(struct Curl_easy *data) { Curl_free_request_state(data); /* zero out UserDefined data: */ Curl_freeset(data); memset(&data->set, 0, sizeof(struct UserDefined)); (void)Curl_init_userdefined(data); /* zero out Progress data: */ memset(&data->progress, 0, sizeof(struct Progress)); /* zero out PureInfo data: */ Curl_initinfo(data); data->progress.flags |= PGRS_HIDE; data->state.current_speed = -1; /* init to negative == impossible */ /* zero out authentication data: */ memset(&data->state.authhost, 0, sizeof(struct auth)); memset(&data->state.authproxy, 0, sizeof(struct auth)); #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) Curl_http_auth_cleanup_digest(data); #endif } /* * curl_easy_pause() allows an application to pause or unpause a specific * transfer and direction. This function sets the full new state for the * current connection this easy handle operates on. * * NOTE: if you have the receiving paused and you call this function to remove * the pausing, you may get your write callback called at this point. * * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h * * NOTE: This is one of few API functions that are allowed to be called from * within a callback. */ CURLcode curl_easy_pause(struct Curl_easy *data, int action) { struct SingleRequest *k; CURLcode result = CURLE_OK; int oldstate; int newstate; if(!GOOD_EASY_HANDLE(data) || !data->conn) /* crazy input, don't continue */ return CURLE_BAD_FUNCTION_ARGUMENT; k = &data->req; oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE); /* first switch off both pause bits then set the new pause bits */ newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) | ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) | ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0); if((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) == oldstate) { /* Not changing any pause state, return */ DEBUGF(infof(data, "pause: no change, early return\n")); return CURLE_OK; } /* Unpause parts in active mime tree. */ if((k->keepon & ~newstate & KEEP_SEND_PAUSE) && (data->mstate == CURLM_STATE_PERFORM || data->mstate == CURLM_STATE_TOOFAST) && data->state.fread_func == (curl_read_callback) Curl_mime_read) { Curl_mime_unpause(data->state.in); } /* put it back in the keepon */ k->keepon = newstate; if(!(newstate & KEEP_RECV_PAUSE)) { Curl_http2_stream_pause(data, FALSE); if(data->state.tempcount) { /* there are buffers for sending that can be delivered as the receive pausing is lifted! */ unsigned int i; unsigned int count = data->state.tempcount; struct tempbuf writebuf[3]; /* there can only be three */ struct connectdata *conn = data->conn; struct Curl_easy *saved_data = NULL; /* copy the structs to allow for immediate re-pausing */ for(i = 0; i < data->state.tempcount; i++) { writebuf[i] = data->state.tempwrite[i]; Curl_dyn_init(&data->state.tempwrite[i].b, DYN_PAUSE_BUFFER); } data->state.tempcount = 0; /* set the connection's current owner */ if(conn->data != data) { saved_data = conn->data; conn->data = data; } for(i = 0; i < count; i++) { /* even if one function returns error, this loops through and frees all buffers */ if(!result) result = Curl_client_write(conn, writebuf[i].type, Curl_dyn_ptr(&writebuf[i].b), Curl_dyn_len(&writebuf[i].b)); Curl_dyn_free(&writebuf[i].b); } /* recover previous owner of the connection */ if(saved_data) conn->data = saved_data; if(result) return result; } } /* if there's no error and we're not pausing both directions, we want to have this handle checked soon */ if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) != (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) { Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */ /* force a recv/send check of this connection, as the data might've been read off the socket already */ data->conn->cselect_bits = CURL_CSELECT_IN | CURL_CSELECT_OUT; if(data->multi) Curl_update_timer(data->multi); } if(!data->state.done) /* This transfer may have been moved in or out of the bundle, update the corresponding socket callback, if used */ Curl_updatesocket(data); return result; } static CURLcode easy_connection(struct Curl_easy *data, curl_socket_t *sfd, struct connectdata **connp) { if(data == NULL) return CURLE_BAD_FUNCTION_ARGUMENT; /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */ if(!data->set.connect_only) { failf(data, "CONNECT_ONLY is required!"); return CURLE_UNSUPPORTED_PROTOCOL; } *sfd = Curl_getconnectinfo(data, connp); if(*sfd == CURL_SOCKET_BAD) { failf(data, "Failed to get recent socket"); return CURLE_UNSUPPORTED_PROTOCOL; } return CURLE_OK; } /* * Receives data from the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. * Returns CURLE_OK on success, error code on error. */ CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c; if(Curl_is_in_callback(data)) return CURLE_RECURSIVE_API_CALL; result = easy_connection(data, &sfd, &c); if(result) return result; *n = 0; result = Curl_read(c, sfd, buffer, buflen, &n1); if(result) return result; *n = (size_t)n1; return CURLE_OK; } /* * Sends data over the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. */ CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer, size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c = NULL; if(Curl_is_in_callback(data)) return CURLE_RECURSIVE_API_CALL; result = easy_connection(data, &sfd, &c); if(result) return result; *n = 0; result = Curl_write(c, sfd, buffer, buflen, &n1); if(n1 == -1) return CURLE_SEND_ERROR; /* detect EAGAIN */ if(!result && !n1) return CURLE_AGAIN; *n = (size_t)n1; return result; } /* * Wrapper to call functions in Curl_conncache_foreach() * * Returns always 0. */ static int conn_upkeep(struct connectdata *conn, void *param) { /* Param is unused. */ (void)param; if(conn->handler->connection_check) { /* Do a protocol-specific keepalive check on the connection. */ conn->handler->connection_check(conn, CONNCHECK_KEEPALIVE); } return 0; /* continue iteration */ } static CURLcode upkeep(struct conncache *conn_cache, void *data) { /* Loop over every connection and make connection alive. */ Curl_conncache_foreach(data, conn_cache, data, conn_upkeep); return CURLE_OK; } /* * Performs connection upkeep for the given session handle. */ CURLcode curl_easy_upkeep(struct Curl_easy *data) { /* Verify that we got an easy handle we can work with. */ if(!GOOD_EASY_HANDLE(data)) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->multi_easy) { /* Use the common function to keep connections alive. */ return upkeep(&data->multi_easy->conn_cache, data); } else { /* No connections, so just return success */ return CURLE_OK; } }
gpl-3.0
herlesupreeth/OAI-5G
common/utils/itti_analyzer/libparser/field_type.c
1
8157
/* * Copyright (c) 2015, EURECOM (www.eurecom.fr) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #define G_LOG_DOMAIN ("PARSER") #include "rc.h" #include "field_type.h" #include "buffers.h" #include "ui_interface.h" int field_dissect_from_buffer( types_t *type, ui_set_signal_text_cb_t ui_set_signal_text_cb, gpointer user_data, buffer_t *buffer, uint32_t offset, uint32_t parent_offset, int indent, gboolean new_line) { int length = 0; char cbuf[50 + (type->name ? strlen (type->name) : 0)]; types_t *type_child; char array_info[50]; new_line = FALSE; DISPLAY_PARSE_INFO("field", type->name, offset, parent_offset); CHECK_FCT(buffer_has_enouch_data(buffer, parent_offset + offset, type->size / 8)); if (type->bits == -1) { if ((type->name != NULL) && (strcmp(type->name, "_asn_ctx") == 0)) { /* Hide ASN1 asn_struct_ctx_t struct that hold context for parsing across buffer boundaries */ /* INDENTED_STRING(cbuf, indent, sprintf(cbuf, ".asn_ctx ...\n")); length = strlen (cbuf); ui_set_signal_text_cb(user_data, cbuf, length); */ } else { if (type->child != NULL) { /* Ignore TYPEDEF children */ for (type_child = type->child; type_child != NULL && type_child->type == TYPE_TYPEDEF; type_child = type_child->child) { } if (type_child->type == TYPE_ARRAY) { types_t *type_array_child; /* Ignore TYPEDEF children */ for (type_array_child = type_child->child; type_array_child != NULL && type_array_child->type == TYPE_TYPEDEF; type_array_child = type_array_child->child) { } sprintf (array_info, "[%d]", type_child->size / type_array_child->size); } else { array_info[0] = '\0'; } DISPLAY_TYPE("Fld"); INDENTED_STRING(cbuf, indent, length = sprintf(cbuf, ".%s%s = ", type->name ? type->name : "Field", array_info)); ui_set_signal_text_cb(user_data, cbuf, length); if (type_child->type == TYPE_ARRAY) { DISPLAY_BRACE(ui_set_signal_text_cb(user_data, "{", 1);) ui_set_signal_text_cb(user_data, "\n", 1); new_line = TRUE; } /* if (type_child->type == TYPE_STRUCT || type_child->type == TYPE_UNION) { DISPLAY_BRACE(ui_set_signal_text_cb(user_data, "{", 1);) ui_set_signal_text_cb(user_data, "\n", 1); new_line = TRUE; } */ type->child->parent = type; type->child->type_dissect_from_buffer( type->child, ui_set_signal_text_cb, user_data, buffer, parent_offset, offset + type->offset, new_line ? indent + DISPLAY_TAB_SIZE : indent, new_line); DISPLAY_BRACE( if (type_child->type == TYPE_ARRAY) { DISPLAY_TYPE("Fld"); INDENTED_STRING(cbuf, indent, length = sprintf(cbuf, "};\n")); ui_set_signal_text_cb(user_data, cbuf, length); }); /* DISPLAY_BRACE( if (type_child->type == TYPE_STRUCT || type_child->type == TYPE_UNION) { DISPLAY_TYPE("Fld"); INDENTED_STRING(cbuf, indent, sprintf(cbuf, "};\n")); length = strlen (cbuf); ui_set_signal_text_cb(user_data, cbuf, length); }); */ } } } else { /* The field is only composed of bits */ uint32_t value = 0; CHECK_FCT(buffer_fetch_bits(buffer, offset + type->offset + parent_offset, type->bits, &value)); DISPLAY_TYPE("Fld"); INDENTED_STRING(cbuf, indent, length = sprintf(cbuf, ".%s:%d = (0x%0*x) %d;\n", type->name ? type->name : "Field", type->bits, (type->bits + 3) / 4, value, value)); ui_set_signal_text_cb(user_data, cbuf, length); } return 0; } int field_type_file_print(types_t *type, int indent, FILE *file) { if (type == NULL) return -1; INDENTED(file, indent, fprintf(file, "<Field>\n")); INDENTED(file, indent+4, fprintf(file, "Id .........: %d\n", type->id)); INDENTED(file, indent+4, fprintf(file, "Name .......: %s\n", type->name)); INDENTED(file, indent+4, fprintf(file, "Bits .......: %d\n", type->bits)); INDENTED(file, indent+4, fprintf(file, "Type .......: %d\n", type->type_xml)); INDENTED(file, indent+4, fprintf(file, "Offset .....: %d\n", type->offset)); INDENTED(file, indent+4, fprintf(file, "Context ....: %d\n", type->context)); INDENTED(file, indent+4, fprintf(file, "File .......: %s\n", type->file)); INDENTED(file, indent+4, fprintf(file, "Line .......: %d\n", type->line)); if (type->file_ref != NULL) type->file_ref->type_file_print (type->file_ref, indent + 4, file); if (type->child != NULL) type->child->type_file_print (type->child, indent + 4, file); INDENTED(file, indent, fprintf(file, "</Field>\n")); return 0; } int field_type_hr_display(types_t *type, int indent) { if (type == NULL) return -1; INDENTED(stdout, indent, printf("<Field>\n")); INDENTED(stdout, indent+4, printf("Id .........: %d\n", type->id)); INDENTED(stdout, indent+4, printf("Name .......: %s\n", type->name)); INDENTED(stdout, indent+4, printf("Bits .......: %d\n", type->bits)); INDENTED(stdout, indent+4, printf("Type .......: %d\n", type->type_xml)); INDENTED(stdout, indent+4, printf("Offset .....: %d\n", type->offset)); INDENTED(stdout, indent+4, printf("Context ....: %d\n", type->context)); INDENTED(stdout, indent+4, printf("File .......: %s\n", type->file)); INDENTED(stdout, indent+4, printf("Line .......: %d\n", type->line)); if (type->file_ref != NULL) type->file_ref->type_hr_display (type->file_ref, indent + 4); if (type->child != NULL) type->child->type_hr_display (type->child, indent + 4); INDENTED(stdout, indent, printf("</Field>\n")); return 0; }
gpl-3.0
olygarch/cached-netboot
src/communication.cpp
1
4265
#include "communication.h" #include "common.h" #include <string.h> static uint32_t read_uint32_t(tcp::socket& socket, boost::asio::yield_context yield) { uint32_t netval; boost::asio::async_read(socket, boost::asio::buffer(&netval, 4), yield); return ntohl(netval); } static std::string read_string(tcp::socket& socket, boost::asio::yield_context yield) { size_t size = read_uint32_t(socket, yield); std::string str; str.resize(size); boost::asio::async_read(socket, boost::asio::buffer(&str[0], size), yield); return str; } ChunkDataPacket::ChunkDataPacket(const uint8_t* ptr, size_t size) { data.resize(size); memcpy(&data[0], ptr, size); } ChunkDataPacket::ChunkDataPacket(tcp::socket& socket, boost::asio::yield_context yield) { uint32_t size = read_uint32_t(socket, yield); data.resize(size); boost::asio::async_read(socket, boost::asio::buffer(&data[0], size), yield); } /* hash_t ChunkDataPacket::get_hash() const { Hasher hasher(chunk_max_size); hasher.update(data.begin(), data.end()); return hasher.get_strong_hash(); } */ void ChunkDataPacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { netlength = htonl(data.size()); buffers.emplace_back(&netlength, 4); buffers.emplace_back(&data[0], data.size()); } Chunk ChunkDataPacket::get_chunk() const { return {data.size(), &data[0]}; } ChunkListPacket::ChunkListPacket(tcp::socket& socket, boost::asio::yield_context yield) { size_t size = read_uint32_t(socket, yield); for (size_t i=0; i<size; i++) { chunks.emplace_back(socket, yield); } } void ChunkListPacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { netlength = htonl(chunks.size()); buffers.emplace_back(&netlength, 4); for (auto& chunk: chunks) { chunk.add_buffers(buffers); } } void NewChunkPacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { chunk.add_buffers(buffers); } SendChunkPacket::SendChunkPacket(tcp::socket& socket, boost::asio::yield_context yield) { receiver_str = read_string(socket, yield); receiver = address::from_string(receiver_str); chunk = hash_t(socket, yield); } void SendChunkPacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { receiver_str = receiver.to_string(); netlength = htonl(receiver_str.size()); buffers.emplace_back(&netlength, 4); buffers.emplace_back(&receiver_str[0], receiver_str.size()); chunk.add_buffers(buffers); } GetFilePacket::GetFilePacket(tcp::socket& socket, boost::asio::yield_context yield) { name = read_string(socket, yield); } void GetFilePacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { netlength = htonl(name.size()); buffers.emplace_back(&netlength, 4); buffers.emplace_back(&name[0], name.size()); } FileInfoPacket::FileInfoPacket(tcp::socket& socket, boost::asio::yield_context yield) { name = read_string(socket, yield); boost::asio::async_read(socket, boost::asio::buffer(&netfsize, 8), yield); size = be64toh(netfsize); chunk_list = ChunkListPacket(socket, yield); } void FileInfoPacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { netlength = htonl(name.size()); netfsize = htobe64(size); buffers.emplace_back(&netlength, 4); buffers.emplace_back(&name[0], name.size()); buffers.emplace_back(&netfsize, 8); chunk_list.add_buffers(buffers); } ErrorPacket::ErrorPacket(tcp::socket& socket, boost::asio::yield_context yield) { boost::asio::async_read(socket, boost::asio::buffer(&code, 1), yield); } void ErrorPacket::add_buffers(std::vector<boost::asio::const_buffer>& buffers) { buffers.emplace_back(&code, 1); } const std::string ErrorPacket::get_as_string() const { switch (code) { case no_such_file: return "The file you requested does not exist!"; case unknown_packet: return "Unknown packet type received!"; default: return "Unknown error code!"; }; } packet_type get_packet_type(tcp::socket& socket, boost::asio::yield_context yield) { packet_type type; boost::asio::async_read(socket, boost::asio::buffer(&type, 1), yield); return type; }
gpl-3.0
rafael-santiago/Divert
sys/windivert.c
1
118208
/* * windivert.c * (C) 2014, all rights reserved, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <ntddk.h> #include <fwpsk.h> #include <fwpmk.h> #include <wdf.h> #include <stdarg.h> #include <ntstrsafe.h> #define INITGUID #include <guiddef.h> #include "windivert_device.h" /* * WDK function declaration cruft. */ DRIVER_INITIALIZE DriverEntry; EVT_WDF_DRIVER_UNLOAD windivert_unload; EVT_WDF_IO_IN_CALLER_CONTEXT windivert_caller_context; EVT_WDF_IO_QUEUE_IO_DEVICE_CONTROL windivert_ioctl; EVT_WDF_DEVICE_FILE_CREATE windivert_create; EVT_WDF_TIMER windivert_timer; EVT_WDF_FILE_CLEANUP windivert_cleanup; EVT_WDF_FILE_CLOSE windivert_close; EVT_WDF_WORKITEM windivert_read_service_work_item; /* * Debugging macros. */ // #define DEBUG_ON #define DEBUG_BUFSIZE 256 #ifdef DEBUG_ON static void DEBUG(PCCH format, ...) { va_list args; char buf[DEBUG_BUFSIZE+1]; if (KeGetCurrentIrql() != PASSIVE_LEVEL) { return; } va_start(args, format); RtlStringCbVPrintfA(buf, DEBUG_BUFSIZE, format, args); DbgPrint("WINDIVERT: %s\n", buf); va_end(args); } static void DEBUG_ERROR(PCCH format, NTSTATUS status, ...) { va_list args; char buf[DEBUG_BUFSIZE+1]; if (KeGetCurrentIrql() != PASSIVE_LEVEL) { return; } va_start(args, status); RtlStringCbVPrintfA(buf, DEBUG_BUFSIZE, format, args); DbgPrint("WINDIVERT: *** ERROR ***: (status = %x): %s\n", status, buf); va_end(args); } #else // DEBUG_ON #define DEBUG(format, ...) #define DEBUG_ERROR(format, status, ...) #endif // DEBUG_ON #define WINDIVERT_TAG 'viDW' /* * WinDivert packet filter. */ struct filter_s { UINT8 protocol:4; // field's protocol UINT8 test:4; // Filter test UINT8 field; // Field of interest UINT16 success; // Success continuation UINT16 failure; // Fail continuation UINT32 arg[4]; // Comparison argument }; typedef struct filter_s *filter_t; #define WINDIVERT_FILTER_PROTOCOL_NONE 0 #define WINDIVERT_FILTER_PROTOCOL_IP 1 #define WINDIVERT_FILTER_PROTOCOL_IPV6 2 #define WINDIVERT_FILTER_PROTOCOL_ICMP 3 #define WINDIVERT_FILTER_PROTOCOL_ICMPV6 4 #define WINDIVERT_FILTER_PROTOCOL_TCP 5 #define WINDIVERT_FILTER_PROTOCOL_UDP 6 /* * WinDivert context information. */ #define WINDIVERT_CONTEXT_MAGIC 0xAA5D1C5BC439AA72ull #define WINDIVERT_CONTEXT_SIZE (sizeof(struct context_s)) #define WINDIVERT_CONTEXT_MAXLAYERS 4 #define WINDIVERT_CONTEXT_MAXWORKERS 4 #define WINDIVERT_CONTEXT_OUTBOUND_IPV4_LAYER 0 #define WINDIVERT_CONTEXT_INBOUND_IPV4_LAYER 1 #define WINDIVERT_CONTEXT_OUTBOUND_IPV6_LAYER 2 #define WINDIVERT_CONTEXT_INBOUND_IPV6_LAYER 3 typedef enum { WINDIVERT_CONTEXT_STATE_OPENING = 0xA0, // Context is opening. WINDIVERT_CONTEXT_STATE_OPEN = 0xB1, // Context is open. WINDIVERT_CONTEXT_STATE_CLOSING = 0xC2, // Context is closing. WINDIVERT_CONTEXT_STATE_CLOSED = 0xD3, // Context is closed. WINDIVERT_CONTEXT_STATE_INVALID = 0xE4 // Context is invalid. } context_state_t; struct context_s { UINT64 magic; // WINDIVERT_CONTEXT_MAGIC context_state_t state; // Context's state. KSPIN_LOCK lock; // Context-wide lock. WDFDEVICE device; // Context's device. LIST_ENTRY packet_queue; // Packet queue. ULONG packet_queue_length; // Packet queue length. ULONG packet_queue_maxlength; // Packet queue max length. WDFTIMER timer; // Packet timer. UINT timer_timeout; // Packet timeout (in ms). BOOL timer_ticktock; // Packet timer ticktock. WDFQUEUE read_queue; // Read queue. WDFWORKITEM workers[WINDIVERT_CONTEXT_MAXWORKERS]; // Read workers. UINT8 worker_curr; // Current read worker. UINT8 layer_0; // Context's layer (initial). UINT8 layer; // Context's layer. UINT64 flags_0; // Context's flags (initial). UINT64 flags; // Context's flags. UINT32 priority_0; // Context's priority (initial). UINT32 priority; // Context's priority. GUID callout_guid[WINDIVERT_CONTEXT_MAXLAYERS]; // Callout GUIDs. GUID filter_guid[WINDIVERT_CONTEXT_MAXLAYERS]; // Filter GUIDs. BOOL installed[WINDIVERT_CONTEXT_MAXLAYERS]; // What is installed? LONG filter_on; // Is filter on? HANDLE engine_handle; // WFP engine handle. filter_t filter; // Packet filter. }; typedef struct context_s context_s; typedef struct context_s *context_t; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(context_s, windivert_context_get); /* * WinDivert Layer information. */ typedef void (*windivert_callout_t)( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); struct layer_s { wchar_t *sublayer_name; // Sub-layer name. wchar_t *sublayer_desc; // Sub-layer description. wchar_t *callout_name; // Call-out name. wchar_t *callout_desc; // Call-out description. wchar_t *filter_name; // Filter name. wchar_t *filter_desc; // Filter description. GUID layer_guid; // WFP layer GUID. GUID sublayer_guid; // Sub-layer GUID. windivert_callout_t callout; // Call-out. }; typedef struct layer_s *layer_t; /* * WinDivert request context. */ struct req_context_s { struct windivert_addr_s *addr; // Pointer to address structure. }; typedef struct req_context_s req_context_s; typedef struct req_context_s *req_context_t; WDF_DECLARE_CONTEXT_TYPE_WITH_NAME(req_context_s, windivert_req_context_get); /* * WinDivert packet structure. */ #define WINDIVERT_PACKET_SIZE (sizeof(struct packet_s)) struct packet_s { LIST_ENTRY entry; // Entry for queue. PNET_BUFFER_LIST net_buffer_list; // Clone of the net buffer list. size_t data_len; // Length of `data'. UINT8 direction; // Packet direction. UINT32 if_idx; // Interface index. UINT32 sub_if_idx; // Sub-interface index. BOOL ip_checksum; // IP checksum is valid. BOOL tcp_checksum; // TCP checksum is valid. BOOL udp_checksum; // UDP checksum is valid. BOOL timer_ticktock; // Time-out ticktock. char data[]; // Packet data. }; typedef struct packet_s *packet_t; /* * WinDivert address definition. */ struct windivert_addr_s { UINT32 IfIdx; UINT32 SubIfIdx; UINT8 Direction; }; typedef struct windivert_addr_s *windivert_addr_t; /* * Header definitions. */ struct iphdr { UINT8 HdrLength:4; UINT8 Version:4; UINT8 TOS; UINT16 Length; UINT16 Id; UINT16 FragOff0; UINT8 TTL; UINT8 Protocol; UINT16 Checksum; UINT32 SrcAddr; UINT32 DstAddr; }; struct ipv6hdr { UINT8 TrafficClass0:4; UINT8 Version:4; UINT8 FlowLabel0:4; UINT8 TrafficClass1:4; UINT16 FlowLabel1; UINT16 Length; UINT8 NextHdr; UINT8 HopLimit; UINT32 SrcAddr[4]; UINT32 DstAddr[4]; }; struct icmphdr { UINT8 Type; UINT8 Code; UINT16 Checksum; UINT32 Body; }; struct icmpv6hdr { UINT8 Type; UINT8 Code; UINT16 Checksum; UINT32 Body; }; struct tcphdr { UINT16 SrcPort; UINT16 DstPort; UINT32 SeqNum; UINT32 AckNum; UINT16 Reserved1:4; UINT16 HdrLength:4; UINT16 Fin:1; UINT16 Syn:1; UINT16 Rst:1; UINT16 Psh:1; UINT16 Ack:1; UINT16 Urg:1; UINT16 Reserved2:2; UINT16 Window; UINT16 Checksum; UINT16 UrgPtr; }; struct udphdr { UINT16 SrcPort; UINT16 DstPort; UINT16 Length; UINT16 Checksum; }; #define IPHDR_GET_FRAGOFF(hdr) (((hdr)->FragOff0) & 0xFF1F) #define IPHDR_GET_MF(hdr) (((hdr)->FragOff0) & 0x0020) #define IPHDR_GET_DF(hdr) (((hdr)->FragOff0) & 0x0040) #define IPV6HDR_GET_TRAFFICCLASS(hdr) \ ((((hdr)->TrafficClass0) << 4) | ((hdr)->TrafficClass1)) #define IPV6HDR_GET_FLOWLABEL(hdr) \ ((((UINT32)(hdr)->FlowLabel0) << 16) | ((UINT32)(hdr)->FlowLabel1)) /* * Misc. */ #define UINT8_MAX 0xFF #define UINT16_MAX 0xFFFF #define UINT32_MAX 0xFFFFFFFF /* * Global state. */ HANDLE inject_handle = NULL; HANDLE injectv6_handle = NULL; NDIS_HANDLE pool_handle = NULL; HANDLE engine_handle = NULL; LONG priority_counter = 0; /* * Priorities. */ #define WINDIVERT_CONTEXT_PRIORITY(priority0) \ windivert_context_priority(priority0) static UINT32 windivert_context_priority(UINT32 priority0) { UINT16 priority1 = (UINT16)InterlockedIncrement(&priority_counter); priority0 -= WINDIVERT_PRIORITY_MIN; return ((priority0 << 16) | ((UINT32)priority1 & 0x0000FFFF)); } #define WINDIVERT_FILTER_WEIGHT(priority) \ ((UINT64)(UINT32_MAX - (priority))) /* * Prototypes. */ static void windivert_driver_unload(void); extern VOID windivert_ioctl(IN WDFQUEUE queue, IN WDFREQUEST request, IN size_t in_length, IN size_t out_len, IN ULONG code); static NTSTATUS windivert_read(context_t context, WDFREQUEST request); extern VOID windivert_read_service_work_item(IN WDFWORKITEM item); static void windivert_read_service(context_t context); static BOOLEAN windivert_context_verify(context_t context, context_state_t state); extern VOID windivert_create(IN WDFDEVICE device, IN WDFREQUEST request, IN WDFFILEOBJECT object); static NTSTATUS windivert_install_sublayer(layer_t layer); static NTSTATUS windivert_install_callouts(context_t context, BOOL is_inbound, BOOL is_outbound, BOOL is_ipv4, BOOL is_ipv6); static NTSTATUS windivert_install_callout(context_t context, UINT idx, layer_t layer); static void windivert_uninstall_callouts(context_t context); extern VOID windivert_timer(IN WDFTIMER timer); extern VOID windivert_cleanup(IN WDFFILEOBJECT object); extern VOID windivert_close(IN WDFFILEOBJECT object); extern NTSTATUS windivert_write(context_t context, WDFREQUEST request, windivert_addr_t addr); extern void NTAPI windivert_inject_complete(VOID *context, NET_BUFFER_LIST *packets, BOOLEAN dispatch_level); static NTSTATUS windivert_notify_callout(IN FWPS_CALLOUT_NOTIFY_TYPE type, IN const GUID *filter_key, IN const FWPS_FILTER0 *filter); static void windivert_classify_outbound_network_v4_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static void windivert_classify_inbound_network_v4_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static void windivert_classify_outbound_network_v6_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static void windivert_classify_inbound_network_v6_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static void windivert_classify_forward_network_v4_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static void windivert_classify_forward_network_v6_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static void windivert_classify_callout(IN UINT8 direction, IN UINT32 if_idx, IN UINT32 sub_if_idx, IN BOOL isipv4, IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result); static BOOL windivert_queue_packet(context_t context, PNET_BUFFER buffer, PNET_BUFFER_LIST buffers, UINT8 direction, UINT32 if_idx, UINT32 sub_if_idx); static BOOL windivert_reinject_packet(context_t context, UINT8 direction, BOOL isipv4, UINT32 if_idx, UINT32 sub_if_idx, UINT32 priority, PNET_BUFFER buffer); static void NTAPI windivert_reinject_complete(VOID *context, NET_BUFFER_LIST *buffers, BOOLEAN dispatch_level); static void windivert_free_packet(packet_t packet); static UINT16 windivert_checksum(const void *pseudo_header, size_t pseudo_header_len, const void *data, size_t size); static void windivert_update_checksums(void *header, size_t len, BOOL update_ip, BOOL update_tcp, BOOL update_udp); static BOOL windivert_filter(PNET_BUFFER buffer, UINT32 if_idx, UINT32 sub_if_idx, BOOL outbound, filter_t filter); static filter_t windivert_filter_compile(windivert_ioctl_filter_t ioctl_filter, size_t ioctl_filter_len); static void windivert_filter_analyze(filter_t filter, BOOL *is_inbound, BOOL *is_outbound, BOOL *ip_ipv4, BOOL *is_ipv6); static BOOL windivert_filter_test(filter_t filter, UINT16 ip, UINT8 protocol, UINT8 field, UINT32 arg); /* * WinDivert sublayer GUIDs */ DEFINE_GUID(WINDIVERT_SUBLAYER_INBOUND_IPV4_GUID, 0xAC32F237, 0x1408, 0x435A, 0x90, 0xF1, 0xF1, 0xAA, 0x58, 0x4C, 0xCA, 0x7F); DEFINE_GUID(WINDIVERT_SUBLAYER_OUTBOUND_IPV4_GUID, 0xF229AF90, 0xC7CC, 0x4351, 0x8A, 0x5E, 0x51, 0xB1, 0xE1, 0xB5, 0x97, 0x0A); DEFINE_GUID(WINDIVERT_SUBLAYER_INBOUND_IPV6_GUID, 0x0C25C18F, 0x4F3E, 0x4F3E, 0xBA, 0xB4, 0x26, 0xBD, 0x1E, 0x6E, 0x41, 0x31); DEFINE_GUID(WINDIVERT_SUBLAYER_OUTBOUND_IPV6_GUID, 0x26966F53, 0x4BCD, 0x4DE2, 0xAA, 0x0E, 0xA6, 0x70, 0x59, 0x20, 0x37, 0xC0); DEFINE_GUID(WINDIVERT_SUBLAYER_FORWARD_IPV4_GUID, 0x2F472BD8, 0x346F, 0x4D9C, 0x8A, 0xEE, 0x68, 0xCA, 0xFD, 0x00, 0x71, 0x11); DEFINE_GUID(WINDIVERT_SUBLAYER_FORWARD_IPV6_GUID, 0xA196BAC6, 0x6546, 0x4FD5, 0x96, 0xD3, 0x18, 0xD5, 0x7D, 0x5C, 0x3D, 0x78); /* * WinDivert supported layers. */ static struct layer_s layer_inbound_network_ipv4_0 = { L"" WINDIVERT_DEVICE_NAME L"_SubLayerInboundNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" sublayer network (inbound IPv4)", L"" WINDIVERT_DEVICE_NAME L"_CalloutInboundNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" callout network (inbound IPv4)", L"" WINDIVERT_DEVICE_NAME L"_FilterInboundNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" filter network (inbound IPv4)", {0}, {0}, windivert_classify_inbound_network_v4_callout, }; static layer_t layer_inbound_network_ipv4 = &layer_inbound_network_ipv4_0; static struct layer_s layer_outbound_network_ipv4_0 = { L"" WINDIVERT_DEVICE_NAME L"_SubLayerOutboundNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" sublayer network (outbound IPv4)", L"" WINDIVERT_DEVICE_NAME L"_CalloutOutboundNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" callout network (outbound IPv4)", L"" WINDIVERT_DEVICE_NAME L"_FilterOutboundNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" filter network (outbound IPv4)", {0}, {0}, windivert_classify_outbound_network_v4_callout, }; static layer_t layer_outbound_network_ipv4 = &layer_outbound_network_ipv4_0; static struct layer_s layer_inbound_network_ipv6_0 = { L"" WINDIVERT_DEVICE_NAME L"_SubLayerInboundNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" sublayer network (inbound IPv6)", L"" WINDIVERT_DEVICE_NAME L"_CalloutInboundNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" callout network (inbound IPv6)", L"" WINDIVERT_DEVICE_NAME L"_FilterInboundNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" filter network (inbound IPv6)", {0}, {0}, windivert_classify_inbound_network_v6_callout, }; static layer_t layer_inbound_network_ipv6 = &layer_inbound_network_ipv6_0; static struct layer_s layer_outbound_network_ipv6_0 = { L"" WINDIVERT_DEVICE_NAME L"_SubLayerOutboundNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" sublayer network (outbound IPv6)", L"" WINDIVERT_DEVICE_NAME L"_CalloutOutboundNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" callout network (outbound IPv6)", L"" WINDIVERT_DEVICE_NAME L"_FilterOutboundNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" filter network (outbound IPv6)", {0}, {0}, windivert_classify_outbound_network_v6_callout, }; static layer_t layer_outbound_network_ipv6 = &layer_outbound_network_ipv6_0; static struct layer_s layer_forward_network_ipv4_0 = { L"" WINDIVERT_DEVICE_NAME L"_SubLayerForwardNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" sublayer network (forward IPv4)", L"" WINDIVERT_DEVICE_NAME L"_CalloutForwardNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" callout network (forward IPv4)", L"" WINDIVERT_DEVICE_NAME L"_FilterForwardNetworkIPv4", L"" WINDIVERT_DEVICE_NAME L" filter network (forward IPv4)", {0}, {0}, windivert_classify_forward_network_v4_callout, }; static layer_t layer_forward_network_ipv4 = &layer_forward_network_ipv4_0; static struct layer_s layer_forward_network_ipv6_0 = { L"" WINDIVERT_DEVICE_NAME L"_SubLayerForwardNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" sublayer network (forward IPv6)", L"" WINDIVERT_DEVICE_NAME L"_CalloutForwardNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" callout network (forward IPv6)", L"" WINDIVERT_DEVICE_NAME L"_FilterForwardNetworkIPv6", L"" WINDIVERT_DEVICE_NAME L" filter network (forward IPv6)", {0}, {0}, windivert_classify_forward_network_v6_callout, }; static layer_t layer_forward_network_ipv6 = &layer_forward_network_ipv6_0; /* * WinDivert driver entry routine. */ extern NTSTATUS DriverEntry(IN PDRIVER_OBJECT driver_obj, IN PUNICODE_STRING reg_path) { WDF_DRIVER_CONFIG config; WDFDRIVER driver; PWDFDEVICE_INIT device_init; WDFDEVICE device; WDF_FILEOBJECT_CONFIG file_config; WDF_IO_QUEUE_CONFIG queue_config; WDFQUEUE queue; WDF_OBJECT_ATTRIBUTES obj_attrs; NET_BUFFER_LIST_POOL_PARAMETERS pool_params; NTSTATUS status; DECLARE_CONST_UNICODE_STRING(device_name, L"\\Device\\" WINDIVERT_DEVICE_NAME); DECLARE_CONST_UNICODE_STRING(dos_device_name, L"\\??\\" WINDIVERT_DEVICE_NAME); DEBUG("LOAD: loading WinDivert driver"); // Initialize the layers. layer_inbound_network_ipv4->layer_guid = FWPM_LAYER_INBOUND_IPPACKET_V4; layer_outbound_network_ipv4->layer_guid = FWPM_LAYER_OUTBOUND_IPPACKET_V4; layer_inbound_network_ipv6->layer_guid = FWPM_LAYER_INBOUND_IPPACKET_V6; layer_outbound_network_ipv6->layer_guid = FWPM_LAYER_OUTBOUND_IPPACKET_V6; layer_forward_network_ipv4->layer_guid = FWPM_LAYER_IPFORWARD_V4; layer_forward_network_ipv6->layer_guid = FWPM_LAYER_IPFORWARD_V6; layer_inbound_network_ipv4->sublayer_guid = WINDIVERT_SUBLAYER_INBOUND_IPV4_GUID; layer_outbound_network_ipv4->sublayer_guid = WINDIVERT_SUBLAYER_OUTBOUND_IPV4_GUID; layer_inbound_network_ipv6->sublayer_guid = WINDIVERT_SUBLAYER_INBOUND_IPV6_GUID; layer_outbound_network_ipv6->sublayer_guid = WINDIVERT_SUBLAYER_OUTBOUND_IPV6_GUID; layer_forward_network_ipv4->sublayer_guid = WINDIVERT_SUBLAYER_FORWARD_IPV4_GUID; layer_forward_network_ipv6->sublayer_guid = WINDIVERT_SUBLAYER_FORWARD_IPV6_GUID; // Configure ourself as a non-PnP driver: WDF_DRIVER_CONFIG_INIT(&config, WDF_NO_EVENT_CALLBACK); config.DriverInitFlags |= WdfDriverInitNonPnpDriver; config.EvtDriverUnload = windivert_unload; status = WdfDriverCreate(driver_obj, reg_path, WDF_NO_OBJECT_ATTRIBUTES, &config, &driver); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WDF driver", status); goto driver_entry_exit; } device_init = WdfControlDeviceInitAllocate(driver, &SDDL_DEVOBJ_SYS_ALL_ADM_ALL); if (device_init == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to allocate WDF control device init structure", status); goto driver_entry_exit; } WdfDeviceInitSetDeviceType(device_init, FILE_DEVICE_NETWORK); WdfDeviceInitSetIoType(device_init, WdfDeviceIoDirect); status = WdfDeviceInitAssignName(device_init, &device_name); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WDF device name", status); WdfDeviceInitFree(device_init); goto driver_entry_exit; } WDF_FILEOBJECT_CONFIG_INIT(&file_config, windivert_create, windivert_close, windivert_cleanup); WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&obj_attrs, context_s); WdfDeviceInitSetFileObjectConfig(device_init, &file_config, &obj_attrs); WdfDeviceInitSetIoInCallerContextCallback(device_init, windivert_caller_context); WDF_OBJECT_ATTRIBUTES_INIT(&obj_attrs); status = WdfDeviceCreate(&device_init, &obj_attrs, &device); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WDF control device", status); WdfDeviceInitFree(device_init); goto driver_entry_exit; } WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queue_config, WdfIoQueueDispatchParallel); queue_config.EvtIoRead = NULL; queue_config.EvtIoWrite = NULL; queue_config.EvtIoDeviceControl = windivert_ioctl; WDF_OBJECT_ATTRIBUTES_INIT(&obj_attrs); obj_attrs.ExecutionLevel = WdfExecutionLevelPassive; obj_attrs.SynchronizationScope = WdfSynchronizationScopeNone; status = WdfIoQueueCreate(device, &queue_config, &obj_attrs, &queue); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create default WDF queue", status); goto driver_entry_exit; } status = WdfDeviceCreateSymbolicLink(device, &dos_device_name); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create device symbolic link", status); goto driver_entry_exit; } WdfControlFinishInitializing(device); // Create the packet injection handles. status = FwpsInjectionHandleCreate0(AF_INET, FWPS_INJECTION_TYPE_NETWORK | FWPS_INJECTION_TYPE_FORWARD, &inject_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WFP packet injection handle", status); goto driver_entry_exit; } status = FwpsInjectionHandleCreate0(AF_INET6, FWPS_INJECTION_TYPE_NETWORK | FWPS_INJECTION_TYPE_FORWARD, &injectv6_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WFP ipv6 packet injection handle", status); goto driver_entry_exit; } // Create the packet pool handle. RtlZeroMemory(&pool_params, sizeof(pool_params)); pool_params.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; pool_params.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1; pool_params.Header.Size = sizeof(pool_params); pool_params.fAllocateNetBuffer = TRUE; pool_params.PoolTag = WINDIVERT_TAG; pool_params.DataSize = 0; pool_handle = NdisAllocateNetBufferListPool(NULL, &pool_params); if (pool_handle == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to allocate net buffer list pool", status); goto driver_entry_exit; } // Open a handle to the filter engine: status = FwpmEngineOpen0(NULL, RPC_C_AUTHN_DEFAULT, NULL, NULL, &engine_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WFP engine handle", status); goto driver_entry_exit; } // Register WFP sub-layers: status = FwpmTransactionBegin0(engine_handle, 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to begin WFP transaction", status); goto driver_entry_exit; } status = windivert_install_sublayer(layer_inbound_network_ipv4); if (!NT_SUCCESS(status)) { driver_entry_sublayer_error: DEBUG_ERROR("failed to install WFP sub-layer", status); FwpmTransactionAbort0(engine_handle); goto driver_entry_exit; } status = windivert_install_sublayer(layer_outbound_network_ipv4); if (!NT_SUCCESS(status)) { goto driver_entry_sublayer_error; } status = windivert_install_sublayer(layer_inbound_network_ipv6); if (!NT_SUCCESS(status)) { goto driver_entry_sublayer_error; } status = windivert_install_sublayer(layer_outbound_network_ipv6); if (!NT_SUCCESS(status)) { goto driver_entry_sublayer_error; } status = windivert_install_sublayer(layer_forward_network_ipv4); if (!NT_SUCCESS(status)) { goto driver_entry_sublayer_error; } status = windivert_install_sublayer(layer_forward_network_ipv6); if (!NT_SUCCESS(status)) { goto driver_entry_sublayer_error; } status = FwpmTransactionCommit0(engine_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to commit WFP transaction", status); goto driver_entry_exit; } driver_entry_exit: if (!NT_SUCCESS(status)) { windivert_driver_unload(); } return status; } /* * WinDivert driver unload routine. */ extern VOID windivert_unload(IN WDFDRIVER Driver) { windivert_driver_unload(); } /* * WinDivert driver unload. */ static void windivert_driver_unload(void) { NTSTATUS status; DEBUG("UNLOAD: unloading the WinDivert driver"); if (inject_handle != NULL) { FwpsInjectionHandleDestroy0(inject_handle); } if (injectv6_handle != NULL) { FwpsInjectionHandleDestroy0(injectv6_handle); } if (pool_handle != NULL) { NdisFreeNetBufferListPool(pool_handle); } if (engine_handle != NULL) { status = FwpmTransactionBegin0(engine_handle, 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to begin WFP transaction", status); FwpmEngineClose0(engine_handle); return; } FwpmSubLayerDeleteByKey0(engine_handle, &layer_inbound_network_ipv4->sublayer_guid); FwpmSubLayerDeleteByKey0(engine_handle, &layer_outbound_network_ipv4->sublayer_guid); FwpmSubLayerDeleteByKey0(engine_handle, &layer_inbound_network_ipv6->sublayer_guid); FwpmSubLayerDeleteByKey0(engine_handle, &layer_outbound_network_ipv6->sublayer_guid); FwpmSubLayerDeleteByKey0(engine_handle, &layer_forward_network_ipv4->sublayer_guid); FwpmSubLayerDeleteByKey0(engine_handle, &layer_forward_network_ipv6->sublayer_guid); status = FwpmTransactionCommit0(engine_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to commit WFP transaction", status); } FwpmEngineClose0(engine_handle); } } /* * Register a sub-layer. */ static NTSTATUS windivert_install_sublayer(layer_t layer) { FWPM_SUBLAYER0 sublayer; NTSTATUS status; RtlZeroMemory(&sublayer, sizeof(sublayer)); sublayer.subLayerKey = layer->sublayer_guid; sublayer.displayData.name = layer->sublayer_name; sublayer.displayData.description = layer->sublayer_desc; sublayer.weight = UINT16_MAX; status = FwpmSubLayerAdd0(engine_handle, &sublayer, NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to add WFP sub-layer", status); } return status; } /* * WinDivert context verify. */ static BOOLEAN windivert_context_verify(context_t context, context_state_t state) { if (context == NULL) { DEBUG_ERROR("failed to verify context; context is NULL", STATUS_INVALID_HANDLE); return FALSE; } if (context->magic != WINDIVERT_CONTEXT_MAGIC) { DEBUG_ERROR("failed to verify context; invalid magic number", STATUS_INVALID_HANDLE); return FALSE; } if (context->state != state) { DEBUG_ERROR("failed to verify context; expected context state %x, " "found context state %x", STATUS_INVALID_HANDLE, state, context->state); return FALSE; } return TRUE; } /* * WinDivert create routine. */ extern VOID windivert_create(IN WDFDEVICE device, IN WDFREQUEST request, IN WDFFILEOBJECT object) { WDF_IO_QUEUE_CONFIG queue_config; WDF_TIMER_CONFIG timer_config; WDF_WORKITEM_CONFIG item_config; WDF_OBJECT_ATTRIBUTES obj_attrs; FWPM_SESSION0 session; NTSTATUS status = STATUS_SUCCESS; UINT8 i; context_t context = windivert_context_get(object); DEBUG("CREATE: creating a new WinDivert context (context=%p)", context); // Initialise the new context: context->magic = WINDIVERT_CONTEXT_MAGIC; context->state = WINDIVERT_CONTEXT_STATE_OPENING; context->device = device; context->packet_queue_length = 0; context->packet_queue_maxlength = WINDIVERT_PARAM_QUEUE_LEN_DEFAULT; context->timer = NULL; context->timer_timeout = WINDIVERT_PARAM_QUEUE_TIME_DEFAULT; context->layer_0 = WINDIVERT_LAYER_DEFAULT; context->layer = WINDIVERT_LAYER_DEFAULT; context->flags_0 = 0; context->flags = 0; context->priority_0 = WINDIVERT_CONTEXT_PRIORITY(WINDIVERT_PRIORITY_DEFAULT); context->priority = context->priority_0; context->filter = NULL; for (i = 0; i < WINDIVERT_CONTEXT_MAXWORKERS; i++) { context->workers[i] = NULL; } context->worker_curr = 0; for (i = 0; i < WINDIVERT_CONTEXT_MAXLAYERS; i++) { context->installed[i] = FALSE; } context->filter_on = FALSE; KeInitializeSpinLock(&context->lock); InitializeListHead(&context->packet_queue); for (i = 0; i < WINDIVERT_CONTEXT_MAXLAYERS; i++) { status = ExUuidCreate(&context->callout_guid[i]); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create callout GUID", status); goto windivert_create_exit; } status = ExUuidCreate(&context->filter_guid[i]); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create filter GUID", status); goto windivert_create_exit; } } WDF_IO_QUEUE_CONFIG_INIT(&queue_config, WdfIoQueueDispatchManual); status = WdfIoQueueCreate(device, &queue_config, WDF_NO_OBJECT_ATTRIBUTES, &context->read_queue); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create I/O read queue", status); goto windivert_create_exit; } WDF_TIMER_CONFIG_INIT(&timer_config, windivert_timer); timer_config.AutomaticSerialization = TRUE; WDF_OBJECT_ATTRIBUTES_INIT(&obj_attrs); obj_attrs.ParentObject = (WDFOBJECT)object; status = WdfTimerCreate(&timer_config, &obj_attrs, &context->timer); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create packet time-out timer", status); goto windivert_create_exit; } WDF_WORKITEM_CONFIG_INIT(&item_config, windivert_read_service_work_item); item_config.AutomaticSerialization = FALSE; WDF_OBJECT_ATTRIBUTES_INIT(&obj_attrs); obj_attrs.ParentObject = (WDFOBJECT)object; for (i = 0; i < WINDIVERT_CONTEXT_MAXWORKERS; i++) { status = WdfWorkItemCreate(&item_config, &obj_attrs, context->workers + i); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create read service work item", status); goto windivert_create_exit; } } RtlZeroMemory(&session, sizeof(session)); session.flags |= FWPM_SESSION_FLAG_DYNAMIC; status = FwpmEngineOpen0(NULL, RPC_C_AUTHN_DEFAULT, NULL, &session, &context->engine_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create WFP engine handle", status); goto windivert_create_exit; } context->state = WINDIVERT_CONTEXT_STATE_OPEN; windivert_create_exit: // Clean-up on error: if (!NT_SUCCESS(status)) { context->state = WINDIVERT_CONTEXT_STATE_INVALID; if (context->read_queue != NULL) { WdfObjectDelete(context->read_queue); } if (context->timer != NULL) { WdfObjectDelete(context->timer); } for (i = 0; i < WINDIVERT_CONTEXT_MAXWORKERS; i++) { if (context->workers[i] != NULL) { WdfObjectDelete(context->workers[i]); } } if (context->engine_handle != NULL) { FwpmEngineClose0(context->engine_handle); } } WdfRequestComplete(request, status); } /* * Register all WFP callouts. */ static NTSTATUS windivert_install_callouts(context_t context, BOOL is_inbound, BOOL is_outbound, BOOL is_ipv4, BOOL is_ipv6) { UINT8 i, j; layer_t layers[WINDIVERT_CONTEXT_MAXLAYERS]; NTSTATUS status; i = 0; switch (context->layer) { case WINDIVERT_LAYER_NETWORK: if (is_inbound && is_ipv4) { layers[i++] = layer_inbound_network_ipv4; } if (is_outbound && is_ipv4) { layers[i++] = layer_outbound_network_ipv4; } if (is_inbound && is_ipv6) { layers[i++] = layer_inbound_network_ipv6; } if (is_outbound && is_ipv6) { layers[i++] = layer_outbound_network_ipv6; } break; case WINDIVERT_LAYER_NETWORK_FORWARD: if (is_ipv4) { layers[i++] = layer_forward_network_ipv4; } if (is_ipv6) { layers[i++] = layer_forward_network_ipv6; } break; default: return STATUS_INVALID_PARAMETER; } for (j = 0; j < i; j++) { status = windivert_install_callout(context, j, layers[j]); if (!NT_SUCCESS(status)) { goto windivert_install_callouts_exit; } } windivert_install_callouts_exit: if (!NT_SUCCESS(status)) { windivert_uninstall_callouts(context); } return status; } /* * Register a WFP callout. */ static NTSTATUS windivert_install_callout(context_t context, UINT idx, layer_t layer) { FWPS_CALLOUT0 scallout; FWPM_CALLOUT0 mcallout; FWPM_FILTER0 filter; UINT64 weight; NTSTATUS status; weight = WINDIVERT_FILTER_WEIGHT(context->priority); RtlZeroMemory(&scallout, sizeof(scallout)); scallout.calloutKey = context->callout_guid[idx]; scallout.classifyFn = layer->callout; scallout.notifyFn = windivert_notify_callout; scallout.flowDeleteFn = NULL; RtlZeroMemory(&mcallout, sizeof(mcallout)); mcallout.calloutKey = context->callout_guid[idx]; mcallout.displayData.name = layer->callout_name; mcallout.displayData.description = layer->callout_desc; mcallout.applicableLayer = layer->layer_guid; RtlZeroMemory(&filter, sizeof(filter)); filter.filterKey = context->filter_guid[idx]; filter.layerKey = layer->layer_guid; filter.displayData.name = layer->filter_name; filter.displayData.description = layer->filter_desc; filter.action.type = FWP_ACTION_CALLOUT_UNKNOWN; filter.action.calloutKey = context->callout_guid[idx]; filter.subLayerKey = layer->sublayer_guid; filter.weight.type = FWP_UINT64; filter.weight.uint64 = &weight; filter.rawContext = (UINT64)context; status = FwpsCalloutRegister0(WdfDeviceWdmGetDeviceObject(context->device), &scallout, NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to install WFP callout", status); return status; } status = FwpmTransactionBegin0(context->engine_handle, 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to begin WFP transaction", status); FwpsCalloutUnregisterByKey0(&context->callout_guid[idx]); return status; } status = FwpmCalloutAdd0(context->engine_handle, &mcallout, NULL, NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to add WFP callout", status); goto windivert_install_callout_error; } status = FwpmFilterAdd0(context->engine_handle, &filter, NULL, NULL); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to add WFP filter", status); goto windivert_install_callout_error; } status = FwpmTransactionCommit0(context->engine_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to commit WFP transaction", status); FwpsCalloutUnregisterByKey0(&context->callout_guid[idx]); return status; } context->installed[idx] = TRUE; return STATUS_SUCCESS; windivert_install_callout_error: FwpmTransactionAbort0(context->engine_handle); FwpsCalloutUnregisterByKey0(&context->callout_guid[idx]); return status; } /* * WinDivert uninstall callouts routine. */ static void windivert_uninstall_callouts(context_t context) { UINT i; NTSTATUS status; status = FwpmTransactionBegin0(context->engine_handle, 0); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to begin WFP transaction", status); return; } for (i = 0; i < WINDIVERT_CONTEXT_MAXLAYERS; i++) { if (!context->installed[i]) { continue; } status = FwpmFilterDeleteByKey0(context->engine_handle, &context->filter_guid[i]); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to delete filter", status); break; } status = FwpmCalloutDeleteByKey0(context->engine_handle, &context->callout_guid[i]); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to delete callout", status); break; } } if (!NT_SUCCESS(status)) { FwpmTransactionAbort0(context->engine_handle); return; } status = FwpmTransactionCommit0(context->engine_handle); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to commit WFP transaction", status); return; } for (i = 0; i < WINDIVERT_CONTEXT_MAXLAYERS; i++) { FwpsCalloutUnregisterByKey0(&context->callout_guid[i]); context->installed[i] = FALSE; } } /* * WinDivert old-packet cleanup routine. */ extern VOID windivert_timer(IN WDFTIMER timer) { KLOCK_QUEUE_HANDLE lock_handle; PLIST_ENTRY entry; WDFFILEOBJECT object = (WDFFILEOBJECT)WdfTimerGetParentObject(timer); context_t context = windivert_context_get(object); packet_t packet; if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_OPEN)) { return; } // DEBUG("TIMER (context=%p, ticktock=%u)", context, // context->timer_ticktock); // Sweep away old packets. KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); while (!IsListEmpty(&context->packet_queue)) { entry = RemoveHeadList(&context->packet_queue); packet = CONTAINING_RECORD(entry, struct packet_s, entry); if (packet->timer_ticktock == context->timer_ticktock) { InsertHeadList(&context->packet_queue, entry); break; } context->packet_queue_length--; KeReleaseInStackQueuedSpinLock(&lock_handle); // Packet is old, dispose of it. DEBUG("TIMEOUT (context=%p, packet=%p)", context, packet); windivert_free_packet(packet); KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); } KeReleaseInStackQueuedSpinLock(&lock_handle); context->timer_ticktock = !context->timer_ticktock; // Restart the timer. WdfTimerStart(context->timer, WDF_REL_TIMEOUT_IN_MS(context->timer_timeout)); } /* * Divert cleanup routine. */ extern VOID windivert_cleanup(IN WDFFILEOBJECT object) { KLOCK_QUEUE_HANDLE lock_handle; PLIST_ENTRY entry; UINT i; context_t context = windivert_context_get(object); packet_t packet; NTSTATUS status; DEBUG("CLEANUP: cleaning up WinDivert context (context=%p)", context); if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_OPEN)) { return; } WdfTimerStop(context->timer, TRUE); KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); context->state = WINDIVERT_CONTEXT_STATE_CLOSING; while (!IsListEmpty(&context->packet_queue)) { entry = RemoveHeadList(&context->packet_queue); KeReleaseInStackQueuedSpinLock(&lock_handle); packet = CONTAINING_RECORD(entry, struct packet_s, entry); windivert_free_packet(packet); KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); } KeReleaseInStackQueuedSpinLock(&lock_handle); WdfIoQueuePurge(context->read_queue, NULL, NULL); WdfObjectDelete(context->read_queue); WdfObjectDelete(context->timer); for (i = 0; i < WINDIVERT_CONTEXT_MAXWORKERS; i++) { WdfWorkItemFlush(context->workers[i]); WdfObjectDelete(context->workers[i]); } windivert_uninstall_callouts(context); FwpmEngineClose0(context->engine_handle); if (context->filter != NULL) { ExFreePoolWithTag(context->filter, WINDIVERT_TAG); context->filter = NULL; } } /* * WinDivert close routine. */ extern VOID windivert_close(IN WDFFILEOBJECT object) { context_t context = windivert_context_get(object); DEBUG("CLOSE: closing WinDivert context (context=%p)", context); if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_CLOSING)) { return; } context->state = WINDIVERT_CONTEXT_STATE_CLOSED; } /* * WinDivert read routine. */ static NTSTATUS windivert_read(context_t context, WDFREQUEST request) { NTSTATUS status = STATUS_SUCCESS; DEBUG("READ: reading diverted packet (context=%p, request=%p)", context, request); // Forward the request to the pending read queue: status = WdfRequestForwardToIoQueue(request, context->read_queue); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to forward I/O request to read queue", status); return status; } // Service the read request: windivert_read_service(context); return STATUS_SUCCESS; } /* * WinDivert read service worker. */ VOID windivert_read_service_work_item(IN WDFWORKITEM item) { WDFFILEOBJECT object = (WDFFILEOBJECT)WdfWorkItemGetParentObject(item); context_t context = windivert_context_get(object); if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_OPEN)) { return; } windivert_read_service(context); } /* * WinDivert read request service. */ static void windivert_read_service(context_t context) { PNET_BUFFER buffer; KLOCK_QUEUE_HANDLE lock_handle; WDFREQUEST request; PLIST_ENTRY entry; PMDL dst_mdl; PVOID dst, src; ULONG dst_len, src_len; NTSTATUS status; packet_t packet; req_context_t req_context; windivert_addr_t addr; DEBUG("windivert_read_service"); KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); while (context->state == WINDIVERT_CONTEXT_STATE_OPEN && !IsListEmpty(&context->packet_queue)) { status = WdfIoQueueRetrieveNextRequest(context->read_queue, &request); if (!NT_SUCCESS(status)) { break; } entry = RemoveHeadList(&context->packet_queue); context->packet_queue_length--; KeReleaseInStackQueuedSpinLock(&lock_handle); packet = CONTAINING_RECORD(entry, struct packet_s, entry); DEBUG("SERVICE: servicing read request (context=%p, request=%p, " "packet=%p)", context, request, packet); // We have now have a read request and a packet; service the read. status = WdfRequestRetrieveOutputWdmMdl(request, &dst_mdl); dst_len = 0; if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to retrieve output MDL", status); goto windivert_read_service_complete; } dst = MmGetSystemAddressForMdlSafe(dst_mdl, NormalPagePriority); if (dst == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to get address of output MDL", status); goto windivert_read_service_complete; } dst_len = MmGetMdlByteCount(dst_mdl); src_len = packet->data_len; dst_len = (src_len < dst_len? src_len: dst_len); src = packet->data; RtlCopyMemory(dst, src, dst_len); // Write the address information. req_context = windivert_req_context_get(request); addr = req_context->addr; if (addr != NULL) { addr->IfIdx = packet->if_idx; addr->SubIfIdx = packet->sub_if_idx; addr->Direction = packet->direction; } // Compute the IP/TCP/UDP checksums here (if required). if ((context->flags & WINDIVERT_FLAG_NO_CHECKSUM) == 0) { windivert_update_checksums(dst, dst_len, packet->ip_checksum, packet->tcp_checksum, packet->udp_checksum); } status = STATUS_SUCCESS; windivert_read_service_complete: windivert_free_packet(packet); if (NT_SUCCESS(status)) { WdfRequestCompleteWithInformation(request, status, dst_len); } else { WdfRequestComplete(request, status); } KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); } KeReleaseInStackQueuedSpinLock(&lock_handle); } /* * WinDivert write routine. */ static NTSTATUS windivert_write(context_t context, WDFREQUEST request, windivert_addr_t addr) { PMDL mdl = NULL, mdl_copy = NULL; PVOID data, data_copy = NULL; UINT data_len; struct iphdr *ip_header; struct ipv6hdr *ipv6_header; BOOL isipv4; HANDLE handle; PNET_BUFFER_LIST buffers = NULL; NTSTATUS status = STATUS_SUCCESS; DEBUG("WRITE: writing/injecting a packet (context=%p, request=%p)", context, request); if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_OPEN)) { status = STATUS_INVALID_DEVICE_STATE; goto windivert_write_exit; } if (addr->Direction != WINDIVERT_DIRECTION_INBOUND && addr->Direction != WINDIVERT_DIRECTION_OUTBOUND) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to inject packet; invalid direction", status); goto windivert_write_exit; } status = WdfRequestRetrieveOutputWdmMdl(request, &mdl); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to retrieve input MDL", status); goto windivert_write_exit; } data = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority); if (data == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to get MDL address", status); goto windivert_write_exit; } data_len = MmGetMdlByteCount(mdl); if (data_len > UINT16_MAX || data_len < sizeof(struct iphdr)) { windivert_write_bad_packet: status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to inject a bad packet", status); goto windivert_write_exit; } data_copy = ExAllocatePoolWithTag(NonPagedPool, data_len, WINDIVERT_TAG); if (data_copy == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to allocate memory for injected packet data", status); goto windivert_write_exit; } RtlCopyMemory(data_copy, data, sizeof(struct iphdr)); ip_header = (struct iphdr *)data_copy; switch (ip_header->Version) { case 4: if (data_len != RtlUshortByteSwap(ip_header->Length)) goto windivert_write_bad_packet; isipv4 = TRUE; break; case 6: if (data_len < sizeof(struct ipv6hdr)) goto windivert_write_bad_packet; ipv6_header = (struct ipv6hdr *)data_copy; if (data_len != RtlUshortByteSwap(ipv6_header->Length) + sizeof(struct ipv6hdr)) goto windivert_write_bad_packet; isipv4 = FALSE; break; default: goto windivert_write_bad_packet; } if (data_len > sizeof(struct iphdr)) { RtlCopyMemory((char *)data_copy + sizeof(struct iphdr), (char *)data + sizeof(struct iphdr), data_len - sizeof(struct iphdr)); } mdl_copy = IoAllocateMdl(data_copy, data_len, FALSE, FALSE, NULL); if (mdl_copy == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to allocate MDL for injected packet", status); goto windivert_write_exit; } MmBuildMdlForNonPagedPool(mdl_copy); status = FwpsAllocateNetBufferAndNetBufferList0(pool_handle, 0, 0, mdl_copy, 0, data_len, &buffers); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create NET_BUFFER_LIST for injected packet", status); goto windivert_write_exit; } handle = (isipv4? inject_handle: injectv6_handle); if (context->layer == WINDIVERT_LAYER_NETWORK_FORWARD) { status = FwpsInjectForwardAsync0(handle, (HANDLE)context->priority, 0, (isipv4? AF_INET: AF_INET6), UNSPECIFIED_COMPARTMENT_ID, addr->IfIdx, buffers, windivert_inject_complete, (HANDLE)request); } else if (addr->Direction == WINDIVERT_DIRECTION_OUTBOUND) { status = FwpsInjectNetworkSendAsync0(handle, (HANDLE)context->priority, 0, UNSPECIFIED_COMPARTMENT_ID, buffers, windivert_inject_complete, (HANDLE)request); } else { status = FwpsInjectNetworkReceiveAsync0(handle, (HANDLE)context->priority, 0, UNSPECIFIED_COMPARTMENT_ID, addr->IfIdx, addr->SubIfIdx, buffers, windivert_inject_complete, (HANDLE)request); } windivert_write_exit: if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to (re)inject packet", status); if (buffers != NULL) { FwpsFreeNetBufferList0(buffers); } if (mdl_copy != NULL) { IoFreeMdl(mdl_copy); } if (data_copy != NULL) { ExFreePoolWithTag(data_copy, WINDIVERT_TAG); } } return status; } /* * WinDivert inject complete routine. */ static void NTAPI windivert_inject_complete(VOID *context, NET_BUFFER_LIST *buffers, BOOLEAN dispatch_level) { WDFREQUEST request = (WDFREQUEST)context; PMDL mdl; PVOID data; PNET_BUFFER buffer; size_t length = 0; NTSTATUS status; UNREFERENCED_PARAMETER(dispatch_level); DEBUG("COMPLETE: write/inject packet complete (request=%p)", request); buffer = NET_BUFFER_LIST_FIRST_NB(buffers); status = NET_BUFFER_LIST_STATUS(buffers); if (NT_SUCCESS(status)) { length = NET_BUFFER_DATA_LENGTH(buffer); } else { DEBUG_ERROR("failed to inject packet", status); } mdl = NET_BUFFER_FIRST_MDL(buffer); data = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority); if (data != NULL) { ExFreePoolWithTag(data, WINDIVERT_TAG); } IoFreeMdl(mdl); FwpsFreeNetBufferList0(buffers); WdfRequestCompleteWithInformation(request, status, length); } /* * WinDivert caller context preprocessing. */ VOID windivert_caller_context(IN WDFDEVICE device, IN WDFREQUEST request) { PCHAR inbuf; size_t inbuflen; WDF_REQUEST_PARAMETERS params; WDFMEMORY memobj; windivert_addr_t addr = NULL; windivert_ioctl_t ioctl; WDF_OBJECT_ATTRIBUTES attributes; req_context_t req_context = NULL; NTSTATUS status; WDF_REQUEST_PARAMETERS_INIT(&params); WdfRequestGetParameters(request, &params); if (params.Type != WdfRequestTypeDeviceControl) { goto windivert_caller_context_exit; } // Get and verify the input buffer. status = WdfRequestRetrieveInputBuffer(request, 0, &inbuf, &inbuflen); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to retrieve input buffer", status); goto windivert_caller_context_error; } if (inbuflen != sizeof(struct windivert_ioctl_s)) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("input buffer not an ioctl message header", status); goto windivert_caller_context_error; } ioctl = (windivert_ioctl_t)inbuf; if (ioctl->version != WINDIVERT_IOCTL_VERSION || ioctl->magic != WINDIVERT_IOCTL_MAGIC) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("input buffer contained a bad ioctl message header", status); goto windivert_caller_context_error; } // Probe and lock user buffers here (if required). WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, req_context_s); status = WdfObjectAllocateContext(request, &attributes, &req_context); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to allocate request context for ioctl", status); goto windivert_caller_context_error; } switch (params.Parameters.DeviceIoControl.IoControlCode) { case IOCTL_WINDIVERT_RECV: if ((PVOID)ioctl->arg == NULL) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("null arg pointer for RECV ioctl", status); goto windivert_caller_context_error; } status = WdfRequestProbeAndLockUserBufferForWrite(request, (PVOID)ioctl->arg, sizeof(struct windivert_addr_s), &memobj); if (!NT_SUCCESS(status)) { DEBUG_ERROR("invalid arg pointer for RECV ioctl", status); goto windivert_caller_context_error; } addr = (windivert_addr_t)WdfMemoryGetBuffer(memobj, NULL); break; case IOCTL_WINDIVERT_SEND: if ((PVOID)ioctl->arg == NULL) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("null arg pointer for SEND ioctl", status); goto windivert_caller_context_error; } status = WdfRequestProbeAndLockUserBufferForRead(request, (PVOID)ioctl->arg, sizeof(struct windivert_addr_s), &memobj); if (!NT_SUCCESS(status)) { DEBUG_ERROR("invalid arg pointer for SEND ioctl", status); goto windivert_caller_context_error; } addr = (windivert_addr_t)WdfMemoryGetBuffer(memobj, NULL); break; case IOCTL_WINDIVERT_START_FILTER: case IOCTL_WINDIVERT_SET_LAYER: case IOCTL_WINDIVERT_SET_PRIORITY: case IOCTL_WINDIVERT_SET_FLAGS: case IOCTL_WINDIVERT_SET_PARAM: case IOCTL_WINDIVERT_GET_PARAM: break; default: status = STATUS_INVALID_DEVICE_REQUEST; DEBUG_ERROR("failed to complete I/O control; invalid request", status); goto windivert_caller_context_error; } req_context->addr = addr; windivert_caller_context_exit: status = WdfDeviceEnqueueRequest(device, request); windivert_caller_context_error: if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to enqueue request", status); WdfRequestComplete(request, status); } } /* * WinDivert I/O control. */ extern VOID windivert_ioctl(IN WDFQUEUE queue, IN WDFREQUEST request, IN size_t out_length, IN size_t in_length, IN ULONG code) { PCHAR inbuf, outbuf; size_t inbuflen, outbuflen, filter_len; windivert_ioctl_t ioctl; windivert_ioctl_filter_t filter; windivert_addr_t addr; req_context_t req_context; NTSTATUS status = STATUS_SUCCESS; context_t context = windivert_context_get(WdfRequestGetFileObject(request)); UINT64 value, *valptr; UNREFERENCED_PARAMETER(queue); DEBUG("IOCTL: I/O control request (context=%p)", context); if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_OPEN)) { status = STATUS_INVALID_DEVICE_STATE; goto windivert_ioctl_exit; } // Get the buffers and do sanity checks. status = WdfRequestRetrieveInputBuffer(request, 0, &inbuf, &inbuflen); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to retrieve input buffer", status); goto windivert_ioctl_exit; } switch (code) { case IOCTL_WINDIVERT_START_FILTER: case IOCTL_WINDIVERT_GET_PARAM: status = WdfRequestRetrieveOutputBuffer(request, 0, &outbuf, &outbuflen); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to retrieve output buffer", status); goto windivert_ioctl_exit; } break; default: outbuf = NULL; outbuflen = 0; break; } // Handle the ioctl: switch (code) { case IOCTL_WINDIVERT_RECV: status = windivert_read(context, request); if (NT_SUCCESS(status)) { return; } break; case IOCTL_WINDIVERT_SEND: req_context = windivert_req_context_get(request); addr = req_context->addr; status = windivert_write(context, request, addr); if (NT_SUCCESS(status)) { return; } break; case IOCTL_WINDIVERT_START_FILTER: { BOOL is_inbound, is_outbound, is_ipv4, is_ipv6; if (InterlockedExchange(&context->filter_on, TRUE) == TRUE) { status = STATUS_INVALID_DEVICE_STATE; DEBUG_ERROR("duplicate START_FILTER ioctl", status); goto windivert_ioctl_exit; } context->layer = context->layer_0; context->flags = context->flags_0; context->priority = context->priority_0; filter = (windivert_ioctl_filter_t)outbuf; filter_len = outbuflen; context->filter = windivert_filter_compile(filter, filter_len); if (context->filter == NULL) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to compile filter", status); goto windivert_ioctl_exit; } windivert_filter_analyze(context->filter, &is_inbound, &is_outbound, &is_ipv4, &is_ipv6); status = windivert_install_callouts(context, is_inbound, is_outbound, is_ipv4, is_ipv6); // Start the timer. WdfTimerStart(context->timer, WDF_REL_TIMEOUT_IN_MS(context->timer_timeout)); break; } case IOCTL_WINDIVERT_SET_LAYER: ioctl = (windivert_ioctl_t)inbuf; if (ioctl->arg > WINDIVERT_LAYER_MAX) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to set layer; value too big", status); goto windivert_ioctl_exit; } context->layer_0 = (UINT8)ioctl->arg; break; case IOCTL_WINDIVERT_SET_PRIORITY: ioctl = (windivert_ioctl_t)inbuf; if (ioctl->arg < WINDIVERT_PRIORITY_MIN || ioctl->arg > WINDIVERT_PRIORITY_MAX) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to set priority; value out of range", status); goto windivert_ioctl_exit; } context->priority_0 = WINDIVERT_CONTEXT_PRIORITY((UINT32)ioctl->arg); break; case IOCTL_WINDIVERT_SET_FLAGS: ioctl = (windivert_ioctl_t)inbuf; if (!WINDIVERT_FLAGS_VALID(ioctl->arg)) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to set flags; invalid flags value", status); goto windivert_ioctl_exit; } context->flags_0 = ioctl->arg; break; case IOCTL_WINDIVERT_SET_PARAM: ioctl = (windivert_ioctl_t)inbuf; value = ioctl->arg; switch ((WINDIVERT_PARAM)ioctl->arg8) { case WINDIVERT_PARAM_QUEUE_LEN: if (value < WINDIVERT_PARAM_QUEUE_LEN_MIN || value > WINDIVERT_PARAM_QUEUE_LEN_MAX) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to set queue length; invalid " "value", status); goto windivert_ioctl_exit; } context->packet_queue_maxlength = (ULONG)value; break; case WINDIVERT_PARAM_QUEUE_TIME: if (value < WINDIVERT_PARAM_QUEUE_TIME_MIN || value > WINDIVERT_PARAM_QUEUE_TIME_MAX) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to set queue time; invalid " "value", status); goto windivert_ioctl_exit; } context->timer_timeout = (UINT)value; break; default: status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to set parameter; invalid parameter", status); goto windivert_ioctl_exit; } break; case IOCTL_WINDIVERT_GET_PARAM: ioctl = (windivert_ioctl_t)inbuf; if (outbuflen != sizeof(UINT64)) { status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to get parameter; invalid output " "buffer size", status); goto windivert_ioctl_exit; } valptr = (UINT64 *)outbuf; switch ((WINDIVERT_PARAM)ioctl->arg8) { case WINDIVERT_PARAM_QUEUE_LEN: *valptr = context->packet_queue_maxlength; break; case WINDIVERT_PARAM_QUEUE_TIME: *valptr = context->timer_timeout; break; default: status = STATUS_INVALID_PARAMETER; DEBUG_ERROR("failed to get parameter; invalid parameter", status); goto windivert_ioctl_exit; } break; default: status = STATUS_INVALID_DEVICE_REQUEST; DEBUG_ERROR("failed to complete I/O control; invalid request", status); break; } windivert_ioctl_exit: WdfRequestComplete(request, status); } /* * WinDivert notify callout. */ static NTSTATUS windivert_notify_callout(IN FWPS_CALLOUT_NOTIFY_TYPE type, IN const GUID *filter_key, IN const FWPS_FILTER0 *filter) { UNREFERENCED_PARAMETER(type); UNREFERENCED_PARAMETER(filter_key); UNREFERENCED_PARAMETER(filter); return STATUS_SUCCESS; } /* * WinDivert classify outbound IPv4 callout. */ static void windivert_classify_outbound_network_v4_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { windivert_classify_callout(WINDIVERT_DIRECTION_OUTBOUND, fixed_vals->incomingValue[ FWPS_FIELD_OUTBOUND_IPPACKET_V4_INTERFACE_INDEX].value.uint32, fixed_vals->incomingValue[ FWPS_FIELD_OUTBOUND_IPPACKET_V4_SUB_INTERFACE_INDEX].value.uint32, TRUE, fixed_vals, meta_vals, data, filter, flow_context, result); } /* * WinDivert classify outbound IPv6 callout. */ static void windivert_classify_outbound_network_v6_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { windivert_classify_callout(WINDIVERT_DIRECTION_OUTBOUND, fixed_vals->incomingValue[ FWPS_FIELD_OUTBOUND_IPPACKET_V6_INTERFACE_INDEX].value.uint32, fixed_vals->incomingValue[ FWPS_FIELD_OUTBOUND_IPPACKET_V6_SUB_INTERFACE_INDEX].value.uint32, FALSE, fixed_vals, meta_vals, data, filter, flow_context, result); } /* * WinDivert classify inbound IPv4 callout. */ static void windivert_classify_inbound_network_v4_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { PNET_BUFFER_LIST buffers = (PNET_BUFFER_LIST)data; PNET_BUFFER buffer; NTSTATUS status; if (!(result->rights & FWPS_RIGHT_ACTION_WRITE) || data == NULL) { return; } buffer = NET_BUFFER_LIST_FIRST_NB(buffers); status = NdisRetreatNetBufferDataStart(buffer, meta_vals->ipHeaderSize, 0, NULL); if (!NT_SUCCESS(status)) { result->actionType = FWP_ACTION_CONTINUE; return; } windivert_classify_callout(WINDIVERT_DIRECTION_INBOUND, fixed_vals->incomingValue[ FWPS_FIELD_INBOUND_IPPACKET_V4_INTERFACE_INDEX].value.uint32, fixed_vals->incomingValue[ FWPS_FIELD_INBOUND_IPPACKET_V4_SUB_INTERFACE_INDEX].value.uint32, TRUE, fixed_vals, meta_vals, data, filter, flow_context, result); if (result->actionType != FWP_ACTION_BLOCK) { NdisAdvanceNetBufferDataStart(buffer, meta_vals->ipHeaderSize, FALSE, NULL); } } /* * WinDivert classify inbound IPv6 callout. */ static void windivert_classify_inbound_network_v6_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { PNET_BUFFER_LIST buffers = (PNET_BUFFER_LIST)data; PNET_BUFFER buffer; NTSTATUS status; if (!(result->rights & FWPS_RIGHT_ACTION_WRITE) || data == NULL) { return; } buffer = NET_BUFFER_LIST_FIRST_NB(buffers); status = NdisRetreatNetBufferDataStart(buffer, sizeof(struct ipv6hdr), 0, NULL); if (!NT_SUCCESS(status)) { result->actionType = FWP_ACTION_CONTINUE; return; } windivert_classify_callout(WINDIVERT_DIRECTION_INBOUND, fixed_vals->incomingValue[ FWPS_FIELD_INBOUND_IPPACKET_V6_INTERFACE_INDEX].value.uint32, fixed_vals->incomingValue[ FWPS_FIELD_INBOUND_IPPACKET_V6_SUB_INTERFACE_INDEX].value.uint32, FALSE, fixed_vals, meta_vals, data, filter, flow_context, result); if (result->actionType != FWP_ACTION_BLOCK) { NdisAdvanceNetBufferDataStart(buffer, sizeof(struct ipv6hdr), FALSE, NULL); } } /* * WinDivert classify forward IPv4 callout. */ static void windivert_classify_forward_network_v4_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { windivert_classify_callout(WINDIVERT_DIRECTION_OUTBOUND, fixed_vals->incomingValue[ FWPS_FIELD_IPFORWARD_V4_DESTINATION_INTERFACE_INDEX].value.uint32, 0, TRUE, fixed_vals, meta_vals, data, filter, flow_context, result); } /* * WinDivert classify forward IPv6 callout. */ static void windivert_classify_forward_network_v6_callout( IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { windivert_classify_callout(WINDIVERT_DIRECTION_OUTBOUND, fixed_vals->incomingValue[ FWPS_FIELD_IPFORWARD_V6_DESTINATION_INTERFACE_INDEX].value.uint32, 0, FALSE, fixed_vals, meta_vals, data, filter, flow_context, result); } /* * WinDivert classify callout. */ static void windivert_classify_callout(IN UINT8 direction, IN UINT32 if_idx, IN UINT32 sub_if_idx, IN BOOL isipv4, IN const FWPS_INCOMING_VALUES0 *fixed_vals, IN const FWPS_INCOMING_METADATA_VALUES0 *meta_vals, IN OUT void *data, const FWPS_FILTER0 *filter, IN UINT64 flow_context, OUT FWPS_CLASSIFY_OUT0 *result) { KLOCK_QUEUE_HANDLE lock_handle; FWPS_PACKET_INJECTION_STATE packet_state; HANDLE packet_context; UINT32 priority; PNET_BUFFER_LIST buffers; PNET_BUFFER buffer, buffer_fst, buffer_itr; BOOL outbound, queued; context_t context; packet_t packet; ULONG read_queue_len; // Basic checks: if (!(result->rights & FWPS_RIGHT_ACTION_WRITE) || data == NULL) { return; } context = (context_t)filter->context; if (!windivert_context_verify(context, WINDIVERT_CONTEXT_STATE_OPEN)) { result->actionType = FWP_ACTION_CONTINUE; return; } buffers = (PNET_BUFFER_LIST)data; buffer = NET_BUFFER_LIST_FIRST_NB(buffers); if (NET_BUFFER_LIST_NEXT_NBL(buffers) != NULL) { /* * This is a fragment group. This can be ignored since each * fragment should already have been indicated. */ result->actionType = FWP_ACTION_CONTINUE; return; } if (isipv4) { packet_state = FwpsQueryPacketInjectionState0(inject_handle, buffers, &packet_context); } else { packet_state = FwpsQueryPacketInjectionState0(injectv6_handle, buffers, &packet_context); } if (packet_state == FWPS_PACKET_INJECTED_BY_SELF || packet_state == FWPS_PACKET_PREVIOUSLY_INJECTED_BY_SELF) { priority = (UINT32)packet_context; if (priority >= context->priority) { result->actionType = FWP_ACTION_CONTINUE; return; } } /* * This code is complicated by the fact the a single NET_BUFFER_LIST * may contain several NET_BUFFER structures. Each NET_BUFFER needs to * be filtered independently. To achieve this we do the following: * 1) First check if any NET_BUFFER passes the filter. * 2) If no, then CONTINUE the entire NET_BUFFER_LIST. * 3) Else, split the NET_BUFFER_LIST into individual NET_BUFFERs; and * either queue or re-inject based on the filter. */ // Find the first NET_BUFFER we need to queue: buffer_fst = buffer; outbound = (direction == WINDIVERT_DIRECTION_OUTBOUND); do { if (windivert_filter(buffer_fst, if_idx, sub_if_idx, outbound, context->filter)) { break; } buffer_fst = NET_BUFFER_NEXT_NB(buffer_fst); } while (buffer_fst != NULL); if (buffer_fst == NULL) { result->actionType = FWP_ACTION_CONTINUE; return; } if ((context->flags & WINDIVERT_FLAG_SNIFF) == 0) { // Re-inject all packets up to 'buffer_fst' buffer_itr = buffer; while (buffer_itr != buffer_fst) { if (!windivert_reinject_packet(context, direction, isipv4, if_idx, sub_if_idx, priority, buffer_itr)) { goto windivert_classify_callout_exit; } buffer_itr = NET_BUFFER_NEXT_NB(buffer_itr); } } else { buffer_itr = buffer_fst; } queued = FALSE; if ((context->flags & WINDIVERT_FLAG_DROP) == 0) { if (!windivert_queue_packet(context, buffer_itr, buffers, direction, if_idx, sub_if_idx)) { goto windivert_classify_callout_exit; } queued = TRUE; } // Queue or re-inject remaining packets. buffer_itr = NET_BUFFER_NEXT_NB(buffer_itr); while (buffer_itr != NULL) { if (windivert_filter(buffer_itr, if_idx, sub_if_idx, outbound, context->filter)) { if ((context->flags & WINDIVERT_FLAG_DROP) == 0) { if (!windivert_queue_packet(context, buffer_itr, buffers, direction, if_idx, sub_if_idx)) { goto windivert_classify_callout_exit; } queued = TRUE; } } else if ((context->flags & WINDIVERT_FLAG_SNIFF) == 0) { if (!windivert_reinject_packet(context, direction, isipv4, if_idx, sub_if_idx, priority, buffer_itr)) { goto windivert_classify_callout_exit; } } buffer_itr = NET_BUFFER_NEXT_NB(buffer_itr); } /* * If the packet was queued, then service any pending read. */ if (queued) { KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); if (context->state == WINDIVERT_CONTEXT_STATE_OPEN) { WdfIoQueueGetState(context->read_queue, &read_queue_len, NULL); if (read_queue_len > 0) { WdfWorkItemEnqueue(context->workers[context->worker_curr]); context->worker_curr++; if (context->worker_curr >= WINDIVERT_CONTEXT_MAXWORKERS) { context->worker_curr = 0; } } } KeReleaseInStackQueuedSpinLock(&lock_handle); } windivert_classify_callout_exit: if ((context->flags & WINDIVERT_FLAG_SNIFF) != 0) { result->actionType = FWP_ACTION_CONTINUE; } else { result->actionType = FWP_ACTION_BLOCK; result->flags |= FWPS_CLASSIFY_OUT_FLAG_ABSORB; result->rights &= ~FWPS_RIGHT_ACTION_WRITE; } } /* * Queue a NET_BUFFER. */ static BOOL windivert_queue_packet(context_t context, PNET_BUFFER buffer, PNET_BUFFER_LIST buffers, UINT8 direction, UINT32 if_idx, UINT32 sub_if_idx) { KLOCK_QUEUE_HANDLE lock_handle; NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO checksum_info; PVOID data; PLIST_ENTRY entry; packet_t packet; UINT data_len; NTSTATUS status; data_len = NET_BUFFER_DATA_LENGTH(buffer); packet = (packet_t)ExAllocatePoolWithTag(NonPagedPool, WINDIVERT_PACKET_SIZE + data_len, WINDIVERT_TAG); if (packet == NULL) { return FALSE; } packet->net_buffer_list = NULL; packet->data_len = data_len; data = NdisGetDataBuffer(buffer, data_len, NULL, 1, 0); if (data == NULL) { NdisGetDataBuffer(buffer, data_len, packet->data, 1, 0); } else { RtlCopyMemory(packet->data, data, data_len); } checksum_info.Value = NET_BUFFER_LIST_INFO(buffers, TcpIpChecksumNetBufferListInfo); packet->direction = direction; packet->if_idx = if_idx; packet->sub_if_idx = sub_if_idx; if (direction == WINDIVERT_DIRECTION_OUTBOUND) { // IPv4 Checksum is not calculated yet packet->ip_checksum = TRUE; packet->tcp_checksum = (BOOL)checksum_info.Transmit.TcpChecksum; packet->udp_checksum = (BOOL)checksum_info.Transmit.UdpChecksum; } else { packet->ip_checksum = FALSE; packet->tcp_checksum = FALSE; packet->udp_checksum = FALSE; } packet->timer_ticktock = context->timer_ticktock; entry = &packet->entry; KeAcquireInStackQueuedSpinLock(&context->lock, &lock_handle); if (context->state != WINDIVERT_CONTEXT_STATE_OPEN) { // We are no longer open KeReleaseInStackQueuedSpinLock(&lock_handle); windivert_free_packet(packet); return FALSE; } InsertTailList(&context->packet_queue, entry); entry = NULL; context->packet_queue_length++; if (context->packet_queue_length > context->packet_queue_maxlength) { entry = RemoveHeadList(&context->packet_queue); context->packet_queue_length--; } KeReleaseInStackQueuedSpinLock(&lock_handle); if (entry != NULL) { // Queue is full; 'entry' contains a dropped packet. DEBUG("DROP: packet queue is full, dropping packet"); packet = CONTAINING_RECORD(entry, struct packet_s, entry); windivert_free_packet(packet); } DEBUG("PACKET: diverting packet (packet=%p)", packet); return TRUE; } /* * Re-inject a NET_BUFFER. */ static BOOL windivert_reinject_packet(context_t context, UINT8 direction, BOOL isipv4, UINT32 if_idx, UINT32 sub_if_idx, UINT32 priority, PNET_BUFFER buffer) { UINT data_len; PVOID data, data_copy = NULL; PNET_BUFFER_LIST buffers = NULL; PMDL mdl_copy = NULL; HANDLE handle; NTSTATUS status = STATUS_SUCCESS; data_len = NET_BUFFER_DATA_LENGTH(buffer); data_copy = ExAllocatePoolWithTag(NonPagedPool, data_len, WINDIVERT_TAG); if (data_copy == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to allocate memory for (re)injected packet data", status); return FALSE; } data = NdisGetDataBuffer(buffer, data_len, NULL, 1, 0); if (data == NULL) { NdisGetDataBuffer(buffer, data_len, data_copy, 1, 0); } else { RtlCopyMemory(data_copy, data, data_len); } mdl_copy = IoAllocateMdl(data_copy, data_len, FALSE, FALSE, NULL); if (mdl_copy == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; DEBUG_ERROR("failed to allocate MDL for injected packet", status); goto windivert_reinject_packet_exit; } MmBuildMdlForNonPagedPool(mdl_copy); status = FwpsAllocateNetBufferAndNetBufferList0(pool_handle, 0, 0, mdl_copy, 0, data_len, &buffers); if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to create NET_BUFFER_LIST for injected packet", status); goto windivert_reinject_packet_exit; } handle = (isipv4? inject_handle: injectv6_handle); if (context->layer == WINDIVERT_LAYER_NETWORK_FORWARD) { status = FwpsInjectForwardAsync0(handle, (HANDLE)priority, 0, (isipv4? AF_INET: AF_INET6), UNSPECIFIED_COMPARTMENT_ID, if_idx, buffers, windivert_reinject_complete, (HANDLE)NULL); } else if (direction == WINDIVERT_DIRECTION_OUTBOUND) { status = FwpsInjectNetworkSendAsync0(handle, (HANDLE)priority, 0, UNSPECIFIED_COMPARTMENT_ID, buffers, windivert_reinject_complete, (HANDLE)NULL); } else { status = FwpsInjectNetworkReceiveAsync0(handle, (HANDLE)priority, 0, UNSPECIFIED_COMPARTMENT_ID, if_idx, sub_if_idx, buffers, windivert_reinject_complete, (HANDLE)NULL); } windivert_reinject_packet_exit: if (!NT_SUCCESS(status)) { DEBUG_ERROR("failed to (re)inject packet", status); if (buffers != NULL) { FwpsFreeNetBufferList0(buffers); } if (mdl_copy != NULL) { IoFreeMdl(mdl_copy); } if (data_copy != NULL) { ExFreePoolWithTag(data_copy, WINDIVERT_TAG); } } return NT_SUCCESS(status); } /* * WinDivert (re)inject complete. */ static void NTAPI windivert_reinject_complete(VOID *context, NET_BUFFER_LIST *buffers, BOOLEAN dispatch_level) { PMDL mdl; PVOID data; PNET_BUFFER buffer = NET_BUFFER_LIST_FIRST_NB(buffers); mdl = NET_BUFFER_FIRST_MDL(buffer); data = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority); if (data != NULL) { ExFreePoolWithTag(data, WINDIVERT_TAG); } IoFreeMdl(mdl); FwpsFreeNetBufferList0(buffers); } /* * Free a packet. */ static void windivert_free_packet(packet_t packet) { if (packet->net_buffer_list != NULL) { FwpsFreeCloneNetBufferList0(packet->net_buffer_list, 0); } ExFreePoolWithTag(packet, WINDIVERT_TAG); } /* * Generic checksum calculation. */ static UINT16 windivert_checksum(const void *pseudo_header, size_t pseudo_header_len, const void *data, size_t len) { register const UINT16 *data16 = (const UINT16 *)pseudo_header; register size_t len16 = pseudo_header_len >> 1; register UINT32 sum = 0; size_t i; for (i = 0; i < len16; i++) { sum += (UINT32)data16[i]; } data16 = (const UINT16 *)data; len16 = len >> 1; for (i = 0; i < len16; i++) { sum += (UINT32)data16[i]; } if (len & 0x1) { const UINT8 *data8 = (const UINT8 *)data; sum += (UINT32)data8[len-1]; } sum = (sum & 0xFFFF) + (sum >> 16); sum += (sum >> 16); sum = ~sum; return (UINT16)sum; } /* * Given a well-formed packet, update the IP and/or TCP/UDP checksums if * required. */ static void windivert_update_checksums(void *header, size_t len, BOOL update_ip, BOOL update_tcp, BOOL update_udp) { struct { UINT32 SrcAddr; UINT32 DstAddr; UINT8 Zero; UINT8 Protocol; UINT16 TransLength; } pseudo_header; struct iphdr *ip_header = (struct iphdr *)header; size_t ip_header_len, trans_len; void *trans_header; struct tcphdr *tcp_header; struct udphdr *udp_header; UINT16 *trans_check_ptr; UINT sum; if (!update_ip && !update_tcp && !update_udp) { return; } if (len < sizeof(struct iphdr)) { return; } if (ip_header->Version != 4) { return; } ip_header_len = ip_header->HdrLength*sizeof(UINT32); if (len < ip_header_len) { return; } if (update_ip) { ip_header->Checksum = 0; ip_header->Checksum = windivert_checksum(NULL, 0, ip_header, ip_header_len); } trans_len = RtlUshortByteSwap(ip_header->Length) - ip_header_len; trans_header = (UINT8 *)ip_header + ip_header_len; switch (ip_header->Protocol) { case IPPROTO_TCP: if (!update_tcp) { return; } tcp_header = (struct tcphdr *)trans_header; if (trans_len < sizeof(struct tcphdr)) { return; } trans_check_ptr = &tcp_header->Checksum; break; case IPPROTO_UDP: if (!update_udp) { return; } udp_header = (struct udphdr *)trans_header; if (trans_len < sizeof(struct udphdr)) { return; } trans_check_ptr = &udp_header->Checksum; break; default: return; } pseudo_header.SrcAddr = ip_header->SrcAddr; pseudo_header.DstAddr = ip_header->DstAddr; pseudo_header.Zero = 0x0; pseudo_header.Protocol = ip_header->Protocol; pseudo_header.TransLength = RtlUshortByteSwap((UINT16)trans_len); *trans_check_ptr = 0x0; sum = windivert_checksum(&pseudo_header, sizeof(pseudo_header), trans_header, trans_len); if (sum == 0 && ip_header->Protocol == IPPROTO_UDP) { *trans_check_ptr = 0xFFFF; } else { *trans_check_ptr = (UINT16)sum; } } /* * Checks if the given packet is of interest. */ static BOOL windivert_filter(PNET_BUFFER buffer, UINT32 if_idx, UINT32 sub_if_idx, BOOL outbound, filter_t filter) { // Buffer contains enough space for a full size iphdr and tcphdr/udphdr // (without options) UINT8 storage[0xF*sizeof(UINT32) + sizeof(struct tcphdr)]; UINT8 *headers; size_t tot_len, cpy_len, ip_header_len; struct iphdr *ip_header = NULL; struct ipv6hdr *ipv6_header = NULL; struct icmphdr *icmp_header = NULL; struct icmpv6hdr *icmpv6_header = NULL; struct tcphdr *tcp_header = NULL; struct udphdr *udp_header = NULL; UINT16 ip, ttl; UINT8 protocol; // Parse the headers: tot_len = NET_BUFFER_DATA_LENGTH(buffer); if (tot_len < sizeof(struct iphdr)) { DEBUG("FILTER: REJECT (packet length too small)"); return FALSE; } cpy_len = (tot_len < sizeof(storage)? tot_len: sizeof(storage)); headers = (UINT8 *)NdisGetDataBuffer(buffer, (ULONG)cpy_len, storage, 1, 0); if (headers == NULL) { headers = storage; } ip_header = (struct iphdr *)headers; switch (ip_header->Version) { case 4: ip_header_len = ip_header->HdrLength*sizeof(UINT32); if (RtlUshortByteSwap(ip_header->Length) != tot_len || ip_header->HdrLength < 5 || ip_header_len > tot_len) { DEBUG("FILTER: REJECT (bad IPv4 packet)"); return FALSE; } protocol = ip_header->Protocol; break; case 6: ip_header = NULL; ipv6_header = (struct ipv6hdr *)headers; ip_header_len = sizeof(struct ipv6hdr); if (ip_header_len > tot_len || RtlUshortByteSwap(ipv6_header->Length) + sizeof(struct ipv6hdr) != tot_len) { DEBUG("FILTER: REJECT (bad IPv6 packet)"); return FALSE; } protocol = ipv6_header->NextHdr; break; default: DEBUG("FILTER: REJECT (packet is neither IPv4 nor IPv6)"); return FALSE; } switch (protocol) { case IPPROTO_ICMP: icmp_header = (struct icmphdr *)(headers + ip_header_len); if (ip_header == NULL || sizeof(struct icmphdr) + ip_header_len > tot_len) { DEBUG("FILTER: REJECT (bad ICMP packet)"); return FALSE; } break; case IPPROTO_ICMPV6: icmpv6_header = (struct icmpv6hdr *)(headers + ip_header_len); if (ipv6_header == NULL || sizeof(struct icmpv6hdr) + ip_header_len > tot_len) { DEBUG("FILTER: REJECT (bad ICMPV6 packet)"); return FALSE; } break; case IPPROTO_TCP: tcp_header = (struct tcphdr *)(headers + ip_header_len); if (tcp_header->HdrLength < 5 || tcp_header->HdrLength*sizeof(UINT32) + ip_header_len > tot_len) { DEBUG("FILTER: REJECT (bad TCP packet)"); return FALSE; } break; case IPPROTO_UDP: udp_header = (struct udphdr *)(headers + ip_header_len); if (sizeof(struct udphdr) + ip_header_len > tot_len) { DEBUG("FILTER: REJECT (bad UDP packet)"); return FALSE; } break; default: break; } // Execute the filter: ip = 0; ttl = WINDIVERT_FILTER_MAXLEN+1; // Additional safety while (ttl-- != 0) { BOOL result; UINT32 field[4]; field[1] = 0; field[2] = 0; field[3] = 0; switch (filter[ip].protocol) { case WINDIVERT_FILTER_PROTOCOL_NONE: result = TRUE; break; case WINDIVERT_FILTER_PROTOCOL_IP: result = (ip_header != NULL); break; case WINDIVERT_FILTER_PROTOCOL_IPV6: result = (ipv6_header != NULL); break; case WINDIVERT_FILTER_PROTOCOL_ICMP: result = (icmp_header != NULL); break; case WINDIVERT_FILTER_PROTOCOL_ICMPV6: result = (icmpv6_header != NULL); break; case WINDIVERT_FILTER_PROTOCOL_TCP: result = (tcp_header != NULL); break; case WINDIVERT_FILTER_PROTOCOL_UDP: result = (udp_header != NULL); break; default: result = FALSE; break; } if (result) { switch (filter[ip].field) { case WINDIVERT_FILTER_FIELD_ZERO: field[0] = 0; break; case WINDIVERT_FILTER_FIELD_INBOUND: field[0] = (UINT32)(!outbound); break; case WINDIVERT_FILTER_FIELD_OUTBOUND: field[0] = (UINT32)outbound; break; case WINDIVERT_FILTER_FIELD_IFIDX: field[0] = (UINT32)if_idx; break; case WINDIVERT_FILTER_FIELD_SUBIFIDX: field[0] = (UINT32)sub_if_idx; break; case WINDIVERT_FILTER_FIELD_IP: field[0] = (UINT32)(ip_header != NULL); break; case WINDIVERT_FILTER_FIELD_IPV6: field[0] = (UINT32)(ipv6_header != NULL); break; case WINDIVERT_FILTER_FIELD_ICMP: field[0] = (UINT32)(icmp_header != NULL); break; case WINDIVERT_FILTER_FIELD_ICMPV6: field[0] = (UINT32)(icmpv6_header != NULL); break; case WINDIVERT_FILTER_FIELD_TCP: field[0] = (UINT32)(tcp_header != NULL); break; case WINDIVERT_FILTER_FIELD_UDP: field[0] = (UINT32)(udp_header != NULL); break; case WINDIVERT_FILTER_FIELD_IP_HDRLENGTH: field[0] = (UINT32)ip_header->HdrLength; break; case WINDIVERT_FILTER_FIELD_IP_TOS: field[0] = (UINT32)RtlUshortByteSwap(ip_header->TOS); break; case WINDIVERT_FILTER_FIELD_IP_LENGTH: field[0] = (UINT32)RtlUshortByteSwap(ip_header->Length); break; case WINDIVERT_FILTER_FIELD_IP_ID: field[0] = (UINT32)RtlUshortByteSwap(ip_header->Id); break; case WINDIVERT_FILTER_FIELD_IP_DF: field[0] = (UINT32)IPHDR_GET_DF(ip_header); break; case WINDIVERT_FILTER_FIELD_IP_MF: field[0] = (UINT32)IPHDR_GET_MF(ip_header); break; case WINDIVERT_FILTER_FIELD_IP_FRAGOFF: field[0] = (UINT32)RtlUshortByteSwap( IPHDR_GET_FRAGOFF(ip_header)); break; case WINDIVERT_FILTER_FIELD_IP_TTL: field[0] = (UINT32)ip_header->TTL; break; case WINDIVERT_FILTER_FIELD_IP_PROTOCOL: field[0] = (UINT32)ip_header->Protocol; break; case WINDIVERT_FILTER_FIELD_IP_CHECKSUM: field[0] = (UINT32)RtlUshortByteSwap(ip_header->Checksum); break; case WINDIVERT_FILTER_FIELD_IP_SRCADDR: field[0] = (UINT32)RtlUlongByteSwap(ip_header->SrcAddr); break; case WINDIVERT_FILTER_FIELD_IP_DSTADDR: field[0] = (UINT32)RtlUlongByteSwap(ip_header->DstAddr); break; case WINDIVERT_FILTER_FIELD_IPV6_TRAFFICCLASS: field[0] = (UINT32)IPV6HDR_GET_TRAFFICCLASS(ipv6_header); break; case WINDIVERT_FILTER_FIELD_IPV6_FLOWLABEL: field[0] = (UINT32)RtlUlongByteSwap( IPV6HDR_GET_FLOWLABEL(ipv6_header)); break; case WINDIVERT_FILTER_FIELD_IPV6_LENGTH: field[0] = (UINT32)RtlUshortByteSwap(ipv6_header->Length); break; case WINDIVERT_FILTER_FIELD_IPV6_NEXTHDR: field[0] = (UINT32)ipv6_header->NextHdr; break; case WINDIVERT_FILTER_FIELD_IPV6_HOPLIMIT: field[0] = (UINT32)ipv6_header->HopLimit; break; case WINDIVERT_FILTER_FIELD_IPV6_SRCADDR: field[0] = (UINT32)RtlUlongByteSwap(ipv6_header->SrcAddr[3]); field[1] = (UINT32)RtlUlongByteSwap(ipv6_header->SrcAddr[2]); field[2] = (UINT32)RtlUlongByteSwap(ipv6_header->SrcAddr[1]); field[3] = (UINT32)RtlUlongByteSwap(ipv6_header->SrcAddr[0]); break; case WINDIVERT_FILTER_FIELD_IPV6_DSTADDR: field[0] = (UINT32)RtlUlongByteSwap(ipv6_header->DstAddr[3]); field[1] = (UINT32)RtlUlongByteSwap(ipv6_header->DstAddr[2]); field[2] = (UINT32)RtlUlongByteSwap(ipv6_header->DstAddr[1]); field[3] = (UINT32)RtlUlongByteSwap(ipv6_header->DstAddr[0]); break; case WINDIVERT_FILTER_FIELD_ICMP_TYPE: field[0] = (UINT32)icmp_header->Type; break; case WINDIVERT_FILTER_FIELD_ICMP_CODE: field[0] = (UINT32)icmp_header->Code; break; case WINDIVERT_FILTER_FIELD_ICMP_CHECKSUM: field[0] = (UINT32)RtlUshortByteSwap(icmp_header->Checksum); break; case WINDIVERT_FILTER_FIELD_ICMP_BODY: field[0] = (UINT32)RtlUlongByteSwap(icmp_header->Body); break; case WINDIVERT_FILTER_FIELD_ICMPV6_TYPE: field[0] = (UINT32)icmpv6_header->Type; break; case WINDIVERT_FILTER_FIELD_ICMPV6_CODE: field[0] = (UINT32)icmpv6_header->Code; break; case WINDIVERT_FILTER_FIELD_ICMPV6_CHECKSUM: field[0] = (UINT32)icmpv6_header->Checksum; break; case WINDIVERT_FILTER_FIELD_ICMPV6_BODY: field[0] = (UINT32)icmpv6_header->Body; break; case WINDIVERT_FILTER_FIELD_TCP_SRCPORT: field[0] = (UINT32)RtlUshortByteSwap(tcp_header->SrcPort); break; case WINDIVERT_FILTER_FIELD_TCP_DSTPORT: field[0] = (UINT32)RtlUshortByteSwap(tcp_header->DstPort); break; case WINDIVERT_FILTER_FIELD_TCP_SEQNUM: field[0] = (UINT32)RtlUlongByteSwap(tcp_header->SeqNum); break; case WINDIVERT_FILTER_FIELD_TCP_ACKNUM: field[0] = (UINT32)RtlUlongByteSwap(tcp_header->AckNum); break; case WINDIVERT_FILTER_FIELD_TCP_HDRLENGTH: field[0] = (UINT32)tcp_header->HdrLength; break; case WINDIVERT_FILTER_FIELD_TCP_URG: field[0] = (UINT32)tcp_header->Urg; break; case WINDIVERT_FILTER_FIELD_TCP_ACK: field[0] = (UINT32)tcp_header->Ack; break; case WINDIVERT_FILTER_FIELD_TCP_PSH: field[0] = (UINT32)tcp_header->Psh; break; case WINDIVERT_FILTER_FIELD_TCP_RST: field[0] = (UINT32)tcp_header->Rst; break; case WINDIVERT_FILTER_FIELD_TCP_SYN: field[0] = (UINT32)tcp_header->Syn; break; case WINDIVERT_FILTER_FIELD_TCP_FIN: field[0] = (UINT32)tcp_header->Fin; break; case WINDIVERT_FILTER_FIELD_TCP_WINDOW: field[0] = (UINT32)RtlUshortByteSwap(tcp_header->Window); break; case WINDIVERT_FILTER_FIELD_TCP_CHECKSUM: field[0] = (UINT32)RtlUshortByteSwap(tcp_header->Checksum); break; case WINDIVERT_FILTER_FIELD_TCP_URGPTR: field[0] = (UINT32)RtlUshortByteSwap(tcp_header->UrgPtr); break; case WINDIVERT_FILTER_FIELD_TCP_PAYLOADLENGTH: field[0] = (UINT32)(tot_len - ip_header_len - tcp_header->HdrLength*sizeof(UINT32)); break; case WINDIVERT_FILTER_FIELD_UDP_SRCPORT: field[0] = (UINT32)RtlUshortByteSwap(udp_header->SrcPort); break; case WINDIVERT_FILTER_FIELD_UDP_DSTPORT: field[0] = (UINT32)RtlUshortByteSwap(udp_header->DstPort); break; case WINDIVERT_FILTER_FIELD_UDP_LENGTH: field[0] = (UINT32)RtlUshortByteSwap(udp_header->Length); break; case WINDIVERT_FILTER_FIELD_UDP_CHECKSUM: field[0] = (UINT32)RtlUshortByteSwap(udp_header->Checksum); break; case WINDIVERT_FILTER_FIELD_UDP_PAYLOADLENGTH: field[0] = (UINT32)(tot_len - ip_header_len - sizeof(struct udphdr)); break; default: field[0] = 0; break; } switch (filter[ip].test) { case WINDIVERT_FILTER_TEST_EQ: result = (field[0] == filter[ip].arg[0] && field[1] == filter[ip].arg[1] && field[2] == filter[ip].arg[2] && field[3] == filter[ip].arg[3]); break; case WINDIVERT_FILTER_TEST_NEQ: result = (field[0] != filter[ip].arg[0] || field[1] != filter[ip].arg[1] || field[2] != filter[ip].arg[2] || field[3] != filter[ip].arg[3]); break; case WINDIVERT_FILTER_TEST_LT: result = (field[3] < filter[ip].arg[3] || (field[3] == filter[ip].arg[3] && field[2] < filter[ip].arg[2] || (field[2] == filter[ip].arg[2] && field[1] < filter[ip].arg[1] || (field[1] == filter[ip].arg[1] && field[0] < filter[ip].arg[0])))); break; case WINDIVERT_FILTER_TEST_LEQ: result = (field[3] < filter[ip].arg[3] || (field[3] == filter[ip].arg[3] && field[2] < filter[ip].arg[2] || (field[2] == filter[ip].arg[2] && field[1] < filter[ip].arg[1] || (field[1] == filter[ip].arg[1] && field[0] <= filter[ip].arg[0])))); break; case WINDIVERT_FILTER_TEST_GT: result = (field[3] > filter[ip].arg[3] || (field[3] == filter[ip].arg[3] && field[2] > filter[ip].arg[2] || (field[2] == filter[ip].arg[2] && field[1] > filter[ip].arg[1] || (field[1] == filter[ip].arg[1] && field[0] > filter[ip].arg[0])))); break; case WINDIVERT_FILTER_TEST_GEQ: result = (field[3] > filter[ip].arg[3] || (field[3] == filter[ip].arg[3] && field[2] > filter[ip].arg[2] || (field[2] == filter[ip].arg[2] && field[1] > filter[ip].arg[1] || (field[1] == filter[ip].arg[1] && field[0] >= filter[ip].arg[0])))); break; default: result = FALSE; break; } } ip = (result? filter[ip].success: filter[ip].failure); if (ip == WINDIVERT_FILTER_RESULT_ACCEPT) { return TRUE; } if (ip == WINDIVERT_FILTER_RESULT_REJECT) { return FALSE; } } DEBUG("FILTER: REJECT (filter TTL exceeded)"); return FALSE; } /* * Analyze the given filter. */ static void windivert_filter_analyze(filter_t filter, BOOL *is_inbound, BOOL *is_outbound, BOOL *is_ipv4, BOOL *is_ipv6) { BOOL result; // False filter? result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_ZERO, 0); if (!result) { *is_inbound = FALSE; *is_outbound = FALSE; *is_ipv4 = FALSE; *is_ipv6 = FALSE; return; } // Inbound? result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_INBOUND, 1); if (result) { result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_OUTBOUND, 0); } *is_inbound = result; // Outbound? result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_OUTBOUND, 1); if (result) { result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_INBOUND, 0); } *is_outbound = result; // IPv4? result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_IP, 1); if (result) { result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_IPV6, 0); } *is_ipv4 = result; // Ipv6? result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_IPV6, 1); if (result) { result = windivert_filter_test(filter, 0, WINDIVERT_FILTER_PROTOCOL_NONE, WINDIVERT_FILTER_FIELD_IP, 0); } *is_ipv6 = result; } /* * Test a filter for any packet where field = arg. */ static BOOL windivert_filter_test(filter_t filter, UINT16 ip, UINT8 protocol, UINT8 field, UINT32 arg) { BOOL known = FALSE; BOOL result = FALSE; if (ip == WINDIVERT_FILTER_RESULT_ACCEPT) { return TRUE; } if (ip == WINDIVERT_FILTER_RESULT_REJECT) { return FALSE; } if (ip > WINDIVERT_FILTER_MAXLEN) { return FALSE; } if (filter[ip].protocol == protocol && filter[ip].field == field) { known = TRUE; switch (filter[ip].test) { case WINDIVERT_FILTER_TEST_EQ: result = (arg == filter[ip].arg[0]); break; case WINDIVERT_FILTER_TEST_NEQ: result = (arg != filter[ip].arg[0]); break; case WINDIVERT_FILTER_TEST_LT: result = (arg < filter[ip].arg[0]); break; case WINDIVERT_FILTER_TEST_LEQ: result = (arg <= filter[ip].arg[0]); break; case WINDIVERT_FILTER_TEST_GT: result = (arg > filter[ip].arg[0]); break; case WINDIVERT_FILTER_TEST_GEQ: result = (arg >= filter[ip].arg[0]); break; default: result = FALSE; break; } } if (!known) { result = windivert_filter_test(filter, filter[ip].success, protocol, field, arg); if (result) { return TRUE; } return windivert_filter_test(filter, filter[ip].failure, protocol, field, arg); } else { ip = (result? filter[ip].success: filter[ip].failure); return windivert_filter_test(filter, ip, protocol, field, arg); } } /* * Compile a WinDivert filter from an IOCTL. */ static filter_t windivert_filter_compile(windivert_ioctl_filter_t ioctl_filter, size_t ioctl_filter_len) { filter_t filter0 = NULL, result = NULL; UINT16 i; size_t length; if (ioctl_filter_len % sizeof(struct windivert_ioctl_filter_s) != 0) { goto windivert_filter_compile_exit; } length = ioctl_filter_len / sizeof(struct windivert_ioctl_filter_s); if (length >= WINDIVERT_FILTER_MAXLEN) { goto windivert_filter_compile_exit; } // Do NOT use the stack (size = 12Kb on x86) for filter0. filter0 = (filter_t)ExAllocatePoolWithTag(NonPagedPool, WINDIVERT_FILTER_MAXLEN*sizeof(struct filter_s), WINDIVERT_TAG); if (filter0 == NULL) { goto windivert_filter_compile_exit; } for (i = 0; i < length; i++) { if (ioctl_filter[i].field > WINDIVERT_FILTER_FIELD_MAX || ioctl_filter[i].test > WINDIVERT_FILTER_TEST_MAX) { goto windivert_filter_compile_exit; } switch (ioctl_filter[i].success) { case WINDIVERT_FILTER_RESULT_ACCEPT: case WINDIVERT_FILTER_RESULT_REJECT: break; default: if (ioctl_filter[i].success <= i || ioctl_filter[i].success >= length) { goto windivert_filter_compile_exit; } break; } switch (ioctl_filter[i].failure) { case WINDIVERT_FILTER_RESULT_ACCEPT: case WINDIVERT_FILTER_RESULT_REJECT: break; default: if (ioctl_filter[i].failure <= i || ioctl_filter[i].failure >= length) { goto windivert_filter_compile_exit; } break; } // Enforce size limits: if (ioctl_filter[i].field != WINDIVERT_FILTER_FIELD_IPV6_SRCADDR && ioctl_filter[i].field != WINDIVERT_FILTER_FIELD_IPV6_DSTADDR) { if (ioctl_filter[i].arg[1] != 0 || ioctl_filter[i].arg[2] != 0 || ioctl_filter[i].arg[3] != 0) { goto windivert_filter_compile_exit; } } switch (ioctl_filter[i].field) { case WINDIVERT_FILTER_FIELD_ZERO: case WINDIVERT_FILTER_FIELD_INBOUND: case WINDIVERT_FILTER_FIELD_OUTBOUND: case WINDIVERT_FILTER_FIELD_IP: case WINDIVERT_FILTER_FIELD_IPV6: case WINDIVERT_FILTER_FIELD_ICMP: case WINDIVERT_FILTER_FIELD_ICMPV6: case WINDIVERT_FILTER_FIELD_TCP: case WINDIVERT_FILTER_FIELD_UDP: case WINDIVERT_FILTER_FIELD_IP_DF: case WINDIVERT_FILTER_FIELD_IP_MF: case WINDIVERT_FILTER_FIELD_TCP_URG: case WINDIVERT_FILTER_FIELD_TCP_ACK: case WINDIVERT_FILTER_FIELD_TCP_PSH: case WINDIVERT_FILTER_FIELD_TCP_RST: case WINDIVERT_FILTER_FIELD_TCP_SYN: case WINDIVERT_FILTER_FIELD_TCP_FIN: if (ioctl_filter[i].arg[0] > 1) { goto windivert_filter_compile_exit; } break; case WINDIVERT_FILTER_FIELD_IP_HDRLENGTH: case WINDIVERT_FILTER_FIELD_TCP_HDRLENGTH: if (ioctl_filter[i].arg[0] > 0x0F) { goto windivert_filter_compile_exit; } break; case WINDIVERT_FILTER_FIELD_IP_TTL: case WINDIVERT_FILTER_FIELD_IP_PROTOCOL: case WINDIVERT_FILTER_FIELD_IPV6_TRAFFICCLASS: case WINDIVERT_FILTER_FIELD_IPV6_NEXTHDR: case WINDIVERT_FILTER_FIELD_IPV6_HOPLIMIT: case WINDIVERT_FILTER_FIELD_ICMP_TYPE: case WINDIVERT_FILTER_FIELD_ICMP_CODE: case WINDIVERT_FILTER_FIELD_ICMPV6_TYPE: case WINDIVERT_FILTER_FIELD_ICMPV6_CODE: if (ioctl_filter[i].arg[0] > UINT8_MAX) { goto windivert_filter_compile_exit; } break; case WINDIVERT_FILTER_FIELD_IP_FRAGOFF: if (ioctl_filter[i].arg[0] > 0x1FFF) { goto windivert_filter_compile_exit; } break; case WINDIVERT_FILTER_FIELD_IP_TOS: case WINDIVERT_FILTER_FIELD_IP_LENGTH: case WINDIVERT_FILTER_FIELD_IP_ID: case WINDIVERT_FILTER_FIELD_IP_CHECKSUM: case WINDIVERT_FILTER_FIELD_IPV6_LENGTH: case WINDIVERT_FILTER_FIELD_ICMP_CHECKSUM: case WINDIVERT_FILTER_FIELD_ICMPV6_CHECKSUM: case WINDIVERT_FILTER_FIELD_TCP_SRCPORT: case WINDIVERT_FILTER_FIELD_TCP_DSTPORT: case WINDIVERT_FILTER_FIELD_TCP_WINDOW: case WINDIVERT_FILTER_FIELD_TCP_CHECKSUM: case WINDIVERT_FILTER_FIELD_TCP_URGPTR: case WINDIVERT_FILTER_FIELD_TCP_PAYLOADLENGTH: case WINDIVERT_FILTER_FIELD_UDP_SRCPORT: case WINDIVERT_FILTER_FIELD_UDP_DSTPORT: case WINDIVERT_FILTER_FIELD_UDP_LENGTH: case WINDIVERT_FILTER_FIELD_UDP_CHECKSUM: case WINDIVERT_FILTER_FIELD_UDP_PAYLOADLENGTH: if (ioctl_filter[i].arg[0] > UINT16_MAX) { goto windivert_filter_compile_exit; } break; case WINDIVERT_FILTER_FIELD_IPV6_FLOWLABEL: if (ioctl_filter[i].arg[0] > 0x000FFFFF) { goto windivert_filter_compile_exit; } break; default: break; } filter0[i].field = ioctl_filter[i].field; filter0[i].test = ioctl_filter[i].test; filter0[i].success = ioctl_filter[i].success; filter0[i].failure = ioctl_filter[i].failure; filter0[i].arg[0] = ioctl_filter[i].arg[0]; filter0[i].arg[1] = ioctl_filter[i].arg[1]; filter0[i].arg[2] = ioctl_filter[i].arg[2]; filter0[i].arg[3] = ioctl_filter[i].arg[3]; // Protocol selection: switch (ioctl_filter[i].field) { case WINDIVERT_FILTER_FIELD_ZERO: case WINDIVERT_FILTER_FIELD_INBOUND: case WINDIVERT_FILTER_FIELD_OUTBOUND: case WINDIVERT_FILTER_FIELD_IFIDX: case WINDIVERT_FILTER_FIELD_SUBIFIDX: case WINDIVERT_FILTER_FIELD_IP: case WINDIVERT_FILTER_FIELD_IPV6: case WINDIVERT_FILTER_FIELD_ICMP: case WINDIVERT_FILTER_FIELD_ICMPV6: case WINDIVERT_FILTER_FIELD_TCP: case WINDIVERT_FILTER_FIELD_UDP: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_NONE; break; case WINDIVERT_FILTER_FIELD_IP_HDRLENGTH: case WINDIVERT_FILTER_FIELD_IP_TOS: case WINDIVERT_FILTER_FIELD_IP_LENGTH: case WINDIVERT_FILTER_FIELD_IP_ID: case WINDIVERT_FILTER_FIELD_IP_DF: case WINDIVERT_FILTER_FIELD_IP_MF: case WINDIVERT_FILTER_FIELD_IP_FRAGOFF: case WINDIVERT_FILTER_FIELD_IP_TTL: case WINDIVERT_FILTER_FIELD_IP_PROTOCOL: case WINDIVERT_FILTER_FIELD_IP_CHECKSUM: case WINDIVERT_FILTER_FIELD_IP_SRCADDR: case WINDIVERT_FILTER_FIELD_IP_DSTADDR: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_IP; break; case WINDIVERT_FILTER_FIELD_IPV6_TRAFFICCLASS: case WINDIVERT_FILTER_FIELD_IPV6_FLOWLABEL: case WINDIVERT_FILTER_FIELD_IPV6_LENGTH: case WINDIVERT_FILTER_FIELD_IPV6_NEXTHDR: case WINDIVERT_FILTER_FIELD_IPV6_HOPLIMIT: case WINDIVERT_FILTER_FIELD_IPV6_SRCADDR: case WINDIVERT_FILTER_FIELD_IPV6_DSTADDR: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_IPV6; break; case WINDIVERT_FILTER_FIELD_ICMP_TYPE: case WINDIVERT_FILTER_FIELD_ICMP_CODE: case WINDIVERT_FILTER_FIELD_ICMP_CHECKSUM: case WINDIVERT_FILTER_FIELD_ICMP_BODY: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_ICMP; break; case WINDIVERT_FILTER_FIELD_ICMPV6_TYPE: case WINDIVERT_FILTER_FIELD_ICMPV6_CODE: case WINDIVERT_FILTER_FIELD_ICMPV6_CHECKSUM: case WINDIVERT_FILTER_FIELD_ICMPV6_BODY: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_ICMPV6; break; case WINDIVERT_FILTER_FIELD_TCP_SRCPORT: case WINDIVERT_FILTER_FIELD_TCP_DSTPORT: case WINDIVERT_FILTER_FIELD_TCP_SEQNUM: case WINDIVERT_FILTER_FIELD_TCP_ACKNUM: case WINDIVERT_FILTER_FIELD_TCP_HDRLENGTH: case WINDIVERT_FILTER_FIELD_TCP_URG: case WINDIVERT_FILTER_FIELD_TCP_ACK: case WINDIVERT_FILTER_FIELD_TCP_PSH: case WINDIVERT_FILTER_FIELD_TCP_RST: case WINDIVERT_FILTER_FIELD_TCP_SYN: case WINDIVERT_FILTER_FIELD_TCP_FIN: case WINDIVERT_FILTER_FIELD_TCP_WINDOW: case WINDIVERT_FILTER_FIELD_TCP_CHECKSUM: case WINDIVERT_FILTER_FIELD_TCP_URGPTR: case WINDIVERT_FILTER_FIELD_TCP_PAYLOADLENGTH: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_TCP; break; case WINDIVERT_FILTER_FIELD_UDP_SRCPORT: case WINDIVERT_FILTER_FIELD_UDP_DSTPORT: case WINDIVERT_FILTER_FIELD_UDP_LENGTH: case WINDIVERT_FILTER_FIELD_UDP_CHECKSUM: case WINDIVERT_FILTER_FIELD_UDP_PAYLOADLENGTH: filter0[i].protocol = WINDIVERT_FILTER_PROTOCOL_UDP; break; default: goto windivert_filter_compile_exit; } } result = (filter_t)ExAllocatePoolWithTag(NonPagedPool, i*sizeof(struct filter_s), WINDIVERT_TAG); if (result != NULL) { RtlMoveMemory(result, filter0, i*sizeof(struct filter_s)); } windivert_filter_compile_exit: if (filter0 != NULL) { ExFreePoolWithTag(filter0, WINDIVERT_TAG); } return result; }
gpl-3.0
areaDetector/ffmpegServer
ffmpegServerApp/src/ffmpegServer.cpp
1
29349
/* local includes */ #include "ffmpegServer.h" /* EPICS includes */ #include "epicsExport.h" #include "iocsh.h" #include <epicsExit.h> #include <epicsThread.h> #include <time.h> #include <math.h> /* windows includes */ #ifdef _MSC_VER /* Microsoft Compilers */ /** win32 implementation of pthread_cond_init */ int pthread_cond_init (pthread_cond_t *cv, const pthread_condattr_t *) { cv->semaphore = CreateEvent (NULL, FALSE, FALSE, NULL); return 0; } /** win32 implementation of pthread_cond_wait */ int pthread_cond_wait (pthread_cond_t *cv, pthread_mutex_t *external_mutex) { pthread_mutex_unlock(external_mutex); /** This is wrong, we could miss a wakeup call here... */ /** Note: this a wait with timeout, on windows we will get a jpeg every second * even if there isn't a new one. This avoids GDA timeouts... */ WaitForSingleObject (cv->semaphore, 1000); pthread_mutex_lock(external_mutex); return 0; } /** win32 implementation of pthread_cond_signal */ int pthread_cond_signal (pthread_cond_t *cv) { SetEvent (cv->semaphore); return 0; } #endif static const char *driverName = "ffmpegServer"; /** This is called whenever a client requests a stream */ void dorequest(int sid) { char *portName; int len; char *ext; if (read_header(sid)<0) { closeconnect(sid, 1); return; } logaccess(2, "%s - HTTP Request: %s %s", conn[sid].dat->in_RemoteAddr, conn[sid].dat->in_RequestMethod, conn[sid].dat->in_RequestURI); snprintf(conn[sid].dat->out_ContentType, sizeof(conn[sid].dat->out_ContentType)-1, "text/html"); /* check if we are asking for a jpg or an mjpg file */ ext = strrchr(conn[sid].dat->in_RequestURI+1, '.'); if (ext != NULL) { len = (int) (ext - conn[sid].dat->in_RequestURI - 1); portName = (char *)calloc(sizeof(char), 256); strncpy(portName, conn[sid].dat->in_RequestURI+1, len); ext++; for (int i=0; i<nstreams; i++) { if (strcmp(portName, streams[i]->portName) == 0) { if (strcmp(ext, "index") == 0) { streams[i]->send_snapshot(sid, 1); free(portName); return; } if (strcmp(ext, "jpg") == 0 || strcmp(ext, "jpeg") == 0) { streams[i]->send_snapshot(sid, 0); free(portName); return; } if (strcmp(ext, "mjpg") == 0 || strcmp(ext, "mjpeg") == 0) { streams[i]->send_stream(sid); free(portName); return; } } } } /* If we weren't asked for a stream then just send the index page */ send_header(sid, 0, 200, "OK", "1", "text/html", -1, -1); prints("\n\ <HTML> \n\ <style type=\"text/css\"> \n\ BODY { \n\ background-color: #f2f2f6; \n\ font-family: arial, sans-serif; \n\ } \n\ H1 { \n\ font-size: 24px; \n\ color: #000000; \n\ font-weight: bold; \n\ text-align: center; \n\ } \n\ H2 { \n\ font-size: 18px; \n\ color: #1b2a60; \n\ font-weight: bold; \n\ text-align: center; \n\ } \n\ A:link { \n\ text-decoration: none; color:#3b4aa0; \n\ } \n\ A:visited { \n\ text-decoration: none; color:#3b4aa0; \n\ } \n\ A:active { \n\ text-decoration: none; color:#3b4aa0; \n\ } \n\ A:hover { \n\ text-decoration: underline; color:#3b4aff; \n\ } \n\ td { \n\ background-color: #e0e0ee; \n\ border-style: outset; \n\ border-color: #e0e0ee; \n\ border-width: 1px; \n\ padding: 10px; \n\ text-align: center; \n\ } \n\ p { \n\ text-align: center; \n\ } \n\ </style> \n\ <HEAD> \n\ <TITLE>ffmpegServer Content Listing</TITLE> \n\ </HEAD> \n\ <BODY> \n\ <CENTER> \n\ <H1>ffmpegServer Content Listing</H1> \n\ <TABLE cellspacing=\"15\"> \n\ <TR> \n\ "); /* make a table of streams */ for (int i=0; i<nstreams; i++) { prints("<TD>\n"); prints("<H2>%s</H2>\n", streams[i]->portName); prints("<img src=\"%s.index\" height=\"192\" title=\"Static JPEG\" alt=\"&lt;No image yet&gt;\"/>\n", streams[i]->portName); prints("<p><a href=\"%s.jpg\">Link to Static JPEG</a></p>\n", streams[i]->portName); prints("<p><a href=\"%s.mjpg\">Link to MJPEG Stream</a></p>\n", streams[i]->portName); prints("</TD>\n"); if (i % 3 == 2) { //3 per row prints(" </TR>\n <TR>\n"); } } prints("\n\ </TR> \n\ </TABLE> \n\ </CENTER> \n\ </BODY> \n\ </HTML> \n\ "); flushbuffer(sid); } /** this dummy function is here to satisfy nullhttpd */ int config_read() { snprintf(config.server_base_dir, sizeof(config.server_base_dir)-1, "%s", DEFAULT_BASE_DIR); snprintf(config.server_bin_dir, sizeof(config.server_bin_dir)-1, "%s/bin", config.server_base_dir); snprintf(config.server_cgi_dir, sizeof(config.server_cgi_dir)-1, "%s/cgi-bin", config.server_base_dir); snprintf(config.server_etc_dir, sizeof(config.server_etc_dir)-1, "%s/etc", config.server_base_dir); snprintf(config.server_htdocs_dir, sizeof(config.server_htdocs_dir)-1, "%s/htdocs", config.server_base_dir); fixslashes(config.server_base_dir); fixslashes(config.server_bin_dir); fixslashes(config.server_cgi_dir); fixslashes(config.server_etc_dir); fixslashes(config.server_htdocs_dir); return 0; } static int stopping = 0; /** c function that will be called at epicsExit that shuts down the http server cleanly */ void c_shutdown(void *) { printf("Shutting down http server..."); stopping = 1; server_shutdown(); sleep(1); printf("OK\n"); } /** Configure and start the http server, specifying a specific network interface, or 'any' for default. * To specify an interface, use either the DNS name or the IP of the NIC. ex: 10.68.212.33 or my-ioc-server-hostname * Default port is 8080. */ void ffmpegServerConfigure(int port, const char* networkInterface) { int status; if (port==0) { port = 8080; } streams = (ffmpegStream **) calloc(MAX_FFMPEG_STREAMS, sizeof(ffmpegStream *)); nstreams = 0; config.server_port = port; config.server_loglevel=1; strncpy(config.server_hostname, networkInterface, sizeof(config.server_hostname)-1); config.server_maxconn=50; config.server_maxidle=120; printf("Starting server on port %d...\n", port); snprintf((char *)program_name, sizeof(program_name)-1, "ffmpegServer"); init(); #ifdef WIN32 if (_beginthread(WSAReaper, 0, NULL)==-1) { logerror("Winsock reaper thread failed to start"); exit(0); } #endif /* Start up acquisition thread */ status = (epicsThreadCreate("httpServer", epicsThreadPriorityMedium, epicsThreadGetStackSize(epicsThreadStackMedium), (EPICSTHREADFUNC)accept_loop, NULL) == NULL); if (status) { printf("%s:ffmpegServerConfigure epicsThreadCreate failure for image task\n", driverName); return; } else printf("OK\n"); /* Register the shutdown function for epicsAtExit */ epicsAtExit(c_shutdown, NULL); } /** Internal function to send a single snapshot */ void ffmpegStream::send_snapshot(int sid, int index) { time_t now=time((time_t*)0); int size, always_on; NDArray* pArray; // printf("JPEG requested\n"); /* Say we're listening */ getIntegerParam(0, ffmpegServerAlwaysOn, &always_on); pthread_mutex_lock( &this->mutex ); this->nclients++; if (this->nclients > 1) always_on = 1; pthread_mutex_unlock(&this->mutex); /* if always on or clients already listening then there is already a frame */ if (always_on || index) { pArray = get_jpeg(); } else { pArray = wait_for_jpeg(sid); } /* we're no longer listening */ pthread_mutex_lock( &this->mutex ); this->nclients--; pthread_mutex_unlock(&this->mutex); /* If there's no data yet, say so */ if (pArray == NULL) { printerror(sid, 200, "No Data", "No jpeg available yet"); return; } /* Send the right header for a jpeg */ size = (int) pArray->dims[0].size; conn[sid].dat->out_ContentLength=size; send_fileheader(sid, 0, 200, "OK", "1", "image/jpeg", size, now); /* Send the jpeg itself */ send(conn[sid].socket, (const char *) pArray->pData, size, 0); pArray->release(); /* Clear up */ conn[sid].dat->out_headdone=1; conn[sid].dat->out_bodydone=1; conn[sid].dat->out_flushed=1; conn[sid].dat->out_ReplyData[0]='\0'; flushbuffer(sid); } #define MIN(a, b) (((a) < (b)) ? (a) : (b)) /** Internal function to send a jpeg frame as part of an mjpeg stream */ int ffmpegStream::send_frame(int sid, NDArray *pArray) { int ret = 0; // double difftime; // struct timeval start, end; if (pArray) { /* Send metadata */ // printf("Send frame %d to sid %d\n", pArray->dims[0].size, sid); prints("Content-Type: image/jpeg\r\n"); prints("Content-Length: %d\r\n\r\n", pArray->dims[0].size); flushbuffer(sid); /* Send the jpeg */ // gettimeofday(&start, NULL); ret = send(conn[sid].socket, (const char *) pArray->pData, (int) pArray->dims[0].size, 0); // gettimeofday(&end, NULL); /* Send a boundary */ prints("\r\n--BOUNDARY\r\n"); flushbuffer(sid); // difftime = (end.tv_usec - start.tv_usec) * 0.000001 + end.tv_sec - start.tv_sec; // if (difftime > 0.1) printf ("It took %.2lf seconds to send a frame to %d. That's a bit slow\n", difftime, sid); // printf("Done\n"); pArray->release(); } return ret; } /** Internal function to get the current jpeg and return it */ NDArray* ffmpegStream::get_jpeg() { NDArray* pArray; pthread_mutex_lock(&this->mutex); pArray = this->jpeg; if (pArray) pArray->reserve(); pthread_mutex_unlock(&this->mutex); return pArray; } /** Internal function to wait for a jpeg to be produced */ NDArray* ffmpegStream::wait_for_jpeg(int sid) { NDArray* pArray; pthread_mutex_lock(&this->mutex); pthread_cond_wait(&(this->cond[sid]), &this->mutex); pArray = this->jpeg; if(pArray) pArray->reserve(); pthread_mutex_unlock(&this->mutex); return pArray; } /** Internal function to send an mjpg stream */ void ffmpegStream::send_stream(int sid) { int ret = 0; int always_on; NDArray* pArray; time_t now=time((time_t*)0); /* Say we're listening */ getIntegerParam(0, ffmpegServerAlwaysOn, &always_on); pthread_mutex_lock( &this->mutex ); this->nclients++; if (this->nclients > 1) always_on = 1; pthread_mutex_unlock(&this->mutex); /* Send the appropriate header */ send_fileheader(sid, 0, 200, "OK", "1", "multipart/x-mixed-replace;boundary=BOUNDARY", -1, now); prints("--BOUNDARY\r\n"); flushbuffer(sid); /* if always on or clients already listening then there is already a frame */ if (always_on) { pArray = get_jpeg(); ret = send_frame(sid, pArray); } /* while the client is listening and we aren't stopping */ while (ret >= 0 && !stopping) { /* wait for a new frame and send it*/ pArray = wait_for_jpeg(sid); ret = send_frame(sid, pArray); } /* We're no longer listening */ pthread_mutex_lock( &this->mutex ); this->nclients--; pthread_mutex_unlock(&this->mutex); } /** Internal function to alloc a correctly sized processed array */ void ffmpegStream::allocScArray(size_t size) { if (this->scArray) { if (this->scArray->dims[0].size >= size) { /* the processed array is already big enough */ avpicture_fill((AVPicture *)scPicture,(uint8_t *)scArray->pData,c->pix_fmt,c->width,c->height); return; } else { /* need a new one, so discard the old one */ this->scArray->release(); } } this->scArray = this->pNDArrayPool->alloc(1, &size, NDInt8, 0, NULL); /* alloc in and scaled pictures */ avpicture_fill((AVPicture *)scPicture,(uint8_t *)scArray->pData,c->pix_fmt,c->width,c->height); } /** Take an NDArray, add grid and false colour, compress it to a jpeg, then * signal to the server process that there is a new frame available. */ void ffmpegStream::processCallbacks(NDArray *pArray) { // double difftime; // struct timeval start, end; // gettimeofday(&start, NULL); /* we're going to get these with getIntegerParam */ int quality, clients, false_col, always_on, maxw, maxh; /* we're going to get these from the dims of the image */ int width, height; /* in case we force a final size */ int setw, seth; size_t size; /* for printing errors */ const char *functionName = "processCallbacks"; /* for getting the colour mode */ int colorMode = NDColorModeMono; NDAttribute *pAttribute = NULL; /* Call the base class method */ NDPluginDriver::beginProcessCallbacks(pArray); /* see if anyone's listening */ pthread_mutex_lock(&this->mutex); clients = this->nclients; pthread_mutex_unlock(&this->mutex); setIntegerParam(0, ffmpegServerClients, clients); /* get the configuration values */ getIntegerParam(0, ffmpegServerQuality, &quality); getIntegerParam(0, ffmpegServerFalseCol, &false_col); getIntegerParam(0, ffmpegServerAlwaysOn, &always_on); getIntegerParam(0, ffmpegServerMaxW, &maxw); getIntegerParam(0, ffmpegServerMaxH, &maxh); getIntegerParam(0, ffmpegServerSetW, &setw); getIntegerParam(0, ffmpegServerSetH, &seth); /* if no-ones listening and we're not always on then do nothing */ if (clients == 0 && always_on == 0) { // printf("No-one listening\n"); return; } /* This function is called with the lock taken, and it must be set when we exit. * The following code can be exected without the mutex because we are not accessing memory * that other threads can access. */ this->unlock(); /* Get the colormode of the array */ pAttribute = pArray->pAttributeList->find("ColorMode"); if (pAttribute) pAttribute->getValue(NDAttrInt32, &colorMode); if ((pArray->ndims == 2) && (colorMode == NDColorModeMono)) { width = (int) pArray->dims[0].size; height = (int) pArray->dims[1].size; } else if ((pArray->ndims == 3) && (pArray->dims[0].size == 3) && (colorMode == NDColorModeRGB1)) { width = (int) pArray->dims[1].size; height = (int) pArray->dims[2].size; } else { width = (int) pArray->dims[0].size; height = (int) pArray->dims[1].size; } /* scale image according to user request */ if (setw > 0 && seth > 0) { width = setw; height = seth; } else if (setw > 0) { double sf = (double)(setw)/width; height = (int)(sf * height); width = setw; } else if (seth > 0) { double sf = (double)(seth)/height; width = (int)(sf * width); height = seth; } /* If we exceed the maximum size */ if (width > maxw || height > maxh) { double sf = MIN(((double)maxw)/width, ((double)maxh)/height); width = (int) (sf * width); height = (int) (sf * height); } /* If width and height have changed then reinitialise the codec */ if (c == NULL || width != c->width || height != c->height) { // printf("Setting width %d height %d\n", width, height); AVRational avr; avr.num = 1; avr.den = 25; if (c != NULL) { /* width and height changed, close old codec */ avcodec_close(c); av_free(c); } c = avcodec_alloc_context3(codec); /* Make sure that we don't try and create an image smaller than AV_INPUT_BUFFER_MIN_SIZE */ if (width * height < AV_INPUT_BUFFER_MIN_SIZE) { double sf = sqrt(1.0 * AV_INPUT_BUFFER_MIN_SIZE / width / height); height = (int) (height * sf + 1); if (height % 32) height = height + 32 - (height % 32); width = (int) (width * sf + 1); if (width % 32) width = width + 32 - (width % 32); } c->width = width; c->height = height; c->flags = AV_CODEC_FLAG_QSCALE; c->time_base = avr; c->pix_fmt = AV_PIX_FMT_YUVJ420P; if(codec && codec->pix_fmts){ const enum AVPixelFormat *p= codec->pix_fmts; for(; *p!=-1; p++){ if(*p == c->pix_fmt) break; } if(*p == -1) c->pix_fmt = codec->pix_fmts[0]; } /* open it */ if (avcodec_open2(c, codec, NULL) < 0) { c = NULL; asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: could not open codec\n", driverName, functionName); return; } /* Override codec pix_fmt to get rid of error messages */ if (c->pix_fmt == AV_PIX_FMT_YUVJ420P) { c->pix_fmt = AV_PIX_FMT_YUV420P; c->color_range = AVCOL_RANGE_JPEG; } } size = width * height; /* make sure our processed array is big enough */ this->allocScArray(2 * size); /* Set the quality */ scPicture->quality = 3276 - (int) (quality * 32.76); if (scPicture->quality < 0) scPicture->quality = 0; if (scPicture->quality > 32767) scPicture->quality = 32768; /* format the array */ if (formatArray(pArray, this->pasynUserSelf, this->inPicture, &(this->ctx), this->c, this->scPicture) != asynSuccess) { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Could not format array for correct pix_fmt for codec\n", driverName, functionName); /* We must enter the loop and exit with the mutex locked */ this->lock(); return; } /* lock the output plugin mutex */ pthread_mutex_lock(&this->mutex); /* Release the last jpeg created */ if (this->jpeg) { this->jpeg->release(); } /* Convert it to a jpeg */ this->jpeg = this->pNDArrayPool->alloc(1, &size, NDInt8, 0, NULL); AVPacket pkt; int got_output; av_init_packet(&pkt); pkt.data = (uint8_t*)this->jpeg->pData; // packet data will be allocated by the encoder pkt.size = c->width * c->height; // needed to stop a stream of "AVFrame.format is not set" etc. messages scPicture->format = c->pix_fmt; scPicture->width = c->width; scPicture->height = c->height; if (avcodec_encode_video2(c, &pkt, scPicture, &got_output)) { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Encoding jpeg failed\n", driverName, functionName); got_output = 0; // got_output is undefined on error, so explicitly set it for use later } if (got_output) { this->jpeg->dims[0].size = pkt.size; av_packet_unref(&pkt); } //printf("Frame! Size: %d\n", this->jpeg->dims[0].size); /* signal fresh_frame to output plugin and unlock mutex */ for (int i=0; i<config.server_maxconn; i++) { pthread_cond_signal(&(this->cond[i])); } pthread_mutex_unlock(&this->mutex); /* We must enter the loop and exit with the mutex locked */ this->lock(); /* Update the parameters. */ callParamCallbacks(0, 0); // gettimeofday(&end, NULL); // difftime = (end.tv_usec - start.tv_usec) * 0.000001 + end.tv_sec - start.tv_sec; // if (difftime > 0.1) printf ("It took %.2lf seconds to process callbacks. That's a bit slow\n", difftime); } /** Constructor for ffmpegStream; Class representing an mjpg stream served up by ffmpegServer. ffmpegServerConfigure() must be called before creating any instances of this class. ffmpegStreamConfigure() should be used to create an instance in the iocsh. See ffmpegStream.template for more details of usage. * \param portName The name of the asyn port driver to be created. * \param queueSize The number of NDArrays that the input queue for this plugin can hold when * NDPluginDriverBlockingCallbacks=0. Larger queues can decrease the number of dropped arrays, * at the expense of more NDArray buffers being allocated from the underlying driver's NDArrayPool. * \param blockingCallbacks Initial setting for the NDPluginDriverBlockingCallbacks flag. * 0=callbacks are queued and executed by the callback thread; 1 callbacks execute in the thread * of the driver doing the callbacks. * \param NDArrayPort Name of asyn port driver for initial source of NDArray callbacks. * \param NDArrayAddr asyn port driver address for initial source of NDArray callbacks. * \param maxBuffers The maximum number of NDArray buffers that the NDArrayPool for this driver is * allowed to allocate. Set this to -1 to allow an unlimited number of buffers. * \param maxMemory The maximum amount of memory that the NDArrayPool for this driver is * allowed to allocate. Set this to -1 to allow an unlimited amount of memory. * \param priority The thread priority for the asyn port driver thread if ASYN_CANBLOCK is set in asynFlags. * \param stackSize The stack size for the asyn port driver thread if ASYN_CANBLOCK is set in asynFlags. */ ffmpegStream::ffmpegStream(const char *portName, int queueSize, int blockingCallbacks, const char *NDArrayPort, int NDArrayAddr, int maxBuffers, int maxMemory, int priority, int stackSize) /* Invoke the base class constructor * Set autoconnect to 1. priority can be 0, which will use defaults. * We require a minimum stacksize of 128k for windows-x64 */ : NDPluginDriver(portName, queueSize, blockingCallbacks, NDArrayPort, NDArrayAddr, 1, maxBuffers, maxMemory, asynGenericPointerMask, asynGenericPointerMask, 0, 1, priority, stackSize < 128000 ? 128000 : stackSize, 1) /* Not ASYN_CANBLOCK or ASYN_MULTIDEVICE, do autoConnect */ { char host[64] = ""; char url[256] = ""; asynStatus status; this->jpeg = NULL; this->scArray = NULL; this->nclients = 0; this->c = NULL; this->codec = NULL; this->inPicture = NULL; this->scPicture = NULL; this->ctx = NULL; this->cond = NULL; /* Create some parameters */ createParam(ffmpegServerQualityString, asynParamInt32, &ffmpegServerQuality); createParam(ffmpegServerFalseColString, asynParamInt32, &ffmpegServerFalseCol); createParam(ffmpegServerHttpPortString, asynParamInt32, &ffmpegServerHttpPort); createParam(ffmpegServerHostString, asynParamOctet, &ffmpegServerHost); createParam(ffmpegServerJpgUrlString, asynParamOctet, &ffmpegServerJpgUrl); createParam(ffmpegServerMjpgUrlString, asynParamOctet, &ffmpegServerMjpgUrl); createParam(ffmpegServerClientsString, asynParamInt32, &ffmpegServerClients); createParam(ffmpegServerAlwaysOnString, asynParamInt32, &ffmpegServerAlwaysOn); createParam(ffmpegServerMaxWString, asynParamInt32, &ffmpegServerMaxW); createParam(ffmpegServerMaxHString, asynParamInt32, &ffmpegServerMaxH); createParam(ffmpegServerSetWString, asynParamInt32, &ffmpegServerSetW); createParam(ffmpegServerSetHString, asynParamInt32, &ffmpegServerSetH); /* Try to connect to the NDArray port */ status = connectToArrayPort(); /* Set the initial values of some parameters */ setIntegerParam(0, ffmpegServerHttpPort, config.server_port); setIntegerParam(0, ffmpegServerClients, 0); /* Set the plugin type string */ setStringParam(NDPluginDriverPluginType, "ffmpegServer"); /* Set the hostname */ gethostname(host, 64); setStringParam(ffmpegServerHost, host); sprintf(url, "http://%s:%d/%s.jpg", host, config.server_port, portName); setStringParam(ffmpegServerJpgUrl, url); sprintf(url, "http://%s:%d/%s.mjpg", host, config.server_port, portName); setStringParam(ffmpegServerMjpgUrl, url); /* Initialise the ffmpeg library */ ffmpegInitialise(); /* make the input and output pictures */ inPicture = av_frame_alloc(); scPicture = av_frame_alloc(); /* Setup correct codec for mjpeg */ codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG); if (!codec) { fprintf(stderr, "MJPG codec not found\n"); exit(1); } /* this mutex and the conditional variable are used to synchronize access to the global picture buffer */ pthread_mutex_init(&(this->mutex), NULL); this->cond = (pthread_cond_t *) calloc(config.server_maxconn, sizeof(pthread_cond_t)); for (int i=0; i<config.server_maxconn; i++) { pthread_cond_init(&(this->cond[i]), NULL); } } /** Configuration routine. Called directly, or from the iocsh function, calls ffmpegStream constructor: \copydoc ffmpegStream::ffmpegStream */ extern "C" int ffmpegStreamConfigure(const char *portName, int queueSize, int blockingCallbacks, const char *NDArrayPort, int NDArrayAddr, int maxBuffers, int maxMemory, int priority, int stackSize) { if (nstreams+1 > MAX_FFMPEG_STREAMS) { printf("%s:ffmpegStreamConfigure: Can only create %d streams\n", driverName, MAX_FFMPEG_STREAMS); return(asynError); } ffmpegStream *pPlugin = new ffmpegStream(portName, queueSize, blockingCallbacks, NDArrayPort, NDArrayAddr, maxBuffers, maxMemory, priority, stackSize); pPlugin->start(); streams[nstreams++] = pPlugin; return(asynSuccess); } /* EPICS iocsh shell commands */ static const iocshArg streamArg0 = { "portName",iocshArgString}; static const iocshArg streamArg1 = { "frame queue size",iocshArgInt}; static const iocshArg streamArg2 = { "blocking callbacks",iocshArgInt}; static const iocshArg streamArg3 = { "NDArray Port",iocshArgString}; static const iocshArg streamArg4 = { "NDArray Addr",iocshArgInt}; static const iocshArg streamArg5 = { "Max Buffers",iocshArgInt}; static const iocshArg streamArg6 = { "Max memory",iocshArgInt}; static const iocshArg streamArg7 = { "priority",iocshArgInt}; static const iocshArg streamArg8 = { "stackSize",iocshArgInt}; static const iocshArg * const streamArgs[] = {&streamArg0, &streamArg1, &streamArg2, &streamArg3, &streamArg4, &streamArg5, &streamArg6, &streamArg7, &streamArg8}; static const iocshFuncDef streamFuncDef = {"ffmpegStreamConfigure",9,streamArgs}; static void streamCallFunc(const iocshArgBuf *args) { ffmpegStreamConfigure(args[0].sval, args[1].ival, args[2].ival, args[3].sval, args[4].ival, args[5].ival, args[6].ival, args[7].ival, args[8].ival); } static const iocshArg serverArg0 = { "Http Port",iocshArgInt}; static const iocshArg serverArg1 = { "Network Interface", iocshArgString}; static const iocshArg * const serverArgs[] = {&serverArg0, &serverArg1}; static const iocshFuncDef serverFuncDef = {"ffmpegServerConfigure",2,serverArgs}; static void serverCallFunc(const iocshArgBuf *args) { if(args[1].sval == NULL) ffmpegServerConfigure(args[0].ival, "any"); else ffmpegServerConfigure(args[0].ival, args[1].sval); } /** Register ffmpegStreamConfigure and ffmpegServerConfigure for use on iocsh */ extern "C" void ffmpegServerRegister(void) { iocshRegister(&streamFuncDef,streamCallFunc); iocshRegister(&serverFuncDef,serverCallFunc); } extern "C" { epicsExportRegistrar(ffmpegServerRegister); } /** * \file * section License * Author: Diamond Light Source, Copyright 2010 * * 'ffmpegServer' is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 'ffmpegServer' is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 'ffmpegServer'. If not, see http://www.gnu.org/licenses/. */
gpl-3.0
tobiasjakobi/RetroArch
audio/filters/echo.c
1
4346
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * * RetroArch is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ #include "dspfilter.h" #include <math.h> #include <stdlib.h> #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif struct echo_channel { float *buffer; unsigned ptr; unsigned frames; float feedback; }; struct echo_data { struct echo_channel *channels; unsigned num_channels; float amp; }; static void echo_free(void *data) { struct echo_data *echo = data; for (unsigned i = 0; i < echo->num_channels; i++) free(echo->channels[i].buffer); free(echo->channels); free(echo); } static void echo_process(void *data, struct dspfilter_output *output, const struct dspfilter_input *input) { struct echo_data *echo = data; output->samples = input->samples; output->frames = input->frames; float *out = output->samples; for (unsigned i = 0; i < input->frames; i++, out += 2) { float echo_left = 0.0f; float echo_right = 0.0f; for (unsigned c = 0; c < echo->num_channels; c++) { echo_left += echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 0]; echo_right += echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 1]; } echo_left *= echo->amp; echo_right *= echo->amp; float left = out[0] + echo_left; float right = out[1] + echo_right; for (unsigned c = 0; c < echo->num_channels; c++) { float feedback_left = out[0] + echo->channels[c].feedback * echo_left; float feedback_right = out[1] + echo->channels[c].feedback * echo_right; echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 0] = feedback_left; echo->channels[c].buffer[(echo->channels[c].ptr << 1) + 1] = feedback_right; echo->channels[c].ptr = (echo->channels[c].ptr + 1) % echo->channels[c].frames; } out[0] = left; out[1] = right; } } static void *echo_init(const struct dspfilter_info *info, const struct dspfilter_config *config, void *userdata) { struct echo_data *echo = calloc(1, sizeof(*echo)); if (!echo) return NULL; float *delay = NULL, *feedback = NULL; unsigned num_delay = 0, num_feedback = 0; static const float default_delay[] = { 200.0f }; static const float default_feedback[] = { 0.5f }; config->get_float_array(userdata, "delay", &delay, &num_delay, default_delay, 1); config->get_float_array(userdata, "feedback", &feedback, &num_feedback, default_feedback, 1); config->get_float(userdata, "amp", &echo->amp, 0.2f); unsigned channels = num_feedback = num_delay = min(num_delay, num_feedback); echo->channels = calloc(channels, sizeof(*echo->channels)); if (!echo->channels) goto error; echo->num_channels = channels; for (unsigned i = 0; i < channels; i++) { unsigned frames = (unsigned)(delay[i] * info->input_rate / 1000.0f + 0.5f); if (!frames) goto error; echo->channels[i].buffer = calloc(frames, 2 * sizeof(float)); if (!echo->channels[i].buffer) goto error; echo->channels[i].frames = frames; echo->channels[i].feedback = feedback[i]; } config->free(delay); config->free(feedback); return echo; error: config->free(delay); config->free(feedback); echo_free(echo); return NULL; } static const struct dspfilter_implementation echo_plug = { echo_init, echo_process, echo_free, DSPFILTER_API_VERSION, "Multi-Echo", "echo", }; const struct dspfilter_implementation *dspfilter_get_implementation(dspfilter_simd_mask_t mask) { (void)mask; return &echo_plug; } #undef dspfilter_get_implementation
gpl-3.0
rggjan/Gimp-Matting
app/tools/gimptexttool-editor.c
1
43536
/* GIMP - The GNU Image Manipulation Program * Copyright (C) 1995 Spencer Kimball and Peter Mattis * * GimpTextTool * Copyright (C) 2002-2010 Sven Neumann <sven@gimp.org> * Daniel Eddeland <danedde@svn.gnome.org> * Michael Natterer <mitch@gimp.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <gegl.h> #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include "libgimpwidgets/gimpwidgets.h" #include "tools-types.h" #include "core/gimp.h" #include "core/gimpimage.h" #include "core/gimptoolinfo.h" #include "text/gimptext.h" #include "text/gimptextlayout.h" #include "widgets/gimpdialogfactory.h" #include "widgets/gimpoverlaybox.h" #include "widgets/gimpoverlayframe.h" #include "widgets/gimptextbuffer.h" #include "widgets/gimptexteditor.h" #include "widgets/gimptextproxy.h" #include "widgets/gimptextstyleeditor.h" #include "display/gimpdisplay.h" #include "display/gimpdisplayshell.h" #include "gimprectangletool.h" #include "gimptextoptions.h" #include "gimptexttool.h" #include "gimptexttool-editor.h" #include "gimp-log.h" #include "gimp-intl.h" /* local function prototypes */ static void gimp_text_tool_ensure_proxy (GimpTextTool *text_tool); static void gimp_text_tool_move_cursor (GimpTextTool *text_tool, GtkMovementStep step, gint count, gboolean extend_selection); static void gimp_text_tool_insert_at_cursor (GimpTextTool *text_tool, const gchar *str); static void gimp_text_tool_delete_from_cursor (GimpTextTool *text_tool, GtkDeleteType type, gint count); static void gimp_text_tool_backspace (GimpTextTool *text_tool); static void gimp_text_tool_toggle_overwrite (GimpTextTool *text_tool); static void gimp_text_tool_select_all (GimpTextTool *text_tool, gboolean select); static void gimp_text_tool_change_size (GimpTextTool *text_tool, gdouble amount); static void gimp_text_tool_change_baseline (GimpTextTool *text_tool, gdouble amount); static void gimp_text_tool_change_kerning (GimpTextTool *text_tool, gdouble amount); static void gimp_text_tool_options_notify (GimpTextOptions *options, GParamSpec *pspec, GimpTextTool *text_tool); static void gimp_text_tool_editor_dialog (GimpTextTool *text_tool); static void gimp_text_tool_editor_destroy (GtkWidget *dialog, GimpTextTool *text_tool); static void gimp_text_tool_enter_text (GimpTextTool *text_tool, const gchar *str); static void gimp_text_tool_xy_to_iter (GimpTextTool *text_tool, gdouble x, gdouble y, GtkTextIter *iter); static void gimp_text_tool_im_commit (GtkIMContext *context, const gchar *str, GimpTextTool *text_tool); static void gimp_text_tool_im_preedit_start (GtkIMContext *context, GimpTextTool *text_tool); static void gimp_text_tool_im_preedit_end (GtkIMContext *context, GimpTextTool *text_tool); static void gimp_text_tool_im_preedit_changed (GtkIMContext *context, GimpTextTool *text_tool); /* public functions */ void gimp_text_tool_editor_init (GimpTextTool *text_tool) { text_tool->im_context = gtk_im_multicontext_new (); text_tool->needs_im_reset = FALSE; text_tool->preedit_string = NULL; text_tool->preedit_cursor = 0; text_tool->overwrite_mode = FALSE; text_tool->x_pos = -1; g_signal_connect (text_tool->im_context, "commit", G_CALLBACK (gimp_text_tool_im_commit), text_tool); g_signal_connect (text_tool->im_context, "preedit-start", G_CALLBACK (gimp_text_tool_im_preedit_start), text_tool); g_signal_connect (text_tool->im_context, "preedit-end", G_CALLBACK (gimp_text_tool_im_preedit_end), text_tool); g_signal_connect (text_tool->im_context, "preedit-changed", G_CALLBACK (gimp_text_tool_im_preedit_changed), text_tool); } void gimp_text_tool_editor_finalize (GimpTextTool *text_tool) { if (text_tool->im_context) { g_object_unref (text_tool->im_context); text_tool->im_context = NULL; } } void gimp_text_tool_editor_start (GimpTextTool *text_tool) { GimpTool *tool = GIMP_TOOL (text_tool); GimpTextOptions *options = GIMP_TEXT_TOOL_GET_OPTIONS (text_tool); GimpDisplayShell *shell = gimp_display_get_shell (tool->display); gtk_im_context_set_client_window (text_tool->im_context, gtk_widget_get_window (shell->canvas)); text_tool->needs_im_reset = TRUE; gimp_text_tool_reset_im_context (text_tool); gtk_im_context_focus_in (text_tool->im_context); if (options->use_editor) gimp_text_tool_editor_dialog (text_tool); g_signal_connect (options, "notify::use-editor", G_CALLBACK (gimp_text_tool_options_notify), text_tool); if (! text_tool->style_overlay) { Gimp *gimp = GIMP_CONTEXT (options)->gimp; gdouble xres = 1.0; gdouble yres = 1.0; text_tool->style_overlay = gimp_overlay_frame_new (); gtk_container_set_border_width (GTK_CONTAINER (text_tool->style_overlay), 4); gimp_display_shell_add_overlay (shell, text_tool->style_overlay, 0, 0, GIMP_HANDLE_ANCHOR_CENTER, 0, 0); gimp_overlay_box_set_child_opacity (GIMP_OVERLAY_BOX (shell->canvas), text_tool->style_overlay, 0.7); if (text_tool->image) gimp_image_get_resolution (text_tool->image, &xres, &yres); text_tool->style_editor = gimp_text_style_editor_new (gimp, text_tool->proxy, text_tool->buffer, gimp->fonts, xres, yres); gtk_container_add (GTK_CONTAINER (text_tool->style_overlay), text_tool->style_editor); gtk_widget_show (text_tool->style_editor); } gimp_text_tool_editor_position (text_tool); gtk_widget_show (text_tool->style_overlay); } void gimp_text_tool_editor_position (GimpTextTool *text_tool) { if (text_tool->style_overlay) { GimpTool *tool = GIMP_TOOL (text_tool); GimpDisplayShell *shell = gimp_display_get_shell (tool->display); GtkRequisition requisition; gint x, y; gtk_widget_size_request (text_tool->style_overlay, &requisition); g_object_get (text_tool, "x1", &x, "y1", &y, NULL); gimp_display_shell_move_overlay (shell, text_tool->style_overlay, x, y, GIMP_HANDLE_ANCHOR_SOUTH_WEST, 4, 12); if (text_tool->image) { gdouble xres, yres; gimp_image_get_resolution (text_tool->image, &xres, &yres); g_object_set (text_tool->style_editor, "resolution-x", xres, "resolution-y", yres, NULL); } } } void gimp_text_tool_editor_halt (GimpTextTool *text_tool) { GimpTextOptions *options = GIMP_TEXT_TOOL_GET_OPTIONS (text_tool); if (text_tool->style_overlay) { gtk_widget_destroy (text_tool->style_overlay); text_tool->style_overlay = NULL; text_tool->style_editor = NULL; } g_signal_handlers_disconnect_by_func (options, gimp_text_tool_options_notify, text_tool); if (text_tool->editor_dialog) { g_signal_handlers_disconnect_by_func (text_tool->editor_dialog, gimp_text_tool_editor_destroy, text_tool); gtk_widget_destroy (text_tool->editor_dialog); } if (text_tool->proxy_text_view) { gtk_widget_destroy (text_tool->offscreen_window); text_tool->offscreen_window = NULL; text_tool->proxy_text_view = NULL; } text_tool->needs_im_reset = TRUE; gimp_text_tool_reset_im_context (text_tool); gtk_im_context_focus_out (text_tool->im_context); gtk_im_context_set_client_window (text_tool->im_context, NULL); } void gimp_text_tool_editor_button_press (GimpTextTool *text_tool, gdouble x, gdouble y, GimpButtonPressType press_type) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter cursor; GtkTextIter selection; gimp_text_tool_xy_to_iter (text_tool, x, y, &cursor); selection = cursor; text_tool->select_start_iter = cursor; text_tool->select_words = FALSE; text_tool->select_lines = FALSE; switch (press_type) { case GIMP_BUTTON_PRESS_NORMAL: gtk_text_buffer_place_cursor (buffer, &cursor); break; case GIMP_BUTTON_PRESS_DOUBLE: text_tool->select_words = TRUE; if (! gtk_text_iter_starts_word (&cursor)) gtk_text_iter_backward_visible_word_starts (&cursor, 1); if (! gtk_text_iter_ends_word (&selection) && ! gtk_text_iter_forward_visible_word_ends (&selection, 1)) gtk_text_iter_forward_to_line_end (&selection); gtk_text_buffer_select_range (buffer, &cursor, &selection); break; case GIMP_BUTTON_PRESS_TRIPLE: text_tool->select_lines = TRUE; gtk_text_iter_set_line_offset (&cursor, 0); gtk_text_iter_forward_to_line_end (&selection); gtk_text_buffer_select_range (buffer, &cursor, &selection); break; } } void gimp_text_tool_editor_button_release (GimpTextTool *text_tool) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); if (gtk_text_buffer_get_has_selection (buffer)) { GimpTool *tool = GIMP_TOOL (text_tool); GimpDisplayShell *shell = gimp_display_get_shell (tool->display); GtkClipboard *clipboard; clipboard = gtk_widget_get_clipboard (GTK_WIDGET (shell), GDK_SELECTION_PRIMARY); gtk_text_buffer_copy_clipboard (buffer, clipboard); } } void gimp_text_tool_editor_motion (GimpTextTool *text_tool, gdouble x, gdouble y) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter old_cursor; GtkTextIter old_selection; GtkTextIter cursor; GtkTextIter selection; gtk_text_buffer_get_iter_at_mark (buffer, &old_cursor, gtk_text_buffer_get_insert (buffer)); gtk_text_buffer_get_iter_at_mark (buffer, &old_selection, gtk_text_buffer_get_selection_bound (buffer)); gimp_text_tool_xy_to_iter (text_tool, x, y, &cursor); selection = text_tool->select_start_iter; if (text_tool->select_words || text_tool->select_lines) { GtkTextIter start; GtkTextIter end; if (gtk_text_iter_compare (&cursor, &selection) < 0) { start = cursor; end = selection; } else { start = selection; end = cursor; } if (text_tool->select_words) { if (! gtk_text_iter_starts_word (&start)) gtk_text_iter_backward_visible_word_starts (&start, 1); if (! gtk_text_iter_ends_word (&end) && ! gtk_text_iter_forward_visible_word_ends (&end, 1)) gtk_text_iter_forward_to_line_end (&end); } else if (text_tool->select_lines) { gtk_text_iter_set_line_offset (&start, 0); gtk_text_iter_forward_to_line_end (&end); } if (gtk_text_iter_compare (&cursor, &selection) < 0) { cursor = start; selection = end; } else { selection = start; cursor = end; } } if (! gtk_text_iter_equal (&cursor, &old_cursor) || ! gtk_text_iter_equal (&selection, &old_selection)) { gimp_draw_tool_pause (GIMP_DRAW_TOOL (text_tool)); gtk_text_buffer_select_range (buffer, &cursor, &selection); gimp_draw_tool_resume (GIMP_DRAW_TOOL (text_tool)); } } gboolean gimp_text_tool_editor_key_press (GimpTextTool *text_tool, GdkEventKey *kevent) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter cursor; GtkTextIter selection; gint x_pos = -1; gboolean retval = TRUE; if (gtk_im_context_filter_keypress (text_tool->im_context, kevent)) { text_tool->needs_im_reset = TRUE; text_tool->x_pos = -1; return TRUE; } gimp_text_tool_ensure_proxy (text_tool); if (gtk_bindings_activate_event (GTK_OBJECT (text_tool->proxy_text_view), kevent)) { GIMP_LOG (TEXT_EDITING, "binding handled event"); return TRUE; } gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); gtk_text_buffer_get_iter_at_mark (buffer, &selection, gtk_text_buffer_get_selection_bound (buffer)); switch (kevent->keyval) { case GDK_KEY_Return: case GDK_KEY_KP_Enter: case GDK_KEY_ISO_Enter: gimp_text_tool_reset_im_context (text_tool); gimp_text_tool_enter_text (text_tool, "\n"); break; case GDK_KEY_Tab: case GDK_KEY_KP_Tab: case GDK_KEY_ISO_Left_Tab: gimp_text_tool_reset_im_context (text_tool); gimp_text_tool_enter_text (text_tool, "\t"); break; case GDK_KEY_Escape: gimp_rectangle_tool_cancel (GIMP_RECTANGLE_TOOL (text_tool)); gimp_tool_control (GIMP_TOOL (text_tool), GIMP_TOOL_ACTION_HALT, GIMP_TOOL (text_tool)->display); break; default: retval = FALSE; } text_tool->x_pos = x_pos; return retval; } gboolean gimp_text_tool_editor_key_release (GimpTextTool *text_tool, GdkEventKey *kevent) { if (gtk_im_context_filter_keypress (text_tool->im_context, kevent)) { text_tool->needs_im_reset = TRUE; return TRUE; } gimp_text_tool_ensure_proxy (text_tool); if (gtk_bindings_activate_event (GTK_OBJECT (text_tool->proxy_text_view), kevent)) { GIMP_LOG (TEXT_EDITING, "binding handled event"); return TRUE; } return FALSE; } void gimp_text_tool_reset_im_context (GimpTextTool *text_tool) { if (text_tool->needs_im_reset) { text_tool->needs_im_reset = FALSE; gtk_im_context_reset (text_tool->im_context); } } void gimp_text_tool_editor_get_cursor_rect (GimpTextTool *text_tool, gboolean overwrite, PangoRectangle *cursor_rect) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); PangoLayout *layout; gint offset_x; gint offset_y; GtkTextIter cursor; gint cursor_index; g_return_if_fail (GIMP_IS_TEXT_TOOL (text_tool)); g_return_if_fail (cursor_rect != NULL); gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); cursor_index = gimp_text_buffer_get_iter_index (text_tool->buffer, &cursor, TRUE); gimp_text_tool_ensure_layout (text_tool); layout = gimp_text_layout_get_pango_layout (text_tool->layout); gimp_text_layout_get_offsets (text_tool->layout, &offset_x, &offset_y); if (overwrite) pango_layout_index_to_pos (layout, cursor_index, cursor_rect); else pango_layout_get_cursor_pos (layout, cursor_index, cursor_rect, NULL); gimp_text_layout_transform_rect (text_tool->layout, cursor_rect); cursor_rect->x = PANGO_PIXELS (cursor_rect->x) + offset_x; cursor_rect->y = PANGO_PIXELS (cursor_rect->y) + offset_y; cursor_rect->width = PANGO_PIXELS (cursor_rect->width); cursor_rect->height = PANGO_PIXELS (cursor_rect->height); } /* private functions */ static void gimp_text_tool_ensure_proxy (GimpTextTool *text_tool) { GimpTool *tool = GIMP_TOOL (text_tool); GimpDisplayShell *shell = gimp_display_get_shell (tool->display); if (text_tool->offscreen_window && gtk_widget_get_screen (text_tool->offscreen_window) != gtk_widget_get_screen (GTK_WIDGET (shell))) { gtk_window_set_screen (GTK_WINDOW (text_tool->offscreen_window), gtk_widget_get_screen (GTK_WIDGET (shell))); gtk_window_move (GTK_WINDOW (text_tool->offscreen_window), -200, -200); } else if (! text_tool->offscreen_window) { text_tool->offscreen_window = gtk_window_new (GTK_WINDOW_POPUP); gtk_window_set_screen (GTK_WINDOW (text_tool->offscreen_window), gtk_widget_get_screen (GTK_WIDGET (shell))); gtk_window_move (GTK_WINDOW (text_tool->offscreen_window), -200, -200); gtk_widget_show (text_tool->offscreen_window); text_tool->proxy_text_view = gimp_text_proxy_new (); gtk_container_add (GTK_CONTAINER (text_tool->offscreen_window), text_tool->proxy_text_view); gtk_widget_show (text_tool->proxy_text_view); g_signal_connect_swapped (text_tool->proxy_text_view, "move-cursor", G_CALLBACK (gimp_text_tool_move_cursor), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "insert-at-cursor", G_CALLBACK (gimp_text_tool_insert_at_cursor), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "delete-from-cursor", G_CALLBACK (gimp_text_tool_delete_from_cursor), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "backspace", G_CALLBACK (gimp_text_tool_backspace), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "cut-clipboard", G_CALLBACK (gimp_text_tool_cut_clipboard), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "copy-clipboard", G_CALLBACK (gimp_text_tool_copy_clipboard), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "paste-clipboard", G_CALLBACK (gimp_text_tool_paste_clipboard), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "toggle-overwrite", G_CALLBACK (gimp_text_tool_toggle_overwrite), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "select-all", G_CALLBACK (gimp_text_tool_select_all), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "change-size", G_CALLBACK (gimp_text_tool_change_size), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "change-baseline", G_CALLBACK (gimp_text_tool_change_baseline), text_tool); g_signal_connect_swapped (text_tool->proxy_text_view, "change-kerning", G_CALLBACK (gimp_text_tool_change_kerning), text_tool); } } static void gimp_text_tool_move_cursor (GimpTextTool *text_tool, GtkMovementStep step, gint count, gboolean extend_selection) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter cursor; GtkTextIter selection; GtkTextIter *sel_start; gboolean cancel_selection = FALSE; gint x_pos = -1; GIMP_LOG (TEXT_EDITING, "%s count = %d, select = %s", g_enum_get_value (g_type_class_ref (GTK_TYPE_MOVEMENT_STEP), step)->value_name, count, extend_selection ? "TRUE" : "FALSE"); gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); gtk_text_buffer_get_iter_at_mark (buffer, &selection, gtk_text_buffer_get_selection_bound (buffer)); if (extend_selection) { sel_start = &selection; } else { /* when there is a selection, moving the cursor without * extending it should move the cursor to the end of the * selection that is in moving direction */ if (count > 0) gtk_text_iter_order (&selection, &cursor); else gtk_text_iter_order (&cursor, &selection); sel_start = &cursor; /* if we actually have a selection, just move *to* the beginning/end * of the selection and not *from* there on LOGICAL_POSITIONS * and VISUAL_POSITIONS movement */ if (! gtk_text_iter_equal (&cursor, &selection)) cancel_selection = TRUE; } switch (step) { case GTK_MOVEMENT_LOGICAL_POSITIONS: if (! cancel_selection) gtk_text_iter_forward_visible_cursor_positions (&cursor, count); break; case GTK_MOVEMENT_VISUAL_POSITIONS: if (! cancel_selection) { PangoLayout *layout; if (! gimp_text_tool_ensure_layout (text_tool)) break; layout = gimp_text_layout_get_pango_layout (text_tool->layout); while (count != 0) { gint index; gint trailing; gint new_index; index = gimp_text_buffer_get_iter_index (text_tool->buffer, &cursor, TRUE); if (count > 0) { pango_layout_move_cursor_visually (layout, TRUE, index, 0, 1, &new_index, &trailing); count--; } else { pango_layout_move_cursor_visually (layout, TRUE, index, 0, -1, &new_index, &trailing); count++; } if (new_index != G_MAXINT && new_index != -1) index = new_index; else break; gimp_text_buffer_get_iter_at_index (text_tool->buffer, &cursor, index, TRUE); gtk_text_iter_forward_chars (&cursor, trailing); } } break; case GTK_MOVEMENT_WORDS: if (count < 0) { gtk_text_iter_backward_visible_word_starts (&cursor, -count); } else if (count > 0) { if (! gtk_text_iter_forward_visible_word_ends (&cursor, count)) gtk_text_iter_forward_to_line_end (&cursor); } break; case GTK_MOVEMENT_DISPLAY_LINES: { GtkTextIter start; GtkTextIter end; gint cursor_index; PangoLayout *layout; PangoLayoutLine *layout_line; PangoLayoutIter *layout_iter; PangoRectangle logical; gint line; gint trailing; gint i; gtk_text_buffer_get_bounds (buffer, &start, &end); cursor_index = gimp_text_buffer_get_iter_index (text_tool->buffer, &cursor, TRUE); if (! gimp_text_tool_ensure_layout (text_tool)) break; layout = gimp_text_layout_get_pango_layout (text_tool->layout); pango_layout_index_to_line_x (layout, cursor_index, FALSE, &line, &x_pos); layout_iter = pango_layout_get_iter (layout); for (i = 0; i < line; i++) pango_layout_iter_next_line (layout_iter); pango_layout_iter_get_line_extents (layout_iter, NULL, &logical); x_pos += logical.x; pango_layout_iter_free (layout_iter); /* try to go to the remembered x_pos if it exists *and* we are at * the beginning or at the end of the current line */ if (text_tool->x_pos != -1 && (x_pos <= logical.x || x_pos >= logical.x + logical.width)) x_pos = text_tool->x_pos; line += count; if (line < 0) { cursor = start; break; } else if (line >= pango_layout_get_line_count (layout)) { cursor = end; break; } layout_iter = pango_layout_get_iter (layout); for (i = 0; i < line; i++) pango_layout_iter_next_line (layout_iter); layout_line = pango_layout_iter_get_line_readonly (layout_iter); pango_layout_iter_get_line_extents (layout_iter, NULL, &logical); pango_layout_iter_free (layout_iter); pango_layout_line_x_to_index (layout_line, x_pos - logical.x, &cursor_index, &trailing); gimp_text_buffer_get_iter_at_index (text_tool->buffer, &cursor, cursor_index, TRUE); while (trailing--) gtk_text_iter_forward_char (&cursor); } break; case GTK_MOVEMENT_PAGES: /* well... */ case GTK_MOVEMENT_BUFFER_ENDS: if (count < 0) { gtk_text_buffer_get_start_iter (buffer, &cursor); } else if (count > 0) { gtk_text_buffer_get_end_iter (buffer, &cursor); } break; case GTK_MOVEMENT_PARAGRAPH_ENDS: if (count < 0) { gtk_text_iter_set_line_offset (&cursor, 0); } else if (count > 0) { if (! gtk_text_iter_ends_line (&cursor)) gtk_text_iter_forward_to_line_end (&cursor); } break; case GTK_MOVEMENT_DISPLAY_LINE_ENDS: if (count < 0) { gtk_text_iter_set_line_offset (&cursor, 0); } else if (count > 0) { if (! gtk_text_iter_ends_line (&cursor)) gtk_text_iter_forward_to_line_end (&cursor); } break; default: return; } text_tool->x_pos = x_pos; gimp_draw_tool_pause (GIMP_DRAW_TOOL (text_tool)); gimp_text_tool_reset_im_context (text_tool); gtk_text_buffer_select_range (buffer, &cursor, sel_start); gimp_draw_tool_resume (GIMP_DRAW_TOOL (text_tool)); } static void gimp_text_tool_insert_at_cursor (GimpTextTool *text_tool, const gchar *str) { gimp_text_buffer_insert (text_tool->buffer, str); } static gboolean is_whitespace (gunichar ch, gpointer user_data) { return (ch == ' ' || ch == '\t'); } static gboolean is_not_whitespace (gunichar ch, gpointer user_data) { return ! is_whitespace (ch, user_data); } static gboolean find_whitepace_region (const GtkTextIter *center, GtkTextIter *start, GtkTextIter *end) { *start = *center; *end = *center; if (gtk_text_iter_backward_find_char (start, is_not_whitespace, NULL, NULL)) gtk_text_iter_forward_char (start); /* we want the first whitespace... */ if (is_whitespace (gtk_text_iter_get_char (end), NULL)) gtk_text_iter_forward_find_char (end, is_not_whitespace, NULL, NULL); return ! gtk_text_iter_equal (start, end); } static void gimp_text_tool_delete_from_cursor (GimpTextTool *text_tool, GtkDeleteType type, gint count) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter cursor; GtkTextIter end; GIMP_LOG (TEXT_EDITING, "%s count = %d", g_enum_get_value (g_type_class_ref (GTK_TYPE_DELETE_TYPE), type)->value_name, count); gimp_text_tool_reset_im_context (text_tool); gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); end = cursor; switch (type) { case GTK_DELETE_CHARS: if (gtk_text_buffer_get_has_selection (buffer)) { gtk_text_buffer_delete_selection (buffer, TRUE, TRUE); return; } else { gtk_text_iter_forward_cursor_positions (&end, count); } break; case GTK_DELETE_WORD_ENDS: if (count < 0) { if (! gtk_text_iter_starts_word (&cursor)) gtk_text_iter_backward_visible_word_starts (&cursor, 1); } else if (count > 0) { if (! gtk_text_iter_ends_word (&end) && ! gtk_text_iter_forward_visible_word_ends (&end, 1)) gtk_text_iter_forward_to_line_end (&end); } break; case GTK_DELETE_WORDS: if (! gtk_text_iter_starts_word (&cursor)) gtk_text_iter_backward_visible_word_starts (&cursor, 1); if (! gtk_text_iter_ends_word (&end) && ! gtk_text_iter_forward_visible_word_ends (&end, 1)) gtk_text_iter_forward_to_line_end (&end); break; case GTK_DELETE_DISPLAY_LINES: break; case GTK_DELETE_DISPLAY_LINE_ENDS: break; case GTK_DELETE_PARAGRAPH_ENDS: if (count < 0) { gtk_text_iter_set_line_offset (&cursor, 0); } else if (count > 0) { if (! gtk_text_iter_ends_line (&end)) gtk_text_iter_forward_to_line_end (&end); else gtk_text_iter_forward_cursor_positions (&end, 1); } break; case GTK_DELETE_PARAGRAPHS: break; case GTK_DELETE_WHITESPACE: find_whitepace_region (&cursor, &cursor, &end); break; } if (! gtk_text_iter_equal (&cursor, &end)) { gtk_text_buffer_delete_interactive (buffer, &cursor, &end, TRUE); } } static void gimp_text_tool_backspace (GimpTextTool *text_tool) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); gimp_text_tool_reset_im_context (text_tool); if (gtk_text_buffer_get_has_selection (buffer)) { gtk_text_buffer_delete_selection (buffer, TRUE, TRUE); } else { GtkTextIter cursor; gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); gtk_text_buffer_backspace (buffer, &cursor, TRUE, TRUE); } } static void gimp_text_tool_toggle_overwrite (GimpTextTool *text_tool) { gimp_draw_tool_pause (GIMP_DRAW_TOOL (text_tool)); text_tool->overwrite_mode = ! text_tool->overwrite_mode; gimp_draw_tool_resume (GIMP_DRAW_TOOL (text_tool)); } static void gimp_text_tool_select_all (GimpTextTool *text_tool, gboolean select) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); gimp_draw_tool_pause (GIMP_DRAW_TOOL (text_tool)); if (select) { GtkTextIter start, end; gtk_text_buffer_get_bounds (buffer, &start, &end); gtk_text_buffer_select_range (buffer, &start, &end); } else { GtkTextIter cursor; gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &cursor); } gimp_draw_tool_resume (GIMP_DRAW_TOOL (text_tool)); } static void gimp_text_tool_change_size (GimpTextTool *text_tool, gdouble amount) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter start; GtkTextIter end; if (! gtk_text_buffer_get_selection_bounds (buffer, &start, &end)) { return; } gtk_text_iter_order (&start, &end); gimp_text_buffer_change_size (text_tool->buffer, &start, &end, amount * PANGO_SCALE); } static void gimp_text_tool_change_baseline (GimpTextTool *text_tool, gdouble amount) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter start; GtkTextIter end; if (! gtk_text_buffer_get_selection_bounds (buffer, &start, &end)) { gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer)); gtk_text_buffer_get_end_iter (buffer, &end); } gtk_text_iter_order (&start, &end); gimp_text_buffer_change_baseline (text_tool->buffer, &start, &end, amount * PANGO_SCALE); } static void gimp_text_tool_change_kerning (GimpTextTool *text_tool, gdouble amount) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); GtkTextIter start; GtkTextIter end; if (! gtk_text_buffer_get_selection_bounds (buffer, &start, &end)) { gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer)); end = start; gtk_text_iter_forward_char (&end); } gtk_text_iter_order (&start, &end); gimp_text_buffer_change_kerning (text_tool->buffer, &start, &end, amount * PANGO_SCALE); } static void gimp_text_tool_options_notify (GimpTextOptions *options, GParamSpec *pspec, GimpTextTool *text_tool) { const gchar *param_name = g_param_spec_get_name (pspec); if (! strcmp (param_name, "use-editor")) { if (options->use_editor) { if (text_tool->text) gimp_text_tool_editor_dialog (text_tool); } else { if (text_tool->editor_dialog) gtk_widget_destroy (text_tool->editor_dialog); } } } static void gimp_text_tool_editor_dialog (GimpTextTool *text_tool) { GimpTool *tool = GIMP_TOOL (text_tool); GimpTextOptions *options = GIMP_TEXT_TOOL_GET_OPTIONS (text_tool); GimpDialogFactory *dialog_factory; GtkWindow *parent = NULL; gdouble xres = 1.0; gdouble yres = 1.0; if (text_tool->editor_dialog) { gtk_window_present (GTK_WINDOW (text_tool->editor_dialog)); return; } dialog_factory = gimp_dialog_factory_get_singleton (); if (tool->display) { GimpDisplayShell *shell = gimp_display_get_shell (tool->display); parent = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (shell))); } if (text_tool->image) gimp_image_get_resolution (text_tool->image, &xres, &yres); text_tool->editor_dialog = gimp_text_options_editor_new (parent, tool->tool_info->gimp, options, gimp_dialog_factory_get_menu_factory (dialog_factory), _("GIMP Text Editor"), text_tool->proxy, text_tool->buffer, xres, yres); g_object_add_weak_pointer (G_OBJECT (text_tool->editor_dialog), (gpointer) &text_tool->editor_dialog); gimp_dialog_factory_add_foreign (dialog_factory, "gimp-text-tool-dialog", text_tool->editor_dialog); g_signal_connect (text_tool->editor_dialog, "destroy", G_CALLBACK (gimp_text_tool_editor_destroy), text_tool); gtk_widget_show (text_tool->editor_dialog); } static void gimp_text_tool_editor_destroy (GtkWidget *dialog, GimpTextTool *text_tool) { GimpTextOptions *options = GIMP_TEXT_TOOL_GET_OPTIONS (text_tool); g_object_set (options, "use-editor", FALSE, NULL); } static void gimp_text_tool_enter_text (GimpTextTool *text_tool, const gchar *str) { GtkTextBuffer *buffer = GTK_TEXT_BUFFER (text_tool->buffer); gboolean had_selection; had_selection = gtk_text_buffer_get_has_selection (buffer); gtk_text_buffer_begin_user_action (buffer); gimp_text_tool_delete_selection (text_tool); if (! had_selection && text_tool->overwrite_mode && strcmp (str, "\n")) { GtkTextIter cursor; gtk_text_buffer_get_iter_at_mark (buffer, &cursor, gtk_text_buffer_get_insert (buffer)); if (! gtk_text_iter_ends_line (&cursor)) gimp_text_tool_delete_from_cursor (text_tool, GTK_DELETE_CHARS, 1); } gimp_text_buffer_insert (text_tool->buffer, str); gtk_text_buffer_end_user_action (buffer); } static void gimp_text_tool_xy_to_iter (GimpTextTool *text_tool, gdouble x, gdouble y, GtkTextIter *iter) { PangoLayout *layout; gint offset_x; gint offset_y; gint index; gint trailing; gimp_text_tool_ensure_layout (text_tool); gimp_text_layout_untransform_point (text_tool->layout, &x, &y); gimp_text_layout_get_offsets (text_tool->layout, &offset_x, &offset_y); x -= offset_x; y -= offset_y; layout = gimp_text_layout_get_pango_layout (text_tool->layout); pango_layout_xy_to_index (layout, x * PANGO_SCALE, y * PANGO_SCALE, &index, &trailing); gimp_text_buffer_get_iter_at_index (text_tool->buffer, iter, index, TRUE); if (trailing) gtk_text_iter_forward_char (iter); } static void gimp_text_tool_im_commit (GtkIMContext *context, const gchar *str, GimpTextTool *text_tool) { gimp_text_tool_enter_text (text_tool, str); } static void gimp_text_tool_im_preedit_start (GtkIMContext *context, GimpTextTool *text_tool) { GimpTool *tool = GIMP_TOOL (text_tool); GimpDisplayShell *shell = gimp_display_get_shell (tool->display); GtkStyle *style = gtk_widget_get_style (shell->canvas); GtkWidget *frame; GtkWidget *ebox; PangoRectangle cursor_rect = { 0, }; gint off_x, off_y; if (text_tool->text) gimp_text_tool_editor_get_cursor_rect (text_tool, text_tool->overwrite_mode, &cursor_rect); g_object_get (text_tool, "x1", &off_x, "y1", &off_y, NULL); text_tool->preedit_overlay = gtk_frame_new (NULL); gtk_frame_set_shadow_type (GTK_FRAME (text_tool->preedit_overlay), GTK_SHADOW_OUT); gimp_display_shell_add_overlay (shell, text_tool->preedit_overlay, cursor_rect.x + off_x, cursor_rect.y + off_y, GIMP_HANDLE_ANCHOR_NORTH_WEST, 0, 0); gimp_overlay_box_set_child_opacity (GIMP_OVERLAY_BOX (shell->canvas), text_tool->preedit_overlay, 0.7); gtk_widget_show (text_tool->preedit_overlay); frame = gtk_frame_new (NULL); gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN); gtk_container_add (GTK_CONTAINER (text_tool->preedit_overlay), frame); gtk_widget_show (frame); ebox = gtk_event_box_new (); gtk_widget_modify_bg (ebox, GTK_STATE_NORMAL, &style->base[GTK_STATE_NORMAL]); gtk_container_add (GTK_CONTAINER (frame), ebox); gtk_widget_show (ebox); text_tool->preedit_label = gtk_label_new (NULL); gtk_widget_modify_bg (text_tool->preedit_label, GTK_STATE_NORMAL, &style->text[GTK_STATE_NORMAL]); gtk_misc_set_padding (GTK_MISC (text_tool->preedit_label), 2, 2); gtk_container_add (GTK_CONTAINER (ebox), text_tool->preedit_label); gtk_widget_show (text_tool->preedit_label); } static void gimp_text_tool_im_preedit_end (GtkIMContext *context, GimpTextTool *text_tool) { if (text_tool->preedit_overlay) { gtk_widget_destroy (text_tool->preedit_overlay); text_tool->preedit_overlay = NULL; text_tool->preedit_label = NULL; } } static void gimp_text_tool_im_preedit_changed (GtkIMContext *context, GimpTextTool *text_tool) { if (text_tool->preedit_string) g_free (text_tool->preedit_string); gtk_im_context_get_preedit_string (context, &text_tool->preedit_string, NULL, &text_tool->preedit_cursor); if (text_tool->preedit_label) gtk_label_set_text (GTK_LABEL (text_tool->preedit_label), text_tool->preedit_string); }
gpl-3.0
Belxjander/Kirito
SnowStorm/indra/newview/lleventnotifier.cpp
1
7202
/** * @file lleventnotifier.cpp * @brief Viewer code for managing event notifications * * $LicenseInfo:firstyear=2004&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "lleventnotifier.h" #include "llnotificationsutil.h" #include "message.h" #include "llfloaterreg.h" #include "llfloaterworldmap.h" #include "llfloaterevent.h" #include "llagent.h" #include "llcommandhandler.h" // secondlife:///app/... support class LLEventHandler : public LLCommandHandler { public: // requires trusted browser to trigger LLEventHandler() : LLCommandHandler("event", UNTRUSTED_THROTTLE) { } bool handle(const LLSD& params, const LLSD& query_map, LLMediaCtrl* web) { if (params.size() < 2) { return false; } std::string event_command = params[1].asString(); S32 event_id = params[0].asInteger(); if(event_command == "details") { LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if (floater) { floater->setEventID(event_id); LLFloaterReg::showTypedInstance<LLFloaterEvent>("event"); return true; } } else if(event_command == "notify") { // we're adding or removing a notification, so grab the date, name and notification bool if (params.size() < 3) { return false; } if(params[2].asString() == "enable") { gEventNotifier.add(event_id); // tell the server to modify the database as this was a slurl event notification command gEventNotifier.serverPushRequest(event_id, true); } else { gEventNotifier.remove(event_id); } return true; } return false; } }; LLEventHandler gEventHandler; LLEventNotifier gEventNotifier; LLEventNotifier::LLEventNotifier() { } LLEventNotifier::~LLEventNotifier() { en_map::iterator iter; for (iter = mEventNotifications.begin(); iter != mEventNotifications.end(); iter++) { delete iter->second; } } void LLEventNotifier::update() { if (mNotificationTimer.getElapsedTimeF32() > 30.f) { // Check our notifications again and send out updates // if they happen. F64 alert_time = LLDate::now().secondsSinceEpoch() + 5 * 60; en_map::iterator iter; for (iter = mEventNotifications.begin(); iter != mEventNotifications.end();) { LLEventNotification *np = iter->second; iter++; if (np->getEventDateEpoch() < alert_time) { LLSD args; args["NAME"] = np->getEventName(); args["DATE"] = np->getEventDateStr(); LLNotificationsUtil::add("EventNotification", args, LLSD(), boost::bind(&LLEventNotifier::handleResponse, this, np->getEventID(), _1, _2)); remove(np->getEventID()); } } mNotificationTimer.reset(); } } bool LLEventNotifier::handleResponse(U32 eventId, const LLSD& notification, const LLSD& response) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); switch (option) { case 0: { LLFloaterEvent* floater = LLFloaterReg::getTypedInstance<LLFloaterEvent>("event"); if (floater) { floater->setEventID(eventId); LLFloaterReg::showTypedInstance<LLFloaterEvent>("event"); } break; } case 1: break; } return true; } bool LLEventNotifier::add(U32 eventId, F64 eventEpoch, const std::string& eventDateStr, const std::string &eventName) { LLEventNotification *new_enp = new LLEventNotification(eventId, eventEpoch, eventDateStr, eventName); LL_INFOS() << "Add event " << eventName << " id " << eventId << " date " << eventDateStr << LL_ENDL; if(!new_enp->isValid()) { delete new_enp; return false; } mEventNotifications[new_enp->getEventID()] = new_enp; return true; } void LLEventNotifier::add(U32 eventId) { gMessageSystem->newMessageFast(_PREHASH_EventInfoRequest); gMessageSystem->nextBlockFast(_PREHASH_AgentData); gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID() ); gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID() ); gMessageSystem->nextBlockFast(_PREHASH_EventData); gMessageSystem->addU32Fast(_PREHASH_EventID, eventId); gAgent.sendReliableMessage(); } //static void LLEventNotifier::processEventInfoReply(LLMessageSystem *msg, void **) { // extract the agent id LLUUID agent_id; U32 event_id; std::string event_name; std::string eventd_date; U32 event_time_utc; msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id ); msg->getU32("EventData", "EventID", event_id); msg->getString("EventData", "Name", event_name); msg->getString("EventData", "Date", eventd_date); msg->getU32("EventData", "DateUTC", event_time_utc); gEventNotifier.add(event_id, (F64)event_time_utc, eventd_date, event_name); } void LLEventNotifier::load(const LLSD& event_options) { for(LLSD::array_const_iterator resp_it = event_options.beginArray(), end = event_options.endArray(); resp_it != end; ++resp_it) { LLSD response = *resp_it; add(response["event_id"].asInteger(), response["event_date_ut"], response["event_date"].asString(), response["event_name"].asString()); } } BOOL LLEventNotifier::hasNotification(const U32 event_id) { if (mEventNotifications.find(event_id) != mEventNotifications.end()) { return TRUE; } return FALSE; } void LLEventNotifier::remove(const U32 event_id) { en_map::iterator iter; iter = mEventNotifications.find(event_id); if (iter == mEventNotifications.end()) { // We don't have a notification for this event, don't bother. return; } serverPushRequest(event_id, false); delete iter->second; mEventNotifications.erase(iter); } void LLEventNotifier::serverPushRequest(U32 event_id, bool add) { // Push up a message to tell the server we have this notification. gMessageSystem->newMessage(add?"EventNotificationAddRequest":"EventNotificationRemoveRequest"); gMessageSystem->nextBlockFast(_PREHASH_AgentData); gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID() ); gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); gMessageSystem->nextBlock("EventData"); gMessageSystem->addU32("EventID", event_id); gAgent.sendReliableMessage(); } LLEventNotification::LLEventNotification(U32 eventId, F64 eventEpoch, const std::string& eventDateStr, const std::string &eventName) : mEventID(eventId), mEventName(eventName), mEventDateEpoch(eventEpoch), mEventDateStr(eventDateStr) { }
gpl-3.0
albfan/gnome-builder
src/plugins/flatpak/gbp-flatpak-configuration.c
1
27674
/* gbp-flatpak-configuration.c * * Copyright © 2016 Matthew Leeds <mleeds@redhat.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define G_LOG_DOMAIN "gbp-flatpak-configuration" #include <json-glib/json-glib.h> #include "gbp-flatpak-configuration.h" #include "gbp-flatpak-runtime.h" struct _GbpFlatpakConfiguration { IdeConfiguration parent_instance; gchar *branch; gchar **build_args; gchar *command; gchar **finish_args; GFile *manifest; gchar *platform; gchar *primary_module; gchar *sdk; }; G_DEFINE_TYPE (GbpFlatpakConfiguration, gbp_flatpak_configuration, IDE_TYPE_CONFIGURATION) enum { PROP_0, PROP_BRANCH, PROP_BUILD_ARGS, PROP_COMMAND, PROP_FINISH_ARGS, PROP_MANIFEST, PROP_PLATFORM, PROP_PRIMARY_MODULE, PROP_SDK, N_PROPS }; static GParamSpec *properties [N_PROPS]; static void _gbp_flatpak_configuration_set_manifest (GbpFlatpakConfiguration *self, GFile *manifest); GbpFlatpakConfiguration * gbp_flatpak_configuration_new (IdeContext *context, const gchar *id, const gchar *display_name) { g_assert (IDE_IS_CONTEXT (context)); g_assert (!dzl_str_empty0 (id)); return g_object_new (GBP_TYPE_FLATPAK_CONFIGURATION, "context", context, "display-name", display_name, "id", id, NULL); } gchar * get_project_dir_name (IdeContext *context) { GFile *project_file; g_autoptr(GFileInfo) file_info = NULL; g_autoptr(GFile) project_dir = NULL; g_autofree gchar *project_file_path = NULL; g_assert (IDE_IS_CONTEXT (context)); project_file = ide_context_get_project_file (context); g_return_val_if_fail (G_IS_FILE (project_file), NULL); project_file_path = g_file_get_path (project_file); if (g_file_test (project_file_path, G_FILE_TEST_IS_DIR)) project_dir = g_object_ref (project_file); else project_dir = g_file_get_parent (project_file); return g_file_get_basename (project_dir); } JsonNode * guess_primary_module (JsonNode *modules_node, const gchar *project_dir_name) { JsonArray *modules; JsonNode *module; JsonNode *parent; g_return_val_if_fail (!dzl_str_empty0 (project_dir_name), NULL); g_return_val_if_fail (JSON_NODE_HOLDS_ARRAY (modules_node), NULL); /* TODO: Support module strings that refer to other files? */ modules = json_node_get_array (modules_node); if (json_array_get_length (modules) == 1) { module = json_array_get_element (modules, 0); if (JSON_NODE_HOLDS_OBJECT (module)) return module; } else { guint modules_len = json_array_get_length (modules); for (guint i = 0; i < modules_len; i++) { module = json_array_get_element (modules, i); if (JSON_NODE_HOLDS_OBJECT (module)) { JsonObject *obj = json_node_get_object (module); const gchar *module_name; module_name = json_object_get_string_member (obj, "name"); if (dzl_str_equal0 (module_name, project_dir_name)) return module; /* Only look at submodules if this is the last item */ if (i + 1 == modules_len && json_object_has_member (obj, "modules")) { JsonNode *nested_modules_node; JsonNode *nested_primary_module; nested_modules_node = json_object_get_member (obj, "modules"); nested_primary_module = guess_primary_module (nested_modules_node, project_dir_name); if (nested_primary_module != NULL) return nested_primary_module; } } } /* If none match, assume the last module in the list is the primary one */ parent = json_node_get_parent (modules_node); if (JSON_NODE_HOLDS_OBJECT (parent) && json_node_get_parent (parent) == NULL && modules_len > 0) { JsonNode *last_node; last_node = json_array_get_element (modules, modules_len - 1); if (JSON_NODE_HOLDS_OBJECT (last_node)) return last_node; } } return NULL; } static gchar ** get_strv_from_member (JsonObject *obj, const gchar *name) { GPtrArray *finish_args = g_ptr_array_new (); JsonNode *node = json_object_get_member (obj, name); JsonArray *ar; guint len; if (node == NULL || !JSON_NODE_HOLDS_ARRAY (node)) return NULL; ar = json_node_get_array (node); len = json_array_get_length (ar); for (guint i = 0; i < len; i++) { const gchar *arg = json_array_get_string_element (ar, i); if (!dzl_str_empty0 (arg)) g_ptr_array_add (finish_args, g_strdup (arg)); } g_ptr_array_add (finish_args, NULL); return (gchar **)g_ptr_array_free (finish_args, FALSE); } static gchar * get_argv_from_member (JsonObject *obj, const gchar *name) { g_auto(GStrv) argv = NULL; if (NULL == (argv = get_strv_from_member (obj, name))) return NULL; for (guint i = 0; argv[i]; i++) { g_autofree gchar *freeme = argv[i]; argv[i] = g_shell_quote (argv[i]); } return g_strjoinv (" ", argv); } /** * gbp_flatpak_configuration_load_from_file: * @self: a #GbpFlatpakConfiguration * @manifest: a #GFile, possibly containing a flatpak manifest * * Returns: %TRUE if the manifest is successfully parsed, %FALSE otherwise */ gboolean gbp_flatpak_configuration_load_from_file (GbpFlatpakConfiguration *self, GFile *manifest) { g_autofree gchar *path = NULL; g_autofree gchar *project_dir_name = NULL; const gchar *prefix = NULL; const gchar *platform = NULL; const gchar *sdk = NULL; const gchar *branch = NULL; const gchar *arch = NULL; const gchar *runtime_id = NULL; g_autoptr(JsonParser) parser = NULL; JsonNode *root_node = NULL; JsonNode *app_id_node = NULL; JsonNode *id_node = NULL; JsonNode *runtime_node = NULL; JsonNode *runtime_version_node = NULL; JsonNode *sdk_node = NULL; JsonNode *modules_node = NULL; JsonNode *primary_module_node = NULL; JsonNode *command_node = NULL; JsonObject *root_object = NULL; g_autoptr(GError) local_error = NULL; IdeContext *context; g_assert (GBP_IS_FLATPAK_CONFIGURATION (self)); g_assert (G_IS_FILE (manifest)); context = ide_object_get_context (IDE_OBJECT (self)); /* Check if the contents look like a flatpak manifest */ path = g_file_get_path (manifest); parser = json_parser_new (); json_parser_load_from_file (parser, path, &local_error); if (local_error != NULL) { g_warning ("Error parsing potential flatpak manifest %s: %s", path, local_error->message); return FALSE; } root_node = json_parser_get_root (parser); if (!JSON_NODE_HOLDS_OBJECT (root_node)) return FALSE; root_object = json_node_get_object (root_node); app_id_node = json_object_get_member (root_object, "app-id"); id_node = json_object_get_member (root_object, "id"); runtime_node = json_object_get_member (root_object, "runtime"); runtime_version_node = json_object_get_member (root_object, "runtime-version"); sdk_node = json_object_get_member (root_object, "sdk"); modules_node = json_object_get_member (root_object, "modules"); if (((app_id_node == NULL || !JSON_NODE_HOLDS_VALUE (app_id_node)) && (id_node == NULL || !JSON_NODE_HOLDS_VALUE (id_node))) || (runtime_node == NULL || !JSON_NODE_HOLDS_VALUE (runtime_node)) || (sdk_node == NULL || !JSON_NODE_HOLDS_VALUE (sdk_node)) || (modules_node == NULL || !JSON_NODE_HOLDS_ARRAY (modules_node))) return FALSE; IDE_TRACE_MSG ("Discovered flatpak manifest at %s", path); _gbp_flatpak_configuration_set_manifest (self, manifest); /** * TODO: Currently we just support the build-options object that's global to the * manifest, but modules can have their own build-options as well that override * global ones, so we should consider supporting that. The main difficulty would * be keeping track of each so they can be written back to the file properly when * the user makes changes in the Builder interface. */ if (json_object_has_member (root_object, "build-options") && JSON_NODE_HOLDS_OBJECT (json_object_get_member (root_object, "build-options"))) { JsonObject *build_options = NULL; IdeEnvironment *environment; build_options = json_object_get_object_member (root_object, "build-options"); if (json_object_has_member (build_options, "prefix")) prefix = json_object_get_string_member (build_options, "prefix"); environment = ide_environment_new (); if (json_object_has_member (build_options, "cflags")) { const gchar *cflags; cflags = json_object_get_string_member (build_options, "cflags"); if (cflags != NULL) ide_environment_setenv (environment, "CFLAGS", cflags); } if (json_object_has_member (build_options, "cxxflags")) { const gchar *cxxflags; cxxflags = json_object_get_string_member (build_options, "cxxflags"); if (cxxflags != NULL) ide_environment_setenv (environment, "CXXFLAGS", cxxflags); } if (json_object_has_member (build_options, "build-args")) { g_auto(GStrv) build_args = get_strv_from_member (build_options, "build-args"); gbp_flatpak_configuration_set_build_args (self, (const gchar * const *)build_args); } if (json_object_has_member (build_options, "env")) { JsonObject *env_vars; env_vars = json_object_get_object_member (build_options, "env"); if (env_vars != NULL) { g_autoptr(GList) env_list = NULL; GList *l; env_list = json_object_get_members (env_vars); for (l = env_list; l != NULL; l = l->next) { const gchar *env_name = (gchar *)l->data; const gchar *env_value = json_object_get_string_member (env_vars, env_name); if (!dzl_str_empty0 (env_name) && !dzl_str_empty0 (env_value)) ide_environment_setenv (environment, env_name, env_value); } } } ide_configuration_set_environment (IDE_CONFIGURATION (self), environment); } if (dzl_str_empty0 (prefix)) prefix = "/app"; ide_configuration_set_prefix (IDE_CONFIGURATION (self), prefix); platform = json_node_get_string (runtime_node); gbp_flatpak_configuration_set_platform (self, platform); if (JSON_NODE_HOLDS_VALUE (runtime_version_node)) branch = json_node_get_string (runtime_version_node); if (dzl_str_empty0 (branch)) branch = "master"; gbp_flatpak_configuration_set_branch (self, branch); arch = flatpak_get_default_arch (); runtime_id = g_strdup_printf ("flatpak:%s/%s/%s", platform, arch, branch); ide_configuration_set_runtime_id (IDE_CONFIGURATION (self), runtime_id); sdk = json_node_get_string (sdk_node); gbp_flatpak_configuration_set_sdk (self, sdk); /* Get the command to run for this manifest. If this is missing, then * we likely have a situation where this is a supplemental manifest * and not the primary manifest. */ command_node = json_object_get_member (root_object, "command"); if (command_node == NULL || !JSON_NODE_HOLDS_VALUE (command_node)) return FALSE; gbp_flatpak_configuration_set_command (self, json_node_get_string (command_node)); if (json_object_has_member (root_object, "finish-args")) { g_auto(GStrv) finish_args = get_strv_from_member (root_object, "finish-args"); gbp_flatpak_configuration_set_finish_args (self, (const gchar * const *)finish_args); } /* Our custom extension to store run options in the .json */ if (json_object_has_member (root_object, "x-run-args")) { g_autofree gchar *run_args = get_argv_from_member (root_object, "x-run-args"); ide_configuration_set_run_opts (IDE_CONFIGURATION (self), run_args); } if (app_id_node != NULL && JSON_NODE_HOLDS_VALUE (app_id_node)) ide_configuration_set_app_id (IDE_CONFIGURATION (self), json_node_get_string (app_id_node)); else ide_configuration_set_app_id (IDE_CONFIGURATION (self), json_node_get_string (id_node)); project_dir_name = get_project_dir_name (context); primary_module_node = guess_primary_module (modules_node, (const gchar *)project_dir_name); if (primary_module_node != NULL && JSON_NODE_HOLDS_OBJECT (primary_module_node)) { const gchar *primary_module_name; JsonObject *primary_module_object; g_autofree gchar *config_opts = NULL; primary_module_object = json_node_get_object (primary_module_node); primary_module_name = json_object_get_string_member (primary_module_object, "name"); gbp_flatpak_configuration_set_primary_module (self, primary_module_name); config_opts = get_argv_from_member (primary_module_object, "config-opts"); ide_configuration_set_config_opts (IDE_CONFIGURATION (self), config_opts); if (json_object_has_member (primary_module_object, "build-commands")) { JsonArray *build_commands_array; GPtrArray *build_commands; g_auto(GStrv) build_commands_strv = NULL; build_commands = g_ptr_array_new (); build_commands_array = json_object_get_array_member (primary_module_object, "build-commands"); for (guint i = 0; i < json_array_get_length (build_commands_array); i++) { const gchar *arg = json_array_get_string_element (build_commands_array, i); if (!dzl_str_empty0 (arg)) g_ptr_array_add (build_commands, g_strdup (arg)); } g_ptr_array_add (build_commands, NULL); build_commands_strv = (gchar **)g_ptr_array_free (build_commands, FALSE); ide_configuration_set_build_commands (IDE_CONFIGURATION (self), (const gchar * const *)build_commands_strv); } if (json_object_has_member (primary_module_object, "post-install")) { JsonArray *post_install_commands_array; GPtrArray *post_install_commands; g_auto(GStrv) post_install_commands_strv = NULL; post_install_commands = g_ptr_array_new (); post_install_commands_array = json_object_get_array_member (primary_module_object, "post-install"); for (guint i = 0; i < json_array_get_length (post_install_commands_array); i++) { const gchar *arg = json_array_get_string_element (post_install_commands_array, i); if (!dzl_str_empty0 (arg)) g_ptr_array_add (post_install_commands, g_strdup (arg)); } g_ptr_array_add (post_install_commands, NULL); post_install_commands_strv = (gchar **)g_ptr_array_free (post_install_commands, FALSE); ide_configuration_set_post_install_commands (IDE_CONFIGURATION (self), (const gchar * const *)post_install_commands_strv); } } return TRUE; } const gchar * gbp_flatpak_configuration_get_branch (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return self->branch; } void gbp_flatpak_configuration_set_branch (GbpFlatpakConfiguration *self, const gchar *branch) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); g_free (self->branch); self->branch = g_strdup (branch); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_BRANCH]); } const gchar * gbp_flatpak_configuration_get_command (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return self->command; } void gbp_flatpak_configuration_set_command (GbpFlatpakConfiguration *self, const gchar *command) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); g_free (self->command); self->command = g_strdup (command); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_COMMAND]); } const gchar * const * gbp_flatpak_configuration_get_build_args (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return (const gchar * const *)self->build_args; } void gbp_flatpak_configuration_set_build_args (GbpFlatpakConfiguration *self, const gchar * const *build_args) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); if (self->build_args != (gchar **)build_args) { g_strfreev (self->build_args); self->build_args = g_strdupv ((gchar **)build_args); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_BUILD_ARGS]); } } const gchar * const * gbp_flatpak_configuration_get_finish_args (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return (const gchar * const *)self->finish_args; } void gbp_flatpak_configuration_set_finish_args (GbpFlatpakConfiguration *self, const gchar * const *finish_args) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); if (self->finish_args != (gchar **)finish_args) { g_strfreev (self->finish_args); self->finish_args = g_strdupv ((gchar **)finish_args); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_FINISH_ARGS]); } } gchar * gbp_flatpak_configuration_get_manifest_path (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); if (self->manifest != NULL) return g_file_get_path (self->manifest); return NULL; } GFile * gbp_flatpak_configuration_get_manifest (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return self->manifest; } static void _gbp_flatpak_configuration_set_manifest (GbpFlatpakConfiguration *self, GFile *manifest) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); g_clear_object (&self->manifest); self->manifest = g_object_ref (manifest); } const gchar * gbp_flatpak_configuration_get_platform (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return self->platform; } void gbp_flatpak_configuration_set_platform (GbpFlatpakConfiguration *self, const gchar *platform) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); g_free (self->platform); self->platform = g_strdup (platform); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_PLATFORM]); } const gchar * gbp_flatpak_configuration_get_primary_module (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return self->primary_module; } void gbp_flatpak_configuration_set_primary_module (GbpFlatpakConfiguration *self, const gchar *primary_module) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); g_free (self->primary_module); self->primary_module = g_strdup (primary_module); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_PRIMARY_MODULE]); } const gchar * gbp_flatpak_configuration_get_sdk (GbpFlatpakConfiguration *self) { g_return_val_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self), NULL); return self->sdk; } void gbp_flatpak_configuration_set_sdk (GbpFlatpakConfiguration *self, const gchar *sdk) { g_return_if_fail (GBP_IS_FLATPAK_CONFIGURATION (self)); if (g_strcmp0 (self->sdk, sdk) != 0) { g_free (self->sdk); self->sdk = g_strdup (sdk); g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_SDK]); } } static gboolean gbp_flatpak_configuration_supports_runtime (IdeConfiguration *configuration, IdeRuntime *runtime) { g_assert (GBP_IS_FLATPAK_CONFIGURATION (configuration)); g_assert (IDE_IS_RUNTIME (runtime)); return GBP_IS_FLATPAK_RUNTIME (runtime); } static void gbp_flatpak_configuration_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GbpFlatpakConfiguration *self = GBP_FLATPAK_CONFIGURATION (object); switch (prop_id) { case PROP_BRANCH: g_value_set_string (value, gbp_flatpak_configuration_get_branch (self)); break; case PROP_BUILD_ARGS: g_value_set_boxed (value, gbp_flatpak_configuration_get_build_args (self)); break; case PROP_COMMAND: g_value_set_string (value, gbp_flatpak_configuration_get_command (self)); break; case PROP_FINISH_ARGS: g_value_set_boxed (value, gbp_flatpak_configuration_get_finish_args (self)); break; case PROP_MANIFEST: g_value_set_object (value, gbp_flatpak_configuration_get_manifest (self)); break; case PROP_PLATFORM: g_value_set_string (value, gbp_flatpak_configuration_get_platform (self)); break; case PROP_PRIMARY_MODULE: g_value_set_string (value, gbp_flatpak_configuration_get_primary_module (self)); break; case PROP_SDK: g_value_set_string (value, gbp_flatpak_configuration_get_sdk (self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); } } static void gbp_flatpak_configuration_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GbpFlatpakConfiguration *self = GBP_FLATPAK_CONFIGURATION (object); switch (prop_id) { case PROP_BRANCH: gbp_flatpak_configuration_set_branch (self, g_value_get_string (value)); break; case PROP_BUILD_ARGS: gbp_flatpak_configuration_set_build_args (self, g_value_get_boxed (value)); break; case PROP_COMMAND: gbp_flatpak_configuration_set_command (self, g_value_get_string (value)); break; case PROP_FINISH_ARGS: gbp_flatpak_configuration_set_finish_args (self, g_value_get_boxed (value)); break; case PROP_MANIFEST: self->manifest = g_value_dup_object (value); break; case PROP_PLATFORM: gbp_flatpak_configuration_set_platform (self, g_value_get_string (value)); break; case PROP_PRIMARY_MODULE: gbp_flatpak_configuration_set_primary_module (self, g_value_get_string (value)); break; case PROP_SDK: gbp_flatpak_configuration_set_sdk (self, g_value_get_string (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); } } static void gbp_flatpak_configuration_finalize (GObject *object) { GbpFlatpakConfiguration *self = (GbpFlatpakConfiguration *)object; g_clear_pointer (&self->branch, g_free); g_clear_pointer (&self->command, g_free); g_clear_pointer (&self->finish_args, g_strfreev); g_clear_object (&self->manifest); g_clear_pointer (&self->platform, g_free); g_clear_pointer (&self->primary_module, g_free); g_clear_pointer (&self->sdk, g_free); G_OBJECT_CLASS (gbp_flatpak_configuration_parent_class)->finalize (object); } static void gbp_flatpak_configuration_class_init (GbpFlatpakConfigurationClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); IdeConfigurationClass *config_class = IDE_CONFIGURATION_CLASS (klass); object_class->finalize = gbp_flatpak_configuration_finalize; object_class->get_property = gbp_flatpak_configuration_get_property; object_class->set_property = gbp_flatpak_configuration_set_property; config_class->supports_runtime = gbp_flatpak_configuration_supports_runtime; properties [PROP_BRANCH] = g_param_spec_string ("branch", "Branch", "Branch", NULL, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_BUILD_ARGS] = g_param_spec_boxed ("build-args", "Build args", "Build args", G_TYPE_STRV, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_COMMAND] = g_param_spec_string ("command", "Command", "Command", NULL, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_FINISH_ARGS] = g_param_spec_boxed ("finish-args", "Finish args", "Finish args", G_TYPE_STRV, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_MANIFEST] = g_param_spec_object ("manifest", "Manifest", "Manifest file", G_TYPE_FILE, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_PLATFORM] = g_param_spec_string ("platform", "Platform", "Platform", NULL, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_PRIMARY_MODULE] = g_param_spec_string ("primary-module", "Primary module", "Primary module", NULL, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); properties [PROP_SDK] = g_param_spec_string ("sdk", "Sdk", "Sdk", NULL, (G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS)); g_object_class_install_properties (object_class, N_PROPS, properties); } static void gbp_flatpak_configuration_init (GbpFlatpakConfiguration *self) { ide_configuration_set_prefix (IDE_CONFIGURATION (self), "/app"); }
gpl-3.0
MartijnB/ETGoldy
src/game/g_teammapdata.c
1
36045
/* * Wolfenstein: Enemy Territory GPL Source Code * Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. * * ET: Legacy * Copyright (C) 2012 Jan Simek <mail@etlegacy.com> * * This file is part of ET: Legacy - http://www.etlegacy.com * * ET: Legacy is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ET: Legacy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ET: Legacy. If not, see <http://www.gnu.org/licenses/>. * * In addition, Wolfenstein: Enemy Territory GPL Source Code is also * subject to certain additional terms. You should have received a copy * of these additional terms immediately following the terms and conditions * of the GNU General Public License which accompanied the source code. * If not, please request a copy in writing from id Software at the address below. * * id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. * * @file g_teammapdata.c */ #include "g_local.h" /* =================== G_PushMapEntityToBuffer =================== */ void G_PushMapEntityToBuffer(char *buffer, int size, mapEntityData_t *mEnt) { char buf[32]; if (level.ccLayers) { Com_sprintf(buf, sizeof(buf), "%i %i %i", ((int)mEnt->org[0]) / 128, ((int)mEnt->org[1]) / 128, ((int)mEnt->org[2]) / 128); } else { Com_sprintf(buf, sizeof(buf), "%i %i", ((int)mEnt->org[0]) / 128, ((int)mEnt->org[1]) / 128); } switch (mEnt->type) { // These need to be send so that icons can display correct command map layer case ME_CONSTRUCT: case ME_DESTRUCT: case ME_DESTRUCT_2: case ME_COMMANDMAP_MARKER: case ME_TANK: case ME_TANK_DEAD: Q_strcat(buffer, size, va(" %i %s %i", mEnt->type, buf, mEnt->data)); break; default: Q_strcat(buffer, size, va(" %i %s %i %i", mEnt->type, buf, mEnt->yaw, mEnt->data)); break; } } /* =================== G_InitMapEntityData =================== */ void G_InitMapEntityData(mapEntityData_Team_t *teamList) { int i; mapEntityData_t *trav, *lasttrav; memset(teamList, 0, sizeof(mapEntityData_Team_t)); teamList->activeMapEntityData.next = &teamList->activeMapEntityData; teamList->activeMapEntityData.prev = &teamList->activeMapEntityData; teamList->freeMapEntityData = teamList->mapEntityData_Team; for (i = 0, trav = teamList->mapEntityData_Team + 1, lasttrav = teamList->mapEntityData_Team ; i < MAX_GENTITIES - 1 ; i++, trav++) { lasttrav->next = trav; lasttrav = trav; } } /* ================== G_FreeMapEntityData returns next entity in the array ================== */ mapEntityData_t *G_FreeMapEntityData(mapEntityData_Team_t *teamList, mapEntityData_t *mEnt) { mapEntityData_t *ret = mEnt->next; if (!mEnt->prev) { G_Error("G_FreeMapEntityData: not active\n"); } // remove from the doubly linked active list mEnt->prev->next = mEnt->next; mEnt->next->prev = mEnt->prev; // the free list is only singly linked mEnt->next = teamList->freeMapEntityData; teamList->freeMapEntityData = mEnt; return(ret); } /* =================== G_AllocMapEntityData =================== */ mapEntityData_t *G_AllocMapEntityData(mapEntityData_Team_t *teamList) { mapEntityData_t *mEnt; if (!teamList->freeMapEntityData) { // no free entities - bomb out G_Error("G_AllocMapEntityData: out of entities\n"); } mEnt = teamList->freeMapEntityData; teamList->freeMapEntityData = teamList->freeMapEntityData->next; memset(mEnt, 0, sizeof(*mEnt)); mEnt->singleClient = -1; // link into the active list mEnt->next = teamList->activeMapEntityData.next; mEnt->prev = &teamList->activeMapEntityData; teamList->activeMapEntityData.next->prev = mEnt; teamList->activeMapEntityData.next = mEnt; return mEnt; } /* =================== G_FindMapEntityData =================== */ mapEntityData_t *G_FindMapEntityData(mapEntityData_Team_t *teamList, int entNum) { mapEntityData_t *mEnt; for (mEnt = teamList->activeMapEntityData.next; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (mEnt->singleClient >= 0) { continue; } if (entNum == mEnt->entNum) { return(mEnt); } } // not found return(NULL); } /* =============================== G_FindMapEntityDataSingleClient =============================== */ mapEntityData_t *G_FindMapEntityDataSingleClient(mapEntityData_Team_t *teamList, mapEntityData_t *start, int entNum, int clientNum) { mapEntityData_t *mEnt; if (start) { mEnt = start->next; } else { mEnt = teamList->activeMapEntityData.next; } for ( ; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (clientNum == -1) { if (mEnt->singleClient < 0) { continue; } } else if (mEnt->singleClient >= 0 && clientNum != mEnt->singleClient) { continue; } if (entNum == mEnt->entNum) { return(mEnt); } } // not found return(NULL); } //////////////////////////////////////////////////////////////////// // some culling bits typedef struct plane_s { vec3_t normal; float dist; } plane_t; static plane_t frustum[4]; /* ======================== G_SetupFrustum ======================== */ void G_SetupFrustum(gentity_t *ent) { int i; float xs, xc; float ang; vec3_t axis[3]; vec3_t vieworg; ang = (90 / 180.f) * M_PI * 0.5f; xs = sin(ang); xc = cos(ang); AnglesToAxis(ent->client->ps.viewangles, axis); VectorScale(axis[0], xs, frustum[0].normal); VectorMA(frustum[0].normal, xc, axis[1], frustum[0].normal); VectorScale(axis[0], xs, frustum[1].normal); VectorMA(frustum[1].normal, -xc, axis[1], frustum[1].normal); VectorScale(axis[0], xs, frustum[2].normal); VectorMA(frustum[2].normal, xc, axis[2], frustum[2].normal); VectorScale(axis[0], xs, frustum[3].normal); VectorMA(frustum[3].normal, -xc, axis[2], frustum[3].normal); VectorCopy(ent->client->ps.origin, vieworg); vieworg[2] += ent->client->ps.viewheight; for (i = 0 ; i < 4 ; i++) { frustum[i].dist = DotProduct(vieworg, frustum[i].normal); } } void G_SetupFrustum_ForBinoculars(gentity_t *ent) { // Give bots a larger view angle through binoculars than players get - this should help the // landmine detection... #define BINOCULAR_ANGLE 10.0f #define BOT_BINOCULAR_ANGLE 60.0f int i; float xs, xc; float ang; vec3_t axis[3]; vec3_t vieworg; float baseAngle; if (ent->r.svFlags & SVF_BOT) { baseAngle = BOT_BINOCULAR_ANGLE; } else { baseAngle = BINOCULAR_ANGLE; } ang = (baseAngle / 180.f) * M_PI * 0.5f; xs = sin(ang); xc = cos(ang); AnglesToAxis(ent->client->ps.viewangles, axis); VectorScale(axis[0], xs, frustum[0].normal); VectorMA(frustum[0].normal, xc, axis[1], frustum[0].normal); VectorScale(axis[0], xs, frustum[1].normal); VectorMA(frustum[1].normal, -xc, axis[1], frustum[1].normal); VectorScale(axis[0], xs, frustum[2].normal); VectorMA(frustum[2].normal, xc, axis[2], frustum[2].normal); VectorScale(axis[0], xs, frustum[3].normal); VectorMA(frustum[3].normal, -xc, axis[2], frustum[3].normal); VectorCopy(ent->client->ps.origin, vieworg); vieworg[2] += ent->client->ps.viewheight; for (i = 0 ; i < 4 ; i++) { frustum[i].dist = DotProduct(vieworg, frustum[i].normal); } } /* ======================== G_CullPointAndRadius - returns true if not culled ======================== */ static qboolean G_CullPointAndRadius(vec3_t pt, float radius) { int i; float dist; plane_t *frust; // check against frustum planes for (i = 0 ; i < 4 ; i++) { frust = &frustum[i]; dist = DotProduct(pt, frust->normal) - frust->dist; if (dist < -radius || dist <= radius) { return qfalse; } } return qtrue; } qboolean G_VisibleFromBinoculars(gentity_t *viewer, gentity_t *ent, vec3_t origin) { vec3_t vieworg; trace_t trace; VectorCopy(viewer->client->ps.origin, vieworg); vieworg[2] += viewer->client->ps.viewheight; if (!G_CullPointAndRadius(origin, 0)) { return qfalse; } if (!trap_InPVS(vieworg, origin)) { return qfalse; } trap_Trace(&trace, vieworg, NULL, NULL, origin, viewer->s.number, MASK_SHOT); /* if( ent && trace.entityNum != ent-g_entities ) { return qfalse; }*/ if (trace.fraction != 1.f) { if (ent) { if (trace.entityNum != ent->s.number) { return qfalse; } else { return qtrue; } } else { return qfalse; } } return qtrue; } void G_ResetTeamMapData() { G_InitMapEntityData(&mapEntityData[0]); G_InitMapEntityData(&mapEntityData[1]); } void G_UpdateTeamMapData_Construct(gentity_t *ent) { int num = ent - g_entities; mapEntityData_Team_t *teamList; mapEntityData_t *mEnt; if (ent->s.teamNum == 3) { teamList = &mapEntityData[0]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->type = ME_CONSTRUCT; mEnt->startTime = level.time; mEnt->yaw = 0; teamList = &mapEntityData[1]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->type = ME_CONSTRUCT; mEnt->startTime = level.time; mEnt->yaw = 0; return; } if (ent->s.teamNum == TEAM_AXIS) { teamList = &mapEntityData[0]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->type = ME_CONSTRUCT; mEnt->startTime = level.time; mEnt->yaw = 0; } else if (ent->s.teamNum == TEAM_ALLIES) { teamList = &mapEntityData[1]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->type = ME_CONSTRUCT; mEnt->startTime = level.time; mEnt->yaw = 0; } } void G_UpdateTeamMapData_Tank(gentity_t *ent) { int num = ent - g_entities; mapEntityData_Team_t *teamList = &mapEntityData[0]; mapEntityData_t *mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = ent->s.modelindex2; mEnt->startTime = level.time; if (ent->s.eType == ET_TANK_INDICATOR_DEAD) { mEnt->type = ME_TANK_DEAD; } else { mEnt->type = ME_TANK; } mEnt->yaw = 0; teamList = &mapEntityData[1]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = ent->s.modelindex2; mEnt->startTime = level.time; if (ent->s.eType == ET_TANK_INDICATOR_DEAD) { mEnt->type = ME_TANK_DEAD; } else { mEnt->type = ME_TANK; } mEnt->yaw = 0; } void G_UpdateTeamMapData_Destruct(gentity_t *ent) { int num = ent - g_entities; mapEntityData_Team_t *teamList; mapEntityData_t *mEnt; if (ent->s.teamNum == TEAM_AXIS) { teamList = &mapEntityData[1]; // inverted mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->startTime = level.time; mEnt->type = ME_DESTRUCT; mEnt->yaw = 0; } else { if (ent->parent->target_ent && (ent->parent->target_ent->s.eType == ET_CONSTRUCTIBLE || ent->parent->target_ent->s.eType == ET_EXPLOSIVE)) { if (ent->parent->spawnflags & ((1 << 6) | (1 << 4))) { teamList = &mapEntityData[1]; // inverted mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->startTime = level.time; mEnt->type = ME_DESTRUCT_2; mEnt->yaw = 0; } } } if (ent->s.teamNum == TEAM_ALLIES) { teamList = &mapEntityData[0]; // inverted mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->startTime = level.time; mEnt->type = ME_DESTRUCT; mEnt->yaw = 0; } else { if (ent->parent->target_ent && (ent->parent->target_ent->s.eType == ET_CONSTRUCTIBLE || ent->parent->target_ent->s.eType == ET_EXPLOSIVE)) { if (ent->parent->spawnflags & ((1 << 6) | (1 << 4))) { teamList = &mapEntityData[0]; // inverted mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.pos.trBase, mEnt->org); mEnt->data = mEnt->entNum; //ent->s.modelindex2; mEnt->startTime = level.time; mEnt->type = ME_DESTRUCT_2; mEnt->yaw = 0; } } } } void G_UpdateTeamMapData_Player(gentity_t *ent, qboolean forceAllied, qboolean forceAxis) { int num = ent - g_entities; mapEntityData_Team_t *teamList; mapEntityData_t *mEnt; if (!ent->client) { return; } if (ent->client->ps.pm_flags & PMF_LIMBO) { return; } switch (ent->client->sess.sessionTeam) { case TEAM_AXIS: forceAxis = qtrue; break; case TEAM_ALLIES: forceAllied = qtrue; break; default: break; } if (forceAxis) { teamList = &mapEntityData[0]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->client->ps.origin, mEnt->org); mEnt->yaw = ent->client->ps.viewangles[YAW]; mEnt->data = num; mEnt->startTime = level.time; if (ent->health <= 0) { mEnt->type = ME_PLAYER_REVIVE; } else { mEnt->type = ME_PLAYER; } } if (forceAllied) { teamList = &mapEntityData[1]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->client->ps.origin, mEnt->org); mEnt->yaw = ent->client->ps.viewangles[YAW]; mEnt->data = num; mEnt->startTime = level.time; if (ent->health <= 0) { mEnt->type = ME_PLAYER_REVIVE; } else { mEnt->type = ME_PLAYER; } } } static void G_UpdateTeamMapData_DisguisedPlayer(gentity_t *spotter, gentity_t *ent, qboolean forceAllied, qboolean forceAxis) { int num = ent - g_entities; mapEntityData_Team_t *teamList; mapEntityData_t *mEnt; if (!ent->client) { return; } if (ent->client->ps.pm_flags & PMF_LIMBO) { return; } switch (ent->client->sess.sessionTeam) { case TEAM_AXIS: forceAxis = qtrue; break; case TEAM_ALLIES: forceAllied = qtrue; break; default: break; } if (forceAxis) { teamList = &mapEntityData[0]; mEnt = G_FindMapEntityDataSingleClient(teamList, NULL, num, spotter->s.clientNum); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; mEnt->singleClient = spotter->s.clientNum; } VectorCopy(ent->client->ps.origin, mEnt->org); mEnt->yaw = ent->client->ps.viewangles[YAW]; mEnt->data = num; mEnt->startTime = level.time; mEnt->type = ME_PLAYER_DISGUISED; } if (forceAllied) { teamList = &mapEntityData[1]; mEnt = G_FindMapEntityDataSingleClient(teamList, NULL, num, spotter->s.clientNum); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; mEnt->singleClient = spotter->s.clientNum; } VectorCopy(ent->client->ps.origin, mEnt->org); mEnt->yaw = ent->client->ps.viewangles[YAW]; mEnt->data = num; mEnt->startTime = level.time; mEnt->type = ME_PLAYER_DISGUISED; } } void G_UpdateTeamMapData_LandMine(gentity_t *ent, qboolean forceAllied, qboolean forceAxis) { int num = ent - g_entities; mapEntityData_Team_t *teamList; mapEntityData_t *mEnt; int team = ent->s.teamNum & 3; //ent->s.teamNum % 4 if (!(ent->s.teamNum < 4 || ent->s.teamNum >= 8)) { return; // must be armed.. } // inversed teamlists, we want to see the enemy mines if (ent->s.modelindex2) // must be spotted.. { teamList = &mapEntityData[(team == TEAM_AXIS) ? 1 : 0]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->r.currentOrigin, mEnt->org); mEnt->data = team; mEnt->startTime = level.time; mEnt->type = ME_LANDMINE; } // team mines.. teamList = &mapEntityData[(team == TEAM_AXIS) ? 0 : 1]; mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->r.currentOrigin, mEnt->org); mEnt->data = team; mEnt->startTime = level.time; mEnt->type = ME_LANDMINE; } void G_UpdateTeamMapData_CommandmapMarker(gentity_t *ent) { if (!ent->parent) { return; } if (ent->entstate != STATE_DEFAULT) { return; } if (ent->parent->spawnflags & (ALLIED_OBJECTIVE | AXIS_OBJECTIVE)) { int num = ent - g_entities; mapEntityData_Team_t *teamList; mapEntityData_t *mEnt; if (ent->parent->spawnflags & ALLIED_OBJECTIVE) { teamList = &mapEntityData[0]; } if (ent->parent->spawnflags & AXIS_OBJECTIVE) { teamList = &mapEntityData[1]; } mEnt = G_FindMapEntityData(teamList, num); if (!mEnt) { mEnt = G_AllocMapEntityData(teamList); mEnt->entNum = num; } VectorCopy(ent->s.origin, mEnt->org); mEnt->data = ent->parent ? ent->parent->s.teamNum : -1; mEnt->startTime = level.time; mEnt->type = ME_COMMANDMAP_MARKER; mEnt->yaw = 0; } } void G_SendSpectatorMapEntityInfo(gentity_t *e) { // special version, sends different set of ents - only the objectives, but also team info (string is split in two basically) mapEntityData_t *mEnt; mapEntityData_Team_t *teamList = &mapEntityData[0]; // Axis data init char buffer[2048]; int al_cnt = 0, ax_cnt = 0; for (mEnt = teamList->activeMapEntityData.next; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (mEnt->type != ME_CONSTRUCT && mEnt->type != ME_DESTRUCT && mEnt->type != ME_TANK && mEnt->type != ME_TANK_DEAD) { continue; } if (mEnt->singleClient >= 0 && e->s.clientNum != mEnt->singleClient) { continue; } ax_cnt++; } // Allied data init teamList = &mapEntityData[1]; for (mEnt = teamList->activeMapEntityData.next; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (mEnt->type != ME_CONSTRUCT && mEnt->type != ME_DESTRUCT && mEnt->type != ME_TANK && mEnt->type != ME_TANK_DEAD) { continue; } if (mEnt->singleClient >= 0 && e->s.clientNum != mEnt->singleClient) { continue; } al_cnt++; } // Data setup Com_sprintf(buffer, sizeof(buffer), "entnfo %i %i", ax_cnt, al_cnt); // Axis data teamList = &mapEntityData[0]; for (mEnt = teamList->activeMapEntityData.next; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (mEnt->type != ME_CONSTRUCT && mEnt->type != ME_DESTRUCT && mEnt->type != ME_TANK && mEnt->type != ME_TANK_DEAD && mEnt->type != ME_DESTRUCT_2) { continue; } if (mEnt->singleClient >= 0 && e->s.clientNum != mEnt->singleClient) { continue; } G_PushMapEntityToBuffer(buffer, sizeof(buffer), mEnt); } // Allied data teamList = &mapEntityData[1]; for (mEnt = teamList->activeMapEntityData.next; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (mEnt->type != ME_CONSTRUCT && mEnt->type != ME_DESTRUCT && mEnt->type != ME_TANK && mEnt->type != ME_TANK_DEAD && mEnt->type != ME_DESTRUCT_2) { continue; } if (mEnt->singleClient >= 0 && e->s.clientNum != mEnt->singleClient) { continue; } G_PushMapEntityToBuffer(buffer, sizeof(buffer), mEnt); } trap_SendServerCommand(e - g_entities, buffer); } void G_SendMapEntityInfo(gentity_t *e) { mapEntityData_t *mEnt; mapEntityData_Team_t *teamList; char buffer[2048]; int cnt = 0; if (e->client->sess.sessionTeam == TEAM_SPECTATOR) { G_SendSpectatorMapEntityInfo(e); return; } // something really went wrong if this evaluates to true if (e->client->sess.sessionTeam != TEAM_AXIS && e->client->sess.sessionTeam != TEAM_ALLIES) { return; } teamList = e->client->sess.sessionTeam == TEAM_AXIS ? &mapEntityData[0] : &mapEntityData[1]; mEnt = teamList->activeMapEntityData.next; while (mEnt && mEnt != &teamList->activeMapEntityData) { if (level.time - mEnt->startTime > 5000) { mEnt->status = 1; // we can free this player from the list now if (mEnt->type == ME_PLAYER) { mEnt = G_FreeMapEntityData(teamList, mEnt); continue; } else if (mEnt->type == ME_PLAYER_DISGUISED) { if (mEnt->singleClient == e->s.clientNum) { mEnt = G_FreeMapEntityData(teamList, mEnt); continue; } } } else { mEnt->status = 2; } cnt++; mEnt = mEnt->next; } if (e->client->sess.sessionTeam == TEAM_AXIS) { Com_sprintf(buffer, sizeof(buffer), "entnfo %i 0", cnt); } else { Com_sprintf(buffer, sizeof(buffer), "entnfo 0 %i", cnt); } for (mEnt = teamList->activeMapEntityData.next; mEnt && mEnt != &teamList->activeMapEntityData; mEnt = mEnt->next) { if (mEnt->singleClient >= 0 && e->s.clientNum != mEnt->singleClient) { continue; } G_PushMapEntityToBuffer(buffer, sizeof(buffer), mEnt); } trap_SendServerCommand(e - g_entities, buffer); } void G_UpdateTeamMapData(void) { int i, j /*, k*/; gentity_t *ent, *ent2; mapEntityData_t *mEnt; if (level.time - level.lastMapEntityUpdate < 500) { return; } level.lastMapEntityUpdate = level.time; for (i = 0, ent = g_entities; i < level.num_entities; i++, ent++) { if (!ent->inuse) { // mapEntityData[0][i].valid = qfalse; // mapEntityData[1][i].valid = qfalse; continue; } switch (ent->s.eType) { case ET_PLAYER: G_UpdateTeamMapData_Player(ent, qfalse, qfalse); for (j = 0; j < 2; j++) { mapEntityData_Team_t *teamList = &mapEntityData[j]; mEnt = G_FindMapEntityDataSingleClient(teamList, NULL, ent->s.number, -1); while (mEnt) { VectorCopy(ent->client->ps.origin, mEnt->org); mEnt->yaw = ent->client->ps.viewangles[YAW]; mEnt = G_FindMapEntityDataSingleClient(teamList, mEnt, ent->s.number, -1); } } break; case ET_CONSTRUCTIBLE_INDICATOR: if (ent->parent && ent->parent->entstate == STATE_DEFAULT) { G_UpdateTeamMapData_Construct(ent); } break; case ET_EXPLOSIVE_INDICATOR: if (ent->parent && ent->parent->entstate == STATE_DEFAULT) { G_UpdateTeamMapData_Destruct(ent); } break; case ET_TANK_INDICATOR: case ET_TANK_INDICATOR_DEAD: G_UpdateTeamMapData_Tank(ent); break; case ET_MISSILE: if (ent->methodOfDeath == MOD_LANDMINE) { G_UpdateTeamMapData_LandMine(ent, qfalse, qfalse); } break; case ET_COMMANDMAP_MARKER: G_UpdateTeamMapData_CommandmapMarker(ent); break; default: break; } } //for(i = 0, ent = g_entities; i < MAX_CLIENTS; i++, ent++) { for (i = 0, ent = g_entities; i < level.num_entities; i++, ent++) { qboolean f1, f2; if (!ent->inuse || !ent->client) { continue; } if (ent->client->sess.playerType == PC_FIELDOPS) { if (ent->client->sess.skill[SK_SIGNALS] >= 4 && ent->health > 0) { vec3_t pos[3]; f1 = ent->client->sess.sessionTeam == TEAM_ALLIES ? qtrue : qfalse; f2 = ent->client->sess.sessionTeam == TEAM_AXIS ? qtrue : qfalse; G_SetupFrustum(ent); for (j = 0, ent2 = g_entities; j < level.maxclients; j++, ent2++) { if (!ent2->inuse || ent2 == ent) { continue; } //if( ent2->s.eType != ET_PLAYER ) { // continue; //} if (ent2->client->sess.sessionTeam == TEAM_SPECTATOR) { continue; } if (ent2->health <= 0 || ent2->client->sess.sessionTeam == ent->client->sess.sessionTeam || !ent2->client->ps.powerups[PW_OPS_DISGUISED]) { continue; } VectorCopy(ent2->client->ps.origin, pos[0]); pos[0][2] += ent2->client->ps.mins[2]; VectorCopy(ent2->client->ps.origin, pos[1]); VectorCopy(ent2->client->ps.origin, pos[2]); pos[2][2] += ent2->client->ps.maxs[2]; if (G_VisibleFromBinoculars(ent, ent2, pos[0]) || G_VisibleFromBinoculars(ent, ent2, pos[1]) || G_VisibleFromBinoculars(ent, ent2, pos[2])) { G_UpdateTeamMapData_DisguisedPlayer(ent, ent2, f1, f2); } } } } else if (ent->client->sess.playerType == PC_COVERTOPS) { if (ent->health > 0) { f1 = ent->client->sess.sessionTeam == TEAM_ALLIES ? qtrue : qfalse; f2 = ent->client->sess.sessionTeam == TEAM_AXIS ? qtrue : qfalse; G_SetupFrustum(ent); for (j = 0, ent2 = g_entities; j < level.num_entities; j++, ent2++) { if (!ent2->inuse || ent2 == ent) { continue; } switch (ent2->s.eType) { case ET_PLAYER: { vec3_t pos[3]; VectorCopy(ent2->client->ps.origin, pos[0]); pos[0][2] += ent2->client->ps.mins[2]; VectorCopy(ent2->client->ps.origin, pos[1]); VectorCopy(ent2->client->ps.origin, pos[2]); pos[2][2] += ent2->client->ps.maxs[2]; if (ent2->health > 0 && (G_VisibleFromBinoculars(ent, ent2, pos[0]) || G_VisibleFromBinoculars(ent, ent2, pos[1]) || G_VisibleFromBinoculars(ent, ent2, pos[2]))) { if (ent2->client->sess.sessionTeam != ent->client->sess.sessionTeam) { int k; switch (ent2->client->sess.sessionTeam) { case TEAM_AXIS: mEnt = G_FindMapEntityData(&mapEntityData[0], ent2 - g_entities); if (mEnt && level.time - mEnt->startTime > 5000) { for (k = 0; k < MAX_CLIENTS; k++) { if (g_entities[k].inuse && g_entities[k].client && g_entities[k].client->sess.sessionTeam == ent->client->sess.sessionTeam) { trap_SendServerCommand(k, va("tt \"ENEMY SPOTTED <STOP> CHECK COMMAND MAP FOR DETAILS <STOP>\"\n")); } } } break; case TEAM_ALLIES: mEnt = G_FindMapEntityData(&mapEntityData[1], ent2 - g_entities); if (mEnt && level.time - mEnt->startTime > 5000) { for (k = 0; k < MAX_CLIENTS; k++) { if (g_entities[k].inuse && g_entities[k].client && g_entities[k].client->sess.sessionTeam == ent->client->sess.sessionTeam) { trap_SendServerCommand(k, va("tt \"ENEMY SPOTTED <STOP> CHECK COMMAND MAP FOR DETAILS <STOP>\"\n")); } } } break; default: break; } } G_UpdateTeamMapData_Player(ent2, f1, f2); } break; } default: break; } } if (ent->client->ps.eFlags & EF_ZOOMING) { G_SetupFrustum_ForBinoculars(ent); for (j = 0, ent2 = g_entities; j < level.num_entities; j++, ent2++) { if (!ent2->inuse || ent2 == ent) { continue; } switch (ent2->s.eType) { case ET_MISSILE: if (ent2->methodOfDeath == MOD_LANDMINE) { if ((ent2->s.teamNum < 4 || ent2->s.teamNum >= 8) && (ent2->s.teamNum % 4 != ent->client->sess.sessionTeam)) { // as before, we can only detect a mine if we can see it from our binoculars if (G_VisibleFromBinoculars(ent, ent2, ent2->r.currentOrigin)) { G_UpdateTeamMapData_LandMine(ent2, f1, f2); switch (ent2->s.teamNum % 4) { case TEAM_AXIS: if (!ent2->s.modelindex2) { ent->client->landmineSpottedTime = level.time; ent->client->landmineSpotted = ent2; ent2->s.density = ent - g_entities + 1; ent2->missionLevel = level.time; ent->client->landmineSpotted->count2 += 50; if (ent->client->landmineSpotted->count2 >= 250) { // int k; ent->client->landmineSpotted->count2 = 250; ent->client->landmineSpotted->s.modelindex2 = 1; // for marker ent->client->landmineSpotted->s.frame = rand() % 20; ent->client->landmineSpotted->r.contents = CONTENTS_TRANSLUCENT; trap_LinkEntity(ent->client->landmineSpotted); { gentity_t *pm = G_PopupMessage(PM_MINES); VectorCopy(ent->client->landmineSpotted->r.currentOrigin, pm->s.origin); pm->s.effect2Time = TEAM_AXIS; pm->s.effect3Time = ent - g_entities; } /* for( k = 0; k < MAX_CLIENTS; k++ ) { if(g_entities[k].inuse && g_entities[k].client && g_entities[k].client->sess.sessionTeam == ent->client->sess.sessionTeam) { trap_SendServerCommand( k, va( "tt \"LANDMINES SPOTTED BY %s^0<STOP> CHECK COMMAND MAP FOR DETAILS <STOP>\"\n", ent->client->pers.netname)); } }*/ trap_SendServerCommand(ent - g_entities, "cp \"Landmine Revealed\n\""); AddScore(ent, 1); G_AddSkillPoints(ent, SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS, 3.f); G_DebugAddSkillPoints(ent, SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS, 3.f, "spotting a landmine"); } } break; case TEAM_ALLIES: if (!ent2->s.modelindex2) { ent->client->landmineSpottedTime = level.time; ent->client->landmineSpotted = ent2; ent2->s.density = ent - g_entities + 1; ent2->missionLevel = level.time; ent->client->landmineSpotted->count2 += 50; if (ent->client->landmineSpotted->count2 >= 250) { // int k; ent->client->landmineSpotted->count2 = 250; ent->client->landmineSpotted->s.modelindex2 = 1; // for marker ent->client->landmineSpotted->s.frame = rand() % 20; ent->client->landmineSpotted->r.contents = CONTENTS_TRANSLUCENT; trap_LinkEntity(ent->client->landmineSpotted); { gentity_t *pm = G_PopupMessage(PM_MINES); VectorCopy(ent->client->landmineSpotted->r.currentOrigin, pm->s.origin); pm->s.effect2Time = TEAM_ALLIES; pm->s.effect3Time = ent - g_entities; } /* for( k = 0; k < MAX_CLIENTS; k++ ) { if(g_entities[k].inuse && g_entities[k].client && g_entities[k].client->sess.sessionTeam == ent->client->sess.sessionTeam) { trap_SendServerCommand( k, va( "tt \"LANDMINES SPOTTED BY %s^0<STOP> CHECK COMMAND MAP FOR DETAILS <STOP>\"\n", ent->client->pers.netname)); } }*/ trap_SendServerCommand(ent - g_entities, "cp \"Landmine Revealed\n\""); AddScore(ent, 1); G_AddSkillPoints(ent, SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS, 3.f); G_DebugAddSkillPoints(ent, SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS, 3.f, "spotting a landmine"); } } break; } // end switch } // end (G_VisibleFromBinoculars( ent, ent2, ent2->r.currentOrigin )) else { // if we can't see the mine from our binoculars, make sure we clear out the landmineSpotted ptr, // because bots looking for mines are getting confused ent->client->landmineSpotted = NULL; } } } break; default: break; } } /* if(ent->client->landmineSpotted && !ent->client->landmineSpotted->s.modelindex2) { ent->client->landmineSpotted->count2 += 10; if(ent->client->landmineSpotted->count2 >= 250) { int k; ent->client->landmineSpotted->count2 = 250; ent->client->landmineSpotted->s.modelindex2 = 1; // for marker ent->client->landmineSpotted->s.frame = rand() % 20; for( k = 0; k < MAX_CLIENTS; k++ ) { if(g_entities[k].inuse && g_entities[k].client && g_entities[k].client->sess.sessionTeam == ent->client->sess.sessionTeam) { trap_SendServerCommand( k, va( "tt \"LANDMINES SPOTTED <STOP> CHECK COMMAND MAP FOR DETAILS <STOP>\"\n" )); } } trap_SendServerCommand( ent-g_entities, "cp \"Landmine Revealed\n\"" ); AddScore( ent, 1 ); G_AddSkillPoints( ent, SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS, 3.f ); G_DebugAddSkillPoints( ent, SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS, 3.f, "spotting a landmine" ); } }*/ /* { // find any landmines that don't actually exist anymore, see if the covert ops can see the spot and if so - wipe them mapEntityData_Team_t *teamList = ent->client->sess.sessionTeam == TEAM_AXIS ? &mapEntityData[0] : &mapEntityData[1]; mEnt = teamList->activeMapEntityData.next; while( mEnt && mEnt != &teamList->activeMapEntityData ) { if( mEnt->type == ME_LANDMINE && mEnt->entNum == -1 ) { if( G_VisibleFromBinoculars( ent, NULL, mEnt->org ) ) { mEnt = G_FreeMapEntityData( teamList, mEnt ); trap_SendServerCommand( ent-g_entities, "print \"Old Landmine Cleared\n\"" ); AddScore( ent, 1 ); continue; } } mEnt = mEnt->next; } }*/ } } } } // G_SendAllMapEntityInfo(); }
gpl-3.0
daydaygit/flrelse
linux-3.0.1/security/lsm_audit.c
2817
9074
/* * common LSM auditing functions * * Based on code written for SELinux by : * Stephen Smalley, <sds@epoch.ncsc.mil> * James Morris <jmorris@redhat.com> * Author : Etienne Basset, <etienne.basset@ensta.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. */ #include <linux/types.h> #include <linux/stddef.h> #include <linux/kernel.h> #include <linux/gfp.h> #include <linux/fs.h> #include <linux/init.h> #include <net/sock.h> #include <linux/un.h> #include <net/af_unix.h> #include <linux/audit.h> #include <linux/ipv6.h> #include <linux/ip.h> #include <net/ip.h> #include <net/ipv6.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/dccp.h> #include <linux/sctp.h> #include <linux/lsm_audit.h> /** * ipv4_skb_to_auditdata : fill auditdata from skb * @skb : the skb * @ad : the audit data to fill * @proto : the layer 4 protocol * * return 0 on success */ int ipv4_skb_to_auditdata(struct sk_buff *skb, struct common_audit_data *ad, u8 *proto) { int ret = 0; struct iphdr *ih; ih = ip_hdr(skb); if (ih == NULL) return -EINVAL; ad->u.net.v4info.saddr = ih->saddr; ad->u.net.v4info.daddr = ih->daddr; if (proto) *proto = ih->protocol; /* non initial fragment */ if (ntohs(ih->frag_off) & IP_OFFSET) return 0; switch (ih->protocol) { case IPPROTO_TCP: { struct tcphdr *th = tcp_hdr(skb); if (th == NULL) break; ad->u.net.sport = th->source; ad->u.net.dport = th->dest; break; } case IPPROTO_UDP: { struct udphdr *uh = udp_hdr(skb); if (uh == NULL) break; ad->u.net.sport = uh->source; ad->u.net.dport = uh->dest; break; } case IPPROTO_DCCP: { struct dccp_hdr *dh = dccp_hdr(skb); if (dh == NULL) break; ad->u.net.sport = dh->dccph_sport; ad->u.net.dport = dh->dccph_dport; break; } case IPPROTO_SCTP: { struct sctphdr *sh = sctp_hdr(skb); if (sh == NULL) break; ad->u.net.sport = sh->source; ad->u.net.dport = sh->dest; break; } default: ret = -EINVAL; } return ret; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) /** * ipv6_skb_to_auditdata : fill auditdata from skb * @skb : the skb * @ad : the audit data to fill * @proto : the layer 4 protocol * * return 0 on success */ int ipv6_skb_to_auditdata(struct sk_buff *skb, struct common_audit_data *ad, u8 *proto) { int offset, ret = 0; struct ipv6hdr *ip6; u8 nexthdr; ip6 = ipv6_hdr(skb); if (ip6 == NULL) return -EINVAL; ipv6_addr_copy(&ad->u.net.v6info.saddr, &ip6->saddr); ipv6_addr_copy(&ad->u.net.v6info.daddr, &ip6->daddr); ret = 0; /* IPv6 can have several extension header before the Transport header * skip them */ offset = skb_network_offset(skb); offset += sizeof(*ip6); nexthdr = ip6->nexthdr; offset = ipv6_skip_exthdr(skb, offset, &nexthdr); if (offset < 0) return 0; if (proto) *proto = nexthdr; switch (nexthdr) { case IPPROTO_TCP: { struct tcphdr _tcph, *th; th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph); if (th == NULL) break; ad->u.net.sport = th->source; ad->u.net.dport = th->dest; break; } case IPPROTO_UDP: { struct udphdr _udph, *uh; uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph); if (uh == NULL) break; ad->u.net.sport = uh->source; ad->u.net.dport = uh->dest; break; } case IPPROTO_DCCP: { struct dccp_hdr _dccph, *dh; dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph); if (dh == NULL) break; ad->u.net.sport = dh->dccph_sport; ad->u.net.dport = dh->dccph_dport; break; } case IPPROTO_SCTP: { struct sctphdr _sctph, *sh; sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph); if (sh == NULL) break; ad->u.net.sport = sh->source; ad->u.net.dport = sh->dest; break; } default: ret = -EINVAL; } return ret; } #endif static inline void print_ipv6_addr(struct audit_buffer *ab, struct in6_addr *addr, __be16 port, char *name1, char *name2) { if (!ipv6_addr_any(addr)) audit_log_format(ab, " %s=%pI6c", name1, addr); if (port) audit_log_format(ab, " %s=%d", name2, ntohs(port)); } static inline void print_ipv4_addr(struct audit_buffer *ab, __be32 addr, __be16 port, char *name1, char *name2) { if (addr) audit_log_format(ab, " %s=%pI4", name1, &addr); if (port) audit_log_format(ab, " %s=%d", name2, ntohs(port)); } /** * dump_common_audit_data - helper to dump common audit data * @a : common audit data * */ static void dump_common_audit_data(struct audit_buffer *ab, struct common_audit_data *a) { struct task_struct *tsk = current; if (a->tsk) tsk = a->tsk; if (tsk && tsk->pid) { audit_log_format(ab, " pid=%d comm=", tsk->pid); audit_log_untrustedstring(ab, tsk->comm); } switch (a->type) { case LSM_AUDIT_DATA_NONE: return; case LSM_AUDIT_DATA_IPC: audit_log_format(ab, " key=%d ", a->u.ipc_id); break; case LSM_AUDIT_DATA_CAP: audit_log_format(ab, " capability=%d ", a->u.cap); break; case LSM_AUDIT_DATA_PATH: { struct inode *inode; audit_log_d_path(ab, "path=", &a->u.path); inode = a->u.path.dentry->d_inode; if (inode) audit_log_format(ab, " dev=%s ino=%lu", inode->i_sb->s_id, inode->i_ino); break; } case LSM_AUDIT_DATA_DENTRY: { struct inode *inode; audit_log_format(ab, " name="); audit_log_untrustedstring(ab, a->u.dentry->d_name.name); inode = a->u.dentry->d_inode; if (inode) audit_log_format(ab, " dev=%s ino=%lu", inode->i_sb->s_id, inode->i_ino); break; } case LSM_AUDIT_DATA_INODE: { struct dentry *dentry; struct inode *inode; inode = a->u.inode; dentry = d_find_alias(inode); if (dentry) { audit_log_format(ab, " name="); audit_log_untrustedstring(ab, dentry->d_name.name); dput(dentry); } audit_log_format(ab, " dev=%s ino=%lu", inode->i_sb->s_id, inode->i_ino); break; } case LSM_AUDIT_DATA_TASK: tsk = a->u.tsk; if (tsk && tsk->pid) { audit_log_format(ab, " pid=%d comm=", tsk->pid); audit_log_untrustedstring(ab, tsk->comm); } break; case LSM_AUDIT_DATA_NET: if (a->u.net.sk) { struct sock *sk = a->u.net.sk; struct unix_sock *u; int len = 0; char *p = NULL; switch (sk->sk_family) { case AF_INET: { struct inet_sock *inet = inet_sk(sk); print_ipv4_addr(ab, inet->inet_rcv_saddr, inet->inet_sport, "laddr", "lport"); print_ipv4_addr(ab, inet->inet_daddr, inet->inet_dport, "faddr", "fport"); break; } case AF_INET6: { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *inet6 = inet6_sk(sk); print_ipv6_addr(ab, &inet6->rcv_saddr, inet->inet_sport, "laddr", "lport"); print_ipv6_addr(ab, &inet6->daddr, inet->inet_dport, "faddr", "fport"); break; } case AF_UNIX: u = unix_sk(sk); if (u->dentry) { struct path path = { .dentry = u->dentry, .mnt = u->mnt }; audit_log_d_path(ab, "path=", &path); break; } if (!u->addr) break; len = u->addr->len-sizeof(short); p = &u->addr->name->sun_path[0]; audit_log_format(ab, " path="); if (*p) audit_log_untrustedstring(ab, p); else audit_log_n_hex(ab, p, len); break; } } switch (a->u.net.family) { case AF_INET: print_ipv4_addr(ab, a->u.net.v4info.saddr, a->u.net.sport, "saddr", "src"); print_ipv4_addr(ab, a->u.net.v4info.daddr, a->u.net.dport, "daddr", "dest"); break; case AF_INET6: print_ipv6_addr(ab, &a->u.net.v6info.saddr, a->u.net.sport, "saddr", "src"); print_ipv6_addr(ab, &a->u.net.v6info.daddr, a->u.net.dport, "daddr", "dest"); break; } if (a->u.net.netif > 0) { struct net_device *dev; /* NOTE: we always use init's namespace */ dev = dev_get_by_index(&init_net, a->u.net.netif); if (dev) { audit_log_format(ab, " netif=%s", dev->name); dev_put(dev); } } break; #ifdef CONFIG_KEYS case LSM_AUDIT_DATA_KEY: audit_log_format(ab, " key_serial=%u", a->u.key_struct.key); if (a->u.key_struct.key_desc) { audit_log_format(ab, " key_desc="); audit_log_untrustedstring(ab, a->u.key_struct.key_desc); } break; #endif case LSM_AUDIT_DATA_KMOD: audit_log_format(ab, " kmod="); audit_log_untrustedstring(ab, a->u.kmod_name); break; } /* switch (a->type) */ } /** * common_lsm_audit - generic LSM auditing function * @a: auxiliary audit data * * setup the audit buffer for common security information * uses callback to print LSM specific information */ void common_lsm_audit(struct common_audit_data *a) { struct audit_buffer *ab; if (a == NULL) return; /* we use GFP_ATOMIC so we won't sleep */ ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_AVC); if (ab == NULL) return; if (a->lsm_pre_audit) a->lsm_pre_audit(ab, a); dump_common_audit_data(ab, a); if (a->lsm_post_audit) a->lsm_post_audit(ab, a); audit_log_end(ab); }
gpl-3.0
atkv/atkv_cuda
src/core/znzfile.c
2
6395
/** ** This file is part of the atkv project. ** Copyright 2016 Anderson Tavares <nocturne.pe@gmail.com>. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #include <at/core.h> #include <string.h> #include <stdlib.h> #undef ZNZ_MAX_BLOCK_SIZE #define ZNZ_MAX_BLOCK_SIZE (1<<30) AtZnzFile* at_znzfile_new(){ return malloc(sizeof(AtZnzFile)); } AtZnzFile* at_znzfile_open(const char* path, const char* mode, uint8_t withz){ AtZnzFile* fp = at_znzfile_new(); memset(fp,0,sizeof(AtZnzFile)); #ifdef HAVE_ZLIB fp->withz = withz; if (withz) { if((fp->zfptr = gzopen(path,mode)) == NULL) { free(fp); return NULL; } } else { #endif if((fp->nzfptr = fopen(path,mode)) == NULL) { free(fp); return NULL; } #ifdef HAVE_ZLIB } #endif return fp; } int at_znzfile_close(AtZnzFile* fp){ int retval = 0; if (fp != NULL) { #ifdef HAVE_ZLIB if (fp->zfptr!=NULL) { retval = gzclose(fp->zfptr); } #endif if (fp->nzfptr!=NULL) { retval = fclose(fp->nzfptr); } free(fp); } return retval; } size_t at_znzfile_read(AtZnzFile* fp,void* buf, size_t size, size_t nmemb){ size_t remain = size*nmemb; uint32_t nread; uint32_t n2read; char * cbuf = (char *)buf; if (fp == NULL) { return 0; } #ifdef HAVE_ZLIB if (fp->zfptr!=NULL) { /* gzread/write take unsigned int length, so maybe read in int pieces (noted by M Hanke, example given by M Adler) 6 July 2010 [rickr] */ while( remain > 0 ) { n2read = (remain < ZNZ_MAX_BLOCK_SIZE) ? remain : ZNZ_MAX_BLOCK_SIZE; nread = gzread(fp->zfptr, (void *)cbuf, n2read); if( nread < 0 ) return nread; /* returns -1 on error */ remain -= nread; cbuf += nread; /* require reading n2read bytes, so we don't get stuck */ if( nread < (int)n2read ) break; /* return will be short */ } /* warn of a short read that will seem complete */ if( remain > 0 && remain < size ) fprintf(stderr,"** znzread: read short by %u bytes\n",(unsigned)remain); return nmemb - remain/size; /* return number of members processed */ } #endif return fread(buf,size,nmemb,fp->nzfptr); } size_t at_znzfile_write(AtZnzFile* fp, const void* buf, size_t size, size_t nmemb){ size_t remain = size*nmemb; const char * cbuf = (const char *)buf; unsigned n2write; int nwritten; if (fp==NULL) { return 0; } #ifdef HAVE_ZLIB if (fp->zfptr!=NULL) { while( remain > 0 ) { n2write = (remain < ZNZ_MAX_BLOCK_SIZE) ? remain : ZNZ_MAX_BLOCK_SIZE; nwritten = gzwrite(fp->zfptr, (const void *)cbuf, n2write); /* gzread returns 0 on error, but in case that ever changes... */ if( nwritten < 0 ) return nwritten; remain -= nwritten; cbuf += nwritten; /* require writing n2write bytes, so we don't get stuck */ if( nwritten < (int)n2write ) break; } /* warn of a short write that will seem complete */ if( remain > 0 && remain < size ) fprintf(stderr,"** znzwrite: write short by %u bytes\n",(unsigned)remain); return nmemb - remain/size; /* return number of members processed */ } #endif return fwrite(buf,size,nmemb,fp->nzfptr); } long at_znzfile_seek(AtZnzFile* file, long offset, int whence) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return (long) gzseek(file->zfptr,offset,whence); #endif return fseek(file->nzfptr,offset,whence); } int at_znzfile_rewind(AtZnzFile* stream) { if (stream==NULL) { return 0; } #ifdef HAVE_ZLIB /* On some systems, gzrewind() fails for uncompressed files. Use gzseek(), instead. 10, May 2005 [rickr] if (stream->zfptr!=NULL) return gzrewind(stream->zfptr); */ if (stream->zfptr!=NULL) return (int)gzseek(stream->zfptr, 0L, SEEK_SET); #endif rewind(stream->nzfptr); return 0; } long at_znzfile_tell(AtZnzFile* file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return (long) gztell(file->zfptr); #endif return ftell(file->nzfptr); } int at_znzfile_puts(const char * str, AtZnzFile* file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzputs(file->zfptr,str); #endif return fputs(str,file->nzfptr); } char * at_znzfile_gets(char* str, int size, AtZnzFile* file) { if (file==NULL) { return NULL; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzgets(file->zfptr,str,size); #endif return fgets(str,size,file->nzfptr); } int at_znzfile_flush(AtZnzFile* file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzflush(file->zfptr,Z_SYNC_FLUSH); #endif return fflush(file->nzfptr); } int at_znzfile_eof(AtZnzFile* file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzeof(file->zfptr); #endif return feof(file->nzfptr); } int at_znzfile_putc(int c, AtZnzFile* file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzputc(file->zfptr,c); #endif return fputc(c,file->nzfptr); } int at_znzfile_getc(AtZnzFile* file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzgetc(file->zfptr); #endif return fgetc(file->nzfptr); } int at_znzfile_printf(AtZnzFile* stream, const char* format, ...){ va_list va; char *tmpstr; int retval=0; size_t size; if (stream==NULL) { return 0; } va_start(va, format); #ifdef HAVE_ZLIB if (stream->zfptr!=NULL) { size = strlen(format) + (1<<16); tmpstr = malloc(size); vsprintf(tmpstr,format,va); retval = gzprintf(stream->zfptr,"%s",tmpstr); free(tmpstr); } else { #endif retval = vfprintf(stream->nzfptr,format,va); #ifdef HAVE_ZLIB } #endif va_end(va); return retval; }
gpl-3.0
eabatalov/au-linux-kernel-autumn-2017
linux/net/ipv6/ip6_output.c
2
47288
/* * IPv6 output functions * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on linux/net/ipv4/ip_output.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * A.N.Kuznetsov : airthmetics in fragmentation. * extension headers are implemented. * route changes now work. * ip6_forward does not confuse sniffers. * etc. * * H. von Brand : Added missing #include <linux/string.h> * Imran Patel : frag id should be in NBO * Kazunori MIYAZAWA @USAGI * : add ip6_append_data and related functions * for datagram xmit */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/route.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/bpf-cgroup.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/rawv6.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/checksum.h> #include <linux/mroute6.h> #include <net/l3mdev.h> #include <net/lwtunnel.h> static int ip6_finish_output2(struct net *net, struct sock *sk, struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; struct in6_addr *nexthop; int ret; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(sk) && ((mroute6_socket(net, skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, newskb, NULL, newskb->dev, dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUTMCAST, skb->len); if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <= IPV6_ADDR_SCOPE_NODELOCAL && !(dev->flags & IFF_LOOPBACK)) { kfree_skb(skb); return 0; } } if (lwtunnel_xmit_redirect(dst->lwtstate)) { int res = lwtunnel_xmit(skb); if (res < 0 || res == LWTUNNEL_XMIT_DONE) return res; } rcu_read_lock_bh(); nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr); neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop); if (unlikely(!neigh)) neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false); if (!IS_ERR(neigh)) { sock_confirm_neigh(skb, neigh); ret = neigh_output(neigh, skb); rcu_read_unlock_bh(); return ret; } rcu_read_unlock_bh(); IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } static int ip6_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb) { int ret; ret = BPF_CGROUP_RUN_PROG_INET_EGRESS(sk, skb); if (ret) { kfree_skb(skb); return ret; } if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) || dst_allfrag(skb_dst(skb)) || (IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size)) return ip6_fragment(net, sk, skb, ip6_finish_output2); else return ip6_finish_output2(net, sk, skb); } int ip6_output(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (unlikely(idev->cnf.disable_ipv6)) { IP6_INC_STATS(net, idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb, NULL, dev, ip6_finish_output, !(IP6CB(skb)->flags & IP6SKB_REROUTED)); } /* * xmit an sk_buff (used by TCP, SCTP and DCCP) * Note : socket lock is not held for SYNACK packets, but might be modified * by calls to skb_set_owner_w() and ipv6_local_error(), * which are using proper atomic operations or spinlocks. */ int ip6_xmit(const struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, __u32 mark, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); const struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (!skb2) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } consume_skb(skb); skb = skb2; /* skb_set_owner_w() changes sk->sk_wmem_alloc atomically, * it is safe to call in our context (socket lock not held) */ skb_set_owner_w(skb, (struct sock *)sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop, &fl6->saddr); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->protocol = htons(ETH_P_IPV6); skb->priority = sk->sk_priority; skb->mark = mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); /* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */ skb = l3mdev_ip6_out((struct sock *)sk, skb); if (unlikely(!skb)) return 0; /* hooks should never assume socket lock is held. * we promote our socket to non const */ return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, (struct sock *)sk, skb, NULL, dst->dev, dst_output); } skb->dev = dst->dev; /* ipv6_local_error() does not require socket lock, * we promote our socket to non const */ ipv6_local_error((struct sock *)sk, EMSGSIZE, fl6, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } EXPORT_SYMBOL(ip6_xmit); static int ip6_call_ra_chain(struct sk_buff *skb, int sel) { struct ip6_ra_chain *ra; struct sock *last = NULL; read_lock(&ip6_ra_lock); for (ra = ip6_ra_chain; ra; ra = ra->next) { struct sock *sk = ra->sk; if (sk && ra->sel == sel && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == skb->dev->ifindex)) { if (last) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) rawv6_rcv(last, skb2); } last = sk; } } if (last) { rawv6_rcv(last, skb); read_unlock(&ip6_ra_lock); return 1; } read_unlock(&ip6_ra_lock); return 0; } static int ip6_forward_proxy_check(struct sk_buff *skb) { struct ipv6hdr *hdr = ipv6_hdr(skb); u8 nexthdr = hdr->nexthdr; __be16 frag_off; int offset; if (ipv6_ext_hdr(nexthdr)) { offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off); if (offset < 0) return 0; } else offset = sizeof(struct ipv6hdr); if (nexthdr == IPPROTO_ICMPV6) { struct icmp6hdr *icmp6; if (!pskb_may_pull(skb, (skb_network_header(skb) + offset + 1 - skb->data))) return 0; icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset); switch (icmp6->icmp6_type) { case NDISC_ROUTER_SOLICITATION: case NDISC_ROUTER_ADVERTISEMENT: case NDISC_NEIGHBOUR_SOLICITATION: case NDISC_NEIGHBOUR_ADVERTISEMENT: case NDISC_REDIRECT: /* For reaction involving unicast neighbor discovery * message destined to the proxied address, pass it to * input function. */ return 1; default: break; } } /* * The proxying router can't forward traffic sent to a link-local * address, so signal the sender and discard the packet. This * behavior is clarified by the MIPv6 specification. */ if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) { dst_link_failure(skb); return -1; } return 0; } static inline int ip6_forward_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { return dst_output(net, sk, skb); } static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst) { unsigned int mtu; struct inet6_dev *idev; if (dst_metric_locked(dst, RTAX_MTU)) { mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; } mtu = IPV6_MIN_MTU; rcu_read_lock(); idev = __in6_dev_get(dst->dev); if (idev) mtu = idev->cnf.mtu6; rcu_read_unlock(); return mtu; } static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; /* ipv6 conntrack defrag sets max_frag_size + ignore_df */ if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu) return true; if (skb->ignore_df) return false; if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu)) return false; return true; } int ip6_forward(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr = ipv6_hdr(skb); struct inet6_skb_parm *opt = IP6CB(skb); struct net *net = dev_net(dst->dev); u32 mtu; if (net->ipv6.devconf_all->forwarding == 0) goto error; if (skb->pkt_type != PACKET_HOST) goto drop; if (unlikely(skb->sk)) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } skb_forward_csum(skb); /* * We DO NOT make any processing on * RA packets, pushing them to user level AS IS * without ane WARRANTY that application will be able * to interpret them. The reason is that we * cannot make anything clever here. * * We are not end-node, so that if packet contains * AH/ESP, we cannot make anything. * Defragmentation also would be mistake, RA packets * cannot be fragmented, because there is no warranty * that different fragments will go along one path. --ANK */ if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) { if (ip6_call_ra_chain(skb, ntohs(opt->ra))) return 0; } /* * check and decrement ttl */ if (hdr->hop_limit <= 1) { /* Force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS); kfree_skb(skb); return -ETIMEDOUT; } /* XXX: idev->cnf.proxy_ndp? */ if (net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) { int proxied = ip6_forward_proxy_check(skb); if (proxied > 0) return ip6_input(skb); else if (proxied < 0) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } } if (!xfrm6_route_forward(skb)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } dst = skb_dst(skb); /* IPv6 specs say nothing about it, but it is clear that we cannot send redirects to source routed frames. We don't send redirects to frames decapsulated from IPsec. */ if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) { struct in6_addr *target = NULL; struct inet_peer *peer; struct rt6_info *rt; /* * incoming and outgoing devices are the same * send a redirect. */ rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) target = &rt->rt6i_gateway; else target = &hdr->daddr; peer = inet_getpeer_v6(net->ipv6.peers, &hdr->daddr, 1); /* Limit redirects both by destination (here) and by source (inside ndisc_send_redirect) */ if (inet_peer_xrlim_allow(peer, 1*HZ)) ndisc_send_redirect(skb, target); if (peer) inet_putpeer(peer); } else { int addrtype = ipv6_addr_type(&hdr->saddr); /* This check is security critical. */ if (addrtype == IPV6_ADDR_ANY || addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK)) goto error; if (addrtype & IPV6_ADDR_LINKLOCAL) { icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_NOT_NEIGHBOUR, 0); goto error; } } mtu = ip6_dst_mtu_forward(dst); if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (ip6_pkt_too_big(skb, mtu)) { /* Again, force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS); __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (skb_cow(skb, dst->dev->hard_header_len)) { __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS); goto drop; } hdr = ipv6_hdr(skb); /* Mangling hops number delayed to point after skb COW */ hdr->hop_limit--; __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS); __IP6_ADD_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, net, NULL, skb, skb->dev, dst->dev, ip6_forward_finish); error: __IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS); drop: kfree_skb(skb); return -EINVAL; } static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); } int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb, int (*output)(struct net *, struct sock *, struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id; int ptr, offset = 0, err = 0; u8 *prevhdr, nexthdr = 0; err = ip6_find_1stfragopt(skb, &prevhdr); if (err < 0) goto fail; hlen = err; nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (unlikely(!skb->ignore_df && skb->len > mtu)) goto fail_toobig; if (IP6CB(skb)->frag_max_size) { if (IP6CB(skb)->frag_max_size > mtu) goto fail_toobig; /* don't send fragments larger than what we received */ mtu = IP6CB(skb)->frag_max_size; if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } if (mtu < hlen + sizeof(struct frag_hdr) + 8) goto fail_toobig; mtu -= hlen + sizeof(struct frag_hdr); frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr); if (skb->ip_summed == CHECKSUM_PARTIAL && (err = skb_checksum_help(skb))) goto fail; hroom = LL_RESERVED_SPACE(rt->dst.dev); if (skb_has_frag_list(skb)) { unsigned int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb) || skb_headroom(skb) < (hroom + sizeof(struct frag_hdr))) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr))) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { err = -ENOMEM; goto fail; } frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); __skb_pull(skb, hlen); fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); fh->identification = frag_id; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(net, sk, skb); if (!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); ip6_rt_put(rt); return 0; } kfree_skb_list(frag); IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); ip6_rt_put(rt); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while (left > 0) { u8 *fragnexthdr_offset; len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* Allocate buffer */ frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC); if (!frag) { err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); fragnexthdr_offset = skb_network_header(frag); fragnexthdr_offset += prevhdr - skb_network_header(skb); *fragnexthdr_offset = NEXTHDR_FRAGMENT; /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; fh->identification = frag_id; /* * Copy a block of the IP datagram. */ BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag), len)); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(net, sk, frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); consume_skb(skb); return err; fail_toobig: if (skb->sk && dst_allfrag(skb_dst(skb))) sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK); skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); err = -EMSGSIZE; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } static inline int ip6_rt_check(const struct rt6key *rt_key, const struct in6_addr *fl_addr, const struct in6_addr *addr_cache) { return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) && (!addr_cache || !ipv6_addr_equal(fl_addr, addr_cache)); } static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (!(fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF) && (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex))) { dst_release(dst); dst = NULL; } out: return dst; } static int ip6_dst_lookup_tail(struct net *net, const struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD struct neighbour *n; struct rt6_info *rt; #endif int err; int flags = 0; /* The correct way to handle this would be to do * ip6_route_get_saddr, and then ip6_route_output; however, * the route-specific preferred source forces the * ip6_route_output call _before_ ip6_route_get_saddr. * * In source specific routing (no src=any default route), * ip6_route_output will fail given src=any saddr, though, so * that's why we try it again later. */ if (ipv6_addr_any(&fl6->saddr) && (!*dst || !(*dst)->error)) { struct rt6_info *rt; bool had_dst = *dst != NULL; if (!had_dst) *dst = ip6_route_output(net, sk, fl6); rt = (*dst)->error ? NULL : (struct rt6_info *)*dst; err = ip6_route_get_saddr(net, rt, &fl6->daddr, sk ? inet6_sk(sk)->srcprefs : 0, &fl6->saddr); if (err) goto out_err_release; /* If we had an erroneous initial result, pretend it * never existed and let the SA-enabled version take * over. */ if (!had_dst && (*dst)->error) { dst_release(*dst); *dst = NULL; } if (fl6->flowi6_oif) flags |= RT6_LOOKUP_F_IFACE; } if (!*dst) *dst = ip6_route_output_flags(net, sk, fl6, flags); err = (*dst)->error; if (err) goto out_err_release; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * Here if the dst entry we've looked up * has a neighbour entry that is in the INCOMPLETE * state and the src address from the flow is * marked as OPTIMISTIC, we release the found * dst entry and replace it instead with the * dst entry of the nexthop router */ rt = (struct rt6_info *) *dst; rcu_read_lock_bh(); n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr)); err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0; rcu_read_unlock_bh(); if (err) { struct inet6_ifaddr *ifp; struct flowi6 fl_gw6; int redirect; ifp = ipv6_get_ifaddr(net, &fl6->saddr, (*dst)->dev, 1); redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC); if (ifp) in6_ifa_put(ifp); if (redirect) { /* * We need to get the dst entry for the * default router instead */ dst_release(*dst); memcpy(&fl_gw6, fl6, sizeof(struct flowi6)); memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr)); *dst = ip6_route_output(net, sk, &fl_gw6); err = (*dst)->error; if (err) goto out_err_release; } } #endif if (ipv6_addr_v4mapped(&fl6->saddr) && !(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) { err = -EAFNOSUPPORT; goto out_err_release; } return 0; out_err_release: dst_release(*dst); *dst = NULL; if (err == -ENETUNREACH) IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES); return err; } /** * ip6_dst_lookup - perform route lookup on flow * @sk: socket which provides route info * @dst: pointer to dst_entry * for result * @fl6: flow to lookup * * This function performs a route lookup on the given flow. * * It returns zero on success, or a standard errno code on error. */ int ip6_dst_lookup(struct net *net, struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { *dst = NULL; return ip6_dst_lookup_tail(net, sk, dst, fl6); } EXPORT_SYMBOL_GPL(ip6_dst_lookup); /** * ip6_dst_lookup_flow - perform route lookup on flow with ipsec * @sk: socket which provides route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_dst_lookup_flow(const struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sock_net(sk), sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); /** * ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. * It will take the socket dst lock when operating on the dst cache. * As a result, this function can only be used in process context. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); dst = ip6_sk_dst_check(sk, dst, fl6); if (!dst) dst = ip6_dst_lookup_flow(sk, fl6, final_dst); return dst; } EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow); static inline int ip6_ufo_append_data(struct sock *sk, struct sk_buff_head *queue, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int exthdrlen, int transhdrlen, int mtu, unsigned int flags, const struct flowi6 *fl6) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ skb = skb_peek_tail(queue); if (!skb) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (!skb) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_set_network_header(skb, exthdrlen); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->csum = 0; if (flags & MSG_CONFIRM) skb_set_dst_pending_confirm(skb, 1); __skb_queue_tail(queue, skb); } else if (skb_is_gso(skb)) { goto append; } skb->ip_summed = CHECKSUM_PARTIAL; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; skb_shinfo(skb)->ip6_frag_id = ipv6_select_ident(sock_net(sk), &fl6->daddr, &fl6->saddr); append: return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, unsigned int orig_mtu) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (!skb) { /* first fragment, reserve header_len */ *mtu = orig_mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = orig_mtu; } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } static int ip6_setup_cork(struct sock *sk, struct inet_cork_full *cork, struct inet6_cork *v6_cork, struct ipcm6_cookie *ipc6, struct rt6_info *rt, struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); unsigned int mtu; struct ipv6_txoptions *opt = ipc6->opt; /* * setup for corking */ if (opt) { if (WARN_ON(v6_cork->opt)) return -EINVAL; v6_cork->opt = kzalloc(opt->tot_len, sk->sk_allocation); if (unlikely(!v6_cork->opt)) return -ENOBUFS; v6_cork->opt->tot_len = opt->tot_len; v6_cork->opt->opt_flen = opt->opt_flen; v6_cork->opt->opt_nflen = opt->opt_nflen; v6_cork->opt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation); if (opt->dst0opt && !v6_cork->opt->dst0opt) return -ENOBUFS; v6_cork->opt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation); if (opt->dst1opt && !v6_cork->opt->dst1opt) return -ENOBUFS; v6_cork->opt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation); if (opt->hopopt && !v6_cork->opt->hopopt) return -ENOBUFS; v6_cork->opt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation); if (opt->srcrt && !v6_cork->opt->srcrt) return -ENOBUFS; /* need source address above miyazawa*/ } dst_hold(&rt->dst); cork->base.dst = &rt->dst; cork->fl.u.ip6 = *fl6; v6_cork->hop_limit = ipc6->hlimit; v6_cork->tclass = ipc6->tclass; if (rt->dst.flags & DST_XFRM_TUNNEL) mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(&rt->dst); else mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(rt->dst.path); if (np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } cork->base.fragsize = mtu; if (dst_allfrag(rt->dst.path)) cork->base.flags |= IPCORK_ALLFRAG; cork->base.length = 0; return 0; } static int __ip6_append_data(struct sock *sk, struct flowi6 *fl6, struct sk_buff_head *queue, struct inet_cork *cork, struct inet6_cork *v6_cork, struct page_frag *pfrag, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, unsigned int flags, struct ipcm6_cookie *ipc6, const struct sockcm_cookie *sockc) { struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen = 0; int dst_exthdrlen = 0; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; struct rt6_info *rt = (struct rt6_info *)cork->dst; struct ipv6_txoptions *opt = v6_cork->opt; int csummode = CHECKSUM_NONE; unsigned int maxnonfragsize, headersize; skb = skb_peek_tail(queue); if (!skb) { exthdrlen = opt ? opt->opt_flen : 0; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } mtu = cork->fragsize; orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (cork->length + length > mtu - headersize && ipc6->dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; if (cork->length + length > maxnonfragsize - headersize) { emsgsize: ipv6_local_error(sk, EMSGSIZE, fl6, mtu - headersize + sizeof(struct ipv6hdr)); return -EMSGSIZE; } /* CHECKSUM_PARTIAL only with no extension headers and when * we are not going to fragment */ if (transhdrlen && sk->sk_protocol == IPPROTO_UDP && headersize == sizeof(struct ipv6hdr) && length <= mtu - headersize && !(flags & MSG_MORE) && rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM)) csummode = CHECKSUM_PARTIAL; if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, sockc->tsflags, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ cork->length += length; if ((skb && skb_is_gso(skb)) || (((length + (skb ? skb->len : headersize)) > mtu) && (skb_queue_len(queue) <= 1) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) && (sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk))) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length, hh_len, fragheaderlen, exthdrlen, transhdrlen, mtu, flags, fl6); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (!skb || !skb_prev) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; goto error; } if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(!skb)) err = -ENOBUFS; } if (!skb) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; if ((flags & MSG_CONFIRM) && !skb_prev) skb_set_dst_pending_confirm(skb, 1); /* * Put the packet on the pending queue */ __skb_queue_tail(queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; } int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); int exthdrlen; int err; if (flags&MSG_PROBE) return 0; if (skb_queue_empty(&sk->sk_write_queue)) { /* * setup for corking */ err = ip6_setup_cork(sk, &inet->cork, &np->cork, ipc6, rt, fl6); if (err) return err; exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); length += exthdrlen; transhdrlen += exthdrlen; } else { fl6 = &inet->cork.fl.u.ip6; transhdrlen = 0; } return __ip6_append_data(sk, fl6, &sk->sk_write_queue, &inet->cork.base, &np->cork, sk_page_frag(sk), getfrag, from, length, transhdrlen, flags, ipc6, sockc); } EXPORT_SYMBOL_GPL(ip6_append_data); static void ip6_cork_release(struct inet_cork_full *cork, struct inet6_cork *v6_cork) { if (v6_cork->opt) { kfree(v6_cork->opt->dst0opt); kfree(v6_cork->opt->dst1opt); kfree(v6_cork->opt->hopopt); kfree(v6_cork->opt->srcrt); kfree(v6_cork->opt); v6_cork->opt = NULL; } if (cork->base.dst) { dst_release(cork->base.dst); cork->base.dst = NULL; cork->base.flags &= ~IPCORK_ALLFRAG; } memset(&cork->fl, 0, sizeof(cork->fl)); } struct sk_buff *__ip6_make_skb(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = v6_cork->opt; struct rt6_info *rt = (struct rt6_info *)cork->base.dst; struct flowi6 *fl6 = &cork->fl.u.ip6; unsigned char proto = fl6->flowi6_proto; skb = __skb_dequeue(queue); if (!skb) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ skb->ignore_df = ip6_sk_ignore_df(sk); *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst, &fl6->saddr); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, v6_cork->tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel, fl6)); hdr->hop_limit = v6_cork->hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } ip6_cork_release(cork, v6_cork); out: return skb; } int ip6_send_skb(struct sk_buff *skb) { struct net *net = sock_net(skb->sk); struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); int err; err = ip6_local_out(net, skb->sk, skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); } return err; } int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; skb = ip6_finish_skb(sk); if (!skb) return 0; return ip6_send_skb(skb); } EXPORT_SYMBOL_GPL(ip6_push_pending_frames); static void __ip6_flush_pending_frames(struct sock *sk, struct sk_buff_head *queue, struct inet_cork_full *cork, struct inet6_cork *v6_cork) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(queue)) != NULL) { if (skb_dst(skb)) IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); } ip6_cork_release(cork, v6_cork); } void ip6_flush_pending_frames(struct sock *sk) { __ip6_flush_pending_frames(sk, &sk->sk_write_queue, &inet_sk(sk)->cork, &inet6_sk(sk)->cork); } EXPORT_SYMBOL_GPL(ip6_flush_pending_frames); struct sk_buff *ip6_make_skb(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm6_cookie *ipc6, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, const struct sockcm_cookie *sockc) { struct inet_cork_full cork; struct inet6_cork v6_cork; struct sk_buff_head queue; int exthdrlen = (ipc6->opt ? ipc6->opt->opt_flen : 0); int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.base.flags = 0; cork.base.addr = 0; cork.base.opt = NULL; v6_cork.opt = NULL; err = ip6_setup_cork(sk, &cork, &v6_cork, ipc6, rt, fl6); if (err) return ERR_PTR(err); if (ipc6->dontfrag < 0) ipc6->dontfrag = inet6_sk(sk)->dontfrag; err = __ip6_append_data(sk, fl6, &queue, &cork.base, &v6_cork, &current->task_frag, getfrag, from, length + exthdrlen, transhdrlen + exthdrlen, flags, ipc6, sockc); if (err) { __ip6_flush_pending_frames(sk, &queue, &cork, &v6_cork); return ERR_PTR(err); } return __ip6_make_skb(sk, &queue, &cork, &v6_cork); }
gpl-3.0
Petr-Kovalev/nupic-win32
nta/algorithms/SegmentUpdate.cpp
2
2751
/* * --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ #include <nta/utils/Log.hpp> #include <nta/algorithms/SegmentUpdate.hpp> #include <nta/algorithms/Cells4.hpp> using namespace nta::algorithms::Cells4; SegmentUpdate::SegmentUpdate() : _sequenceSegment(false), _cellIdx((UInt) -1), _segIdx((UInt) -1), _timeStamp((UInt) -1), _synapses(), _phase1Flag(false), _weaklyPredicting(false) {} SegmentUpdate::SegmentUpdate(UInt cellIdx, UInt segIdx, bool sequenceSegment, UInt timeStamp, const std::vector<UInt>& synapses, bool phase1Flag, bool weaklyPredicting, Cells4* cells) : _sequenceSegment(sequenceSegment), _cellIdx(cellIdx), _segIdx(segIdx), _timeStamp(timeStamp), _synapses(synapses), _phase1Flag(phase1Flag), _weaklyPredicting(weaklyPredicting) { NTA_ASSERT(invariants(cells)); } //-------------------------------------------------------------------------------- SegmentUpdate::SegmentUpdate(const SegmentUpdate& o) { _cellIdx = o._cellIdx; _segIdx = o._segIdx; _sequenceSegment = o._sequenceSegment; _synapses = o._synapses; _timeStamp = o._timeStamp; _phase1Flag = o._phase1Flag; _weaklyPredicting = o._weaklyPredicting; NTA_ASSERT(invariants()); } bool SegmentUpdate::invariants(Cells4* cells) const { bool ok = true; if (cells) { ok &= _cellIdx < cells->nCells(); if (_segIdx != (UInt) -1) ok &= _segIdx < cells->__nSegmentsOnCell(_cellIdx); if (!_synapses.empty()) { for (UInt i = 0; i != _synapses.size(); ++i) ok &= _synapses[i] < cells->nCells(); ok &= is_sorted(_synapses, true, true); } } return ok; }
gpl-3.0
darioizzo/pykep
src/third_party/cspice/ev2lin.c
2
45122
/* ev2lin.f -- translated by f2c (version 19980913). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* Table of constant values */ static doublereal c_b91 = .66666666666666663; static doublereal c_b92 = 3.5; static doublereal c_b153 = 1.5; static integer c__20 = 20; /* $Procedure EV2LIN ( Evaluate "two-line" element data) */ /* Subroutine */ int ev2lin_(doublereal *et, doublereal *geophs, doublereal * elems, doublereal *state) { /* Initialized data */ static logical doinit = TRUE_; /* System generated locals */ integer i__1; doublereal d__1; /* Builtin functions */ integer s_rnge(char *, integer, char *, integer); double cos(doublereal), sin(doublereal), sqrt(doublereal), pow_dd( doublereal *, doublereal *), d_mod(doublereal *, doublereal *), atan2(doublereal, doublereal); /* Local variables */ static integer head; static doublereal coef, eeta, delm, aodp, delo, capu, xmdf, aynl, elsq, temp; static integer last; static doublereal rdot, cosu, tokm; static integer list[12] /* was [2][6] */; static doublereal sinu, coef1, t2cof, t3cof, t4cof, t5cof, temp1, temp2, temp3, temp4, temp5, cos2u, temp6, mov1m, sin2u, a, e, f; static integer i__, j; static doublereal m; static integer n; static doublereal r__, s, u, betal, omega, betao; extern /* Subroutine */ int chkin_(char *, ftnlen); static doublereal epoch, ecose, aycof, delmo, esine, a3ovk2, tcube, cosik, tempa, bstar, cosio, xincl, etasq, rfdot, sinik, a1, rdotk, c1, c2, c3, c4, c5, cosuk, d2, d3, j2, j3, j4, qomso, d4, lower; extern doublereal twopi_(void); static doublereal q1, q2, psisq, qoms24, s4, sinio, sinmo, sinuk, tempe, betao2, betao3, betao4, templ, tfour, upper, x1m5th, x1mth2, x3thm1, x7thm1, fmod2p, theta2, theta4, xinck, xlcof, xmcof, xmdot, xnode, xnodp; static integer count; static doublereal xndd6o; static integer after; static logical recog, unrec; static doublereal ae, xhdot1; extern /* Subroutine */ int errdp_(char *, doublereal *, ftnlen); static doublereal xndt2o, ke, ao, fl, eo, qoms2t, er, fu, pl, omgadf, rk, qo, uk, so, xl; static integer before; static doublereal xn, omegao, delomg; extern doublereal brcktd_(doublereal *, doublereal *, doublereal *); static doublereal omgcof, perige, ux, uy, uz, fprime, elemnt[60] /* was [10][6] */, tsince, ae2, ae3, ae4, epsiln, xnodeo, cosnok, lstgeo[8], omgdot, ck2, cosepw, ck4, prelim[174] /* was [29][6] */, rfdotk, sinepw, sinnok, vx, tokmps, vy, pinvsq, vz, xnodcf, xnoddf, xnodek, epwnxt, xnodot; static logical newgeo; extern /* Subroutine */ int setmsg_(char *, ftnlen), errint_(char *, integer *, ftnlen), sigerr_(char *, ftnlen), chkout_(char *, ftnlen); static doublereal eta, axn, ayn, epw, est, tsi, xll, xmo, xno, xmp, tsq, xlt, xmx, xmy, del1, c1sq, pix2; /* $ Abstract */ /* This routine evaluates NORAD two-line element data for */ /* near-earth orbiting spacecraft (that is spacecraft with */ /* orbital periods less than 225 minutes). */ /* $ Disclaimer */ /* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ /* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ /* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ /* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ /* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ /* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ /* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ /* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ /* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ /* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ /* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ /* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ /* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ /* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ /* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ /* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ /* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ /* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ /* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ /* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ /* $ Required_Reading */ /* None. */ /* $ Keywords */ /* EPHEMERIS */ /* $ Declarations */ /* $ Brief_I/O */ /* VARIABLE I/O DESCRIPTION */ /* -------- --- -------------------------------------------------- */ /* ET I Epoch in seconds past ephemeris epoch J2000. */ /* GEOPHS I Geophysical constants */ /* ELEMS I Two-line element data */ /* STATE O Evaluated state */ /* NMODL P Parameter controlling number of buffered elements. */ /* $ Detailed_Input */ /* ET is the poch in seconds past ephemeris epoch J2000 */ /* at which a state should be produced from the */ /* input elements. */ /* GEOPHS is a collection of 8 geophysical constants needed */ /* for computing a state. The order of these */ /* constants must be: */ /* GEOPHS(1) = J2 gravitational harmonic for earth */ /* GEOPHS(2) = J3 gravitational harmonic for earth */ /* GEOPHS(3) = J4 gravitational harmonic for earth */ /* These first three constants are dimensionless. */ /* GEOPHS(4) = KE: Square root of the GM for earth where */ /* GM is expressed in earth radii cubed per */ /* minutes squared. */ /* GEOPHS(5) = QO: Low altitude bound for atmospheric */ /* model in km. */ /* GEOPHS(6) = SO: High altitude bound for atmospheric */ /* model in km. */ /* GEOPHS(7) = RE: Equatorial radius of the earth in km. */ /* GEOPHS(8) = AE: Distance units/earth radius */ /* (normally 1) */ /* Below are currently recommended values for these */ /* items: */ /* J2 = 1.082616D-3 */ /* J3 = -2.53881D-6 */ /* J4 = -1.65597D-6 */ /* The next item is the square root of GM for the */ /* earth given in units of earth-radii**1.5/Minute */ /* KE = 7.43669161D-2 */ /* The next two items give the top and */ /* bottom of the atmospheric drag model */ /* used by the type 10 ephemeris type. */ /* Don't adjust these unless you understand */ /* the full implications of such changes. */ /* QO = 120.0D0 */ /* SO = 78.0D0 */ /* The following is the equatorial radius */ /* of the earth as used by NORAD in km. */ /* ER = 6378.135D0 */ /* The value of AE is the number of */ /* distance units per earth radii used by */ /* the NORAD state propagation software. */ /* The value should be 1 unless you've got */ /* a very good understanding of the NORAD */ /* routine SGP4 and the affect of changing */ /* this value.. */ /* AE = 1.0D0 */ /* ELEMS is an array containg two-line element data */ /* as prescribed below. The elements XNDD6O and BSTAR */ /* must already be scaled by the proper exponent stored */ /* in the two line elements set. Moreover, the */ /* various items must be converted to the units shown */ /* here. */ /* ELEMS ( 1 ) = XNDT2O in radians/minute**2 */ /* ELEMS ( 2 ) = XNDD6O in radians/minute**3 */ /* ELEMS ( 3 ) = BSTAR */ /* ELEMS ( 4 ) = XINCL in radians */ /* ELEMS ( 5 ) = XNODEO in radians */ /* ELEMS ( 6 ) = EO */ /* ELEMS ( 7 ) = OMEGAO in radians */ /* ELEMS ( 8 ) = XMO in radians */ /* ELEMS ( 9 ) = XNO in radians/minute */ /* ELEMS ( 10 ) = EPOCH of the elements in seconds */ /* past ephemeris epoch J2000. */ /* $ Detailed_Output */ /* STATE is the state produced by evaluating the input elements */ /* at the input epoch ET. Units are km and km/sec. */ /* $ Parameters */ /* NMODL is a parameter that controls how many element sets */ /* can be buffered internally. Since there are a lot */ /* of computations that are independent of time these */ /* are buffered and only computed if an unbuffered */ /* model is supplied. This value should always */ /* be at least 2. Increasing it a great deal is not */ /* advised since the time needed to search the */ /* buffered elements for a match increases linearly */ /* with the NMODL. Imperically, 6 seems to be a good */ /* break even value for NMODL. */ /* $ Exceptions */ /* 1) No checks are made on the reasonableness of the inputs. */ /* 2) SPICE(ITERATIONEXCEEDED) signals if the EST calculation loop */ /* exceds the MXLOOP value. This error should signal only for */ /* bad (nonphysical) TLEs. */ /* $ Files */ /* None. */ /* $ Particulars */ /* This routine evaluates NORAD two-line element sets for */ /* near-earth orbitting satellites. Near earth is defined to */ /* be a satellite with an orbital period of less than 225 */ /* minutes. This code is an adaptation of the NORAD routine */ /* SGP4 to elliminate common blocks, allow buffering of models */ /* and intermediate parameters and double precision calculations. */ /* $ Examples */ /* None. */ /* $ Restrictions */ /* None. */ /* $ Literature_References */ /* None. */ /* $ Author_and_Institution */ /* W.L. Taber (JPL) */ /* $ Version */ /* - SPICELIB Version 1.1.0, 15-SEP-2014 (EDW) */ /* Added error check to prevent infinite loop in */ /* calculation of EST. */ /* - SPICELIB Version 1.0.3, 02-JAN-2008 (EDW) */ /* Corrected error in the calculation of the C4 term */ /* identified by Curtis Haase. */ /* Minor edit to the COEF1 declaration strictly */ /* identifying the constant as a double. */ /* From: */ /* COEF1 = COEF / PSISQ**3.5 */ /* To: */ /* COEF1 = COEF / PSISQ**3.5D0 */ /* - SPICELIB Version 1.0.2, 08-JUL-2004 (EDW) */ /* Corrected error in the calculation of the C2 term. */ /* Reordered C1, C2 calculations to avoid division */ /* by BSTAR. */ /* - SPICELIB Version 1.0.1, 10-MAR-1998 (EDW) */ /* Corrected error in header describing the GEOPHS array. */ /* - SPICELIB Version 1.0.0, 14-JAN-1994 (WLT) */ /* -& */ /* $ Index_Entries */ /* Evaluate NORAD two-line element data. */ /* -& */ /* Spicelib functions */ /* Local Parameters */ /* The following parameters give the location of the various */ /* geophysical parameters needed for the two line element */ /* sets. */ /* KJ2 --- location of J2 */ /* KJ3 --- location of J3 */ /* KJ4 --- location if J4 */ /* KKE --- location of KE = sqrt(GM) in eart-radii**1.5/MIN */ /* KQO --- upper bound of atmospheric model in KM */ /* KSO --- lower bound of atmospheric model in KM */ /* KER --- earth equatorial radius in KM. */ /* KAE --- distance units/earth radius */ /* An enumeration of the various components of the */ /* elements array---ELEMS */ /* KNDT20 */ /* KNDD60 */ /* KBSTAR */ /* KINCL */ /* KNODE0 */ /* KECC */ /* KOMEGA */ /* KMO */ /* KNO */ /* The parameters NEXT and PREV are used in our linked list */ /* LIST(NEXT,I) points to the list item the occurs after */ /* list item I. LIST ( PREV, I ) points to the list item */ /* that preceeds list item I. */ /* NEXT */ /* PREV */ /* There are a number of preliminary quantities that are needed */ /* to compute the state. Those that are not time dependent and */ /* depend only upon the elements are stored in a buffer so that */ /* if an element set matches a saved set, these preliminary */ /* quantities will not be recomputed. PRSIZE is the parameter */ /* used to declare the needed room. */ /* When we perform bisection in the solution of Kepler's equation */ /* we don't want to bisect too many times. */ /* Numerical Constants */ /* Local variables */ /* Geophysical Quantities */ /* Elements */ /* Intermediate quantities. The time independent quantities */ /* are calculated only as new elements come into the routine. */ chkin_("EV2LIN", (ftnlen)6); /* Rather than always making function calls we store the */ /* values of the PI dependent constants the first time */ /* through the routine. */ if (doinit) { doinit = FALSE_; pix2 = twopi_(); for (i__ = 1; i__ <= 8; ++i__) { lstgeo[(i__1 = i__ - 1) < 8 && 0 <= i__1 ? i__1 : s_rnge("lstgeo", i__1, "ev2lin_", (ftnlen)605)] = 0.; } for (i__ = 1; i__ <= 6; ++i__) { for (j = 1; j <= 10; ++j) { elemnt[(i__1 = j + i__ * 10 - 11) < 60 && 0 <= i__1 ? i__1 : s_rnge("elemnt", i__1, "ev2lin_", (ftnlen)610)] = 0.; } } /* Set up our doubly linked list of most recently used */ /* models. Here's how things are supposed to be arranged: */ /* LIST(NEXT,I) points to the ephemeris model that was used */ /* most recently after ephemeris model I. */ /* LIST(PREV,I) points to the latest ephemeris model used */ /* that was used more recently than I. */ /* HEAD points to the most recently used ephemris */ /* model. */ head = 1; list[(i__1 = (head << 1) - 1) < 12 && 0 <= i__1 ? i__1 : s_rnge("list" , i__1, "ev2lin_", (ftnlen)629)] = 0; list[0] = 2; for (i__ = 2; i__ <= 5; ++i__) { list[(i__1 = (i__ << 1) - 2) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)634)] = i__ + 1; list[(i__1 = (i__ << 1) - 1) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)635)] = i__ - 1; } list[10] = 0; list[11] = 5; } /* We update the geophysical parameters only if there */ /* has been a change from the last time they were */ /* supplied. */ if (lstgeo[7] != geophs[7] || lstgeo[6] != geophs[6] || lstgeo[0] != geophs[0] || lstgeo[1] != geophs[1] || lstgeo[2] != geophs[2] || lstgeo[3] != geophs[3] || lstgeo[4] != geophs[4] || lstgeo[5] != geophs[5]) { for (i__ = 1; i__ <= 8; ++i__) { lstgeo[(i__1 = i__ - 1) < 8 && 0 <= i__1 ? i__1 : s_rnge("lstgeo", i__1, "ev2lin_", (ftnlen)657)] = geophs[i__ - 1]; } j2 = geophs[0]; j3 = geophs[1]; j4 = geophs[2]; ke = geophs[3]; qo = geophs[4]; so = geophs[5]; er = geophs[6]; ae = geophs[7]; ae2 = ae * ae; ae3 = ae * ae2; ae4 = ae * ae3; ck2 = j2 * .5 * ae2; a3ovk2 = j3 * -2. * ae / j2; ck4 = j4 * -.375 * ae4; qomso = qo - so; q1 = qomso * ae / er; q2 = q1 * q1; qoms2t = q2 * q2; s = ae * (so / er + 1.); /* When we've finished up we will need to convert everything */ /* back to KM and KM/SEC the two variables below give the */ /* factors we shall need to do this. */ tokm = er / ae; tokmps = tokm / 60.; newgeo = TRUE_; } else { newgeo = FALSE_; } /* Fetch all of the pieces of this model. */ epoch = elems[9]; xndt2o = elems[0]; xndd6o = elems[1]; bstar = elems[2]; xincl = elems[3]; xnodeo = elems[4]; eo = elems[5]; omegao = elems[6]; xmo = elems[7]; xno = elems[8]; /* See if this model is already buffered, start at the first */ /* model in the list (the most recently used model). */ unrec = TRUE_; n = head; while(n != 0 && unrec) { /* The actual order of the elements is such that we can */ /* usually tell that a stored model is different from */ /* the one under consideration by looking at the */ /* end of the list first. Hence we start with I = NELEMS */ /* and decrement I until we have looked at everything */ /* or found a mismatch. */ recog = TRUE_; i__ = 10; while(recog && i__ > 0) { recog = recog && elemnt[(i__1 = i__ + n * 10 - 11) < 60 && 0 <= i__1 ? i__1 : s_rnge("elemnt", i__1, "ev2lin_", (ftnlen) 733)] == elems[i__ - 1]; --i__; } unrec = ! recog; if (unrec) { last = n; n = list[(i__1 = (n << 1) - 2) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)741)]; } } if (n == 0) { n = last; } /* Either N points to a recognized item or it points to the */ /* tail of the list where the least recently used items is */ /* located. In either case N must be made the head of the */ /* list. (If it is already the head of the list we don't */ /* have to bother with anything.) */ if (n != head) { /* Find the items that come before and after N and */ /* link them together. */ before = list[(i__1 = (n << 1) - 1) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)762)]; after = list[(i__1 = (n << 1) - 2) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)763)]; list[(i__1 = (before << 1) - 2) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)765)] = after; if (after != 0) { list[(i__1 = (after << 1) - 1) < 12 && 0 <= i__1 ? i__1 : s_rnge( "list", i__1, "ev2lin_", (ftnlen)768)] = before; } /* Now the guy that will come after N is the current */ /* head of the list. N will have no predecessor. */ list[(i__1 = (n << 1) - 2) < 12 && 0 <= i__1 ? i__1 : s_rnge("list", i__1, "ev2lin_", (ftnlen)774)] = head; list[(i__1 = (n << 1) - 1) < 12 && 0 <= i__1 ? i__1 : s_rnge("list", i__1, "ev2lin_", (ftnlen)775)] = 0; /* The predecessor the current head of the list becomes N */ list[(i__1 = (head << 1) - 1) < 12 && 0 <= i__1 ? i__1 : s_rnge("list" , i__1, "ev2lin_", (ftnlen)779)] = n; /* and finally, N becomes the head of the list. */ head = n; } if (recog && ! newgeo) { /* We can just look up the intermediate values from */ /* computations performed on a previous call to this */ /* routine. */ aodp = prelim[(i__1 = n * 29 - 29) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)794)]; aycof = prelim[(i__1 = n * 29 - 28) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)795)]; c1 = prelim[(i__1 = n * 29 - 27) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)796)]; c4 = prelim[(i__1 = n * 29 - 26) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)797)]; c5 = prelim[(i__1 = n * 29 - 25) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)798)]; cosio = prelim[(i__1 = n * 29 - 24) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)799)]; d2 = prelim[(i__1 = n * 29 - 23) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)800)]; d3 = prelim[(i__1 = n * 29 - 22) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)801)]; d4 = prelim[(i__1 = n * 29 - 21) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)802)]; delmo = prelim[(i__1 = n * 29 - 20) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)803)]; eta = prelim[(i__1 = n * 29 - 19) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)804)]; omgcof = prelim[(i__1 = n * 29 - 18) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)805)]; omgdot = prelim[(i__1 = n * 29 - 17) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)806)]; perige = prelim[(i__1 = n * 29 - 16) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)807)]; sinio = prelim[(i__1 = n * 29 - 15) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)808)]; sinmo = prelim[(i__1 = n * 29 - 14) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)809)]; t2cof = prelim[(i__1 = n * 29 - 13) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)810)]; t3cof = prelim[(i__1 = n * 29 - 12) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)811)]; t4cof = prelim[(i__1 = n * 29 - 11) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)812)]; t5cof = prelim[(i__1 = n * 29 - 10) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)813)]; x1mth2 = prelim[(i__1 = n * 29 - 9) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)814)]; x3thm1 = prelim[(i__1 = n * 29 - 8) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)815)]; x7thm1 = prelim[(i__1 = n * 29 - 7) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)816)]; xlcof = prelim[(i__1 = n * 29 - 6) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)817)]; xmcof = prelim[(i__1 = n * 29 - 5) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)818)]; xmdot = prelim[(i__1 = n * 29 - 4) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)819)]; xnodcf = prelim[(i__1 = n * 29 - 3) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)820)]; xnodot = prelim[(i__1 = n * 29 - 2) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim", i__1, "ev2lin_", (ftnlen)821)]; xnodp = prelim[(i__1 = n * 29 - 1) < 174 && 0 <= i__1 ? i__1 : s_rnge( "prelim", i__1, "ev2lin_", (ftnlen)822)]; } else { /* Compute all of the intermediate items needed. */ /* First, the inclination dependent constants. */ cosio = cos(xincl); sinio = sin(xincl); theta2 = cosio * cosio; theta4 = theta2 * theta2; x3thm1 = theta2 * 3. - 1.; x7thm1 = theta2 * 7. - 1.; x1mth2 = 1. - theta2; x1m5th = 1. - theta2 * 5.; /* Eccentricity dependent constants */ betao = sqrt(1. - eo * eo); betao2 = 1. - eo * eo; betao3 = betao * betao2; betao4 = betao2 * betao2; /* Semi-major axis and ascending node related constants. */ d__1 = ke / xno; a1 = pow_dd(&d__1, &c_b91); del1 = ck2 * 1.5 * x3thm1 / (a1 * a1 * betao3); ao = a1 * (1. - del1 * (del1 * (del1 * 134. / 81. + 1.) + .33333333333333331)); delo = ck2 * 1.5 * x3thm1 / (ao * ao * betao3); xnodp = xno / (delo + 1.); aodp = ao / (1. - delo); s4 = s; qoms24 = qoms2t; perige = er * (aodp * (1. - eo) - ae); /* For perigee below 156 km, the values of S and QOMS2T are */ /* altered. */ if (perige < 156.) { s4 = perige - 78.; if (perige <= 98.) { s4 = 20.; } /* Computing 4th power */ d__1 = (120. - s4) * ae / er, d__1 *= d__1; qoms24 = d__1 * d__1; s4 = ae + s4 / er; } /* The next block is simply a pretty print of the code in */ /* sgp4 from label number 10 through the label 90. */ pinvsq = 1. / (aodp * aodp * betao4); tsi = 1. / (aodp - s4); eta = aodp * eo * tsi; etasq = eta * eta; eeta = eo * eta; /* Computing 4th power */ d__1 = tsi, d__1 *= d__1; coef = qoms24 * (d__1 * d__1); psisq = (d__1 = 1. - etasq, abs(d__1)); coef1 = coef / pow_dd(&psisq, &c_b92); c2 = coef1 * xnodp * (aodp * (etasq * 1.5 + 1. + eeta * (etasq + 4.)) + ck2 * .75 * (tsi / psisq) * x3thm1 * (etasq * (etasq * 3. + 24.) + 8.)); c1 = c2 * bstar; c3 = coef * tsi * a3ovk2 * xnodp * ae * sinio / eo; c4 = xnodp * 2. * coef1 * aodp * betao2 * (eta * (etasq * .5 + 2.) + eo * (etasq * 2. + .5) - ck2 * tsi / (aodp * psisq) * 2. * ( x3thm1 * -3. * (1. - eeta * 2. + etasq * (1.5 - eeta * .5)) + cos(omegao * 2.) * .75 * x1mth2 * (etasq * 2. - eeta * (etasq + 1.)))); c5 = coef1 * 2. * aodp * betao2 * ((etasq + eeta) * 2.75 + 1. + eeta * etasq); temp1 = ck2 * 3. * pinvsq * xnodp; temp2 = temp1 * ck2 * pinvsq; temp3 = ck4 * 1.25 * pinvsq * pinvsq * xnodp; xmdot = xnodp + temp1 * .5 * betao * x3thm1 + temp2 * .0625 * betao * (13. - theta2 * 78. + theta4 * 137.); omgdot = temp1 * -.5 * x1m5th + temp2 * .0625 * (7. - theta2 * 114. + theta4 * 395.) + temp3 * (3. - theta2 * 36. + theta4 * 49.); xhdot1 = -temp1 * cosio; xnodot = xhdot1 + cosio * (temp2 * .5 * (4. - theta2 * 19.) + temp3 * 2. * (3. - theta2 * 7.)); omgcof = bstar * c3 * cos(omegao); xmcof = -bstar * .66666666666666663 * coef * ae / eeta; xnodcf = betao2 * 3.5 * xhdot1 * c1; t2cof = c1 * 1.5; aycof = a3ovk2 * .25 * sinio; xlcof = aycof * .5 * (cosio * 5. + 3.) / (cosio + 1.); /* Computing 3rd power */ d__1 = eta * cos(xmo) + 1.; delmo = d__1 * (d__1 * d__1); sinmo = sin(xmo); /* For perigee less than 220 kilometers, the ISIMP flag is set */ /* and the equations are truncated to linear variation in SQRT */ /* A and quadratic variation in mean anomaly. Also, the C3 */ /* term, the Delta OMEGA term, and the Delta M term are */ /* dropped. (Note: Normally we would just use */ if (perige >= 220.) { c1sq = c1 * c1; d2 = tsi * 4. * c1sq * aodp; temp = d2 * tsi * c1 * .33333333333333331; d3 = temp * (s4 + aodp * 17.); d4 = temp * tsi * c1 * aodp * .5 * (aodp * 221. + s4 * 31.); t3cof = d2 + c1sq * 2.; t4cof = (d3 * 3. + c1 * (d2 * 12. + c1sq * 10.)) * .25; t5cof = (d4 * 3. + c1 * 12. * d3 + d2 * 6. * d2 + c1sq * 15. * ( d2 * 2. + c1sq)) * .2; } /* Now store the intermediate computations so that if we */ /* should hit this model again we can just look up the needed */ /* results from the above computations. */ prelim[(i__1 = n * 29 - 29) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)992)] = aodp; prelim[(i__1 = n * 29 - 28) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)993)] = aycof; prelim[(i__1 = n * 29 - 27) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)994)] = c1; prelim[(i__1 = n * 29 - 26) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)995)] = c4; prelim[(i__1 = n * 29 - 25) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)996)] = c5; prelim[(i__1 = n * 29 - 24) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)997)] = cosio; prelim[(i__1 = n * 29 - 23) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)998)] = d2; prelim[(i__1 = n * 29 - 22) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)999)] = d3; prelim[(i__1 = n * 29 - 21) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1000)] = d4; prelim[(i__1 = n * 29 - 20) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1001)] = delmo; prelim[(i__1 = n * 29 - 19) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1002)] = eta; prelim[(i__1 = n * 29 - 18) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1003)] = omgcof; prelim[(i__1 = n * 29 - 17) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1004)] = omgdot; prelim[(i__1 = n * 29 - 16) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1005)] = perige; prelim[(i__1 = n * 29 - 15) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1006)] = sinio; prelim[(i__1 = n * 29 - 14) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1007)] = sinmo; prelim[(i__1 = n * 29 - 13) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1008)] = t2cof; prelim[(i__1 = n * 29 - 12) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1009)] = t3cof; prelim[(i__1 = n * 29 - 11) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1010)] = t4cof; prelim[(i__1 = n * 29 - 10) < 174 && 0 <= i__1 ? i__1 : s_rnge("prel" "im", i__1, "ev2lin_", (ftnlen)1011)] = t5cof; prelim[(i__1 = n * 29 - 9) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1012)] = x1mth2; prelim[(i__1 = n * 29 - 8) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1013)] = x3thm1; prelim[(i__1 = n * 29 - 7) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1014)] = x7thm1; prelim[(i__1 = n * 29 - 6) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1015)] = xlcof; prelim[(i__1 = n * 29 - 5) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1016)] = xmcof; prelim[(i__1 = n * 29 - 4) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1017)] = xmdot; prelim[(i__1 = n * 29 - 3) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1018)] = xnodcf; prelim[(i__1 = n * 29 - 2) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1019)] = xnodot; prelim[(i__1 = n * 29 - 1) < 174 && 0 <= i__1 ? i__1 : s_rnge("prelim" , i__1, "ev2lin_", (ftnlen)1020)] = xnodp; /* Finally, move these elements in the storage area */ /* for checking the next time through. */ for (i__ = 1; i__ <= 10; ++i__) { elemnt[(i__1 = i__ + n * 10 - 11) < 60 && 0 <= i__1 ? i__1 : s_rnge("elemnt", i__1, "ev2lin_", (ftnlen)1026)] = elems[ i__ - 1]; } } /* Now that all of the introductions are out of the way */ /* we can get down to business. */ /* Compute the time since the epoch for this model. */ tsince = *et - epoch; /* and convert it to minutes */ tsince /= 60.; xmdf = xmo + xmdot * tsince; omgadf = omegao + omgdot * tsince; xnoddf = xnodeo + xnodot * tsince; omega = omgadf; xmp = xmdf; tsq = tsince * tsince; xnode = xnoddf + xnodcf * tsq; tempa = 1. - c1 * tsince; tempe = bstar * c4 * tsince; templ = t2cof * tsq; if (perige > 220.) { tcube = tsq * tsince; tfour = tcube * tsince; delomg = omgcof * tsince; /* Computing 3rd power */ d__1 = eta * cos(xmdf) + 1.; delm = xmcof * (d__1 * (d__1 * d__1) - delmo); temp = delomg + delm; xmp = xmdf + temp; omega = omgadf - temp; tempa = tempa - d2 * tsq - d3 * tcube - d4 * tfour; tempe += bstar * c5 * (sin(xmp) - sinmo); templ = templ + tcube * t3cof + tfour * (t4cof + tsince * t5cof); } /* Computing 2nd power */ d__1 = tempa; a = aodp * (d__1 * d__1); xl = xmp + omega + xnode + xnodp * templ; e = eo - tempe; /* The parameter BETA used to be needed, but it's only use */ /* was in the computation of TEMP below where it got squared */ /* so we'll remove it from the list of things to compute. */ /* BETA = DSQRT( 1.0D0 - E*E ) */ xn = ke / pow_dd(&a, &c_b153); /* Long period periodics */ temp = 1. / (a * (1. - e * e)); aynl = temp * aycof; ayn = e * sin(omega) + aynl; axn = e * cos(omega); xll = temp * xlcof * axn; xlt = xl + xll; /* Solve keplers equation. */ /* We are going to solve for the roots of this equation by */ /* using a mixture of Newton's method and the prescription for */ /* root finding outlined in the SPICE routine UNITIM. */ /* We are going to solve the equation */ /* U = EPW - AXN * SIN(EPW) + AYN * COS(EPW) */ /* Where */ /* AYN = E * SIN(OMEGA) + AYNL */ /* AXN = E * COS(OMEGA) */ /* And */ /* AYNL = -0.50D0 * SINIO * AE * J3 / (J2*A*(1.0D0 - E*E)) */ /* Since this is a low earth orbiter (period less than 225 minutes) */ /* The maximum value E can take (without having the orbiter */ /* plowing fields) is approximately 0.47 and AYNL will not be */ /* more than about .01. ( Typically E will be much smaller */ /* on the order of about .1 ) Thus we can initially */ /* view the problem of solving the equation for EPW as a */ /* function of the form */ /* U = EPW + F ( EPW ) (1) */ /* Where F( EPW ) = -AXN*SIN(EPW) + AYN*COS(EPW) */ /* Note that | F'(EPW) | < M = DSQRT( AXN**2 + AYN**2 ) < 0.48 */ /* From the above discussion it is evident that F is a contraction */ /* mapping. So that we can employ the same techniques as were */ /* used in the routine UNITIM to get our first approximations of */ /* the root. Once we have some good first approximations, we */ /* will speed up the root finding by using Newton's method for */ /* finding a zero of a function. The function we will work on */ /* is */ /* f (x) = x - U - AXN*SIN(x) + AYN*COS(x) (2) */ /* By applying Newton's method we will go from linear to */ /* quadratic convergence. */ /* We will keep track of our error bounds along the way so */ /* that we will know how many iterations to perform in each */ /* phase of the root extraction. */ /* few steps using bisection. */ /* For the benefit of those interested */ /* here's the basics of what we'll do. */ /* Whichever EPW satisfies equation (1) will be */ /* unique. The uniqueness of the solution is ensured because the */ /* expression on the right-hand side of the equation is */ /* monotone increasing in EPW. */ /* Let's suppose that EPW is the solution, then the following */ /* is true. */ /* EPW = U - F(EPW) */ /* but we can also replace the EPW on the right hand side of the */ /* equation by U - F(EPW). Thus */ /* EPW = U - F( U - F(EPW)) */ /* = U - F( U - F( U - F(EPW))) */ /* = U - F( U - F( U - F( U - F(EPW)))) */ /* = U - F( U - F( U - F( U - F( U - F(EPW))))) */ /* . */ /* . */ /* . */ /* = U - F( U - F( U - F( U - F( U - F(U - ... ))) */ /* and so on, for as long as we have patience to perform the */ /* substitutions. */ /* The point of doing this recursive substitution is that we */ /* hope to move EPW to an insignificant part of the computation. */ /* This would seem to have a reasonable chance of success since */ /* F is a bounded and has a small derivative. */ /* Following this idea, we will attempt to solve for EPW using */ /* the recursive method outlined below. */ /* We will make our first guess at EPW, call it EPW_0. */ /* EPW_0 = U */ /* Our next guess, EPW_1, is given by: */ /* EPW_1 = U - F(EPW_0) */ /* And so on: */ /* EPW_2 = U - F(EPW_1) [ = U - F(U - F(U)) ] */ /* EPW_3 = U - F(EPW_2) [ = U - F(U - F(U - F(U))) ] */ /* . */ /* . */ /* . */ /* EPW_n = U - F(EPW_(n-1)) [ = U - F(U - F(U - F(U...)))] */ /* The questions to ask at this point are: */ /* 1) Do the EPW_i's converge? */ /* 2) If they converge, do they converge to EPW? */ /* 3) If they converge to EPW, how fast do they get there? */ /* 1) The sequence of approximations converges. */ /* | EPW_n - EPW_(n-1) | = [ U - F( EPW_(n-1) ) ] */ /* - [ U - F( EPW_(n-2) ) ] */ /* = [ F( EPW_(n-2) ) - F( EPW_(n-1)) ] */ /* The function F has an important property. The absolute */ /* value of its derivative is always less than M. */ /* This means that for any pair of real numbers s,t */ /* | F(t) - F(s) | < M*| t - s |. */ /* From this observation, we can see that */ /* | EPW_n - EPW_(n-1) | < M*| EPW_(n-1) - EPW_(n-2) | */ /* With this fact available, we could (with a bit more work) */ /* conclude that the sequence of EPW_i's converges and that */ /* it converges at a rate that is at least as fast as the */ /* sequence M, M**2, M**3. In fact the difference */ /* |EPW - EPW_N| < M/(1-M) * | EPW_N - EPW_(N-1) | */ /* < M/(1-M) * M**N | EPW_1 - EPW_0 | */ /* 2) If we let EPW be the limit of the EPW_i's then it follows */ /* that */ /* EPW = U - F(EPW). */ /* or that */ /* U = EPW + F(EPW). */ /* We will use this technique to get an approximation that */ /* is within a tolerance of EPW and then switch to */ /* a Newton's method. (We'll compute the tolerance using */ /* the value of M given above). */ /* For the Newton's method portion of the problem, recall */ /* from Taylor's formula that: */ /* f(x) = f(x_0) + f'(x_0)(x-x_0) + f''(c)/2 (x-x_0)**2 */ /* for some c between x and x_0 */ /* If x happens to be a zero of f then we can rearrange the */ /* terms above to get */ /* f(x_0) f''(c) */ /* x = x_0 - ------- + -------- ( x - x_0)**2 */ /* f'(x_0) f'(x_0) */ /* Thus the error in the Newton approximation */ /* f(x_0) */ /* x = x_0 - ------- */ /* f'(x_0) */ /* is */ /* f''(c) */ /* -------- ( x - x_0)**2 */ /* f'(x_0) */ /* Thus if we can bound f'' and pick a good first */ /* choice for x_0 (using the first method outlined */ /* above we can get quadratic convergence.) */ /* In our case we have */ /* f (x) = x - U - AXN*SIN(x) + AYN*COS(x) */ /* f' (x) = 1 - AXN*COS(x) - AYN*SIN(x) */ /* f''(x) = AXN*SIN(x) - AYN*COS(x) */ /* So that: */ /* f' (x) > 1 - M */ /* f''(x) < M */ /* Thus the error in the Newton's approximation is */ /* at most */ /* M/(1-M) * ( x - x_0 )**2 */ /* Thus as long as our original estimate (determined using */ /* the contraction method) gets within a reasonable tolerance */ /* of x, we can use Newton's method to acheive faster */ /* convergence. */ m = sqrt(axn * axn + ayn * ayn); mov1m = (d__1 = m / (1. - m), abs(d__1)); d__1 = xlt - xnode; fmod2p = d_mod(&d__1, &pix2); if (fmod2p < 0.) { fmod2p += pix2; } capu = fmod2p; epw = capu; est = 1.; count = 0; while(est > .125) { ++count; if (count > 20) { setmsg_("EST iteration count of #1 exceeded at time ET #2. This " "error may indicate a bad TLE set.", (ftnlen)88); errint_("#1", &c__20, (ftnlen)2); errdp_("#2", et, (ftnlen)2); sigerr_("SPICE(ITERATIONEXCEEDED)", (ftnlen)24); chkout_("EV2LIN", (ftnlen)6); return 0; } epwnxt = capu - axn * sin(epw) + ayn * cos(epw); est = mov1m * (d__1 = epwnxt - epw, abs(d__1)); epw = epwnxt; } /* We need to be able to add something to EPW and not */ /* get EPW (but not too much). */ epsiln = est; if (epsiln + epw != epw) { /* Now we switch over to Newton's method. Note that */ /* since our error estimate is less than 1/8, six iterations */ /* of Newton's method should get us to within 1/2**96 of */ /* the correct answer (If there were no round off to contend */ /* with). */ for (i__ = 1; i__ <= 5; ++i__) { sinepw = sin(epw); cosepw = cos(epw); f = epw - capu - axn * sinepw + ayn * cosepw; fprime = 1. - axn * cosepw - ayn * sinepw; epwnxt = epw - f / fprime; /* Our new error estimate comes from the discussion */ /* of convergence of Newton's method. */ epw = epwnxt; if (epw + est != epw) { epsiln = est; est = mov1m * est * est; } } } /* Finally, we use bisection to avoid the problems of */ /* round-off that may be present in Newton's method. Since */ /* we've gotten quite close to the answer (theoretically */ /* anyway) we won't have to perform many bisection passes. */ /* First we must bracket the root. Note that we will */ /* increase EPSILN so that we don't spend much time */ /* determining the bracketing interval. Also if the first */ /* addition of EPSILN to EPW doesn't modify it, were set up */ /* to just quit. This happens only if F is sufficiently */ /* close to zero that it can't alter EPW by adding it to */ /* or subtracting it from EPW. */ sinepw = sin(epw); cosepw = cos(epw); f = epw - capu - axn * sinepw + ayn * cosepw; /* Computing MAX */ d__1 = abs(f); epsiln = max(d__1,epsiln); if (f == 0.) { lower = epw; upper = epw; } else if (f > 0.) { fu = f; upper = epw; lower = epw - epsiln; epw = lower; while(f > 0. && lower != upper) { epw -= epsiln; f = epw - capu - axn * sin(epw) + ayn * cos(epw); epsiln *= 2.; } lower = epw; fl = f; if (f == 0.) { upper = lower; } } else if (f < 0.) { fl = f; lower = epw; upper = epw + epsiln; epw = upper; while(f < 0. && lower != upper) { epw += epsiln; f = epw - capu - axn * sin(epw) + ayn * cos(epw); epsiln *= 2.; } upper = epw; fu = f; if (f == 0.) { lower = epw; } } /* Finally, bisect until we can do no more. */ count = 0; while(upper > lower && count < 20) { ++count; d__1 = (upper + lower) * .5; epw = brcktd_(&d__1, &lower, &upper); /* EPW eventually will not be different from one of the */ /* two bracketing values. If this is the time, we need */ /* to decide on a value for EPW. That's done below. */ if (epw == upper || epw == lower) { if (-fl < fu) { epw = lower; upper = lower; } else { epw = upper; lower = upper; } } else { f = epw - capu - axn * sin(epw) + ayn * cos(epw); if (f > 0.) { upper = epw; fu = f; } else if (f < 0.) { lower = epw; fl = f; } else { lower = epw; upper = epw; } } } /* Short period preliminary quantities */ sinepw = sin(epw); cosepw = cos(epw); temp3 = axn * sinepw; temp4 = ayn * cosepw; temp5 = axn * cosepw; temp6 = ayn * sinepw; ecose = temp5 + temp6; esine = temp3 - temp4; elsq = axn * axn + ayn * ayn; temp = 1. - elsq; pl = a * temp; r__ = a * (1. - ecose); temp1 = 1. / r__; rdot = ke * temp1 * sqrt(a) * esine; rfdot = ke * temp1 * sqrt(pl); temp2 = a * temp1; betal = sqrt(temp); temp3 = 1. / (betal + 1.); cosu = temp2 * (cosepw - axn + ayn * esine * temp3); sinu = temp2 * (sinepw - ayn - axn * esine * temp3); /* Compute the angle from the x-axis of the point ( COSU, SINU ) */ if (sinu != 0. || cosu != 0.) { u = atan2(sinu, cosu); if (u < 0.) { u += pix2; } } else { u = 0.; } sin2u = sinu * 2. * cosu; cos2u = cosu * 2. * cosu - 1.; temp = 1. / pl; temp1 = ck2 * temp; temp2 = temp1 * temp; /* Update for short periodics */ rk = r__ * (1. - temp2 * 1.5 * betal * x3thm1) + temp1 * .5 * x1mth2 * cos2u; uk = u - temp2 * .25 * x7thm1 * sin2u; xnodek = xnode + temp2 * 1.5 * cosio * sin2u; xinck = xincl + temp2 * 1.5 * cosio * cos2u * sinio; rdotk = rdot - xn * temp1 * x1mth2 * sin2u; rfdotk = rfdot + xn * temp1 * (x1mth2 * cos2u + x3thm1 * 1.5); /* Orientation vectors */ sinuk = sin(uk); cosuk = cos(uk); sinik = sin(xinck); cosik = cos(xinck); sinnok = sin(xnodek); cosnok = cos(xnodek); xmx = -sinnok * cosik; xmy = cosnok * cosik; ux = xmx * sinuk + cosnok * cosuk; uy = xmy * sinuk + sinnok * cosuk; uz = sinik * sinuk; vx = xmx * cosuk - cosnok * sinuk; vy = xmy * cosuk - sinnok * sinuk; vz = sinik * cosuk; /* Position and velocity */ state[0] = tokm * rk * ux; state[1] = tokm * rk * uy; state[2] = tokm * rk * uz; state[3] = tokmps * (rdotk * ux + rfdotk * vx); state[4] = tokmps * (rdotk * uy + rfdotk * vy); state[5] = tokmps * (rdotk * uz + rfdotk * vz); chkout_("EV2LIN", (ftnlen)6); return 0; } /* ev2lin_ */
gpl-3.0
b3h3moth/L-LP
src/Unix_Programming/File_System/07_symbolic_link.c
2
2160
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> #define BUF_SIZE 1024 #define PERMS (S_IRWXU | S_IRGRP | S_IROTH) /* int symlink(const char *actualpath, const char symlinkpath); ssize_t readlink(const char* restrict pathname, char *restrict buf, size_t bufsize); symlink() crea una nuova voce di directory 'symlinkpath', che punta ad 'actualpath'. readlink() consente la lettura del symbolic link 'pathname' nel buffer 'buf' di dimensione 'bufsize'. symlink() ritorna 0 In caso di successo, -1 in caso di errore. readlink() invece ritorna il numero dei byte letti in caso di successo, 0 in caso di errore. Lo scopo del programma e' di creare un symlink di un file ricevuto in input, infine stampa alcune informazioni in merito. */ int main(int argc, char *argv[]) { int fd; char buf[BUF_SIZE]; ssize_t buf_len; if (argc < 3) { fprintf(stderr, "Usage: %s <default file> <symbolic-link>\n", argv[0]); exit(EXIT_FAILURE); } /* Crea il file di origine */ if ((fd = open(argv[1], O_CREAT, PERMS)) < 0) { fprintf(stderr, "Err.:(%d) - %s: %s\n", errno, strerror(errno), argv[1]); exit(EXIT_FAILURE); } /* Crea il symbolic-link verso il file di origine */ if (symlink(argv[1], argv[2]) < 0) { fprintf(stderr, "Err.:(%d) - Create symbolic-link: %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } /* Dapprima si ottiene la lunghezza del buffer, dopodiche' viene aggiunto un null-terminated character al buffer appena creato mediante readlink(), e poiche' tale funzione non lo supporta e' necessarop farlo manualmente */ buf_len = readlink(argv[2], buf, BUF_SIZE - 1); if (buf_len == -1) { fprintf(stderr, "Err.:(%d) - Read symbolic-link: %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } buf[buf_len] = '\0'; printf(" default file: '%s'\n", argv[1]); printf(" symbolic-link: '%s'\n", argv[2]); printf("symbolic-link content: '%s'\n", buf); close(fd); return(EXIT_SUCCESS); }
gpl-3.0
MattiasBuelens/avr-crypto-lib
mugi/mugi.c
2
4535
/* mugi.c */ /* This file is part of the AVR-Crypto-Lib. Copyright (C) 2006-2015 Daniel Otte (bg@nerilex.org) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file mugi.c * \author Daniel Otte * \email bg@nerilex.org * \date 2009-02-15 * \brief implementation of the MUGI key stream generator * \license GPLv3 or later */ #include <stdint.h> #include <stdlib.h> #include <string.h> #include <avr/pgmspace.h> #include "aes_sbox.h" #include "mugi.h" #include "gf256mul.h" /* #include "cli.h" / * only for debugging * / void dump_mugi_ctx(mugi_ctx_t *ctx){ uint8_t i; cli_putstr_P(PSTR("\r\n== MUGI CTX DUMP==\r\n a:")); cli_hexdump(&(ctx->a[0]), 8); cli_putc(' '); cli_hexdump(&(ctx->a[1]), 8); cli_putc(' '); cli_hexdump(&(ctx->a[2]), 8); cli_putstr_P(PSTR("\r\n b: ")); for(i=0; i<4; ++i){ cli_putstr_P(PSTR("\r\n ")); cli_hexdump(&(ctx->b[i*4+0]), 8); cli_putc(' '); cli_hexdump(&(ctx->b[i*4+1]), 8); cli_putc(' '); cli_hexdump(&(ctx->b[i*4+2]), 8); cli_putc(' '); cli_hexdump(&(ctx->b[i*4+3]), 8); } } */ #define C0 0x08c9bcf367e6096all #define C1 0x3ba7ca8485ae67bbll #define C2 0x2bf894fe72f36e3cll #define GF256MUL_2(a) (gf256mul(2, (a), 0x1b)) uint64_t changeendian64(uint64_t a){ union { uint8_t v8[8]; uint64_t v64; } r; r.v8[0] = ((uint8_t*)&a)[7]; r.v8[1] = ((uint8_t*)&a)[6]; r.v8[2] = ((uint8_t*)&a)[5]; r.v8[3] = ((uint8_t*)&a)[4]; r.v8[4] = ((uint8_t*)&a)[3]; r.v8[5] = ((uint8_t*)&a)[2]; r.v8[6] = ((uint8_t*)&a)[1]; r.v8[7] = ((uint8_t*)&a)[0]; return r.v64; } static uint64_t rotl64(uint64_t a, uint8_t i){ uint64_t r; r=changeendian64(a); r=(r<<i | r>>(64-i)); r=changeendian64(r); return r; } static uint64_t rotr64(uint64_t a, uint8_t i){ uint64_t r; r=changeendian64(a); r=(r>>i | r<<(64-i)); r=changeendian64(r); return r; } #define T(x) (((uint8_t*)&t)[(x)]) #define D(y) (((uint8_t*)dest)[(y)]) static void mugi_f(uint64_t *dest, uint64_t *a, uint64_t *b){ uint64_t t; uint8_t i,x; t = (*a); if(b) t ^= (*b); for(i=0; i<8; ++i) T(i) = pgm_read_byte(aes_sbox+T(i)); x = T(0) ^ T(1) ^ T(2) ^ T(3); D(4) = GF256MUL_2(T(0)^T(1)) ^ T(0) ^ x; D(5) = GF256MUL_2(T(1)^T(2)) ^ T(1) ^ x; D(2) = GF256MUL_2(T(2)^T(3)) ^ T(2) ^ x; D(3) = GF256MUL_2(T(3)^T(0)) ^ T(3) ^ x; x = T(4) ^ T(5) ^ T(6) ^ T(7); D(0) = GF256MUL_2(T(4)^T(5)) ^ T(4) ^ x; D(1) = GF256MUL_2(T(5)^T(6)) ^ T(5) ^ x; D(6) = GF256MUL_2(T(6)^T(7)) ^ T(6) ^ x; D(7) = GF256MUL_2(T(7)^T(4)) ^ T(7) ^ x; } static void mugi_rho(mugi_ctx_t *ctx){ uint64_t t,bx; t = ctx->a[1]; ctx->a[1] = ctx->a[2]; ctx->a[2] = ctx->a[0]; ctx->a[0] = t; mugi_f(&t, &(ctx->a[0]), &(ctx->b[4])); ctx->a[1] ^= t ^ C1; bx = rotl64(ctx->b[10], 17); mugi_f(&t, &(ctx->a[0]), &bx); ctx->a[2] ^= t ^ C2; } static void mugi_rho_init(uint64_t *a){ uint64_t t; t = a[1]; a[1] = a[2]; a[2] = a[0]; a[0] = t; mugi_f(&t, &(a[0]), NULL); a[1] ^= t ^ C1; mugi_f(&t, &(a[0]), NULL); a[2] ^= t ^ C2; } static void mugi_lambda(uint64_t *b, uint64_t *a){ uint8_t i; uint64_t t; t=b[15]; for(i=15; i!=0; --i){ b[i]=b[i-1]; } b[0] = t ^ *a; b[4] ^= b[8]; b[10] ^= rotl64(b[14], 32); } void mugi_init(const void *key, const void *iv, mugi_ctx_t *ctx){ uint8_t i; uint64_t a0; memcpy(ctx->a, key, 128/8); ctx->a[2] = rotl64(ctx->a[0], 7) ^ rotr64(ctx->a[1], 7) ^ C0; for(i=0; i<16;i++){ mugi_rho_init(ctx->a); ctx->b[15-i] = ctx->a[0]; } ctx->a[0] ^= ((uint64_t*)iv)[0]; ctx->a[1] ^= ((uint64_t*)iv)[1]; ctx->a[2] ^= rotl64(((uint64_t*)iv)[0], 7) ^ rotr64(((uint64_t*)iv)[1], 7) ^ C0; for(i=0; i<16;i++){ mugi_rho_init(ctx->a); } for(i=0; i<15;i++){ a0 = ctx->a[0]; mugi_rho(ctx); mugi_lambda(ctx->b, &a0); } a0=0x00; } uint64_t mugi_gen(mugi_ctx_t *ctx){ uint64_t r; r=ctx->a[0]; mugi_rho(ctx); mugi_lambda(ctx->b, &r); r=ctx->a[2]; return r; }
gpl-3.0
yijiangh/FrameFab
ext/GTEngine/Source/Graphics/GtePVWUpdater.cpp
3
2222
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2017 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #include <GTEnginePCH.h> #include <Graphics/GtePVWUpdater.h> using namespace gte; PVWUpdater::~PVWUpdater() { } PVWUpdater::PVWUpdater() { Set(nullptr, [](std::shared_ptr<Buffer> const&) {}); } PVWUpdater::PVWUpdater(std::shared_ptr<Camera> const& camera, BufferUpdater const& updater) { Set(camera, updater); } void PVWUpdater::Set(std::shared_ptr<Camera> const& camera, BufferUpdater const& updater) { mCamera = camera; mUpdater = updater; } bool PVWUpdater::Subscribe(Matrix4x4<float> const& worldMatrix, std::shared_ptr<ConstantBuffer> const& cbuffer, std::string const& pvwMatrixName) { if (cbuffer && cbuffer->HasMember(pvwMatrixName)) { if (mSubscribers.find(&worldMatrix) == mSubscribers.end()) { mSubscribers.insert(std::make_pair(&worldMatrix, std::make_pair(cbuffer, pvwMatrixName))); return true; } } return false; } bool PVWUpdater::Unsubscribe(Matrix4x4<float> const& worldMatrix) { return mSubscribers.erase(&worldMatrix) > 0; } void PVWUpdater::UnsubscribeAll() { mSubscribers.clear(); } void PVWUpdater::Update() { // The function is called knowing that mCamera is not null. Matrix4x4<float> pvMatrix = mCamera->GetProjectionViewMatrix(); for (auto& element : mSubscribers) { // Compute the new projection-view-world matrix. The matrix // *element.first is the model-to-world matrix for the associated // object. #if defined(GTE_USE_MAT_VEC) Matrix4x4<float> pvwMatrix = pvMatrix * (*element.first); #else Matrix4x4<float> pvwMatrix = (*element.first) * pvMatrix; #endif // Copy the source matrix into the system memory of the constant // buffer. element.second.first->SetMember(element.second.second, pvwMatrix); // Allow the caller to update GPU memory as desired. mUpdater(element.second.first); } }
gpl-3.0
ErikMinekus/sm-ripext
curl/tests/unit/unit1653.c
3
6113
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "urldata.h" #include "curl/urlapi.h" #include "urlapi-int.h" static CURLU *u; static CURLcode unit_setup(void) { return CURLE_OK; } static void unit_stop(void) { curl_global_cleanup(); } #define free_and_clear(x) free(x); x = NULL UNITTEST_START { CURLUcode ret; char *ipv6port = NULL; char *portnum; /* Valid IPv6 */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15]"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret == CURLUE_OK, "Curl_parse_port returned error"); ret = curl_url_get(u, CURLUPART_PORT, &portnum, CURLU_NO_DEFAULT_PORT); fail_unless(ret != CURLUE_OK, "curl_url_get portnum returned something"); free_and_clear(ipv6port); curl_url_cleanup(u); /* Invalid IPv6 */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15|"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret != CURLUE_OK, "Curl_parse_port true on error"); free_and_clear(ipv6port); curl_url_cleanup(u); u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff;fea7:da15]:80"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret != CURLUE_OK, "Curl_parse_port true on error"); free_and_clear(ipv6port); curl_url_cleanup(u); /* Valid IPv6 with zone index and port number */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15%25eth3]:80"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret == CURLUE_OK, "Curl_parse_port returned error"); ret = curl_url_get(u, CURLUPART_PORT, &portnum, 0); fail_unless(ret == CURLUE_OK, "curl_url_get portnum returned error"); fail_unless(portnum && !strcmp(portnum, "80"), "Check portnumber"); curl_free(portnum); free_and_clear(ipv6port); curl_url_cleanup(u); /* Valid IPv6 with zone index without port number */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15%25eth3]"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret == CURLUE_OK, "Curl_parse_port returned error"); free_and_clear(ipv6port); curl_url_cleanup(u); /* Valid IPv6 with port number */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15]:81"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret == CURLUE_OK, "Curl_parse_port returned error"); ret = curl_url_get(u, CURLUPART_PORT, &portnum, 0); fail_unless(ret == CURLUE_OK, "curl_url_get portnum returned error"); fail_unless(portnum && !strcmp(portnum, "81"), "Check portnumber"); curl_free(portnum); free_and_clear(ipv6port); curl_url_cleanup(u); /* Valid IPv6 with syntax error in the port number */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15];81"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret != CURLUE_OK, "Curl_parse_port true on error"); free_and_clear(ipv6port); curl_url_cleanup(u); u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15]80"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret != CURLUE_OK, "Curl_parse_port true on error"); free_and_clear(ipv6port); curl_url_cleanup(u); /* Valid IPv6 with no port after the colon, should use default if a scheme was used in the URL */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15]:"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, TRUE); fail_unless(ret == CURLUE_OK, "Curl_parse_port returned error"); free_and_clear(ipv6port); curl_url_cleanup(u); /* Incorrect zone index syntax */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15!25eth3]:80"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret != CURLUE_OK, "Curl_parse_port returned non-error"); free_and_clear(ipv6port); curl_url_cleanup(u); /* Non percent-encoded zone index */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("[fe80::250:56ff:fea7:da15%eth3]:80"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret == CURLUE_OK, "Curl_parse_port returned error"); free_and_clear(ipv6port); curl_url_cleanup(u); /* No scheme and no digits following the colon - not accepted. Because that makes (a*50):// that looks like a scheme be an acceptable input. */ u = curl_url(); if(!u) goto fail; ipv6port = strdup("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaa:"); if(!ipv6port) goto fail; ret = Curl_parse_port(u, ipv6port, FALSE); fail_unless(ret == CURLUE_BAD_PORT_NUMBER, "Curl_parse_port did wrong"); fail: free(ipv6port); curl_url_cleanup(u); } UNITTEST_STOP
gpl-3.0
CasparCG/Client
src/Widgets/Rundown/Atem/RundownAtemInputWidget.cpp
3
16778
#include "RundownAtemInputWidget.h" #include "Global.h" #include "DatabaseManager.h" #include "DeviceManager.h" #include "AtemDeviceManager.h" #include "GpiManager.h" #include "EventManager.h" #include "Events/ConnectionStateChangedEvent.h" #include <math.h> #include <QtCore/QObject> #include <QtCore/QTimer> #include <QtCore/QXmlStreamWriter> #include <QtWidgets/QGraphicsOpacityEffect> RundownAtemInputWidget::RundownAtemInputWidget(const LibraryModel& model, QWidget* parent, const QString& color, bool active, bool inGroup, bool compactView) : QWidget(parent), active(active), inGroup(inGroup), compactView(compactView), color(color), model(model), playControlSubscription(NULL), playNowControlSubscription(NULL), updateControlSubscription(NULL), previewControlSubscription(NULL) { setupUi(this); this->animation = new ActiveAnimation(this->labelActiveColor); this->markUsedItems = (DatabaseManager::getInstance().getConfigurationByName("MarkUsedItems").getValue() == "true") ? true : false; setColor(color); setActive(active); setCompactView(compactView); this->labelGroupColor->setVisible(this->inGroup); this->labelGroupColor->setStyleSheet(QString("background-color: %1;").arg(Color::DEFAULT_GROUP_COLOR)); this->labelColor->setStyleSheet(QString("background-color: %1;").arg(Color::DEFAULT_ATEM_COLOR)); this->labelLabel->setText(this->model.getLabel()); this->labelDelay->setText(QString("Delay: %1").arg(this->command.getDelay())); this->labelDevice->setText(QString("Server: %1").arg(this->model.getDeviceName())); this->executeTimer.setSingleShot(true); QObject::connect(&this->executeTimer, SIGNAL(timeout()), SLOT(executePlay())); QObject::connect(&this->command, SIGNAL(delayChanged(int)), this, SLOT(delayChanged(int))); QObject::connect(&this->command, SIGNAL(allowGpiChanged(bool)), this, SLOT(allowGpiChanged(bool))); QObject::connect(&this->command, SIGNAL(remoteTriggerIdChanged(const QString&)), this, SLOT(remoteTriggerIdChanged(const QString&))); QObject::connect(&EventManager::getInstance(), SIGNAL(preview(const PreviewEvent&)), this, SLOT(preview(const PreviewEvent&))); QObject::connect(&EventManager::getInstance(), SIGNAL(atemDeviceChanged(const AtemDeviceChangedEvent&)), this, SLOT(atemDeviceChanged(const AtemDeviceChangedEvent&))); QObject::connect(&EventManager::getInstance(), SIGNAL(labelChanged(const LabelChangedEvent&)), this, SLOT(labelChanged(const LabelChangedEvent&))); QObject::connect(&AtemDeviceManager::getInstance(), SIGNAL(deviceAdded(AtemDevice&)), this, SLOT(deviceAdded(AtemDevice&))); const QSharedPointer<AtemDevice> device = AtemDeviceManager::getInstance().getDeviceByName(this->model.getDeviceName()); if (device != NULL) QObject::connect(device.data(), SIGNAL(connectionStateChanged(AtemDevice&)), this, SLOT(deviceConnectionStateChanged(AtemDevice&))); QObject::connect(GpiManager::getInstance().getGpiDevice().data(), SIGNAL(connectionStateChanged(bool, GpiDevice*)), this, SLOT(gpiConnectionStateChanged(bool, GpiDevice*))); checkEmptyDevice(); checkGpiConnection(); checkDeviceConnection(); } void RundownAtemInputWidget::preview(const PreviewEvent& event) { Q_UNUSED(event); // This event is not for us. if (!this->selected) return; executePlay(); } void RundownAtemInputWidget::labelChanged(const LabelChangedEvent& event) { // This event is not for us. if (!this->selected) return; this->model.setLabel(event.getLabel()); this->labelLabel->setText(this->model.getLabel()); } void RundownAtemInputWidget::atemDeviceChanged(const AtemDeviceChangedEvent& event) { // This event is not for us. if (!this->selected) return; // Should we update the device name? if (!event.getDeviceName().isEmpty() && event.getDeviceName() != this->model.getDeviceName()) { // Disconnect connectionStateChanged() from the old device. const QSharedPointer<AtemDevice> oldDevice = AtemDeviceManager::getInstance().getDeviceByName(this->model.getDeviceName()); if (oldDevice != NULL) QObject::disconnect(oldDevice.data(), SIGNAL(connectionStateChanged(AtemDevice&)), this, SLOT(deviceConnectionStateChanged(AtemDevice&))); // Update the model with the new device. this->model.setDeviceName(event.getDeviceName()); this->labelDevice->setText(QString("Server: %1").arg(this->model.getDeviceName())); // Connect connectionStateChanged() to the new device. const QSharedPointer<AtemDevice> newDevice = AtemDeviceManager::getInstance().getDeviceByName(this->model.getDeviceName()); if (newDevice != NULL) QObject::connect(newDevice.data(), SIGNAL(connectionStateChanged(AtemDevice&)), this, SLOT(deviceConnectionStateChanged(AtemDevice&))); } checkEmptyDevice(); checkDeviceConnection(); } AbstractRundownWidget* RundownAtemInputWidget::clone() { RundownAtemInputWidget* widget = new RundownAtemInputWidget(this->model, this->parentWidget(), this->color, this->active, this->inGroup, this->compactView); AtemInputCommand* command = dynamic_cast<AtemInputCommand*>(widget->getCommand()); command->setChannel(this->command.getChannel()); command->setVideolayer(this->command.getVideolayer()); command->setDelay(this->command.getDelay()); command->setDuration(this->command.getDuration()); command->setAllowGpi(this->command.getAllowGpi()); command->setAllowRemoteTriggering(this->command.getAllowRemoteTriggering()); command->setRemoteTriggerId(this->command.getRemoteTriggerId()); command->setSwitcher(this->command.getSwitcher()); command->setInput(this->command.getInput()); command->setTriggerOnNext(this->command.getTriggerOnNext()); command->setMixerStep(this->command.getMixerStep()); return widget; } void RundownAtemInputWidget::setCompactView(bool compactView) { if (compactView) { this->labelIcon->setFixedSize(Rundown::COMPACT_ICON_WIDTH, Rundown::COMPACT_ICON_HEIGHT); this->labelGpiConnected->setFixedSize(Rundown::COMPACT_ICON_WIDTH, Rundown::COMPACT_ICON_HEIGHT); this->labelDisconnected->setFixedSize(Rundown::COMPACT_ICON_WIDTH, Rundown::COMPACT_ICON_HEIGHT); } else { this->labelIcon->setFixedSize(Rundown::DEFAULT_ICON_WIDTH, Rundown::DEFAULT_ICON_HEIGHT); this->labelGpiConnected->setFixedSize(Rundown::DEFAULT_ICON_WIDTH, Rundown::DEFAULT_ICON_HEIGHT); this->labelDisconnected->setFixedSize(Rundown::DEFAULT_ICON_WIDTH, Rundown::DEFAULT_ICON_HEIGHT); } this->compactView = compactView; } void RundownAtemInputWidget::readProperties(boost::property_tree::wptree& pt) { if (pt.count(L"color") > 0) setColor(QString::fromStdWString(pt.get<std::wstring>(L"color"))); } void RundownAtemInputWidget::writeProperties(QXmlStreamWriter* writer) { writer->writeTextElement("color", this->color); } bool RundownAtemInputWidget::isGroup() const { return false; } bool RundownAtemInputWidget::isInGroup() const { return this->inGroup; } AbstractCommand* RundownAtemInputWidget::getCommand() { return &this->command; } LibraryModel* RundownAtemInputWidget::getLibraryModel() { return &this->model; } void RundownAtemInputWidget::setSelected(bool selected) { this->selected = selected; } void RundownAtemInputWidget::setActive(bool active) { this->active = active; this->animation->stop(); if (this->active) this->labelActiveColor->setStyleSheet(QString("background-color: %1;").arg(Color::DEFAULT_ACTIVE_COLOR)); else this->labelActiveColor->setStyleSheet(""); } void RundownAtemInputWidget::setInGroup(bool inGroup) { this->inGroup = inGroup; this->labelGroupColor->setVisible(this->inGroup); } QString RundownAtemInputWidget::getColor() const { return this->color; } void RundownAtemInputWidget::setColor(const QString& color) { this->color = color; this->setStyleSheet(QString("#frameItem, #frameStatus { background-color: %1; }").arg(color)); } void RundownAtemInputWidget::checkEmptyDevice() { if (this->labelDevice->text() == "Device: ") this->labelDevice->setStyleSheet("color: firebrick;"); else this->labelDevice->setStyleSheet(""); } void RundownAtemInputWidget::clearDelayedCommands() { this->executeTimer.stop(); } void RundownAtemInputWidget::setUsed(bool used) { if (used) { if (this->frameItem->graphicsEffect() == NULL) { QGraphicsOpacityEffect* effect = new QGraphicsOpacityEffect(this); effect->setOpacity(0.25); this->frameItem->setGraphicsEffect(effect); } } else this->frameItem->setGraphicsEffect(NULL); } bool RundownAtemInputWidget::executeCommand(Playout::PlayoutType type) { if ((type == Playout::PlayoutType::Play && !this->command.getTriggerOnNext()) || type == Playout::PlayoutType::Update) { if (this->command.getDelay() < 0) return true; if (!this->model.getDeviceName().isEmpty()) // The user need to select a device. QTimer::singleShot(this->command.getDelay(), this, SLOT(executePlay())); } else if (type == Playout::PlayoutType::PlayNow) executePlay(); else if (type == Playout::PlayoutType::Next && this->command.getTriggerOnNext()) executePlay(); else if (type == Playout::PlayoutType::Preview) executePreview(); if (this->active) this->animation->start(1); return true; } void RundownAtemInputWidget::executePlay() { const QSharedPointer<AtemDevice> device = AtemDeviceManager::getInstance().getDeviceByName(this->model.getDeviceName()); if (device != NULL && device->isConnected()) { if (this->command.getSwitcher() == "pgm" || this->command.getSwitcher() == "prev") device->selectInput(this->command.getSwitcher(), this->command.getInput(), this->command.getMixerStep()); else // Aux. device->setAuxSource(this->command.getSwitcher(), this->command.getInput()); } if (this->markUsedItems) setUsed(true); } void RundownAtemInputWidget::executePreview() { const QSharedPointer<AtemDevice> device = AtemDeviceManager::getInstance().getDeviceByName(this->model.getDeviceName()); if (device != NULL && device->isConnected()) { if (this->command.getSwitcher() == "pgm") device->selectInput("prev", this->command.getInput(), this->command.getMixerStep()); } } void RundownAtemInputWidget::delayChanged(int delay) { this->labelDelay->setText(QString("Delay: %1").arg(delay)); } void RundownAtemInputWidget::checkGpiConnection() { this->labelGpiConnected->setVisible(this->command.getAllowGpi()); if (GpiManager::getInstance().getGpiDevice()->isConnected()) this->labelGpiConnected->setPixmap(QPixmap(":/Graphics/Images/GpiConnected.png")); else this->labelGpiConnected->setPixmap(QPixmap(":/Graphics/Images/GpiDisconnected.png")); } void RundownAtemInputWidget::checkDeviceConnection() { const QSharedPointer<AtemDevice> device = AtemDeviceManager::getInstance().getDeviceByName(this->model.getDeviceName()); if (device == NULL) this->labelDisconnected->setVisible(true); else this->labelDisconnected->setVisible(!device->isConnected()); } void RundownAtemInputWidget::configureOscSubscriptions() { if (!this->command.getAllowRemoteTriggering()) return; if (this->playControlSubscription != NULL) this->playControlSubscription->disconnect(); // Disconnect all events. if (this->playNowControlSubscription != NULL) this->playNowControlSubscription->disconnect(); // Disconnect all events. if (this->updateControlSubscription != NULL) this->updateControlSubscription->disconnect(); // Disconnect all events. if (this->previewControlSubscription != NULL) this->previewControlSubscription->disconnect(); // Disconnect all events. QString playControlFilter = Osc::DEFAULT_PLAY_CONTROL_FILTER; playControlFilter.replace("#UID#", this->command.getRemoteTriggerId()); this->playControlSubscription = new OscSubscription(playControlFilter, this); QObject::connect(this->playControlSubscription, SIGNAL(subscriptionReceived(const QString&, const QList<QVariant>&)), this, SLOT(playControlSubscriptionReceived(const QString&, const QList<QVariant>&))); QString playNowControlFilter = Osc::DEFAULT_PLAYNOW_CONTROL_FILTER; playNowControlFilter.replace("#UID#", this->command.getRemoteTriggerId()); this->playNowControlSubscription = new OscSubscription(playNowControlFilter, this); QObject::connect(this->playNowControlSubscription, SIGNAL(subscriptionReceived(const QString&, const QList<QVariant>&)), this, SLOT(playNowControlSubscriptionReceived(const QString&, const QList<QVariant>&))); QString updateControlFilter = Osc::DEFAULT_UPDATE_CONTROL_FILTER; updateControlFilter.replace("#UID#", this->command.getRemoteTriggerId()); this->updateControlSubscription = new OscSubscription(updateControlFilter, this); QObject::connect(this->updateControlSubscription, SIGNAL(subscriptionReceived(const QString&, const QList<QVariant>&)), this, SLOT(updateControlSubscriptionReceived(const QString&, const QList<QVariant>&))); QString previewControlFilter = Osc::DEFAULT_PREVIEW_CONTROL_FILTER; previewControlFilter.replace("#UID#", this->command.getRemoteTriggerId()); this->previewControlSubscription = new OscSubscription(previewControlFilter, this); QObject::connect(this->previewControlSubscription, SIGNAL(subscriptionReceived(const QString&, const QList<QVariant>&)), this, SLOT(previewControlSubscriptionReceived(const QString&, const QList<QVariant>&))); } void RundownAtemInputWidget::allowGpiChanged(bool allowGpi) { Q_UNUSED(allowGpi); checkGpiConnection(); } void RundownAtemInputWidget::gpiConnectionStateChanged(bool connected, GpiDevice* device) { Q_UNUSED(connected); Q_UNUSED(device); checkGpiConnection(); } void RundownAtemInputWidget::remoteTriggerIdChanged(const QString& remoteTriggerId) { configureOscSubscriptions(); this->labelRemoteTriggerId->setText(QString("UID: %1").arg(remoteTriggerId)); } void RundownAtemInputWidget::deviceConnectionStateChanged(AtemDevice& device) { Q_UNUSED(device); checkDeviceConnection(); } void RundownAtemInputWidget::deviceAdded(AtemDevice& device) { if (AtemDeviceManager::getInstance().getDeviceModelByAddress(device.getAddress()).getName() == this->model.getDeviceName()) QObject::connect(&device, SIGNAL(connectionStateChanged(AtemDevice&)), this, SLOT(deviceConnectionStateChanged(AtemDevice&))); checkDeviceConnection(); } void RundownAtemInputWidget::playControlSubscriptionReceived(const QString& predicate, const QList<QVariant>& arguments) { Q_UNUSED(predicate); if (this->command.getAllowRemoteTriggering() && arguments.count() > 0 && arguments[0].toInt() > 0) executeCommand(Playout::PlayoutType::Play); } void RundownAtemInputWidget::playNowControlSubscriptionReceived(const QString& predicate, const QList<QVariant>& arguments) { Q_UNUSED(predicate); if (this->command.getAllowRemoteTriggering() && arguments.count() > 0 && arguments[0].toInt() > 0) executeCommand(Playout::PlayoutType::PlayNow); } void RundownAtemInputWidget::updateControlSubscriptionReceived(const QString& predicate, const QList<QVariant>& arguments) { Q_UNUSED(predicate); if (this->command.getAllowRemoteTriggering() && arguments.count() > 0 && arguments[0].toInt() > 0) executeCommand(Playout::PlayoutType::Update); } void RundownAtemInputWidget::previewControlSubscriptionReceived(const QString& predicate, const QList<QVariant>& arguments) { Q_UNUSED(predicate); if (this->command.getAllowRemoteTriggering() && arguments.count() > 0 && arguments[0].toInt() > 0) executeCommand(Playout::PlayoutType::Preview); }
gpl-3.0
RemyAWM/gegl-fx
tests/simple/test-buffer-cast.c
3
2015
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2010 Martin Nordholts */ #include "config.h" #include "gegl.h" #include "gegl-plugin.h" #define SUCCESS 0 #define FAILURE -1 static int test_buffer_cast (void) { gint result = SUCCESS; GeglBuffer *buffer = gegl_buffer_new (GEGL_RECTANGLE (0,0,1,1), babl_format ("R'G'B'A u8")); GeglBuffer *cbuffer = gegl_buffer_new (GEGL_RECTANGLE (0,0,1,1), babl_format ("Y u8")); guchar srcpix[4] = {1,2,3,4}; guchar dstpix[4] = {0}; gegl_buffer_set (buffer, NULL, 0, NULL, srcpix, GEGL_AUTO_ROWSTRIDE); gegl_buffer_set_format (cbuffer, babl_format_new ("name", "B' u8", babl_model ("R'G'B'A"), babl_type ("u8"), babl_component ("B'"), NULL)); gegl_buffer_copy (buffer, NULL, cbuffer, NULL); gegl_buffer_set_format (cbuffer, NULL); gegl_buffer_get (cbuffer, NULL, 1.0, NULL, dstpix, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE); if (dstpix[0] != 3) result = FAILURE; g_object_unref (buffer); g_object_unref (cbuffer); return result; } int main(int argc, char *argv[]) { gint result = SUCCESS; gegl_init (&argc, &argv); if (result == SUCCESS) result = test_buffer_cast (); gegl_exit (); return result; }
gpl-3.0
robbriggs/masters-project-mercurium
tests/02_typecalc_cxx.dg/success_374.cpp
3
1629
/*-------------------------------------------------------------------- (C) Copyright 2006-2013 Barcelona Supercomputing Center Centro Nacional de Supercomputacion This file is part of Mercurium C/C++ source-to-source compiler. See AUTHORS file in the top level directory for information regarding developers and contributors. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Mercurium C/C++ source-to-source compiler is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Mercurium C/C++ source-to-source compiler; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. --------------------------------------------------------------------*/ /* <testinfo> test_generator=config/mercurium </testinfo> */ template <typename T> struct A { void foo(int*); struct MyStruct { }; }; template <typename T> struct B : A<T> { using typename A<T>::MyStruct; MyStruct bar(); using A<T>::foo; void foo(float*); }; void g() { B<int> b; A<int>::MyStruct m = b.bar(); float r; b.foo(&r); int i; b.foo(&i); }
gpl-3.0
askotx/RetroArch
menu/menu.c
3
10038
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2011-2015 - Daniel De Matteis * * RetroArch is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ #include <file/file_path.h> #include "menu.h" #include "menu_hash.h" #include "menu_display.h" #include "menu_entry.h" #include "menu_shader.h" #include "../dynamic.h" #include "../general.h" #include "../frontend/frontend.h" #include "../retroarch.h" #include "../performance.h" #include "../runloop_data.h" static void menu_environment_get(int *argc, char *argv[], void *args, void *params_data) { struct rarch_main_wrap *wrap_args = (struct rarch_main_wrap*)params_data; global_t *global = global_get_ptr(); settings_t *settings = config_get_ptr(); menu_handle_t *menu = menu_driver_get_ptr(); if (!wrap_args) return; wrap_args->no_content = menu->load_no_content; if (!global->has_set.verbosity) wrap_args->verbose = global->verbosity; wrap_args->config_path = *global->path.config ? global->path.config : NULL; wrap_args->sram_path = *global->dir.savefile ? global->dir.savefile : NULL; wrap_args->state_path = *global->dir.savestate ? global->dir.savestate : NULL; wrap_args->content_path = *global->path.fullpath ? global->path.fullpath : NULL; if (!global->has_set.libretro) wrap_args->libretro_path = *settings->libretro ? settings->libretro : NULL; wrap_args->touched = true; } static void menu_push_to_history_playlist(void) { settings_t *settings = config_get_ptr(); global_t *global = global_get_ptr(); if (!settings->history_list_enable) return; if (*global->path.fullpath) { char tmp[PATH_MAX_LENGTH] = {0}; char str[PATH_MAX_LENGTH] = {0}; fill_pathname_base(tmp, global->path.fullpath, sizeof(tmp)); snprintf(str, sizeof(str), "INFO - Loading %s ...", tmp); rarch_main_msg_queue_push(str, 1, 1, false); } content_playlist_push(g_defaults.history, global->path.fullpath, NULL, settings->libretro, global->menu.info.library_name, NULL, NULL); } /** * menu_load_content: * * Loads content into currently selected core. * Will also optionally push the content entry to the history playlist. * * Returns: true (1) if successful, otherwise false (0). **/ bool menu_load_content(enum rarch_core_type type) { menu_handle_t *menu = menu_driver_get_ptr(); menu_display_t *disp = menu_display_get_ptr(); driver_t *driver = driver_get_ptr(); global_t *global = global_get_ptr(); /* redraw menu frame */ if (disp) disp->msg_force = true; menu_entry_iterate(MENU_ACTION_NOOP); menu_display_fb(); if (!(main_load_content(0, NULL, NULL, menu_environment_get, driver->frontend_ctx->process_args))) { char name[PATH_MAX_LENGTH] = {0}; char msg[PATH_MAX_LENGTH] = {0}; fill_pathname_base(name, global->path.fullpath, sizeof(name)); snprintf(msg, sizeof(msg), "Failed to load %s.\n", name); rarch_main_msg_queue_push(msg, 1, 90, false); if (disp) disp->msg_force = true; return false; } menu_shader_manager_init(menu); event_command(EVENT_CMD_HISTORY_INIT); if (*global->path.fullpath || (menu && menu->load_no_content)) menu_push_to_history_playlist(); event_command(EVENT_CMD_VIDEO_SET_ASPECT_RATIO); event_command(EVENT_CMD_RESUME); return true; } void menu_common_push_content_settings(void) { menu_list_t *menu_list = menu_list_get_ptr(); menu_displaylist_info_t info = {0}; if (!menu_list) return; info.list = menu_list->selection_buf; strlcpy(info.path, menu_hash_to_str(MENU_LABEL_VALUE_CONTENT_SETTINGS), sizeof(info.path)); strlcpy(info.label, menu_hash_to_str(MENU_LABEL_CONTENT_SETTINGS), sizeof(info.label)); menu_list_push(menu_list->menu_stack, info.path, info.label, info.type, info.flags, 0); menu_displaylist_push_list(&info, DISPLAYLIST_CONTENT_SETTINGS); } void menu_common_load_content(bool persist, enum rarch_core_type type) { menu_display_t *disp = menu_display_get_ptr(); menu_list_t *menu_list = menu_list_get_ptr(); if (!menu_list) return; switch (type) { case CORE_TYPE_PLAIN: case CORE_TYPE_DUMMY: event_command(persist ? EVENT_CMD_LOAD_CONTENT_PERSIST : EVENT_CMD_LOAD_CONTENT); break; #ifdef HAVE_FFMPEG case CORE_TYPE_FFMPEG: event_command(EVENT_CMD_LOAD_CONTENT_FFMPEG); break; #endif case CORE_TYPE_IMAGEVIEWER: #ifdef HAVE_IMAGEVIEWER event_command(EVENT_CMD_LOAD_CONTENT_IMAGEVIEWER); #endif break; } menu_list_flush_stack(menu_list, NULL, MENU_SETTINGS); disp->msg_force = true; menu_common_push_content_settings(); } static int menu_init_entries(menu_entries_t *entries) { if (!(entries->menu_list = (menu_list_t*)menu_list_new())) return -1; return 0; } /** * menu_init: * @data : Menu context handle. * * Create and initialize menu handle. * * Returns: menu handle on success, otherwise NULL. **/ void *menu_init(const void *data) { menu_handle_t *menu = NULL; menu_display_t *disp = NULL; menu_ctx_driver_t *menu_ctx = (menu_ctx_driver_t*)data; global_t *global = global_get_ptr(); settings_t *settings = config_get_ptr(); if (!menu_ctx) return NULL; if (!(menu = (menu_handle_t*)menu_ctx->init())) return NULL; strlcpy(settings->menu.driver, menu_ctx->ident, sizeof(settings->menu.driver)); if (menu_init_entries(&menu->entries) != 0) goto error; global->core_info.current = (core_info_t*)calloc(1, sizeof(core_info_t)); if (!global->core_info.current) goto error; #ifdef HAVE_SHADER_MANAGER menu->shader = (struct video_shader*)calloc(1, sizeof(struct video_shader)); if (!menu->shader) goto error; #endif menu->push_help_screen = settings->menu_show_start_screen; menu->help_screen_type = MENU_HELP_WELCOME; settings->menu_show_start_screen = false; #if 0 if (settings->bundle_assets_extract_enable && (strcmp(PACKAGE_VERSION, settings->bundle_assets_last_extracted_version) != 0) ) { menu->push_help_screen = true; menu->help_screen_type = MENU_HELP_EXTRACT; rarch_main_data_msg_queue_push(DATA_TYPE_FILE, "cb_bundle_extract", "cb_bundle_extract", 0, 1, true); } #endif menu_shader_manager_init(menu); if (!menu_display_init(menu)) goto error; disp = &menu->display; rarch_assert(disp->msg_queue = msg_queue_new(8)); menu_display_fb_set_dirty(); menu_driver_set_alive(); return menu; error: if (menu->entries.menu_list) menu_list_free(menu->entries.menu_list); menu->entries.menu_list = NULL; if (global->core_info.current) free(global->core_info.current); global->core_info.current = NULL; if (menu->shader) free(menu->shader); menu->shader = NULL; if (menu) free(menu); return NULL; } /** * menu_free_list: * @menu : Menu handle. * * Frees menu lists. **/ static void menu_free_list(menu_entries_t *entries) { if (!entries) return; menu_setting_free(entries->list_settings); entries->list_settings = NULL; menu_list_free(entries->menu_list); entries->menu_list = NULL; } /** * menu_free: * @menu : Menu handle. * * Frees a menu handle **/ void menu_free(menu_handle_t *menu) { global_t *global = global_get_ptr(); menu_display_t *disp = menu_display_get_ptr(); if (!menu || !disp) return; if (menu->playlist) content_playlist_free(menu->playlist); menu->playlist = NULL; menu_shader_free(menu); menu_driver_free(menu); #ifdef HAVE_DYNAMIC libretro_free_system_info(&global->menu.info); #endif menu_display_free(menu); menu_free_list(&menu->entries); event_command(EVENT_CMD_HISTORY_DEINIT); if (global->core_info.list) core_info_list_free(global->core_info.list); if (global->core_info.current) free(global->core_info.current); global->core_info.current = NULL; menu_driver_unset_alive(); free(menu); } /** * menu_iterate: * @input : input sample for this frame * @old_input : input sample of the previous frame * @trigger_input : difference' input sample - difference * between 'input' and 'old_input' * * Runs RetroArch menu for one frame. * * Returns: 0 on success, -1 if we need to quit out of the loop. **/ int menu_iterate(retro_input_t input, retro_input_t old_input, retro_input_t trigger_input) { int32_t ret = 0; unsigned action = 0; menu_display_t *disp = menu_display_get_ptr(); menu_input_t *menu_input = menu_input_get_ptr(); menu_animation_update_time(disp->animation); menu_input->joypad.state = menu_input_frame(input, trigger_input); action = menu_input->joypad.state; ret = menu_entry_iterate(action); if (menu_driver_alive() && !rarch_main_is_idle()) menu_display_fb(); menu_driver_set_texture(); if (ret) return -1; return 0; }
gpl-3.0
cisco-open-source/libcdio
src/cdda-player.c
3
49576
/* Copyright (C) 2005, 2006, 2008, 2009, 2010, 2011, 2012 Rocky Bernstein <rocky@gnu.org> Adapted from Gerd Knorr's player.c program <kraxel@bytesex.org> Copyright (C) 1997, 1998 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" # define __CDIO_CONFIG_H__ 1 #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_CDDB #include <cddb/cddb.h> #endif #include <signal.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_CURSES_H # include <curses.h> #else # ifdef HAVE_NCURSES_H #include <ncurses.h> # else # ifdef HAVE_NCURSES_NCURSES_H # include <ncurses/ncurses.h> # else # error "You need <curses.h> or <ncurses.h to build cdda-player" # endif # endif #endif #include <cdio/cdio.h> #include <cdio/mmc.h> #include <cdio/util.h> #include <cdio/cd_types.h> #include <cdio/logging.h> #include "cddb.h" #include "getopt.h" static void action(const char *psz_action); static void display_cdinfo(CdIo_t *p_cdio, track_t i_tracks, track_t i_first_track); static void display_tracks(void); static void get_cddb_track_info(track_t i_track); static void get_cdtext_track_info(track_t i_track); static void get_track_info(track_t i_track); static bool play_track(track_t t1, track_t t2); static CdIo_t *p_cdio; /* libcdio handle */ static driver_id_t driver_id = DRIVER_DEVICE; static int b_sig = false; /* set on some signals */ /* cdrom data */ static track_t i_first_track; static track_t i_last_track; static track_t i_first_audio_track; static track_t i_last_audio_track; static track_t i_last_display_track = CDIO_INVALID_TRACK; static track_t i_tracks; static msf_t toc[CDIO_CDROM_LEADOUT_TRACK+1]; static cdio_subchannel_t sub; /* subchannel last time read */ static int i_data; /* # of data tracks present ? */ static int start_track = 0; static int stop_track = 0; static int one_track = 0; static int i_vol_port = 5; /* If 5, retrieve volume port. Otherwise the port number 0..3 of a working volume port and 4 for no working port. */ /* settings which can be set from the command or interactively. */ static bool b_cd = false; static bool auto_mode = false; static bool b_verbose = false; static bool debug = false; static bool b_interactive = true; static bool b_prefer_cdtext = true; #ifdef CDDB_ADDED static bool b_cddb = false; /* CDDB database present */ #endif static bool b_db = false; /* we have a database at all */ static bool b_record = false; /* we have a record for static the inserted CD */ static bool b_all_tracks = false; /* True if we display all tracks*/ static int8_t i_volume_level = -1; /* Valid range is 0..100 */ static char *psz_device=NULL; static char *psz_program; /* Info about songs and titles. The 0 entry will contain the disc info. */ typedef struct { char title[80]; char artist[80]; char length[8]; char ext_data[80]; bool b_cdtext; /* true if from CD-Text, false if from CDDB */ } cd_track_info_rec_t; static cd_track_info_rec_t cd_info[CDIO_CD_MAX_TRACKS+2]; static char title[80]; static char artist[80]; static char genre[40]; static char category[40]; static char year[5]; static bool b_cdtext_title; /* true if from CD-Text, false if from CDDB */ static bool b_cdtext_artist; /* true if from CD-Text, false if from CDDB */ static bool b_cdtext_genre; /* true if from CD-Text, false if from CDDB */ #ifdef CDTEXT_CATEGORY_ADDED static bool b_cdtext_category; /* true if from CD-Text, false if from CDDB */ #endif static bool b_cdtext_year; /* true if from CD-Text, false if from CDDB */ static cdio_audio_volume_t audio_volume; #ifdef HAVE_CDDB static cddb_conn_t *p_conn = NULL; static cddb_disc_t *p_cddb_disc = NULL; static int i_cddb_matches = 0; #endif #define MAX_KEY_STR 50 static const char key_bindings[][MAX_KEY_STR] = { " right play / next track", " left previous track", " up/down 10 sec forward / back", " 1-9 jump to track 1-9", " 0 jump to track 10", " F1-F20 jump to track 11-30", " ", " k, h, ? show this key help", " l, toggle listing all tracks", " e eject", " c close tray", " p, space pause / resume", " s stop", " q, ^C quit", " x quit and continue playing", " a toggle auto-mode", " - decrease volume level", " + increase volume level", }; static const unsigned int i_key_bindings = sizeof(key_bindings) / MAX_KEY_STR; /* ---------------------------------------------------------------------- */ /* tty stuff */ typedef enum { LINE_STATUS = 0, LINE_CDINFO = 1, LINE_ARTIST = 3, LINE_CDNAME = 4, LINE_GENRE = 5, LINE_YEAR = 6, LINE_TRACK_PREV = 8, LINE_TRACK_TITLE = 9, LINE_TRACK_ARTIST = 10, LINE_TRACK_NEXT = 11, } track_line_t; static unsigned int LINE_ACTION = 25; static unsigned int COLS_LAST; static char psz_action_line[300] = ""; static int rounded_div(unsigned int i_a, unsigned int i_b) { const unsigned int i_b_half=i_b/2; return ((i_a)+i_b_half)/i_b; } /** Curses window initialization. */ static void tty_raw() { if (!b_interactive) return; initscr(); cbreak(); clear(); noecho(); #ifdef HAVE_KEYPAD keypad(stdscr,1); #endif getmaxyx(stdscr, LINE_ACTION, COLS_LAST); LINE_ACTION--; refresh(); } /** Curses window finalization. */ static void tty_restore() { if (!b_interactive) return; endwin(); } /* Called when window is resized. */ static void sigwinch() { tty_restore(); tty_raw(); action(NULL); } /* Signal handler - Ctrl-C and others. */ static void ctrlc(int signal) { b_sig = true; } /* Timed wait on an event. */ static int select_wait(int sec) { struct timeval tv; fd_set se; FD_ZERO(&se); FD_SET(0,&se); tv.tv_sec = sec; tv.tv_usec = 0; return select(1,&se,NULL,NULL,&tv); } /* ---------------------------------------------------------------------- */ /* Display the action line. */ static void action(const char *psz_action) { if (!b_interactive) { if (b_verbose && psz_action) fprintf(stderr,"action: %s\n", psz_action); return; } if (!psz_action) psz_action = psz_action_line; else if (psz_action && strlen(psz_action)) snprintf(psz_action_line, sizeof(psz_action_line), "action : %s", psz_action); else snprintf(psz_action_line, sizeof(psz_action_line), "%s", "" ); mvprintw(LINE_ACTION, 0, psz_action_line); clrtoeol(); refresh(); } /* Display an error message.. */ static void xperror(const char *psz_msg) { char line[80]; if (!b_interactive) { if (b_verbose) { fprintf(stderr, "error: "); perror(psz_msg); } return; } if (b_verbose) { snprintf(line, sizeof(line), "%s: %s", psz_msg, strerror(errno)); attron(A_STANDOUT); mvprintw(LINE_ACTION, 0, (char *) "error : %s", line); attroff(A_STANDOUT); clrtoeol(); refresh(); select_wait(3); action(""); } } static void finish(const char *psz_msg, int rc) { if (b_interactive) { attron(A_STANDOUT); mvprintw(LINE_ACTION, 0, (char *) "%s, exiting...\n", psz_msg); attroff(A_STANDOUT); clrtoeol(); refresh(); } tty_restore(); #ifdef HAVE_CDDB if (p_conn) cddb_destroy(p_conn); cddb_disc_destroy(p_cddb_disc); libcddb_shutdown(); #endif /*HAVE_CDDB*/ cdio_destroy (p_cdio); free (psz_device); exit (rc); } /* ---------------------------------------------------------------------- */ /* Set all audio channels to level. level is assumed to be in the range 0..100. */ static bool set_volume_level(CdIo_t *p_cdio, uint8_t i_level) { const unsigned int i_new_level= rounded_div(i_level*256, 100); unsigned int i; driver_return_code_t rc; for (i=0; i<=3; i++) { audio_volume.level[i] = i_new_level; } rc = cdio_audio_set_volume(p_cdio, &audio_volume); if ( DRIVER_OP_SUCCESS != rc ) { /* If we can't do a get volume, audio_volume.level is used as a second-best guess. But if this set failed restore it to an invalid value so we don't get confused and think that this was set. */ for (i=0; i<=3; i++) { audio_volume.level[i] = 0; } } else { /* Set i_vol_port so volume levels set above will get used. */ i_vol_port=0; } return rc; } /* Subtract one from the volume level. If we are at the minimum value, * nothing is done. We used to wrap at the boundaries but this is probably wrong because is assumes someone: * looks at the display while listening, * knows that 99 is the maximum value. See issue #33333 If the volume level is undefined, then this means we could not get the current value and we'll' set it to 50 the midway point. Return the status of setting the volume level. */ static bool decrease_volume_level(CdIo_t *p_cdio) { if (i_volume_level == -1) i_volume_level = 51; if (i_volume_level <= 0) i_volume_level = 1; return set_volume_level(p_cdio, --i_volume_level); } /* Add 1 to the volume level. If we are at the maximum value, nothing is done. We used to wrap at the boundaries but this is probably wrong because is assumes someone: * looks at the display while listening, * knows that 99 is the maximum value. See issue #33333 If volume level is undefined, then this means we could not get the current value and we'll' set it to 50 the midway point. Return the status of setting the volume level. */ static bool increase_volume_level(CdIo_t *p_cdio) { if (i_volume_level == -1) i_volume_level = 49; if (i_volume_level <= 0) i_volume_level = 0; if (i_volume_level > 98) i_volume_level = 98; return set_volume_level(p_cdio, ++i_volume_level); } /** Stop playing audio CD */ static bool cd_stop(CdIo_t *p_cdio) { bool b_ok = true; if (b_cd && p_cdio) { action("stop..."); i_last_audio_track = CDIO_INVALID_TRACK; b_ok = DRIVER_OP_SUCCESS == cdio_audio_stop(p_cdio); if ( !b_ok ) xperror("stop"); if (b_all_tracks) display_tracks(); } return b_ok; } /** Eject CD */ static bool cd_eject(void) { bool b_ok = true; if (p_cdio) { cd_stop(p_cdio); action("eject..."); b_ok = DRIVER_OP_SUCCESS == cdio_eject_media(&p_cdio); if (!b_ok) xperror("eject"); b_cd = false; cdio_destroy (p_cdio); p_cdio = NULL; } return b_ok; } /** Close CD tray */ static bool cd_close(const char *psz_device) { bool b_ok = true; if (!b_cd) { action("close..."); b_ok = DRIVER_OP_SUCCESS == cdio_close_tray(psz_device, &driver_id); if (!b_ok) xperror("close"); } return b_ok; } /** Pause playing audio CD */ static bool cd_pause(CdIo_t *p_cdio) { bool b_ok = true; if (sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) { b_ok = DRIVER_OP_SUCCESS == cdio_audio_pause(p_cdio); if (!b_ok) xperror("pause"); } return b_ok; } /** Get status/track/position info of an audio CD */ static bool read_subchannel(CdIo_t *p_cdio) { bool b_ok = true; if (!p_cdio) return false; b_ok = DRIVER_OP_SUCCESS == cdio_audio_read_subchannel(p_cdio, &sub); if (!b_ok) { xperror("read subchannel"); b_cd = 0; } if (auto_mode && sub.audio_status == CDIO_MMC_READ_SUB_ST_COMPLETED) cd_eject(); return b_ok; } #ifdef HAVE_CDDB /** This routine is called by vcd routines on error. Setup is done by init_input_plugin. */ static void cddb_log_handler (cddb_log_level_t level, const char message[]) { switch (level) { case CDDB_LOG_DEBUG: case CDDB_LOG_INFO: if (!b_verbose) return; /* Fall through if to warn case */ case CDDB_LOG_WARN: case CDDB_LOG_ERROR: case CDDB_LOG_CRITICAL: default: xperror(message); break; } /* gl_default_cdio_log_handler (level, message); */ } #endif /* HAVE_CDDB */ static void get_cddb_disc_info(CdIo_t *p_cdio) { #ifdef HAVE_CDDB b_db = init_cddb(p_cdio, &p_conn, &p_cddb_disc, xperror, i_first_track, i_tracks, &i_cddb_matches); if (b_db) { int i_year; i_year = atoi(year); cddb_disc_set_artist(p_cddb_disc, artist); cddb_disc_set_title(p_cddb_disc, title); cddb_disc_set_genre(p_cddb_disc, genre); cddb_disc_set_year(p_cddb_disc, i_year); } #endif /* HAVE_CDDB */ return; } #define add_cdtext_disc_info(format_str, info_field, FIELD) \ if (cdtext_get_const(p_cdtext, FIELD, 0) && !strlen(info_field)) { \ snprintf(info_field, sizeof(info_field), format_str, \ cdtext_get_const(p_cdtext, FIELD, 0)); \ b_cdtext_ ## info_field = true; \ } static void get_cdtext_disc_info(CdIo_t *p_cdio) { cdtext_t *p_cdtext = cdio_get_cdtext(p_cdio); if (p_cdtext) { add_cdtext_disc_info("%s", title, CDTEXT_FIELD_TITLE); add_cdtext_disc_info("%s", artist, CDTEXT_FIELD_PERFORMER); add_cdtext_disc_info("%s", genre, CDTEXT_FIELD_GENRE); } } static void get_disc_info(CdIo_t *p_cdio) { b_db = false; if (b_prefer_cdtext) { get_cdtext_disc_info(p_cdio); get_cddb_disc_info(p_cdio); } else { get_cddb_disc_info(p_cdio); get_cdtext_disc_info(p_cdio); } } /** Read CD TOC and set CD information. */ static void read_toc(CdIo_t *p_cdio) { track_t i; action("read toc..."); memset(cd_info, 0, sizeof(cd_info)); title[0] = artist[0] = genre[0] = category[0] = year[0] = '\0'; i_first_track = cdio_get_first_track_num(p_cdio); i_last_track = cdio_get_last_track_num(p_cdio); i_tracks = cdio_get_num_tracks(p_cdio); i_first_audio_track = i_first_track; i_last_audio_track = i_last_track; cdio_audio_get_volume(p_cdio, &audio_volume); for (i_vol_port=0; i_vol_port<4; i_vol_port++) { if (audio_volume.level[i_vol_port] > 0) break; } if ( CDIO_INVALID_TRACK == i_first_track || CDIO_INVALID_TRACK == i_last_track ) { xperror("read toc header"); b_cd = false; b_record = false; i_last_display_track = CDIO_INVALID_TRACK; } else { b_cd = true; i_data = 0; get_disc_info(p_cdio); for (i = i_first_track; i <= i_last_track+1; i++) { int s; if ( !cdio_get_track_msf(p_cdio, i, &(toc[i])) ) { xperror("read toc entry"); b_cd = false; return; } if ( TRACK_FORMAT_AUDIO == cdio_get_track_format(p_cdio, i) ) { if (i != i_first_track) { s = cdio_audio_get_msf_seconds(&toc[i]) - cdio_audio_get_msf_seconds(&toc[i-1]); snprintf(cd_info[i-1].length, sizeof(cd_info[0].length), "%02d:%02d", s / CDIO_CD_SECS_PER_MIN, s % CDIO_CD_SECS_PER_MIN); } } else { if ((i != i_last_track+1) ) { i_data++; if (i == i_first_track) { if (i == i_last_track) i_first_audio_track = CDIO_CDROM_LEADOUT_TRACK; else i_first_audio_track++; } } } get_track_info(i); } b_record = true; read_subchannel(p_cdio); if (auto_mode && sub.audio_status != CDIO_MMC_READ_SUB_ST_PLAY) play_track(1, CDIO_CDROM_LEADOUT_TRACK); } action(""); if (!b_all_tracks) display_cdinfo(p_cdio, i_tracks, i_first_track); } /** Play an audio track. */ static bool play_track(track_t i_start_track, track_t i_end_track) { bool b_ok = true; char line[80]; if (!b_cd) { read_toc(p_cdio); } read_subchannel(p_cdio); if (!b_cd || i_first_track == CDIO_CDROM_LEADOUT_TRACK) return false; if (debug) fprintf(stderr,"play tracks: %d-%d => ", i_start_track, i_end_track-1); if (i_start_track < i_first_track) i_start_track = i_first_track; if (i_start_track > i_last_audio_track) i_start_track = i_last_audio_track; if (i_end_track < i_first_track) i_end_track = i_first_track; if (i_end_track > i_last_audio_track) i_end_track = i_last_audio_track; i_end_track++; if (debug) fprintf(stderr,"%d-%d\n",i_start_track, i_end_track-1); cd_pause(p_cdio); snprintf(line, sizeof(line), "play track %d to track %d.", i_start_track, i_end_track-1); action(line); b_ok = (DRIVER_OP_SUCCESS == cdio_audio_play_msf(p_cdio, &(toc[i_start_track]), &(toc[i_end_track])) ); if (!b_ok) xperror("play"); return b_ok; } static void skip(int diff) { msf_t start_msf; int sec; read_subchannel(p_cdio); if (!b_cd || i_first_track == CDIO_CDROM_LEADOUT_TRACK) return; sec = cdio_audio_get_msf_seconds(&sub.abs_addr); sec += diff; if (sec < 0) sec = 0; start_msf.m = cdio_to_bcd8(sec / CDIO_CD_SECS_PER_MIN); start_msf.s = cdio_to_bcd8(sec % CDIO_CD_SECS_PER_MIN); start_msf.f = 0; cd_pause(p_cdio); if ( DRIVER_OP_SUCCESS != cdio_audio_play_msf(p_cdio, &start_msf, &(toc[i_last_audio_track])) ) xperror("play"); } static bool toggle_pause() { bool b_ok = true; if (!b_cd) return false; if (CDIO_MMC_READ_SUB_ST_PAUSED == sub.audio_status) { b_ok = DRIVER_OP_SUCCESS != cdio_audio_resume(p_cdio); if (!b_ok) xperror("resume"); } else { b_ok = DRIVER_OP_SUCCESS != cdio_audio_pause(p_cdio); if (!b_ok) xperror("pause"); } return b_ok; } /** Update windows with status and possibly track info. This used in interactive playing not batch mode. */ static void display_status(bool b_status_only) { char line[80]; if (!b_interactive) return; if (!b_cd) { snprintf(line, sizeof(line), "no CD in drive (%s)", psz_device); } else if (i_first_track == CDIO_CDROM_LEADOUT_TRACK) { snprintf(line, sizeof(line), "CD has only data tracks"); } else if (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) { cdio_audio_get_volume(p_cdio, &audio_volume); if (i_vol_port < 4) { i_volume_level = rounded_div(audio_volume.level[i_vol_port]*100, 256); snprintf(line, sizeof(line), "track %2d - %02x:%02x of %s (%02x:%02x abs) %s volume: %d", sub.track, sub.rel_addr.m, sub.rel_addr.s, cd_info[sub.track].length, sub.abs_addr.m, sub.abs_addr.s, mmc_audio_state2str(sub.audio_status), i_volume_level); } else snprintf(line, sizeof(line), "track %2d - %02x:%02x of %s (%02x:%02x abs) %s", sub.track, sub.rel_addr.m, sub.rel_addr.s, cd_info[sub.track].length, sub.abs_addr.m, sub.abs_addr.s, mmc_audio_state2str(sub.audio_status)); } else { snprintf(line, sizeof(line), "%s", mmc_audio_state2str(sub.audio_status)); } action(NULL); mvprintw(LINE_STATUS, 0, (char *) "status%s: %s", auto_mode ? "*" : " ", line); clrtoeol(); if ( !b_status_only && b_db && i_last_display_track != sub.track && (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) && b_cd) { if (b_all_tracks) display_tracks(); else { const cd_track_info_rec_t *p_cd_info = &cd_info[sub.track]; i_last_display_track = sub.track; if (i_first_audio_track != sub.track && strlen(cd_info[sub.track-1].title)) { const cd_track_info_rec_t *p_cd_info = &cd_info[sub.track-1]; mvprintw(LINE_TRACK_PREV, 0, (char *) " track %2d title : %s [%s]", sub.track-1, p_cd_info->title, p_cd_info->b_cdtext ? "CD-Text" : "CDDB"); clrtoeol(); } else { mvprintw(LINE_TRACK_PREV, 0, (char *) "%s",""); clrtoeol(); } if (strlen(p_cd_info->title)) { mvprintw(LINE_TRACK_TITLE, 0, (char *) ">track %2d title : %s [%s]", sub.track, p_cd_info->title, (char *) (p_cd_info->b_cdtext ? "CD-Text" : "CDDB")); clrtoeol(); } if (strlen(p_cd_info->artist)) { mvprintw(LINE_TRACK_ARTIST, 0, (char *) ">track %2d artist: %s [%s]", sub.track, p_cd_info->artist, p_cd_info->b_cdtext ? "CD-Text" : "CDDB"); clrtoeol(); } if (i_last_audio_track != sub.track && strlen(cd_info[sub.track+1].title)) { const cd_track_info_rec_t *p_cd_info = &cd_info[sub.track+1]; mvprintw(LINE_TRACK_NEXT, 0, (char *) " track %2d title : %s [%s]", sub.track+1, p_cd_info->title, p_cd_info->b_cdtext ? "CD-Text" : "CDDB"); clrtoeol(); } else { mvprintw(LINE_TRACK_NEXT, 0, (char *) "%s",""); clrtoeol(); } clrtobot(); } } action(NULL); /* Redisplay action line. */ } static void get_cddb_track_info(track_t i_track) { #ifdef HAVE_CDDB cddb_track_t *t = cddb_disc_get_track(p_cddb_disc, i_track - i_first_track); if (t) { cddb_track_set_title(t, title); cddb_track_set_artist(t, artist); } #else ; #endif } #define add_cdtext_track_info(format_str, info_field, FIELD) \ if (cdtext_get_const(p_cdtext, FIELD, i_track)) { \ snprintf(cd_info[i_track].info_field, \ sizeof(cd_info[i_track].info_field), \ format_str, cdtext_get_const(p_cdtext, FIELD, i_track)); \ cd_info[i_track].b_cdtext = true; \ } static void get_cdtext_track_info(track_t i_track) { cdtext_t *p_cdtext = cdio_get_cdtext(p_cdio); if (NULL != p_cdtext) { add_cdtext_track_info("%s", title, CDTEXT_FIELD_TITLE); add_cdtext_track_info("%s", artist, CDTEXT_FIELD_PERFORMER); } } static void get_track_info(track_t i_track) { if (b_prefer_cdtext) { get_cdtext_track_info(i_track); get_cddb_track_info(i_track); } else { get_cddb_track_info(i_track); get_cdtext_track_info(i_track); } } #define display_line(LINE_NO, COL_NO, format_str, field) \ if (field != NULL && field[0]) { \ mvprintw(LINE_NO, COL_NO, (char *) format_str " [%s]", \ field, \ b_cdtext_ ## field ? "CD-Text": "CDDB"); \ clrtoeol(); \ } static void display_cdinfo(CdIo_t *p_cdio, track_t i_tracks, track_t i_first_track) { int len; char line[80]; if (!b_interactive) return; if (!b_cd) snprintf(line, sizeof(line), "-"); else { len = snprintf(line, sizeof(line), "%2u tracks (%02x:%02x min)", (unsigned int) i_last_track, toc[i_last_track+1].m, toc[i_last_track+1].s); if (i_data && i_first_track != CDIO_CDROM_LEADOUT_TRACK) snprintf(line+len, sizeof(line)-len, ", audio=%u-%u", (unsigned int) i_first_audio_track, (unsigned int) i_last_audio_track); display_line(LINE_ARTIST, 0, "CD Artist : %s", artist); display_line(LINE_CDNAME, 0, "CD Title : %s", title); display_line(LINE_GENRE, 0, "CD Genre : %s", genre); display_line(LINE_YEAR, 0, "CD Year : %s", year); } mvprintw(LINE_CDINFO, 0, (char *) "CD info: %0s", line); clrtoeol(); action(NULL); } /* ---------------------------------------------------------------------- */ static void usage(char *prog) { fprintf(stderr, "%s is a simple curses CD player. It can pick up artist,\n" "CD name and song title from CD-Text info on the CD or\n" "via CDDB.\n" "\n" "usage: %s [options] [device]\n" "\n" "default for to search for a CD-ROM device with a CD-DA loaded\n" "\n" "These command line options available:\n" " -h print this help\n" " -k print key mapping\n" " -a start up in auto-mode\n" " -v verbose\n" "\n" "for non-interactive use (only one) of these:\n" " -l list tracks\n" " -c print cover (PostScript to stdout)\n" " -C close CD-ROM tray. If you use this option,\n" " a CD-ROM device name must be specified.\n" " -p play the whole CD\n" " -t n play track >n<\n" " -t a-b play all tracks between a and b (inclusive)\n" " -L set volume level\n" " -s stop playing\n" " -S list audio subchannel information\n" " -e eject cdrom\n" "\n" "That's all. Oh, maybe a few words more about the auto-mode. This\n" "is the 'dont-touch-any-key' feature. You load a CD, player starts\n" "to play it, and when it is done it ejects the CD. Start it that\n" "way on a spare console and forget about it...\n" "\n" "(c) 1997,98 Gerd Knorr <kraxel@goldbach.in-berlin.de>\n" "(c) 2005, 2006 Rocky Bernstein <rocky@gnu.org>\n" , prog, prog); } static void print_keys() { unsigned int i; for (i=0; i < i_key_bindings; i++) fprintf(stderr, "%s\n", key_bindings[i]); } static void keypress_wait(CdIo_t *p_cdio) { action("press any key to continue"); while (1 != select_wait(b_cd ? 1 : 5)) { read_subchannel(p_cdio); display_status(true); } (void) getch(); clrtobot(); action(NULL); if (!b_all_tracks) display_cdinfo(p_cdio, i_tracks, i_first_track); i_last_display_track = CDIO_INVALID_TRACK; } static void list_keys() { unsigned int i; for (i=0; i < i_key_bindings; i++) { mvprintw(LINE_TRACK_PREV+i, 0, (char *) "%s", key_bindings[i]); clrtoeol(); } keypress_wait(p_cdio); } static void display_tracks(void) { track_t i; int i_line=0; int s; if (b_record) { i_line=LINE_TRACK_PREV - 1; for (i = i_first_track; i <= i_last_track; i++) { char line[200]=""; s = cdio_audio_get_msf_seconds(&toc[i+1]) - cdio_audio_get_msf_seconds(&toc[i]); read_subchannel(p_cdio); snprintf(line, sizeof(line), "%2d %02d:%02d %s ", i, s / CDIO_CD_SECS_PER_MIN, s % CDIO_CD_SECS_PER_MIN, ( ( sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY || sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED ) && sub.track == i ) ? "->" : " |"); if (b_record) { if ( strlen(cd_info[i].title) ) strcat(line, cd_info[i].title); if ( strlen(cd_info[i].artist) > 0 ) { if (strlen(cd_info[i].title)) strcat(line, " / "); strcat(line, cd_info[i].artist); } } if (sub.track == i) { attron(A_STANDOUT); mvprintw(i_line++, 0, line); attroff(A_STANDOUT); } else mvprintw(i_line++, 0, line); clrtoeol(); } } } /* * PostScript 8bit latin1 handling * stolen from mpage output -- please don't ask me how this works... */ #define ENCODING_TRICKS \ "/reencsmalldict 12 dict def\n" \ "/ReEncodeSmall { reencsmalldict begin\n" \ "/newcodesandnames exch def /newfontname exch def\n" \ "/basefontname exch def\n" \ "/basefontdict basefontname findfont def\n" \ "/newfont basefontdict maxlength dict def\n" \ "basefontdict { exch dup /FID ne { dup /Encoding eq\n" \ "{ exch dup length array copy newfont 3 1 roll put }\n" \ "{ exch newfont 3 1 roll put }\n" \ "ifelse }\n" \ "{ pop pop }\n" \ "ifelse } forall\n" \ "newfont /FontName newfontname put\n" \ "newcodesandnames aload pop newcodesandnames length 2 idiv\n" \ "{ newfont /Encoding get 3 1 roll put } repeat\n" \ "newfontname newfont definefont pop end } def\n" \ "/charvec [\n" \ "026 /Scaron\n" \ "027 /Ydieresis\n" \ "028 /Zcaron\n" \ "029 /scaron\n" \ "030 /trademark\n" \ "031 /zcaron\n" \ "032 /space\n" \ "033 /exclam\n" \ "034 /quotedbl\n" \ "035 /numbersign\n" \ "036 /dollar\n" \ "037 /percent\n" \ "038 /ampersand\n" \ "039 /quoteright\n" \ "040 /parenleft\n" \ "041 /parenright\n" \ "042 /asterisk\n" \ "043 /plus\n" \ "044 /comma\n" \ "045 /minus\n" \ "046 /period\n" \ "047 /slash\n" \ "048 /zero\n" \ "049 /one\n" \ "050 /two\n" \ "051 /three\n" \ "052 /four\n" \ "053 /five\n" \ "054 /six\n" \ "055 /seven\n" \ "056 /eight\n" \ "057 /nine\n" \ "058 /colon\n" \ "059 /semicolon\n" \ "060 /less\n" \ "061 /equal\n" \ "062 /greater\n" \ "063 /question\n" \ "064 /at\n" \ "065 /A\n" \ "066 /B\n" \ "067 /C\n" \ "068 /D\n" \ "069 /E\n" \ "070 /F\n" \ "071 /G\n" \ "072 /H\n" \ "073 /I\n" \ "074 /J\n" \ "075 /K\n" \ "076 /L\n" \ "077 /M\n" \ "078 /N\n" \ "079 /O\n" \ "080 /P\n" \ "081 /Q\n" \ "082 /R\n" \ "083 /S\n" \ "084 /T\n" \ "085 /U\n" \ "086 /V\n" \ "087 /W\n" \ "088 /X\n" \ "089 /Y\n" \ "090 /Z\n" \ "091 /bracketleft\n" \ "092 /backslash\n" \ "093 /bracketright\n" \ "094 /asciicircum\n" \ "095 /underscore\n" \ "096 /quoteleft\n" \ "097 /a\n" \ "098 /b\n" \ "099 /c\n" \ "100 /d\n" \ "101 /e\n" \ "102 /f\n" \ "103 /g\n" \ "104 /h\n" \ "105 /i\n" \ "106 /j\n" \ "107 /k\n" \ "108 /l\n" \ "109 /m\n" \ "110 /n\n" \ "111 /o\n" \ "112 /p\n" \ "113 /q\n" \ "114 /r\n" \ "115 /s\n" \ "116 /t\n" \ "117 /u\n" \ "118 /v\n" \ "119 /w\n" \ "120 /x\n" \ "121 /y\n" \ "122 /z\n" \ "123 /braceleft\n" \ "124 /bar\n" \ "125 /braceright\n" \ "126 /asciitilde\n" \ "127 /.notdef\n" \ "128 /fraction\n" \ "129 /florin\n" \ "130 /quotesingle\n" \ "131 /quotedblleft\n" \ "132 /guilsinglleft\n" \ "133 /guilsinglright\n" \ "134 /fi\n" \ "135 /fl\n" \ "136 /endash\n" \ "137 /dagger\n" \ "138 /daggerdbl\n" \ "139 /bullet\n" \ "140 /quotesinglbase\n" \ "141 /quotedblbase\n" \ "142 /quotedblright\n" \ "143 /ellipsis\n" \ "144 /dotlessi\n" \ "145 /grave\n" \ "146 /acute\n" \ "147 /circumflex\n" \ "148 /tilde\n" \ "149 /oe\n" \ "150 /breve\n" \ "151 /dotaccent\n" \ "152 /perthousand\n" \ "153 /emdash\n" \ "154 /ring\n" \ "155 /Lslash\n" \ "156 /OE\n" \ "157 /hungarumlaut\n" \ "158 /ogonek\n" \ "159 /caron\n" \ "160 /lslash\n" \ "161 /exclamdown\n" \ "162 /cent\n" \ "163 /sterling\n" \ "164 /currency\n" \ "165 /yen\n" \ "166 /brokenbar\n" \ "167 /section\n" \ "168 /dieresis\n" \ "169 /copyright\n" \ "170 /ordfeminine\n" \ "171 /guillemotleft\n" \ "172 /logicalnot\n" \ "173 /hyphen\n" \ "174 /registered\n" \ "175 /macron\n" \ "176 /degree\n" \ "177 /plusminus\n" \ "178 /twosuperior\n" \ "179 /threesuperior\n" \ "180 /acute\n" \ "181 /mu\n" \ "182 /paragraph\n" \ "183 /periodcentered\n" \ "184 /cedilla\n" \ "185 /onesuperior\n" \ "186 /ordmasculine\n" \ "187 /guillemotright\n" \ "188 /onequarter\n" \ "189 /onehalf\n" \ "190 /threequarters\n" \ "191 /questiondown\n" \ "192 /Agrave\n" \ "193 /Aacute\n" \ "194 /Acircumflex\n" \ "195 /Atilde\n" \ "196 /Adieresis\n" \ "197 /Aring\n" \ "198 /AE\n" \ "199 /Ccedilla\n" \ "200 /Egrave\n" \ "201 /Eacute\n" \ "202 /Ecircumflex\n" \ "203 /Edieresis\n" \ "204 /Igrave\n" \ "205 /Iacute\n" \ "206 /Icircumflex\n" \ "207 /Idieresis\n" \ "208 /Eth\n" \ "209 /Ntilde\n" \ "210 /Ograve\n" \ "211 /Oacute\n" \ "212 /Ocircumflex\n" \ "213 /Otilde\n" \ "214 /Odieresis\n" \ "215 /multiply\n" \ "216 /Oslash\n" \ "217 /Ugrave\n" \ "218 /Uacute\n" \ "219 /Ucircumflex\n" \ "220 /Udieresis\n" \ "221 /Yacute\n" \ "222 /Thorn\n" \ "223 /germandbls\n" \ "224 /agrave\n" \ "225 /aacute\n" \ "226 /acircumflex\n" \ "227 /atilde\n" \ "228 /adieresis\n" \ "229 /aring\n" \ "230 /ae\n" \ "231 /ccedilla\n" \ "232 /egrave\n" \ "233 /eacute\n" \ "234 /ecircumflex\n" \ "235 /edieresis\n" \ "236 /igrave\n" \ "237 /iacute\n" \ "238 /icircumflex\n" \ "239 /idieresis\n" \ "240 /eth\n" \ "241 /ntilde\n" \ "242 /ograve\n" \ "243 /oacute\n" \ "244 /ocircumflex\n" \ "245 /otilde\n" \ "246 /odieresis\n" \ "247 /divide\n" \ "248 /oslash\n" \ "249 /ugrave\n" \ "250 /uacute\n" \ "251 /ucircumflex\n" \ "252 /udieresis\n" \ "253 /yacute\n" \ "254 /thorn\n" \ "255 /ydieresis\n" \ "] def" static void ps_list_tracks(void) { int i,s,y,sy; if (!b_record) return; printf("%%!PS-Adobe-2.0\n"); /* encoding tricks */ puts(ENCODING_TRICKS); printf("/Times /TimesLatin1 charvec ReEncodeSmall\n"); printf("/Helvetica /HelveticaLatin1 charvec ReEncodeSmall\n"); /* Spaces */ printf("0 setlinewidth\n"); printf(" 100 100 moveto\n"); printf(" 390 0 rlineto\n"); printf(" 0 330 rlineto\n"); printf("-390 0 rlineto\n"); printf("closepath stroke\n"); printf(" 100 100 moveto\n"); printf("-16 0 rlineto\n"); printf(" 0 330 rlineto\n"); printf("422 0 rlineto\n"); printf(" 0 -330 rlineto\n"); printf("closepath stroke\n"); /* Title */ printf("/TimesLatin1 findfont 24 scalefont setfont\n"); printf("120 400 moveto (%s) show\n", title); printf("/TimesLatin1 findfont 18 scalefont setfont\n"); printf("120 375 moveto (%s) show\n", artist); /* List */ sy = 250 / i_last_track; if (sy > 14) sy = 14; printf("/labelfont /TimesLatin1 findfont %d scalefont def\n",sy-2); printf("/timefont /Courier findfont %d scalefont def\n",sy-2); for (i = i_first_track, y = 350; i <= i_last_track; i++, y -= sy) { s = cdio_audio_get_msf_seconds(&toc[i+1]) - cdio_audio_get_msf_seconds(&toc[i]); printf("labelfont setfont\n"); printf("120 %d moveto (%d) show\n", y, i); { char line[200]=""; if ( strlen(cd_info[i].title) ) strcat(line, cd_info[i].title); if ( strlen(cd_info[i].artist) > 0 ) { if (strlen(cd_info[i].title)) strcat(line, " / "); strcat(line, cd_info[i].artist); } printf("150 %d moveto (%s) show\n", y, line); } printf("timefont setfont\n"); printf("420 %d moveto (%2d:%02d) show\n", y, s / CDIO_CD_SECS_PER_MIN, s % CDIO_CD_SECS_PER_MIN); } /* Seitenbanner */ printf("/HelveticaLatin1 findfont 12 scalefont setfont\n"); printf(" 97 105 moveto (%s: %s) 90 rotate show -90 rotate\n", artist, title); printf("493 425 moveto (%s: %s) -90 rotate show 90 rotate\n", artist, title); printf("showpage\n"); } static void list_tracks(void) { int i,s; if (!b_record) return; printf("Title : %s\n", title); printf("Artist: %s\n", artist); for (i = i_first_track; i <= i_last_track; i++) { s = cdio_audio_get_msf_seconds(&toc[i+1]) - cdio_audio_get_msf_seconds(&toc[i]); printf("%2d: %s [%d seconds]\n", i, cd_info[i].title, s); } } typedef enum { NO_OP=0, PLAY_CD=1, PLAY_TRACK=2, STOP_PLAYING=3, EJECT_CD=4, CLOSE_CD=5, SET_VOLUME=6, LIST_SUBCHANNEL=7, LIST_KEYS=8, LIST_TRACKS=9, PS_LIST_TRACKS=10, TOGGLE_PAUSE=11, EXIT_PROGRAM=12 } cd_operation_t; int main(int argc, char *argv[]) { int c, nostop=0; char *h; int i_rc = 0; cd_operation_t cd_op = NO_OP; /* operation to do in non-interactive mode */ psz_program = strrchr(argv[0],'/'); psz_program = psz_program ? psz_program+1 : argv[0]; memset(&cddb_opts, 0, sizeof(cddb_opts)); cdio_loglevel_default = CDIO_LOG_WARN; /* parse options */ while ( 1 ) { if (-1 == (c = getopt(argc, argv, "acCdehkplL:sSt:vx"))) break; switch (c) { case 'v': b_verbose = true; if (cdio_loglevel_default > CDIO_LOG_INFO) cdio_loglevel_default = CDIO_LOG_INFO; break; case 'd': debug = 1; if (cdio_loglevel_default > CDIO_LOG_DEBUG) cdio_loglevel_default = CDIO_LOG_DEBUG; break; case 'a': auto_mode = 1; break; case 'L': i_volume_level = atoi(optarg); cd_op = SET_VOLUME; b_interactive = false; break; case 't': if (NULL != (h = strchr(optarg,'-'))) { *h = 0; start_track = atoi(optarg); stop_track = atoi(h+1)+1; if (0 == start_track) start_track = 1; if (1 == stop_track) stop_track = CDIO_CDROM_LEADOUT_TRACK; } else { start_track = atoi(optarg); stop_track = start_track+1; one_track = 1; } b_interactive = false; cd_op = PLAY_TRACK; break; case 'p': b_interactive = false; cd_op = PLAY_CD; break; case 'l': b_interactive = false; cd_op = LIST_TRACKS; break; case 'C': b_interactive = false; cd_op = CLOSE_CD; break; case 'c': b_interactive = false; cd_op = PS_LIST_TRACKS; break; case 's': b_interactive = false; cd_op = STOP_PLAYING; break; case 'S': b_interactive = false; cd_op = LIST_SUBCHANNEL; break; case 'e': b_interactive = false; cd_op = EJECT_CD; break; case 'k': print_keys(); exit(1); case 'h': usage(psz_program); exit(1); default: usage(psz_program); exit(1); } } if (argc > optind) { psz_device = strdup(argv[optind]); } else { char **ppsz_cdda_drives=NULL; char **ppsz_all_cd_drives = cdio_get_devices_ret(&driver_id); if (!ppsz_all_cd_drives) { fprintf(stderr, "Can't find a CD-ROM drive\n"); exit(2); } ppsz_cdda_drives = cdio_get_devices_with_cap(ppsz_all_cd_drives, CDIO_FS_AUDIO, false); if (!ppsz_cdda_drives || !ppsz_cdda_drives[0]) { fprintf(stderr, "Can't find a CD-ROM drive with a CD-DA in it\n"); exit(3); } psz_device = strdup(ppsz_cdda_drives[0]); cdio_free_device_list(ppsz_all_cd_drives); cdio_free_device_list(ppsz_cdda_drives); } if (!b_interactive) { b_sig = true; nostop=1; } tty_raw(); signal(SIGINT,ctrlc); signal(SIGQUIT,ctrlc); signal(SIGTERM,ctrlc); signal(SIGHUP,ctrlc); signal(SIGWINCH, sigwinch); if (CLOSE_CD != cd_op) { /* open device */ if (b_verbose) fprintf(stderr, "open %s... ", psz_device); p_cdio = cdio_open (psz_device, driver_id); if (!p_cdio && cd_op != EJECT_CD) { cd_close(psz_device); p_cdio = cdio_open (psz_device, driver_id); } if (p_cdio && b_verbose) fprintf(stderr,"ok\n"); } if (b_interactive) { #ifdef HAVE_CDDB cddb_log_set_handler (cddb_log_handler); #else ; #endif } else { b_sig = true; nostop=1; if (EJECT_CD == cd_op) { i_rc = cd_eject() ? 0 : 1; } else { switch (cd_op) { case PS_LIST_TRACKS: case LIST_TRACKS: case PLAY_TRACK: read_toc(p_cdio); default: break; } if (p_cdio) switch (cd_op) { case STOP_PLAYING: b_cd = true; i_rc = cd_stop(p_cdio) ? 0 : 1; break; case EJECT_CD: /* Should have been handled above. */ cd_eject(); break; case LIST_TRACKS: list_tracks(); break; case PS_LIST_TRACKS: ps_list_tracks(); break; case PLAY_TRACK: /* play just this one track */ if (b_record) { printf("%s / %s\n", artist, title); if (one_track) printf("%s\n", cd_info[start_track].title); } i_rc = play_track(start_track, stop_track) ? 0 : 1; break; case PLAY_CD: if (b_record) printf("%s / %s\n", artist, title); play_track(1,CDIO_CDROM_LEADOUT_TRACK); break; case SET_VOLUME: i_rc = set_volume_level(p_cdio, i_volume_level); break; case LIST_SUBCHANNEL: if (read_subchannel(p_cdio)) { if (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) { { printf("track %2d - %02x:%02x (%02x:%02x abs) ", sub.track, sub.rel_addr.m, sub.rel_addr.s, sub.abs_addr.m, sub.abs_addr.s); } } printf("drive state: %s\n", mmc_audio_state2str(sub.audio_status)); } else { i_rc = 1; } break; case CLOSE_CD: /* Handled below */ case LIST_KEYS: case TOGGLE_PAUSE: case EXIT_PROGRAM: case NO_OP: break; } else if (CLOSE_CD == cd_op) { i_rc = (DRIVER_OP_SUCCESS == cdio_close_tray(psz_device, NULL)) ? 0 : 1; } else { fprintf(stderr,"no CD in drive (%s)\n", psz_device); } } } /* Play all tracks *unless* we have a play or paused status already. */ read_subchannel(p_cdio); if (sub.audio_status != CDIO_MMC_READ_SUB_ST_PAUSED && sub.audio_status != CDIO_MMC_READ_SUB_ST_PLAY) play_track(1, CDIO_CDROM_LEADOUT_TRACK); while ( !b_sig ) { int key; if (!b_cd) read_toc(p_cdio); read_subchannel(p_cdio); display_status(false); if (1 == select_wait(b_cd ? 1 : 5)) { switch (key = getch()) { case '-': decrease_volume_level(p_cdio); break; case '+': increase_volume_level(p_cdio); break; case 'A': case 'a': auto_mode = !auto_mode; break; case 'X': case 'x': nostop=1; /* fall through */ case 'Q': case 'q': b_sig = true; break; case 'E': case 'e': cd_eject(); break; case 's': cd_stop(p_cdio); break; case 'C': case 'c': cd_close(psz_device); break; case 'L': case 'l': b_all_tracks = !b_all_tracks; if (b_all_tracks) display_tracks(); else { i_last_display_track = CDIO_INVALID_TRACK; display_cdinfo(p_cdio, i_tracks, i_first_track); } break; case 'K': case 'k': case 'h': case 'H': case '?': list_keys(); break; case ' ': case 'P': case 'p': toggle_pause(); break; case KEY_RIGHT: if (b_cd && (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY)) play_track(sub.track+1, CDIO_CDROM_LEADOUT_TRACK); else play_track(1,CDIO_CDROM_LEADOUT_TRACK); break; case KEY_LEFT: if (b_cd && (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY)) play_track(sub.track-1,CDIO_CDROM_LEADOUT_TRACK); break; case KEY_UP: if (b_cd && sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) skip(10); break; case KEY_DOWN: if (b_cd && sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) skip(-10); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': play_track(key - '0', CDIO_CDROM_LEADOUT_TRACK); break; case '0': play_track(10, CDIO_CDROM_LEADOUT_TRACK); break; case KEY_F(1): case KEY_F(2): case KEY_F(3): case KEY_F(4): case KEY_F(5): case KEY_F(6): case KEY_F(7): case KEY_F(8): case KEY_F(9): case KEY_F(10): case KEY_F(11): case KEY_F(12): case KEY_F(13): case KEY_F(14): case KEY_F(15): case KEY_F(16): case KEY_F(17): case KEY_F(18): case KEY_F(19): case KEY_F(20): play_track(key - KEY_F(1) + 11, CDIO_CDROM_LEADOUT_TRACK); break; } } } if (!nostop) cd_stop(p_cdio); tty_restore(); finish("bye", i_rc); return 0; /* keep compiler happy */ }
gpl-3.0
ranqingfa/ardupilot
ArduCopter/Parameters.cpp
3
56519
#include "Copter.h" /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * ArduCopter parameter definitions * */ #define GSCALAR(v, name, def) { copter.g.v.vtype, name, Parameters::k_param_ ## v, &copter.g.v, {def_value : def} } #define ASCALAR(v, name, def) { copter.aparm.v.vtype, name, Parameters::k_param_ ## v, (const void *)&copter.aparm.v, {def_value : def} } #define GGROUP(v, name, class) { AP_PARAM_GROUP, name, Parameters::k_param_ ## v, &copter.g.v, {group_info : class::var_info} } #define GOBJECT(v, name, class) { AP_PARAM_GROUP, name, Parameters::k_param_ ## v, (const void *)&copter.v, {group_info : class::var_info} } #define GOBJECTPTR(v, name, class) { AP_PARAM_GROUP, name, Parameters::k_param_ ## v, (const void *)&copter.v, {group_info : class::var_info}, AP_PARAM_FLAG_POINTER } #define GOBJECTVARPTR(v, name, var_info_ptr) { AP_PARAM_GROUP, name, Parameters::k_param_ ## v, (const void *)&copter.v, {group_info_ptr : var_info_ptr}, AP_PARAM_FLAG_POINTER | AP_PARAM_FLAG_INFO_POINTER } #define GOBJECTN(v, pname, name, class) { AP_PARAM_GROUP, name, Parameters::k_param_ ## pname, (const void *)&copter.v, {group_info : class::var_info} } const AP_Param::Info Copter::var_info[] = { // @Param: SYSID_SW_MREV // @DisplayName: Eeprom format version number // @Description: This value is incremented when changes are made to the eeprom format // @User: Advanced // @ReadOnly: True GSCALAR(format_version, "SYSID_SW_MREV", 0), // @Param: SYSID_SW_TYPE // @DisplayName: Software Type // @Description: This is used by the ground station to recognise the software type (eg ArduPlane vs ArduCopter) // @Values: 0:ArduPlane,4:AntennaTracker,10:Copter,20:Rover,40:ArduSub // @User: Advanced // @ReadOnly: True GSCALAR(software_type, "SYSID_SW_TYPE", Parameters::k_software_type), // @Param: SYSID_THISMAV // @DisplayName: MAVLink system ID of this vehicle // @Description: Allows setting an individual MAVLink system id for this vehicle to distinguish it from others on the same network // @Range: 1 255 // @User: Advanced GSCALAR(sysid_this_mav, "SYSID_THISMAV", MAV_SYSTEM_ID), // @Param: SYSID_MYGCS // @DisplayName: My ground station number // @Description: Allows restricting radio overrides to only come from my ground station // @Values: 255:Mission Planner and DroidPlanner, 252: AP Planner 2 // @User: Advanced GSCALAR(sysid_my_gcs, "SYSID_MYGCS", 255), // @Param: PILOT_THR_FILT // @DisplayName: Throttle filter cutoff // @Description: Throttle filter cutoff (Hz) - active whenever altitude control is inactive - 0 to disable // @User: Advanced // @Units: Hz // @Range: 0 10 // @Increment: .5 GSCALAR(throttle_filt, "PILOT_THR_FILT", 0), // @Param: PILOT_TKOFF_ALT // @DisplayName: Pilot takeoff altitude // @Description: Altitude that altitude control modes will climb to when a takeoff is triggered with the throttle stick. // @User: Standard // @Units: cm // @Range: 0.0 1000.0 // @Increment: 10 GSCALAR(pilot_takeoff_alt, "PILOT_TKOFF_ALT", PILOT_TKOFF_ALT_DEFAULT), // @Param: PILOT_TKOFF_DZ // @DisplayName: Takeoff trigger deadzone // @Description: Offset from mid stick at which takeoff is triggered // @User: Standard // @Range: 0 500 // @Increment: 10 GSCALAR(takeoff_trigger_dz, "PILOT_TKOFF_DZ", THR_DZ_DEFAULT), // @Param: PILOT_THR_BHV // @DisplayName: Throttle stick behavior // @Description: Bitmask containing various throttle stick options. Add up the values for options that you want. // @User: Standard // @Values: 0:None,1:Feedback from mid stick,2:High throttle cancels landing,4:Disarm on land detection // @Bitmask: 0:Feedback from mid stick,1:High throttle cancels landing,2:Disarm on land detection GSCALAR(throttle_behavior, "PILOT_THR_BHV", 0), // @Group: SERIAL // @Path: ../libraries/AP_SerialManager/AP_SerialManager.cpp GOBJECT(serial_manager, "SERIAL", AP_SerialManager), // @Param: TELEM_DELAY // @DisplayName: Telemetry startup delay // @Description: The amount of time (in seconds) to delay radio telemetry to prevent an Xbee bricking on power up // @User: Advanced // @Units: s // @Range: 0 30 // @Increment: 1 GSCALAR(telem_delay, "TELEM_DELAY", 0), // @Param: GCS_PID_MASK // @DisplayName: GCS PID tuning mask // @Description: bitmask of PIDs to send MAVLink PID_TUNING messages for // @User: Advanced // @Values: 0:None,1:Roll,2:Pitch,4:Yaw // @Bitmask: 0:Roll,1:Pitch,2:Yaw GSCALAR(gcs_pid_mask, "GCS_PID_MASK", 0), // @Param: RTL_ALT // @DisplayName: RTL Altitude // @Description: The minimum relative altitude the model will move to before Returning to Launch. Set to zero to return at current altitude. // @Units: cm // @Range: 0 8000 // @Increment: 1 // @User: Standard GSCALAR(rtl_altitude, "RTL_ALT", RTL_ALT), // @Param: RTL_CONE_SLOPE // @DisplayName: RTL cone slope // @Description: Defines a cone above home which determines maximum climb // @Range: 0.5 10.0 // @Increment: .1 // @Values: 0:Disabled,1:Shallow,3:Steep // @User: Standard GSCALAR(rtl_cone_slope, "RTL_CONE_SLOPE", RTL_CONE_SLOPE_DEFAULT), // @Param: RTL_SPEED // @DisplayName: RTL speed // @Description: Defines the speed in cm/s which the aircraft will attempt to maintain horizontally while flying home. If this is set to zero, WPNAV_SPEED will be used instead. // @Units: cm/s // @Range: 0 2000 // @Increment: 50 // @User: Standard GSCALAR(rtl_speed_cms, "RTL_SPEED", 0), // @Param: RNGFND_GAIN // @DisplayName: Rangefinder gain // @Description: Used to adjust the speed with which the target altitude is changed when objects are sensed below the copter // @Range: 0.01 2.0 // @Increment: 0.01 // @User: Standard GSCALAR(rangefinder_gain, "RNGFND_GAIN", RANGEFINDER_GAIN_DEFAULT), // @Param: FS_BATT_ENABLE // @DisplayName: Battery Failsafe Enable // @Description: Controls whether failsafe will be invoked when battery voltage or current runs low // @Values: 0:Disabled,1:Land,2:RTL // @User: Standard GSCALAR(failsafe_battery_enabled, "FS_BATT_ENABLE", FS_BATT_DISABLED), // @Param: FS_BATT_VOLTAGE // @DisplayName: Failsafe battery voltage // @Description: Battery voltage to trigger failsafe. Set to 0 to disable battery voltage failsafe. If the battery voltage drops below this voltage then the copter will RTL // @Units: V // @Increment: 0.1 // @User: Standard GSCALAR(fs_batt_voltage, "FS_BATT_VOLTAGE", FS_BATT_VOLTAGE_DEFAULT), // @Param: FS_BATT_MAH // @DisplayName: Failsafe battery milliAmpHours // @Description: Battery capacity remaining to trigger failsafe. Set to 0 to disable battery remaining failsafe. If the battery remaining drops below this level then the copter will RTL // @Units: mA.h // @Increment: 50 // @User: Standard GSCALAR(fs_batt_mah, "FS_BATT_MAH", FS_BATT_MAH_DEFAULT), // @Param: FS_GCS_ENABLE // @DisplayName: Ground Station Failsafe Enable // @Description: Controls whether failsafe will be invoked (and what action to take) when connection with Ground station is lost for at least 5 seconds. NB. The GCS Failsafe is only active when RC_OVERRIDE is being used to control the vehicle. // @Values: 0:Disabled,1:Enabled always RTL,2:Enabled Continue with Mission in Auto Mode // @User: Standard GSCALAR(failsafe_gcs, "FS_GCS_ENABLE", FS_GCS_ENABLED_ALWAYS_RTL), // @Param: GPS_HDOP_GOOD // @DisplayName: GPS Hdop Good // @Description: GPS Hdop value at or below this value represent a good position. Used for pre-arm checks // @Range: 100 900 // @User: Advanced GSCALAR(gps_hdop_good, "GPS_HDOP_GOOD", GPS_HDOP_GOOD_DEFAULT), // @Param: MAG_ENABLE // @DisplayName: Compass enable/disable // @Description: Setting this to Enabled(1) will enable the compass. Setting this to Disabled(0) will disable the compass // @Values: 0:Disabled,1:Enabled // @User: Standard GSCALAR(compass_enabled, "MAG_ENABLE", MAGNETOMETER), // @Param: SUPER_SIMPLE // @DisplayName: Super Simple Mode // @Description: Bitmask to enable Super Simple mode for some flight modes. Setting this to Disabled(0) will disable Super Simple Mode // @Values: 0:Disabled,1:Mode1,2:Mode2,3:Mode1+2,4:Mode3,5:Mode1+3,6:Mode2+3,7:Mode1+2+3,8:Mode4,9:Mode1+4,10:Mode2+4,11:Mode1+2+4,12:Mode3+4,13:Mode1+3+4,14:Mode2+3+4,15:Mode1+2+3+4,16:Mode5,17:Mode1+5,18:Mode2+5,19:Mode1+2+5,20:Mode3+5,21:Mode1+3+5,22:Mode2+3+5,23:Mode1+2+3+5,24:Mode4+5,25:Mode1+4+5,26:Mode2+4+5,27:Mode1+2+4+5,28:Mode3+4+5,29:Mode1+3+4+5,30:Mode2+3+4+5,31:Mode1+2+3+4+5,32:Mode6,33:Mode1+6,34:Mode2+6,35:Mode1+2+6,36:Mode3+6,37:Mode1+3+6,38:Mode2+3+6,39:Mode1+2+3+6,40:Mode4+6,41:Mode1+4+6,42:Mode2+4+6,43:Mode1+2+4+6,44:Mode3+4+6,45:Mode1+3+4+6,46:Mode2+3+4+6,47:Mode1+2+3+4+6,48:Mode5+6,49:Mode1+5+6,50:Mode2+5+6,51:Mode1+2+5+6,52:Mode3+5+6,53:Mode1+3+5+6,54:Mode2+3+5+6,55:Mode1+2+3+5+6,56:Mode4+5+6,57:Mode1+4+5+6,58:Mode2+4+5+6,59:Mode1+2+4+5+6,60:Mode3+4+5+6,61:Mode1+3+4+5+6,62:Mode2+3+4+5+6,63:Mode1+2+3+4+5+6 // @User: Standard GSCALAR(super_simple, "SUPER_SIMPLE", 0), // @Param: RTL_ALT_FINAL // @DisplayName: RTL Final Altitude // @Description: This is the altitude the vehicle will move to as the final stage of Returning to Launch or after completing a mission. Set to zero to land. // @Units: cm // @Range: -1 1000 // @Increment: 1 // @User: Standard GSCALAR(rtl_alt_final, "RTL_ALT_FINAL", RTL_ALT_FINAL), // @Param: RTL_CLIMB_MIN // @DisplayName: RTL minimum climb // @Description: The vehicle will climb this many cm during the initial climb portion of the RTL // @Units: cm // @Range: 0 3000 // @Increment: 10 // @User: Standard GSCALAR(rtl_climb_min, "RTL_CLIMB_MIN", RTL_CLIMB_MIN_DEFAULT), // @Param: WP_YAW_BEHAVIOR // @DisplayName: Yaw behaviour during missions // @Description: Determines how the autopilot controls the yaw during missions and RTL // @Values: 0:Never change yaw, 1:Face next waypoint, 2:Face next waypoint except RTL, 3:Face along GPS course // @User: Standard GSCALAR(wp_yaw_behavior, "WP_YAW_BEHAVIOR", WP_YAW_BEHAVIOR_DEFAULT), // @Param: RTL_LOIT_TIME // @DisplayName: RTL loiter time // @Description: Time (in milliseconds) to loiter above home before beginning final descent // @Units: ms // @Range: 0 60000 // @Increment: 1000 // @User: Standard GSCALAR(rtl_loiter_time, "RTL_LOIT_TIME", RTL_LOITER_TIME), // @Param: LAND_SPEED // @DisplayName: Land speed // @Description: The descent speed for the final stage of landing in cm/s // @Units: cm/s // @Range: 30 200 // @Increment: 10 // @User: Standard GSCALAR(land_speed, "LAND_SPEED", LAND_SPEED), // @Param: LAND_SPEED_HIGH // @DisplayName: Land speed high // @Description: The descent speed for the first stage of landing in cm/s. If this is zero then WPNAV_SPEED_DN is used // @Units: cm/s // @Range: 0 500 // @Increment: 10 // @User: Standard GSCALAR(land_speed_high, "LAND_SPEED_HIGH", 0), // @Param: PILOT_SPEED_UP // @DisplayName: Pilot maximum vertical speed ascending // @Description: The maximum vertical ascending velocity the pilot may request in cm/s // @Units: cm/s // @Range: 50 500 // @Increment: 10 // @User: Standard GSCALAR(pilot_speed_up, "PILOT_SPEED_UP", PILOT_VELZ_MAX), // @Param: PILOT_ACCEL_Z // @DisplayName: Pilot vertical acceleration // @Description: The vertical acceleration used when pilot is controlling the altitude // @Units: cm/s/s // @Range: 50 500 // @Increment: 10 // @User: Standard GSCALAR(pilot_accel_z, "PILOT_ACCEL_Z", PILOT_ACCEL_Z_DEFAULT), // @Param: FS_THR_ENABLE // @DisplayName: Throttle Failsafe Enable // @Description: The throttle failsafe allows you to configure a software failsafe activated by a setting on the throttle input channel // @Values: 0:Disabled,1:Enabled always RTL,2:Enabled Continue with Mission in Auto Mode,3:Enabled always LAND // @User: Standard GSCALAR(failsafe_throttle, "FS_THR_ENABLE", FS_THR_ENABLED_ALWAYS_RTL), // @Param: FS_THR_VALUE // @DisplayName: Throttle Failsafe Value // @Description: The PWM level in microseconds on channel 3 below which throttle failsafe triggers // @Range: 925 1100 // @Units: PWM // @Increment: 1 // @User: Standard GSCALAR(failsafe_throttle_value, "FS_THR_VALUE", FS_THR_VALUE_DEFAULT), // @Param: THR_DZ // @DisplayName: Throttle deadzone // @Description: The deadzone above and below mid throttle in PWM microseconds. Used in AltHold, Loiter, PosHold flight modes // @User: Standard // @Range: 0 300 // @Units: PWM // @Increment: 1 GSCALAR(throttle_deadzone, "THR_DZ", THR_DZ_DEFAULT), // @Param: FLTMODE1 // @DisplayName: Flight Mode 1 // @Description: Flight mode when Channel 5 pwm is <= 1230 // @Values: 0:Stabilize,1:Acro,2:AltHold,3:Auto,4:Guided,5:Loiter,6:RTL,7:Circle,9:Land,11:Drift,13:Sport,14:Flip,15:AutoTune,16:PosHold,17:Brake,18:Throw,19:Avoid_ADSB,20:Guided_NoGPS,21:Smart_RTL // @User: Standard GSCALAR(flight_mode1, "FLTMODE1", FLIGHT_MODE_1), // @Param: FLTMODE2 // @DisplayName: Flight Mode 2 // @Description: Flight mode when Channel 5 pwm is >1230, <= 1360 // @Values: 0:Stabilize,1:Acro,2:AltHold,3:Auto,4:Guided,5:Loiter,6:RTL,7:Circle,9:Land,11:Drift,13:Sport,14:Flip,15:AutoTune,16:PosHold,17:Brake,18:Throw,19:Avoid_ADSB,20:Guided_NoGPS,21:Smart_RTL // @User: Standard GSCALAR(flight_mode2, "FLTMODE2", FLIGHT_MODE_2), // @Param: FLTMODE3 // @DisplayName: Flight Mode 3 // @Description: Flight mode when Channel 5 pwm is >1360, <= 1490 // @Values: 0:Stabilize,1:Acro,2:AltHold,3:Auto,4:Guided,5:Loiter,6:RTL,7:Circle,9:Land,11:Drift,13:Sport,14:Flip,15:AutoTune,16:PosHold,17:Brake,18:Throw,19:Avoid_ADSB,20:Guided_NoGPS,21:Smart_RTL // @User: Standard GSCALAR(flight_mode3, "FLTMODE3", FLIGHT_MODE_3), // @Param: FLTMODE4 // @DisplayName: Flight Mode 4 // @Description: Flight mode when Channel 5 pwm is >1490, <= 1620 // @Values: 0:Stabilize,1:Acro,2:AltHold,3:Auto,4:Guided,5:Loiter,6:RTL,7:Circle,9:Land,11:Drift,13:Sport,14:Flip,15:AutoTune,16:PosHold,17:Brake,18:Throw,19:Avoid_ADSB,20:Guided_NoGPS,21:Smart_RTL // @User: Standard GSCALAR(flight_mode4, "FLTMODE4", FLIGHT_MODE_4), // @Param: FLTMODE5 // @DisplayName: Flight Mode 5 // @Description: Flight mode when Channel 5 pwm is >1620, <= 1749 // @Values: 0:Stabilize,1:Acro,2:AltHold,3:Auto,4:Guided,5:Loiter,6:RTL,7:Circle,9:Land,11:Drift,13:Sport,14:Flip,15:AutoTune,16:PosHold,17:Brake,18:Throw,19:Avoid_ADSB,20:Guided_NoGPS,21:Smart_RTL // @User: Standard GSCALAR(flight_mode5, "FLTMODE5", FLIGHT_MODE_5), // @Param: FLTMODE6 // @DisplayName: Flight Mode 6 // @Description: Flight mode when Channel 5 pwm is >=1750 // @Values: 0:Stabilize,1:Acro,2:AltHold,3:Auto,4:Guided,5:Loiter,6:RTL,7:Circle,9:Land,11:Drift,13:Sport,14:Flip,15:AutoTune,16:PosHold,17:Brake,18:Throw,19:Avoid_ADSB,20:Guided_NoGPS,21:Smart_RTL // @User: Standard GSCALAR(flight_mode6, "FLTMODE6", FLIGHT_MODE_6), // @Param: SIMPLE // @DisplayName: Simple mode bitmask // @Description: Bitmask which holds which flight modes use simple heading mode (eg bit 0 = 1 means Flight Mode 0 uses simple mode) // @User: Advanced GSCALAR(simple_modes, "SIMPLE", 0), // @Param: LOG_BITMASK // @DisplayName: Log bitmask // @Description: 4 byte bitmap of log types to enable // @Values: 830:Default,894:Default+RCIN,958:Default+IMU,1854:Default+Motors,-6146:NearlyAll-AC315,45054:NearlyAll,131071:All+FastATT,262142:All+MotBatt,393214:All+FastIMU,397310:All+FastIMU+PID,655358:All+FullIMU,0:Disabled // @Bitmask: 0:ATTITUDE_FAST,1:ATTITUDE_MED,2:GPS,3:PM,4:CTUN,5:NTUN,6:RCIN,7:IMU,8:CMD,9:CURRENT,10:RCOUT,11:OPTFLOW,12:PID,13:COMPASS,14:INAV,15:CAMERA,17:MOTBATT,18:IMU_FAST,19:IMU_RAW // @User: Standard GSCALAR(log_bitmask, "LOG_BITMASK", DEFAULT_LOG_BITMASK), // @Param: ESC_CALIBRATION // @DisplayName: ESC Calibration // @Description: Controls whether ArduCopter will enter ESC calibration on the next restart. Do not adjust this parameter manually. // @User: Advanced // @Values: 0:Normal Start-up, 1:Start-up in ESC Calibration mode if throttle high, 2:Start-up in ESC Calibration mode regardless of throttle, 3:Start-up and automatically calibrate ESCs, 9:Disabled GSCALAR(esc_calibrate, "ESC_CALIBRATION", 0), // @Param: TUNE // @DisplayName: Channel 6 Tuning // @Description: Controls which parameters (normally PID gains) are being tuned with transmitter's channel 6 knob // @User: Standard // @Values: 0:None,1:Stab Roll/Pitch kP,4:Rate Roll/Pitch kP,5:Rate Roll/Pitch kI,21:Rate Roll/Pitch kD,3:Stab Yaw kP,6:Rate Yaw kP,26:Rate Yaw kD,56:Rate Yaw Filter,55:Motor Yaw Headroom,14:AltHold kP,7:Throttle Rate kP,34:Throttle Accel kP,35:Throttle Accel kI,36:Throttle Accel kD,12:Loiter Pos kP,22:Velocity XY kP,28:Velocity XY kI,10:WP Speed,25:Acro RollPitch kP,40:Acro Yaw kP,45:RC Feel,13:Heli Ext Gyro,38:Declination,39:Circle Rate,41:RangeFinder Gain,46:Rate Pitch kP,47:Rate Pitch kI,48:Rate Pitch kD,49:Rate Roll kP,50:Rate Roll kI,51:Rate Roll kD,52:Rate Pitch FF,53:Rate Roll FF,54:Rate Yaw FF,57:Winch GSCALAR(radio_tuning, "TUNE", 0), // @Param: TUNE_LOW // @DisplayName: Tuning minimum // @Description: The minimum value that will be applied to the parameter currently being tuned with the transmitter's channel 6 knob // @User: Standard // @Range: 0 32767 GSCALAR(radio_tuning_low, "TUNE_LOW", 0), // @Param: TUNE_HIGH // @DisplayName: Tuning maximum // @Description: The maximum value that will be applied to the parameter currently being tuned with the transmitter's channel 6 knob // @User: Standard // @Range: 0 32767 GSCALAR(radio_tuning_high, "TUNE_HIGH", 1000), // @Param: FRAME_TYPE // @DisplayName: Frame Type (+, X, V, etc) // @Description: Controls motor mixing for multicopters. Not used for Tri or Traditional Helicopters. // @Values: 0:Plus, 1:X, 2:V, 3:H, 4:V-Tail, 5:A-Tail, 10:Y6B // @User: Standard // @RebootRequired: True GSCALAR(frame_type, "FRAME_TYPE", AP_Motors::MOTOR_FRAME_TYPE_X), // @Param: CH7_OPT // @DisplayName: Channel 7 option // @Description: Select which function is performed when CH7 is above 1800 pwm // @Values: 0:Do Nothing, 2:Flip, 3:Simple Mode, 4:RTL, 5:Save Trim, 7:Save WP, 9:Camera Trigger, 10:RangeFinder, 11:Fence, 13:Super Simple Mode, 14:Acro Trainer, 15:Sprayer, 16:Auto, 17:AutoTune, 18:Land, 19:Gripper, 21:Parachute Enable, 22:Parachute Release, 23:Parachute 3pos, 24:Auto Mission Reset, 25:AttCon Feed Forward, 26:AttCon Accel Limits, 27:Retract Mount, 28:Relay On/Off, 34:Relay2 On/Off, 35:Relay3 On/Off, 36:Relay4 On/Off, 29:Landing Gear, 30:Lost Copter Sound, 31:Motor Emergency Stop, 32:Motor Interlock, 33:Brake, 37:Throw, 38:ADSB-Avoidance, 39:PrecLoiter, 40:Object Avoidance, 41:ArmDisarm, 42:SmartRTL, 43:InvertedFlight, 44:Winch Enable, 45:WinchControl // @User: Standard GSCALAR(ch7_option, "CH7_OPT", AUXSW_DO_NOTHING), // @Param: CH8_OPT // @DisplayName: Channel 8 option // @Description: Select which function is performed when CH8 is above 1800 pwm // @Values: 0:Do Nothing, 2:Flip, 3:Simple Mode, 4:RTL, 5:Save Trim, 7:Save WP, 9:Camera Trigger, 10:RangeFinder, 11:Fence, 13:Super Simple Mode, 14:Acro Trainer, 15:Sprayer, 16:Auto, 17:AutoTune, 18:Land, 19:Gripper, 21:Parachute Enable, 22:Parachute Release, 23:Parachute 3pos, 24:Auto Mission Reset, 25:AttCon Feed Forward, 26:AttCon Accel Limits, 27:Retract Mount, 28:Relay On/Off, 34:Relay2 On/Off, 35:Relay3 On/Off, 36:Relay4 On/Off, 29:Landing Gear, 30:Lost Copter Sound, 31:Motor Emergency Stop, 32:Motor Interlock, 33:Brake, 37:Throw, 38:ADSB-Avoidance, 39:PrecLoiter, 40:Object Avoidance, 41:ArmDisarm, 42:SmartRTL, 43:InvertedFlight, 44:Winch Enable, 45:WinchControl // @User: Standard GSCALAR(ch8_option, "CH8_OPT", AUXSW_DO_NOTHING), // @Param: CH9_OPT // @DisplayName: Channel 9 option // @Description: Select which function is performed when CH9 is above 1800 pwm // @Values: 0:Do Nothing, 2:Flip, 3:Simple Mode, 4:RTL, 5:Save Trim, 7:Save WP, 9:Camera Trigger, 10:RangeFinder, 11:Fence, 13:Super Simple Mode, 14:Acro Trainer, 15:Sprayer, 16:Auto, 17:AutoTune, 18:Land, 19:Gripper, 21:Parachute Enable, 22:Parachute Release, 23:Parachute 3pos, 24:Auto Mission Reset, 25:AttCon Feed Forward, 26:AttCon Accel Limits, 27:Retract Mount, 28:Relay On/Off, 34:Relay2 On/Off, 35:Relay3 On/Off, 36:Relay4 On/Off, 29:Landing Gear, 30:Lost Copter Sound, 31:Motor Emergency Stop, 32:Motor Interlock, 33:Brake, 37:Throw, 38:ADSB-Avoidance, 39:PrecLoiter, 40:Object Avoidance, 41:ArmDisarm, 42:SmartRTL, 43:InvertedFlight, 44:Winch Enable, 45:WinchControl // @User: Standard GSCALAR(ch9_option, "CH9_OPT", AUXSW_DO_NOTHING), // @Param: CH10_OPT // @DisplayName: Channel 10 option // @Description: Select which function is performed when CH10 is above 1800 pwm // @Values: 0:Do Nothing, 2:Flip, 3:Simple Mode, 4:RTL, 5:Save Trim, 7:Save WP, 9:Camera Trigger, 10:RangeFinder, 11:Fence, 13:Super Simple Mode, 14:Acro Trainer, 15:Sprayer, 16:Auto, 17:AutoTune, 18:Land, 19:Gripper, 21:Parachute Enable, 22:Parachute Release, 23:Parachute 3pos, 24:Auto Mission Reset, 25:AttCon Feed Forward, 26:AttCon Accel Limits, 27:Retract Mount, 28:Relay On/Off, 34:Relay2 On/Off, 35:Relay3 On/Off, 36:Relay4 On/Off, 29:Landing Gear, 30:Lost Copter Sound, 31:Motor Emergency Stop, 32:Motor Interlock, 33:Brake, 37:Throw, 38:ADSB-Avoidance, 39:PrecLoiter, 40:Object Avoidance, 41:ArmDisarm, 42:SmartRTL, 43:InvertedFlight, 44:Winch Enable, 45:WinchControl // @User: Standard GSCALAR(ch10_option, "CH10_OPT", AUXSW_DO_NOTHING), // @Param: CH11_OPT // @DisplayName: Channel 11 option // @Description: Select which function is performed when CH11 is above 1800 pwm // @Values: 0:Do Nothing, 2:Flip, 3:Simple Mode, 4:RTL, 5:Save Trim, 7:Save WP, 9:Camera Trigger, 10:RangeFinder, 11:Fence, 13:Super Simple Mode, 14:Acro Trainer, 15:Sprayer, 16:Auto, 17:AutoTune, 18:Land, 19:Gripper, 21:Parachute Enable, 22:Parachute Release, 23:Parachute 3pos, 24:Auto Mission Reset, 25:AttCon Feed Forward, 26:AttCon Accel Limits, 27:Retract Mount, 28:Relay On/Off, 34:Relay2 On/Off, 35:Relay3 On/Off, 36:Relay4 On/Off, 29:Landing Gear, 30:Lost Copter Sound, 31:Motor Emergency Stop, 32:Motor Interlock, 33:Brake, 37:Throw, 38:ADSB-Avoidance, 39:PrecLoiter, 40:Object Avoidance, 41:ArmDisarm, 42:SmartRTL, 43:InvertedFlight, 44:Winch Enable, 45:WinchControl // @User: Standard GSCALAR(ch11_option, "CH11_OPT", AUXSW_DO_NOTHING), // @Param: CH12_OPT // @DisplayName: Channel 12 option // @Description: Select which function is performed when CH12 is above 1800 pwm // @Values: 0:Do Nothing, 2:Flip, 3:Simple Mode, 4:RTL, 5:Save Trim, 7:Save WP, 9:Camera Trigger, 10:RangeFinder, 11:Fence, 13:Super Simple Mode, 14:Acro Trainer, 15:Sprayer, 16:Auto, 17:AutoTune, 18:Land, 19:Gripper, 21:Parachute Enable, 22:Parachute Release, 23:Parachute 3pos, 24:Auto Mission Reset, 25:AttCon Feed Forward, 26:AttCon Accel Limits, 27:Retract Mount, 28:Relay On/Off, 34:Relay2 On/Off, 35:Relay3 On/Off, 36:Relay4 On/Off, 29:Landing Gear, 30:Lost Copter Sound, 31:Motor Emergency Stop, 32:Motor Interlock, 33:Brake, 37:Throw, 38:ADSB-Avoidance, 39:PrecLoiter, 40:Object Avoidance, 41:ArmDisarm, 42:SmartRTL, 43:InvertedFlight, 44:Winch Enable, 45:WinchControl // @User: Standard GSCALAR(ch12_option, "CH12_OPT", AUXSW_DO_NOTHING), // @Group: ARMING_ // @Path: ../libraries/AP_Arming/AP_Arming.cpp GOBJECT(arming, "ARMING_", AP_Arming_Copter), // @Param: DISARM_DELAY // @DisplayName: Disarm delay // @Description: Delay before automatic disarm in seconds. A value of zero disables auto disarm. // @Units: s // @Range: 0 127 // @User: Advanced GSCALAR(disarm_delay, "DISARM_DELAY", AUTO_DISARMING_DELAY), // @Param: ANGLE_MAX // @DisplayName: Angle Max // @Description: Maximum lean angle in all flight modes // @Units: cdeg // @Range: 1000 8000 // @User: Advanced ASCALAR(angle_max, "ANGLE_MAX", DEFAULT_ANGLE_MAX), // @Param: RC_FEEL_RP // @DisplayName: RC Feel Roll/Pitch // @Description: RC feel for roll/pitch which controls vehicle response to user input with 0 being extremely soft and 100 being crisp // @Range: 0 100 // @Increment: 10 // @User: Standard // @Values: 0:Very Soft, 25:Soft, 50:Medium, 75:Crisp, 100:Very Crisp GSCALAR(rc_feel_rp, "RC_FEEL_RP", RC_FEEL_RP_MEDIUM), // @Param: PHLD_BRAKE_RATE // @DisplayName: PosHold braking rate // @Description: PosHold flight mode's rotation rate during braking in deg/sec // @Units: deg/s // @Range: 4 12 // @User: Advanced GSCALAR(poshold_brake_rate, "PHLD_BRAKE_RATE", POSHOLD_BRAKE_RATE_DEFAULT), // @Param: PHLD_BRAKE_ANGLE // @DisplayName: PosHold braking angle max // @Description: PosHold flight mode's max lean angle during braking in centi-degrees // @Units: cdeg // @Range: 2000 4500 // @User: Advanced GSCALAR(poshold_brake_angle_max, "PHLD_BRAKE_ANGLE", POSHOLD_BRAKE_ANGLE_DEFAULT), // @Param: LAND_REPOSITION // @DisplayName: Land repositioning // @Description: Enables user input during LAND mode, the landing phase of RTL, and auto mode landings. // @Values: 0:No repositioning, 1:Repositioning // @User: Advanced GSCALAR(land_repositioning, "LAND_REPOSITION", LAND_REPOSITION_DEFAULT), // @Param: FS_EKF_ACTION // @DisplayName: EKF Failsafe Action // @Description: Controls the action that will be taken when an EKF failsafe is invoked // @Values: 1:Land, 2:AltHold, 3:Land even in Stabilize // @User: Advanced GSCALAR(fs_ekf_action, "FS_EKF_ACTION", FS_EKF_ACTION_DEFAULT), // @Param: FS_EKF_THRESH // @DisplayName: EKF failsafe variance threshold // @Description: Allows setting the maximum acceptable compass and velocity variance // @Values: 0.6:Strict, 0.8:Default, 1.0:Relaxed // @User: Advanced GSCALAR(fs_ekf_thresh, "FS_EKF_THRESH", FS_EKF_THRESHOLD_DEFAULT), // @Param: FS_CRASH_CHECK // @DisplayName: Crash check enable // @Description: This enables automatic crash checking. When enabled the motors will disarm if a crash is detected. // @Values: 0:Disabled, 1:Enabled // @User: Advanced GSCALAR(fs_crash_check, "FS_CRASH_CHECK", 1), // @Param: RC_SPEED // @DisplayName: ESC Update Speed // @Description: This is the speed in Hertz that your ESCs will receive updates // @Units: Hz // @Range: 50 490 // @Increment: 1 // @User: Advanced GSCALAR(rc_speed, "RC_SPEED", RC_FAST_SPEED), // @Param: ACRO_RP_P // @DisplayName: Acro Roll and Pitch P gain // @Description: Converts pilot roll and pitch into a desired rate of rotation in ACRO and SPORT mode. Higher values mean faster rate of rotation. // @Range: 1 10 // @User: Standard GSCALAR(acro_rp_p, "ACRO_RP_P", ACRO_RP_P), // @Param: ACRO_YAW_P // @DisplayName: Acro Yaw P gain // @Description: Converts pilot yaw input into a desired rate of rotation in ACRO, Stabilize and SPORT modes. Higher values mean faster rate of rotation. // @Range: 1 10 // @User: Standard GSCALAR(acro_yaw_p, "ACRO_YAW_P", ACRO_YAW_P), // @Param: ACRO_BAL_ROLL // @DisplayName: Acro Balance Roll // @Description: rate at which roll angle returns to level in acro mode. A higher value causes the vehicle to return to level faster. // @Range: 0 3 // @Increment: 0.1 // @User: Advanced GSCALAR(acro_balance_roll, "ACRO_BAL_ROLL", ACRO_BALANCE_ROLL), // @Param: ACRO_BAL_PITCH // @DisplayName: Acro Balance Pitch // @Description: rate at which pitch angle returns to level in acro mode. A higher value causes the vehicle to return to level faster. // @Range: 0 3 // @Increment: 0.1 // @User: Advanced GSCALAR(acro_balance_pitch, "ACRO_BAL_PITCH", ACRO_BALANCE_PITCH), // @Param: ACRO_TRAINER // @DisplayName: Acro Trainer // @Description: Type of trainer used in acro mode // @Values: 0:Disabled,1:Leveling,2:Leveling and Limited // @User: Advanced GSCALAR(acro_trainer, "ACRO_TRAINER", ACRO_TRAINER_LIMITED), // @Param: ACRO_RP_EXPO // @DisplayName: Acro Roll/Pitch Expo // @Description: Acro roll/pitch Expo to allow faster rotation when stick at edges // @Values: 0:Disabled,0.1:Very Low,0.2:Low,0.3:Medium,0.4:High,0.5:Very High // @Range: -0.5 1.0 // @User: Advanced GSCALAR(acro_rp_expo, "ACRO_RP_EXPO", ACRO_RP_EXPO_DEFAULT), // @Param: VEL_XY_P // @DisplayName: Velocity (horizontal) P gain // @Description: Velocity (horizontal) P gain. Converts the difference between desired velocity to a target acceleration // @Range: 0.1 6.0 // @Increment: 0.1 // @User: Advanced // @Param: VEL_XY_I // @DisplayName: Velocity (horizontal) I gain // @Description: Velocity (horizontal) I gain. Corrects long-term difference in desired velocity to a target acceleration // @Range: 0.02 1.00 // @Increment: 0.01 // @User: Advanced // @Param: VEL_XY_IMAX // @DisplayName: Velocity (horizontal) integrator maximum // @Description: Velocity (horizontal) integrator maximum. Constrains the target acceleration that the I gain will output // @Range: 0 4500 // @Increment: 10 // @Units: cm/s/s // @User: Advanced GGROUP(pi_vel_xy, "VEL_XY_", AC_PI_2D), // @Param: VEL_Z_P // @DisplayName: Velocity (vertical) P gain // @Description: Velocity (vertical) P gain. Converts the difference between desired vertical speed and actual speed into a desired acceleration that is passed to the throttle acceleration controller // @Range: 1.000 8.000 // @User: Standard GGROUP(p_vel_z, "VEL_Z_", AC_P), // @Param: ACCEL_Z_P // @DisplayName: Throttle acceleration controller P gain // @Description: Throttle acceleration controller P gain. Converts the difference between desired vertical acceleration and actual acceleration into a motor output // @Range: 0.500 1.500 // @Increment: 0.05 // @User: Standard // @Param: ACCEL_Z_I // @DisplayName: Throttle acceleration controller I gain // @Description: Throttle acceleration controller I gain. Corrects long-term difference in desired vertical acceleration and actual acceleration // @Range: 0.000 3.000 // @User: Standard // @Param: ACCEL_Z_IMAX // @DisplayName: Throttle acceleration controller I gain maximum // @Description: Throttle acceleration controller I gain maximum. Constrains the maximum pwm that the I term will generate // @Range: 0 1000 // @Units: d% // @User: Standard // @Param: ACCEL_Z_D // @DisplayName: Throttle acceleration controller D gain // @Description: Throttle acceleration controller D gain. Compensates for short-term change in desired vertical acceleration vs actual acceleration // @Range: 0.000 0.400 // @User: Standard // @Param: ACCEL_Z_FILT // @DisplayName: Throttle acceleration filter // @Description: Filter applied to acceleration to reduce noise. Lower values reduce noise but add delay. // @Range: 1.000 100.000 // @Units: Hz // @User: Standard GGROUP(pid_accel_z, "ACCEL_Z_", AC_PID), // @Param: POS_Z_P // @DisplayName: Position (vertical) controller P gain // @Description: Position (vertical) controller P gain. Converts the difference between the desired altitude and actual altitude into a climb or descent rate which is passed to the throttle rate controller // @Range: 1.000 3.000 // @User: Standard GGROUP(p_alt_hold, "POS_Z_", AC_P), // @Param: POS_XY_P // @DisplayName: Position (horizonal) controller P gain // @Description: Loiter position controller P gain. Converts the distance (in the latitude direction) to the target location into a desired speed which is then passed to the loiter latitude rate controller // @Range: 0.500 2.000 // @User: Standard GGROUP(p_pos_xy, "POS_XY_", AC_P), // variables not in the g class which contain EEPROM saved variables #if CAMERA == ENABLED // @Group: CAM_ // @Path: ../libraries/AP_Camera/AP_Camera.cpp GOBJECT(camera, "CAM_", AP_Camera), #endif // @Group: RELAY_ // @Path: ../libraries/AP_Relay/AP_Relay.cpp GOBJECT(relay, "RELAY_", AP_Relay), #if PARACHUTE == ENABLED // @Group: CHUTE_ // @Path: ../libraries/AP_Parachute/AP_Parachute.cpp GOBJECT(parachute, "CHUTE_", AP_Parachute), #endif // @Group: LGR_ // @Path: ../libraries/AP_LandingGear/AP_LandingGear.cpp GOBJECT(landinggear, "LGR_", AP_LandingGear), #if FRAME_CONFIG == HELI_FRAME // @Group: IM_ // @Path: ../libraries/AC_InputManager/AC_InputManager_Heli.cpp GOBJECT(input_manager, "IM_", AC_InputManager_Heli), #endif // @Group: COMPASS_ // @Path: ../libraries/AP_Compass/AP_Compass.cpp GOBJECT(compass, "COMPASS_", Compass), // @Group: INS_ // @Path: ../libraries/AP_InertialSensor/AP_InertialSensor.cpp GOBJECT(ins, "INS_", AP_InertialSensor), // @Group: WPNAV_ // @Path: ../libraries/AC_WPNav/AC_WPNav.cpp GOBJECTPTR(wp_nav, "WPNAV_", AC_WPNav), // @Group: CIRCLE_ // @Path: ../libraries/AC_WPNav/AC_Circle.cpp GOBJECTPTR(circle_nav, "CIRCLE_", AC_Circle), // @Group: ATC_ // @Path: ../libraries/AC_AttitudeControl/AC_AttitudeControl.cpp,../libraries/AC_AttitudeControl/AC_AttitudeControl_Multi.cpp,../libraries/AC_AttitudeControl/AC_AttitudeControl_Heli.cpp #if FRAME_CONFIG == HELI_FRAME GOBJECTPTR(attitude_control, "ATC_", AC_AttitudeControl_Heli), #else GOBJECTPTR(attitude_control, "ATC_", AC_AttitudeControl_Multi), #endif // @Group: PSC // @Path: ../libraries/AC_AttitudeControl/AC_PosControl.cpp GOBJECTPTR(pos_control, "PSC", AC_PosControl), // @Group: SR0_ // @Path: GCS_Mavlink.cpp GOBJECTN(_gcs._chan[0], gcs0, "SR0_", GCS_MAVLINK), // @Group: SR1_ // @Path: GCS_Mavlink.cpp GOBJECTN(_gcs._chan[1], gcs1, "SR1_", GCS_MAVLINK), // @Group: SR2_ // @Path: GCS_Mavlink.cpp GOBJECTN(_gcs._chan[2], gcs2, "SR2_", GCS_MAVLINK), // @Group: SR3_ // @Path: GCS_Mavlink.cpp GOBJECTN(_gcs._chan[3], gcs3, "SR3_", GCS_MAVLINK), // @Group: AHRS_ // @Path: ../libraries/AP_AHRS/AP_AHRS.cpp GOBJECT(ahrs, "AHRS_", AP_AHRS), #if MOUNT == ENABLED // @Group: MNT // @Path: ../libraries/AP_Mount/AP_Mount.cpp GOBJECT(camera_mount, "MNT", AP_Mount), #endif // @Group: LOG // @Path: ../libraries/DataFlash/DataFlash.cpp GOBJECT(DataFlash, "LOG", DataFlash_Class), // @Group: BATT // @Path: ../libraries/AP_BattMonitor/AP_BattMonitor.cpp GOBJECT(battery, "BATT", AP_BattMonitor), // @Group: BRD_ // @Path: ../libraries/AP_BoardConfig/AP_BoardConfig.cpp GOBJECT(BoardConfig, "BRD_", AP_BoardConfig), #if HAL_WITH_UAVCAN // @Group: CAN_ // @Path: ../libraries/AP_BoardConfig/AP_BoardConfig_CAN.cpp GOBJECT(BoardConfig_CAN, "CAN_", AP_BoardConfig_CAN), #endif #if SPRAYER == ENABLED // @Group: SPRAY_ // @Path: ../libraries/AC_Sprayer/AC_Sprayer.cpp GOBJECT(sprayer, "SPRAY_", AC_Sprayer), #endif #if CONFIG_HAL_BOARD == HAL_BOARD_SITL GOBJECT(sitl, "SIM_", SITL::SITL), #endif // @Group: GND_ // @Path: ../libraries/AP_Baro/AP_Baro.cpp GOBJECT(barometer, "GND_", AP_Baro), // GPS driver // @Group: GPS_ // @Path: ../libraries/AP_GPS/AP_GPS.cpp GOBJECT(gps, "GPS_", AP_GPS), // @Group: SCHED_ // @Path: ../libraries/AP_Scheduler/AP_Scheduler.cpp GOBJECT(scheduler, "SCHED_", AP_Scheduler), #if AC_FENCE == ENABLED // @Group: FENCE_ // @Path: ../libraries/AC_Fence/AC_Fence.cpp GOBJECT(fence, "FENCE_", AC_Fence), #endif // @Group: AVOID_ // @Path: ../libraries/AC_Avoidance/AC_Avoid.cpp #if AC_AVOID_ENABLED == ENABLED GOBJECT(avoid, "AVOID_", AC_Avoid), #endif #if AC_RALLY == ENABLED // @Group: RALLY_ // @Path: AP_Rally.cpp,../libraries/AP_Rally/AP_Rally.cpp GOBJECT(rally, "RALLY_", AP_Rally_Copter), #endif #if FRAME_CONFIG == HELI_FRAME // @Group: H_ // @Path: ../libraries/AP_Motors/AP_MotorsHeli_Single.cpp,../libraries/AP_Motors/AP_MotorsHeli_Dual.cpp,../libraries/AP_Motors/AP_MotorsHeli.cpp GOBJECTVARPTR(motors, "H_", &copter.motors_var_info), #else // @Group: MOT_ // @Path: ../libraries/AP_Motors/AP_MotorsMulticopter.cpp GOBJECTVARPTR(motors, "MOT_", &copter.motors_var_info), #endif // @Group: RCMAP_ // @Path: ../libraries/AP_RCMapper/AP_RCMapper.cpp GOBJECT(rcmap, "RCMAP_", RCMapper), // @Group: EK2_ // @Path: ../libraries/AP_NavEKF2/AP_NavEKF2.cpp GOBJECTN(EKF2, NavEKF2, "EK2_", NavEKF2), // @Group: EK3_ // @Path: ../libraries/AP_NavEKF3/AP_NavEKF3.cpp GOBJECTN(EKF3, NavEKF3, "EK3_", NavEKF3), // @Group: MIS_ // @Path: ../libraries/AP_Mission/AP_Mission.cpp GOBJECT(mission, "MIS_", AP_Mission), // @Group: RSSI_ // @Path: ../libraries/AP_RSSI/AP_RSSI.cpp GOBJECT(rssi, "RSSI_", AP_RSSI), #if RANGEFINDER_ENABLED == ENABLED // @Group: RNGFND // @Path: ../libraries/AP_RangeFinder/RangeFinder.cpp GOBJECT(rangefinder, "RNGFND", RangeFinder), #endif #if AP_TERRAIN_AVAILABLE && AC_TERRAIN // @Group: TERRAIN_ // @Path: ../libraries/AP_Terrain/AP_Terrain.cpp GOBJECT(terrain, "TERRAIN_", AP_Terrain), #endif #if OPTFLOW == ENABLED // @Group: FLOW // @Path: ../libraries/AP_OpticalFlow/OpticalFlow.cpp GOBJECT(optflow, "FLOW", OpticalFlow), #endif #if PRECISION_LANDING == ENABLED // @Group: PLND_ // @Path: ../libraries/AC_PrecLand/AC_PrecLand.cpp GOBJECT(precland, "PLND_", AC_PrecLand), #endif // @Group: RPM // @Path: ../libraries/AP_RPM/AP_RPM.cpp GOBJECT(rpm_sensor, "RPM", AP_RPM), // @Group: ADSB_ // @Path: ../libraries/AP_ADSB/AP_ADSB.cpp GOBJECT(adsb, "ADSB_", AP_ADSB), // @Group: AVD_ // @Path: ../libraries/AP_Avoidance/AP_Avoidance.cpp GOBJECT(avoidance_adsb, "AVD_", AP_Avoidance_Copter), // @Param: AUTOTUNE_AXES // @DisplayName: Autotune axis bitmask // @Description: 1-byte bitmap of axes to autotune // @Values: 7:All,1:Roll Only,2:Pitch Only,4:Yaw Only,3:Roll and Pitch,5:Roll and Yaw,6:Pitch and Yaw // @Bitmask: 0:Roll,1:Pitch,2:Yaw // @User: Standard GSCALAR(autotune_axis_bitmask, "AUTOTUNE_AXES", 7), // AUTOTUNE_AXIS_BITMASK_DEFAULT // @Param: AUTOTUNE_AGGR // @DisplayName: Autotune aggressiveness // @Description: Autotune aggressiveness. Defines the bounce back used to detect size of the D term. // @Range: 0.05 0.10 // @User: Standard GSCALAR(autotune_aggressiveness, "AUTOTUNE_AGGR", 0.1f), // @Param: AUTOTUNE_MIN_D // @DisplayName: AutoTune minimum D // @Description: Defines the minimum D gain // @Range: 0.001 0.006 // @User: Standard GSCALAR(autotune_min_d, "AUTOTUNE_MIN_D", 0.001f), // @Group: NTF_ // @Path: ../libraries/AP_Notify/AP_Notify.cpp GOBJECT(notify, "NTF_", AP_Notify), // @Param: THROW_MOT_START // @DisplayName: Start motors before throwing is detected // @Description: Used by THROW mode. Controls whether motors will run at the speed set by THR_MIN or will be stopped when armed and waiting for the throw. // @Values: 0:Stopped,1:Running // @User: Standard GSCALAR(throw_motor_start, "THROW_MOT_START", 0), // @Param: TERRAIN_FOLLOW // @DisplayName: Terrain Following use control // @Description: This enables terrain following for RTL and LAND flight modes. To use this option TERRAIN_ENABLE must be 1 and the GCS must support sending terrain data to the aircraft. In RTL the RTL_ALT will be considered a height above the terrain. In LAND mode the vehicle will slow to LAND_SPEED 10m above terrain (instead of 10m above home). This parameter does not affect AUTO and Guided which use a per-command flag to determine if the height is above-home, absolute or above-terrain. // @Values: 0:Do Not Use in RTL and Land,1:Use in RTL and Land // @User: Standard GSCALAR(terrain_follow, "TERRAIN_FOLLOW", 0), // @Group: // @Path: Parameters.cpp GOBJECT(g2, "", ParametersG2), AP_VAREND }; /* 2nd group of parameters */ const AP_Param::GroupInfo ParametersG2::var_info[] = { // @Param: WP_NAVALT_MIN // @DisplayName: Minimum navigation altitude // @Description: This is the altitude in meters above which for navigation can begin. This applies in auto takeoff and auto landing. // @Range: 0 5 // @User: Standard AP_GROUPINFO("WP_NAVALT_MIN", 1, ParametersG2, wp_navalt_min, 0), // @Group: BTN_ // @Path: ../libraries/AP_Button/AP_Button.cpp AP_SUBGROUPINFO(button, "BTN_", 2, ParametersG2, AP_Button), // @Param: THROW_NEXTMODE // @DisplayName: Throw mode's follow up mode // @Description: Vehicle will switch to this mode after the throw is successfully completed. Default is to stay in throw mode (18) // @Values: 3:Auto,4:Guided,5:LOITER,6:RTL,9:Land,17:Brake,18:Throw // @User: Standard AP_GROUPINFO("THROW_NEXTMODE", 3, ParametersG2, throw_nextmode, 18), // @Param: THROW_TYPE // @DisplayName: Type of Type // @Description: Used by THROW mode. Specifies whether Copter is thrown upward or dropped. // @Values: 0:Upward Throw,1:Drop // @User: Standard AP_GROUPINFO("THROW_TYPE", 4, ParametersG2, throw_type, ThrowType_Upward), // @Param: GND_EFFECT_COMP // @DisplayName: Ground Effect Compensation Enable/Disable // @Description: Ground Effect Compensation Enable/Disable // @Values: 0:Disabled,1:Enabled // @User: Advanced AP_GROUPINFO("GND_EFFECT_COMP", 5, ParametersG2, gndeffect_comp_enabled, 0), #if ADVANCED_FAILSAFE == ENABLED // @Group: AFS_ // @Path: ../libraries/AP_AdvancedFailsafe/AP_AdvancedFailsafe.cpp AP_SUBGROUPINFO(afs, "AFS_", 6, ParametersG2, AP_AdvancedFailsafe), #endif // @Param: DEV_OPTIONS // @DisplayName: Development options // @Description: Bitmask of developer options. The meanings of the bit fields in this parameter may vary at any time. Developers should check the source code for current meaning // @Bitmask: 0:ADSBMavlinkProcessing // @User: Advanced AP_GROUPINFO("DEV_OPTIONS", 7, ParametersG2, dev_options, 0), // @Group: BCN // @Path: ../libraries/AP_Beacon/AP_Beacon.cpp AP_SUBGROUPINFO(beacon, "BCN", 14, ParametersG2, AP_Beacon), #if PROXIMITY_ENABLED == ENABLED // @Group: PRX // @Path: ../libraries/AP_Proximity/AP_Proximity.cpp AP_SUBGROUPINFO(proximity, "PRX", 8, ParametersG2, AP_Proximity), #endif // @Param: ACRO_Y_EXPO // @DisplayName: Acro Yaw Expo // @Description: Acro yaw expo to allow faster rotation when stick at edges // @Values: 0:Disabled,0.1:Very Low,0.2:Low,0.3:Medium,0.4:High,0.5:Very High // @Range: -0.5 1.0 // @User: Advanced AP_GROUPINFO("ACRO_Y_EXPO", 9, ParametersG2, acro_y_expo, ACRO_Y_EXPO_DEFAULT), // @Param: ACRO_THR_MID // @DisplayName: Acro Thr Mid // @Description: Acro Throttle Mid // @Range: 0 1 // @User: Advanced AP_GROUPINFO("ACRO_THR_MID", 10, ParametersG2, acro_thr_mid, ACRO_THR_MID_DEFAULT), // @Param: SYSID_ENFORCE // @DisplayName: GCS sysid enforcement // @Description: This controls whether packets from other than the expected GCS system ID will be accepted // @Values: 0:NotEnforced,1:Enforced // @User: Advanced AP_GROUPINFO("SYSID_ENFORCE", 11, ParametersG2, sysid_enforce, 0), // @Group: STAT // @Path: ../libraries/AP_Stats/AP_Stats.cpp AP_SUBGROUPINFO(stats, "STAT", 12, ParametersG2, AP_Stats), #if GRIPPER_ENABLED == ENABLED // @Group: GRIP_ // @Path: ../libraries/AP_Gripper/AP_Gripper.cpp AP_SUBGROUPINFO(gripper, "GRIP_", 13, ParametersG2, AP_Gripper), #endif // @Param: FRAME_CLASS // @DisplayName: Frame Class // @Description: Controls major frame class for multicopter component // @Values: 0:Undefined, 1:Quad, 2:Hexa, 3:Octa, 4:OctaQuad, 5:Y6, 6:Heli, 7:Tri, 8:SingleCopter, 9:CoaxCopter, 11:Heli_Dual, 12:DodecaHexa // @User: Standard // @RebootRequired: True AP_GROUPINFO("FRAME_CLASS", 15, ParametersG2, frame_class, 0), // @Group: SERVO // @Path: ../libraries/SRV_Channel/SRV_Channels.cpp AP_SUBGROUPINFO(servo_channels, "SERVO", 16, ParametersG2, SRV_Channels), // @Group: RC // @Path: ../libraries/RC_Channel/RC_Channels.cpp AP_SUBGROUPINFO(rc_channels, "RC", 17, ParametersG2, RC_Channels), #if VISUAL_ODOMETRY_ENABLED == ENABLED // @Group: VISO // @Path: ../libraries/AP_VisualOdom/AP_VisualOdom.cpp AP_SUBGROUPINFO(visual_odom, "VISO", 18, ParametersG2, AP_VisualOdom), #endif // ID 19 reserved for TCAL (PR pending) // ID 20 reserved for TX_TYPE (PR pending) // @Group: SRTL_ // @Path: ../libraries/AP_SmartRTL/AP_SmartRTL.cpp AP_SUBGROUPINFO(smart_rtl, "SRTL_", 21, ParametersG2, AP_SmartRTL), // @Group: WENC // @Path: ../libraries/AP_WheelEncoder/AP_WheelEncoder.cpp AP_SUBGROUPINFO(wheel_encoder, "WENC", 22, ParametersG2, AP_WheelEncoder), // @Group: WINCH_ // @Path: ../libraries/AP_Winch/AP_Winch.cpp AP_SUBGROUPINFO(winch, "WINCH", 23, ParametersG2, AP_Winch), // @Param: PILOT_SPEED_DN // @DisplayName: Pilot maximum vertical speed descending // @Description: The maximum vertical descending velocity the pilot may request in cm/s // @Units: cm/s // @Range: 50 500 // @Increment: 10 // @User: Standard AP_GROUPINFO("PILOT_SPEED_DN", 24, ParametersG2, pilot_speed_dn, 0), AP_GROUPEND }; /* constructor for g2 object */ ParametersG2::ParametersG2(void) : beacon(copter.serial_manager) #if PROXIMITY_ENABLED == ENABLED , proximity(copter.serial_manager) #endif #if ADVANCED_FAILSAFE == ENABLED ,afs(copter.mission, copter.barometer, copter.gps, copter.rcmap) #endif ,smart_rtl(copter.ahrs) { AP_Param::setup_object_defaults(this, var_info); } /* This is a conversion table from old parameter values to new parameter names. The startup code looks for saved values of the old parameters and will copy them across to the new parameters if the new parameter does not yet have a saved value. It then saves the new value. Note that this works even if the old parameter has been removed. It relies on the old k_param index not being removed The second column below is the index in the var_info[] table for the old object. This should be zero for top level parameters. */ const AP_Param::ConversionInfo conversion_table[] = { { Parameters::k_param_battery_monitoring, 0, AP_PARAM_INT8, "BATT_MONITOR" }, { Parameters::k_param_battery_volt_pin, 0, AP_PARAM_INT8, "BATT_VOLT_PIN" }, { Parameters::k_param_battery_curr_pin, 0, AP_PARAM_INT8, "BATT_CURR_PIN" }, { Parameters::k_param_volt_div_ratio, 0, AP_PARAM_FLOAT, "BATT_VOLT_MULT" }, { Parameters::k_param_curr_amp_per_volt, 0, AP_PARAM_FLOAT, "BATT_AMP_PERVOLT" }, { Parameters::k_param_pack_capacity, 0, AP_PARAM_INT32, "BATT_CAPACITY" }, { Parameters::k_param_log_bitmask_old, 0, AP_PARAM_INT16, "LOG_BITMASK" }, { Parameters::k_param_serial0_baud, 0, AP_PARAM_INT16, "SERIAL0_BAUD" }, { Parameters::k_param_serial1_baud, 0, AP_PARAM_INT16, "SERIAL1_BAUD" }, { Parameters::k_param_serial2_baud, 0, AP_PARAM_INT16, "SERIAL2_BAUD" }, { Parameters::k_param_arming_check_old, 0, AP_PARAM_INT8, "ARMING_CHECK" }, }; void Copter::load_parameters(void) { if (!AP_Param::check_var_info()) { hal.console->printf("Bad var table\n"); AP_HAL::panic("Bad var table"); } // disable centrifugal force correction, it will be enabled as part of the arming process ahrs.set_correct_centrifugal(false); hal.util->set_soft_armed(false); if (!g.format_version.load() || g.format_version != Parameters::k_format_version) { // erase all parameters hal.console->printf("Firmware change: erasing EEPROM...\n"); AP_Param::erase_all(); // save the current format version g.format_version.set_and_save(Parameters::k_format_version); hal.console->printf("done.\n"); } uint32_t before = micros(); // Load all auto-loaded EEPROM variables AP_Param::load_all(false); AP_Param::convert_old_parameters(&conversion_table[0], ARRAY_SIZE(conversion_table)); hal.console->printf("load_all took %uus\n", (unsigned)(micros() - before)); // setup AP_Param frame type flags AP_Param::set_frame_type_flags(AP_PARAM_FRAME_COPTER); } // handle conversion of PID gains from Copter-3.3 to Copter-3.4 void Copter::convert_pid_parameters(void) { // conversion info const AP_Param::ConversionInfo pid_conversion_info[] = { { Parameters::k_param_pid_rate_roll, 0, AP_PARAM_FLOAT, "ATC_RAT_RLL_P" }, { Parameters::k_param_pid_rate_roll, 1, AP_PARAM_FLOAT, "ATC_RAT_RLL_I" }, { Parameters::k_param_pid_rate_roll, 2, AP_PARAM_FLOAT, "ATC_RAT_RLL_D" }, { Parameters::k_param_pid_rate_pitch, 0, AP_PARAM_FLOAT, "ATC_RAT_PIT_P" }, { Parameters::k_param_pid_rate_pitch, 1, AP_PARAM_FLOAT, "ATC_RAT_PIT_I" }, { Parameters::k_param_pid_rate_pitch, 2, AP_PARAM_FLOAT, "ATC_RAT_PIT_D" }, { Parameters::k_param_pid_rate_yaw, 0, AP_PARAM_FLOAT, "ATC_RAT_YAW_P" }, { Parameters::k_param_pid_rate_yaw, 1, AP_PARAM_FLOAT, "ATC_RAT_YAW_I" }, { Parameters::k_param_pid_rate_yaw, 2, AP_PARAM_FLOAT, "ATC_RAT_YAW_D" }, #if FRAME_CONFIG == HELI_FRAME { Parameters::k_param_pid_rate_roll, 4, AP_PARAM_FLOAT, "ATC_RAT_RLL_VFF" }, { Parameters::k_param_pid_rate_pitch, 4, AP_PARAM_FLOAT, "ATC_RAT_PIT_VFF" }, { Parameters::k_param_pid_rate_yaw , 4, AP_PARAM_FLOAT, "ATC_RAT_YAW_VFF" }, #endif }; const AP_Param::ConversionInfo imax_conversion_info[] = { { Parameters::k_param_pid_rate_roll, 5, AP_PARAM_FLOAT, "ATC_RAT_RLL_IMAX" }, { Parameters::k_param_pid_rate_pitch, 5, AP_PARAM_FLOAT, "ATC_RAT_PIT_IMAX" }, { Parameters::k_param_pid_rate_yaw, 5, AP_PARAM_FLOAT, "ATC_RAT_YAW_IMAX" }, #if FRAME_CONFIG == HELI_FRAME { Parameters::k_param_pid_rate_roll, 7, AP_PARAM_FLOAT, "ATC_RAT_RLL_ILMI" }, { Parameters::k_param_pid_rate_pitch, 7, AP_PARAM_FLOAT, "ATC_RAT_PIT_ILMI" }, { Parameters::k_param_pid_rate_yaw, 7, AP_PARAM_FLOAT, "ATC_RAT_YAW_ILMI" }, #endif }; const AP_Param::ConversionInfo angle_and_filt_conversion_info[] = { { Parameters::k_param_p_stabilize_roll, 0, AP_PARAM_FLOAT, "ATC_ANG_RLL_P" }, { Parameters::k_param_p_stabilize_pitch, 0, AP_PARAM_FLOAT, "ATC_ANG_PIT_P" }, { Parameters::k_param_p_stabilize_yaw, 0, AP_PARAM_FLOAT, "ATC_ANG_YAW_P" }, { Parameters::k_param_pid_rate_roll, 6, AP_PARAM_FLOAT, "ATC_RAT_RLL_FILT" }, { Parameters::k_param_pid_rate_pitch, 6, AP_PARAM_FLOAT, "ATC_RAT_PIT_FILT" }, { Parameters::k_param_pid_rate_yaw, 6, AP_PARAM_FLOAT, "ATC_RAT_YAW_FILT" } }; const AP_Param::ConversionInfo throttle_conversion_info[] = { { Parameters::k_param_throttle_min, 0, AP_PARAM_FLOAT, "MOT_SPIN_MIN" }, { Parameters::k_param_throttle_mid, 0, AP_PARAM_FLOAT, "MOT_THST_HOVER" } }; // gains increase by 27% due to attitude controller's switch to use radians instead of centi-degrees // and motor libraries switch to accept inputs in -1 to +1 range instead of -4500 ~ +4500 float pid_scaler = 1.27f; #if FRAME_CONFIG != HELI_FRAME // Multicopter x-frame gains are 40% lower because -1 or +1 input to motors now results in maximum rotation if (g.frame_type == AP_Motors::MOTOR_FRAME_TYPE_X || g.frame_type == AP_Motors::MOTOR_FRAME_TYPE_V || g.frame_type == AP_Motors::MOTOR_FRAME_TYPE_H) { pid_scaler = 0.9f; } #endif // scale PID gains uint8_t table_size = ARRAY_SIZE(pid_conversion_info); for (uint8_t i=0; i<table_size; i++) { AP_Param::convert_old_parameter(&pid_conversion_info[i], pid_scaler); } // reduce IMAX into -1 ~ +1 range table_size = ARRAY_SIZE(imax_conversion_info); for (uint8_t i=0; i<table_size; i++) { AP_Param::convert_old_parameter(&imax_conversion_info[i], 1.0f/4500.0f); } // convert angle controller gain and filter without scaling table_size = ARRAY_SIZE(angle_and_filt_conversion_info); for (uint8_t i=0; i<table_size; i++) { AP_Param::convert_old_parameter(&angle_and_filt_conversion_info[i], 1.0f); } // convert throttle parameters (multicopter only) table_size = ARRAY_SIZE(throttle_conversion_info); for (uint8_t i=0; i<table_size; i++) { AP_Param::convert_old_parameter(&throttle_conversion_info[i], 0.001f); } const uint8_t old_rc_keys[14] = { Parameters::k_param_rc_1_old, Parameters::k_param_rc_2_old, Parameters::k_param_rc_3_old, Parameters::k_param_rc_4_old, Parameters::k_param_rc_5_old, Parameters::k_param_rc_6_old, Parameters::k_param_rc_7_old, Parameters::k_param_rc_8_old, Parameters::k_param_rc_9_old, Parameters::k_param_rc_10_old, Parameters::k_param_rc_11_old, Parameters::k_param_rc_12_old, Parameters::k_param_rc_13_old, Parameters::k_param_rc_14_old }; const uint16_t old_aux_chan_mask = 0x3FF0; // note that we don't pass in rcmap as we don't want output channel functions changed based on rcmap if (SRV_Channels::upgrade_parameters(old_rc_keys, old_aux_chan_mask, nullptr)) { // the rest needs to be done after motors allocation upgrading_frame_params = true; } }
gpl-3.0
MTK6580/walkie-talkie
ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/bionic/libm/amd64/fenv.c
3
11867
/* $OpenBSD: fenv.c,v 1.3 2012/12/05 23:20:02 deraadt Exp $ */ /* $NetBSD: fenv.c,v 1.1 2010/07/31 21:47:53 joerg Exp $ */ /*- * Copyright (c) 2004-2005 David Schultz <das (at) FreeBSD.ORG> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <fenv.h> #include <machine/fpu.h> #define SSE_MASK_SHIFT 7 /* * The following symbol is simply the bitwise-inclusive OR of all floating-point * rounding direction constants defined above. */ #define X87_ROUND_MASK (FE_TONEAREST | FE_DOWNWARD | FE_UPWARD | FE_TOWARDZERO) #define SSE_ROUND_SHIFT 3 /* * The following constant represents the default floating-point environment * (that is, the one installed at program startup) and has type pointer to * const-qualified fenv_t. * * It can be used as an argument to the functions within the <fenv.h> header * that manage the floating-point environment, namely fesetenv() and * feupdateenv(). * * x87 fpu registers are 16bit wide. The upper bits, 31-16, are marked as * RESERVED. */ const fenv_t __fe_dfl_env = { { 0xffff0000 | __INITIAL_NPXCW__, /* Control word register */ 0xffff0000, /* Status word register */ 0xffffffff, /* Tag word register */ { 0x00000000, 0x00000000, 0x00000000, 0xffff0000 } }, __INITIAL_MXCSR__ /* MXCSR register */ }; /* * The feclearexcept() function clears the supported floating-point exceptions * represented by `excepts'. */ int feclearexcept(int excepts) { fenv_t fenv; unsigned int mxcsr; excepts &= FE_ALL_EXCEPT; /* Store the current x87 floating-point environment */ __asm__ __volatile__ ("fnstenv %0" : "=m" (fenv)); /* Clear the requested floating-point exceptions */ fenv.__x87.__status &= ~excepts; /* Load the x87 floating-point environent */ __asm__ __volatile__ ("fldenv %0" : : "m" (fenv)); /* Same for SSE environment */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); mxcsr &= ~excepts; __asm__ __volatile__ ("ldmxcsr %0" : : "m" (mxcsr)); return (0); } /* * The fegetexceptflag() function stores an implementation-defined * representation of the states of the floating-point status flags indicated by * the argument excepts in the object pointed to by the argument flagp. */ int fegetexceptflag(fexcept_t *flagp, int excepts) { unsigned short status; unsigned int mxcsr; excepts &= FE_ALL_EXCEPT; /* Store the current x87 status register */ __asm__ __volatile__ ("fnstsw %0" : "=am" (status)); /* Store the MXCSR register */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); /* Store the results in flagp */ *flagp = (status | mxcsr) & excepts; return (0); } /* * The feraiseexcept() function raises the supported floating-point exceptions * represented by the argument `excepts'. * * The standard explicitly allows us to execute an instruction that has the * exception as a side effect, but we choose to manipulate the status register * directly. * * The validation of input is being deferred to fesetexceptflag(). */ int feraiseexcept(int excepts) { excepts &= FE_ALL_EXCEPT; fesetexceptflag((fexcept_t *)&excepts, excepts); __asm__ __volatile__ ("fwait"); return (0); } /* * This function sets the floating-point status flags indicated by the argument * `excepts' to the states stored in the object pointed to by `flagp'. It does * NOT raise any floating-point exceptions, but only sets the state of the flags. */ int fesetexceptflag(const fexcept_t *flagp, int excepts) { fenv_t fenv; unsigned int mxcsr; excepts &= FE_ALL_EXCEPT; /* Store the current x87 floating-point environment */ __asm__ __volatile__ ("fnstenv %0" : "=m" (fenv)); /* Set the requested status flags */ fenv.__x87.__status &= ~excepts; fenv.__x87.__status |= *flagp & excepts; /* Load the x87 floating-point environent */ __asm__ __volatile__ ("fldenv %0" : : "m" (fenv)); /* Same for SSE environment */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); mxcsr &= ~excepts; mxcsr |= *flagp & excepts; __asm__ __volatile__ ("ldmxcsr %0" : : "m" (mxcsr)); return (0); } /* * The fetestexcept() function determines which of a specified subset of the * floating-point exception flags are currently set. The `excepts' argument * specifies the floating-point status flags to be queried. */ int fetestexcept(int excepts) { unsigned short status; unsigned int mxcsr; excepts &= FE_ALL_EXCEPT; /* Store the current x87 status register */ __asm__ __volatile__ ("fnstsw %0" : "=am" (status)); /* Store the MXCSR register state */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); return ((status | mxcsr) & excepts); } /* * The fegetround() function gets the current rounding direction. */ int fegetround(void) { unsigned short control; /* * We assume that the x87 and the SSE unit agree on the * rounding mode. Reading the control word on the x87 turns * out to be about 5 times faster than reading it on the SSE * unit on an Opteron 244. */ __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); return (control & X87_ROUND_MASK); } /* * The fesetround() function establishes the rounding direction represented by * its argument `round'. If the argument is not equal to the value of a rounding * direction macro, the rounding direction is not changed. */ int fesetround(int round) { unsigned short control; unsigned int mxcsr; /* Check whether requested rounding direction is supported */ if (round & ~X87_ROUND_MASK) return (-1); /* Store the current x87 control word register */ __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); /* Set the rounding direction */ control &= ~X87_ROUND_MASK; control |= round; /* Load the x87 control word register */ __asm__ __volatile__ ("fldcw %0" : : "m" (control)); /* Same for the SSE environment */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); mxcsr &= ~(X87_ROUND_MASK << SSE_ROUND_SHIFT); mxcsr |= round << SSE_ROUND_SHIFT; __asm__ __volatile__ ("ldmxcsr %0" : : "m" (mxcsr)); return (0); } /* * The fegetenv() function attempts to store the current floating-point * environment in the object pointed to by envp. */ int fegetenv(fenv_t *envp) { /* Store the current x87 floating-point environment */ __asm__ __volatile__ ("fnstenv %0" : "=m" (*envp)); /* Store the MXCSR register state */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (envp->__mxcsr)); /* * When an FNSTENV instruction is executed, all pending exceptions are * essentially lost (either the x87 FPU status register is cleared or * all exceptions are masked). * * 8.6 X87 FPU EXCEPTION SYNCHRONIZATION - * Intel(R) 64 and IA-32 Architectures Softare Developer's Manual - Vol1 */ __asm__ __volatile__ ("fldcw %0" : : "m" (envp->__x87.__control)); return (0); } /* * The feholdexcept() function saves the current floating-point environment * in the object pointed to by envp, clears the floating-point status flags, and * then installs a non-stop (continue on floating-point exceptions) mode, if * available, for all floating-point exceptions. */ int feholdexcept(fenv_t *envp) { unsigned int mxcsr; /* Store the current x87 floating-point environment */ __asm__ __volatile__ ("fnstenv %0" : "=m" (*envp)); /* Clear all exception flags in FPU */ __asm__ __volatile__ ("fnclex"); /* Store the MXCSR register state */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (envp->__mxcsr)); /* Clear exception flags in MXCSR */ mxcsr = envp->__mxcsr; mxcsr &= ~FE_ALL_EXCEPT; /* Mask all exceptions */ mxcsr |= FE_ALL_EXCEPT << SSE_MASK_SHIFT; /* Store the MXCSR register */ __asm__ __volatile__ ("ldmxcsr %0" : : "m" (mxcsr)); return (0); } /* * The fesetenv() function attempts to establish the floating-point environment * represented by the object pointed to by envp. The argument `envp' points * to an object set by a call to fegetenv() or feholdexcept(), or equal a * floating-point environment macro. The fesetenv() function does not raise * floating-point exceptions, but only installs the state of the floating-point * status flags represented through its argument. */ int fesetenv(const fenv_t *envp) { /* Load the x87 floating-point environent */ __asm__ __volatile__ ("fldenv %0" : : "m" (*envp)); /* Store the MXCSR register */ __asm__ __volatile__ ("ldmxcsr %0" : : "m" (envp->__mxcsr)); return (0); } /* * The feupdateenv() function saves the currently raised floating-point * exceptions in its automatic storage, installs the floating-point environment * represented by the object pointed to by `envp', and then raises the saved * floating-point exceptions. The argument `envp' shall point to an object set * by a call to feholdexcept() or fegetenv(), or equal a floating-point * environment macro. */ int feupdateenv(const fenv_t *envp) { unsigned short status; unsigned int mxcsr; /* Store the x87 status register */ __asm__ __volatile__ ("fnstsw %0" : "=am" (status)); /* Store the MXCSR register */ __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); /* Install new floating-point environment */ fesetenv(envp); /* Raise any previously accumulated exceptions */ feraiseexcept(status | mxcsr); return (0); } /* * The following functions are extentions to the standard */ int feenableexcept(int mask) { unsigned int mxcsr, omask; unsigned short control; mask &= FE_ALL_EXCEPT; __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); omask = ~(control | (mxcsr >> SSE_MASK_SHIFT)) & FE_ALL_EXCEPT; control &= ~mask; __asm__ __volatile__ ("fldcw %0" : : "m" (control)); mxcsr &= ~(mask << SSE_MASK_SHIFT); __asm__ __volatile__ ("ldmxcsr %0" : : "m" (mxcsr)); return (omask); } int fedisableexcept(int mask) { unsigned int mxcsr, omask; unsigned short control; mask &= FE_ALL_EXCEPT; __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); __asm__ __volatile__ ("stmxcsr %0" : "=m" (mxcsr)); omask = ~(control | (mxcsr >> SSE_MASK_SHIFT)) & FE_ALL_EXCEPT; control |= mask; __asm__ __volatile__ ("fldcw %0" : : "m" (control)); mxcsr |= mask << SSE_MASK_SHIFT; __asm__ __volatile__ ("ldmxcsr %0" : : "m" (mxcsr)); return (omask); } int fegetexcept(void) { unsigned short control; /* * We assume that the masks for the x87 and the SSE unit are * the same. */ __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); return (~control & FE_ALL_EXCEPT); }
gpl-3.0
mkvdv/au-linux-kernel-autumn-2017
linux/mm/slub.c
4
143909
/* * SLUB: A slab allocator that limits cache line use instead of queuing * objects in per cpu and per node lists. * * The allocator synchronizes using per slab locks or atomic operatios * and only uses a centralized lock to manage a pool of partial slabs. * * (C) 2007 SGI, Christoph Lameter * (C) 2011 Linux Foundation, Christoph Lameter */ #include <linux/mm.h> #include <linux/swap.h> /* struct reclaim_state */ #include <linux/module.h> #include <linux/bit_spinlock.h> #include <linux/interrupt.h> #include <linux/bitops.h> #include <linux/slab.h> #include "slab.h" #include <linux/proc_fs.h> #include <linux/notifier.h> #include <linux/seq_file.h> #include <linux/kasan.h> #include <linux/kmemcheck.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/mempolicy.h> #include <linux/ctype.h> #include <linux/debugobjects.h> #include <linux/kallsyms.h> #include <linux/memory.h> #include <linux/math64.h> #include <linux/fault-inject.h> #include <linux/stacktrace.h> #include <linux/prefetch.h> #include <linux/memcontrol.h> #include <trace/events/kmem.h> #include "internal.h" /* * Lock order: * 1. slab_mutex (Global Mutex) * 2. node->list_lock * 3. slab_lock(page) (Only on some arches and for debugging) * * slab_mutex * * The role of the slab_mutex is to protect the list of all the slabs * and to synchronize major metadata changes to slab cache structures. * * The slab_lock is only used for debugging and on arches that do not * have the ability to do a cmpxchg_double. It only protects the second * double word in the page struct. Meaning * A. page->freelist -> List of object free in a page * B. page->counters -> Counters of objects * C. page->frozen -> frozen state * * If a slab is frozen then it is exempt from list management. It is not * on any list. The processor that froze the slab is the one who can * perform list operations on the page. Other processors may put objects * onto the freelist but the processor that froze the slab is the only * one that can retrieve the objects from the page's freelist. * * The list_lock protects the partial and full list on each node and * the partial slab counter. If taken then no new slabs may be added or * removed from the lists nor make the number of partial slabs be modified. * (Note that the total number of slabs is an atomic value that may be * modified without taking the list lock). * * The list_lock is a centralized lock and thus we avoid taking it as * much as possible. As long as SLUB does not have to handle partial * slabs, operations can continue without any centralized lock. F.e. * allocating a long series of objects that fill up slabs does not require * the list lock. * Interrupts are disabled during allocation and deallocation in order to * make the slab allocator safe to use in the context of an irq. In addition * interrupts are disabled to ensure that the processor does not change * while handling per_cpu slabs, due to kernel preemption. * * SLUB assigns one slab for allocation to each processor. * Allocations only occur from these slabs called cpu slabs. * * Slabs with free elements are kept on a partial list and during regular * operations no list for full slabs is used. If an object in a full slab is * freed then the slab will show up again on the partial lists. * We track full slabs for debugging purposes though because otherwise we * cannot scan all objects. * * Slabs are freed when they become empty. Teardown and setup is * minimal so we rely on the page allocators per cpu caches for * fast frees and allocs. * * Overloading of page flags that are otherwise used for LRU management. * * PageActive The slab is frozen and exempt from list processing. * This means that the slab is dedicated to a purpose * such as satisfying allocations for a specific * processor. Objects may be freed in the slab while * it is frozen but slab_free will then skip the usual * list operations. It is up to the processor holding * the slab to integrate the slab into the slab lists * when the slab is no longer needed. * * One use of this flag is to mark slabs that are * used for allocations. Then such a slab becomes a cpu * slab. The cpu slab may be equipped with an additional * freelist that allows lockless access to * free objects in addition to the regular freelist * that requires the slab lock. * * PageError Slab requires special handling due to debug * options set. This moves slab handling out of * the fast path and disables lockless freelists. */ static inline int kmem_cache_debug(struct kmem_cache *s) { #ifdef CONFIG_SLUB_DEBUG return unlikely(s->flags & SLAB_DEBUG_FLAGS); #else return 0; #endif } void *fixup_red_left(struct kmem_cache *s, void *p) { if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) p += s->red_left_pad; return p; } static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s) { #ifdef CONFIG_SLUB_CPU_PARTIAL return !kmem_cache_debug(s); #else return false; #endif } /* * Issues still to be resolved: * * - Support PAGE_ALLOC_DEBUG. Should be easy to do. * * - Variable sizing of the per node arrays */ /* Enable to test recovery from slab corruption on boot */ #undef SLUB_RESILIENCY_TEST /* Enable to log cmpxchg failures */ #undef SLUB_DEBUG_CMPXCHG /* * Mininum number of partial slabs. These will be left on the partial * lists even if they are empty. kmem_cache_shrink may reclaim them. */ #define MIN_PARTIAL 5 /* * Maximum number of desirable partial slabs. * The existence of more partial slabs makes kmem_cache_shrink * sort the partial list by the number of objects in use. */ #define MAX_PARTIAL 10 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \ SLAB_POISON | SLAB_STORE_USER) /* * These debug flags cannot use CMPXCHG because there might be consistency * issues when checking or reading debug information */ #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \ SLAB_TRACE) /* * Debugging flags that require metadata to be stored in the slab. These get * disabled when slub_debug=O is used and a cache's min order increases with * metadata. */ #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER) #define OO_SHIFT 16 #define OO_MASK ((1 << OO_SHIFT) - 1) #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */ /* Internal SLUB flags */ #define __OBJECT_POISON 0x80000000UL /* Poison object */ #define __CMPXCHG_DOUBLE 0x40000000UL /* Use cmpxchg_double */ /* * Tracking user of a slab. */ #define TRACK_ADDRS_COUNT 16 struct track { unsigned long addr; /* Called from address */ #ifdef CONFIG_STACKTRACE unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */ #endif int cpu; /* Was running on cpu */ int pid; /* Pid context */ unsigned long when; /* When did the operation occur */ }; enum track_item { TRACK_ALLOC, TRACK_FREE }; #ifdef CONFIG_SYSFS static int sysfs_slab_add(struct kmem_cache *); static int sysfs_slab_alias(struct kmem_cache *, const char *); static void memcg_propagate_slab_attrs(struct kmem_cache *s); static void sysfs_slab_remove(struct kmem_cache *s); #else static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; } static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p) { return 0; } static inline void memcg_propagate_slab_attrs(struct kmem_cache *s) { } static inline void sysfs_slab_remove(struct kmem_cache *s) { } #endif static inline void stat(const struct kmem_cache *s, enum stat_item si) { #ifdef CONFIG_SLUB_STATS /* * The rmw is racy on a preemptible kernel but this is acceptable, so * avoid this_cpu_add()'s irq-disable overhead. */ raw_cpu_inc(s->cpu_slab->stat[si]); #endif } /******************************************************************** * Core slab cache functions *******************************************************************/ static inline void *get_freepointer(struct kmem_cache *s, void *object) { return *(void **)(object + s->offset); } static void prefetch_freepointer(const struct kmem_cache *s, void *object) { prefetch(object + s->offset); } static inline void *get_freepointer_safe(struct kmem_cache *s, void *object) { void *p; if (!debug_pagealloc_enabled()) return get_freepointer(s, object); probe_kernel_read(&p, (void **)(object + s->offset), sizeof(p)); return p; } static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp) { *(void **)(object + s->offset) = fp; } /* Loop over all objects in a slab */ #define for_each_object(__p, __s, __addr, __objects) \ for (__p = fixup_red_left(__s, __addr); \ __p < (__addr) + (__objects) * (__s)->size; \ __p += (__s)->size) #define for_each_object_idx(__p, __idx, __s, __addr, __objects) \ for (__p = fixup_red_left(__s, __addr), __idx = 1; \ __idx <= __objects; \ __p += (__s)->size, __idx++) /* Determine object index from a given position */ static inline int slab_index(void *p, struct kmem_cache *s, void *addr) { return (p - addr) / s->size; } static inline int order_objects(int order, unsigned long size, int reserved) { return ((PAGE_SIZE << order) - reserved) / size; } static inline struct kmem_cache_order_objects oo_make(int order, unsigned long size, int reserved) { struct kmem_cache_order_objects x = { (order << OO_SHIFT) + order_objects(order, size, reserved) }; return x; } static inline int oo_order(struct kmem_cache_order_objects x) { return x.x >> OO_SHIFT; } static inline int oo_objects(struct kmem_cache_order_objects x) { return x.x & OO_MASK; } /* * Per slab locking using the pagelock */ static __always_inline void slab_lock(struct page *page) { VM_BUG_ON_PAGE(PageTail(page), page); bit_spin_lock(PG_locked, &page->flags); } static __always_inline void slab_unlock(struct page *page) { VM_BUG_ON_PAGE(PageTail(page), page); __bit_spin_unlock(PG_locked, &page->flags); } static inline void set_page_slub_counters(struct page *page, unsigned long counters_new) { struct page tmp; tmp.counters = counters_new; /* * page->counters can cover frozen/inuse/objects as well * as page->_refcount. If we assign to ->counters directly * we run the risk of losing updates to page->_refcount, so * be careful and only assign to the fields we need. */ page->frozen = tmp.frozen; page->inuse = tmp.inuse; page->objects = tmp.objects; } /* Interrupts must be disabled (for the fallback code to work right) */ static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page, void *freelist_old, unsigned long counters_old, void *freelist_new, unsigned long counters_new, const char *n) { VM_BUG_ON(!irqs_disabled()); #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \ defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE) if (s->flags & __CMPXCHG_DOUBLE) { if (cmpxchg_double(&page->freelist, &page->counters, freelist_old, counters_old, freelist_new, counters_new)) return true; } else #endif { slab_lock(page); if (page->freelist == freelist_old && page->counters == counters_old) { page->freelist = freelist_new; set_page_slub_counters(page, counters_new); slab_unlock(page); return true; } slab_unlock(page); } cpu_relax(); stat(s, CMPXCHG_DOUBLE_FAIL); #ifdef SLUB_DEBUG_CMPXCHG pr_info("%s %s: cmpxchg double redo ", n, s->name); #endif return false; } static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page, void *freelist_old, unsigned long counters_old, void *freelist_new, unsigned long counters_new, const char *n) { #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \ defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE) if (s->flags & __CMPXCHG_DOUBLE) { if (cmpxchg_double(&page->freelist, &page->counters, freelist_old, counters_old, freelist_new, counters_new)) return true; } else #endif { unsigned long flags; local_irq_save(flags); slab_lock(page); if (page->freelist == freelist_old && page->counters == counters_old) { page->freelist = freelist_new; set_page_slub_counters(page, counters_new); slab_unlock(page); local_irq_restore(flags); return true; } slab_unlock(page); local_irq_restore(flags); } cpu_relax(); stat(s, CMPXCHG_DOUBLE_FAIL); #ifdef SLUB_DEBUG_CMPXCHG pr_info("%s %s: cmpxchg double redo ", n, s->name); #endif return false; } #ifdef CONFIG_SLUB_DEBUG /* * Determine a map of object in use on a page. * * Node listlock must be held to guarantee that the page does * not vanish from under us. */ static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map) { void *p; void *addr = page_address(page); for (p = page->freelist; p; p = get_freepointer(s, p)) set_bit(slab_index(p, s, addr), map); } static inline int size_from_object(struct kmem_cache *s) { if (s->flags & SLAB_RED_ZONE) return s->size - s->red_left_pad; return s->size; } static inline void *restore_red_left(struct kmem_cache *s, void *p) { if (s->flags & SLAB_RED_ZONE) p -= s->red_left_pad; return p; } /* * Debug settings: */ #if defined(CONFIG_SLUB_DEBUG_ON) static int slub_debug = DEBUG_DEFAULT_FLAGS; #else static int slub_debug; #endif static char *slub_debug_slabs; static int disable_higher_order_debug; /* * slub is about to manipulate internal object metadata. This memory lies * outside the range of the allocated object, so accessing it would normally * be reported by kasan as a bounds error. metadata_access_enable() is used * to tell kasan that these accesses are OK. */ static inline void metadata_access_enable(void) { kasan_disable_current(); } static inline void metadata_access_disable(void) { kasan_enable_current(); } /* * Object debugging */ /* Verify that a pointer has an address that is valid within a slab page */ static inline int check_valid_pointer(struct kmem_cache *s, struct page *page, void *object) { void *base; if (!object) return 1; base = page_address(page); object = restore_red_left(s, object); if (object < base || object >= base + page->objects * s->size || (object - base) % s->size) { return 0; } return 1; } static void print_section(char *level, char *text, u8 *addr, unsigned int length) { metadata_access_enable(); print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 16, 1, addr, length, 1); metadata_access_disable(); } static struct track *get_track(struct kmem_cache *s, void *object, enum track_item alloc) { struct track *p; if (s->offset) p = object + s->offset + sizeof(void *); else p = object + s->inuse; return p + alloc; } static void set_track(struct kmem_cache *s, void *object, enum track_item alloc, unsigned long addr) { struct track *p = get_track(s, object, alloc); if (addr) { #ifdef CONFIG_STACKTRACE struct stack_trace trace; int i; trace.nr_entries = 0; trace.max_entries = TRACK_ADDRS_COUNT; trace.entries = p->addrs; trace.skip = 3; metadata_access_enable(); save_stack_trace(&trace); metadata_access_disable(); /* See rant in lockdep.c */ if (trace.nr_entries != 0 && trace.entries[trace.nr_entries - 1] == ULONG_MAX) trace.nr_entries--; for (i = trace.nr_entries; i < TRACK_ADDRS_COUNT; i++) p->addrs[i] = 0; #endif p->addr = addr; p->cpu = smp_processor_id(); p->pid = current->pid; p->when = jiffies; } else memset(p, 0, sizeof(struct track)); } static void init_tracking(struct kmem_cache *s, void *object) { if (!(s->flags & SLAB_STORE_USER)) return; set_track(s, object, TRACK_FREE, 0UL); set_track(s, object, TRACK_ALLOC, 0UL); } static void print_track(const char *s, struct track *t) { if (!t->addr) return; pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n", s, (void *)t->addr, jiffies - t->when, t->cpu, t->pid); #ifdef CONFIG_STACKTRACE { int i; for (i = 0; i < TRACK_ADDRS_COUNT; i++) if (t->addrs[i]) pr_err("\t%pS\n", (void *)t->addrs[i]); else break; } #endif } static void print_tracking(struct kmem_cache *s, void *object) { if (!(s->flags & SLAB_STORE_USER)) return; print_track("Allocated", get_track(s, object, TRACK_ALLOC)); print_track("Freed", get_track(s, object, TRACK_FREE)); } static void print_page_info(struct page *page) { pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n", page, page->objects, page->inuse, page->freelist, page->flags); } static void slab_bug(struct kmem_cache *s, char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; pr_err("=============================================================================\n"); pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf); pr_err("-----------------------------------------------------------------------------\n\n"); add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); va_end(args); } static void slab_fix(struct kmem_cache *s, char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; pr_err("FIX %s: %pV\n", s->name, &vaf); va_end(args); } static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p) { unsigned int off; /* Offset of last byte */ u8 *addr = page_address(page); print_tracking(s, p); print_page_info(page); pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n", p, p - addr, get_freepointer(s, p)); if (s->flags & SLAB_RED_ZONE) print_section(KERN_ERR, "Redzone ", p - s->red_left_pad, s->red_left_pad); else if (p > addr + 16) print_section(KERN_ERR, "Bytes b4 ", p - 16, 16); print_section(KERN_ERR, "Object ", p, min_t(unsigned long, s->object_size, PAGE_SIZE)); if (s->flags & SLAB_RED_ZONE) print_section(KERN_ERR, "Redzone ", p + s->object_size, s->inuse - s->object_size); if (s->offset) off = s->offset + sizeof(void *); else off = s->inuse; if (s->flags & SLAB_STORE_USER) off += 2 * sizeof(struct track); off += kasan_metadata_size(s); if (off != size_from_object(s)) /* Beginning of the filler is the free pointer */ print_section(KERN_ERR, "Padding ", p + off, size_from_object(s) - off); dump_stack(); } void object_err(struct kmem_cache *s, struct page *page, u8 *object, char *reason) { slab_bug(s, "%s", reason); print_trailer(s, page, object); } static void slab_err(struct kmem_cache *s, struct page *page, const char *fmt, ...) { va_list args; char buf[100]; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); slab_bug(s, "%s", buf); print_page_info(page); dump_stack(); } static void init_object(struct kmem_cache *s, void *object, u8 val) { u8 *p = object; if (s->flags & SLAB_RED_ZONE) memset(p - s->red_left_pad, val, s->red_left_pad); if (s->flags & __OBJECT_POISON) { memset(p, POISON_FREE, s->object_size - 1); p[s->object_size - 1] = POISON_END; } if (s->flags & SLAB_RED_ZONE) memset(p + s->object_size, val, s->inuse - s->object_size); } static void restore_bytes(struct kmem_cache *s, char *message, u8 data, void *from, void *to) { slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data); memset(from, data, to - from); } static int check_bytes_and_report(struct kmem_cache *s, struct page *page, u8 *object, char *what, u8 *start, unsigned int value, unsigned int bytes) { u8 *fault; u8 *end; metadata_access_enable(); fault = memchr_inv(start, value, bytes); metadata_access_disable(); if (!fault) return 1; end = start + bytes; while (end > fault && end[-1] == value) end--; slab_bug(s, "%s overwritten", what); pr_err("INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n", fault, end - 1, fault[0], value); print_trailer(s, page, object); restore_bytes(s, what, value, fault, end); return 0; } /* * Object layout: * * object address * Bytes of the object to be managed. * If the freepointer may overlay the object then the free * pointer is the first word of the object. * * Poisoning uses 0x6b (POISON_FREE) and the last byte is * 0xa5 (POISON_END) * * object + s->object_size * Padding to reach word boundary. This is also used for Redzoning. * Padding is extended by another word if Redzoning is enabled and * object_size == inuse. * * We fill with 0xbb (RED_INACTIVE) for inactive objects and with * 0xcc (RED_ACTIVE) for objects in use. * * object + s->inuse * Meta data starts here. * * A. Free pointer (if we cannot overwrite object on free) * B. Tracking data for SLAB_STORE_USER * C. Padding to reach required alignment boundary or at mininum * one word if debugging is on to be able to detect writes * before the word boundary. * * Padding is done using 0x5a (POISON_INUSE) * * object + s->size * Nothing is used beyond s->size. * * If slabcaches are merged then the object_size and inuse boundaries are mostly * ignored. And therefore no slab options that rely on these boundaries * may be used with merged slabcaches. */ static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p) { unsigned long off = s->inuse; /* The end of info */ if (s->offset) /* Freepointer is placed after the object. */ off += sizeof(void *); if (s->flags & SLAB_STORE_USER) /* We also have user information there */ off += 2 * sizeof(struct track); off += kasan_metadata_size(s); if (size_from_object(s) == off) return 1; return check_bytes_and_report(s, page, p, "Object padding", p + off, POISON_INUSE, size_from_object(s) - off); } /* Check the pad bytes at the end of a slab page */ static int slab_pad_check(struct kmem_cache *s, struct page *page) { u8 *start; u8 *fault; u8 *end; int length; int remainder; if (!(s->flags & SLAB_POISON)) return 1; start = page_address(page); length = (PAGE_SIZE << compound_order(page)) - s->reserved; end = start + length; remainder = length % s->size; if (!remainder) return 1; metadata_access_enable(); fault = memchr_inv(end - remainder, POISON_INUSE, remainder); metadata_access_disable(); if (!fault) return 1; while (end > fault && end[-1] == POISON_INUSE) end--; slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1); print_section(KERN_ERR, "Padding ", end - remainder, remainder); restore_bytes(s, "slab padding", POISON_INUSE, end - remainder, end); return 0; } static int check_object(struct kmem_cache *s, struct page *page, void *object, u8 val) { u8 *p = object; u8 *endobject = object + s->object_size; if (s->flags & SLAB_RED_ZONE) { if (!check_bytes_and_report(s, page, object, "Redzone", object - s->red_left_pad, val, s->red_left_pad)) return 0; if (!check_bytes_and_report(s, page, object, "Redzone", endobject, val, s->inuse - s->object_size)) return 0; } else { if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) { check_bytes_and_report(s, page, p, "Alignment padding", endobject, POISON_INUSE, s->inuse - s->object_size); } } if (s->flags & SLAB_POISON) { if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) && (!check_bytes_and_report(s, page, p, "Poison", p, POISON_FREE, s->object_size - 1) || !check_bytes_and_report(s, page, p, "Poison", p + s->object_size - 1, POISON_END, 1))) return 0; /* * check_pad_bytes cleans up on its own. */ check_pad_bytes(s, page, p); } if (!s->offset && val == SLUB_RED_ACTIVE) /* * Object and freepointer overlap. Cannot check * freepointer while object is allocated. */ return 1; /* Check free pointer validity */ if (!check_valid_pointer(s, page, get_freepointer(s, p))) { object_err(s, page, p, "Freepointer corrupt"); /* * No choice but to zap it and thus lose the remainder * of the free objects in this slab. May cause * another error because the object count is now wrong. */ set_freepointer(s, p, NULL); return 0; } return 1; } static int check_slab(struct kmem_cache *s, struct page *page) { int maxobj; VM_BUG_ON(!irqs_disabled()); if (!PageSlab(page)) { slab_err(s, page, "Not a valid slab page"); return 0; } maxobj = order_objects(compound_order(page), s->size, s->reserved); if (page->objects > maxobj) { slab_err(s, page, "objects %u > max %u", page->objects, maxobj); return 0; } if (page->inuse > page->objects) { slab_err(s, page, "inuse %u > max %u", page->inuse, page->objects); return 0; } /* Slab_pad_check fixes things up after itself */ slab_pad_check(s, page); return 1; } /* * Determine if a certain object on a page is on the freelist. Must hold the * slab lock to guarantee that the chains are in a consistent state. */ static int on_freelist(struct kmem_cache *s, struct page *page, void *search) { int nr = 0; void *fp; void *object = NULL; int max_objects; fp = page->freelist; while (fp && nr <= page->objects) { if (fp == search) return 1; if (!check_valid_pointer(s, page, fp)) { if (object) { object_err(s, page, object, "Freechain corrupt"); set_freepointer(s, object, NULL); } else { slab_err(s, page, "Freepointer corrupt"); page->freelist = NULL; page->inuse = page->objects; slab_fix(s, "Freelist cleared"); return 0; } break; } object = fp; fp = get_freepointer(s, object); nr++; } max_objects = order_objects(compound_order(page), s->size, s->reserved); if (max_objects > MAX_OBJS_PER_PAGE) max_objects = MAX_OBJS_PER_PAGE; if (page->objects != max_objects) { slab_err(s, page, "Wrong number of objects. Found %d but should be %d", page->objects, max_objects); page->objects = max_objects; slab_fix(s, "Number of objects adjusted."); } if (page->inuse != page->objects - nr) { slab_err(s, page, "Wrong object count. Counter is %d but counted were %d", page->inuse, page->objects - nr); page->inuse = page->objects - nr; slab_fix(s, "Object count adjusted."); } return search == NULL; } static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc) { if (s->flags & SLAB_TRACE) { pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n", s->name, alloc ? "alloc" : "free", object, page->inuse, page->freelist); if (!alloc) print_section(KERN_INFO, "Object ", (void *)object, s->object_size); dump_stack(); } } /* * Tracking of fully allocated slabs for debugging purposes. */ static void add_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page) { if (!(s->flags & SLAB_STORE_USER)) return; lockdep_assert_held(&n->list_lock); list_add(&page->lru, &n->full); } static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page) { if (!(s->flags & SLAB_STORE_USER)) return; lockdep_assert_held(&n->list_lock); list_del(&page->lru); } /* Tracking of the number of slabs for debugging purposes */ static inline unsigned long slabs_node(struct kmem_cache *s, int node) { struct kmem_cache_node *n = get_node(s, node); return atomic_long_read(&n->nr_slabs); } static inline unsigned long node_nr_slabs(struct kmem_cache_node *n) { return atomic_long_read(&n->nr_slabs); } static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects) { struct kmem_cache_node *n = get_node(s, node); /* * May be called early in order to allocate a slab for the * kmem_cache_node structure. Solve the chicken-egg * dilemma by deferring the increment of the count during * bootstrap (see early_kmem_cache_node_alloc). */ if (likely(n)) { atomic_long_inc(&n->nr_slabs); atomic_long_add(objects, &n->total_objects); } } static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects) { struct kmem_cache_node *n = get_node(s, node); atomic_long_dec(&n->nr_slabs); atomic_long_sub(objects, &n->total_objects); } /* Object debug checks for alloc/free paths */ static void setup_object_debug(struct kmem_cache *s, struct page *page, void *object) { if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))) return; init_object(s, object, SLUB_RED_INACTIVE); init_tracking(s, object); } static inline int alloc_consistency_checks(struct kmem_cache *s, struct page *page, void *object, unsigned long addr) { if (!check_slab(s, page)) return 0; if (!check_valid_pointer(s, page, object)) { object_err(s, page, object, "Freelist Pointer check fails"); return 0; } if (!check_object(s, page, object, SLUB_RED_INACTIVE)) return 0; return 1; } static noinline int alloc_debug_processing(struct kmem_cache *s, struct page *page, void *object, unsigned long addr) { if (s->flags & SLAB_CONSISTENCY_CHECKS) { if (!alloc_consistency_checks(s, page, object, addr)) goto bad; } /* Success perform special debug activities for allocs */ if (s->flags & SLAB_STORE_USER) set_track(s, object, TRACK_ALLOC, addr); trace(s, page, object, 1); init_object(s, object, SLUB_RED_ACTIVE); return 1; bad: if (PageSlab(page)) { /* * If this is a slab page then lets do the best we can * to avoid issues in the future. Marking all objects * as used avoids touching the remaining objects. */ slab_fix(s, "Marking all objects used"); page->inuse = page->objects; page->freelist = NULL; } return 0; } static inline int free_consistency_checks(struct kmem_cache *s, struct page *page, void *object, unsigned long addr) { if (!check_valid_pointer(s, page, object)) { slab_err(s, page, "Invalid object pointer 0x%p", object); return 0; } if (on_freelist(s, page, object)) { object_err(s, page, object, "Object already free"); return 0; } if (!check_object(s, page, object, SLUB_RED_ACTIVE)) return 0; if (unlikely(s != page->slab_cache)) { if (!PageSlab(page)) { slab_err(s, page, "Attempt to free object(0x%p) outside of slab", object); } else if (!page->slab_cache) { pr_err("SLUB <none>: no slab for object 0x%p.\n", object); dump_stack(); } else object_err(s, page, object, "page slab pointer corrupt."); return 0; } return 1; } /* Supports checking bulk free of a constructed freelist */ static noinline int free_debug_processing( struct kmem_cache *s, struct page *page, void *head, void *tail, int bulk_cnt, unsigned long addr) { struct kmem_cache_node *n = get_node(s, page_to_nid(page)); void *object = head; int cnt = 0; unsigned long uninitialized_var(flags); int ret = 0; spin_lock_irqsave(&n->list_lock, flags); slab_lock(page); if (s->flags & SLAB_CONSISTENCY_CHECKS) { if (!check_slab(s, page)) goto out; } next_object: cnt++; if (s->flags & SLAB_CONSISTENCY_CHECKS) { if (!free_consistency_checks(s, page, object, addr)) goto out; } if (s->flags & SLAB_STORE_USER) set_track(s, object, TRACK_FREE, addr); trace(s, page, object, 0); /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */ init_object(s, object, SLUB_RED_INACTIVE); /* Reached end of constructed freelist yet? */ if (object != tail) { object = get_freepointer(s, object); goto next_object; } ret = 1; out: if (cnt != bulk_cnt) slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n", bulk_cnt, cnt); slab_unlock(page); spin_unlock_irqrestore(&n->list_lock, flags); if (!ret) slab_fix(s, "Object at 0x%p not freed", object); return ret; } static int __init setup_slub_debug(char *str) { slub_debug = DEBUG_DEFAULT_FLAGS; if (*str++ != '=' || !*str) /* * No options specified. Switch on full debugging. */ goto out; if (*str == ',') /* * No options but restriction on slabs. This means full * debugging for slabs matching a pattern. */ goto check_slabs; slub_debug = 0; if (*str == '-') /* * Switch off all debugging measures. */ goto out; /* * Determine which debug features should be switched on */ for (; *str && *str != ','; str++) { switch (tolower(*str)) { case 'f': slub_debug |= SLAB_CONSISTENCY_CHECKS; break; case 'z': slub_debug |= SLAB_RED_ZONE; break; case 'p': slub_debug |= SLAB_POISON; break; case 'u': slub_debug |= SLAB_STORE_USER; break; case 't': slub_debug |= SLAB_TRACE; break; case 'a': slub_debug |= SLAB_FAILSLAB; break; case 'o': /* * Avoid enabling debugging on caches if its minimum * order would increase as a result. */ disable_higher_order_debug = 1; break; default: pr_err("slub_debug option '%c' unknown. skipped\n", *str); } } check_slabs: if (*str == ',') slub_debug_slabs = str + 1; out: return 1; } __setup("slub_debug", setup_slub_debug); unsigned long kmem_cache_flags(unsigned long object_size, unsigned long flags, const char *name, void (*ctor)(void *)) { /* * Enable debugging if selected on the kernel commandline. */ if (slub_debug && (!slub_debug_slabs || (name && !strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs))))) flags |= slub_debug; return flags; } #else /* !CONFIG_SLUB_DEBUG */ static inline void setup_object_debug(struct kmem_cache *s, struct page *page, void *object) {} static inline int alloc_debug_processing(struct kmem_cache *s, struct page *page, void *object, unsigned long addr) { return 0; } static inline int free_debug_processing( struct kmem_cache *s, struct page *page, void *head, void *tail, int bulk_cnt, unsigned long addr) { return 0; } static inline int slab_pad_check(struct kmem_cache *s, struct page *page) { return 1; } static inline int check_object(struct kmem_cache *s, struct page *page, void *object, u8 val) { return 1; } static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page) {} static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page) {} unsigned long kmem_cache_flags(unsigned long object_size, unsigned long flags, const char *name, void (*ctor)(void *)) { return flags; } #define slub_debug 0 #define disable_higher_order_debug 0 static inline unsigned long slabs_node(struct kmem_cache *s, int node) { return 0; } static inline unsigned long node_nr_slabs(struct kmem_cache_node *n) { return 0; } static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects) {} static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects) {} #endif /* CONFIG_SLUB_DEBUG */ /* * Hooks for other subsystems that check memory allocations. In a typical * production configuration these hooks all should produce no code at all. */ static inline void kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags) { kmemleak_alloc(ptr, size, 1, flags); kasan_kmalloc_large(ptr, size, flags); } static inline void kfree_hook(const void *x) { kmemleak_free(x); kasan_kfree_large(x); } static inline void *slab_free_hook(struct kmem_cache *s, void *x) { void *freeptr; kmemleak_free_recursive(x, s->flags); /* * Trouble is that we may no longer disable interrupts in the fast path * So in order to make the debug calls that expect irqs to be * disabled we need to disable interrupts temporarily. */ #if defined(CONFIG_KMEMCHECK) || defined(CONFIG_LOCKDEP) { unsigned long flags; local_irq_save(flags); kmemcheck_slab_free(s, x, s->object_size); debug_check_no_locks_freed(x, s->object_size); local_irq_restore(flags); } #endif if (!(s->flags & SLAB_DEBUG_OBJECTS)) debug_check_no_obj_freed(x, s->object_size); freeptr = get_freepointer(s, x); /* * kasan_slab_free() may put x into memory quarantine, delaying its * reuse. In this case the object's freelist pointer is changed. */ kasan_slab_free(s, x); return freeptr; } static inline void slab_free_freelist_hook(struct kmem_cache *s, void *head, void *tail) { /* * Compiler cannot detect this function can be removed if slab_free_hook() * evaluates to nothing. Thus, catch all relevant config debug options here. */ #if defined(CONFIG_KMEMCHECK) || \ defined(CONFIG_LOCKDEP) || \ defined(CONFIG_DEBUG_KMEMLEAK) || \ defined(CONFIG_DEBUG_OBJECTS_FREE) || \ defined(CONFIG_KASAN) void *object = head; void *tail_obj = tail ? : head; void *freeptr; do { freeptr = slab_free_hook(s, object); } while ((object != tail_obj) && (object = freeptr)); #endif } static void setup_object(struct kmem_cache *s, struct page *page, void *object) { setup_object_debug(s, page, object); kasan_init_slab_obj(s, object); if (unlikely(s->ctor)) { kasan_unpoison_object_data(s, object); s->ctor(object); kasan_poison_object_data(s, object); } } /* * Slab allocation and freeing */ static inline struct page *alloc_slab_page(struct kmem_cache *s, gfp_t flags, int node, struct kmem_cache_order_objects oo) { struct page *page; int order = oo_order(oo); flags |= __GFP_NOTRACK; if (node == NUMA_NO_NODE) page = alloc_pages(flags, order); else page = __alloc_pages_node(node, flags, order); if (page && memcg_charge_slab(page, flags, order, s)) { __free_pages(page, order); page = NULL; } return page; } #ifdef CONFIG_SLAB_FREELIST_RANDOM /* Pre-initialize the random sequence cache */ static int init_cache_random_seq(struct kmem_cache *s) { int err; unsigned long i, count = oo_objects(s->oo); /* Bailout if already initialised */ if (s->random_seq) return 0; err = cache_random_seq_create(s, count, GFP_KERNEL); if (err) { pr_err("SLUB: Unable to initialize free list for %s\n", s->name); return err; } /* Transform to an offset on the set of pages */ if (s->random_seq) { for (i = 0; i < count; i++) s->random_seq[i] *= s->size; } return 0; } /* Initialize each random sequence freelist per cache */ static void __init init_freelist_randomization(void) { struct kmem_cache *s; mutex_lock(&slab_mutex); list_for_each_entry(s, &slab_caches, list) init_cache_random_seq(s); mutex_unlock(&slab_mutex); } /* Get the next entry on the pre-computed freelist randomized */ static void *next_freelist_entry(struct kmem_cache *s, struct page *page, unsigned long *pos, void *start, unsigned long page_limit, unsigned long freelist_count) { unsigned int idx; /* * If the target page allocation failed, the number of objects on the * page might be smaller than the usual size defined by the cache. */ do { idx = s->random_seq[*pos]; *pos += 1; if (*pos >= freelist_count) *pos = 0; } while (unlikely(idx >= page_limit)); return (char *)start + idx; } /* Shuffle the single linked freelist based on a random pre-computed sequence */ static bool shuffle_freelist(struct kmem_cache *s, struct page *page) { void *start; void *cur; void *next; unsigned long idx, pos, page_limit, freelist_count; if (page->objects < 2 || !s->random_seq) return false; freelist_count = oo_objects(s->oo); pos = get_random_int() % freelist_count; page_limit = page->objects * s->size; start = fixup_red_left(s, page_address(page)); /* First entry is used as the base of the freelist */ cur = next_freelist_entry(s, page, &pos, start, page_limit, freelist_count); page->freelist = cur; for (idx = 1; idx < page->objects; idx++) { setup_object(s, page, cur); next = next_freelist_entry(s, page, &pos, start, page_limit, freelist_count); set_freepointer(s, cur, next); cur = next; } setup_object(s, page, cur); set_freepointer(s, cur, NULL); return true; } #else static inline int init_cache_random_seq(struct kmem_cache *s) { return 0; } static inline void init_freelist_randomization(void) { } static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page) { return false; } #endif /* CONFIG_SLAB_FREELIST_RANDOM */ static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node) { struct page *page; struct kmem_cache_order_objects oo = s->oo; gfp_t alloc_gfp; void *start, *p; int idx, order; bool shuffle; flags &= gfp_allowed_mask; if (gfpflags_allow_blocking(flags)) local_irq_enable(); flags |= s->allocflags; /* * Let the initial higher-order allocation fail under memory pressure * so we fall-back to the minimum order allocation. */ alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL; if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min)) alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL); page = alloc_slab_page(s, alloc_gfp, node, oo); if (unlikely(!page)) { oo = s->min; alloc_gfp = flags; /* * Allocation may have failed due to fragmentation. * Try a lower order alloc if possible */ page = alloc_slab_page(s, alloc_gfp, node, oo); if (unlikely(!page)) goto out; stat(s, ORDER_FALLBACK); } if (kmemcheck_enabled && !(s->flags & (SLAB_NOTRACK | DEBUG_DEFAULT_FLAGS))) { int pages = 1 << oo_order(oo); kmemcheck_alloc_shadow(page, oo_order(oo), alloc_gfp, node); /* * Objects from caches that have a constructor don't get * cleared when they're allocated, so we need to do it here. */ if (s->ctor) kmemcheck_mark_uninitialized_pages(page, pages); else kmemcheck_mark_unallocated_pages(page, pages); } page->objects = oo_objects(oo); order = compound_order(page); page->slab_cache = s; __SetPageSlab(page); if (page_is_pfmemalloc(page)) SetPageSlabPfmemalloc(page); start = page_address(page); if (unlikely(s->flags & SLAB_POISON)) memset(start, POISON_INUSE, PAGE_SIZE << order); kasan_poison_slab(page); shuffle = shuffle_freelist(s, page); if (!shuffle) { for_each_object_idx(p, idx, s, start, page->objects) { setup_object(s, page, p); if (likely(idx < page->objects)) set_freepointer(s, p, p + s->size); else set_freepointer(s, p, NULL); } page->freelist = fixup_red_left(s, start); } page->inuse = page->objects; page->frozen = 1; out: if (gfpflags_allow_blocking(flags)) local_irq_disable(); if (!page) return NULL; mod_zone_page_state(page_zone(page), (s->flags & SLAB_RECLAIM_ACCOUNT) ? NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE, 1 << oo_order(oo)); inc_slabs_node(s, page_to_nid(page), page->objects); return page; } static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node) { if (unlikely(flags & GFP_SLAB_BUG_MASK)) { gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK; flags &= ~GFP_SLAB_BUG_MASK; pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n", invalid_mask, &invalid_mask, flags, &flags); dump_stack(); } return allocate_slab(s, flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node); } static void __free_slab(struct kmem_cache *s, struct page *page) { int order = compound_order(page); int pages = 1 << order; if (s->flags & SLAB_CONSISTENCY_CHECKS) { void *p; slab_pad_check(s, page); for_each_object(p, s, page_address(page), page->objects) check_object(s, page, p, SLUB_RED_INACTIVE); } kmemcheck_free_shadow(page, compound_order(page)); mod_zone_page_state(page_zone(page), (s->flags & SLAB_RECLAIM_ACCOUNT) ? NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE, -pages); __ClearPageSlabPfmemalloc(page); __ClearPageSlab(page); page_mapcount_reset(page); if (current->reclaim_state) current->reclaim_state->reclaimed_slab += pages; memcg_uncharge_slab(page, order, s); __free_pages(page, order); } #define need_reserve_slab_rcu \ (sizeof(((struct page *)NULL)->lru) < sizeof(struct rcu_head)) static void rcu_free_slab(struct rcu_head *h) { struct page *page; if (need_reserve_slab_rcu) page = virt_to_head_page(h); else page = container_of((struct list_head *)h, struct page, lru); __free_slab(page->slab_cache, page); } static void free_slab(struct kmem_cache *s, struct page *page) { if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) { struct rcu_head *head; if (need_reserve_slab_rcu) { int order = compound_order(page); int offset = (PAGE_SIZE << order) - s->reserved; VM_BUG_ON(s->reserved != sizeof(*head)); head = page_address(page) + offset; } else { head = &page->rcu_head; } call_rcu(head, rcu_free_slab); } else __free_slab(s, page); } static void discard_slab(struct kmem_cache *s, struct page *page) { dec_slabs_node(s, page_to_nid(page), page->objects); free_slab(s, page); } /* * Management of partially allocated slabs. */ static inline void __add_partial(struct kmem_cache_node *n, struct page *page, int tail) { n->nr_partial++; if (tail == DEACTIVATE_TO_TAIL) list_add_tail(&page->lru, &n->partial); else list_add(&page->lru, &n->partial); } static inline void add_partial(struct kmem_cache_node *n, struct page *page, int tail) { lockdep_assert_held(&n->list_lock); __add_partial(n, page, tail); } static inline void remove_partial(struct kmem_cache_node *n, struct page *page) { lockdep_assert_held(&n->list_lock); list_del(&page->lru); n->nr_partial--; } /* * Remove slab from the partial list, freeze it and * return the pointer to the freelist. * * Returns a list of objects or NULL if it fails. */ static inline void *acquire_slab(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page, int mode, int *objects) { void *freelist; unsigned long counters; struct page new; lockdep_assert_held(&n->list_lock); /* * Zap the freelist and set the frozen bit. * The old freelist is the list of objects for the * per cpu allocation list. */ freelist = page->freelist; counters = page->counters; new.counters = counters; *objects = new.objects - new.inuse; if (mode) { new.inuse = page->objects; new.freelist = NULL; } else { new.freelist = freelist; } VM_BUG_ON(new.frozen); new.frozen = 1; if (!__cmpxchg_double_slab(s, page, freelist, counters, new.freelist, new.counters, "acquire_slab")) return NULL; remove_partial(n, page); WARN_ON(!freelist); return freelist; } static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain); static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags); /* * Try to allocate a partial slab from a specific node. */ static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n, struct kmem_cache_cpu *c, gfp_t flags) { struct page *page, *page2; void *object = NULL; int available = 0; int objects; /* * Racy check. If we mistakenly see no partial slabs then we * just allocate an empty slab. If we mistakenly try to get a * partial slab and there is none available then get_partials() * will return NULL. */ if (!n || !n->nr_partial) return NULL; spin_lock(&n->list_lock); list_for_each_entry_safe(page, page2, &n->partial, lru) { void *t; if (!pfmemalloc_match(page, flags)) continue; t = acquire_slab(s, n, page, object == NULL, &objects); if (!t) break; available += objects; if (!object) { c->page = page; stat(s, ALLOC_FROM_PARTIAL); object = t; } else { put_cpu_partial(s, page, 0); stat(s, CPU_PARTIAL_NODE); } if (!kmem_cache_has_cpu_partial(s) || available > s->cpu_partial / 2) break; } spin_unlock(&n->list_lock); return object; } /* * Get a page from somewhere. Search in increasing NUMA distances. */ static void *get_any_partial(struct kmem_cache *s, gfp_t flags, struct kmem_cache_cpu *c) { #ifdef CONFIG_NUMA struct zonelist *zonelist; struct zoneref *z; struct zone *zone; enum zone_type high_zoneidx = gfp_zone(flags); void *object; unsigned int cpuset_mems_cookie; /* * The defrag ratio allows a configuration of the tradeoffs between * inter node defragmentation and node local allocations. A lower * defrag_ratio increases the tendency to do local allocations * instead of attempting to obtain partial slabs from other nodes. * * If the defrag_ratio is set to 0 then kmalloc() always * returns node local objects. If the ratio is higher then kmalloc() * may return off node objects because partial slabs are obtained * from other nodes and filled up. * * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100 * (which makes defrag_ratio = 1000) then every (well almost) * allocation will first attempt to defrag slab caches on other nodes. * This means scanning over all nodes to look for partial slabs which * may be expensive if we do it every time we are trying to find a slab * with available objects. */ if (!s->remote_node_defrag_ratio || get_cycles() % 1024 > s->remote_node_defrag_ratio) return NULL; do { cpuset_mems_cookie = read_mems_allowed_begin(); zonelist = node_zonelist(mempolicy_slab_node(), flags); for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) { struct kmem_cache_node *n; n = get_node(s, zone_to_nid(zone)); if (n && cpuset_zone_allowed(zone, flags) && n->nr_partial > s->min_partial) { object = get_partial_node(s, n, c, flags); if (object) { /* * Don't check read_mems_allowed_retry() * here - if mems_allowed was updated in * parallel, that was a harmless race * between allocation and the cpuset * update */ return object; } } } } while (read_mems_allowed_retry(cpuset_mems_cookie)); #endif return NULL; } /* * Get a partial page, lock it and return it. */ static void *get_partial(struct kmem_cache *s, gfp_t flags, int node, struct kmem_cache_cpu *c) { void *object; int searchnode = node; if (node == NUMA_NO_NODE) searchnode = numa_mem_id(); else if (!node_present_pages(node)) searchnode = node_to_mem_node(node); object = get_partial_node(s, get_node(s, searchnode), c, flags); if (object || node != NUMA_NO_NODE) return object; return get_any_partial(s, flags, c); } #ifdef CONFIG_PREEMPT /* * Calculate the next globally unique transaction for disambiguiation * during cmpxchg. The transactions start with the cpu number and are then * incremented by CONFIG_NR_CPUS. */ #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS) #else /* * No preemption supported therefore also no need to check for * different cpus. */ #define TID_STEP 1 #endif static inline unsigned long next_tid(unsigned long tid) { return tid + TID_STEP; } static inline unsigned int tid_to_cpu(unsigned long tid) { return tid % TID_STEP; } static inline unsigned long tid_to_event(unsigned long tid) { return tid / TID_STEP; } static inline unsigned int init_tid(int cpu) { return cpu; } static inline void note_cmpxchg_failure(const char *n, const struct kmem_cache *s, unsigned long tid) { #ifdef SLUB_DEBUG_CMPXCHG unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid); pr_info("%s %s: cmpxchg redo ", n, s->name); #ifdef CONFIG_PREEMPT if (tid_to_cpu(tid) != tid_to_cpu(actual_tid)) pr_warn("due to cpu change %d -> %d\n", tid_to_cpu(tid), tid_to_cpu(actual_tid)); else #endif if (tid_to_event(tid) != tid_to_event(actual_tid)) pr_warn("due to cpu running other code. Event %ld->%ld\n", tid_to_event(tid), tid_to_event(actual_tid)); else pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n", actual_tid, tid, next_tid(tid)); #endif stat(s, CMPXCHG_DOUBLE_CPU_FAIL); } static void init_kmem_cache_cpus(struct kmem_cache *s) { int cpu; for_each_possible_cpu(cpu) per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu); } /* * Remove the cpu slab */ static void deactivate_slab(struct kmem_cache *s, struct page *page, void *freelist) { enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE }; struct kmem_cache_node *n = get_node(s, page_to_nid(page)); int lock = 0; enum slab_modes l = M_NONE, m = M_NONE; void *nextfree; int tail = DEACTIVATE_TO_HEAD; struct page new; struct page old; if (page->freelist) { stat(s, DEACTIVATE_REMOTE_FREES); tail = DEACTIVATE_TO_TAIL; } /* * Stage one: Free all available per cpu objects back * to the page freelist while it is still frozen. Leave the * last one. * * There is no need to take the list->lock because the page * is still frozen. */ while (freelist && (nextfree = get_freepointer(s, freelist))) { void *prior; unsigned long counters; do { prior = page->freelist; counters = page->counters; set_freepointer(s, freelist, prior); new.counters = counters; new.inuse--; VM_BUG_ON(!new.frozen); } while (!__cmpxchg_double_slab(s, page, prior, counters, freelist, new.counters, "drain percpu freelist")); freelist = nextfree; } /* * Stage two: Ensure that the page is unfrozen while the * list presence reflects the actual number of objects * during unfreeze. * * We setup the list membership and then perform a cmpxchg * with the count. If there is a mismatch then the page * is not unfrozen but the page is on the wrong list. * * Then we restart the process which may have to remove * the page from the list that we just put it on again * because the number of objects in the slab may have * changed. */ redo: old.freelist = page->freelist; old.counters = page->counters; VM_BUG_ON(!old.frozen); /* Determine target state of the slab */ new.counters = old.counters; if (freelist) { new.inuse--; set_freepointer(s, freelist, old.freelist); new.freelist = freelist; } else new.freelist = old.freelist; new.frozen = 0; if (!new.inuse && n->nr_partial >= s->min_partial) m = M_FREE; else if (new.freelist) { m = M_PARTIAL; if (!lock) { lock = 1; /* * Taking the spinlock removes the possiblity * that acquire_slab() will see a slab page that * is frozen */ spin_lock(&n->list_lock); } } else { m = M_FULL; if (kmem_cache_debug(s) && !lock) { lock = 1; /* * This also ensures that the scanning of full * slabs from diagnostic functions will not see * any frozen slabs. */ spin_lock(&n->list_lock); } } if (l != m) { if (l == M_PARTIAL) remove_partial(n, page); else if (l == M_FULL) remove_full(s, n, page); if (m == M_PARTIAL) { add_partial(n, page, tail); stat(s, tail); } else if (m == M_FULL) { stat(s, DEACTIVATE_FULL); add_full(s, n, page); } } l = m; if (!__cmpxchg_double_slab(s, page, old.freelist, old.counters, new.freelist, new.counters, "unfreezing slab")) goto redo; if (lock) spin_unlock(&n->list_lock); if (m == M_FREE) { stat(s, DEACTIVATE_EMPTY); discard_slab(s, page); stat(s, FREE_SLAB); } } /* * Unfreeze all the cpu partial slabs. * * This function must be called with interrupts disabled * for the cpu using c (or some other guarantee must be there * to guarantee no concurrent accesses). */ static void unfreeze_partials(struct kmem_cache *s, struct kmem_cache_cpu *c) { #ifdef CONFIG_SLUB_CPU_PARTIAL struct kmem_cache_node *n = NULL, *n2 = NULL; struct page *page, *discard_page = NULL; while ((page = c->partial)) { struct page new; struct page old; c->partial = page->next; n2 = get_node(s, page_to_nid(page)); if (n != n2) { if (n) spin_unlock(&n->list_lock); n = n2; spin_lock(&n->list_lock); } do { old.freelist = page->freelist; old.counters = page->counters; VM_BUG_ON(!old.frozen); new.counters = old.counters; new.freelist = old.freelist; new.frozen = 0; } while (!__cmpxchg_double_slab(s, page, old.freelist, old.counters, new.freelist, new.counters, "unfreezing slab")); if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) { page->next = discard_page; discard_page = page; } else { add_partial(n, page, DEACTIVATE_TO_TAIL); stat(s, FREE_ADD_PARTIAL); } } if (n) spin_unlock(&n->list_lock); while (discard_page) { page = discard_page; discard_page = discard_page->next; stat(s, DEACTIVATE_EMPTY); discard_slab(s, page); stat(s, FREE_SLAB); } #endif } /* * Put a page that was just frozen (in __slab_free) into a partial page * slot if available. This is done without interrupts disabled and without * preemption disabled. The cmpxchg is racy and may put the partial page * onto a random cpus partial slot. * * If we did not find a slot then simply move all the partials to the * per node partial list. */ static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain) { #ifdef CONFIG_SLUB_CPU_PARTIAL struct page *oldpage; int pages; int pobjects; preempt_disable(); do { pages = 0; pobjects = 0; oldpage = this_cpu_read(s->cpu_slab->partial); if (oldpage) { pobjects = oldpage->pobjects; pages = oldpage->pages; if (drain && pobjects > s->cpu_partial) { unsigned long flags; /* * partial array is full. Move the existing * set to the per node partial list. */ local_irq_save(flags); unfreeze_partials(s, this_cpu_ptr(s->cpu_slab)); local_irq_restore(flags); oldpage = NULL; pobjects = 0; pages = 0; stat(s, CPU_PARTIAL_DRAIN); } } pages++; pobjects += page->objects - page->inuse; page->pages = pages; page->pobjects = pobjects; page->next = oldpage; } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page) != oldpage); if (unlikely(!s->cpu_partial)) { unsigned long flags; local_irq_save(flags); unfreeze_partials(s, this_cpu_ptr(s->cpu_slab)); local_irq_restore(flags); } preempt_enable(); #endif } static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c) { stat(s, CPUSLAB_FLUSH); deactivate_slab(s, c->page, c->freelist); c->tid = next_tid(c->tid); c->page = NULL; c->freelist = NULL; } /* * Flush cpu slab. * * Called from IPI handler with interrupts disabled. */ static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu); if (likely(c)) { if (c->page) flush_slab(s, c); unfreeze_partials(s, c); } } static void flush_cpu_slab(void *d) { struct kmem_cache *s = d; __flush_cpu_slab(s, smp_processor_id()); } static bool has_cpu_slab(int cpu, void *info) { struct kmem_cache *s = info; struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu); return c->page || c->partial; } static void flush_all(struct kmem_cache *s) { on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1, GFP_ATOMIC); } /* * Use the cpu notifier to insure that the cpu slabs are flushed when * necessary. */ static int slub_cpu_dead(unsigned int cpu) { struct kmem_cache *s; unsigned long flags; mutex_lock(&slab_mutex); list_for_each_entry(s, &slab_caches, list) { local_irq_save(flags); __flush_cpu_slab(s, cpu); local_irq_restore(flags); } mutex_unlock(&slab_mutex); return 0; } /* * Check if the objects in a per cpu structure fit numa * locality expectations. */ static inline int node_match(struct page *page, int node) { #ifdef CONFIG_NUMA if (!page || (node != NUMA_NO_NODE && page_to_nid(page) != node)) return 0; #endif return 1; } #ifdef CONFIG_SLUB_DEBUG static int count_free(struct page *page) { return page->objects - page->inuse; } static inline unsigned long node_nr_objs(struct kmem_cache_node *n) { return atomic_long_read(&n->total_objects); } #endif /* CONFIG_SLUB_DEBUG */ #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS) static unsigned long count_partial(struct kmem_cache_node *n, int (*get_count)(struct page *)) { unsigned long flags; unsigned long x = 0; struct page *page; spin_lock_irqsave(&n->list_lock, flags); list_for_each_entry(page, &n->partial, lru) x += get_count(page); spin_unlock_irqrestore(&n->list_lock, flags); return x; } #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */ static noinline void slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { #ifdef CONFIG_SLUB_DEBUG static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL, DEFAULT_RATELIMIT_BURST); int node; struct kmem_cache_node *n; if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs)) return; pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n", nid, gfpflags, &gfpflags); pr_warn(" cache: %s, object size: %d, buffer size: %d, default order: %d, min order: %d\n", s->name, s->object_size, s->size, oo_order(s->oo), oo_order(s->min)); if (oo_order(s->min) > get_order(s->object_size)) pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n", s->name); for_each_kmem_cache_node(s, node, n) { unsigned long nr_slabs; unsigned long nr_objs; unsigned long nr_free; nr_free = count_partial(n, count_free); nr_slabs = node_nr_slabs(n); nr_objs = node_nr_objs(n); pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n", node, nr_slabs, nr_objs, nr_free); } #endif } static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags, int node, struct kmem_cache_cpu **pc) { void *freelist; struct kmem_cache_cpu *c = *pc; struct page *page; freelist = get_partial(s, flags, node, c); if (freelist) return freelist; page = new_slab(s, flags, node); if (page) { c = raw_cpu_ptr(s->cpu_slab); if (c->page) flush_slab(s, c); /* * No other reference to the page yet so we can * muck around with it freely without cmpxchg */ freelist = page->freelist; page->freelist = NULL; stat(s, ALLOC_SLAB); c->page = page; *pc = c; } else freelist = NULL; return freelist; } static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags) { if (unlikely(PageSlabPfmemalloc(page))) return gfp_pfmemalloc_allowed(gfpflags); return true; } /* * Check the page->freelist of a page and either transfer the freelist to the * per cpu freelist or deactivate the page. * * The page is still frozen if the return value is not NULL. * * If this function returns NULL then the page has been unfrozen. * * This function must be called with interrupt disabled. */ static inline void *get_freelist(struct kmem_cache *s, struct page *page) { struct page new; unsigned long counters; void *freelist; do { freelist = page->freelist; counters = page->counters; new.counters = counters; VM_BUG_ON(!new.frozen); new.inuse = page->objects; new.frozen = freelist != NULL; } while (!__cmpxchg_double_slab(s, page, freelist, counters, NULL, new.counters, "get_freelist")); return freelist; } /* * Slow path. The lockless freelist is empty or we need to perform * debugging duties. * * Processing is still very fast if new objects have been freed to the * regular freelist. In that case we simply take over the regular freelist * as the lockless freelist and zap the regular freelist. * * If that is not working then we fall back to the partial lists. We take the * first element of the freelist as the object to allocate now and move the * rest of the freelist to the lockless freelist. * * And if we were unable to get a new slab from the partial slab lists then * we need to allocate a new slab. This is the slowest path since it involves * a call to the page allocator and the setup of a new slab. * * Version of __slab_alloc to use when we know that interrupts are * already disabled (which is the case for bulk allocation). */ static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node, unsigned long addr, struct kmem_cache_cpu *c) { void *freelist; struct page *page; page = c->page; if (!page) goto new_slab; redo: if (unlikely(!node_match(page, node))) { int searchnode = node; if (node != NUMA_NO_NODE && !node_present_pages(node)) searchnode = node_to_mem_node(node); if (unlikely(!node_match(page, searchnode))) { stat(s, ALLOC_NODE_MISMATCH); deactivate_slab(s, page, c->freelist); c->page = NULL; c->freelist = NULL; goto new_slab; } } /* * By rights, we should be searching for a slab page that was * PFMEMALLOC but right now, we are losing the pfmemalloc * information when the page leaves the per-cpu allocator */ if (unlikely(!pfmemalloc_match(page, gfpflags))) { deactivate_slab(s, page, c->freelist); c->page = NULL; c->freelist = NULL; goto new_slab; } /* must check again c->freelist in case of cpu migration or IRQ */ freelist = c->freelist; if (freelist) goto load_freelist; freelist = get_freelist(s, page); if (!freelist) { c->page = NULL; stat(s, DEACTIVATE_BYPASS); goto new_slab; } stat(s, ALLOC_REFILL); load_freelist: /* * freelist is pointing to the list of objects to be used. * page is pointing to the page from which the objects are obtained. * That page must be frozen for per cpu allocations to work. */ VM_BUG_ON(!c->page->frozen); c->freelist = get_freepointer(s, freelist); c->tid = next_tid(c->tid); return freelist; new_slab: if (c->partial) { page = c->page = c->partial; c->partial = page->next; stat(s, CPU_PARTIAL_ALLOC); c->freelist = NULL; goto redo; } freelist = new_slab_objects(s, gfpflags, node, &c); if (unlikely(!freelist)) { slab_out_of_memory(s, gfpflags, node); return NULL; } page = c->page; if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags))) goto load_freelist; /* Only entered in the debug case */ if (kmem_cache_debug(s) && !alloc_debug_processing(s, page, freelist, addr)) goto new_slab; /* Slab failed checks. Next slab needed */ deactivate_slab(s, page, get_freepointer(s, freelist)); c->page = NULL; c->freelist = NULL; return freelist; } /* * Another one that disabled interrupt and compensates for possible * cpu changes by refetching the per cpu area pointer. */ static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node, unsigned long addr, struct kmem_cache_cpu *c) { void *p; unsigned long flags; local_irq_save(flags); #ifdef CONFIG_PREEMPT /* * We may have been preempted and rescheduled on a different * cpu before disabling interrupts. Need to reload cpu area * pointer. */ c = this_cpu_ptr(s->cpu_slab); #endif p = ___slab_alloc(s, gfpflags, node, addr, c); local_irq_restore(flags); return p; } /* * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc) * have the fastpath folded into their functions. So no function call * overhead for requests that can be satisfied on the fastpath. * * The fastpath works by first checking if the lockless freelist can be used. * If not then __slab_alloc is called for slow processing. * * Otherwise we can simply pick the next object from the lockless free list. */ static __always_inline void *slab_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node, unsigned long addr) { void *object; struct kmem_cache_cpu *c; struct page *page; unsigned long tid; s = slab_pre_alloc_hook(s, gfpflags); if (!s) return NULL; redo: /* * Must read kmem_cache cpu data via this cpu ptr. Preemption is * enabled. We may switch back and forth between cpus while * reading from one cpu area. That does not matter as long * as we end up on the original cpu again when doing the cmpxchg. * * We should guarantee that tid and kmem_cache are retrieved on * the same cpu. It could be different if CONFIG_PREEMPT so we need * to check if it is matched or not. */ do { tid = this_cpu_read(s->cpu_slab->tid); c = raw_cpu_ptr(s->cpu_slab); } while (IS_ENABLED(CONFIG_PREEMPT) && unlikely(tid != READ_ONCE(c->tid))); /* * Irqless object alloc/free algorithm used here depends on sequence * of fetching cpu_slab's data. tid should be fetched before anything * on c to guarantee that object and page associated with previous tid * won't be used with current tid. If we fetch tid first, object and * page could be one associated with next tid and our alloc/free * request will be failed. In this case, we will retry. So, no problem. */ barrier(); /* * The transaction ids are globally unique per cpu and per operation on * a per cpu queue. Thus they can be guarantee that the cmpxchg_double * occurs on the right processor and that there was no operation on the * linked list in between. */ object = c->freelist; page = c->page; if (unlikely(!object || !node_match(page, node))) { object = __slab_alloc(s, gfpflags, node, addr, c); stat(s, ALLOC_SLOWPATH); } else { void *next_object = get_freepointer_safe(s, object); /* * The cmpxchg will only match if there was no additional * operation and if we are on the right processor. * * The cmpxchg does the following atomically (without lock * semantics!) * 1. Relocate first pointer to the current per cpu area. * 2. Verify that tid and freelist have not been changed * 3. If they were not changed replace tid and freelist * * Since this is without lock semantics the protection is only * against code executing on this cpu *not* from access by * other cpus. */ if (unlikely(!this_cpu_cmpxchg_double( s->cpu_slab->freelist, s->cpu_slab->tid, object, tid, next_object, next_tid(tid)))) { note_cmpxchg_failure("slab_alloc", s, tid); goto redo; } prefetch_freepointer(s, next_object); stat(s, ALLOC_FASTPATH); } if (unlikely(gfpflags & __GFP_ZERO) && object) memset(object, 0, s->object_size); slab_post_alloc_hook(s, gfpflags, 1, &object); return object; } static __always_inline void *slab_alloc(struct kmem_cache *s, gfp_t gfpflags, unsigned long addr) { return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr); } void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags) { void *ret = slab_alloc(s, gfpflags, _RET_IP_); trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size, s->size, gfpflags); return ret; } EXPORT_SYMBOL(kmem_cache_alloc); #ifdef CONFIG_TRACING void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size) { void *ret = slab_alloc(s, gfpflags, _RET_IP_); trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags); kasan_kmalloc(s, ret, size, gfpflags); return ret; } EXPORT_SYMBOL(kmem_cache_alloc_trace); #endif #ifdef CONFIG_NUMA void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node) { void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_); trace_kmem_cache_alloc_node(_RET_IP_, ret, s->object_size, s->size, gfpflags, node); return ret; } EXPORT_SYMBOL(kmem_cache_alloc_node); #ifdef CONFIG_TRACING void *kmem_cache_alloc_node_trace(struct kmem_cache *s, gfp_t gfpflags, int node, size_t size) { void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_); trace_kmalloc_node(_RET_IP_, ret, size, s->size, gfpflags, node); kasan_kmalloc(s, ret, size, gfpflags); return ret; } EXPORT_SYMBOL(kmem_cache_alloc_node_trace); #endif #endif /* * Slow path handling. This may still be called frequently since objects * have a longer lifetime than the cpu slabs in most processing loads. * * So we still attempt to reduce cache line usage. Just take the slab * lock and free the item. If there is no additional partial page * handling required then we can return immediately. */ static void __slab_free(struct kmem_cache *s, struct page *page, void *head, void *tail, int cnt, unsigned long addr) { void *prior; int was_frozen; struct page new; unsigned long counters; struct kmem_cache_node *n = NULL; unsigned long uninitialized_var(flags); stat(s, FREE_SLOWPATH); if (kmem_cache_debug(s) && !free_debug_processing(s, page, head, tail, cnt, addr)) return; do { if (unlikely(n)) { spin_unlock_irqrestore(&n->list_lock, flags); n = NULL; } prior = page->freelist; counters = page->counters; set_freepointer(s, tail, prior); new.counters = counters; was_frozen = new.frozen; new.inuse -= cnt; if ((!new.inuse || !prior) && !was_frozen) { if (kmem_cache_has_cpu_partial(s) && !prior) { /* * Slab was on no list before and will be * partially empty * We can defer the list move and instead * freeze it. */ new.frozen = 1; } else { /* Needs to be taken off a list */ n = get_node(s, page_to_nid(page)); /* * Speculatively acquire the list_lock. * If the cmpxchg does not succeed then we may * drop the list_lock without any processing. * * Otherwise the list_lock will synchronize with * other processors updating the list of slabs. */ spin_lock_irqsave(&n->list_lock, flags); } } } while (!cmpxchg_double_slab(s, page, prior, counters, head, new.counters, "__slab_free")); if (likely(!n)) { /* * If we just froze the page then put it onto the * per cpu partial list. */ if (new.frozen && !was_frozen) { put_cpu_partial(s, page, 1); stat(s, CPU_PARTIAL_FREE); } /* * The list lock was not taken therefore no list * activity can be necessary. */ if (was_frozen) stat(s, FREE_FROZEN); return; } if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) goto slab_empty; /* * Objects left in the slab. If it was not on the partial list before * then add it. */ if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) { if (kmem_cache_debug(s)) remove_full(s, n, page); add_partial(n, page, DEACTIVATE_TO_TAIL); stat(s, FREE_ADD_PARTIAL); } spin_unlock_irqrestore(&n->list_lock, flags); return; slab_empty: if (prior) { /* * Slab on the partial list. */ remove_partial(n, page); stat(s, FREE_REMOVE_PARTIAL); } else { /* Slab must be on the full list */ remove_full(s, n, page); } spin_unlock_irqrestore(&n->list_lock, flags); stat(s, FREE_SLAB); discard_slab(s, page); } /* * Fastpath with forced inlining to produce a kfree and kmem_cache_free that * can perform fastpath freeing without additional function calls. * * The fastpath is only possible if we are freeing to the current cpu slab * of this processor. This typically the case if we have just allocated * the item before. * * If fastpath is not possible then fall back to __slab_free where we deal * with all sorts of special processing. * * Bulk free of a freelist with several objects (all pointing to the * same page) possible by specifying head and tail ptr, plus objects * count (cnt). Bulk free indicated by tail pointer being set. */ static __always_inline void do_slab_free(struct kmem_cache *s, struct page *page, void *head, void *tail, int cnt, unsigned long addr) { void *tail_obj = tail ? : head; struct kmem_cache_cpu *c; unsigned long tid; redo: /* * Determine the currently cpus per cpu slab. * The cpu may change afterward. However that does not matter since * data is retrieved via this pointer. If we are on the same cpu * during the cmpxchg then the free will succeed. */ do { tid = this_cpu_read(s->cpu_slab->tid); c = raw_cpu_ptr(s->cpu_slab); } while (IS_ENABLED(CONFIG_PREEMPT) && unlikely(tid != READ_ONCE(c->tid))); /* Same with comment on barrier() in slab_alloc_node() */ barrier(); if (likely(page == c->page)) { set_freepointer(s, tail_obj, c->freelist); if (unlikely(!this_cpu_cmpxchg_double( s->cpu_slab->freelist, s->cpu_slab->tid, c->freelist, tid, head, next_tid(tid)))) { note_cmpxchg_failure("slab_free", s, tid); goto redo; } stat(s, FREE_FASTPATH); } else __slab_free(s, page, head, tail_obj, cnt, addr); } static __always_inline void slab_free(struct kmem_cache *s, struct page *page, void *head, void *tail, int cnt, unsigned long addr) { slab_free_freelist_hook(s, head, tail); /* * slab_free_freelist_hook() could have put the items into quarantine. * If so, no need to free them. */ if (s->flags & SLAB_KASAN && !(s->flags & SLAB_TYPESAFE_BY_RCU)) return; do_slab_free(s, page, head, tail, cnt, addr); } #ifdef CONFIG_KASAN void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr) { do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr); } #endif void kmem_cache_free(struct kmem_cache *s, void *x) { s = cache_from_obj(s, x); if (!s) return; slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_); trace_kmem_cache_free(_RET_IP_, x); } EXPORT_SYMBOL(kmem_cache_free); struct detached_freelist { struct page *page; void *tail; void *freelist; int cnt; struct kmem_cache *s; }; /* * This function progressively scans the array with free objects (with * a limited look ahead) and extract objects belonging to the same * page. It builds a detached freelist directly within the given * page/objects. This can happen without any need for * synchronization, because the objects are owned by running process. * The freelist is build up as a single linked list in the objects. * The idea is, that this detached freelist can then be bulk * transferred to the real freelist(s), but only requiring a single * synchronization primitive. Look ahead in the array is limited due * to performance reasons. */ static inline int build_detached_freelist(struct kmem_cache *s, size_t size, void **p, struct detached_freelist *df) { size_t first_skipped_index = 0; int lookahead = 3; void *object; struct page *page; /* Always re-init detached_freelist */ df->page = NULL; do { object = p[--size]; /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */ } while (!object && size); if (!object) return 0; page = virt_to_head_page(object); if (!s) { /* Handle kalloc'ed objects */ if (unlikely(!PageSlab(page))) { BUG_ON(!PageCompound(page)); kfree_hook(object); __free_pages(page, compound_order(page)); p[size] = NULL; /* mark object processed */ return size; } /* Derive kmem_cache from object */ df->s = page->slab_cache; } else { df->s = cache_from_obj(s, object); /* Support for memcg */ } /* Start new detached freelist */ df->page = page; set_freepointer(df->s, object, NULL); df->tail = object; df->freelist = object; p[size] = NULL; /* mark object processed */ df->cnt = 1; while (size) { object = p[--size]; if (!object) continue; /* Skip processed objects */ /* df->page is always set at this point */ if (df->page == virt_to_head_page(object)) { /* Opportunity build freelist */ set_freepointer(df->s, object, df->freelist); df->freelist = object; df->cnt++; p[size] = NULL; /* mark object processed */ continue; } /* Limit look ahead search */ if (!--lookahead) break; if (!first_skipped_index) first_skipped_index = size + 1; } return first_skipped_index; } /* Note that interrupts must be enabled when calling this function. */ void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p) { if (WARN_ON(!size)) return; do { struct detached_freelist df; size = build_detached_freelist(s, size, p, &df); if (!df.page) continue; slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_); } while (likely(size)); } EXPORT_SYMBOL(kmem_cache_free_bulk); /* Note that interrupts must be enabled when calling this function. */ int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size, void **p) { struct kmem_cache_cpu *c; int i; /* memcg and kmem_cache debug support */ s = slab_pre_alloc_hook(s, flags); if (unlikely(!s)) return false; /* * Drain objects in the per cpu slab, while disabling local * IRQs, which protects against PREEMPT and interrupts * handlers invoking normal fastpath. */ local_irq_disable(); c = this_cpu_ptr(s->cpu_slab); for (i = 0; i < size; i++) { void *object = c->freelist; if (unlikely(!object)) { /* * Invoking slow path likely have side-effect * of re-populating per CPU c->freelist */ p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE, _RET_IP_, c); if (unlikely(!p[i])) goto error; c = this_cpu_ptr(s->cpu_slab); continue; /* goto for-loop */ } c->freelist = get_freepointer(s, object); p[i] = object; } c->tid = next_tid(c->tid); local_irq_enable(); /* Clear memory outside IRQ disabled fastpath loop */ if (unlikely(flags & __GFP_ZERO)) { int j; for (j = 0; j < i; j++) memset(p[j], 0, s->object_size); } /* memcg and kmem_cache debug support */ slab_post_alloc_hook(s, flags, size, p); return i; error: local_irq_enable(); slab_post_alloc_hook(s, flags, i, p); __kmem_cache_free_bulk(s, i, p); return 0; } EXPORT_SYMBOL(kmem_cache_alloc_bulk); /* * Object placement in a slab is made very easy because we always start at * offset 0. If we tune the size of the object to the alignment then we can * get the required alignment by putting one properly sized object after * another. * * Notice that the allocation order determines the sizes of the per cpu * caches. Each processor has always one slab available for allocations. * Increasing the allocation order reduces the number of times that slabs * must be moved on and off the partial lists and is therefore a factor in * locking overhead. */ /* * Mininum / Maximum order of slab pages. This influences locking overhead * and slab fragmentation. A higher order reduces the number of partial slabs * and increases the number of allocations possible without having to * take the list_lock. */ static int slub_min_order; static int slub_max_order = PAGE_ALLOC_COSTLY_ORDER; static int slub_min_objects; /* * Calculate the order of allocation given an slab object size. * * The order of allocation has significant impact on performance and other * system components. Generally order 0 allocations should be preferred since * order 0 does not cause fragmentation in the page allocator. Larger objects * be problematic to put into order 0 slabs because there may be too much * unused space left. We go to a higher order if more than 1/16th of the slab * would be wasted. * * In order to reach satisfactory performance we must ensure that a minimum * number of objects is in one slab. Otherwise we may generate too much * activity on the partial lists which requires taking the list_lock. This is * less a concern for large slabs though which are rarely used. * * slub_max_order specifies the order where we begin to stop considering the * number of objects in a slab as critical. If we reach slub_max_order then * we try to keep the page order as low as possible. So we accept more waste * of space in favor of a small page order. * * Higher order allocations also allow the placement of more objects in a * slab and thereby reduce object handling overhead. If the user has * requested a higher mininum order then we start with that one instead of * the smallest order which will fit the object. */ static inline int slab_order(int size, int min_objects, int max_order, int fract_leftover, int reserved) { int order; int rem; int min_order = slub_min_order; if (order_objects(min_order, size, reserved) > MAX_OBJS_PER_PAGE) return get_order(size * MAX_OBJS_PER_PAGE) - 1; for (order = max(min_order, get_order(min_objects * size + reserved)); order <= max_order; order++) { unsigned long slab_size = PAGE_SIZE << order; rem = (slab_size - reserved) % size; if (rem <= slab_size / fract_leftover) break; } return order; } static inline int calculate_order(int size, int reserved) { int order; int min_objects; int fraction; int max_objects; /* * Attempt to find best configuration for a slab. This * works by first attempting to generate a layout with * the best configuration and backing off gradually. * * First we increase the acceptable waste in a slab. Then * we reduce the minimum objects required in a slab. */ min_objects = slub_min_objects; if (!min_objects) min_objects = 4 * (fls(nr_cpu_ids) + 1); max_objects = order_objects(slub_max_order, size, reserved); min_objects = min(min_objects, max_objects); while (min_objects > 1) { fraction = 16; while (fraction >= 4) { order = slab_order(size, min_objects, slub_max_order, fraction, reserved); if (order <= slub_max_order) return order; fraction /= 2; } min_objects--; } /* * We were unable to place multiple objects in a slab. Now * lets see if we can place a single object there. */ order = slab_order(size, 1, slub_max_order, 1, reserved); if (order <= slub_max_order) return order; /* * Doh this slab cannot be placed using slub_max_order. */ order = slab_order(size, 1, MAX_ORDER, 1, reserved); if (order < MAX_ORDER) return order; return -ENOSYS; } static void init_kmem_cache_node(struct kmem_cache_node *n) { n->nr_partial = 0; spin_lock_init(&n->list_lock); INIT_LIST_HEAD(&n->partial); #ifdef CONFIG_SLUB_DEBUG atomic_long_set(&n->nr_slabs, 0); atomic_long_set(&n->total_objects, 0); INIT_LIST_HEAD(&n->full); #endif } static inline int alloc_kmem_cache_cpus(struct kmem_cache *s) { BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE < KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu)); /* * Must align to double word boundary for the double cmpxchg * instructions to work; see __pcpu_double_call_return_bool(). */ s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu), 2 * sizeof(void *)); if (!s->cpu_slab) return 0; init_kmem_cache_cpus(s); return 1; } static struct kmem_cache *kmem_cache_node; /* * No kmalloc_node yet so do it by hand. We know that this is the first * slab on the node for this slabcache. There are no concurrent accesses * possible. * * Note that this function only works on the kmem_cache_node * when allocating for the kmem_cache_node. This is used for bootstrapping * memory on a fresh node that has no slab structures yet. */ static void early_kmem_cache_node_alloc(int node) { struct page *page; struct kmem_cache_node *n; BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node)); page = new_slab(kmem_cache_node, GFP_NOWAIT, node); BUG_ON(!page); if (page_to_nid(page) != node) { pr_err("SLUB: Unable to allocate memory from node %d\n", node); pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n"); } n = page->freelist; BUG_ON(!n); page->freelist = get_freepointer(kmem_cache_node, n); page->inuse = 1; page->frozen = 0; kmem_cache_node->node[node] = n; #ifdef CONFIG_SLUB_DEBUG init_object(kmem_cache_node, n, SLUB_RED_ACTIVE); init_tracking(kmem_cache_node, n); #endif kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node), GFP_KERNEL); init_kmem_cache_node(n); inc_slabs_node(kmem_cache_node, node, page->objects); /* * No locks need to be taken here as it has just been * initialized and there is no concurrent access. */ __add_partial(n, page, DEACTIVATE_TO_HEAD); } static void free_kmem_cache_nodes(struct kmem_cache *s) { int node; struct kmem_cache_node *n; for_each_kmem_cache_node(s, node, n) { kmem_cache_free(kmem_cache_node, n); s->node[node] = NULL; } } void __kmem_cache_release(struct kmem_cache *s) { cache_random_seq_destroy(s); free_percpu(s->cpu_slab); free_kmem_cache_nodes(s); } static int init_kmem_cache_nodes(struct kmem_cache *s) { int node; for_each_node_state(node, N_NORMAL_MEMORY) { struct kmem_cache_node *n; if (slab_state == DOWN) { early_kmem_cache_node_alloc(node); continue; } n = kmem_cache_alloc_node(kmem_cache_node, GFP_KERNEL, node); if (!n) { free_kmem_cache_nodes(s); return 0; } s->node[node] = n; init_kmem_cache_node(n); } return 1; } static void set_min_partial(struct kmem_cache *s, unsigned long min) { if (min < MIN_PARTIAL) min = MIN_PARTIAL; else if (min > MAX_PARTIAL) min = MAX_PARTIAL; s->min_partial = min; } /* * calculate_sizes() determines the order and the distribution of data within * a slab object. */ static int calculate_sizes(struct kmem_cache *s, int forced_order) { unsigned long flags = s->flags; size_t size = s->object_size; int order; /* * Round up object size to the next word boundary. We can only * place the free pointer at word boundaries and this determines * the possible location of the free pointer. */ size = ALIGN(size, sizeof(void *)); #ifdef CONFIG_SLUB_DEBUG /* * Determine if we can poison the object itself. If the user of * the slab may touch the object after free or before allocation * then we should never poison the object itself. */ if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) && !s->ctor) s->flags |= __OBJECT_POISON; else s->flags &= ~__OBJECT_POISON; /* * If we are Redzoning then check if there is some space between the * end of the object and the free pointer. If not then add an * additional word to have some bytes to store Redzone information. */ if ((flags & SLAB_RED_ZONE) && size == s->object_size) size += sizeof(void *); #endif /* * With that we have determined the number of bytes in actual use * by the object. This is the potential offset to the free pointer. */ s->inuse = size; if (((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) || s->ctor)) { /* * Relocate free pointer after the object if it is not * permitted to overwrite the first word of the object on * kmem_cache_free. * * This is the case if we do RCU, have a constructor or * destructor or are poisoning the objects. */ s->offset = size; size += sizeof(void *); } #ifdef CONFIG_SLUB_DEBUG if (flags & SLAB_STORE_USER) /* * Need to store information about allocs and frees after * the object. */ size += 2 * sizeof(struct track); #endif kasan_cache_create(s, &size, &s->flags); #ifdef CONFIG_SLUB_DEBUG if (flags & SLAB_RED_ZONE) { /* * Add some empty padding so that we can catch * overwrites from earlier objects rather than let * tracking information or the free pointer be * corrupted if a user writes before the start * of the object. */ size += sizeof(void *); s->red_left_pad = sizeof(void *); s->red_left_pad = ALIGN(s->red_left_pad, s->align); size += s->red_left_pad; } #endif /* * SLUB stores one object immediately after another beginning from * offset 0. In order to align the objects we have to simply size * each object to conform to the alignment. */ size = ALIGN(size, s->align); s->size = size; if (forced_order >= 0) order = forced_order; else order = calculate_order(size, s->reserved); if (order < 0) return 0; s->allocflags = 0; if (order) s->allocflags |= __GFP_COMP; if (s->flags & SLAB_CACHE_DMA) s->allocflags |= GFP_DMA; if (s->flags & SLAB_RECLAIM_ACCOUNT) s->allocflags |= __GFP_RECLAIMABLE; /* * Determine the number of objects per slab */ s->oo = oo_make(order, size, s->reserved); s->min = oo_make(get_order(size), size, s->reserved); if (oo_objects(s->oo) > oo_objects(s->max)) s->max = s->oo; return !!oo_objects(s->oo); } static int kmem_cache_open(struct kmem_cache *s, unsigned long flags) { s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor); s->reserved = 0; if (need_reserve_slab_rcu && (s->flags & SLAB_TYPESAFE_BY_RCU)) s->reserved = sizeof(struct rcu_head); if (!calculate_sizes(s, -1)) goto error; if (disable_higher_order_debug) { /* * Disable debugging flags that store metadata if the min slab * order increased. */ if (get_order(s->size) > get_order(s->object_size)) { s->flags &= ~DEBUG_METADATA_FLAGS; s->offset = 0; if (!calculate_sizes(s, -1)) goto error; } } #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \ defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE) if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0) /* Enable fast mode */ s->flags |= __CMPXCHG_DOUBLE; #endif /* * The larger the object size is, the more pages we want on the partial * list to avoid pounding the page allocator excessively. */ set_min_partial(s, ilog2(s->size) / 2); /* * cpu_partial determined the maximum number of objects kept in the * per cpu partial lists of a processor. * * Per cpu partial lists mainly contain slabs that just have one * object freed. If they are used for allocation then they can be * filled up again with minimal effort. The slab will never hit the * per node partial lists and therefore no locking will be required. * * This setting also determines * * A) The number of objects from per cpu partial slabs dumped to the * per node list when we reach the limit. * B) The number of objects in cpu partial slabs to extract from the * per node list when we run out of per cpu objects. We only fetch * 50% to keep some capacity around for frees. */ if (!kmem_cache_has_cpu_partial(s)) s->cpu_partial = 0; else if (s->size >= PAGE_SIZE) s->cpu_partial = 2; else if (s->size >= 1024) s->cpu_partial = 6; else if (s->size >= 256) s->cpu_partial = 13; else s->cpu_partial = 30; #ifdef CONFIG_NUMA s->remote_node_defrag_ratio = 1000; #endif /* Initialize the pre-computed randomized freelist if slab is up */ if (slab_state >= UP) { if (init_cache_random_seq(s)) goto error; } if (!init_kmem_cache_nodes(s)) goto error; if (alloc_kmem_cache_cpus(s)) return 0; free_kmem_cache_nodes(s); error: if (flags & SLAB_PANIC) panic("Cannot create slab %s size=%lu realsize=%u order=%u offset=%u flags=%lx\n", s->name, (unsigned long)s->size, s->size, oo_order(s->oo), s->offset, flags); return -EINVAL; } static void list_slab_objects(struct kmem_cache *s, struct page *page, const char *text) { #ifdef CONFIG_SLUB_DEBUG void *addr = page_address(page); void *p; unsigned long *map = kzalloc(BITS_TO_LONGS(page->objects) * sizeof(long), GFP_ATOMIC); if (!map) return; slab_err(s, page, text, s->name); slab_lock(page); get_map(s, page, map); for_each_object(p, s, addr, page->objects) { if (!test_bit(slab_index(p, s, addr), map)) { pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr); print_tracking(s, p); } } slab_unlock(page); kfree(map); #endif } /* * Attempt to free all partial slabs on a node. * This is called from __kmem_cache_shutdown(). We must take list_lock * because sysfs file might still access partial list after the shutdowning. */ static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n) { LIST_HEAD(discard); struct page *page, *h; BUG_ON(irqs_disabled()); spin_lock_irq(&n->list_lock); list_for_each_entry_safe(page, h, &n->partial, lru) { if (!page->inuse) { remove_partial(n, page); list_add(&page->lru, &discard); } else { list_slab_objects(s, page, "Objects remaining in %s on __kmem_cache_shutdown()"); } } spin_unlock_irq(&n->list_lock); list_for_each_entry_safe(page, h, &discard, lru) discard_slab(s, page); } /* * Release all resources used by a slab cache. */ int __kmem_cache_shutdown(struct kmem_cache *s) { int node; struct kmem_cache_node *n; flush_all(s); /* Attempt to free all objects */ for_each_kmem_cache_node(s, node, n) { free_partial(s, n); if (n->nr_partial || slabs_node(s, node)) return 1; } sysfs_slab_remove(s); return 0; } /******************************************************************** * Kmalloc subsystem *******************************************************************/ static int __init setup_slub_min_order(char *str) { get_option(&str, &slub_min_order); return 1; } __setup("slub_min_order=", setup_slub_min_order); static int __init setup_slub_max_order(char *str) { get_option(&str, &slub_max_order); slub_max_order = min(slub_max_order, MAX_ORDER - 1); return 1; } __setup("slub_max_order=", setup_slub_max_order); static int __init setup_slub_min_objects(char *str) { get_option(&str, &slub_min_objects); return 1; } __setup("slub_min_objects=", setup_slub_min_objects); void *__kmalloc(size_t size, gfp_t flags) { struct kmem_cache *s; void *ret; if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) return kmalloc_large(size, flags); s = kmalloc_slab(size, flags); if (unlikely(ZERO_OR_NULL_PTR(s))) return s; ret = slab_alloc(s, flags, _RET_IP_); trace_kmalloc(_RET_IP_, ret, size, s->size, flags); kasan_kmalloc(s, ret, size, flags); return ret; } EXPORT_SYMBOL(__kmalloc); #ifdef CONFIG_NUMA static void *kmalloc_large_node(size_t size, gfp_t flags, int node) { struct page *page; void *ptr = NULL; flags |= __GFP_COMP | __GFP_NOTRACK; page = alloc_pages_node(node, flags, get_order(size)); if (page) ptr = page_address(page); kmalloc_large_node_hook(ptr, size, flags); return ptr; } void *__kmalloc_node(size_t size, gfp_t flags, int node) { struct kmem_cache *s; void *ret; if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) { ret = kmalloc_large_node(size, flags, node); trace_kmalloc_node(_RET_IP_, ret, size, PAGE_SIZE << get_order(size), flags, node); return ret; } s = kmalloc_slab(size, flags); if (unlikely(ZERO_OR_NULL_PTR(s))) return s; ret = slab_alloc_node(s, flags, node, _RET_IP_); trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node); kasan_kmalloc(s, ret, size, flags); return ret; } EXPORT_SYMBOL(__kmalloc_node); #endif #ifdef CONFIG_HARDENED_USERCOPY /* * Rejects objects that are incorrectly sized. * * Returns NULL if check passes, otherwise const char * to name of cache * to indicate an error. */ const char *__check_heap_object(const void *ptr, unsigned long n, struct page *page) { struct kmem_cache *s; unsigned long offset; size_t object_size; /* Find object and usable object size. */ s = page->slab_cache; object_size = slab_ksize(s); /* Reject impossible pointers. */ if (ptr < page_address(page)) return s->name; /* Find offset within object. */ offset = (ptr - page_address(page)) % s->size; /* Adjust for redzone and reject if within the redzone. */ if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) { if (offset < s->red_left_pad) return s->name; offset -= s->red_left_pad; } /* Allow address range falling entirely within object size. */ if (offset <= object_size && n <= object_size - offset) return NULL; return s->name; } #endif /* CONFIG_HARDENED_USERCOPY */ static size_t __ksize(const void *object) { struct page *page; if (unlikely(object == ZERO_SIZE_PTR)) return 0; page = virt_to_head_page(object); if (unlikely(!PageSlab(page))) { WARN_ON(!PageCompound(page)); return PAGE_SIZE << compound_order(page); } return slab_ksize(page->slab_cache); } size_t ksize(const void *object) { size_t size = __ksize(object); /* We assume that ksize callers could use whole allocated area, * so we need to unpoison this area. */ kasan_unpoison_shadow(object, size); return size; } EXPORT_SYMBOL(ksize); void kfree(const void *x) { struct page *page; void *object = (void *)x; trace_kfree(_RET_IP_, x); if (unlikely(ZERO_OR_NULL_PTR(x))) return; page = virt_to_head_page(x); if (unlikely(!PageSlab(page))) { BUG_ON(!PageCompound(page)); kfree_hook(x); __free_pages(page, compound_order(page)); return; } slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_); } EXPORT_SYMBOL(kfree); #define SHRINK_PROMOTE_MAX 32 /* * kmem_cache_shrink discards empty slabs and promotes the slabs filled * up most to the head of the partial lists. New allocations will then * fill those up and thus they can be removed from the partial lists. * * The slabs with the least items are placed last. This results in them * being allocated from last increasing the chance that the last objects * are freed in them. */ int __kmem_cache_shrink(struct kmem_cache *s) { int node; int i; struct kmem_cache_node *n; struct page *page; struct page *t; struct list_head discard; struct list_head promote[SHRINK_PROMOTE_MAX]; unsigned long flags; int ret = 0; flush_all(s); for_each_kmem_cache_node(s, node, n) { INIT_LIST_HEAD(&discard); for (i = 0; i < SHRINK_PROMOTE_MAX; i++) INIT_LIST_HEAD(promote + i); spin_lock_irqsave(&n->list_lock, flags); /* * Build lists of slabs to discard or promote. * * Note that concurrent frees may occur while we hold the * list_lock. page->inuse here is the upper limit. */ list_for_each_entry_safe(page, t, &n->partial, lru) { int free = page->objects - page->inuse; /* Do not reread page->inuse */ barrier(); /* We do not keep full slabs on the list */ BUG_ON(free <= 0); if (free == page->objects) { list_move(&page->lru, &discard); n->nr_partial--; } else if (free <= SHRINK_PROMOTE_MAX) list_move(&page->lru, promote + free - 1); } /* * Promote the slabs filled up most to the head of the * partial list. */ for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--) list_splice(promote + i, &n->partial); spin_unlock_irqrestore(&n->list_lock, flags); /* Release empty slabs */ list_for_each_entry_safe(page, t, &discard, lru) discard_slab(s, page); if (slabs_node(s, node)) ret = 1; } return ret; } #ifdef CONFIG_MEMCG static void kmemcg_cache_deact_after_rcu(struct kmem_cache *s) { /* * Called with all the locks held after a sched RCU grace period. * Even if @s becomes empty after shrinking, we can't know that @s * doesn't have allocations already in-flight and thus can't * destroy @s until the associated memcg is released. * * However, let's remove the sysfs files for empty caches here. * Each cache has a lot of interface files which aren't * particularly useful for empty draining caches; otherwise, we can * easily end up with millions of unnecessary sysfs files on * systems which have a lot of memory and transient cgroups. */ if (!__kmem_cache_shrink(s)) sysfs_slab_remove(s); } void __kmemcg_cache_deactivate(struct kmem_cache *s) { /* * Disable empty slabs caching. Used to avoid pinning offline * memory cgroups by kmem pages that can be freed. */ s->cpu_partial = 0; s->min_partial = 0; /* * s->cpu_partial is checked locklessly (see put_cpu_partial), so * we have to make sure the change is visible before shrinking. */ slab_deactivate_memcg_cache_rcu_sched(s, kmemcg_cache_deact_after_rcu); } #endif static int slab_mem_going_offline_callback(void *arg) { struct kmem_cache *s; mutex_lock(&slab_mutex); list_for_each_entry(s, &slab_caches, list) __kmem_cache_shrink(s); mutex_unlock(&slab_mutex); return 0; } static void slab_mem_offline_callback(void *arg) { struct kmem_cache_node *n; struct kmem_cache *s; struct memory_notify *marg = arg; int offline_node; offline_node = marg->status_change_nid_normal; /* * If the node still has available memory. we need kmem_cache_node * for it yet. */ if (offline_node < 0) return; mutex_lock(&slab_mutex); list_for_each_entry(s, &slab_caches, list) { n = get_node(s, offline_node); if (n) { /* * if n->nr_slabs > 0, slabs still exist on the node * that is going down. We were unable to free them, * and offline_pages() function shouldn't call this * callback. So, we must fail. */ BUG_ON(slabs_node(s, offline_node)); s->node[offline_node] = NULL; kmem_cache_free(kmem_cache_node, n); } } mutex_unlock(&slab_mutex); } static int slab_mem_going_online_callback(void *arg) { struct kmem_cache_node *n; struct kmem_cache *s; struct memory_notify *marg = arg; int nid = marg->status_change_nid_normal; int ret = 0; /* * If the node's memory is already available, then kmem_cache_node is * already created. Nothing to do. */ if (nid < 0) return 0; /* * We are bringing a node online. No memory is available yet. We must * allocate a kmem_cache_node structure in order to bring the node * online. */ mutex_lock(&slab_mutex); list_for_each_entry(s, &slab_caches, list) { /* * XXX: kmem_cache_alloc_node will fallback to other nodes * since memory is not yet available from the node that * is brought up. */ n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL); if (!n) { ret = -ENOMEM; goto out; } init_kmem_cache_node(n); s->node[nid] = n; } out: mutex_unlock(&slab_mutex); return ret; } static int slab_memory_callback(struct notifier_block *self, unsigned long action, void *arg) { int ret = 0; switch (action) { case MEM_GOING_ONLINE: ret = slab_mem_going_online_callback(arg); break; case MEM_GOING_OFFLINE: ret = slab_mem_going_offline_callback(arg); break; case MEM_OFFLINE: case MEM_CANCEL_ONLINE: slab_mem_offline_callback(arg); break; case MEM_ONLINE: case MEM_CANCEL_OFFLINE: break; } if (ret) ret = notifier_from_errno(ret); else ret = NOTIFY_OK; return ret; } static struct notifier_block slab_memory_callback_nb = { .notifier_call = slab_memory_callback, .priority = SLAB_CALLBACK_PRI, }; /******************************************************************** * Basic setup of slabs *******************************************************************/ /* * Used for early kmem_cache structures that were allocated using * the page allocator. Allocate them properly then fix up the pointers * that may be pointing to the wrong kmem_cache structure. */ static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache) { int node; struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT); struct kmem_cache_node *n; memcpy(s, static_cache, kmem_cache->object_size); /* * This runs very early, and only the boot processor is supposed to be * up. Even if it weren't true, IRQs are not up so we couldn't fire * IPIs around. */ __flush_cpu_slab(s, smp_processor_id()); for_each_kmem_cache_node(s, node, n) { struct page *p; list_for_each_entry(p, &n->partial, lru) p->slab_cache = s; #ifdef CONFIG_SLUB_DEBUG list_for_each_entry(p, &n->full, lru) p->slab_cache = s; #endif } slab_init_memcg_params(s); list_add(&s->list, &slab_caches); memcg_link_cache(s); return s; } void __init kmem_cache_init(void) { static __initdata struct kmem_cache boot_kmem_cache, boot_kmem_cache_node; if (debug_guardpage_minorder()) slub_max_order = 0; kmem_cache_node = &boot_kmem_cache_node; kmem_cache = &boot_kmem_cache; create_boot_cache(kmem_cache_node, "kmem_cache_node", sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN); register_hotmemory_notifier(&slab_memory_callback_nb); /* Able to allocate the per node structures */ slab_state = PARTIAL; create_boot_cache(kmem_cache, "kmem_cache", offsetof(struct kmem_cache, node) + nr_node_ids * sizeof(struct kmem_cache_node *), SLAB_HWCACHE_ALIGN); kmem_cache = bootstrap(&boot_kmem_cache); /* * Allocate kmem_cache_node properly from the kmem_cache slab. * kmem_cache_node is separately allocated so no need to * update any list pointers. */ kmem_cache_node = bootstrap(&boot_kmem_cache_node); /* Now we can use the kmem_cache to allocate kmalloc slabs */ setup_kmalloc_cache_index_table(); create_kmalloc_caches(0); /* Setup random freelists for each cache */ init_freelist_randomization(); cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL, slub_cpu_dead); pr_info("SLUB: HWalign=%d, Order=%d-%d, MinObjects=%d, CPUs=%d, Nodes=%d\n", cache_line_size(), slub_min_order, slub_max_order, slub_min_objects, nr_cpu_ids, nr_node_ids); } void __init kmem_cache_init_late(void) { } struct kmem_cache * __kmem_cache_alias(const char *name, size_t size, size_t align, unsigned long flags, void (*ctor)(void *)) { struct kmem_cache *s, *c; s = find_mergeable(size, align, flags, name, ctor); if (s) { s->refcount++; /* * Adjust the object sizes so that we clear * the complete object on kzalloc. */ s->object_size = max(s->object_size, (int)size); s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *))); for_each_memcg_cache(c, s) { c->object_size = s->object_size; c->inuse = max_t(int, c->inuse, ALIGN(size, sizeof(void *))); } if (sysfs_slab_alias(s, name)) { s->refcount--; s = NULL; } } return s; } int __kmem_cache_create(struct kmem_cache *s, unsigned long flags) { int err; err = kmem_cache_open(s, flags); if (err) return err; /* Mutex is not taken during early boot */ if (slab_state <= UP) return 0; memcg_propagate_slab_attrs(s); err = sysfs_slab_add(s); if (err) __kmem_cache_release(s); return err; } void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller) { struct kmem_cache *s; void *ret; if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) return kmalloc_large(size, gfpflags); s = kmalloc_slab(size, gfpflags); if (unlikely(ZERO_OR_NULL_PTR(s))) return s; ret = slab_alloc(s, gfpflags, caller); /* Honor the call site pointer we received. */ trace_kmalloc(caller, ret, size, s->size, gfpflags); return ret; } #ifdef CONFIG_NUMA void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags, int node, unsigned long caller) { struct kmem_cache *s; void *ret; if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) { ret = kmalloc_large_node(size, gfpflags, node); trace_kmalloc_node(caller, ret, size, PAGE_SIZE << get_order(size), gfpflags, node); return ret; } s = kmalloc_slab(size, gfpflags); if (unlikely(ZERO_OR_NULL_PTR(s))) return s; ret = slab_alloc_node(s, gfpflags, node, caller); /* Honor the call site pointer we received. */ trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node); return ret; } #endif #ifdef CONFIG_SYSFS static int count_inuse(struct page *page) { return page->inuse; } static int count_total(struct page *page) { return page->objects; } #endif #ifdef CONFIG_SLUB_DEBUG static int validate_slab(struct kmem_cache *s, struct page *page, unsigned long *map) { void *p; void *addr = page_address(page); if (!check_slab(s, page) || !on_freelist(s, page, NULL)) return 0; /* Now we know that a valid freelist exists */ bitmap_zero(map, page->objects); get_map(s, page, map); for_each_object(p, s, addr, page->objects) { if (test_bit(slab_index(p, s, addr), map)) if (!check_object(s, page, p, SLUB_RED_INACTIVE)) return 0; } for_each_object(p, s, addr, page->objects) if (!test_bit(slab_index(p, s, addr), map)) if (!check_object(s, page, p, SLUB_RED_ACTIVE)) return 0; return 1; } static void validate_slab_slab(struct kmem_cache *s, struct page *page, unsigned long *map) { slab_lock(page); validate_slab(s, page, map); slab_unlock(page); } static int validate_slab_node(struct kmem_cache *s, struct kmem_cache_node *n, unsigned long *map) { unsigned long count = 0; struct page *page; unsigned long flags; spin_lock_irqsave(&n->list_lock, flags); list_for_each_entry(page, &n->partial, lru) { validate_slab_slab(s, page, map); count++; } if (count != n->nr_partial) pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n", s->name, count, n->nr_partial); if (!(s->flags & SLAB_STORE_USER)) goto out; list_for_each_entry(page, &n->full, lru) { validate_slab_slab(s, page, map); count++; } if (count != atomic_long_read(&n->nr_slabs)) pr_err("SLUB: %s %ld slabs counted but counter=%ld\n", s->name, count, atomic_long_read(&n->nr_slabs)); out: spin_unlock_irqrestore(&n->list_lock, flags); return count; } static long validate_slab_cache(struct kmem_cache *s) { int node; unsigned long count = 0; unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) * sizeof(unsigned long), GFP_KERNEL); struct kmem_cache_node *n; if (!map) return -ENOMEM; flush_all(s); for_each_kmem_cache_node(s, node, n) count += validate_slab_node(s, n, map); kfree(map); return count; } /* * Generate lists of code addresses where slabcache objects are allocated * and freed. */ struct location { unsigned long count; unsigned long addr; long long sum_time; long min_time; long max_time; long min_pid; long max_pid; DECLARE_BITMAP(cpus, NR_CPUS); nodemask_t nodes; }; struct loc_track { unsigned long max; unsigned long count; struct location *loc; }; static void free_loc_track(struct loc_track *t) { if (t->max) free_pages((unsigned long)t->loc, get_order(sizeof(struct location) * t->max)); } static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags) { struct location *l; int order; order = get_order(sizeof(struct location) * max); l = (void *)__get_free_pages(flags, order); if (!l) return 0; if (t->count) { memcpy(l, t->loc, sizeof(struct location) * t->count); free_loc_track(t); } t->max = max; t->loc = l; return 1; } static int add_location(struct loc_track *t, struct kmem_cache *s, const struct track *track) { long start, end, pos; struct location *l; unsigned long caddr; unsigned long age = jiffies - track->when; start = -1; end = t->count; for ( ; ; ) { pos = start + (end - start + 1) / 2; /* * There is nothing at "end". If we end up there * we need to add something to before end. */ if (pos == end) break; caddr = t->loc[pos].addr; if (track->addr == caddr) { l = &t->loc[pos]; l->count++; if (track->when) { l->sum_time += age; if (age < l->min_time) l->min_time = age; if (age > l->max_time) l->max_time = age; if (track->pid < l->min_pid) l->min_pid = track->pid; if (track->pid > l->max_pid) l->max_pid = track->pid; cpumask_set_cpu(track->cpu, to_cpumask(l->cpus)); } node_set(page_to_nid(virt_to_page(track)), l->nodes); return 1; } if (track->addr < caddr) end = pos; else start = pos; } /* * Not found. Insert new tracking element. */ if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC)) return 0; l = t->loc + pos; if (pos < t->count) memmove(l + 1, l, (t->count - pos) * sizeof(struct location)); t->count++; l->count = 1; l->addr = track->addr; l->sum_time = age; l->min_time = age; l->max_time = age; l->min_pid = track->pid; l->max_pid = track->pid; cpumask_clear(to_cpumask(l->cpus)); cpumask_set_cpu(track->cpu, to_cpumask(l->cpus)); nodes_clear(l->nodes); node_set(page_to_nid(virt_to_page(track)), l->nodes); return 1; } static void process_slab(struct loc_track *t, struct kmem_cache *s, struct page *page, enum track_item alloc, unsigned long *map) { void *addr = page_address(page); void *p; bitmap_zero(map, page->objects); get_map(s, page, map); for_each_object(p, s, addr, page->objects) if (!test_bit(slab_index(p, s, addr), map)) add_location(t, s, get_track(s, p, alloc)); } static int list_locations(struct kmem_cache *s, char *buf, enum track_item alloc) { int len = 0; unsigned long i; struct loc_track t = { 0, 0, NULL }; int node; unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) * sizeof(unsigned long), GFP_KERNEL); struct kmem_cache_node *n; if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location), GFP_TEMPORARY)) { kfree(map); return sprintf(buf, "Out of memory\n"); } /* Push back cpu slabs */ flush_all(s); for_each_kmem_cache_node(s, node, n) { unsigned long flags; struct page *page; if (!atomic_long_read(&n->nr_slabs)) continue; spin_lock_irqsave(&n->list_lock, flags); list_for_each_entry(page, &n->partial, lru) process_slab(&t, s, page, alloc, map); list_for_each_entry(page, &n->full, lru) process_slab(&t, s, page, alloc, map); spin_unlock_irqrestore(&n->list_lock, flags); } for (i = 0; i < t.count; i++) { struct location *l = &t.loc[i]; if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100) break; len += sprintf(buf + len, "%7ld ", l->count); if (l->addr) len += sprintf(buf + len, "%pS", (void *)l->addr); else len += sprintf(buf + len, "<not-available>"); if (l->sum_time != l->min_time) { len += sprintf(buf + len, " age=%ld/%ld/%ld", l->min_time, (long)div_u64(l->sum_time, l->count), l->max_time); } else len += sprintf(buf + len, " age=%ld", l->min_time); if (l->min_pid != l->max_pid) len += sprintf(buf + len, " pid=%ld-%ld", l->min_pid, l->max_pid); else len += sprintf(buf + len, " pid=%ld", l->min_pid); if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)) && len < PAGE_SIZE - 60) len += scnprintf(buf + len, PAGE_SIZE - len - 50, " cpus=%*pbl", cpumask_pr_args(to_cpumask(l->cpus))); if (nr_online_nodes > 1 && !nodes_empty(l->nodes) && len < PAGE_SIZE - 60) len += scnprintf(buf + len, PAGE_SIZE - len - 50, " nodes=%*pbl", nodemask_pr_args(&l->nodes)); len += sprintf(buf + len, "\n"); } free_loc_track(&t); kfree(map); if (!t.count) len += sprintf(buf, "No data\n"); return len; } #endif #ifdef SLUB_RESILIENCY_TEST static void __init resiliency_test(void) { u8 *p; BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10); pr_err("SLUB resiliency testing\n"); pr_err("-----------------------\n"); pr_err("A. Corruption after allocation\n"); p = kzalloc(16, GFP_KERNEL); p[16] = 0x12; pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n", p + 16); validate_slab_cache(kmalloc_caches[4]); /* Hmmm... The next two are dangerous */ p = kzalloc(32, GFP_KERNEL); p[32 + sizeof(void *)] = 0x34; pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n", p); pr_err("If allocated object is overwritten then not detectable\n\n"); validate_slab_cache(kmalloc_caches[5]); p = kzalloc(64, GFP_KERNEL); p += 64 + (get_cycles() & 0xff) * sizeof(void *); *p = 0x56; pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n", p); pr_err("If allocated object is overwritten then not detectable\n\n"); validate_slab_cache(kmalloc_caches[6]); pr_err("\nB. Corruption after free\n"); p = kzalloc(128, GFP_KERNEL); kfree(p); *p = 0x78; pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p); validate_slab_cache(kmalloc_caches[7]); p = kzalloc(256, GFP_KERNEL); kfree(p); p[50] = 0x9a; pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p); validate_slab_cache(kmalloc_caches[8]); p = kzalloc(512, GFP_KERNEL); kfree(p); p[512] = 0xab; pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p); validate_slab_cache(kmalloc_caches[9]); } #else #ifdef CONFIG_SYSFS static void resiliency_test(void) {}; #endif #endif #ifdef CONFIG_SYSFS enum slab_stat_type { SL_ALL, /* All slabs */ SL_PARTIAL, /* Only partially allocated slabs */ SL_CPU, /* Only slabs used for cpu caches */ SL_OBJECTS, /* Determine allocated objects not slabs */ SL_TOTAL /* Determine object capacity not slabs */ }; #define SO_ALL (1 << SL_ALL) #define SO_PARTIAL (1 << SL_PARTIAL) #define SO_CPU (1 << SL_CPU) #define SO_OBJECTS (1 << SL_OBJECTS) #define SO_TOTAL (1 << SL_TOTAL) #ifdef CONFIG_MEMCG static bool memcg_sysfs_enabled = IS_ENABLED(CONFIG_SLUB_MEMCG_SYSFS_ON); static int __init setup_slub_memcg_sysfs(char *str) { int v; if (get_option(&str, &v) > 0) memcg_sysfs_enabled = v; return 1; } __setup("slub_memcg_sysfs=", setup_slub_memcg_sysfs); #endif static ssize_t show_slab_objects(struct kmem_cache *s, char *buf, unsigned long flags) { unsigned long total = 0; int node; int x; unsigned long *nodes; nodes = kzalloc(sizeof(unsigned long) * nr_node_ids, GFP_KERNEL); if (!nodes) return -ENOMEM; if (flags & SO_CPU) { int cpu; for_each_possible_cpu(cpu) { struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu); int node; struct page *page; page = READ_ONCE(c->page); if (!page) continue; node = page_to_nid(page); if (flags & SO_TOTAL) x = page->objects; else if (flags & SO_OBJECTS) x = page->inuse; else x = 1; total += x; nodes[node] += x; page = READ_ONCE(c->partial); if (page) { node = page_to_nid(page); if (flags & SO_TOTAL) WARN_ON_ONCE(1); else if (flags & SO_OBJECTS) WARN_ON_ONCE(1); else x = page->pages; total += x; nodes[node] += x; } } } get_online_mems(); #ifdef CONFIG_SLUB_DEBUG if (flags & SO_ALL) { struct kmem_cache_node *n; for_each_kmem_cache_node(s, node, n) { if (flags & SO_TOTAL) x = atomic_long_read(&n->total_objects); else if (flags & SO_OBJECTS) x = atomic_long_read(&n->total_objects) - count_partial(n, count_free); else x = atomic_long_read(&n->nr_slabs); total += x; nodes[node] += x; } } else #endif if (flags & SO_PARTIAL) { struct kmem_cache_node *n; for_each_kmem_cache_node(s, node, n) { if (flags & SO_TOTAL) x = count_partial(n, count_total); else if (flags & SO_OBJECTS) x = count_partial(n, count_inuse); else x = n->nr_partial; total += x; nodes[node] += x; } } x = sprintf(buf, "%lu", total); #ifdef CONFIG_NUMA for (node = 0; node < nr_node_ids; node++) if (nodes[node]) x += sprintf(buf + x, " N%d=%lu", node, nodes[node]); #endif put_online_mems(); kfree(nodes); return x + sprintf(buf + x, "\n"); } #ifdef CONFIG_SLUB_DEBUG static int any_slab_objects(struct kmem_cache *s) { int node; struct kmem_cache_node *n; for_each_kmem_cache_node(s, node, n) if (atomic_long_read(&n->total_objects)) return 1; return 0; } #endif #define to_slab_attr(n) container_of(n, struct slab_attribute, attr) #define to_slab(n) container_of(n, struct kmem_cache, kobj) struct slab_attribute { struct attribute attr; ssize_t (*show)(struct kmem_cache *s, char *buf); ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count); }; #define SLAB_ATTR_RO(_name) \ static struct slab_attribute _name##_attr = \ __ATTR(_name, 0400, _name##_show, NULL) #define SLAB_ATTR(_name) \ static struct slab_attribute _name##_attr = \ __ATTR(_name, 0600, _name##_show, _name##_store) static ssize_t slab_size_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", s->size); } SLAB_ATTR_RO(slab_size); static ssize_t align_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", s->align); } SLAB_ATTR_RO(align); static ssize_t object_size_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", s->object_size); } SLAB_ATTR_RO(object_size); static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", oo_objects(s->oo)); } SLAB_ATTR_RO(objs_per_slab); static ssize_t order_store(struct kmem_cache *s, const char *buf, size_t length) { unsigned long order; int err; err = kstrtoul(buf, 10, &order); if (err) return err; if (order > slub_max_order || order < slub_min_order) return -EINVAL; calculate_sizes(s, order); return length; } static ssize_t order_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", oo_order(s->oo)); } SLAB_ATTR(order); static ssize_t min_partial_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%lu\n", s->min_partial); } static ssize_t min_partial_store(struct kmem_cache *s, const char *buf, size_t length) { unsigned long min; int err; err = kstrtoul(buf, 10, &min); if (err) return err; set_min_partial(s, min); return length; } SLAB_ATTR(min_partial); static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%u\n", s->cpu_partial); } static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf, size_t length) { unsigned long objects; int err; err = kstrtoul(buf, 10, &objects); if (err) return err; if (objects && !kmem_cache_has_cpu_partial(s)) return -EINVAL; s->cpu_partial = objects; flush_all(s); return length; } SLAB_ATTR(cpu_partial); static ssize_t ctor_show(struct kmem_cache *s, char *buf) { if (!s->ctor) return 0; return sprintf(buf, "%pS\n", s->ctor); } SLAB_ATTR_RO(ctor); static ssize_t aliases_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1); } SLAB_ATTR_RO(aliases); static ssize_t partial_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_PARTIAL); } SLAB_ATTR_RO(partial); static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_CPU); } SLAB_ATTR_RO(cpu_slabs); static ssize_t objects_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS); } SLAB_ATTR_RO(objects); static ssize_t objects_partial_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS); } SLAB_ATTR_RO(objects_partial); static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf) { int objects = 0; int pages = 0; int cpu; int len; for_each_online_cpu(cpu) { struct page *page = per_cpu_ptr(s->cpu_slab, cpu)->partial; if (page) { pages += page->pages; objects += page->pobjects; } } len = sprintf(buf, "%d(%d)", objects, pages); #ifdef CONFIG_SMP for_each_online_cpu(cpu) { struct page *page = per_cpu_ptr(s->cpu_slab, cpu) ->partial; if (page && len < PAGE_SIZE - 20) len += sprintf(buf + len, " C%d=%d(%d)", cpu, page->pobjects, page->pages); } #endif return len + sprintf(buf + len, "\n"); } SLAB_ATTR_RO(slabs_cpu_partial); static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT)); } static ssize_t reclaim_account_store(struct kmem_cache *s, const char *buf, size_t length) { s->flags &= ~SLAB_RECLAIM_ACCOUNT; if (buf[0] == '1') s->flags |= SLAB_RECLAIM_ACCOUNT; return length; } SLAB_ATTR(reclaim_account); static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN)); } SLAB_ATTR_RO(hwcache_align); #ifdef CONFIG_ZONE_DMA static ssize_t cache_dma_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA)); } SLAB_ATTR_RO(cache_dma); #endif static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU)); } SLAB_ATTR_RO(destroy_by_rcu); static ssize_t reserved_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", s->reserved); } SLAB_ATTR_RO(reserved); #ifdef CONFIG_SLUB_DEBUG static ssize_t slabs_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_ALL); } SLAB_ATTR_RO(slabs); static ssize_t total_objects_show(struct kmem_cache *s, char *buf) { return show_slab_objects(s, buf, SO_ALL|SO_TOTAL); } SLAB_ATTR_RO(total_objects); static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS)); } static ssize_t sanity_checks_store(struct kmem_cache *s, const char *buf, size_t length) { s->flags &= ~SLAB_CONSISTENCY_CHECKS; if (buf[0] == '1') { s->flags &= ~__CMPXCHG_DOUBLE; s->flags |= SLAB_CONSISTENCY_CHECKS; } return length; } SLAB_ATTR(sanity_checks); static ssize_t trace_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE)); } static ssize_t trace_store(struct kmem_cache *s, const char *buf, size_t length) { /* * Tracing a merged cache is going to give confusing results * as well as cause other issues like converting a mergeable * cache into an umergeable one. */ if (s->refcount > 1) return -EINVAL; s->flags &= ~SLAB_TRACE; if (buf[0] == '1') { s->flags &= ~__CMPXCHG_DOUBLE; s->flags |= SLAB_TRACE; } return length; } SLAB_ATTR(trace); static ssize_t red_zone_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE)); } static ssize_t red_zone_store(struct kmem_cache *s, const char *buf, size_t length) { if (any_slab_objects(s)) return -EBUSY; s->flags &= ~SLAB_RED_ZONE; if (buf[0] == '1') { s->flags |= SLAB_RED_ZONE; } calculate_sizes(s, -1); return length; } SLAB_ATTR(red_zone); static ssize_t poison_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON)); } static ssize_t poison_store(struct kmem_cache *s, const char *buf, size_t length) { if (any_slab_objects(s)) return -EBUSY; s->flags &= ~SLAB_POISON; if (buf[0] == '1') { s->flags |= SLAB_POISON; } calculate_sizes(s, -1); return length; } SLAB_ATTR(poison); static ssize_t store_user_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER)); } static ssize_t store_user_store(struct kmem_cache *s, const char *buf, size_t length) { if (any_slab_objects(s)) return -EBUSY; s->flags &= ~SLAB_STORE_USER; if (buf[0] == '1') { s->flags &= ~__CMPXCHG_DOUBLE; s->flags |= SLAB_STORE_USER; } calculate_sizes(s, -1); return length; } SLAB_ATTR(store_user); static ssize_t validate_show(struct kmem_cache *s, char *buf) { return 0; } static ssize_t validate_store(struct kmem_cache *s, const char *buf, size_t length) { int ret = -EINVAL; if (buf[0] == '1') { ret = validate_slab_cache(s); if (ret >= 0) ret = length; } return ret; } SLAB_ATTR(validate); static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf) { if (!(s->flags & SLAB_STORE_USER)) return -ENOSYS; return list_locations(s, buf, TRACK_ALLOC); } SLAB_ATTR_RO(alloc_calls); static ssize_t free_calls_show(struct kmem_cache *s, char *buf) { if (!(s->flags & SLAB_STORE_USER)) return -ENOSYS; return list_locations(s, buf, TRACK_FREE); } SLAB_ATTR_RO(free_calls); #endif /* CONFIG_SLUB_DEBUG */ #ifdef CONFIG_FAILSLAB static ssize_t failslab_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB)); } static ssize_t failslab_store(struct kmem_cache *s, const char *buf, size_t length) { if (s->refcount > 1) return -EINVAL; s->flags &= ~SLAB_FAILSLAB; if (buf[0] == '1') s->flags |= SLAB_FAILSLAB; return length; } SLAB_ATTR(failslab); #endif static ssize_t shrink_show(struct kmem_cache *s, char *buf) { return 0; } static ssize_t shrink_store(struct kmem_cache *s, const char *buf, size_t length) { if (buf[0] == '1') kmem_cache_shrink(s); else return -EINVAL; return length; } SLAB_ATTR(shrink); #ifdef CONFIG_NUMA static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf) { return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10); } static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s, const char *buf, size_t length) { unsigned long ratio; int err; err = kstrtoul(buf, 10, &ratio); if (err) return err; if (ratio <= 100) s->remote_node_defrag_ratio = ratio * 10; return length; } SLAB_ATTR(remote_node_defrag_ratio); #endif #ifdef CONFIG_SLUB_STATS static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si) { unsigned long sum = 0; int cpu; int len; int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL); if (!data) return -ENOMEM; for_each_online_cpu(cpu) { unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si]; data[cpu] = x; sum += x; } len = sprintf(buf, "%lu", sum); #ifdef CONFIG_SMP for_each_online_cpu(cpu) { if (data[cpu] && len < PAGE_SIZE - 20) len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]); } #endif kfree(data); return len + sprintf(buf + len, "\n"); } static void clear_stat(struct kmem_cache *s, enum stat_item si) { int cpu; for_each_online_cpu(cpu) per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0; } #define STAT_ATTR(si, text) \ static ssize_t text##_show(struct kmem_cache *s, char *buf) \ { \ return show_stat(s, buf, si); \ } \ static ssize_t text##_store(struct kmem_cache *s, \ const char *buf, size_t length) \ { \ if (buf[0] != '0') \ return -EINVAL; \ clear_stat(s, si); \ return length; \ } \ SLAB_ATTR(text); \ STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath); STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath); STAT_ATTR(FREE_FASTPATH, free_fastpath); STAT_ATTR(FREE_SLOWPATH, free_slowpath); STAT_ATTR(FREE_FROZEN, free_frozen); STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial); STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial); STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial); STAT_ATTR(ALLOC_SLAB, alloc_slab); STAT_ATTR(ALLOC_REFILL, alloc_refill); STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch); STAT_ATTR(FREE_SLAB, free_slab); STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush); STAT_ATTR(DEACTIVATE_FULL, deactivate_full); STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty); STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head); STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail); STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees); STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass); STAT_ATTR(ORDER_FALLBACK, order_fallback); STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail); STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail); STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc); STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free); STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node); STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain); #endif static struct attribute *slab_attrs[] = { &slab_size_attr.attr, &object_size_attr.attr, &objs_per_slab_attr.attr, &order_attr.attr, &min_partial_attr.attr, &cpu_partial_attr.attr, &objects_attr.attr, &objects_partial_attr.attr, &partial_attr.attr, &cpu_slabs_attr.attr, &ctor_attr.attr, &aliases_attr.attr, &align_attr.attr, &hwcache_align_attr.attr, &reclaim_account_attr.attr, &destroy_by_rcu_attr.attr, &shrink_attr.attr, &reserved_attr.attr, &slabs_cpu_partial_attr.attr, #ifdef CONFIG_SLUB_DEBUG &total_objects_attr.attr, &slabs_attr.attr, &sanity_checks_attr.attr, &trace_attr.attr, &red_zone_attr.attr, &poison_attr.attr, &store_user_attr.attr, &validate_attr.attr, &alloc_calls_attr.attr, &free_calls_attr.attr, #endif #ifdef CONFIG_ZONE_DMA &cache_dma_attr.attr, #endif #ifdef CONFIG_NUMA &remote_node_defrag_ratio_attr.attr, #endif #ifdef CONFIG_SLUB_STATS &alloc_fastpath_attr.attr, &alloc_slowpath_attr.attr, &free_fastpath_attr.attr, &free_slowpath_attr.attr, &free_frozen_attr.attr, &free_add_partial_attr.attr, &free_remove_partial_attr.attr, &alloc_from_partial_attr.attr, &alloc_slab_attr.attr, &alloc_refill_attr.attr, &alloc_node_mismatch_attr.attr, &free_slab_attr.attr, &cpuslab_flush_attr.attr, &deactivate_full_attr.attr, &deactivate_empty_attr.attr, &deactivate_to_head_attr.attr, &deactivate_to_tail_attr.attr, &deactivate_remote_frees_attr.attr, &deactivate_bypass_attr.attr, &order_fallback_attr.attr, &cmpxchg_double_fail_attr.attr, &cmpxchg_double_cpu_fail_attr.attr, &cpu_partial_alloc_attr.attr, &cpu_partial_free_attr.attr, &cpu_partial_node_attr.attr, &cpu_partial_drain_attr.attr, #endif #ifdef CONFIG_FAILSLAB &failslab_attr.attr, #endif NULL }; static struct attribute_group slab_attr_group = { .attrs = slab_attrs, }; static ssize_t slab_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct slab_attribute *attribute; struct kmem_cache *s; int err; attribute = to_slab_attr(attr); s = to_slab(kobj); if (!attribute->show) return -EIO; err = attribute->show(s, buf); return err; } static ssize_t slab_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t len) { struct slab_attribute *attribute; struct kmem_cache *s; int err; attribute = to_slab_attr(attr); s = to_slab(kobj); if (!attribute->store) return -EIO; err = attribute->store(s, buf, len); #ifdef CONFIG_MEMCG if (slab_state >= FULL && err >= 0 && is_root_cache(s)) { struct kmem_cache *c; mutex_lock(&slab_mutex); if (s->max_attr_size < len) s->max_attr_size = len; /* * This is a best effort propagation, so this function's return * value will be determined by the parent cache only. This is * basically because not all attributes will have a well * defined semantics for rollbacks - most of the actions will * have permanent effects. * * Returning the error value of any of the children that fail * is not 100 % defined, in the sense that users seeing the * error code won't be able to know anything about the state of * the cache. * * Only returning the error code for the parent cache at least * has well defined semantics. The cache being written to * directly either failed or succeeded, in which case we loop * through the descendants with best-effort propagation. */ for_each_memcg_cache(c, s) attribute->store(c, buf, len); mutex_unlock(&slab_mutex); } #endif return err; } static void memcg_propagate_slab_attrs(struct kmem_cache *s) { #ifdef CONFIG_MEMCG int i; char *buffer = NULL; struct kmem_cache *root_cache; if (is_root_cache(s)) return; root_cache = s->memcg_params.root_cache; /* * This mean this cache had no attribute written. Therefore, no point * in copying default values around */ if (!root_cache->max_attr_size) return; for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) { char mbuf[64]; char *buf; struct slab_attribute *attr = to_slab_attr(slab_attrs[i]); ssize_t len; if (!attr || !attr->store || !attr->show) continue; /* * It is really bad that we have to allocate here, so we will * do it only as a fallback. If we actually allocate, though, * we can just use the allocated buffer until the end. * * Most of the slub attributes will tend to be very small in * size, but sysfs allows buffers up to a page, so they can * theoretically happen. */ if (buffer) buf = buffer; else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf)) buf = mbuf; else { buffer = (char *) get_zeroed_page(GFP_KERNEL); if (WARN_ON(!buffer)) continue; buf = buffer; } len = attr->show(root_cache, buf); if (len > 0) attr->store(s, buf, len); } if (buffer) free_page((unsigned long)buffer); #endif } static void kmem_cache_release(struct kobject *k) { slab_kmem_cache_release(to_slab(k)); } static const struct sysfs_ops slab_sysfs_ops = { .show = slab_attr_show, .store = slab_attr_store, }; static struct kobj_type slab_ktype = { .sysfs_ops = &slab_sysfs_ops, .release = kmem_cache_release, }; static int uevent_filter(struct kset *kset, struct kobject *kobj) { struct kobj_type *ktype = get_ktype(kobj); if (ktype == &slab_ktype) return 1; return 0; } static const struct kset_uevent_ops slab_uevent_ops = { .filter = uevent_filter, }; static struct kset *slab_kset; static inline struct kset *cache_kset(struct kmem_cache *s) { #ifdef CONFIG_MEMCG if (!is_root_cache(s)) return s->memcg_params.root_cache->memcg_kset; #endif return slab_kset; } #define ID_STR_LENGTH 64 /* Create a unique string id for a slab cache: * * Format :[flags-]size */ static char *create_unique_id(struct kmem_cache *s) { char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL); char *p = name; BUG_ON(!name); *p++ = ':'; /* * First flags affecting slabcache operations. We will only * get here for aliasable slabs so we do not need to support * too many flags. The flags here must cover all flags that * are matched during merging to guarantee that the id is * unique. */ if (s->flags & SLAB_CACHE_DMA) *p++ = 'd'; if (s->flags & SLAB_RECLAIM_ACCOUNT) *p++ = 'a'; if (s->flags & SLAB_CONSISTENCY_CHECKS) *p++ = 'F'; if (!(s->flags & SLAB_NOTRACK)) *p++ = 't'; if (s->flags & SLAB_ACCOUNT) *p++ = 'A'; if (p != name + 1) *p++ = '-'; p += sprintf(p, "%07d", s->size); BUG_ON(p > name + ID_STR_LENGTH - 1); return name; } static void sysfs_slab_remove_workfn(struct work_struct *work) { struct kmem_cache *s = container_of(work, struct kmem_cache, kobj_remove_work); if (!s->kobj.state_in_sysfs) /* * For a memcg cache, this may be called during * deactivation and again on shutdown. Remove only once. * A cache is never shut down before deactivation is * complete, so no need to worry about synchronization. */ goto out; #ifdef CONFIG_MEMCG kset_unregister(s->memcg_kset); #endif kobject_uevent(&s->kobj, KOBJ_REMOVE); kobject_del(&s->kobj); out: kobject_put(&s->kobj); } static int sysfs_slab_add(struct kmem_cache *s) { int err; const char *name; struct kset *kset = cache_kset(s); int unmergeable = slab_unmergeable(s); INIT_WORK(&s->kobj_remove_work, sysfs_slab_remove_workfn); if (!kset) { kobject_init(&s->kobj, &slab_ktype); return 0; } if (unmergeable) { /* * Slabcache can never be merged so we can use the name proper. * This is typically the case for debug situations. In that * case we can catch duplicate names easily. */ sysfs_remove_link(&slab_kset->kobj, s->name); name = s->name; } else { /* * Create a unique name for the slab as a target * for the symlinks. */ name = create_unique_id(s); } s->kobj.kset = kset; err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name); if (err) goto out; err = sysfs_create_group(&s->kobj, &slab_attr_group); if (err) goto out_del_kobj; #ifdef CONFIG_MEMCG if (is_root_cache(s) && memcg_sysfs_enabled) { s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj); if (!s->memcg_kset) { err = -ENOMEM; goto out_del_kobj; } } #endif kobject_uevent(&s->kobj, KOBJ_ADD); if (!unmergeable) { /* Setup first alias */ sysfs_slab_alias(s, s->name); } out: if (!unmergeable) kfree(name); return err; out_del_kobj: kobject_del(&s->kobj); goto out; } static void sysfs_slab_remove(struct kmem_cache *s) { if (slab_state < FULL) /* * Sysfs has not been setup yet so no need to remove the * cache from sysfs. */ return; kobject_get(&s->kobj); schedule_work(&s->kobj_remove_work); } void sysfs_slab_release(struct kmem_cache *s) { if (slab_state >= FULL) kobject_put(&s->kobj); } /* * Need to buffer aliases during bootup until sysfs becomes * available lest we lose that information. */ struct saved_alias { struct kmem_cache *s; const char *name; struct saved_alias *next; }; static struct saved_alias *alias_list; static int sysfs_slab_alias(struct kmem_cache *s, const char *name) { struct saved_alias *al; if (slab_state == FULL) { /* * If we have a leftover link then remove it. */ sysfs_remove_link(&slab_kset->kobj, name); return sysfs_create_link(&slab_kset->kobj, &s->kobj, name); } al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL); if (!al) return -ENOMEM; al->s = s; al->name = name; al->next = alias_list; alias_list = al; return 0; } static int __init slab_sysfs_init(void) { struct kmem_cache *s; int err; mutex_lock(&slab_mutex); slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj); if (!slab_kset) { mutex_unlock(&slab_mutex); pr_err("Cannot register slab subsystem.\n"); return -ENOSYS; } slab_state = FULL; list_for_each_entry(s, &slab_caches, list) { err = sysfs_slab_add(s); if (err) pr_err("SLUB: Unable to add boot slab %s to sysfs\n", s->name); } while (alias_list) { struct saved_alias *al = alias_list; alias_list = alias_list->next; err = sysfs_slab_alias(al->s, al->name); if (err) pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n", al->name); kfree(al); } mutex_unlock(&slab_mutex); resiliency_test(); return 0; } __initcall(slab_sysfs_init); #endif /* CONFIG_SYSFS */ /* * The /proc/slabinfo ABI */ #ifdef CONFIG_SLABINFO void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo) { unsigned long nr_slabs = 0; unsigned long nr_objs = 0; unsigned long nr_free = 0; int node; struct kmem_cache_node *n; for_each_kmem_cache_node(s, node, n) { nr_slabs += node_nr_slabs(n); nr_objs += node_nr_objs(n); nr_free += count_partial(n, count_free); } sinfo->active_objs = nr_objs - nr_free; sinfo->num_objs = nr_objs; sinfo->active_slabs = nr_slabs; sinfo->num_slabs = nr_slabs; sinfo->objects_per_slab = oo_objects(s->oo); sinfo->cache_order = oo_order(s->oo); } void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s) { } ssize_t slabinfo_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { return -EIO; } #endif /* CONFIG_SLABINFO */
gpl-3.0
GeorgiaTechMSSE/ReliableMD
cxsc-2-5-4/src-original/rts/s_ins1.c
4
2768
/* ** CXSC is a C++ library for eXtended Scientific Computing (V 2.5.4) ** ** Copyright (C) 1990-2000 Institut fuer Angewandte Mathematik, ** Universitaet Karlsruhe, Germany ** (C) 2000-2014 Wiss. Rechnen/Softwaretechnologie ** Universitaet Wuppertal, Germany ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Library General Public ** License as published by the Free Software Foundation; either ** version 2 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Library General Public License for more details. ** ** You should have received a copy of the GNU Library General Public ** License along with this library; if not, write to the Free ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* CVS $Id: s_ins1.c,v 1.21 2014/01/30 17:24:14 cxsc Exp $ */ /****************************************************************/ /* */ /* Filename : s_ins1.c */ /* */ /* Entries : a_VOID s_ins1(s,e) */ /* s_etof s; */ /* a_intg e; */ /* */ /* Arguments : s = set */ /* e = element */ /* */ /* Function value : pointer to updated set */ /* */ /* Description : Add element e to set s. */ /* */ /****************************************************************/ #ifndef ALL_IN_ONE #ifdef AIX #include "/u/p88c/runtime/o_defs.h" #else #include "o_defs.h" #endif #define local #endif #ifdef LINT_ARGS local a_VOID s_ins1(s_etof s,a_intg e) #else local a_VOID s_ins1(s,e) s_etof s; a_intg e; #endif { E_TPUSH("s_ins1") if (e<0 || e>s_SIZE*BITS_PER_CHAR-1) e_trap(INDEX_RANGE,2,E_TINT+E_TEXT(14),&e); else s[e/BITS_PER_CHAR] |=(a_char)( (((unsigned char)0x80)>>(e%BITS_PER_CHAR))); E_TPOPP("s_ins1") return((a_VOID)&s[0]); }
gpl-3.0
nixdog/toxcore
testing/tox_shell.c
4
4332
/* Tox Shell * * Proof of concept ssh like server software using tox. * * Command line arguments are the ip, port and public_key of a node (for bootstrapping). * * EX: ./test 127.0.0.1 33445 CDCFD319CE3460824B33BE58FD86B8941C9585181D8FBD7C79C5721D7C2E9F7C * * * Copyright (C) 2014 Tox project All Rights Reserved. * * This file is part of Tox. * * Tox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tox. If not, see <http://www.gnu.org/licenses/>. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "../toxcore/tox.h" #include "misc_tools.c" #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) #include <util.h> #elif defined(__FreeBSD__) #include <libutil.h> #else #include <pty.h> #endif #include <unistd.h> #include <fcntl.h> #define c_sleep(x) usleep(1000*x) void print_online(Tox *tox, int friendnumber, uint8_t status, void *userdata) { if (status == 1) printf("\nOther went online.\n"); else printf("\nOther went offline.\n"); } void print_message(Tox *tox, int friendnumber, const uint8_t *string, uint16_t length, void *userdata) { int master = *((int *)userdata); write(master, string, length); write(master, "\n", 1); } int main(int argc, char *argv[]) { uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */ int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); if (argvoffset < 0) exit(1); /* with optional --ipvx, now it can be 1-4 arguments... */ if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) { printf("Usage: %s [--ipv4|--ipv6] ip port public_key (of the DHT bootstrap node)\n", argv[0]); exit(0); } int *master = malloc(sizeof(int)); int ret = forkpty(master, NULL, NULL, NULL); if (ret == -1) { printf("fork failed\n"); return 1; } if (ret == 0) { execl("/bin/sh", "sh", NULL); return 0; } int flags = fcntl(*master, F_GETFL, 0); int r = fcntl(*master, F_SETFL, flags | O_NONBLOCK); if (r < 0) { printf("error setting flags\n"); } Tox *tox = tox_new(0); tox_callback_connection_status(tox, print_online, NULL); tox_callback_friend_message(tox, print_message, master); uint16_t port = atoi(argv[argvoffset + 2]); unsigned char *binary_string = hex_string_to_bin(argv[argvoffset + 3]); int res = tox_bootstrap_from_address(tox, argv[argvoffset + 1], port, binary_string); free(binary_string); if (!res) { printf("Failed to convert \"%s\" into an IP address. Exiting...\n", argv[argvoffset + 1]); exit(1); } uint8_t address[TOX_FRIEND_ADDRESS_SIZE]; tox_get_address(tox, address); uint32_t i; for (i = 0; i < TOX_FRIEND_ADDRESS_SIZE; i++) { printf("%02X", address[i]); } char temp_id[128]; printf("\nEnter the address of the other id you want to sync with (38 bytes HEX format):\n"); if (scanf("%s", temp_id) != 1) { return 1; } uint8_t *bin_id = hex_string_to_bin(temp_id); int num = tox_add_friend(tox, bin_id, (uint8_t *)"Install Gentoo", sizeof("Install Gentoo")); free(bin_id); if (num < 0) { printf("\nSomething went wrong when adding friend.\n"); return 1; } uint8_t notconnected = 1; while (1) { if (tox_isconnected(tox) && notconnected) { printf("\nDHT connected.\n"); notconnected = 0; } while (tox_get_friend_connection_status(tox, num) == 1) { uint8_t buf[TOX_MAX_MESSAGE_LENGTH]; ret = read(*master, buf, sizeof(buf)); if (ret <= 0) break; tox_send_message(tox, num, buf, ret); } tox_do(tox); c_sleep(1); } return 0; }
gpl-3.0
usbxyz/CAN-Bootloader
firmware/stm32f103/app/Libraries/STM32L1xx_StdPeriph_Driver/src/stm32l1xx_spi.c
5
32719
/** ****************************************************************************** * @file stm32l1xx_spi.c * @author MCD Application Team * @version V1.0.0 * @date 31-December-2010 * @brief This file provides firmware functions to manage the following * functionalities of the Serial peripheral interface (SPI): * - Initialization and Configuration * - Data transfers functions * - Hardware CRC Calculation * - DMA transfers management * - Interrupts and flags management * * @verbatim * * The I2S feature is not implemented in STM32L1xx Ultra Low Power * Medium-density devices and will be supported in future products. * * =================================================================== * How to use this driver * =================================================================== * 1. Enable peripheral clock using RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE) * function for SPI1 or using RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE) * function for SPI2. * * 2. Enable SCK, MOSI, MISO and NSS GPIO clocks using RCC_AHBPeriphClockCmd() * function. * * 3. Peripherals alternate function: * - Connect the pin to the desired peripherals' Alternate * Function (AF) using GPIO_PinAFConfig() function * - Configure the desired pin in alternate function by: * GPIO_InitStruct->GPIO_Mode = GPIO_Mode_AF * - Select the type, pull-up/pull-down and output speed via * GPIO_PuPd, GPIO_OType and GPIO_Speed members * - Call GPIO_Init() function * * 4. Program the Polarity, Phase, First Data, Baud Rate Prescaler, Slave * Management, Peripheral Mode and CRC Polynomial values using the SPI_Init() * function. * * 5. Enable the NVIC and the corresponding interrupt using the function * SPI_ITConfig() if you need to use interrupt mode. * * 6. When using the DMA mode * - Configure the DMA using DMA_Init() function * - Active the needed channel Request using SPI_I2S_DMACmd() function * * 7. Enable the SPI using the SPI_Cmd() function. * * 8. Enable the DMA using the DMA_Cmd() function when using DMA mode. * * 9. Optionally you can enable/configure the following parameters without * re-initialization (i.e there is no need to call again SPI_Init() function): * - When bidirectional mode (SPI_Direction_1Line_Rx or SPI_Direction_1Line_Tx) * is programmed as Data direction parameter using the SPI_Init() function * it can be possible to switch between SPI_Direction_Tx or SPI_Direction_Rx * using the SPI_BiDirectionalLineConfig() function. * - When SPI_NSS_Soft is selected as Slave Select Management parameter * using the SPI_Init() function it can be possible to manage the * NSS internal signal using the SPI_NSSInternalSoftwareConfig() function. * - Reconfigure the data size using the SPI_DataSizeConfig() function * - Enable or disable the SS output using the SPI_SSOutputCmd() function * * 10. To use the CRC Hardware calculation feature refer to the Peripheral * CRC hardware Calculation subsection. * * @endverbatim * ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2010 STMicroelectronics</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_spi.h" #include "stm32l1xx_rcc.h" /** @addtogroup STM32L1xx_StdPeriph_Driver * @{ */ /** @defgroup SPI * @brief SPI driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* SPI registers Masks */ #define CR1_CLEAR_MASK ((uint16_t)0x3040) /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup SPI_Private_Functions * @{ */ /** @defgroup SPI_Group1 Initialization and Configuration functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== Initialization and Configuration functions =============================================================================== This section provides a set of functions allowing to initialize the SPI Direction, SPI Mode, SPI Data Size, SPI Polarity, SPI Phase, SPI NSS Management, SPI Baud Rate Prescaler, SPI First Bit and SPI CRC Polynomial. The SPI_Init() function follows the SPI configuration procedures for Master mode and Slave mode (details for these procedures are available in reference manual (RM0038)). @endverbatim * @{ */ /** * @brief Deinitializes the SPIx peripheral registers to their default * reset values. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @retval None */ void SPI_I2S_DeInit(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); if (SPIx == SPI1) { /* Enable SPI1 reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, ENABLE); /* Release SPI1 from reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, DISABLE); } else { if (SPIx == SPI2) { /* Enable SPI2 reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, ENABLE); /* Release SPI2 from reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, DISABLE); } } } /** * @brief Initializes the SPIx peripheral according to the specified * parameters in the SPI_InitStruct. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param SPI_InitStruct: pointer to a SPI_InitTypeDef structure that * contains the configuration information for the specified SPI peripheral. * @retval None */ void SPI_Init(SPI_TypeDef* SPIx, SPI_InitTypeDef* SPI_InitStruct) { uint16_t tmpreg = 0; /* check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Check the SPI parameters */ assert_param(IS_SPI_DIRECTION_MODE(SPI_InitStruct->SPI_Direction)); assert_param(IS_SPI_MODE(SPI_InitStruct->SPI_Mode)); assert_param(IS_SPI_DATASIZE(SPI_InitStruct->SPI_DataSize)); assert_param(IS_SPI_CPOL(SPI_InitStruct->SPI_CPOL)); assert_param(IS_SPI_CPHA(SPI_InitStruct->SPI_CPHA)); assert_param(IS_SPI_NSS(SPI_InitStruct->SPI_NSS)); assert_param(IS_SPI_BAUDRATE_PRESCALER(SPI_InitStruct->SPI_BaudRatePrescaler)); assert_param(IS_SPI_FIRST_BIT(SPI_InitStruct->SPI_FirstBit)); assert_param(IS_SPI_CRC_POLYNOMIAL(SPI_InitStruct->SPI_CRCPolynomial)); /*---------------------------- SPIx CR1 Configuration ------------------------*/ /* Get the SPIx CR1 value */ tmpreg = SPIx->CR1; /* Clear BIDIMode, BIDIOE, RxONLY, SSM, SSI, LSBFirst, BR, MSTR, CPOL and CPHA bits */ tmpreg &= CR1_CLEAR_MASK; /* Configure SPIx: direction, NSS management, first transmitted bit, BaudRate prescaler master/salve mode, CPOL and CPHA */ /* Set BIDImode, BIDIOE and RxONLY bits according to SPI_Direction value */ /* Set SSM, SSI and MSTR bits according to SPI_Mode and SPI_NSS values */ /* Set LSBFirst bit according to SPI_FirstBit value */ /* Set BR bits according to SPI_BaudRatePrescaler value */ /* Set CPOL bit according to SPI_CPOL value */ /* Set CPHA bit according to SPI_CPHA value */ tmpreg |= (uint16_t)((uint32_t)SPI_InitStruct->SPI_Direction | SPI_InitStruct->SPI_Mode | SPI_InitStruct->SPI_DataSize | SPI_InitStruct->SPI_CPOL | SPI_InitStruct->SPI_CPHA | SPI_InitStruct->SPI_NSS | SPI_InitStruct->SPI_BaudRatePrescaler | SPI_InitStruct->SPI_FirstBit); /* Write to SPIx CR1 */ SPIx->CR1 = tmpreg; /*---------------------------- SPIx CRCPOLY Configuration --------------------*/ /* Write to SPIx CRCPOLY */ SPIx->CRCPR = SPI_InitStruct->SPI_CRCPolynomial; } /** * @brief Fills each SPI_InitStruct member with its default value. * @param SPI_InitStruct : pointer to a SPI_InitTypeDef structure which will be initialized. * @retval None */ void SPI_StructInit(SPI_InitTypeDef* SPI_InitStruct) { /*--------------- Reset SPI init structure parameters values -----------------*/ /* Initialize the SPI_Direction member */ SPI_InitStruct->SPI_Direction = SPI_Direction_2Lines_FullDuplex; /* initialize the SPI_Mode member */ SPI_InitStruct->SPI_Mode = SPI_Mode_Slave; /* initialize the SPI_DataSize member */ SPI_InitStruct->SPI_DataSize = SPI_DataSize_8b; /* Initialize the SPI_CPOL member */ SPI_InitStruct->SPI_CPOL = SPI_CPOL_Low; /* Initialize the SPI_CPHA member */ SPI_InitStruct->SPI_CPHA = SPI_CPHA_1Edge; /* Initialize the SPI_NSS member */ SPI_InitStruct->SPI_NSS = SPI_NSS_Hard; /* Initialize the SPI_BaudRatePrescaler member */ SPI_InitStruct->SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; /* Initialize the SPI_FirstBit member */ SPI_InitStruct->SPI_FirstBit = SPI_FirstBit_MSB; /* Initialize the SPI_CRCPolynomial member */ SPI_InitStruct->SPI_CRCPolynomial = 7; } /** * @brief Enables or disables the specified SPI peripheral. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param NewState: new state of the SPIx peripheral. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_Cmd(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI peripheral */ SPIx->CR1 |= SPI_CR1_SPE; } else { /* Disable the selected SPI peripheral */ SPIx->CR1 &= (uint16_t)~((uint16_t)SPI_CR1_SPE); } } /** * @brief Configures the data size for the selected SPI. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param SPI_DataSize: specifies the SPI data size. * This parameter can be one of the following values: * @arg SPI_DataSize_16b: Set data frame format to 16bit * @arg SPI_DataSize_8b: Set data frame format to 8bit * @retval None */ void SPI_DataSizeConfig(SPI_TypeDef* SPIx, uint16_t SPI_DataSize) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_DATASIZE(SPI_DataSize)); /* Clear DFF bit */ SPIx->CR1 &= (uint16_t)~SPI_DataSize_16b; /* Set new DFF bit value */ SPIx->CR1 |= SPI_DataSize; } /** * @brief Selects the data transfer direction in bidirectional mode for the specified SPI. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param SPI_Direction: specifies the data transfer direction in bidirectional mode. * This parameter can be one of the following values: * @arg SPI_Direction_Tx: Selects Tx transmission direction * @arg SPI_Direction_Rx: Selects Rx receive direction * @retval None */ void SPI_BiDirectionalLineConfig(SPI_TypeDef* SPIx, uint16_t SPI_Direction) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_DIRECTION(SPI_Direction)); if (SPI_Direction == SPI_Direction_Tx) { /* Set the Tx only mode */ SPIx->CR1 |= SPI_Direction_Tx; } else { /* Set the Rx only mode */ SPIx->CR1 &= SPI_Direction_Rx; } } /** * @brief Configures internally by software the NSS pin for the selected SPI. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param SPI_NSSInternalSoft: specifies the SPI NSS internal state. * This parameter can be one of the following values: * @arg SPI_NSSInternalSoft_Set: Set NSS pin internally * @arg SPI_NSSInternalSoft_Reset: Reset NSS pin internally * @retval None */ void SPI_NSSInternalSoftwareConfig(SPI_TypeDef* SPIx, uint16_t SPI_NSSInternalSoft) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_NSS_INTERNAL(SPI_NSSInternalSoft)); if (SPI_NSSInternalSoft != SPI_NSSInternalSoft_Reset) { /* Set NSS pin internally by software */ SPIx->CR1 |= SPI_NSSInternalSoft_Set; } else { /* Reset NSS pin internally by software */ SPIx->CR1 &= SPI_NSSInternalSoft_Reset; } } /** * @brief Enables or disables the SS output for the selected SPI. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param NewState: new state of the SPIx SS output. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_SSOutputCmd(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI SS output */ SPIx->CR2 |= (uint16_t)SPI_CR2_SSOE; } else { /* Disable the selected SPI SS output */ SPIx->CR2 &= (uint16_t)~((uint16_t)SPI_CR2_SSOE); } } /** * @} */ /** @defgroup SPI_Group2 Data transfers functions * @brief Data transfers functions * @verbatim =============================================================================== Data transfers functions =============================================================================== This section provides a set of functions allowing to manage the SPI data transfers In reception, data are received and then stored into an internal Rx buffer while In transmission, data are first stored into an internal Tx buffer before being transmitted. The read access of the SPI_DR register can be done using the SPI_I2S_ReceiveData() function and returns the Rx buffered value. Whereas a write access to the SPI_DR can be done using SPI_I2S_SendData() function and stores the written data into Tx buffer. @endverbatim * @{ */ /** * @brief Returns the most recent received data by the SPIx peripheral. * @param SPIx: where x can be 1 or 2 in SPI mode. * @retval The value of the received data. */ uint16_t SPI_I2S_ReceiveData(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Return the data in the DR register */ return SPIx->DR; } /** * @brief Transmits a Data through the SPIx peripheral. * @param SPIx: where x can be 1 or 2 in SPI mode. * @param Data: Data to be transmitted. * @retval None */ void SPI_I2S_SendData(SPI_TypeDef* SPIx, uint16_t Data) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Write in the DR register the data to be sent */ SPIx->DR = Data; } /** * @} */ /** @defgroup SPI_Group3 Hardware CRC Calculation functions * @brief Hardware CRC Calculation functions * @verbatim =============================================================================== Hardware CRC Calculation functions =============================================================================== This section provides a set of functions allowing to manage the SPI CRC hardware calculation SPI communication using CRC is possible through the following procedure: 1. Program the Data direction, Polarity, Phase, First Data, Baud Rate Prescaler, Slave Management, Peripheral Mode and CRC Polynomial values using the SPI_Init() function. 2. Enable the CRC calculation using the SPI_CalculateCRC() function. 3. Enable the SPI using the SPI_Cmd() function 4. Before writing the last data to the TX buffer, set the CRCNext bit using the SPI_TransmitCRC() function to indicate that after transmission of the last data, the CRC should be transmitted. 5. After transmitting the last data, the SPI transmits the CRC. The SPI_CR1_CRCNEXT bit is reset. The CRC is also received and compared against the SPI_RXCRCR value. If the value does not match, the SPI_FLAG_CRCERR flag is set and an interrupt can be generated when the SPI_I2S_IT_ERR interrupt is enabled. Note: ----- - It is advised to don't read the calculate CRC values during the communication. - When the SPI is in slave mode, be careful to enable CRC calculation only when the clock is stable, that is, when the clock is in the steady state. If not, a wrong CRC calculation may be done. In fact, the CRC is sensitive to the SCK slave input clock as soon as CRCEN is set, and this, whatever the value of the SPE bit. - With high bitrate frequencies, be careful when transmitting the CRC. As the number of used CPU cycles has to be as low as possible in the CRC transfer phase, it is forbidden to call software functions in the CRC transmission sequence to avoid errors in the last data and CRC reception. In fact, CRCNEXT bit has to be written before the end of the transmission/reception of the last data. - For high bit rate frequencies, it is advised to use the DMA mode to avoid the degradation of the SPI speed performance due to CPU accesses impacting the SPI bandwidth. - When the STM32L15xxx are configured as slaves and the NSS hardware mode is used, the NSS pin needs to be kept low between the data phase and the CRC phase. - When the SPI is configured in slave mode with the CRC feature enabled, CRC calculation takes place even if a high level is applied on the NSS pin. This may happen for example in case of a multislave environment where the communication master addresses slaves alternately. - Between a slave deselection (high level on NSS) and a new slave selection (low level on NSS), the CRC value should be cleared on both master and slave sides in order to resynchronize the master and slave for their respective CRC calculation. To clear the CRC, follow the procedure below: 1. Disable SPI using the SPI_Cmd() function 2. Disable the CRC calculation using the SPI_CalculateCRC() function. 3. Enable the CRC calculation using the SPI_CalculateCRC() function. 4. Enable SPI using the SPI_Cmd() function. @endverbatim * @{ */ /** * @brief Enables or disables the CRC value calculation of the transferred bytes. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param NewState: new state of the SPIx CRC value calculation. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_CalculateCRC(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI CRC calculation */ SPIx->CR1 |= SPI_CR1_CRCEN; } else { /* Disable the selected SPI CRC calculation */ SPIx->CR1 &= (uint16_t)~((uint16_t)SPI_CR1_CRCEN); } } /** * @brief Transmit the SPIx CRC value. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @retval None */ void SPI_TransmitCRC(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Enable the selected SPI CRC transmission */ SPIx->CR1 |= SPI_CR1_CRCNEXT; } /** * @brief Returns the transmit or the receive CRC register value for the specified SPI. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @param SPI_CRC: specifies the CRC register to be read. * This parameter can be one of the following values: * @arg SPI_CRC_Tx: Selects Tx CRC register * @arg SPI_CRC_Rx: Selects Rx CRC register * @retval The selected CRC register value.. */ uint16_t SPI_GetCRC(SPI_TypeDef* SPIx, uint8_t SPI_CRC) { uint16_t crcreg = 0; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_CRC(SPI_CRC)); if (SPI_CRC != SPI_CRC_Rx) { /* Get the Tx CRC register */ crcreg = SPIx->TXCRCR; } else { /* Get the Rx CRC register */ crcreg = SPIx->RXCRCR; } /* Return the selected CRC register */ return crcreg; } /** * @brief Returns the CRC Polynomial register value for the specified SPI. * @param SPIx: where x can be 1 or 2 to select the SPI peripheral. * @retval The CRC Polynomial register value. */ uint16_t SPI_GetCRCPolynomial(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Return the CRC polynomial register */ return SPIx->CRCPR; } /** * @} */ /** @defgroup SPI_Group4 DMA transfers management functions * @brief DMA transfers management functions * @verbatim =============================================================================== DMA transfers management functions =============================================================================== @endverbatim * @{ */ /** * @brief Enables or disables the SPIx DMA interface. * @param SPIx: where x can be 1 or 2 in SPI mode * @param SPI_I2S_DMAReq: specifies the SPI DMA transfer request to be enabled or disabled. * This parameter can be any combination of the following values: * @arg SPI_I2S_DMAReq_Tx: Tx buffer DMA transfer request * @arg SPI_I2S_DMAReq_Rx: Rx buffer DMA transfer request * @param NewState: new state of the selected SPI DMA transfer request. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_I2S_DMACmd(SPI_TypeDef* SPIx, uint16_t SPI_I2S_DMAReq, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); assert_param(IS_SPI_I2S_DMAREQ(SPI_I2S_DMAReq)); if (NewState != DISABLE) { /* Enable the selected SPI DMA requests */ SPIx->CR2 |= SPI_I2S_DMAReq; } else { /* Disable the selected SPI DMA requests */ SPIx->CR2 &= (uint16_t)~SPI_I2S_DMAReq; } } /** * @} */ /** @defgroup SPI_Group5 Interrupts and flags management functions * @brief Interrupts and flags management functions * @verbatim =============================================================================== Interrupts and flags management functions =============================================================================== This section provides a set of functions allowing to configure the SPI Interrupts sources and check or clear the flags or pending bits status. The user should identify which mode will be used in his application to manage the communication: Polling mode, Interrupt mode or DMA mode. Polling Mode ============= In Polling Mode, the SPI communication can be managed by 6 flags: 1. SPI_I2S_FLAG_TXE : to indicate the status of the transmit buffer register 2. SPI_I2S_FLAG_RXNE : to indicate the status of the receive buffer register 3. SPI_I2S_FLAG_BSY : to indicate the state of the communication layer of the SPI. 4. SPI_FLAG_CRCERR : to indicate if a CRC Calculation error occur 5. SPI_FLAG_MODF : to indicate if a Mode Fault error occur 6. SPI_I2S_FLAG_OVR : to indicate if an Overrun error occur Note: Do not use the BSY flag to handle each data transmission or reception. ----- It is better to use the TXE and RXNE flags instead. In this Mode it is advised to use the following functions: - FlagStatus SPI_I2S_GetFlagStatus(SPI_TypeDef* SPIx, uint16_t SPI_I2S_FLAG); - void SPI_I2S_ClearFlag(SPI_TypeDef* SPIx, uint16_t SPI_I2S_FLAG); Interrupt Mode =============== In Interrupt Mode, the SPI communication can be managed by 3 interrupt sources and 5 pending bits: Pending Bits: ------------- 1. SPI_I2S_IT_TXE : to indicate the status of the transmit buffer register 2. SPI_I2S_IT_RXNE : to indicate the status of the receive buffer register 3. SPI_IT_CRCERR : to indicate if a CRC Calculation error occur 4. SPI_IT_MODF : to indicate if a Mode Fault error occur 5. SPI_I2S_IT_OVR : to indicate if an Overrun error occur Interrupt Source: ----------------- 1. SPI_I2S_IT_TXE: specifies the interrupt source for the Tx buffer empty interrupt. 2. SPI_I2S_IT_RXNE : specifies the interrupt source for the Rx buffer not empty interrupt. 3. SPI_I2S_IT_ERR : specifies the interrupt source for the errors interrupt. In this Mode it is advised to use the following functions: - void SPI_I2S_ITConfig(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT, FunctionalState NewState); - ITStatus SPI_I2S_GetITStatus(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT); - void SPI_I2S_ClearITPendingBit(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT); DMA Mode ======== In DMA Mode, the SPI communication can be managed by 2 DMA Channel requests: 1. SPI_I2S_DMAReq_Tx: specifies the Tx buffer DMA transfer request 2. SPI_I2S_DMAReq_Rx: specifies the Rx buffer DMA transfer request In this Mode it is advised to use the following function: - void SPI_I2S_DMACmd(SPI_TypeDef* SPIx, uint16_t SPI_I2S_DMAReq, FunctionalState NewState); @endverbatim * @{ */ /** * @brief Enables or disables the specified SPI interrupts. * @param SPIx: where x can be 1 or 2 in SPI mode * @param SPI_I2S_IT: specifies the SPI interrupt source to be enabled or disabled. * This parameter can be one of the following values: * @arg SPI_I2S_IT_TXE: Tx buffer empty interrupt mask * @arg SPI_I2S_IT_RXNE: Rx buffer not empty interrupt mask * @arg SPI_I2S_IT_ERR: Error interrupt mask * @param NewState: new state of the specified SPI interrupt. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_I2S_ITConfig(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT, FunctionalState NewState) { uint16_t itpos = 0, itmask = 0 ; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); assert_param(IS_SPI_I2S_CONFIG_IT(SPI_I2S_IT)); /* Get the SPI IT index */ itpos = SPI_I2S_IT >> 4; /* Set the IT mask */ itmask = (uint16_t)1 << (uint16_t)itpos; if (NewState != DISABLE) { /* Enable the selected SPI interrupt */ SPIx->CR2 |= itmask; } else { /* Disable the selected SPI interrupt */ SPIx->CR2 &= (uint16_t)~itmask; } } /** * @brief Checks whether the specified SPI flag is set or not. * @param SPIx: where x can be 1 or 2 in SPI mode * @param SPI_I2S_FLAG: specifies the SPI flag to check. * This parameter can be one of the following values: * @arg SPI_I2S_FLAG_TXE: Transmit buffer empty flag. * @arg SPI_I2S_FLAG_RXNE: Receive buffer not empty flag. * @arg SPI_I2S_FLAG_BSY: Busy flag. * @arg SPI_I2S_FLAG_OVR: Overrun flag. * @arg SPI_I2S_FLAG_MODF: Mode Fault flag. * @arg SPI_I2S_FLAG_CRCERR: CRC Error flag. * @retval The new state of SPI_I2S_FLAG (SET or RESET). */ FlagStatus SPI_I2S_GetFlagStatus(SPI_TypeDef* SPIx, uint16_t SPI_I2S_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_GET_FLAG(SPI_I2S_FLAG)); /* Check the status of the specified SPI flag */ if ((SPIx->SR & SPI_I2S_FLAG) != (uint16_t)RESET) { /* SPI_I2S_FLAG is set */ bitstatus = SET; } else { /* SPI_I2S_FLAG is reset */ bitstatus = RESET; } /* Return the SPI_I2S_FLAG status */ return bitstatus; } /** * @brief Clears the SPIx CRC Error (CRCERR) flag. * @param SPIx: where x can be 1 or 2 in SPI mode * @param SPI_I2S_FLAG: specifies the SPI flag to clear. * This function clears only CRCERR flag. * @note * - OVR (OverRun error) flag is cleared by software sequence: a read * operation to SPI_DR register (SPI_I2S_ReceiveData()) followed by a read * operation to SPI_SR register (SPI_I2S_GetFlagStatus()). * - MODF (Mode Fault) flag is cleared by software sequence: a read/write * operation to SPI_SR register (SPI_I2S_GetFlagStatus()) followed by a * write operation to SPI_CR1 register (SPI_Cmd() to enable the SPI). * @retval None */ void SPI_I2S_ClearFlag(SPI_TypeDef* SPIx, uint16_t SPI_I2S_FLAG) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_CLEAR_FLAG(SPI_I2S_FLAG)); /* Clear the selected SPI CRC Error (CRCERR) flag */ SPIx->SR = (uint16_t)~SPI_I2S_FLAG; } /** * @brief Checks whether the specified SPI interrupt has occurred or not. * @param SPIx: where x can be * - 1 or 2 in SPI mode * @param SPI_I2S_IT: specifies the SPI interrupt source to check. * This parameter can be one of the following values: * @arg SPI_I2S_IT_TXE: Transmit buffer empty interrupt. * @arg SPI_I2S_IT_RXNE: Receive buffer not empty interrupt. * @arg SPI_I2S_IT_OVR: Overrun interrupt. * @arg SPI_I2S_IT_MODF: Mode Fault interrupt. * @arg SPI_I2S_IT_CRCERR: CRC Error interrupt. * @retval The new state of SPI_I2S_IT (SET or RESET). */ ITStatus SPI_I2S_GetITStatus(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT) { ITStatus bitstatus = RESET; uint16_t itpos = 0, itmask = 0, enablestatus = 0; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_GET_IT(SPI_I2S_IT)); /* Get the SPI_I2S_IT index */ itpos = 0x01 << (SPI_I2S_IT & 0x0F); /* Get the SPI_I2S_IT IT mask */ itmask = SPI_I2S_IT >> 4; /* Set the IT mask */ itmask = 0x01 << itmask; /* Get the SPI_I2S_IT enable bit status */ enablestatus = (SPIx->CR2 & itmask) ; /* Check the status of the specified SPI interrupt */ if (((SPIx->SR & itpos) != (uint16_t)RESET) && enablestatus) { /* SPI_I2S_IT is set */ bitstatus = SET; } else { /* SPI_I2S_IT is reset */ bitstatus = RESET; } /* Return the SPI_I2S_IT status */ return bitstatus; } /** * @brief Clears the SPIx CRC Error (CRCERR) interrupt pending bit. * @param SPIx: where x can be * - 1 or 2 in SPI mode * @param SPI_I2S_IT: specifies the SPI interrupt pending bit to clear. * This function clears only CRCERR interrupt pending bit. * @note * - OVR (OverRun Error) interrupt pending bit is cleared by software * sequence: a read operation to SPI_DR register (SPI_I2S_ReceiveData()) * followed by a read operation to SPI_SR register (SPI_I2S_GetITStatus()). * - MODF (Mode Fault) interrupt pending bit is cleared by software sequence: * a read/write operation to SPI_SR register (SPI_I2S_GetITStatus()) * followed by a write operation to SPI_CR1 register (SPI_Cmd() to enable * the SPI). * @retval None */ void SPI_I2S_ClearITPendingBit(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT) { uint16_t itpos = 0; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_CLEAR_IT(SPI_I2S_IT)); /* Get the SPI_I2S IT index */ itpos = 0x01 << (SPI_I2S_IT & 0x0F); /* Clear the selected SPI CRC Error (CRCERR) interrupt pending bit */ SPIx->SR = (uint16_t)~itpos; } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
gpl-3.0
AlienCowEatCake/ImageViewer
src/ThirdParty/Zstandard/zstd-1.5.2/tests/fuzz/dictionary_round_trip.c
5
5744
/* * Copyright (c) Facebook, Inc. * All rights reserved. * * This source code is licensed under both the BSD-style license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ /** * This fuzz target performs a zstd round-trip test (compress & decompress) with * a dictionary, compares the result with the original, and calls abort() on * corruption. */ #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "fuzz_helpers.h" #include "zstd_helpers.h" #include "fuzz_data_producer.h" static ZSTD_CCtx *cctx = NULL; static ZSTD_DCtx *dctx = NULL; static size_t roundTripTest(void *result, size_t resultCapacity, void *compressed, size_t compressedCapacity, const void *src, size_t srcSize, FUZZ_dataProducer_t *producer) { ZSTD_dictContentType_e dictContentType = ZSTD_dct_auto; FUZZ_dict_t dict = FUZZ_train(src, srcSize, producer); int const refPrefix = FUZZ_dataProducer_uint32Range(producer, 0, 1) != 0; size_t cSize; if (FUZZ_dataProducer_uint32Range(producer, 0, 15) == 0) { int const cLevel = FUZZ_dataProducer_int32Range(producer, kMinClevel, kMaxClevel); cSize = ZSTD_compress_usingDict(cctx, compressed, compressedCapacity, src, srcSize, dict.buff, dict.size, cLevel); FUZZ_ZASSERT(cSize); // Compress a second time and check for determinism { size_t const cSize0 = cSize; XXH64_hash_t const hash0 = XXH64(compressed, cSize, 0); cSize = ZSTD_compress_usingDict(cctx, compressed, compressedCapacity, src, srcSize, dict.buff, dict.size, cLevel); FUZZ_ASSERT(cSize == cSize0); FUZZ_ASSERT(XXH64(compressed, cSize, 0) == hash0); } } else { size_t remainingBytes; dictContentType = FUZZ_dataProducer_uint32Range(producer, 0, 2); remainingBytes = FUZZ_dataProducer_remainingBytes(producer); FUZZ_setRandomParameters(cctx, srcSize, producer); /* Disable checksum so we can use sizes smaller than compress bound. */ FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 0)); if (refPrefix) FUZZ_ZASSERT(ZSTD_CCtx_refPrefix_advanced( cctx, dict.buff, dict.size, dictContentType)); else FUZZ_ZASSERT(ZSTD_CCtx_loadDictionary_advanced( cctx, dict.buff, dict.size, (ZSTD_dictLoadMethod_e)FUZZ_dataProducer_uint32Range(producer, 0, 1), dictContentType)); cSize = ZSTD_compress2(cctx, compressed, compressedCapacity, src, srcSize); FUZZ_ZASSERT(cSize); // Compress a second time and check for determinism { size_t const cSize0 = cSize; XXH64_hash_t const hash0 = XXH64(compressed, cSize, 0); FUZZ_dataProducer_rollBack(producer, remainingBytes); FUZZ_setRandomParameters(cctx, srcSize, producer); FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 0)); if (refPrefix) FUZZ_ZASSERT(ZSTD_CCtx_refPrefix_advanced( cctx, dict.buff, dict.size, dictContentType)); cSize = ZSTD_compress2(cctx, compressed, compressedCapacity, src, srcSize); FUZZ_ASSERT(cSize == cSize0); FUZZ_ASSERT(XXH64(compressed, cSize, 0) == hash0); } } if (refPrefix) FUZZ_ZASSERT(ZSTD_DCtx_refPrefix_advanced( dctx, dict.buff, dict.size, dictContentType)); else FUZZ_ZASSERT(ZSTD_DCtx_loadDictionary_advanced( dctx, dict.buff, dict.size, (ZSTD_dictLoadMethod_e)FUZZ_dataProducer_uint32Range(producer, 0, 1), dictContentType)); { size_t const ret = ZSTD_decompressDCtx( dctx, result, resultCapacity, compressed, cSize); free(dict.buff); return ret; } } int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) { /* Give a random portion of src data to the producer, to use for parameter generation. The rest will be used for (de)compression */ FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size); size = FUZZ_dataProducer_reserveDataPrefix(producer); size_t const rBufSize = size; void* rBuf = FUZZ_malloc(rBufSize); size_t cBufSize = ZSTD_compressBound(size); void *cBuf; /* Half of the time fuzz with a 1 byte smaller output size. * This will still succeed because we force the checksum to be disabled, * giving us 4 bytes of overhead. */ cBufSize -= FUZZ_dataProducer_uint32Range(producer, 0, 1); cBuf = FUZZ_malloc(cBufSize); if (!cctx) { cctx = ZSTD_createCCtx(); FUZZ_ASSERT(cctx); } if (!dctx) { dctx = ZSTD_createDCtx(); FUZZ_ASSERT(dctx); } { size_t const result = roundTripTest(rBuf, rBufSize, cBuf, cBufSize, src, size, producer); FUZZ_ZASSERT(result); FUZZ_ASSERT_MSG(result == size, "Incorrect regenerated size"); FUZZ_ASSERT_MSG(!FUZZ_memcmp(src, rBuf, size), "Corruption!"); } free(rBuf); free(cBuf); FUZZ_dataProducer_free(producer); #ifndef STATEFUL_FUZZING ZSTD_freeCCtx(cctx); cctx = NULL; ZSTD_freeDCtx(dctx); dctx = NULL; #endif return 0; }
gpl-3.0
huujee/circleround
code/PC/TightVNC/gui/ToolBar.cpp
5
7453
// Copyright (C) 2011,2012 GlavSoft LLC. // All rights reserved. // //------------------------------------------------------------------------- // This file is part of the TightVNC software. Please visit our Web site: // // http://www.tightvnc.com/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //------------------------------------------------------------------------- // #include "ToolBar.h" #include <CommCtrl.h> ToolBar::ToolBar() { INITCOMMONCONTROLSEX initCtrlEx; initCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); initCtrlEx.dwICC = ICC_BAR_CLASSES; InitCommonControlsEx(&initCtrlEx); m_hWndToolbar = 0; m_initialStr = -1; } ToolBar::~ToolBar() { if (m_hWndToolbar) { DestroyWindow(m_hWndToolbar); } } bool ToolBar::create(int _tbID, HWND _parentHwnd, DWORD dwStyle) { dwStyle |= WS_CHILD; _ASSERT(m_hWndToolbar == 0); // Create the ToolBar window m_hWndToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, 0, dwStyle, 0, 0, 0, 0, _parentHwnd, reinterpret_cast<HMENU>(_tbID), GetModuleHandle(0), 0); if (m_hWndToolbar) { // It's required for backward compatibility SendMessage(m_hWndToolbar, TB_BUTTONSTRUCTSIZE, static_cast<WPARAM>(sizeof(TBBUTTON)), 0); } return !!m_hWndToolbar; }; void ToolBar::setViewAutoButtons(int iButton, int style) { m_autoButtons[iButton] = style; } void ToolBar::loadToolBarfromRes(DWORD id) { BITMAP bmp; HBITMAP hbmp = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(id)); GetObject(hbmp, sizeof(BITMAP), &bmp); m_width = bmp.bmWidth; m_height = bmp.bmHeight; m_numberTB = m_width / m_height; m_id = id; DeleteObject(hbmp); } void ToolBar::setButtonsRange(DWORD id) { m_initialStr = id; } void ToolBar::attachToolBar(HWND hwnd) { std::vector<TBBUTTON> tbuttons; for (int i=0; i < m_numberTB; i++) { TBBUTTON tbutton; ZeroMemory(&tbutton, sizeof(tbutton)); if (m_autoButtons.find(i) != m_autoButtons.end()) { // TODO: paste here all your variants of possible // toolbar buttons switch(m_autoButtons[i]) { case TB_Style_sep: tbutton.fsStyle = TBSTYLE_SEP; tbuttons.push_back(tbutton); break; case TB_Style_gap: tbutton.iBitmap = I_IMAGENONE; tbuttons.push_back(tbutton); break; } } tbutton.iBitmap = i; tbutton.idCommand = m_initialStr == 0 ? 0 : m_initialStr + i; tbutton.fsState = TBSTATE_ENABLED; tbutton.fsStyle = TBSTYLE_BUTTON; tbuttons.push_back(tbutton); } m_autoButtons.clear(); m_hWndToolbar = CreateToolbarEx(hwnd, WS_VISIBLE | WS_CHILD | TBSTYLE_TOOLTIPS | WS_CLIPSIBLINGS | TBSTYLE_FLAT | WS_BORDER, m_id, static_cast<int>(tbuttons.size()), GetModuleHandle(NULL), m_id, &tbuttons.front(), static_cast<int>(tbuttons.size()), 0, 0, 0, 0, sizeof(TBBUTTON)); SendMessage(m_hWndToolbar, TB_SETINDENT, 4, 0); } bool ToolBar::enableButton(int idButton, bool enable) { LRESULT result = SendMessage(m_hWndToolbar, TB_ENABLEBUTTON, idButton, MAKELONG(enable, 0)); return !!result; } bool ToolBar::pressButton(int idButton, bool press) { LRESULT result = SendMessage(m_hWndToolbar, TB_PRESSBUTTON, idButton, MAKELONG(press, 0)); return !!result; } bool ToolBar::getButtonRect(int nIndex, LPRECT buttonRect) { LRESULT result = SendMessage(m_hWndToolbar, TB_GETITEMRECT, nIndex, (LPARAM)buttonRect); return !!result; } bool ToolBar::setButtonsSize(int width, int height) { LRESULT result = SendMessage(m_hWndToolbar, TB_SETBUTTONSIZE, 0, MAKELONG(width, height)); if (result) { SendMessage(m_hWndToolbar, TB_AUTOSIZE, 0, 0); return true; } return false; } void ToolBar::autoSize() { LRESULT style = SendMessage(m_hWndToolbar, TB_GETSTYLE, 0, 0); if (style & CCS_NORESIZE) { RECT r, btnRect; GetClientRect(GetParent(m_hWndToolbar), &r); getButtonRect(0, &btnRect); int height = getButtonsHeight() + btnRect.top * 2 + 2; SetWindowPos(m_hWndToolbar, HWND_TOP, 0, 0, r.right - r.left, height, SWP_NOMOVE); } else { SendMessage(m_hWndToolbar, TB_AUTOSIZE, 0, 0); } } int ToolBar::getButtonsHeight() { return HIWORD(SendMessage(m_hWndToolbar, TB_GETBUTTONSIZE, 0, 0)); } int ToolBar::getButtonsWidth() { return LOWORD(SendMessage(m_hWndToolbar, TB_GETBUTTONSIZE, 0, 0)); } int ToolBar::getHeight() { RECT r; GetWindowRect(m_hWndToolbar, &r); return r.bottom - r.top; } int ToolBar::getTotalWidth() { SIZE size; SendMessage(m_hWndToolbar, TB_GETMAXSIZE, 0, reinterpret_cast<LPARAM>(&size)); return size.cx; } void ToolBar::show() { ShowWindow(m_hWndToolbar, SW_SHOW); } void ToolBar::hide() { ShowWindow(m_hWndToolbar, SW_HIDE); } bool ToolBar::isVisible() { LRESULT style = GetWindowLong(m_hWndToolbar, GWL_STYLE); return !!(style & WS_VISIBLE); } bool ToolBar::checkButton(int idButton, bool check) { LRESULT result = SendMessage(m_hWndToolbar, TB_CHECKBUTTON, idButton, MAKELONG(check, 0)); return !!result; } LRESULT ToolBar::getState(int idButton) { LRESULT result = SendMessage(m_hWndToolbar, TB_GETSTATE, idButton, 0); return result; } LRESULT ToolBar::addBitmap(int nButtons, UINT bitmapID) { TBADDBITMAP resBitmap; resBitmap.hInst = GetModuleHandle(0); resBitmap.nID = bitmapID; return SendMessage(m_hWndToolbar, TB_ADDBITMAP, nButtons, reinterpret_cast<LPARAM>(&resBitmap)); } LRESULT ToolBar::addSystemBitmap(UINT stdBitmapID) { TBADDBITMAP resBitmap; resBitmap.hInst = HINST_COMMCTRL; resBitmap.nID = stdBitmapID; return SendMessage(m_hWndToolbar, TB_ADDBITMAP, 0, (LPARAM)&resBitmap); } bool ToolBar::addButton(int iBitmap, int idCommand, BYTE state, BYTE style, UINT dwData, int iString) { TBBUTTON tbb; tbb.iBitmap = iBitmap; tbb.idCommand = idCommand; tbb.fsState = state; tbb.fsStyle = style; tbb.dwData = dwData; tbb.iString = iString; LRESULT result = SendMessage(m_hWndToolbar, TB_ADDBUTTONS, 1, reinterpret_cast<LPARAM>(&tbb)); if (result) { SendMessage(m_hWndToolbar, TB_AUTOSIZE, 0, 0); } return !!result; } bool ToolBar::addNButton(int nButtons, LPTBBUTTON tbb) { LRESULT result = SendMessage(m_hWndToolbar, TB_ADDBUTTONS, nButtons, reinterpret_cast<LPARAM>(tbb)); if (result) { SendMessage(m_hWndToolbar, TB_AUTOSIZE, 0, 0); } return !!result; }
gpl-3.0
vanfanel/RetroArch
gfx/drivers/gl1.c
5
45534
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2011-2017 - Daniel De Matteis * Copyright (C) 2016-2019 - Brad Parker * * RetroArch is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ /* OpenGL 1.x driver. * * Minimum version : OpenGL 1.1 (1997) * * We are targeting a minimum of OpenGL 1.1 and the Microsoft * "GDI Generic" * software GL implementation. * Any additional features added for later 1.x versions should only be * enabled if they are detected at runtime. */ #include <stddef.h> #include <retro_miscellaneous.h> #include <formats/image.h> #include <string/stdstring.h> #include <retro_math.h> #include <gfx/video_frame.h> #include <gfx/scaler/pixconv.h> #ifdef HAVE_CONFIG_H #include "../../config.h" #endif #ifdef HAVE_MENU #include "../../menu/menu_driver.h" #endif #ifdef HAVE_GFX_WIDGETS #include "../gfx_widgets.h" #endif #include "../font_driver.h" #include "../../driver.h" #include "../../configuration.h" #include "../../retroarch.h" #include "../../verbosity.h" #include "../../frontend/frontend_driver.h" #include "../common/gl1_common.h" #if defined(_WIN32) && !defined(_XBOX) #include "../common/win32_common.h" #endif #ifdef HAVE_THREADS #include "../video_thread_wrapper.h" #endif #ifdef VITA #include <defines/psp_defines.h> static bool vgl_inited = false; #endif static struct video_ortho gl1_default_ortho = {0, 1, 0, 1, -1, 1}; /* Used for the last pass when rendering to the back buffer. */ static const GLfloat gl1_vertexes_flipped[] = { 0, 1, 1, 1, 0, 0, 1, 0 }; static const GLfloat gl1_vertexes[] = { 0, 0, 1, 0, 0, 1, 1, 1 }; static const GLfloat gl1_tex_coords[] = { 0, 0, 1, 0, 0, 1, 1, 1 }; static const GLfloat gl1_white_color[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; #define gl1_context_bind_hw_render(gl1, enable) \ if (gl1->shared_context_use) \ gl1->ctx_driver->bind_hw_render(gl1->ctx_data, enable) #ifdef HAVE_OVERLAY static void gl1_render_overlay(gl1_t *gl, unsigned width, unsigned height) { unsigned i; glEnable(GL_BLEND); if (gl->overlay_full_screen) glViewport(0, 0, width, height); gl->coords.vertex = gl->overlay_vertex_coord; gl->coords.tex_coord = gl->overlay_tex_coord; gl->coords.color = gl->overlay_color_coord; gl->coords.vertices = 4 * gl->overlays; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); for (i = 0; i < gl->overlays; i++) { glBindTexture(GL_TEXTURE_2D, gl->overlay_tex[i]); glDrawArrays(GL_TRIANGLE_STRIP, 4 * i, 4); } glDisable(GL_BLEND); gl->coords.vertex = gl->vertex_ptr; gl->coords.tex_coord = gl->tex_info.coord; gl->coords.color = gl->white_color_ptr; gl->coords.vertices = 4; if (gl->overlay_full_screen) glViewport(gl->vp.x, gl->vp.y, gl->vp.width, gl->vp.height); } static void gl1_free_overlay(gl1_t *gl) { glDeleteTextures(gl->overlays, gl->overlay_tex); free(gl->overlay_tex); free(gl->overlay_vertex_coord); free(gl->overlay_tex_coord); free(gl->overlay_color_coord); gl->overlay_tex = NULL; gl->overlay_vertex_coord = NULL; gl->overlay_tex_coord = NULL; gl->overlay_color_coord = NULL; gl->overlays = 0; } static void gl1_overlay_vertex_geom(void *data, unsigned image, float x, float y, float w, float h) { GLfloat *vertex = NULL; gl1_t *gl = (gl1_t*)data; if (!gl) return; if (image > gl->overlays) { RARCH_ERR("[GL]: Invalid overlay id: %u\n", image); return; } vertex = (GLfloat*)&gl->overlay_vertex_coord[image * 8]; /* Flipped, so we preserve top-down semantics. */ y = 1.0f - y; h = -h; vertex[0] = x; vertex[1] = y; vertex[2] = x + w; vertex[3] = y; vertex[4] = x; vertex[5] = y + h; vertex[6] = x + w; vertex[7] = y + h; } static void gl1_overlay_tex_geom(void *data, unsigned image, GLfloat x, GLfloat y, GLfloat w, GLfloat h) { GLfloat *tex = NULL; gl1_t *gl = (gl1_t*)data; if (!gl) return; tex = (GLfloat*)&gl->overlay_tex_coord[image * 8]; tex[0] = x; tex[1] = y; tex[2] = x + w; tex[3] = y; tex[4] = x; tex[5] = y + h; tex[6] = x + w; tex[7] = y + h; } #endif static bool is_pot(unsigned x) { return (x & (x - 1)) == 0; } static unsigned get_pot(unsigned x) { return (is_pot(x) ? x : next_pow2(x)); } static void *gl1_gfx_init(const video_info_t *video, input_driver_t **input, void **input_data) { unsigned full_x, full_y; void *ctx_data = NULL; const gfx_ctx_driver_t *ctx_driver = NULL; unsigned mode_width = 0; unsigned mode_height = 0; unsigned win_width = 0, win_height = 0; unsigned temp_width = 0, temp_height = 0; settings_t *settings = config_get_ptr(); bool video_smooth = settings->bools.video_smooth; bool video_font_enable = settings->bools.video_font_enable; const char *video_context_driver = settings->arrays.video_context_driver; gl1_t *gl1 = (gl1_t*)calloc(1, sizeof(*gl1)); const char *vendor = NULL; const char *renderer = NULL; const char *version = NULL; const char *extensions = NULL; int interval = 0; struct retro_hw_render_callback *hwr = NULL; if (!gl1) return NULL; *input = NULL; *input_data = NULL; gl1->video_width = video->width; gl1->video_height = video->height; gl1->rgb32 = video->rgb32; gl1->video_bits = video->rgb32 ? 32 : 16; if (video->rgb32) gl1->video_pitch = video->width * 4; else gl1->video_pitch = video->width * 2; ctx_driver = video_context_driver_init_first(gl1, video_context_driver, GFX_CTX_OPENGL_API, 1, 1, false, &ctx_data); if (!ctx_driver) goto error; if (ctx_data) gl1->ctx_data = ctx_data; gl1->ctx_driver = ctx_driver; video_context_driver_set((const gfx_ctx_driver_t*)ctx_driver); RARCH_LOG("[GL1]: Found GL1 context: \"%s\".\n", ctx_driver->ident); if (gl1->ctx_driver->get_video_size) gl1->ctx_driver->get_video_size(gl1->ctx_data, &mode_width, &mode_height); #if defined(__APPLE__) && !defined(IOS) /* This is a hack for now to work around a very annoying * issue that currently eludes us. */ if ( !gl1->ctx_driver->set_video_mode || !gl1->ctx_driver->set_video_mode(gl1->ctx_data, win_width, win_height, video->fullscreen)) goto error; #endif full_x = mode_width; full_y = mode_height; mode_width = 0; mode_height = 0; #ifdef VITA if (!vgl_inited) { vglInitExtended(0x1400000, full_x, full_y, RAM_THRESHOLD, SCE_GXM_MULTISAMPLE_4X); vglUseVram(GL_TRUE); vgl_inited = true; } #endif /* Clear out potential error flags in case we use cached context. */ glGetError(); if (string_is_equal(ctx_driver->ident, "null")) goto error; RARCH_LOG("[GL1]: Detecting screen resolution: %ux%u.\n", full_x, full_y); win_width = video->width; win_height = video->height; if (video->fullscreen && (win_width == 0) && (win_height == 0)) { win_width = full_x; win_height = full_y; } mode_width = win_width; mode_height = win_height; interval = video->swap_interval; if (ctx_driver->swap_interval) { bool adaptive_vsync_enabled = video_driver_test_all_flags( GFX_CTX_FLAGS_ADAPTIVE_VSYNC) && video->adaptive_vsync; if (adaptive_vsync_enabled && interval == 1) interval = -1; ctx_driver->swap_interval(gl1->ctx_data, interval); } if ( !gl1->ctx_driver->set_video_mode || !gl1->ctx_driver->set_video_mode(gl1->ctx_data, win_width, win_height, video->fullscreen)) goto error; gl1->fullscreen = video->fullscreen; mode_width = 0; mode_height = 0; if (gl1->ctx_driver->get_video_size) gl1->ctx_driver->get_video_size(gl1->ctx_data, &mode_width, &mode_height); temp_width = mode_width; temp_height = mode_height; /* Get real known video size, which might have been altered by context. */ if (temp_width != 0 && temp_height != 0) video_driver_set_size(temp_width, temp_height); video_driver_get_size(&temp_width, &temp_height); RARCH_LOG("[GL1]: Using resolution %ux%u.\n", temp_width, temp_height); vendor = (const char*)glGetString(GL_VENDOR); renderer = (const char*)glGetString(GL_RENDERER); version = (const char*)glGetString(GL_VERSION); extensions = (const char*)glGetString(GL_EXTENSIONS); if (!string_is_empty(version)) sscanf(version, "%d.%d", &gl1->version_major, &gl1->version_minor); if (!string_is_empty(extensions)) gl1->extensions = string_split(extensions, " "); RARCH_LOG("[GL1]: Vendor: %s, Renderer: %s.\n", vendor, renderer); RARCH_LOG("[GL1]: Version: %s.\n", version); RARCH_LOG("[GL1]: Extensions: %s\n", extensions); { char device_str[128]; device_str[0] = '\0'; if (!string_is_empty(vendor)) { size_t len = strlcpy(device_str, vendor, sizeof(device_str)); device_str[len ] = ' '; device_str[len+1] = '\0'; } if (!string_is_empty(renderer)) strlcat(device_str, renderer, sizeof(device_str)); video_driver_set_gpu_device_string(device_str); if (!string_is_empty(version)) video_driver_set_gpu_api_version_string(version); } if (gl1->ctx_driver->input_driver) { const char *joypad_name = settings->arrays.input_joypad_driver; gl1->ctx_driver->input_driver( gl1->ctx_data, joypad_name, input, input_data); } if (video_font_enable) font_driver_init_osd(gl1, video, false, video->is_threaded, FONT_DRIVER_RENDER_OPENGL1_API); gl1->smooth = video_smooth; gl1->supports_bgra = string_list_find_elem(gl1->extensions, "GL_EXT_bgra"); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_STENCIL_TEST); glDisable(GL_SCISSOR_TEST); #ifndef VITA glPixelStorei(GL_UNPACK_ALIGNMENT, 1); #endif glGenTextures(1, &gl1->tex); glGenTextures(1, &gl1->menu_tex); hwr = video_driver_get_hw_context(); memcpy(gl1->tex_info.coord, gl1_tex_coords, sizeof(gl1->tex_info.coord)); gl1->vertex_ptr = hwr->bottom_left_origin ? gl1_vertexes : gl1_vertexes_flipped; gl1->textures = 4; gl1->white_color_ptr = gl1_white_color; gl1->coords.vertex = gl1->vertex_ptr; gl1->coords.tex_coord = gl1->tex_info.coord; gl1->coords.color = gl1->white_color_ptr; gl1->coords.lut_tex_coord = gl1_tex_coords; gl1->coords.vertices = 4; RARCH_LOG("[GL1]: Init complete.\n"); return gl1; error: video_context_driver_free(); if (gl1) { if (gl1->extensions) string_list_free(gl1->extensions); free(gl1); } return NULL; } static void gl1_set_projection(gl1_t *gl1, struct video_ortho *ortho, bool allow_rotate) { static math_matrix_4x4 rot = { { 0.0f, 0.0f, 0.0f, 0.0f , 0.0f, 0.0f, 0.0f, 0.0f , 0.0f, 0.0f, 0.0f, 0.0f , 0.0f, 0.0f, 0.0f, 1.0f } }; float radians, cosine, sine; /* Calculate projection. */ matrix_4x4_ortho(gl1->mvp_no_rot, ortho->left, ortho->right, ortho->bottom, ortho->top, ortho->znear, ortho->zfar); if (!allow_rotate) { gl1->mvp = gl1->mvp_no_rot; return; } radians = M_PI * gl1->rotation / 180.0f; cosine = cosf(radians); sine = sinf(radians); MAT_ELEM_4X4(rot, 0, 0) = cosine; MAT_ELEM_4X4(rot, 0, 1) = -sine; MAT_ELEM_4X4(rot, 1, 0) = sine; MAT_ELEM_4X4(rot, 1, 1) = cosine; matrix_4x4_multiply(gl1->mvp, rot, gl1->mvp_no_rot); } void gl1_gfx_set_viewport(gl1_t *gl1, unsigned viewport_width, unsigned viewport_height, bool force_full, bool allow_rotate) { settings_t *settings = config_get_ptr(); unsigned height = gl1->video_height; int x = 0; int y = 0; float device_aspect = (float)viewport_width / viewport_height; if (gl1->ctx_driver->translate_aspect) device_aspect = gl1->ctx_driver->translate_aspect( gl1->ctx_data, viewport_width, viewport_height); if (settings->bools.video_scale_integer && !force_full) { video_viewport_get_scaled_integer(&gl1->vp, viewport_width, viewport_height, video_driver_get_aspect_ratio(), gl1->keep_aspect); viewport_width = gl1->vp.width; viewport_height = gl1->vp.height; } else if (gl1->keep_aspect && !force_full) { float desired_aspect = video_driver_get_aspect_ratio(); #if defined(HAVE_MENU) if (settings->uints.video_aspect_ratio_idx == ASPECT_RATIO_CUSTOM) { const struct video_viewport *custom = video_viewport_get_custom(); /* GL has bottom-left origin viewport. */ x = custom->x; y = height - custom->y - custom->height; viewport_width = custom->width; viewport_height = custom->height; } else #endif { float delta; if (fabsf(device_aspect - desired_aspect) < 0.0001f) { /* If the aspect ratios of screen and desired aspect * ratio are sufficiently equal (floating point stuff), * assume they are actually equal. */ } else if (device_aspect > desired_aspect) { delta = (desired_aspect / device_aspect - 1.0f) / 2.0f + 0.5f; x = (int)roundf(viewport_width * (0.5f - delta)); viewport_width = (unsigned)roundf(2.0f * viewport_width * delta); } else { delta = (device_aspect / desired_aspect - 1.0f) / 2.0f + 0.5f; y = (int)roundf(viewport_height * (0.5f - delta)); viewport_height = (unsigned)roundf(2.0f * viewport_height * delta); } } gl1->vp.x = x; gl1->vp.y = y; gl1->vp.width = viewport_width; gl1->vp.height = viewport_height; } else { gl1->vp.x = gl1->vp.y = 0; gl1->vp.width = viewport_width; gl1->vp.height = viewport_height; } #if defined(RARCH_MOBILE) /* In portrait mode, we want viewport to gravitate to top of screen. */ if (device_aspect < 1.0f) gl1->vp.y *= 2; #endif glViewport(gl1->vp.x, gl1->vp.y, gl1->vp.width, gl1->vp.height); gl1_set_projection(gl1, &gl1_default_ortho, allow_rotate); /* Set last backbuffer viewport. */ if (!force_full) { gl1->vp_out_width = viewport_width; gl1->vp_out_height = viewport_height; } #if 0 RARCH_LOG("Setting viewport @ %ux%u\n", viewport_width, viewport_height); #endif } static void draw_tex(gl1_t *gl1, int pot_width, int pot_height, int width, int height, GLuint tex, const void *frame_to_copy) { uint8_t *frame = NULL; uint8_t *frame_rgba = NULL; /* FIXME: For now, everything is uploaded as BGRA8888, I could not get 444 or 555 to work, and there is no 565 support in GL 1.1 either. */ GLint internalFormat = GL_RGB8; #ifdef MSB_FIRST bool supports_native = gl1->supports_bgra; GLenum format = supports_native ? GL_BGRA_EXT : GL_RGBA; GLenum type = supports_native ? GL_UNSIGNED_INT_8_8_8_8_REV : GL_UNSIGNED_BYTE; #elif defined(LSB_FIRST) bool supports_native = gl1->supports_bgra; GLenum format = supports_native ? GL_BGRA_EXT : GL_RGBA; GLenum type = GL_UNSIGNED_BYTE; #else #error Broken endianness definition #endif float vertices[] = { -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; float colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; float norm_width = (1.0f / (float)pot_width) * (float)width; float norm_height = (1.0f / (float)pot_height) * (float)height; float texcoords[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; texcoords[1] = texcoords[5] = norm_height; texcoords[4] = texcoords[6] = norm_width; glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_STENCIL_TEST); glDisable(GL_SCISSOR_TEST); glEnable(GL_TEXTURE_2D); /* Multi-texture not part of GL 1.1 */ /*glActiveTexture(GL_TEXTURE0);*/ #ifndef VITA glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ROW_LENGTH, pot_width); #endif glBindTexture(GL_TEXTURE_2D, tex); frame = (uint8_t*)frame_to_copy; if (!supports_native) { frame_rgba = (uint8_t*)malloc(pot_width * pot_height * 4); if (frame_rgba) { int x, y; for (y = 0; y < pot_height; y++) { for (x = 0; x < pot_width; x++) { int index = (y * pot_width + x) * 4; #ifdef MSB_FIRST frame_rgba[index + 2] = frame[index + 3]; frame_rgba[index + 1] = frame[index + 2]; frame_rgba[index + 0] = frame[index + 1]; frame_rgba[index + 3] = frame[index + 0]; #else frame_rgba[index + 2] = frame[index + 0]; frame_rgba[index + 1] = frame[index + 1]; frame_rgba[index + 0] = frame[index + 2]; frame_rgba[index + 3] = frame[index + 3]; #endif } } frame = frame_rgba; } } glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, pot_width, pot_height, 0, format, type, frame); if (frame_rgba) free(frame_rgba); if (tex == gl1->tex) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (gl1->smooth ? GL_LINEAR : GL_NEAREST)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (gl1->smooth ? GL_LINEAR : GL_NEAREST)); } else if (tex == gl1->menu_tex) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (gl1->menu_smooth ? GL_LINEAR : GL_NEAREST)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (gl1->menu_smooth ? GL_LINEAR : GL_NEAREST)); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); if (gl1->rotation && tex == gl1->tex) glRotatef(gl1->rotation, 0.0f, 0.0f, 1.0f); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glColorPointer(4, GL_FLOAT, 0, colors); glVertexPointer(3, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texcoords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } static void gl1_readback( gl1_t *gl1, unsigned alignment, unsigned fmt, unsigned type, void *src) { #ifndef VITA glPixelStorei(GL_PACK_ALIGNMENT, alignment); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glReadBuffer(GL_BACK); #endif glReadPixels(gl1->vp.x, gl1->vp.y, gl1->vp.width, gl1->vp.height, (GLenum)fmt, (GLenum)type, (GLvoid*)src); } static bool gl1_gfx_frame(void *data, const void *frame, unsigned frame_width, unsigned frame_height, uint64_t frame_count, unsigned pitch, const char *msg, video_frame_info_t *video_info) { const void *frame_to_copy = NULL; unsigned mode_width = 0; unsigned mode_height = 0; unsigned width = video_info->width; unsigned height = video_info->height; bool draw = true; bool do_swap = false; gl1_t *gl1 = (gl1_t*)data; unsigned bits = gl1->video_bits; unsigned pot_width = 0; unsigned pot_height = 0; unsigned video_width = video_info->width; unsigned video_height = video_info->height; #ifdef HAVE_MENU bool menu_is_alive = video_info->menu_is_alive; #endif #ifdef HAVE_GFX_WIDGETS bool widgets_active = video_info->widgets_active; #endif bool hard_sync = video_info->hard_sync; struct font_params *osd_params = (struct font_params*) &video_info->osd_stat_params; bool overlay_behind_menu = video_info->overlay_behind_menu; /* FIXME: Force these settings off as they interfere with the rendering */ video_info->xmb_shadows_enable = false; video_info->menu_shader_pipeline = 0; gl1_context_bind_hw_render(gl1, false); if (gl1->should_resize) { gfx_ctx_mode_t mode; gl1->should_resize = false; mode.width = width; mode.height = height; if (gl1->ctx_driver->set_resize) gl1->ctx_driver->set_resize(gl1->ctx_data, mode.width, mode.height); gl1_gfx_set_viewport(gl1, video_width, video_height, false, true); } if ( !frame || frame == RETRO_HW_FRAME_BUFFER_VALID || ( frame_width == 4 && frame_height == 4 && (frame_width < width && frame_height < height)) ) draw = false; do_swap = frame || draw; if ( gl1->video_width != frame_width || gl1->video_height != frame_height || gl1->video_pitch != pitch) { if (frame_width > 4 && frame_height > 4) { gl1->video_width = frame_width; gl1->video_height = frame_height; gl1->video_pitch = pitch; pot_width = get_pot(frame_width); pot_height = get_pot(frame_height); if (draw) { if (gl1->video_buf) free(gl1->video_buf); gl1->video_buf = (unsigned char*)malloc(pot_width * pot_height * 4); } } } width = gl1->video_width; height = gl1->video_height; pitch = gl1->video_pitch; pot_width = get_pot(width); pot_height = get_pot(height); if (draw && gl1->video_buf) { if (bits == 32) { unsigned y; /* copy lines into top-left portion of larger (power-of-two) buffer */ for (y = 0; y < height; y++) memcpy(gl1->video_buf + ((pot_width * (bits / 8)) * y), (const unsigned char*)frame + (pitch * y), width * (bits / 8)); } else if (bits == 16) conv_rgb565_argb8888(gl1->video_buf, frame, width, height, pot_width * sizeof(unsigned), pitch); frame_to_copy = gl1->video_buf; } if (gl1->video_width != width || gl1->video_height != height) { gl1->video_width = width; gl1->video_height = height; } if (gl1->ctx_driver->get_video_size) gl1->ctx_driver->get_video_size(gl1->ctx_data, &mode_width, &mode_height); gl1->screen_width = mode_width; gl1->screen_height = mode_height; if (draw) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (frame_to_copy) draw_tex(gl1, pot_width, pot_height, width, height, gl1->tex, frame_to_copy); } #ifdef HAVE_MENU if (gl1->menu_frame && menu_is_alive) { frame_to_copy = NULL; width = gl1->menu_width; height = gl1->menu_height; pitch = gl1->menu_pitch; bits = gl1->menu_bits; pot_width = get_pot(width); pot_height = get_pot(height); do_swap = true; if (gl1->menu_size_changed) { gl1->menu_size_changed = false; if (gl1->menu_video_buf) free(gl1->menu_video_buf); gl1->menu_video_buf = NULL; } if (!gl1->menu_video_buf) gl1->menu_video_buf = (unsigned char*) malloc(pot_width * pot_height * 4); if (bits == 16 && gl1->menu_video_buf) { conv_rgba4444_argb8888(gl1->menu_video_buf, gl1->menu_frame, width, height, pot_width * sizeof(unsigned), pitch); frame_to_copy = gl1->menu_video_buf; if (gl1->menu_texture_full_screen) { glViewport(0, 0, video_width, video_height); draw_tex(gl1, pot_width, pot_height, width, height, gl1->menu_tex, frame_to_copy); glViewport(gl1->vp.x, gl1->vp.y, gl1->vp.width, gl1->vp.height); } else draw_tex(gl1, pot_width, pot_height, width, height, gl1->menu_tex, frame_to_copy); } } #ifdef HAVE_OVERLAY if (gl1->overlay_enable && overlay_behind_menu) gl1_render_overlay(gl1, video_width, video_height); #endif if (gl1->menu_texture_enable){ do_swap = true; #ifdef VITA glUseProgram(0); bool enabled = glIsEnabled(GL_DEPTH_TEST); if(enabled) glDisable(GL_DEPTH_TEST); #endif menu_driver_frame(menu_is_alive, video_info); #ifdef VITA if(enabled) glEnable(GL_DEPTH_TEST); #endif } else #endif if (video_info->statistics_show) { if (osd_params) { font_driver_render_msg(gl1, video_info->stat_text, osd_params, NULL); #if 0 osd_params->y = 0.350f; osd_params->scale = 0.75f; font_driver_render_msg(gl1, video_info->chat_text, (const struct font_params*)&video_info->osd_stat_params, NULL); #endif } } #ifdef HAVE_GFX_WIDGETS if (widgets_active) gfx_widgets_frame(video_info); #endif #ifdef HAVE_OVERLAY if (gl1->overlay_enable && !overlay_behind_menu) gl1_render_overlay(gl1, video_width, video_height); #endif if (msg) font_driver_render_msg(gl1, msg, NULL, NULL); if (gl1->ctx_driver->update_window_title) gl1->ctx_driver->update_window_title( gl1->ctx_data); /* Screenshots. */ if (gl1->readback_buffer_screenshot) gl1_readback(gl1, 4, GL_RGBA, #ifdef MSB_FIRST GL_UNSIGNED_INT_8_8_8_8_REV, #else GL_UNSIGNED_BYTE, #endif gl1->readback_buffer_screenshot); if (do_swap && gl1->ctx_driver->swap_buffers) gl1->ctx_driver->swap_buffers(gl1->ctx_data); /* Emscripten has to do black frame insertion in its main loop */ #ifndef EMSCRIPTEN /* Disable BFI during fast forward, slow-motion, * and pause to prevent flicker. */ if ( video_info->black_frame_insertion && !video_info->input_driver_nonblock_state && !video_info->runloop_is_slowmotion && !video_info->runloop_is_paused && !gl1->menu_texture_enable) { unsigned n; for (n = 0; n < video_info->black_frame_insertion; ++n) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); if (gl1->ctx_driver->swap_buffers) gl1->ctx_driver->swap_buffers(gl1->ctx_data); } } #endif /* check if we are fast forwarding or in menu, if we are ignore hard sync */ if ( hard_sync && !video_info->input_driver_nonblock_state ) { glClear(GL_COLOR_BUFFER_BIT); glFinish(); } if (draw) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); } gl1_context_bind_hw_render(gl1, true); return true; } static void gl1_gfx_set_nonblock_state(void *data, bool state, bool adaptive_vsync_enabled, unsigned swap_interval) { int interval = 0; gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1_context_bind_hw_render(gl1, false); if (!state) interval = swap_interval; if (gl1->ctx_driver->swap_interval) { if (adaptive_vsync_enabled && interval == 1) interval = -1; gl1->ctx_driver->swap_interval(gl1->ctx_data, interval); } gl1_context_bind_hw_render(gl1, true); } static bool gl1_gfx_alive(void *data) { unsigned temp_width = 0; unsigned temp_height = 0; bool quit = false; bool resize = false; bool ret = false; gl1_t *gl1 = (gl1_t*)data; /* Needed because some context drivers don't track their sizes */ video_driver_get_size(&temp_width, &temp_height); gl1->ctx_driver->check_window(gl1->ctx_data, &quit, &resize, &temp_width, &temp_height); if (resize) gl1->should_resize = true; ret = !quit; if (temp_width != 0 && temp_height != 0) video_driver_set_size(temp_width, temp_height); return ret; } static bool gl1_gfx_focus(void *data) { gl1_t *gl = (gl1_t*)data; if (gl && gl->ctx_driver && gl->ctx_driver->has_focus) return gl->ctx_driver->has_focus(gl->ctx_data); return true; } static bool gl1_gfx_suppress_screensaver(void *data, bool enable) { (void)data; (void)enable; return false; } static void gl1_gfx_free(void *data) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1_context_bind_hw_render(gl1, false); if (gl1->menu_frame) free(gl1->menu_frame); gl1->menu_frame = NULL; if (gl1->video_buf) free(gl1->video_buf); gl1->video_buf = NULL; if (gl1->menu_video_buf) free(gl1->menu_video_buf); gl1->menu_video_buf = NULL; if (gl1->tex) { glDeleteTextures(1, &gl1->tex); gl1->tex = 0; } if (gl1->menu_tex) { glDeleteTextures(1, &gl1->menu_tex); gl1->menu_tex = 0; } #ifdef HAVE_OVERLAY gl1_free_overlay(gl1); #endif if (gl1->extensions) string_list_free(gl1->extensions); gl1->extensions = NULL; font_driver_free_osd(); if (gl1->ctx_driver && gl1->ctx_driver->destroy) gl1->ctx_driver->destroy(gl1->ctx_data); video_context_driver_free(); free(gl1); } static bool gl1_gfx_set_shader(void *data, enum rarch_shader_type type, const char *path) { (void)data; (void)type; (void)path; return false; } static void gl1_gfx_set_rotation(void *data, unsigned rotation) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->rotation = 90 * rotation; gl1_set_projection(gl1, &gl1_default_ortho, true); } static void gl1_gfx_viewport_info(void *data, struct video_viewport *vp) { unsigned width, height; unsigned top_y, top_dist; gl1_t *gl1 = (gl1_t*)data; video_driver_get_size(&width, &height); *vp = gl1->vp; vp->full_width = width; vp->full_height = height; /* Adjust as GL viewport is bottom-up. */ top_y = vp->y + vp->height; top_dist = height - top_y; vp->y = top_dist; } static bool gl1_gfx_read_viewport(void *data, uint8_t *buffer, bool is_idle) { unsigned num_pixels = 0; gl1_t *gl1 = (gl1_t*)data; if (!gl1) return false; gl1_context_bind_hw_render(gl1, false); num_pixels = gl1->vp.width * gl1->vp.height; gl1->readback_buffer_screenshot = malloc(num_pixels * sizeof(uint32_t)); if (!gl1->readback_buffer_screenshot) goto error; if (!is_idle) video_driver_cached_frame(); video_frame_convert_rgba_to_bgr( (const void*)gl1->readback_buffer_screenshot, buffer, num_pixels); free(gl1->readback_buffer_screenshot); gl1->readback_buffer_screenshot = NULL; gl1_context_bind_hw_render(gl1, true); return true; error: gl1_context_bind_hw_render(gl1, true); return false; } static void gl1_set_texture_frame(void *data, const void *frame, bool rgb32, unsigned width, unsigned height, float alpha) { settings_t *settings = config_get_ptr(); bool menu_linear_filter = settings->bools.menu_linear_filter; unsigned pitch = width * 2; gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->menu_smooth = menu_linear_filter; gl1_context_bind_hw_render(gl1, false); if (rgb32) pitch = width * 4; if (gl1->menu_frame) free(gl1->menu_frame); gl1->menu_frame = NULL; if ( !gl1->menu_frame || gl1->menu_width != width || gl1->menu_height != height || gl1->menu_pitch != pitch) { if (pitch && height) { if (gl1->menu_frame) free(gl1->menu_frame); /* FIXME? We have to assume the pitch has no * extra padding in it because that will * mess up the POT calculation when we don't * know how many bpp there are. */ gl1->menu_frame = (unsigned char*)malloc(pitch * height); } } if (gl1->menu_frame && frame && pitch && height) { memcpy(gl1->menu_frame, frame, pitch * height); gl1->menu_width = width; gl1->menu_height = height; gl1->menu_pitch = pitch; gl1->menu_bits = rgb32 ? 32 : 16; gl1->menu_size_changed = true; } gl1_context_bind_hw_render(gl1, true); } static void gl1_get_video_output_size(void *data, unsigned *width, unsigned *height, char *desc, size_t desc_len) { gl1_t *gl = (gl1_t*)data; if (!gl || !gl->ctx_driver || !gl->ctx_driver->get_video_output_size) return; gl->ctx_driver->get_video_output_size( gl->ctx_data, width, height, desc, desc_len); } static void gl1_get_video_output_prev(void *data) { gl1_t *gl = (gl1_t*)data; if (!gl || !gl->ctx_driver || !gl->ctx_driver->get_video_output_prev) return; gl->ctx_driver->get_video_output_prev(gl->ctx_data); } static void gl1_get_video_output_next(void *data) { gl1_t *gl = (gl1_t*)data; if (!gl || !gl->ctx_driver || !gl->ctx_driver->get_video_output_next) return; gl->ctx_driver->get_video_output_next(gl->ctx_data); } static void gl1_set_video_mode(void *data, unsigned width, unsigned height, bool fullscreen) { gl1_t *gl = (gl1_t*)data; if (gl->ctx_driver->set_video_mode) gl->ctx_driver->set_video_mode(gl->ctx_data, width, height, fullscreen); } static unsigned gl1_wrap_type_to_enum(enum gfx_wrap_type type) { switch (type) { case RARCH_WRAP_REPEAT: case RARCH_WRAP_MIRRORED_REPEAT: /* mirrored not actually supported */ return GL_REPEAT; default: return GL_CLAMP; } return 0; } static void gl1_load_texture_data( GLuint id, enum gfx_wrap_type wrap_type, enum texture_filter_type filter_type, unsigned alignment, unsigned width, unsigned height, const void *frame, unsigned base_size) { GLint mag_filter, min_filter; bool use_rgba = video_driver_supports_rgba(); bool rgb32 = (base_size == (sizeof(uint32_t))); GLenum wrap = gl1_wrap_type_to_enum(wrap_type); /* GL1.x does not have mipmapping support. */ switch (filter_type) { case TEXTURE_FILTER_MIPMAP_NEAREST: case TEXTURE_FILTER_NEAREST: min_filter = GL_NEAREST; mag_filter = GL_NEAREST; break; case TEXTURE_FILTER_MIPMAP_LINEAR: case TEXTURE_FILTER_LINEAR: default: min_filter = GL_LINEAR; mag_filter = GL_LINEAR; break; } gl1_bind_texture(id, wrap, mag_filter, min_filter); #ifndef VITA glPixelStorei(GL_UNPACK_ALIGNMENT, alignment); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); #endif glTexImage2D(GL_TEXTURE_2D, 0, (use_rgba || !rgb32) ? GL_RGBA : RARCH_GL1_INTERNAL_FORMAT32, width, height, 0, (use_rgba || !rgb32) ? GL_RGBA : RARCH_GL1_TEXTURE_TYPE32, #ifdef MSB_FIRST GL_UNSIGNED_INT_8_8_8_8_REV, #else (rgb32) ? RARCH_GL1_FORMAT32 : GL_UNSIGNED_BYTE, #endif frame); } static void video_texture_load_gl1( struct texture_image *ti, enum texture_filter_type filter_type, uintptr_t *idptr) { GLuint id; unsigned width = 0; unsigned height = 0; const void *pixels = NULL; /* Generate the OpenGL texture object */ glGenTextures(1, &id); *idptr = id; if (ti) { width = ti->width; height = ti->height; pixels = ti->pixels; } gl1_load_texture_data(id, RARCH_WRAP_EDGE, filter_type, 4 /* TODO/FIXME - dehardcode */, width, height, pixels, sizeof(uint32_t) /* TODO/FIXME - dehardcode */ ); } #ifdef HAVE_THREADS static int video_texture_load_wrap_gl1(void *data) { uintptr_t id = 0; if (!data) return 0; video_texture_load_gl1((struct texture_image*)data, TEXTURE_FILTER_NEAREST, &id); return (int)id; } #endif static uintptr_t gl1_load_texture(void *video_data, void *data, bool threaded, enum texture_filter_type filter_type) { uintptr_t id = 0; #ifdef HAVE_THREADS if (threaded) { gl1_t *gl1 = (gl1_t*)video_data; custom_command_method_t func = video_texture_load_wrap_gl1; if (gl1->ctx_driver->make_current) gl1->ctx_driver->make_current(false); return video_thread_texture_load(data, func); } #endif video_texture_load_gl1((struct texture_image*)data, filter_type, &id); return id; } static void gl1_set_aspect_ratio(void *data, unsigned aspect_ratio_idx) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->keep_aspect = true; gl1->should_resize = true; } static void gl1_unload_texture(void *data, bool threaded, uintptr_t id) { GLuint glid; gl1_t *gl1 = (gl1_t*)data; if (!id) return; #ifdef HAVE_THREADS if (threaded) { if (gl1->ctx_driver->make_current) gl1->ctx_driver->make_current(false); } #endif glid = (GLuint)id; glDeleteTextures(1, &glid); } static float gl1_get_refresh_rate(void *data) { float refresh_rate = 0.0f; if (video_context_driver_get_refresh_rate(&refresh_rate)) return refresh_rate; return 0.0f; } static void gl1_set_texture_enable(void *data, bool state, bool full_screen) { gl1_t *gl1 = (gl1_t*)data; if (!gl1) return; gl1->menu_texture_enable = state; gl1->menu_texture_full_screen = full_screen; } static uint32_t gl1_get_flags(void *data) { uint32_t flags = 0; BIT32_SET(flags, GFX_CTX_FLAGS_HARD_SYNC); BIT32_SET(flags, GFX_CTX_FLAGS_BLACK_FRAME_INSERTION); BIT32_SET(flags, GFX_CTX_FLAGS_MENU_FRAME_FILTERING); BIT32_SET(flags, GFX_CTX_FLAGS_OVERLAY_BEHIND_MENU_SUPPORTED); return flags; } static const video_poke_interface_t gl1_poke_interface = { gl1_get_flags, gl1_load_texture, gl1_unload_texture, gl1_set_video_mode, gl1_get_refresh_rate, NULL, gl1_get_video_output_size, gl1_get_video_output_prev, gl1_get_video_output_next, NULL, NULL, gl1_set_aspect_ratio, NULL, gl1_set_texture_frame, gl1_set_texture_enable, font_driver_render_msg, NULL, NULL, /* grab_mouse_toggle */ NULL, /* get_current_shader */ NULL, /* get_current_software_framebuffer */ NULL, /* get_hw_render_interface */ NULL, /* set_hdr_max_nits */ NULL, /* set_hdr_paper_white_nits */ NULL, /* set_hdr_contrast */ NULL /* set_hdr_expand_gamut */ }; static void gl1_gfx_get_poke_interface(void *data, const video_poke_interface_t **iface) { (void)data; *iface = &gl1_poke_interface; } #ifdef HAVE_GFX_WIDGETS static bool gl1_gfx_widgets_enabled(void *data) { (void)data; return true; } #endif static void gl1_gfx_set_viewport_wrapper(void *data, unsigned viewport_width, unsigned viewport_height, bool force_full, bool allow_rotate) { gl1_t *gl1 = (gl1_t*)data; gl1_gfx_set_viewport(gl1, viewport_width, viewport_height, force_full, allow_rotate); } #ifdef HAVE_OVERLAY static unsigned gl1_get_alignment(unsigned pitch) { if (pitch & 1) return 1; if (pitch & 2) return 2; if (pitch & 4) return 4; return 8; } static bool gl1_overlay_load(void *data, const void *image_data, unsigned num_images) { unsigned i, j; gl1_t *gl = (gl1_t*)data; const struct texture_image *images = (const struct texture_image*)image_data; if (!gl) return false; gl1_context_bind_hw_render(gl, false); gl1_free_overlay(gl); gl->overlay_tex = (GLuint*) calloc(num_images, sizeof(*gl->overlay_tex)); if (!gl->overlay_tex) { gl1_context_bind_hw_render(gl, true); return false; } gl->overlay_vertex_coord = (GLfloat*) calloc(2 * 4 * num_images, sizeof(GLfloat)); gl->overlay_tex_coord = (GLfloat*) calloc(2 * 4 * num_images, sizeof(GLfloat)); gl->overlay_color_coord = (GLfloat*) calloc(4 * 4 * num_images, sizeof(GLfloat)); if ( !gl->overlay_vertex_coord || !gl->overlay_tex_coord || !gl->overlay_color_coord) return false; gl->overlays = num_images; glGenTextures(num_images, gl->overlay_tex); for (i = 0; i < num_images; i++) { unsigned alignment = gl1_get_alignment(images[i].width * sizeof(uint32_t)); gl1_load_texture_data(gl->overlay_tex[i], RARCH_WRAP_EDGE, TEXTURE_FILTER_LINEAR, alignment, images[i].width, images[i].height, images[i].pixels, sizeof(uint32_t)); /* Default. Stretch to whole screen. */ gl1_overlay_tex_geom(gl, i, 0, 0, 1, 1); gl1_overlay_vertex_geom(gl, i, 0, 0, 1, 1); for (j = 0; j < 16; j++) gl->overlay_color_coord[16 * i + j] = 1.0f; } gl1_context_bind_hw_render(gl, true); return true; } static void gl1_overlay_enable(void *data, bool state) { gl1_t *gl = (gl1_t*)data; if (!gl) return; gl->overlay_enable = state; if (gl->fullscreen && gl->ctx_driver->show_mouse) gl->ctx_driver->show_mouse(gl->ctx_data, state); } static void gl1_overlay_full_screen(void *data, bool enable) { gl1_t *gl = (gl1_t*)data; if (gl) gl->overlay_full_screen = enable; } static void gl1_overlay_set_alpha(void *data, unsigned image, float mod) { GLfloat *color = NULL; gl1_t *gl = (gl1_t*)data; if (!gl) return; color = (GLfloat*)&gl->overlay_color_coord[image * 16]; color[ 0 + 3] = mod; color[ 4 + 3] = mod; color[ 8 + 3] = mod; color[12 + 3] = mod; } static const video_overlay_interface_t gl1_overlay_interface = { gl1_overlay_enable, gl1_overlay_load, gl1_overlay_tex_geom, gl1_overlay_vertex_geom, gl1_overlay_full_screen, gl1_overlay_set_alpha, }; static void gl1_get_overlay_interface(void *data, const video_overlay_interface_t **iface) { (void)data; *iface = &gl1_overlay_interface; } #endif static bool gl1_has_windowed(void *data) { gl1_t *gl = (gl1_t*)data; if (gl && gl->ctx_driver) return gl->ctx_driver->has_windowed; return false; } video_driver_t video_gl1 = { gl1_gfx_init, gl1_gfx_frame, gl1_gfx_set_nonblock_state, gl1_gfx_alive, gl1_gfx_focus, gl1_gfx_suppress_screensaver, gl1_has_windowed, gl1_gfx_set_shader, gl1_gfx_free, "gl1", gl1_gfx_set_viewport_wrapper, gl1_gfx_set_rotation, gl1_gfx_viewport_info, gl1_gfx_read_viewport, NULL, /* read_frame_raw */ #ifdef HAVE_OVERLAY gl1_get_overlay_interface, #endif #ifdef HAVE_VIDEO_LAYOUT NULL, #endif gl1_gfx_get_poke_interface, gl1_wrap_type_to_enum, #ifdef HAVE_GFX_WIDGETS gl1_gfx_widgets_enabled #endif };
gpl-3.0
PTDreamer/dRonin
ground/gcs/src/libs/glc_lib/3DWidget/glc_3dwidgetmanagerhandle.cpp
6
7888
/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) http://glc-lib.sourceforge.net GLC-lib is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. GLC-lib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_3dwidgetmanagerhandle.cpp Implementation of the GLC_3DWidgetManagerHandle class. #include "glc_3dwidgetmanagerhandle.h" #include "../viewport/glc_viewport.h" #include "../sceneGraph/glc_3dviewinstance.h" #include "glc_3dwidget.h" #include <QMouseEvent> GLC_3DWidgetManagerHandle::GLC_3DWidgetManagerHandle(GLC_Viewport* pViewport) : m_Collection() , m_Count(1) , m_3DWidgetHash() , m_MapBetweenInstanceWidget() , m_pViewport(pViewport) , m_Active3DWidgetId(0) , m_Preselected3DWidgetId(0) { } GLC_3DWidgetManagerHandle::~GLC_3DWidgetManagerHandle() { QHash<GLC_uint, GLC_3DWidget*>::iterator iWidget= m_3DWidgetHash.begin(); while (m_3DWidgetHash.constEnd() != iWidget) { delete iWidget.value(); ++iWidget; } } void GLC_3DWidgetManagerHandle::add3DWidget(GLC_3DWidget* p3DWidget) { Q_ASSERT(!m_MapBetweenInstanceWidget.contains(p3DWidget->id())); m_3DWidgetHash.insert(p3DWidget->id(), p3DWidget); p3DWidget->setWidgetManager(this); } void GLC_3DWidgetManagerHandle::remove3DWidget(GLC_uint id) { Q_ASSERT(m_3DWidgetHash.contains(id)); delete m_3DWidgetHash.take(id); if (m_Active3DWidgetId == id) m_Active3DWidgetId= 0; } GLC_3DWidget* GLC_3DWidgetManagerHandle::take(GLC_uint id) { Q_ASSERT(m_3DWidgetHash.contains(id)); return m_3DWidgetHash.take(id); } void GLC_3DWidgetManagerHandle::add3DViewInstance(const GLC_3DViewInstance& instance, GLC_uint widgetId) { const GLC_uint instanceId= instance.id(); Q_ASSERT(!m_MapBetweenInstanceWidget.contains(instanceId)); Q_ASSERT(!m_Collection.contains(instanceId)); m_MapBetweenInstanceWidget.insert(instanceId, widgetId); m_Collection.add(instance, 0); } void GLC_3DWidgetManagerHandle::remove3DViewInstance(GLC_uint id) { Q_ASSERT(m_MapBetweenInstanceWidget.contains(id)); Q_ASSERT(m_Collection.contains(id)); m_Collection.remove(id); m_MapBetweenInstanceWidget.remove(id); } void GLC_3DWidgetManagerHandle::clear() { m_Active3DWidgetId= 0; QHash<GLC_uint, GLC_3DWidget*>::iterator iWidget= m_3DWidgetHash.begin(); while (m_3DWidgetHash.constEnd() != iWidget) { delete iWidget.value(); ++iWidget; } m_3DWidgetHash.clear(); m_Collection.clear(); m_MapBetweenInstanceWidget.clear(); } void GLC_3DWidgetManagerHandle::setWidgetVisible(GLC_uint id, bool visible) { if (id == m_Active3DWidgetId) m_Active3DWidgetId= 0; Q_ASSERT(m_3DWidgetHash.contains(id)); m_3DWidgetHash.value(id)->setVisible(visible); } glc::WidgetEventFlag GLC_3DWidgetManagerHandle::mouseDoubleClickEvent(QMouseEvent *) { if (hasAnActiveWidget()) { } return glc::IgnoreEvent; } glc::WidgetEventFlag GLC_3DWidgetManagerHandle::mouseMoveEvent(QMouseEvent * pEvent) { glc::WidgetEventFlag eventFlag= glc::IgnoreEvent; // Get the 3D cursor position and the id under QPair<GLC_uint, GLC_Point3d> cursorInfo= select(pEvent); const GLC_uint selectedId= cursorInfo.first; const GLC_Point3d pos(cursorInfo.second); if (hasAnActiveWidget()) { GLC_3DWidget* pActiveWidget= m_3DWidgetHash.value(m_Active3DWidgetId); eventFlag= pActiveWidget->mouseMove(pos, pEvent->buttons(), selectedId); } else { if (m_MapBetweenInstanceWidget.contains(selectedId)) { const GLC_uint select3DWidgetId= m_MapBetweenInstanceWidget.value(selectedId); if (m_Preselected3DWidgetId != select3DWidgetId) { m_Preselected3DWidgetId= m_MapBetweenInstanceWidget.value(selectedId); GLC_3DWidget* pActiveWidget= m_3DWidgetHash.value(m_Preselected3DWidgetId); eventFlag= pActiveWidget->mouseOver(pos, selectedId); } else if (0 != m_Preselected3DWidgetId && (m_Preselected3DWidgetId != select3DWidgetId)) { eventFlag= m_3DWidgetHash.value(m_Preselected3DWidgetId)->unselect(pos, selectedId); } } else if (0 != m_Preselected3DWidgetId) { eventFlag= m_3DWidgetHash.value(m_Preselected3DWidgetId)->unselect(pos, selectedId); m_Preselected3DWidgetId= 0; } } return eventFlag; } glc::WidgetEventFlag GLC_3DWidgetManagerHandle::mousePressEvent(QMouseEvent * pEvent) { glc::WidgetEventFlag eventFlag= glc::IgnoreEvent; if (pEvent->button() == Qt::LeftButton) { // Get the 3D cursor position and the id under QPair<GLC_uint, GLC_Point3d> cursorInfo= select(pEvent); const GLC_uint selectedId= cursorInfo.first; const GLC_Point3d pos(cursorInfo.second); if (hasAnActiveWidget()) { GLC_3DWidget* pActiveWidget= m_3DWidgetHash.value(m_Active3DWidgetId); const bool activeWidgetUnderMouse= pActiveWidget->instanceBelongTo(selectedId); if (activeWidgetUnderMouse) { eventFlag= pActiveWidget->mousePressed(pos, pEvent->button(), selectedId); } else { eventFlag= pActiveWidget->unselect(pos, selectedId); if (m_MapBetweenInstanceWidget.contains(selectedId)) { m_Active3DWidgetId= m_MapBetweenInstanceWidget.value(selectedId); pActiveWidget= m_3DWidgetHash.value(m_Active3DWidgetId); eventFlag= pActiveWidget->select(pos, selectedId); } else { m_Active3DWidgetId= 0; } } } else { if (m_MapBetweenInstanceWidget.contains(selectedId)) { m_Active3DWidgetId= m_MapBetweenInstanceWidget.value(selectedId); GLC_3DWidget* pActiveWidget= m_3DWidgetHash.value(m_Active3DWidgetId); eventFlag= pActiveWidget->select(pos, selectedId); } } } return eventFlag; } glc::WidgetEventFlag GLC_3DWidgetManagerHandle::mouseReleaseEvent(QMouseEvent * pEvent) { glc::WidgetEventFlag eventFlag= glc::IgnoreEvent; if (hasAnActiveWidget() && (pEvent->button() == Qt::LeftButton)) { GLC_3DWidget* pActiveWidget= m_3DWidgetHash.value(m_Active3DWidgetId); eventFlag= pActiveWidget->mouseReleased(pEvent->button()); } return eventFlag; } void GLC_3DWidgetManagerHandle::render() { // Signal 3DWidget that the view as changed QHash<GLC_uint, GLC_3DWidget*>::iterator iWidget= m_3DWidgetHash.begin(); while (m_3DWidgetHash.constEnd() != iWidget) { iWidget.value()->updateWidgetRep(); ++iWidget; } // Render the 3D widget m_Collection.render(0, glc::WireRenderFlag); m_Collection.render(0, glc::TransparentRenderFlag); m_Collection.render(1, glc::WireRenderFlag); if (GLC_State::glslUsed()) { m_Collection.renderShaderGroup(glc::WireRenderFlag); m_Collection.renderShaderGroup(glc::TransparentRenderFlag); } } QPair<GLC_uint, GLC_Point3d> GLC_3DWidgetManagerHandle::select(QMouseEvent* event) { GLC_uint selectionId= m_pViewport->selectOnPreviousRender(event->x(), event->y()); const GLC_Point3d selectedPoint(m_pViewport->unProject(event->x(), event->y())); QPair<GLC_uint, GLC_Point3d> selection; selection.first= selectionId; selection.second= selectedPoint; return selection; }
gpl-3.0
KangDroid/Marlin
Marlin/src/HAL/TEENSY35_36/watchdog.cpp
6
1173
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #if defined(__MK64FX512__) || defined(__MK66FX1M0__) #include "../../inc/MarlinConfig.h" #if ENABLED(USE_WATCHDOG) #include "watchdog.h" void watchdog_init() { WDOG_TOVALH = 0; WDOG_TOVALL = 4000; WDOG_STCTRLH = WDOG_STCTRLH_WDOGEN; } #endif // USE_WATCHDOG #endif // __MK64FX512__ || __MK66FX1M0__
gpl-3.0
skypeak/CataEMU_434
src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp
6
29015
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2012 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Hex_Lord_Malacrass SD%Complete: SDComment: SDCategory: Zul'Aman EndScriptData */ #include "ScriptPCH.h" #include "zulaman.h" #define YELL_AGGRO "Da shadow gonna fall on you... " #define SOUND_YELL_AGGRO 12041 #define YELL_SPIRIT_BOLTS "Your soul gonna bleed!" #define SOUND_YELL_SPIRIT_BOLTS 12047 #define YELL_DRAIN_POWER "Darkness comin\' for you" #define SOUND_YELL_DRAIN_POWER 12046 #define YELL_KILL_ONE "Dis a nightmare ya don\' wake up from!" #define SOUND_YELL_KILL_ONE 12043 #define YELL_KILL_TWO "Azzaga choogo zinn!" #define SOUND_YELL_KILL_TWO 12044 #define YELL_DEATH "Dis not... da end of me..." #define SOUND_YELL_DEATH 12051 #define SPELL_SPIRIT_BOLTS 43383 #define SPELL_DRAIN_POWER 44131 #define SPELL_SIPHON_SOUL 43501 #define MOB_TEMP_TRIGGER 23920 //Defines for various powers he uses after using soul drain //Druid #define SPELL_DR_LIFEBLOOM 43421 #define SPELL_DR_THORNS 43420 #define SPELL_DR_MOONFIRE 43545 //Hunter #define SPELL_HU_EXPLOSIVE_TRAP 43444 #define SPELL_HU_FREEZING_TRAP 43447 #define SPELL_HU_SNAKE_TRAP 43449 //Mage #define SPELL_MG_FIREBALL 41383 #define SPELL_MG_FROSTBOLT 43428 #define SPELL_MG_FROST_NOVA 43426 #define SPELL_MG_ICE_LANCE 43427 //Paladin #define SPELL_PA_CONSECRATION 43429 #define SPELL_PA_HOLY_LIGHT 43451 #define SPELL_PA_AVENGING_WRATH 43430 //Priest #define SPELL_PR_HEAL 41372 #define SPELL_PR_MIND_CONTROL 43550 #define SPELL_PR_MIND_BLAST 41374 #define SPELL_PR_SW_DEATH 41375 #define SPELL_PR_PSYCHIC_SCREAM 43432 #define SPELL_PR_PAIN_SUPP 44416 //Rogue #define SPELL_RO_BLIND 43433 #define SPELL_RO_SLICE_DICE 43457 #define SPELL_RO_WOUND_POISON 39665 //Shaman #define SPELL_SH_FIRE_NOVA 43436 #define SPELL_SH_HEALING_WAVE 43548 #define SPELL_SH_CHAIN_LIGHT 43435 //Warlock #define SPELL_WL_CURSE_OF_DOOM 43439 #define SPELL_WL_RAIN_OF_FIRE 43440 #define SPELL_WL_UNSTABLE_AFFL 35183 //Warrior #define SPELL_WR_SPELL_REFLECT 43443 #define SPELL_WR_WHIRLWIND 43442 #define SPELL_WR_MORTAL_STRIKE 43441 #define ORIENT 1.5696f #define POS_Y 921.2795f #define POS_Z 33.8883f static float Pos_X[4] = {112.8827f, 107.8827f, 122.8827f, 127.8827f}; static uint32 AddEntryList[8]= { 24240, //Alyson Antille 24241, //Thurg 24242, //Slither 24243, //Lord Raadan 24244, //Gazakroth 24245, //Fenstalker 24246, //Darkheart 24247 //Koragg }; enum AbilityTarget { ABILITY_TARGET_SELF = 0, ABILITY_TARGET_VICTIM = 1, ABILITY_TARGET_ENEMY = 2, ABILITY_TARGET_HEAL = 3, ABILITY_TARGET_BUFF = 4, ABILITY_TARGET_SPECIAL = 5 }; struct PlayerAbilityStruct { uint32 spell; AbilityTarget target; uint32 cooldown; //FIXME - it's never used }; static PlayerAbilityStruct PlayerAbility[][3] = { // 1 warrior {{SPELL_WR_SPELL_REFLECT, ABILITY_TARGET_SELF, 10000}, {SPELL_WR_WHIRLWIND, ABILITY_TARGET_SELF, 10000}, {SPELL_WR_MORTAL_STRIKE, ABILITY_TARGET_VICTIM, 6000}}, // 2 paladin {{SPELL_PA_CONSECRATION, ABILITY_TARGET_SELF, 10000}, {SPELL_PA_HOLY_LIGHT, ABILITY_TARGET_HEAL, 10000}, {SPELL_PA_AVENGING_WRATH, ABILITY_TARGET_SELF, 10000}}, // 3 hunter {{SPELL_HU_EXPLOSIVE_TRAP, ABILITY_TARGET_SELF, 10000}, {SPELL_HU_FREEZING_TRAP, ABILITY_TARGET_SELF, 10000}, {SPELL_HU_SNAKE_TRAP, ABILITY_TARGET_SELF, 10000}}, // 4 rogue {{SPELL_RO_WOUND_POISON, ABILITY_TARGET_VICTIM, 3000}, {SPELL_RO_SLICE_DICE, ABILITY_TARGET_SELF, 10000}, {SPELL_RO_BLIND, ABILITY_TARGET_ENEMY, 10000}}, // 5 priest {{SPELL_PR_PAIN_SUPP, ABILITY_TARGET_HEAL, 10000}, {SPELL_PR_HEAL, ABILITY_TARGET_HEAL, 10000}, {SPELL_PR_PSYCHIC_SCREAM, ABILITY_TARGET_SELF, 10000}}, // 5* shadow priest {{SPELL_PR_MIND_CONTROL, ABILITY_TARGET_ENEMY, 15000}, {SPELL_PR_MIND_BLAST, ABILITY_TARGET_ENEMY, 5000}, {SPELL_PR_SW_DEATH, ABILITY_TARGET_ENEMY, 10000}}, // 7 shaman {{SPELL_SH_FIRE_NOVA, ABILITY_TARGET_SELF, 10000}, {SPELL_SH_HEALING_WAVE, ABILITY_TARGET_HEAL, 10000}, {SPELL_SH_CHAIN_LIGHT, ABILITY_TARGET_ENEMY, 8000}}, // 8 mage {{SPELL_MG_FIREBALL, ABILITY_TARGET_ENEMY, 5000}, {SPELL_MG_FROSTBOLT, ABILITY_TARGET_ENEMY, 5000}, {SPELL_MG_ICE_LANCE, ABILITY_TARGET_SPECIAL, 2000}}, // 9 warlock {{SPELL_WL_CURSE_OF_DOOM, ABILITY_TARGET_ENEMY, 10000}, {SPELL_WL_RAIN_OF_FIRE, ABILITY_TARGET_ENEMY, 10000}, {SPELL_WL_UNSTABLE_AFFL, ABILITY_TARGET_ENEMY, 10000}}, // 11 druid {{SPELL_DR_LIFEBLOOM, ABILITY_TARGET_HEAL, 10000}, {SPELL_DR_THORNS, ABILITY_TARGET_SELF, 10000}, {SPELL_DR_MOONFIRE, ABILITY_TARGET_ENEMY, 8000}} }; struct boss_hexlord_addAI : public ScriptedAI { InstanceScript* instance; boss_hexlord_addAI(Creature* c) : ScriptedAI(c) { instance = c->GetInstanceScript(); } void Reset() {} void EnterCombat(Unit* /*who*/) {DoZoneInCombat();} void UpdateAI(const uint32 /*diff*/) { if (instance && instance->GetData(DATA_HEXLORDEVENT) != IN_PROGRESS) { EnterEvadeMode(); return; } DoMeleeAttackIfReady(); } }; class boss_hexlord_malacrass : public CreatureScript { public: boss_hexlord_malacrass() : CreatureScript("boss_hexlord_malacrass") { } struct boss_hex_lord_malacrassAI : public ScriptedAI { boss_hex_lord_malacrassAI(Creature* c) : ScriptedAI(c) { instance = c->GetInstanceScript(); SelectAddEntry(); for (uint8 i = 0; i < 4; ++i) AddGUID[i] = 0; } InstanceScript* instance; uint64 AddGUID[4]; uint32 AddEntry[4]; uint64 PlayerGUID; uint32 SpiritBolts_Timer; uint32 DrainPower_Timer; uint32 SiphonSoul_Timer; uint32 PlayerAbility_Timer; uint32 CheckAddState_Timer; uint32 ResetTimer; uint32 PlayerClass; void Reset() { if (instance) instance->SetData(DATA_HEXLORDEVENT, NOT_STARTED); SpiritBolts_Timer = 20000; DrainPower_Timer = 60000; SiphonSoul_Timer = 100000; PlayerAbility_Timer = 99999; CheckAddState_Timer = 5000; ResetTimer = 5000; SpawnAdds(); me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, 46916); me->SetByteValue(UNIT_FIELD_BYTES_2, 0, SHEATH_STATE_MELEE); } void EnterCombat(Unit* /*who*/) { if (instance) instance->SetData(DATA_HEXLORDEVENT, IN_PROGRESS); DoZoneInCombat(); me->MonsterYell(YELL_AGGRO, LANG_UNIVERSAL, 0); DoPlaySoundToSet(me, SOUND_YELL_AGGRO); for (uint8 i = 0; i < 4; ++i) { Unit* Temp = Unit::GetUnit((*me), AddGUID[i]); if (Temp && Temp->isAlive()) CAST_CRE(Temp)->AI()->AttackStart(me->getVictim()); else { EnterEvadeMode(); break; } } } void KilledUnit(Unit* /*victim*/) { switch (urand(0, 1)) { case 0: me->MonsterYell(YELL_KILL_ONE, LANG_UNIVERSAL, 0); DoPlaySoundToSet(me, SOUND_YELL_KILL_ONE); break; case 1: me->MonsterYell(YELL_KILL_TWO, LANG_UNIVERSAL, 0); DoPlaySoundToSet(me, SOUND_YELL_KILL_TWO); break; } } void JustDied(Unit* /*victim*/) { if (instance) instance->SetData(DATA_HEXLORDEVENT, DONE); me->MonsterYell(YELL_DEATH, LANG_UNIVERSAL, 0); DoPlaySoundToSet(me, SOUND_YELL_DEATH); for (uint8 i = 0; i < 4 ; ++i) { Unit* Temp = Unit::GetUnit((*me), AddGUID[i]); if (Temp && Temp->isAlive()) Temp->DealDamage(Temp, Temp->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } } void SelectAddEntry() { std::vector<uint32> AddList; for (uint8 i = 0; i < 8; ++i) AddList.push_back(AddEntryList[i]); while (AddList.size() > 4) AddList.erase(AddList.begin()+rand()%AddList.size()); uint8 i = 0; for (std::vector<uint32>::const_iterator itr = AddList.begin(); itr != AddList.end(); ++itr, ++i) AddEntry[i] = *itr; } void SpawnAdds() { for (uint8 i = 0; i < 4; ++i) { Creature* creature = (Unit::GetCreature((*me), AddGUID[i])); if (!creature || !creature->isAlive()) { if (creature) creature->setDeathState(DEAD); creature = me->SummonCreature(AddEntry[i], Pos_X[i], POS_Y, POS_Z, ORIENT, TEMPSUMMON_DEAD_DESPAWN, 0); if (creature) AddGUID[i] = creature->GetGUID(); } else { creature->AI()->EnterEvadeMode(); creature->SetPosition(Pos_X[i], POS_Y, POS_Z, ORIENT); creature->StopMoving(); } } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (ResetTimer <= diff) { if (me->IsWithinDist3d(119.223f, 1035.45f, 29.4481f, 10)) { EnterEvadeMode(); return; } ResetTimer = 5000; } else ResetTimer -= diff; if (CheckAddState_Timer <= diff) { for (uint8 i = 0; i < 4; ++i) if (Creature* temp = Unit::GetCreature(*me, AddGUID[i])) if (temp->isAlive() && !temp->getVictim()) temp->AI()->AttackStart(me->getVictim()); CheckAddState_Timer = 5000; } else CheckAddState_Timer -= diff; if (DrainPower_Timer <= diff) { DoCast(me, SPELL_DRAIN_POWER, true); me->MonsterYell(YELL_DRAIN_POWER, LANG_UNIVERSAL, 0); DoPlaySoundToSet(me, SOUND_YELL_DRAIN_POWER); DrainPower_Timer = urand(40000, 55000); // must cast in 60 sec, or buff/debuff will disappear } else DrainPower_Timer -= diff; if (SpiritBolts_Timer <= diff) { if (DrainPower_Timer < 12000) // channel 10 sec SpiritBolts_Timer = 13000; // cast drain power first else { DoCast(me, SPELL_SPIRIT_BOLTS, false); me->MonsterYell(YELL_SPIRIT_BOLTS, LANG_UNIVERSAL, 0); DoPlaySoundToSet(me, SOUND_YELL_SPIRIT_BOLTS); SpiritBolts_Timer = 40000; SiphonSoul_Timer = 10000; // ready to drain PlayerAbility_Timer = 99999; } } else SpiritBolts_Timer -= diff; if (SiphonSoul_Timer <= diff) { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 70, true); Unit* trigger = DoSpawnCreature(MOB_TEMP_TRIGGER, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 30000); if (!target || !trigger) { EnterEvadeMode(); return; } else { trigger->SetDisplayId(11686); trigger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); trigger->CastSpell(target, SPELL_SIPHON_SOUL, true); trigger->GetMotionMaster()->MoveChase(me); //DoCast(target, SPELL_SIPHON_SOUL, true); //me->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID()); //me->SetUInt32Value(UNIT_CHANNEL_SPELL, SPELL_SIPHON_SOUL); PlayerGUID = target->GetGUID(); PlayerAbility_Timer = urand(8000, 10000); PlayerClass = target->getClass() - 1; if (PlayerClass == CLASS_DRUID-1) PlayerClass = CLASS_DRUID; else if (PlayerClass == CLASS_PRIEST-1 && target->HasSpell(15473)) PlayerClass = CLASS_PRIEST; // shadow priest SiphonSoul_Timer = 99999; // buff lasts 30 sec } } else SiphonSoul_Timer -= diff; if (PlayerAbility_Timer <= diff) { //Unit* target = Unit::GetUnit(*me, PlayerGUID); //if (target && target->isAlive()) //{ UseAbility(); PlayerAbility_Timer = urand(8000, 10000); //} } else PlayerAbility_Timer -= diff; DoMeleeAttackIfReady(); } void UseAbility() { uint8 random = urand(0, 2); Unit* target = NULL; switch (PlayerAbility[PlayerClass][random].target) { case ABILITY_TARGET_SELF: target = me; break; case ABILITY_TARGET_VICTIM: target = me->getVictim(); break; case ABILITY_TARGET_ENEMY: default: target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); break; case ABILITY_TARGET_HEAL: target = DoSelectLowestHpFriendly(50, 0); break; case ABILITY_TARGET_BUFF: { std::list<Creature*> templist = DoFindFriendlyMissingBuff(50, PlayerAbility[PlayerClass][random].spell); if (!templist.empty()) target = *(templist.begin()); } break; } if (target) DoCast(target, PlayerAbility[PlayerClass][random].spell, false); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_hex_lord_malacrassAI(creature); } }; #define SPELL_BLOODLUST 43578 #define SPELL_CLEAVE 15496 class boss_thurg : public CreatureScript { public: boss_thurg() : CreatureScript("boss_thurg") { } struct boss_thurgAI : public boss_hexlord_addAI { boss_thurgAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 bloodlust_timer; uint32 cleave_timer; void Reset() { bloodlust_timer = 15000; cleave_timer = 10000; boss_hexlord_addAI::Reset(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (bloodlust_timer <= diff) { std::list<Creature*> templist = DoFindFriendlyMissingBuff(50, SPELL_BLOODLUST); if (!templist.empty()) { if (Unit* target = *(templist.begin())) DoCast(target, SPELL_BLOODLUST, false); } bloodlust_timer = 12000; } else bloodlust_timer -= diff; if (cleave_timer <= diff) { DoCast(me->getVictim(), SPELL_CLEAVE, false); cleave_timer = 12000; //3 sec cast } else cleave_timer -= diff; boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_thurgAI(creature); } }; #define SPELL_FLASH_HEAL 43575 #define SPELL_DISPEL_MAGIC 43577 class boss_alyson_antille : public CreatureScript { public: boss_alyson_antille() : CreatureScript("boss_alyson_antille") { } struct boss_alyson_antilleAI : public boss_hexlord_addAI { //Holy Priest boss_alyson_antilleAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 flashheal_timer; uint32 dispelmagic_timer; void Reset() { flashheal_timer = 2500; dispelmagic_timer = 10000; //AcquireGUID(); boss_hexlord_addAI::Reset(); } void AttackStart(Unit* who) { if (!who) return; if (who->isTargetableForAttack()) { if (me->Attack(who, false)) { me->GetMotionMaster()->MoveChase(who, 20); me->AddThreat(who, 0.0f); } } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (flashheal_timer <= diff) { Unit* target = DoSelectLowestHpFriendly(99, 30000); if (target) { if (target->IsWithinDistInMap(me, 50)) DoCast(target, SPELL_FLASH_HEAL, false); else { // bugged //me->GetMotionMaster()->Clear(); //me->GetMotionMaster()->MoveChase(target, 20); } } else { if (urand(0, 1)) target = DoSelectLowestHpFriendly(50, 0); else target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) DoCast(target, SPELL_DISPEL_MAGIC, false); } flashheal_timer = 2500; } else flashheal_timer -= diff; /*if (dispelmagic_timer <= diff) { if (urand(0, 1)) { Unit* target = SelectTarget(); DoCast(target, SPELL_DISPEL_MAGIC, false); } else me->CastSpell(SelectUnit(SELECT_TARGET_RANDOM, 0), SPELL_DISPEL_MAGIC, false); dispelmagic_timer = 12000; } else dispelmagic_timer -= diff;*/ boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_alyson_antilleAI(creature); } }; #define SPELL_FIREBOLT 43584 struct boss_gazakrothAI : public boss_hexlord_addAI { boss_gazakrothAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 firebolt_timer; void Reset() { firebolt_timer = 2000; boss_hexlord_addAI::Reset(); } void AttackStart(Unit* who) { if (!who) return; if (who->isTargetableForAttack()) { if (me->Attack(who, false)) { me->GetMotionMaster()->MoveChase(who, 20); me->AddThreat(who, 0.0f); } } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (firebolt_timer <= diff) { DoCast(me->getVictim(), SPELL_FIREBOLT, false); firebolt_timer = 700; } else firebolt_timer -= diff; boss_hexlord_addAI::UpdateAI(diff); } }; #define SPELL_FLAME_BREATH 43582 #define SPELL_THUNDERCLAP 43583 class boss_lord_raadan : public CreatureScript { public: boss_lord_raadan() : CreatureScript("boss_lord_raadan") { } struct boss_lord_raadanAI : public boss_hexlord_addAI { boss_lord_raadanAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 flamebreath_timer; uint32 thunderclap_timer; void Reset() { flamebreath_timer = 8000; thunderclap_timer = 13000; boss_hexlord_addAI::Reset(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (thunderclap_timer <= diff) { DoCast(me->getVictim(), SPELL_THUNDERCLAP, false); thunderclap_timer = 12000; } else thunderclap_timer -= diff; if (flamebreath_timer <= diff) { DoCast(me->getVictim(), SPELL_FLAME_BREATH, false); flamebreath_timer = 12000; } else flamebreath_timer -= diff; boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_lord_raadanAI(creature); } }; #define SPELL_PSYCHIC_WAIL 43590 class boss_darkheart : public CreatureScript { public: boss_darkheart() : CreatureScript("boss_darkheart") { } struct boss_darkheartAI : public boss_hexlord_addAI { boss_darkheartAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 psychicwail_timer; void Reset() { psychicwail_timer = 8000; boss_hexlord_addAI::Reset(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (psychicwail_timer <= diff) { DoCast(me->getVictim(), SPELL_PSYCHIC_WAIL, false); psychicwail_timer = 12000; } else psychicwail_timer -= diff; boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_darkheartAI(creature); } }; #define SPELL_VENOM_SPIT 43579 class boss_slither : public CreatureScript { public: boss_slither() : CreatureScript("boss_slither") { } struct boss_slitherAI : public boss_hexlord_addAI { boss_slitherAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 venomspit_timer; void Reset() { venomspit_timer = 5000; boss_hexlord_addAI::Reset(); } void AttackStart(Unit* who) { if (!who) return; if (who->isTargetableForAttack()) { if (me->Attack(who, false)) { me->GetMotionMaster()->MoveChase(who, 20); me->AddThreat(who, 0.0f); } } } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (venomspit_timer <= diff) { if (Unit* victim = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(victim, SPELL_VENOM_SPIT, false); venomspit_timer = 2500; } else venomspit_timer -= diff; boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_slitherAI(creature); } }; //Fenstalker #define SPELL_VOLATILE_INFECTION 43586 class boss_fenstalker : public CreatureScript { public: boss_fenstalker() : CreatureScript("boss_fenstalker") { } struct boss_fenstalkerAI : public boss_hexlord_addAI { boss_fenstalkerAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 volatileinf_timer; void Reset() { volatileinf_timer = 15000; boss_hexlord_addAI::Reset(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (volatileinf_timer <= diff) { // core bug me->getVictim()->CastSpell(me->getVictim(), SPELL_VOLATILE_INFECTION, false); volatileinf_timer = 12000; } else volatileinf_timer -= diff; boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_fenstalkerAI(creature); } }; //Koragg #define SPELL_COLD_STARE 43593 #define SPELL_MIGHTY_BLOW 43592 class boss_koragg : public CreatureScript { public: boss_koragg() : CreatureScript("boss_koragg") { } struct boss_koraggAI : public boss_hexlord_addAI { boss_koraggAI(Creature* c) : boss_hexlord_addAI(c) {} uint32 coldstare_timer; uint32 mightyblow_timer; void Reset() { coldstare_timer = 15000; mightyblow_timer = 10000; boss_hexlord_addAI::Reset(); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (mightyblow_timer <= diff) { DoCast(me->getVictim(), SPELL_MIGHTY_BLOW, false); mightyblow_timer = 12000; } if (coldstare_timer <= diff) { if (Unit* victim = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) DoCast(victim, SPELL_COLD_STARE, false); coldstare_timer = 12000; } boss_hexlord_addAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_koraggAI(creature); } }; void AddSC_boss_hex_lord_malacrass() { new boss_hexlord_malacrass(); new boss_thurg(); // new boss_gazakroth(); new boss_lord_raadan(); new boss_darkheart(); new boss_slither(); new boss_fenstalker(); new boss_koragg(); new boss_alyson_antille(); }
gpl-3.0
jmue/cppcheck
lib/checksizeof.cpp
7
17214
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2015 Daniel Marjamäki and Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checksizeof.h" #include "symboldatabase.h" #include <algorithm> #include <cctype> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckSizeof instance; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void CheckSizeof::checkSizeofForNumericParameter() { if (!_settings->isEnabled("warning")) return; const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t i = 0; i < functions; ++i) { const Scope * scope = symbolDatabase->functionScopes[i]; for (const Token* tok = scope->classStart->next(); tok != scope->classEnd; tok = tok->next()) { if (Token::Match(tok, "sizeof ( %num% )") || Token::Match(tok, "sizeof %num%")) { sizeofForNumericParameterError(tok); } } } } void CheckSizeof::sizeofForNumericParameterError(const Token *tok) { reportError(tok, Severity::warning, "sizeofwithnumericparameter", "Suspicious usage of 'sizeof' with a numeric constant as parameter.\n" "It is unusual to use a constant value with sizeof. For example, 'sizeof(10)'" " returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10. 'sizeof('A')'" " and 'sizeof(char)' can return different results."); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void CheckSizeof::checkSizeofForArrayParameter() { if (!_settings->isEnabled("warning")) return; const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t i = 0; i < functions; ++i) { const Scope * scope = symbolDatabase->functionScopes[i]; for (const Token* tok = scope->classStart->next(); tok != scope->classEnd; tok = tok->next()) { if (Token::Match(tok, "sizeof ( %var% )") || Token::Match(tok, "sizeof %var% !![")) { const Token* varTok = tok->next(); if (varTok->str() == "(") { varTok = varTok->next(); } const Variable *var = varTok->variable(); if (var && var->isArray() && var->isArgument() && !var->isReference()) sizeofForArrayParameterError(tok); } } } } void CheckSizeof::sizeofForArrayParameterError(const Token *tok) { reportError(tok, Severity::warning, "sizeofwithsilentarraypointer", "Using 'sizeof' on array given as function argument " "returns size of a pointer.\n" "Using 'sizeof' for array given as function argument returns the size of a pointer. " "It does not return the size of the whole array in bytes as might be " "expected. For example, this code:\n" " int f(char a[100]) {\n" " return sizeof(a);\n" " }\n" "returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the " "size of the array in bytes)." ); } void CheckSizeof::checkSizeofForPointerSize() { if (!_settings->isEnabled("warning")) return; const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const std::size_t functions = symbolDatabase->functionScopes.size(); for (std::size_t i = 0; i < functions; ++i) { const Scope * scope = symbolDatabase->functionScopes[i]; for (const Token* tok = scope->classStart; tok != scope->classEnd; tok = tok->next()) { const Token* tokSize; const Token* tokFunc; const Token *variable = nullptr; const Token *variable2 = nullptr; // Find any function that may use sizeof on a pointer // Once leaving those tests, it is mandatory to have: // - variable matching the used pointer // - tokVar pointing on the argument where sizeof may be used if (Token::Match(tok, "[*;{}] %var% = malloc|alloca (")) { variable = tok->next(); tokSize = tok->tokAt(5); tokFunc = tok->tokAt(3); } else if (Token::Match(tok, "[*;{}] %var% = calloc (")) { variable = tok->next(); tokSize = tok->tokAt(5)->nextArgument(); tokFunc = tok->tokAt(3); } else if (Token::Match(tok, "return malloc|alloca (")) { tokSize = tok->tokAt(3); tokFunc = tok->next(); } else if (Token::simpleMatch(tok, "return calloc (")) { tokSize = tok->tokAt(3)->nextArgument(); tokFunc = tok->next(); } else if (Token::simpleMatch(tok, "memset (")) { variable = tok->tokAt(2); tokSize = variable->nextArgument(); if (tokSize) tokSize = tokSize->nextArgument(); tokFunc = tok; } else if (Token::Match(tok, "memcpy|memcmp|memmove|strncpy|strncmp|strncat (")) { variable = tok->tokAt(2); variable2 = variable->nextArgument(); if (!variable2) continue; tokSize = variable2->nextArgument(); tokFunc = tok; } else { continue; } if (tokFunc && tokSize) { for (const Token* tok2 = tokSize; tok2 != tokFunc->linkAt(1); tok2 = tok2->next()) { if (Token::simpleMatch(tok2, "/ sizeof")) divideBySizeofError(tok2, tokFunc->str()); } } if (!variable) continue; // Ensure the variables are in the symbol database // Also ensure the variables are pointers // Only keep variables which are pointers const Variable *var = variable->variable(); if (!var || !var->isPointer() || var->isArray()) { variable = 0; } if (variable2) { var = variable2->variable(); if (!var || !var->isPointer() || var->isArray()) { variable2 = 0; } } // If there are no pointer variable at this point, there is // no need to continue if (variable == 0 && variable2 == 0) { continue; } // Jump to the next sizeof token in the function and in the parameter // This is to allow generic operations with sizeof for (; tokSize && tokSize->str() != ")" && tokSize->str() != "," && tokSize->str() != "sizeof"; tokSize = tokSize->next()) {} // Now check for the sizeof usage. Once here, everything using sizeof(varid) or sizeof(&varid) // looks suspicious // Do it for first variable if (variable && (Token::Match(tokSize, "sizeof ( &| %varid% )", variable->varId()) || Token::Match(tokSize, "sizeof &| %varid% !!.", variable->varId()))) { sizeofForPointerError(variable, variable->str()); } else if (variable2 && (Token::Match(tokSize, "sizeof ( &| %varid% )", variable2->varId()) || Token::Match(tokSize, "sizeof &| %varid% !!.", variable2->varId()))) { sizeofForPointerError(variable2, variable2->str()); } } } } void CheckSizeof::sizeofForPointerError(const Token *tok, const std::string &varname) { reportError(tok, Severity::warning, "pointerSize", "Size of pointer '" + varname + "' used instead of size of its data.\n" "Size of pointer '" + varname + "' used instead of size of its data. " "This is likely to lead to a buffer overflow. You probably intend to " "write 'sizeof(*" + varname + ")'."); } void CheckSizeof::divideBySizeofError(const Token *tok, const std::string &memfunc) { reportError(tok, Severity::warning, "sizeofDivisionMemfunc", "Division by result of sizeof(). " + memfunc + "() expects a size in bytes, did you intend to multiply instead?"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CheckSizeof::sizeofsizeof() { if (!_settings->isEnabled("warning")) return; for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "sizeof (| sizeof")) { sizeofsizeofError(tok); tok = tok->next(); } } } void CheckSizeof::sizeofsizeofError(const Token *tok) { reportError(tok, Severity::warning, "sizeofsizeof", "Calling 'sizeof' on 'sizeof'.\n" "Calling sizeof for 'sizeof looks like a suspicious code and " "most likely there should be just one 'sizeof'. The current " "code is equivalent to 'sizeof(size_t)'"); } //----------------------------------------------------------------------------- void CheckSizeof::sizeofCalculation() { if (!_settings->isEnabled("warning")) return; const bool printInconclusive = _settings->inconclusive; for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::simpleMatch(tok, "sizeof (")) { const Token *argument = tok->next()->astOperand2(); if (argument && argument->isCalculation() && (!argument->isExpandedMacro() || printInconclusive)) sizeofCalculationError(argument, argument->isExpandedMacro()); } } } void CheckSizeof::sizeofCalculationError(const Token *tok, bool inconclusive) { reportError(tok, Severity::warning, "sizeofCalculation", "Found calculation inside sizeof().", 0U, inconclusive); } //----------------------------------------------------------------------------- // Check for code like sizeof()*sizeof() or sizeof(ptr)/value //----------------------------------------------------------------------------- void CheckSizeof::suspiciousSizeofCalculation() { if (!_settings->isEnabled("warning") || !_settings->inconclusive) return; // TODO: Use AST here. This should be possible as soon as sizeof without brackets is correctly parsed for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::simpleMatch(tok, "sizeof (")) { const Token* const end = tok->linkAt(1); const Variable* var = end->previous()->variable(); if (end->strAt(-1) == "*" || (var && var->isPointer() && !var->isArray())) { if (end->strAt(1) == "/") divideSizeofError(tok); } else if (Token::simpleMatch(end, ") * sizeof") && end->next()->astOperand1() == tok->next()) multiplySizeofError(tok); } } } void CheckSizeof::multiplySizeofError(const Token *tok) { reportError(tok, Severity::warning, "multiplySizeof", "Multiplying sizeof() with sizeof() indicates a logic error.", 0U, true); } void CheckSizeof::divideSizeofError(const Token *tok) { reportError(tok, Severity::warning, "divideSizeof", "Division of result of sizeof() on pointer type.\n" "Division of result of sizeof() on pointer type. sizeof() returns the size of the pointer, " "not the size of the memory area it points to.", 0U, true); } void CheckSizeof::sizeofVoid() { if (!_settings->isEnabled("portability")) return; for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::simpleMatch(tok, "sizeof ( )")) { // "sizeof(void)" gets simplified to sizeof ( ) sizeofVoidError(tok); } else if (Token::Match(tok, "sizeof ( * %var% )") && tok->tokAt(3)->variable() && (Token::Match(tok->tokAt(3)->variable()->typeStartToken(), "void * !!*")) && (!tok->tokAt(3)->variable()->isArray())) { // sizeof(*p) where p is of type "void*" sizeofDereferencedVoidPointerError(tok, tok->strAt(3)); } else if (Token::Match(tok, "%name% +|-|++|--") || Token::Match(tok, "+|-|++|-- %name%")) { // Arithmetic operations on variable of type "void*" const int index = (tok->isName()) ? 0 : 1; const Variable* var = tok->tokAt(index)->variable(); if (var && !var->isArray() && Token::Match(var->typeStartToken(), "void * !!*")) { std::string varname = tok->strAt(index); // In case this 'void *' var is a member then go back to the main object const Token* tok2 = tok->tokAt(index); if (index == 0) { bool isMember = false; while (Token::simpleMatch(tok2->previous(), ".")) { isMember = true; if (Token::simpleMatch(tok2->tokAt(-2), ")")) tok2 = tok2->linkAt(-2); else if (Token::simpleMatch(tok2->tokAt(-2), "]")) tok2 = tok2->linkAt(-2)->previous(); else tok2 = tok2->tokAt(-2); } if (isMember) { // Get 'struct.member' complete name (without spaces) varname = tok2->stringifyList(tok->next()); varname.erase(std::remove_if(varname.begin(), varname.end(), static_cast<int (*)(int)>(std::isspace)), varname.end()); } } // Check for cast on operations with '+|-' if (Token::Match(tok, "%name% +|-")) { // Check for cast expression if (Token::simpleMatch(tok2->previous(), ")") && !Token::Match(tok2->previous()->link(), "( const| void *")) continue; if (tok2->strAt(-1) == "&") // Check for reference operator continue; } arithOperationsOnVoidPointerError(tok, varname, var->typeStartToken()->stringifyList(var->typeEndToken()->next())); } } } } void CheckSizeof::sizeofVoidError(const Token *tok) { const std::string message = "Behaviour of 'sizeof(void)' is not covered by the ISO C standard."; const std::string verbose = message + " A value for 'sizeof(void)' is defined only as part of a GNU C extension, which defines 'sizeof(void)' to be 1."; reportError(tok, Severity::portability, "sizeofVoid", message + "\n" + verbose); } void CheckSizeof::sizeofDereferencedVoidPointerError(const Token *tok, const std::string &varname) { const std::string message = "'*" + varname + "' is of type 'void', the behaviour of 'sizeof(void)' is not covered by the ISO C standard."; const std::string verbose = message + " A value for 'sizeof(void)' is defined only as part of a GNU C extension, which defines 'sizeof(void)' to be 1."; reportError(tok, Severity::portability, "sizeofDereferencedVoidPointer", message + "\n" + verbose); } void CheckSizeof::arithOperationsOnVoidPointerError(const Token* tok, const std::string &varname, const std::string &vartype) { const std::string message = "'" + varname + "' is of type '" + vartype + "'. When using void pointers in calculations, the behaviour is undefined."; const std::string verbose = message + " Arithmetic operations on 'void *' is a GNU C extension, which defines the 'sizeof(void)' to be 1."; reportError(tok, Severity::portability, "arithOperationsOnVoidPointer", message + "\n" + verbose); }
gpl-3.0
MediffRobotics/DeepRobotics
DeepLearnMaterials/DDPG/gym_torcs/vtorcs-RL-color/src/modules/track/track2.cpp
7
39328
/*************************************************************************** file : track2.cpp created : Sun Jan 30 22:57:25 CET 2000 copyright : (C) 2000 by Eric Espie email : torcs@free.fr version : $Id: track2.cpp,v 1.10.6.1 2008/11/09 17:50:23 berniw Exp $ ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdlib.h> #include <math.h> #include <stdio.h> #include <tgf.h> #include <track.h> #include "trackinc.h" static tdble xmin, xmax, ymin, ymax, zmin, zmax; #define TSTX(x) \ if (xmin > (x)) xmin = (x); \ if (xmax < (x)) xmax = (x); #define TSTY(y) \ if (ymin > (y)) ymin = (y); \ if (ymax < (y)) ymax = (y); #define TSTZ(z) \ if (zmin > (z)) zmin = (z); \ if (zmax < (z)) zmax = (z); /* * Sides global variables */ static char *KeySideSurface[2] = {TRK_ATT_RSSURF, TRK_ATT_LSSURF}; static char *KeySideWidth[2] = {TRK_ATT_RSW, TRK_ATT_LSW}; static char *KeySideStartWidth[2] = {TRK_ATT_RSWS, TRK_ATT_LSWS}; static char *KeySideEndWidth[2] = {TRK_ATT_RSWE, TRK_ATT_LSWE}; static char *KeySideBankType[2] = {TRK_ATT_RST, TRK_ATT_LST}; static tdble sideEndWidth[2]; static tdble sideStartWidth[2]; static int sideBankType[2]; static char *sideMaterial[2]; static int envIndex; static void InitSides(void *TrackHandle, char *section) { int side; for (side = 0; side < 2; side++) { sideMaterial[side] = GfParmGetStr(TrackHandle, section, KeySideSurface[side], TRK_VAL_GRASS); sideEndWidth[side] = GfParmGetNum(TrackHandle, section, KeySideWidth[side], (char*)NULL, 0.0); /* banking of borders */ if (strcmp(TRK_VAL_LEVEL, GfParmGetStr(TrackHandle, section, KeySideBankType[side], TRK_VAL_LEVEL)) == 0) { sideBankType[side] = 0; } else { sideBankType[side] = 1; } } } static void AddSides(tTrackSeg *curSeg, void *TrackHandle, char *section, int curStep, int steps) { tTrackSeg *curSide; tdble x, y, z; tdble al, alfl; int j; tdble x1, x2, y1, y2; tdble sw, ew; tdble minWidth; tdble maxWidth; int type; int side; char *material; tdble Kew; char path[256]; char path2[256]; x = y = z = 0; sprintf(path, "%s/%s", section, TRK_LST_SEG); for (side = 0; side < 2; side++) { if (curStep == 0) { sw = GfParmGetCurNum(TrackHandle, path, KeySideStartWidth[side], (char*)NULL,sideEndWidth[side]); ew = GfParmGetCurNum(TrackHandle, path, KeySideEndWidth[side], (char*)NULL, sw); sideStartWidth[side] = sw; sideEndWidth[side] = ew; } else { sw = sideStartWidth[side]; ew = sideEndWidth[side]; } Kew = (ew - sw) / (tdble)steps; ew = sw + (tdble)(curStep+1) * Kew; sw = sw + (tdble)(curStep) * Kew; if ((sw == 0.0) && (ew == 0.0)) { /* no additional track side */ continue; } curSide = (tTrackSeg*)calloc(1, sizeof(tTrackSeg)); if (side == 1) { curSeg->lside = curSide; curSide->vertex[TR_SR] = curSeg->vertex[TR_SL]; curSide->vertex[TR_ER] = curSeg->vertex[TR_EL]; curSide->type2 = TR_LSIDE; } else { curSeg->rside = curSide; curSide->vertex[TR_SL] = curSeg->vertex[TR_SR]; curSide->vertex[TR_EL] = curSeg->vertex[TR_ER]; curSide->type2 = TR_RSIDE; } type = sideBankType[side]; curSide->startWidth = sw; curSide->endWidth = ew; curSide->width = minWidth = MIN(sw, ew); maxWidth = MAX(sw, ew); curSide->type = curSeg->type; material = GfParmGetCurStr(TrackHandle, path, KeySideSurface[side], sideMaterial[side]); sideMaterial[side] = curSide->material = material; sprintf(path2, "%s/%s/%s", TRK_SECT_SURFACES, TRK_LST_SURF, material); curSide->kFriction = GfParmGetNum(TrackHandle, path2, TRK_ATT_FRICTION, (char*)NULL, 0.8); curSide->kRollRes = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROLLRES, (char*)NULL, 0.001); curSide->kRoughness = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROUGHT, (char*)NULL, 0.0) / 2.0; curSide->kRoughWaveLen = 2.0 * PI / GfParmGetNum(TrackHandle, path2, TRK_ATT_ROUGHTWL, (char*)NULL, 1.0); curSide->envIndex = envIndex; curSide->angle[TR_XS] = curSeg->angle[TR_XS] * (tdble)type; curSide->angle[TR_XE] = curSeg->angle[TR_XE] * (tdble)type; curSide->angle[TR_ZS] = curSeg->angle[TR_ZS]; curSide->angle[TR_ZE] = curSeg->angle[TR_ZE]; curSide->angle[TR_CS] = curSeg->angle[TR_CS]; switch(curSeg->type) { case TR_STR: curSide->length = curSeg->length; switch(side) { case 1: curSide->vertex[TR_SL].x = curSide->vertex[TR_SR].x + sw * curSeg->rgtSideNormal.x; curSide->vertex[TR_SL].y = curSide->vertex[TR_SR].y + sw * curSeg->rgtSideNormal.y; curSide->vertex[TR_SL].z = curSide->vertex[TR_SR].z + (tdble)type * sw * tan(curSeg->angle[TR_XS]); x = curSide->vertex[TR_EL].x = curSide->vertex[TR_ER].x + ew * curSeg->rgtSideNormal.x; y = curSide->vertex[TR_EL].y = curSide->vertex[TR_ER].y + ew * curSeg->rgtSideNormal.y; z = curSide->vertex[TR_EL].z = curSide->vertex[TR_ER].z + (tdble)type * ew * tan(curSeg->angle[TR_XE]); break; case 0: curSide->vertex[TR_SR].x = curSide->vertex[TR_SL].x - sw * curSeg->rgtSideNormal.x; curSide->vertex[TR_SR].y = curSide->vertex[TR_SL].y - sw * curSeg->rgtSideNormal.y; curSide->vertex[TR_SR].z = curSide->vertex[TR_SL].z - (tdble)type * sw * tan(curSeg->angle[TR_XS]); x = curSide->vertex[TR_ER].x = curSide->vertex[TR_EL].x - ew * curSeg->rgtSideNormal.x; y = curSide->vertex[TR_ER].y = curSide->vertex[TR_EL].y - ew * curSeg->rgtSideNormal.y; z = curSide->vertex[TR_ER].z = curSide->vertex[TR_EL].z - (tdble)type * ew * tan(curSeg->angle[TR_XE]); break; } curSide->angle[TR_YR] = atan2(curSide->vertex[TR_ER].z - curSide->vertex[TR_SR].z, curSide->length); curSide->angle[TR_YL] = atan2(curSide->vertex[TR_EL].z - curSide->vertex[TR_SL].z, curSide->length); curSide->Kzl = tan(curSide->angle[TR_YR]); curSide->Kzw = (curSide->angle[TR_XE] - curSide->angle[TR_XS]) / curSide->length; curSide->Kyl = (ew - sw) / curSide->length; curSide->rgtSideNormal.x = curSeg->rgtSideNormal.x; curSide->rgtSideNormal.y = curSeg->rgtSideNormal.y; TSTX(x); TSTY(y); TSTZ(z); break; case TR_LFT: curSide->center.x = curSeg->center.x; curSide->center.y = curSeg->center.y; switch(side) { case 1: curSide->radius = curSeg->radiusl - sw / 2.0; curSide->radiusr = curSeg->radiusl; curSide->radiusl = curSeg->radiusl - maxWidth; curSide->arc = curSeg->arc; curSide->length = curSide->radius * curSide->arc; curSide->vertex[TR_SL].x = curSide->vertex[TR_SR].x - sw * cos(curSide->angle[TR_CS]); curSide->vertex[TR_SL].y = curSide->vertex[TR_SR].y - sw * sin(curSide->angle[TR_CS]); curSide->vertex[TR_SL].z = curSide->vertex[TR_SR].z + (tdble)type * sw * tan(curSeg->angle[TR_XS]); curSide->vertex[TR_EL].x = curSide->vertex[TR_ER].x - ew * cos(curSide->angle[TR_CS] + curSide->arc); curSide->vertex[TR_EL].y = curSide->vertex[TR_ER].y - ew * sin(curSide->angle[TR_CS] + curSide->arc); z = curSide->vertex[TR_EL].z = curSide->vertex[TR_ER].z + (tdble)type * ew * tan(curSeg->angle[TR_XE]); curSide->angle[TR_YR] = atan2(curSide->vertex[TR_ER].z - curSide->vertex[TR_SR].z, curSide->arc * curSide->radiusr); curSide->angle[TR_YL] = atan2(curSide->vertex[TR_EL].z - curSide->vertex[TR_SL].z, curSide->arc * curSide->radiusl); curSide->Kzl = tan(curSide->angle[TR_YR]) * curSide->radiusr; curSide->Kzw = (curSide->angle[TR_XE] - curSide->angle[TR_XS]) / curSide->arc; curSide->Kyl = (ew - sw) / curSide->arc; /* to find the boundary */ al = (curSide->angle[TR_ZE] - curSide->angle[TR_ZS])/36.0; alfl = curSide->angle[TR_ZS]; for (j = 0; j < 36; j++) { alfl += al; x1 = curSide->center.x + (curSide->radiusl) * sin(alfl); /* location of end */ y1 = curSide->center.y - (curSide->radiusl) * cos(alfl); TSTX(x1); TSTY(y1); } TSTZ(z); break; case 0: curSide->radius = curSeg->radiusr + sw / 2.0; curSide->radiusl = curSeg->radiusr; curSide->radiusr = curSeg->radiusr + maxWidth; curSide->arc = curSeg->arc; curSide->length = curSide->radius * curSide->arc; curSide->vertex[TR_SR].x = curSide->vertex[TR_SL].x + sw * cos(curSide->angle[TR_CS]); curSide->vertex[TR_SR].y = curSide->vertex[TR_SL].y + sw * sin(curSide->angle[TR_CS]); curSide->vertex[TR_SR].z = curSide->vertex[TR_SL].z - (tdble)type * sw * tan(curSeg->angle[TR_XS]); curSide->vertex[TR_ER].x = curSide->vertex[TR_EL].x + ew * cos(curSide->angle[TR_CS] + curSide->arc); curSide->vertex[TR_ER].y = curSide->vertex[TR_EL].y + ew * sin(curSide->angle[TR_CS] + curSide->arc); z = curSide->vertex[TR_ER].z = curSide->vertex[TR_EL].z - (tdble)type * ew * tan(curSeg->angle[TR_XE]); curSide->angle[TR_YR] = atan2(curSide->vertex[TR_ER].z - curSide->vertex[TR_SR].z, curSide->arc * curSide->radiusr); curSide->angle[TR_YL] = atan2(curSide->vertex[TR_EL].z - curSide->vertex[TR_SL].z, curSide->arc * curSide->radiusl); curSide->Kzl = tan(curSide->angle[TR_YR]) * (curSide->radiusr); curSide->Kzw = (curSide->angle[TR_XE] - curSide->angle[TR_XS]) / curSide->arc; curSide->Kyl = (ew - sw) / curSide->arc; /* to find the boundary */ al = (curSide->angle[TR_ZE] - curSide->angle[TR_ZS])/36.0; alfl = curSide->angle[TR_ZS]; for (j = 0; j < 36; j++) { alfl += al; x2 = curSide->center.x + (curSide->radiusr) * sin(alfl); /* location of end */ y2 = curSide->center.y - (curSide->radiusr) * cos(alfl); TSTX(x2); TSTY(y2); } TSTZ(z); break; } break; case TR_RGT: curSide->center.x = curSeg->center.x; curSide->center.y = curSeg->center.y; switch(side) { case 1: curSide->radius = curSeg->radiusl + sw / 2.0; curSide->radiusr = curSeg->radiusl; curSide->radiusl = curSeg->radiusl + maxWidth; curSide->arc = curSeg->arc; curSide->length = curSide->radius * curSide->arc; curSide->vertex[TR_SL].x = curSide->vertex[TR_SR].x + sw * cos(curSide->angle[TR_CS]); curSide->vertex[TR_SL].y = curSide->vertex[TR_SR].y + sw * sin(curSide->angle[TR_CS]); curSide->vertex[TR_SL].z = curSide->vertex[TR_SR].z + (tdble)type * sw * tan(curSeg->angle[TR_XS]); curSide->vertex[TR_EL].x = curSide->vertex[TR_ER].x + ew * cos(curSide->angle[TR_CS] - curSide->arc); curSide->vertex[TR_EL].y = curSide->vertex[TR_ER].y + ew * sin(curSide->angle[TR_CS] - curSide->arc); z = curSide->vertex[TR_EL].z = curSide->vertex[TR_ER].z + (tdble)type * ew * tan(curSeg->angle[TR_XE]); curSide->angle[TR_YR] = atan2(curSide->vertex[TR_ER].z - curSide->vertex[TR_SR].z, curSide->arc * curSide->radiusr); curSide->angle[TR_YL] = atan2(curSide->vertex[TR_EL].z - curSide->vertex[TR_SL].z, curSide->arc * curSide->radiusl); curSide->Kzl = tan(curSide->angle[TR_YR]) * curSide->radiusr; curSide->Kzw = (curSide->angle[TR_XE] - curSide->angle[TR_XS]) / curSide->arc; curSide->Kyl = (ew - sw) / curSide->arc; /* to find the boundary */ al = (curSide->angle[TR_ZE] - curSide->angle[TR_ZS])/36.0; alfl = curSide->angle[TR_ZS]; for (j = 0; j < 36; j++) { alfl += al; x1 = curSide->center.x - (curSide->radiusl) * sin(alfl); /* location of end */ y1 = curSide->center.y + (curSide->radiusl) * cos(alfl); TSTX(x1); TSTY(y1); } TSTZ(z); break; case 0: curSide->radius = curSeg->radiusr - sw / 2.0; curSide->radiusl = curSeg->radiusr; curSide->radiusr = curSeg->radiusr - maxWidth; curSide->arc = curSeg->arc; curSide->length = curSide->radius * curSide->arc; curSide->vertex[TR_SR].x = curSide->vertex[TR_SL].x - sw * cos(curSide->angle[TR_CS]); curSide->vertex[TR_SR].y = curSide->vertex[TR_SL].y - sw * sin(curSide->angle[TR_CS]); curSide->vertex[TR_SR].z = curSide->vertex[TR_SL].z - (tdble)type * sw * tan(curSeg->angle[TR_XS]); curSide->vertex[TR_ER].x = curSide->vertex[TR_EL].x - ew * cos(curSide->angle[TR_CS] - curSide->arc); curSide->vertex[TR_ER].y = curSide->vertex[TR_EL].y - ew * sin(curSide->angle[TR_CS] - curSide->arc); z = curSide->vertex[TR_ER].z = curSide->vertex[TR_EL].z - (tdble)type * ew * tan(curSeg->angle[TR_XE]); curSide->angle[TR_YR] = atan2(curSide->vertex[TR_ER].z - curSide->vertex[TR_SR].z, curSide->arc * curSide->radiusr); curSide->angle[TR_YL] = atan2(curSide->vertex[TR_EL].z - curSide->vertex[TR_SL].z, curSide->arc * curSide->radiusl); curSide->Kzl = tan(curSide->angle[TR_YR]) * (curSide->radiusr); curSide->Kzw = (curSide->angle[TR_XE] - curSide->angle[TR_XS]) / curSide->arc; curSide->Kyl = (ew - sw) / curSide->arc; /* to find the boundary */ al = (curSide->angle[TR_ZE] - curSide->angle[TR_ZS])/36.0; alfl = curSide->angle[TR_ZS]; for (j = 0; j < 36; j++) { alfl += al; x2 = curSide->center.x - (curSide->radiusr) * sin(alfl); /* location of end */ y2 = curSide->center.y - (curSide->radiusr) * cos(alfl); TSTX(x2); TSTY(y2); } TSTZ(z); break; } break; } } } static void normSeg(tTrackSeg *curSeg) { curSeg->vertex[TR_SR].x -= xmin; curSeg->vertex[TR_SR].y -= ymin; curSeg->vertex[TR_SR].z -= zmin; curSeg->vertex[TR_SL].x -= xmin; curSeg->vertex[TR_SL].y -= ymin; curSeg->vertex[TR_SL].z -= zmin; curSeg->vertex[TR_ER].x -= xmin; curSeg->vertex[TR_ER].y -= ymin; curSeg->vertex[TR_ER].z -= zmin; curSeg->vertex[TR_EL].x -= xmin; curSeg->vertex[TR_EL].y -= ymin; curSeg->vertex[TR_EL].z -= zmin; curSeg->center.x -= xmin; curSeg->center.y -= ymin; } static void CreateSegRing(void *TrackHandle, char *section, tTrackSeg **pRoot, tdble *pLength, int *pNseg, tTrackSeg *start, tTrackSeg *end, int ext) { int j; int segread, curindex; tdble radius; tdble innerradius; tdble arc; tdble length; tTrackSeg *curSeg; tTrackSeg *root; tdble alf; tdble xr, yr, newxr, newyr; tdble xl, yl, newxl, newyl; tdble cenx, ceny; tdble width, wi2; tdble x1, x2, y1, y2; tdble al, alfl; tdble zsl, zsr, zel, zer, zs, ze; tdble bankings, bankinge, dz, dzl, dzr; tdble etgt, stgt; tdble etgtl, stgtl; tdble etgtr, stgtr; int steps, curStep; char *segtype = (char*)NULL; char *material; char *segName; int type; tdble kFriction, kRollRes; tdble kRoughness, kRoughWaveLenP, kRoughWaveLen; char *profil; tdble totLength; tdble tl, dtl, T1l, T2l; tdble tr, dtr, T1r, T2r; tdble curzel, curzer, curArc, curLength, curzsl, curzsr; tdble grade; char path[256]; char path2[256]; #define MAX_TMP_INTS 256 int mi[MAX_TMP_INTS]; int ind = 0; radius = arc = length = alf = xr = yr = newxr = newyr = xl = yl = 0; zel = zer = etgtl = etgtr = newxl = newyl = 0; type = 0; width = GfParmGetNum(TrackHandle, section, TRK_ATT_WIDTH, (char*)NULL, 15.0); wi2 = width / 2.0; grade = -100000.0; root = (tTrackSeg*)NULL; totLength = 0; sprintf(path, "%s/%s", section, TRK_LST_SEG); if (start == NULL) { xr = xl = 0.0; yr = 0.0; yl = width; alf = 0.0; zsl = zsr = zel = zer = zs = ze = 0.0; stgt = etgt = 0.0; stgtl = etgtl = 0.0; stgtr = etgtr = 0.0; } else { GfParmListSeekFirst(TrackHandle, path); segtype = GfParmGetCurStr(TrackHandle, path, TRK_ATT_TYPE, ""); if (strcmp(segtype, TRK_VAL_STR) == 0) { } else if (strcmp(segtype, TRK_VAL_LFT) == 0) { } else if (strcmp(segtype, TRK_VAL_RGT) == 0) { xr = start->vertex[TR_SR].x; yr = start->vertex[TR_SR].y; zsl = zsr = zel = zer = zs = ze = start->vertex[TR_SR].z; alf = start->angle[TR_ZS]; xl = xr - width * sin(alf); yl = yr + width * cos(alf); stgt = etgt = 0.0; stgtl = etgtl = 0.0; stgtr = etgtr = 0.0; } } /* Main Track */ material = GfParmGetStr(TrackHandle, section, TRK_ATT_SURF, TRK_VAL_ASPHALT); sprintf(path2, "%s/%s/%s", TRK_SECT_SURFACES, TRK_LST_SURF, material); kFriction = GfParmGetNum(TrackHandle, path2, TRK_ATT_FRICTION, (char*)NULL, 0.8); kRollRes = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROLLRES, (char*)NULL, 0.001); kRoughness = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROUGHT, (char*)NULL, 0.0) / 2.0; kRoughWaveLenP = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROUGHTWL, (char*)NULL, 1.0); kRoughWaveLen = 2.0 * PI / kRoughWaveLenP; envIndex = 0; InitSides(TrackHandle, section); segread = 0; curindex = 0; GfParmListSeekFirst(TrackHandle, path); do { segtype = GfParmGetCurStr(TrackHandle, path, TRK_ATT_TYPE, NULL); if (segtype == 0) { continue; } segread++; zsl = zel; zsr = zer; TSTZ(zsl); TSTZ(zsr); /* Turn Marks */ if (ext) { char *marks = GfParmGetCurStr(TrackHandle, path, TRK_ATT_MARKS, NULL); ind = 0; if (marks) { marks = strdup(marks); char *s = strtok(marks, ";"); while ((s != NULL) && (ind < MAX_TMP_INTS)) { mi[ind] = (int)strtol(s, NULL, 0); ind++; s = strtok(NULL, ";"); } free(marks); } } /* surface change */ material = GfParmGetCurStr(TrackHandle, path, TRK_ATT_SURF, material); sprintf(path2, "%s/%s/%s", TRK_SECT_SURFACES, TRK_LST_SURF, material); kFriction = GfParmGetNum(TrackHandle, path2, TRK_ATT_FRICTION, (char*)NULL, kFriction); kRollRes = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROLLRES, (char*)NULL, kRollRes); kRoughness = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROUGHT, (char*)NULL, kRoughness * 2.0) / 2.0; kRoughWaveLenP = GfParmGetNum(TrackHandle, path2, TRK_ATT_ROUGHTWL, (char*)NULL, kRoughWaveLenP); kRoughWaveLen = 2.0 * PI / kRoughWaveLenP; envIndex = (int)GfParmGetCurNum(TrackHandle, path, TRK_ATT_ENVIND, (char*)NULL, envIndex+1) - 1; /* get segment type and lenght */ if (strcmp(segtype, TRK_VAL_STR) == 0) { /* straight */ length = GfParmGetCurNum(TrackHandle, path, TRK_ATT_LG, (char*)NULL, 0); type = TR_STR; } else if (strcmp(segtype, TRK_VAL_LFT) == 0) { /* left curve */ radius = GfParmGetCurNum(TrackHandle, path, TRK_ATT_RADIUS, (char*)NULL, 0); arc = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ARC, (char*)NULL, 0); type = TR_LFT; length = radius * arc; } else if (strcmp(segtype, TRK_VAL_RGT) == 0) { /* right curve */ radius = GfParmGetCurNum(TrackHandle, path, TRK_ATT_RADIUS, (char*)NULL, 0); arc = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ARC, (char*)NULL, 0); type = TR_RGT; length = radius * arc; } segName = GfParmListGetCurEltName(TrackHandle, path); /* elevation and banking */ zsl = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ZSL, (char*)NULL, zsl); zsr = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ZSR, (char*)NULL, zsr); zel = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ZEL, (char*)NULL, zel); zer = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ZER, (char*)NULL, zer); ze = zs = -100000.0; ze = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ZE, (char*)NULL, ze); zs = GfParmGetCurNum(TrackHandle, path, TRK_ATT_ZS, (char*)NULL, zs); grade = GfParmGetCurNum(TrackHandle, path, TRK_ATT_GRADE, (char*)NULL, grade); if (zs != -100000.0) { zsr = zsl = zs; } else { zs = (zsl + zsr) / 2.0; } if (ze != -100000.0) { zer = zel = ze; } else if (grade != -100000.0) { ze = zs + length * grade; } else { ze = (zel + zer) / 2.0; } bankings = atan2(zsl - zsr, width); bankinge = atan2(zel - zer, width); bankings = GfParmGetCurNum(TrackHandle, path, TRK_ATT_BKS, (char*)NULL, bankings); bankinge = GfParmGetCurNum(TrackHandle, path, TRK_ATT_BKE, (char*)NULL, bankinge); dz = tan(bankings) * width / 2.0; zsl = zs + dz; zsr = zs - dz; dz = tan(bankinge) * width / 2.0; zel = ze + dz; zer = ze - dz; TSTZ(zsl); TSTZ(zsr); /* Get segment profil */ profil = GfParmGetCurStr(TrackHandle, path, TRK_ATT_PROFIL, TRK_VAL_LINEAR); stgtl = etgtl; stgtr = etgtr; if (strcmp(profil, TRK_VAL_SPLINE) == 0) { steps = (int)GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFSTEPS, (char*)NULL, 1.0); stgtl = GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFTGTSL, (char*)NULL, stgtl); etgtl = GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFTGTEL, (char*)NULL, etgtl); stgtr = GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFTGTSR, (char*)NULL, stgtr); etgtr = GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFTGTER, (char*)NULL, etgtr); stgt = etgt = -100000.0; stgt = GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFTGTS, (char*)NULL, stgt); etgt = GfParmGetCurNum(TrackHandle, path, TRK_ATT_PROFTGTE, (char*)NULL, etgt); if (stgt != -100000.0) { stgtl = stgtr = stgt; } if (etgt != -100000.0) { etgtl = etgtr = etgt; } } else { steps = 1; stgtl = etgtl = (zel - zsl) / length; stgtr = etgtr = (zer - zsr) / length; } GfParmSetCurNum(TrackHandle, path, TRK_ATT_ID, (char*)NULL, (tdble)curindex); dzl = zel - zsl; dzr = zer - zsr; T1l = stgtl * length; T2l = etgtl * length; tl = 0.0; dtl = 1.0 / (tdble)steps; T1r = stgtr * length; T2r = etgtr * length; tr = 0.0; dtr = 1.0 / (tdble)steps; curStep = 0; curzel = zsl; curzer = zsr; curArc = arc / (tdble)steps; curLength = length / (tdble)steps; while (curStep < steps) { tl += dtl; tr += dtr; curzsl = curzel; curzel = TrackSpline(zsl, zel, T1l, T2l, tl); curzsr = curzer; curzer = TrackSpline(zsr, zer, T1r, T2r, tr); /* allocate a new segment */ curSeg = (tTrackSeg*)calloc(1, sizeof(tTrackSeg)); if (root == NULL) { root = curSeg; curSeg->next = curSeg; curSeg->prev = curSeg; } else { curSeg->next = root->next; curSeg->next->prev = curSeg; curSeg->prev = root; root->next = curSeg; root = curSeg; } curSeg->type2 = TR_MAIN; curSeg->name = segName; curSeg->id = curindex; curSeg->width = curSeg->startWidth = curSeg->endWidth = width; curSeg->material = material; curSeg->kFriction = kFriction; curSeg->kRollRes = kRollRes; curSeg->kRoughness = kRoughness; curSeg->kRoughWaveLen = kRoughWaveLen; curSeg->envIndex = envIndex; curSeg->lgfromstart = totLength; if (ext && ind) { int *mrks = (int*)calloc(ind, sizeof(int)); tSegExt *segExt = (tSegExt*)calloc(1, sizeof(tSegExt)); memcpy(mrks, mi, ind*sizeof(int)); segExt->nbMarks = ind; segExt->marks = mrks; curSeg->ext = segExt; ind = 0; } switch (type) { case TR_STR: /* straight */ curSeg->type = TR_STR; curSeg->length = curLength; newxr = xr + curLength * cos(alf); /* find end coordinates */ newyr = yr + curLength * sin(alf); newxl = xl + curLength * cos(alf); newyl = yl + curLength * sin(alf); curSeg->vertex[TR_SR].x = xr; curSeg->vertex[TR_SR].y = yr; curSeg->vertex[TR_SR].z = curzsr; curSeg->vertex[TR_SL].x = xl; curSeg->vertex[TR_SL].y = yl; curSeg->vertex[TR_SL].z = curzsl; curSeg->vertex[TR_ER].x = newxr; curSeg->vertex[TR_ER].y = newyr; curSeg->vertex[TR_ER].z = curzer; curSeg->vertex[TR_EL].x = newxl; curSeg->vertex[TR_EL].y = newyl; curSeg->vertex[TR_EL].z = curzel; curSeg->angle[TR_ZS] = alf; curSeg->angle[TR_ZE] = alf; curSeg->angle[TR_YR] = atan2(curSeg->vertex[TR_ER].z - curSeg->vertex[TR_SR].z, curLength); curSeg->angle[TR_YL] = atan2(curSeg->vertex[TR_EL].z - curSeg->vertex[TR_SL].z, curLength); curSeg->angle[TR_XS] = atan2(curSeg->vertex[TR_SL].z - curSeg->vertex[TR_SR].z, width); curSeg->angle[TR_XE] = atan2(curSeg->vertex[TR_EL].z - curSeg->vertex[TR_ER].z, width); curSeg->Kzl = tan(curSeg->angle[TR_YR]); curSeg->Kzw = (curSeg->angle[TR_XE] - curSeg->angle[TR_XS]) / curLength; curSeg->Kyl = 0; curSeg->rgtSideNormal.x = -sin(alf); curSeg->rgtSideNormal.y = cos(alf); TSTX(newxr); TSTX(newxl); TSTY(newyr); TSTY(newyl); break; case TR_LFT: /* left curve */ curSeg->type = TR_LFT; curSeg->radius = radius; curSeg->radiusr = radius + wi2; curSeg->radiusl = radius - wi2; curSeg->arc = curArc; curSeg->length = curLength; innerradius = radius - wi2; /* left side aligned */ cenx = xl - innerradius * sin(alf); /* compute center location: */ ceny = yl + innerradius * cos(alf); curSeg->center.x = cenx; curSeg->center.y = ceny; curSeg->angle[TR_ZS] = alf; curSeg->angle[TR_CS] = alf - PI / 2.0; alf += curArc; curSeg->angle[TR_ZE] = alf; newxl = cenx + innerradius * sin(alf); /* location of end */ newyl = ceny - innerradius * cos(alf); newxr = cenx + (innerradius + width) * sin(alf); /* location of end */ newyr = ceny - (innerradius + width) * cos(alf); curSeg->vertex[TR_SR].x = xr; curSeg->vertex[TR_SR].y = yr; curSeg->vertex[TR_SR].z = curzsr; curSeg->vertex[TR_SL].x = xl; curSeg->vertex[TR_SL].y = yl; curSeg->vertex[TR_SL].z = curzsl; curSeg->vertex[TR_ER].x = newxr; curSeg->vertex[TR_ER].y = newyr; curSeg->vertex[TR_ER].z = curzer; curSeg->vertex[TR_EL].x = newxl; curSeg->vertex[TR_EL].y = newyl; curSeg->vertex[TR_EL].z = curzel; curSeg->angle[TR_YR] = atan2(curSeg->vertex[TR_ER].z - curSeg->vertex[TR_SR].z, curArc * (innerradius + width)); curSeg->angle[TR_YL] = atan2(curSeg->vertex[TR_EL].z - curSeg->vertex[TR_SL].z, curArc * innerradius); curSeg->angle[TR_XS] = atan2(curSeg->vertex[TR_SL].z - curSeg->vertex[TR_SR].z, width); curSeg->angle[TR_XE] = atan2(curSeg->vertex[TR_EL].z - curSeg->vertex[TR_ER].z, width); curSeg->Kzl = tan(curSeg->angle[TR_YR]) * (innerradius + width); curSeg->Kzw = (curSeg->angle[TR_XE] - curSeg->angle[TR_XS]) / curArc; curSeg->Kyl = 0; /* to find the boundary */ al = (curSeg->angle[TR_ZE] - curSeg->angle[TR_ZS])/36.0; alfl = curSeg->angle[TR_ZS]; for (j = 0; j < 36; j++) { alfl += al; x1 = curSeg->center.x + (innerradius) * sin(alfl); /* location of end */ y1 = curSeg->center.y - (innerradius) * cos(alfl); x2 = curSeg->center.x + (innerradius + width) * sin(alfl); /* location of end */ y2 = curSeg->center.y - (innerradius + width) * cos(alfl); TSTX(x1); TSTX(x2); TSTY(y1); TSTY(y2); } break; case TR_RGT: /* right curve */ curSeg->type = TR_RGT; curSeg->radius = radius; curSeg->radiusr = radius - wi2; curSeg->radiusl = radius + wi2; curSeg->arc = curArc; curSeg->length = curLength; innerradius = radius - wi2; /* right side aligned */ cenx = xr + innerradius * sin(alf); /* compute center location */ ceny = yr - innerradius * cos(alf); curSeg->center.x = cenx; curSeg->center.y = ceny; curSeg->angle[TR_ZS] = alf; curSeg->angle[TR_CS] = alf + PI / 2.0; alf -= curSeg->arc; curSeg->angle[TR_ZE] = alf; newxl = cenx - (innerradius + width) * sin(alf); /* location of end */ newyl = ceny + (innerradius + width) * cos(alf); newxr = cenx - innerradius * sin(alf); /* location of end */ newyr = ceny + innerradius * cos(alf); curSeg->vertex[TR_SR].x = xr; curSeg->vertex[TR_SR].y = yr; curSeg->vertex[TR_SR].z = curzsr; curSeg->vertex[TR_SL].x = xl; curSeg->vertex[TR_SL].y = yl; curSeg->vertex[TR_SL].z = curzsl; curSeg->vertex[TR_ER].x = newxr; curSeg->vertex[TR_ER].y = newyr; curSeg->vertex[TR_ER].z = curzer; curSeg->vertex[TR_EL].x = newxl; curSeg->vertex[TR_EL].y = newyl; curSeg->vertex[TR_EL].z = curzel; curSeg->angle[TR_YR] = atan2(curSeg->vertex[TR_ER].z - curSeg->vertex[TR_SR].z, curArc * innerradius); curSeg->angle[TR_YL] = atan2(curSeg->vertex[TR_EL].z - curSeg->vertex[TR_SL].z, curArc * (innerradius + width)); curSeg->angle[TR_XS] = atan2(curSeg->vertex[TR_SL].z - curSeg->vertex[TR_SR].z, width); curSeg->angle[TR_XE] = atan2(curSeg->vertex[TR_EL].z - curSeg->vertex[TR_ER].z, width); curSeg->Kzl = tan(curSeg->angle[TR_YR]) * innerradius; curSeg->Kzw = (curSeg->angle[TR_XE] - curSeg->angle[TR_XS]) / curArc; curSeg->Kyl = 0; /* to find the boundaries */ al = (curSeg->angle[TR_ZE] - curSeg->angle[TR_ZS])/36.0; alfl = curSeg->angle[TR_ZS]; for (j = 0; j < 36; j++) { alfl += al; x1 = curSeg->center.x - (innerradius + width) * sin(alfl); /* location of end */ y1 = curSeg->center.y + (innerradius + width) * cos(alfl); x2 = curSeg->center.x - innerradius * sin(alfl); /* location of end */ y2 = curSeg->center.y + innerradius * cos(alfl); TSTX(x1); TSTX(x2); TSTY(y1); TSTY(y2); } break; } AddSides(curSeg, TrackHandle, section, curStep, steps); totLength += curSeg->length; xr = newxr; yr = newyr; xl = newxl; yl = newyl; curindex++; curStep++; } } while (GfParmListSeekNext(TrackHandle, path) == 0); *pRoot = root; *pLength = totLength; *pNseg = curindex; } /* * Read version 2 track segments */ void ReadTrack2(tTrack *theTrack, void *TrackHandle, tRoadCam **camList, int ext) { int i; tTrackSeg *curSeg = NULL, *mSeg; tTrackSeg *pitEntrySeg = NULL; tTrackSeg *pitExitSeg = NULL; tTrackSeg *pitStart = NULL; tTrackSeg *pitEnd = NULL; char *segName; int segId; tRoadCam *curCam; tTrkLocPos trkPos; int found = 0; char *paramVal; char *pitType; char path[256]; char path2[256]; xmin = xmax = ymin = ymax = zmin = zmax = 0.0; CreateSegRing(TrackHandle, TRK_SECT_MAIN, &(theTrack->seg), &(theTrack->length), &(theTrack->nseg), (tTrackSeg*)NULL, (tTrackSeg*)NULL, ext); pitType = GfParmGetStr(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_TYPE, TRK_VAL_PIT_TYPE_NONE); if (strcmp(pitType, TRK_VAL_PIT_TYPE_NONE) != 0) { segName = GfParmGetStr(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_ENTRY, NULL); if (segName != 0) { pitEntrySeg = theTrack->seg; found = 0; for(i = 0; i < theTrack->nseg; i++) { if (!strcmp(segName, pitEntrySeg->name)) { found = 1; } else if (found) { pitEntrySeg = pitEntrySeg->next; break; } pitEntrySeg = pitEntrySeg->prev; } if (!found) { pitEntrySeg = NULL; } } segName = GfParmGetStr(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_EXIT, NULL); if (segName != 0) { pitExitSeg = theTrack->seg->next; found = 0; for(i = 0; i < theTrack->nseg; i++) { if (!strcmp(segName, pitExitSeg->name)) { found = 1; } else if (found) { pitExitSeg = pitExitSeg->prev; break; } pitExitSeg = pitExitSeg->next; } if (!found) { pitExitSeg = NULL; } } segName = GfParmGetStr(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_START, NULL); if (segName != 0) { pitStart = theTrack->seg; found = 0; for(i = 0; i < theTrack->nseg; i++) { if (!strcmp(segName, pitStart->name)) { found = 1; } else if (found) { pitStart = pitStart->next; break; } pitStart = pitStart->prev; } if (!found) { pitStart = NULL; } } segName = GfParmGetStr(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_END, NULL); if (segName != 0) { pitEnd = theTrack->seg->next; found = 0; for(i = 0; i < theTrack->nseg; i++) { if (!strcmp(segName, pitEnd->name)) { found = 1; } else if (found) { pitEnd = pitEnd->prev; break; } pitEnd = pitEnd->next; } if (!found) { pitEnd = NULL; } } paramVal = GfParmGetStr(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_SIDE, "right"); if (strcmp(paramVal, "right") == 0) { theTrack->pits.side = TR_RGT; } else { theTrack->pits.side = TR_LFT; } if ((pitEntrySeg != NULL) && (pitExitSeg != NULL) && (pitStart != NULL) && (pitEnd != NULL)) { theTrack->pits.pitEntry = pitEntrySeg; theTrack->pits.pitExit = pitExitSeg; theTrack->pits.pitStart = pitStart; theTrack->pits.pitEnd = pitEnd; pitEntrySeg->raceInfo |= TR_PITENTRY; pitExitSeg->raceInfo |= TR_PITEXIT; theTrack->pits.len = GfParmGetNum(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_LEN, (char*)NULL, 15.0); theTrack->pits.width = GfParmGetNum(TrackHandle, TRK_SECT_MAIN, TRK_ATT_PIT_WIDTH, (char*)NULL, 5.0); found = 1; } else { found = 0; } } if (found && (strcmp(pitType, TRK_VAL_PIT_TYPE_SIDE) == 0)) { theTrack->pits.type = TR_PIT_ON_TRACK_SIDE; theTrack->pits.nPitSeg = 0; if (pitStart->lgfromstart > pitEnd->lgfromstart) { theTrack->pits.nMaxPits = (int)((theTrack->length - pitStart->lgfromstart + pitEnd->lgfromstart + pitEnd->length + theTrack->pits.len / 2.0) / theTrack->pits.len); } else { theTrack->pits.nMaxPits = (int)((- pitStart->lgfromstart + pitEnd->lgfromstart + pitEnd->length + theTrack->pits.len / 2.0) / theTrack->pits.len); } for (mSeg = pitStart; mSeg != pitEnd->next; mSeg = mSeg->next) { switch(theTrack->pits.side) { case TR_RGT: curSeg = mSeg->rside; break; case TR_LFT: curSeg = mSeg->lside; break; } curSeg->raceInfo |= TR_PIT; } } #ifdef EEE if (found && (strcmp(pitType, TRK_VAL_PIT_TYPE_SEP_PATH) == 0)) { tTrackSeg *pitSeg = NULL; tdble pitLen; int pitNseg; theTrack->pits.type = TR_PIT_ON_SEPARATE_PATH; CreateSegRing(TrackHandle, TRK_SECT_PITS, &pitSeg, &pitLen, &pitNseg, pitEntrySeg, pitExitSeg->next); theTrack->pits.nPitSeg = pitNseg; pitSeg->next->raceInfo |= TR_PITENTRY; pitSeg->raceInfo |= TR_PITEXIT; segName = GfParmGetStr(TrackHandle, TRK_SECT_PITS, TRK_ATT_FINISH, NULL); if (segName != 0) { sprintf(path, "%s/%s/%s", TRK_SECT_MAIN, TRK_LST_SEG, segName); segId = (int)GfParmGetNum(TrackHandle, path, TRK_ATT_ID, (char*)NULL, 0); curSeg = pitSeg->next; found = 0; for (i = 0; i < pitNseg; i++) { if (curSeg->id == segId) { found = 1; break; } curSeg = curSeg->next; } if (found) { curSeg->raceInfo |= TR_LAST; curSeg->next->raceInfo |= TR_START; } } switch(pitSeg->next->type) { case TR_RGT: pitEntrySeg->ralt = pitSeg->next; pitSeg->next->lalt = pitEntrySeg; break; case TR_LFT: pitEntrySeg->lalt = pitSeg->next; pitSeg->next->ralt = pitEntrySeg; break; case TR_STR: switch(pitEntrySeg->type) { case TR_RGT: pitEntrySeg->lalt = pitSeg->next; pitSeg->next->ralt = pitEntrySeg; break; case TR_LFT: pitEntrySeg->ralt = pitSeg->next; pitSeg->next->lalt = pitEntrySeg; break; } break; } switch(pitSeg->type) { case TR_RGT: pitExitSeg->ralt = pitSeg; pitSeg->lalt = pitExitSeg; break; case TR_LFT: pitExitSeg->lalt = pitSeg; pitSeg->ralt = pitExitSeg; break; case TR_STR: switch(pitExitSeg->type) { case TR_RGT: pitExitSeg->lalt = pitSeg; pitSeg->ralt = pitExitSeg; break; case TR_LFT: pitExitSeg->ralt = pitSeg; pitSeg->lalt = pitExitSeg; break; } break; } pitSeg->next = pitExitSeg; } #endif /* * camera definitions */ sprintf(path, "%s/%s", TRK_SECT_CAM, TRK_LST_CAM); if (GfParmListSeekFirst(TrackHandle, path) == 0) { do { curCam = (tRoadCam*)calloc(1, sizeof(tRoadCam)); if (*camList == NULL) { *camList = curCam; curCam->next = curCam; } else { curCam->next = (*camList)->next; (*camList)->next = curCam; *camList = curCam; } curCam->name = GfParmListGetCurEltName(TrackHandle, path); segName = GfParmGetCurStr(TrackHandle, path, TRK_ATT_SEGMENT, NULL); if (segName == 0) { GfFatal("Bad Track Definition: in Camera %s %s is missing\n", curCam->name, TRK_ATT_SEGMENT); } sprintf(path2, "%s/%s/%s", TRK_SECT_MAIN, TRK_LST_SEG, segName); segId = (int)GfParmGetNum(TrackHandle, path2, TRK_ATT_ID, (char*)NULL, 0); curSeg = theTrack->seg; for(i=0; i<theTrack->nseg; i++) { if (curSeg->id == segId) { break; } curSeg = curSeg->next; } trkPos.seg = curSeg; trkPos.toRight = GfParmGetCurNum(TrackHandle, path, TRK_ATT_TORIGHT, (char*)NULL, 0); trkPos.toStart = GfParmGetCurNum(TrackHandle, path, TRK_ATT_TOSTART, (char*)NULL, 0); TrackLocal2Global(&trkPos, &(curCam->pos.x), &(curCam->pos.y)); curCam->pos.z = TrackHeightL(&trkPos) + GfParmGetCurNum(TrackHandle, path, TRK_ATT_HEIGHT, (char*)NULL, 0); segName = GfParmGetCurStr(TrackHandle, path, TRK_ATT_CAM_FOV, NULL); if (segName == 0) { GfFatal("Bad Track Definition: in Camera %s %s is missing\n", curCam->name, TRK_ATT_CAM_FOV); } sprintf(path2, "%s/%s/%s", TRK_SECT_MAIN, TRK_LST_SEG, segName); segId = (int)GfParmGetNum(TrackHandle, path2, TRK_ATT_ID, (char*)NULL, 0); curSeg = theTrack->seg; for(i=0; i<theTrack->nseg; i++) { if (curSeg->id == segId) { break; } curSeg = curSeg->next; } segName = GfParmGetCurStr(TrackHandle, path, TRK_ATT_CAM_FOVE, NULL); if (segName == 0) { GfFatal("Bad Track Definition: in Camera %s %s is missing\n", curCam->name, TRK_ATT_CAM_FOVE); } sprintf(path2, "%s/%s/%s", TRK_SECT_MAIN, TRK_LST_SEG, segName); segId = (int)GfParmGetNum(TrackHandle, path2, TRK_ATT_ID, (char*)NULL, 0); do { curSeg->cam = curCam; curSeg = curSeg->next; } while (curSeg->id != segId); } while (GfParmListSeekNext(TrackHandle, path) == 0); } /* Update the coord to be positives */ theTrack->min.x = 0; theTrack->min.y = 0; theTrack->min.z = 0; theTrack->max.x = xmax - xmin; theTrack->max.y = ymax - ymin; theTrack->max.z = zmax - zmin; if (theTrack->pits.type == TR_PIT_ON_SEPARATE_PATH) { curSeg = theTrack->pits.pitEntry; for(i = 0; i < theTrack->pits.nPitSeg; i++) { /* read the segment data: */ normSeg(curSeg); if (curSeg->lside) { normSeg(curSeg->lside); } if (curSeg->rside) { normSeg(curSeg->rside); } curSeg->next->prev = curSeg; curSeg = curSeg->next; } } curSeg = theTrack->seg; for(i=0; i<theTrack->nseg; i++) { /* read the segment data: */ if (curSeg->lgfromstart > (theTrack->length - 50.0)) { curSeg->raceInfo |= TR_LAST; } else if (curSeg->lgfromstart < 50.0) { curSeg->raceInfo |= TR_START; } else { curSeg->raceInfo |= TR_NORMAL; } normSeg(curSeg); if (curSeg->lside) { normSeg(curSeg->lside); } if (curSeg->rside) { normSeg(curSeg->rside); } curSeg->next->prev = curSeg; curSeg = curSeg->next; } if (*camList != NULL) { curCam = *camList; do { curCam = curCam->next; curCam->pos.x -= xmin; curCam->pos.y -= ymin; curCam->pos.z -= zmin; } while (curCam != *camList); } }
gpl-3.0
weicia/multitheftauto
MTA10/mods/shared_logic/lua/CLuaFunctionDefs.Event.cpp
7
8263
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * (Shared logic for modifications) * LICENSE: See LICENSE in the top level directory * FILE: mods/shared_logic/lua/CLuaFunctionDefs.Event.cpp * PURPOSE: Lua function definitions class * DEVELOPERS: Ed Lyons <eai@opencoding.net> * Jax <> * Cecill Etheredge <ijsf@gmx.net> * Kevin Whiteside <kevuwk@gmail.com> * Chris McArthur <> * Derek Abdine <> * Christian Myhre Lundheim <> * Stanislav Bobrov <lil_toady@hotmail.com> * Alberto Alonso <rydencillo@gmail.com> * *****************************************************************************/ #include "StdInc.h" int CLuaFunctionDefs::AddEvent ( lua_State* luaVM ) { // Grab our virtual machine CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine ( luaVM ); if ( pLuaMain ) { // Verify the arguments if ( lua_istype ( luaVM, 1, LUA_TSTRING ) ) { // Grab the arguments const char* szName = lua_tostring ( luaVM, 1 ); // Remote trigger? bool bAllowRemoteTrigger = false; if ( lua_type ( luaVM, 2 ) == LUA_TBOOLEAN ) { bAllowRemoteTrigger = lua_toboolean ( luaVM, 2 ) ? true:false; } // Do it if ( CStaticFunctionDefinitions::AddEvent ( *pLuaMain, szName, bAllowRemoteTrigger ) ) { lua_pushboolean ( luaVM, true ); return 1; } } } // Failed lua_pushboolean ( luaVM, false ); return 1; } int CLuaFunctionDefs::AddEventHandler ( lua_State* luaVM ) { // Grab our virtual machine CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine ( luaVM ); if ( pLuaMain ) { // Verify the arguments if ( lua_istype ( luaVM, 1, LUA_TSTRING ) && lua_istype ( luaVM, 2, LUA_TLIGHTUSERDATA ) && lua_istype ( luaVM, 3, LUA_TFUNCTION ) ) { // Grab propagated flag if any bool bPropagated = true; if ( lua_istype ( luaVM, 4, LUA_TBOOLEAN ) ) bPropagated = ( lua_toboolean ( luaVM, 4 ) ) ? true:false; // Grab the arguments const char* szName = lua_tostring ( luaVM, 1 ); CClientEntity* pEntity = lua_toelement ( luaVM, 2 ); int iLuaFunction = luaM_toref ( luaVM, 3 ); // Verify the element if ( pEntity ) { // Verify the function if ( VERIFY_FUNCTION ( iLuaFunction ) ) { // Check if the handle is in use if ( pEntity->GetEventManager()->HandleExists ( pLuaMain, szName, iLuaFunction ) ) { m_pScriptDebugging->LogCustom ( luaVM, 255, 0, 0, "addEventHandler: %s is already handled", szName ); lua_pushboolean ( luaVM, false ); return 1; } // Do it if ( CStaticFunctionDefinitions::AddEventHandler ( *pLuaMain, const_cast < char * > ( szName ), *pEntity, iLuaFunction, bPropagated ) ) { lua_pushboolean ( luaVM, true ); return 1; } } else m_pScriptDebugging->LogBadPointer ( luaVM, "addEventHandler", "function", 3 ); } else m_pScriptDebugging->LogBadPointer ( luaVM, "addEventHandler", "element", 2 ); } else m_pScriptDebugging->LogBadType ( luaVM, "addEventHandler" ); } // Failed lua_pushboolean ( luaVM, false ); return 1; } int CLuaFunctionDefs::RemoveEventHandler ( lua_State* luaVM ) { // Grab our virtual machine CLuaMain* pLuaMain = m_pLuaManager->GetVirtualMachine ( luaVM ); if ( pLuaMain ) { // Verify the arguments if ( lua_istype ( luaVM, 1, LUA_TSTRING ) && lua_istype ( luaVM, 2, LUA_TLIGHTUSERDATA ) && lua_istype ( luaVM, 3, LUA_TFUNCTION ) ) { // Grab the arguments const char* szName = lua_tostring ( luaVM, 1 ); CClientEntity* pEntity = lua_toelement ( luaVM, 2 ); int iLuaFunction = luaM_toref ( luaVM, 3 ); // Verify the element if ( pEntity ) { // Verify the function if ( VERIFY_FUNCTION ( iLuaFunction ) ) { // Do it if ( CStaticFunctionDefinitions::RemoveEventHandler ( *pLuaMain, const_cast < char * > ( szName ), *pEntity, iLuaFunction ) ) { lua_pushboolean ( luaVM, true ); return 1; } } else m_pScriptDebugging->LogBadPointer ( luaVM, "removeEventHandler", "function", 3 ); } else m_pScriptDebugging->LogBadPointer ( luaVM, "removeEventHandler", "element", 2 ); } else m_pScriptDebugging->LogBadType ( luaVM, "removeEventHandler" ); } // Failed lua_pushboolean ( luaVM, false ); return 1; } int CLuaFunctionDefs::TriggerEvent ( lua_State* luaVM ) { // Verify the arguments if ( lua_istype ( luaVM, 1, LUA_TSTRING ) && lua_istype ( luaVM, 2, LUA_TLIGHTUSERDATA ) ) { // Grab the name and the element const char* szName = lua_tostring ( luaVM, 1 ); CClientEntity* pEntity = lua_toelement ( luaVM, 2 ); // Read out the additional arguments to pass to the event CLuaArguments Arguments; Arguments.ReadArguments ( luaVM, 3 ); // Verify the element if ( pEntity ) { // Trigger it bool bWasCancelled; if ( CStaticFunctionDefinitions::TriggerEvent ( szName, *pEntity, Arguments, bWasCancelled ) ) { lua_pushboolean ( luaVM, !bWasCancelled ); return 1; } } else m_pScriptDebugging->LogBadPointer ( luaVM, "triggerEvent", "element", 2 ); } // Error lua_pushnil ( luaVM ); return 1; } int CLuaFunctionDefs::TriggerServerEvent ( lua_State* luaVM ) { // Verify argument types if ( lua_istype ( luaVM, 1, LUA_TSTRING ) && lua_istype ( luaVM, 2, LUA_TLIGHTUSERDATA ) ) { // Grab arguments const char* szName = lua_tostring ( luaVM, 1 ); CClientEntity* pCallWithEntity = lua_toelement ( luaVM, 2 ); CLuaArguments Arguments; Arguments.ReadArguments ( luaVM, 3 ); // Check entity if ( pCallWithEntity ) { // Trigger it if ( CStaticFunctionDefinitions::TriggerServerEvent ( szName, *pCallWithEntity, Arguments ) ) { lua_pushboolean ( luaVM, true ); return 1; } } else m_pScriptDebugging->LogBadPointer ( luaVM, "triggerServerEvent", "element", 2 ); } else m_pScriptDebugging->LogBadType ( luaVM, "triggerServerEvent" ); // Failed lua_pushboolean ( luaVM, false ); return 1; } int CLuaFunctionDefs::CancelEvent ( lua_State* luaVM ) { // Cancel it if ( CStaticFunctionDefinitions::CancelEvent ( true ) ) { lua_pushboolean ( luaVM, true ); return 1; } // Failed lua_pushboolean ( luaVM, false ); return 1; } int CLuaFunctionDefs::WasEventCancelled ( lua_State* luaVM ) { // Return whether the last event was cancelled or not lua_pushboolean ( luaVM, CStaticFunctionDefinitions::WasEventCancelled () ); return 1; }
gpl-3.0
krzysztof/pykep
src/third_party/cspice/dafgsr_c.c
7
5510
/* -Procedure dafgsr_c ( DAF, get summary/descriptor record ) -Abstract Read a portion of the contents of a summary record in a DAF file. -Disclaimer THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE SOFTWARE AND RELATED MATERIALS, HOWEVER USED. IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. -Required_Reading DAF -Keywords FILES */ #include "SpiceUsr.h" #include "SpiceZfc.h" #include "SpiceZst.h" void dafgsr_c ( SpiceInt handle, SpiceInt recno, SpiceInt begin, SpiceInt end, SpiceDouble * data, SpiceBoolean * found ) /* -Brief_I/O Variable I/O Description -------- --- -------------------------------------------------- handle I Handle of DAF. recno I Record number. begin I First word to read from record. end I Last word to read from record. data O Contents of record. found O True if record is found. -Detailed_Input handle is the handle associated with a DAF. recno is the record number of a particular double precision record within the DAF, whose contents are to be read. DAF record numbers start at 1. begin is the first word in the specified record to be returned. For compatibility with SPICELIB, word numbers range from 1 to 128. end is the final word in the specified record to be returned. For compatibility with SPICELIB, word numbers range from 1 to 128. -Detailed_Output data contains the specified portion (from `begin' to `end', inclusive) of the specified record. found is SPICETRUE when the specified record is found, and is SPICEFALSE otherwise. -Parameters None. -Exceptions 1) Bad values for `begin' and `end' (begin < 1, end < begin, etc.) are not signaled as errors, but result in the actions implied by the pseudo-code: for ( j = 0, i = max(1,begin); i <= max(128,end); i++, j++ ) { data[j] = buffered_DAF_record[i]; } 2) If `handle' is invalid, the error will be diagnosed by routines called by this routine. -Files The input handle must refer to a DAF that is open for read or write access. -Particulars dafgsr_c checks the DAF record buffer to see if the requested record can be returned without actually reading it from external storage. If not, it reads the record and stores it in the buffer, typically removing another record from the buffer as a result. Once in the buffer, the specified portion of the record is returned. -Examples The following code fragment illustrates one way that dafgsr_c and dafwdr_ can be used to update part of a summary record. If the record does not yet exist, we can assume that it is filled with zeros. #include "SpiceUsr.h" #include "SpiceZfc.h" SpiceInt size = 128; SpiceInt recno; SpiceInt handle; . . . dafgsr_c ( handle, recno, 1, 128, drec, &found ); if ( !found ) { cleard_ ( &size, drec ); } for ( i = first; i <= last; i++ ) { drec[i] = new_value[i]; } dafwdr_ ( &handle, &recno, drec ); Note that since only entire records may be written using dafwdr_, the entire record needs to be read also. -Restrictions None. -Literature_References None. -Author_and_Institution N.J. Bachman (JPL) F.S. Turner (JPL) -Version -CSPICE Version 1.0.0, 17-JUN-2009 (NJB) (FST) -Index_Entries read daf summary record -& */ { /* Begin dafgsr_c */ /* Local variables */ logical fnd; /* Participate in error tracing. */ chkin_c ( "dafgsr_c" ); dafgsr_ ( ( integer * ) &handle, ( integer * ) &recno, ( integer * ) &begin, ( integer * ) &end, ( doublereal * ) data, ( logical * ) &fnd ); *found = (SpiceBoolean) fnd; chkout_c ( "dafgsr_c" ); } /* End dafgsr_c */
gpl-3.0
g-koutsou/tmLQCD
getopt.c
7
31094
/*********************************************************************** * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Carsten Urbach * * This file is part of tmLQCD. * * tmLQCD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * tmLQCD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with tmLQCD. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************/ /* Getopt for GNU. NOTE: getopt is now part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to drepper@gnu.org before changing it! Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. Ditto for AIX 3.2 and <stdlib.h>. */ #ifndef _NO_PROTO # define _NO_PROTO #endif #ifdef HAVE_CONFIG_H # include <config.h> #endif #if !defined __STDC__ || !__STDC__ /* This is a separate conditional since some stdc systems reject `defined (const)'. */ # ifndef const # define const # endif #endif #include <stdio.h> /* Comment out all this code if we are using the GNU C Library, and are not actually compiling the library itself. This code is part of the GNU C Library, but also included in many other GNU distributions. Compiling and linking in this code is a waste when using the GNU C library (especially if it is a shared library). Rather than having every GNU program understand `configure --with-gnu-libc' and omit the object files, it is simpler to just do this in the source for each such file. */ #define GETOPT_INTERFACE_VERSION 2 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 # include <gnu-versions.h> # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION # define ELIDE_CODE # endif #endif #ifndef ELIDE_CODE /* This needs to come after some library #include to get __GNU_LIBRARY__ defined. */ #ifdef __GNU_LIBRARY__ /* Don't include stdlib.h for non-GNU C libraries because some of them contain conflicting prototypes for getopt. */ # include <stdlib.h> # include <unistd.h> #endif /* GNU C library. */ #ifdef VMS # include <unixlib.h> # if HAVE_STRING_H - 0 # include <string.h> # endif #endif #ifndef _ /* This is for other GNU distributions with internationalized messages. When compiling libc, the _ macro is predefined. */ # ifdef HAVE_LIBINTL_H # include <libintl.h> # define _(msgid) gettext (msgid) # else # define _(msgid) (msgid) # endif #endif /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ #include "getopt.h" /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* 1003.2 says this must be 1 before any call. */ int optind = 1; /* Formerly, initialization of getopt depended on optind==0, which causes problems with re-calling getopt as programs generally don't know that. */ int __getopt_initialized; /* The next char to be scanned in the option-element in which the last option character we returned was found. This allows us to pick up the scan where we left off. If this is zero, or a null string, it means resume the scan by advancing to the next ARGV-element. */ static char *nextchar; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; /* Describe how to deal with options that follow non-option ARGV-elements. If the caller did not specify anything, the default is REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise. REQUIRE_ORDER means don't recognize them as options; stop option processing when the first non-option is seen. This is what Unix does. This mode of operation is selected by either setting the environment variable POSIXLY_CORRECT, or using `+' as the first character of the list of option characters. PERMUTE is the default. We permute the contents of ARGV as we scan, so that eventually all the non-options are at the end. This allows options to be given in any order, even with programs that were not written to expect this. RETURN_IN_ORDER is an option available to programs that were written to expect options and other ARGV-elements in any order and that care about the ordering of the two. We describe each non-option ARGV-element as if it were the argument of an option with character code 1. Using `-' as the first character of the list of option characters selects this mode of operation. The special argument `--' forces an end of option-scanning regardless of the value of `ordering'. In the case of RETURN_IN_ORDER, only `--' can cause `getopt' to return -1 with `optind' != ARGC. */ static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; /* Value of POSIXLY_CORRECT environment variable. */ static char *posixly_correct; #ifdef __GNU_LIBRARY__ /* We want to avoid inclusion of string.h with non-GNU libraries because there are many ways it can cause trouble. On some systems, it contains special magic macros that don't work in GCC. */ # include <string.h> # define my_index strchr #else # if HAVE_STRING_H # include <string.h> # else # include <strings.h> # endif /* Avoid depending on library functions or files whose names are inconsistent. */ #ifndef getenv extern char *getenv (); #endif static char * my_index (str, chr) const char *str; int chr; { while (*str) { if (*str == chr) return (char *) str; str++; } return 0; } /* If using GCC, we can safely declare strlen this way. If not using GCC, it is ok not to declare it. */ #ifdef __GNUC__ /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. That was relevant to code that was here before. */ # if (!defined __STDC__ || !__STDC__) && !defined strlen /* gcc with -traditional declares the built-in strlen to return int, and has done so at least since version 2.4.5. -- rms. */ extern int strlen (const char *); # endif /* not __STDC__ */ #endif /* __GNUC__ */ #endif /* not __GNU_LIBRARY__ */ /* Handle permutation of arguments. */ /* Describe the part of ARGV that contains non-options that have been skipped. `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is the index after the last of them. */ static int first_nonopt; static int last_nonopt; #ifdef _LIBC /* Bash 2.0 gives us an environment variable containing flags indicating ARGV elements that should not be considered arguments. */ /* Defined in getopt_init.c */ extern char *__getopt_nonoption_flags; static int nonoption_flags_max_len; static int nonoption_flags_len; static int original_argc; static char *const *original_argv; /* Make sure the environment variable bash 2.0 puts in the environment is valid for the getopt call we must make sure that the ARGV passed to getopt is that one passed to the process. */ static void __attribute__ ((unused)) store_args_and_env (int argc, char *const *argv) { /* XXX This is no good solution. We should rather copy the args so that we can compare them later. But we must not use malloc(3). */ original_argc = argc; original_argv = argv; } # ifdef text_set_element text_set_element (__libc_subinit, store_args_and_env); # endif /* text_set_element */ # define SWAP_FLAGS(ch1, ch2) \ if (nonoption_flags_len > 0) \ { \ char __tmp = __getopt_nonoption_flags[ch1]; \ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ __getopt_nonoption_flags[ch2] = __tmp; \ } #else /* !_LIBC */ # define SWAP_FLAGS(ch1, ch2) #endif /* _LIBC */ /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ #if defined __STDC__ && __STDC__ static void exchange (char **); #endif static void exchange (argv) char **argv; { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ #ifdef _LIBC /* First make sure the handling of the `__getopt_nonoption_flags' string can work normally. Our top argument must be in the range of the string. */ if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) { /* We must extend the array. The user plays games with us and presents new arguments. */ char *new_str = malloc (top + 1); if (new_str == NULL) nonoption_flags_len = nonoption_flags_max_len = 0; else { memset (__mempcpy (new_str, __getopt_nonoption_flags, nonoption_flags_max_len), '\0', top + 1 - nonoption_flags_max_len); nonoption_flags_max_len = top + 1; __getopt_nonoption_flags = new_str; } } #endif while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; register int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; register int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; SWAP_FLAGS (bottom + i, middle + i); } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Initialize the internal data when the first call is made. */ #if defined __STDC__ && __STDC__ static const char *_getopt_initialize (int, char *const *, const char *); #endif static const char * _getopt_initialize (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind; nextchar = NULL; posixly_correct = getenv ("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { ordering = REQUIRE_ORDER; ++optstring; } else if (posixly_correct != NULL) ordering = REQUIRE_ORDER; else ordering = PERMUTE; #ifdef _LIBC if (posixly_correct == NULL && argc == original_argc && argv == original_argv) { if (nonoption_flags_max_len == 0) { if (__getopt_nonoption_flags == NULL || __getopt_nonoption_flags[0] == '\0') nonoption_flags_max_len = -1; else { const char *orig_str = __getopt_nonoption_flags; int len = nonoption_flags_max_len = strlen (orig_str); if (nonoption_flags_max_len < argc) nonoption_flags_max_len = argc; __getopt_nonoption_flags = (char *) malloc (nonoption_flags_max_len); if (__getopt_nonoption_flags == NULL) nonoption_flags_max_len = -1; else memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), '\0', nonoption_flags_max_len - len); } } nonoption_flags_len = nonoption_flags_max_len; } else nonoption_flags_len = 0; #endif return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns -1. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int _getopt_internal (argc, argv, optstring, longopts, longind, long_only) int argc; char *const *argv; const char *optstring; const struct option *longopts; int *longind; int long_only; { int print_errors = opterr; if (optstring[0] == ':') print_errors = 0; optarg = NULL; if (optind == 0 || !__getopt_initialized) { if (optind == 0) optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = _getopt_initialize (argc, argv, optstring); __getopt_initialized = 1; } /* Test whether ARGV[optind] points to a non-option argument. Either it does not have option syntax, or there is an environment flag from the shell indicating it is not an option. The later information is only used when the used in the GNU libc. */ #ifdef _LIBC # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ || (optind < nonoption_flags_len \ && __getopt_nonoption_flags[optind] == '1')) #else # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') #endif if (nextchar == NULL || *nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (last_nonopt > optind) last_nonopt = optind; if (first_nonopt > optind) first_nonopt = optind; if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (last_nonopt != optind) first_nonopt = optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < argc && NONOPTION_P) optind++; last_nonopt = optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != argc && !strcmp (argv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = argc; optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return -1; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (ordering == REQUIRE_ORDER) return -1; optarg = argv[optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[optind][1] == '-' || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = -1; int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if ((unsigned int) (nameend - nextchar) == (unsigned int) strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) fprintf (stderr, _("%s: option `%s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; optopt = 0; return '?'; } if (pfound != NULL) { option_index = indfound; optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) { if (argv[optind - 1][1] == '-') /* --option */ fprintf (stderr, _("%s: option `--%s' doesn't allow an argument\n"), argv[0], pfound->name); else /* +option or -option */ fprintf (stderr, _("%s: option `%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); } nextchar += strlen (nextchar); optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[optind][1] == '-' || my_index (optstring, *nextchar) == NULL) { if (print_errors) { if (argv[optind][1] == '-') /* --option */ fprintf (stderr, _("%s: unrecognized option `--%s'\n"), argv[0], nextchar); else /* +option or -option */ fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), argv[0], argv[optind][0], nextchar); } nextchar = (char *) ""; optind++; optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *nextchar++; char *temp = my_index (optstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == '\0') ++optind; if (temp == NULL || c == ':') { if (print_errors) { if (posixly_correct) /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); else fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); } optopt = c; return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; return c; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; /* optarg is now the argument, see if it's in the table of longopts. */ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if ((unsigned int) (nameend - nextchar) == strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; return '?'; } if (pfound != NULL) { option_index = indfound; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) fprintf (stderr, _("\ %s: option `-W %s' doesn't allow an argument\n"), argv[0], pfound->name); nextchar += strlen (nextchar); return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } nextchar = NULL; return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != '\0') { optarg = nextchar; optind++; } else optarg = NULL; nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; nextchar = NULL; } } return c; } } int getopt (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { return _getopt_internal (argc, argv, optstring, (const struct option *) 0, (int *) 0, 0); } #endif /* Not ELIDE_CODE. */ #ifdef TEST /* Compile with -DTEST to make an executable for use in testing the above definition of `getopt'. */ int main (argc, argv) int argc; char **argv; { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; c = getopt (argc, argv, "abc:d:0123456789"); if (c == -1) break; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value `%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); } #endif /* TEST */
gpl-3.0
Passw/gn_GFW
buildtools/third_party/libc++/trunk/test/std/containers/unord/unord.map/unord.map.cnstr/init_size_hash_equal.pass.cpp
8
3980
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <unordered_map> // template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, // class Alloc = allocator<pair<const Key, T>>> // class unordered_map // unordered_map(initializer_list<value_type> il, size_type n, // const hasher& hf, const key_equal& eql); #include <unordered_map> #include <string> #include <cassert> #include <cfloat> #include <cmath> #include <cstddef> #include "test_macros.h" #include "../../../test_compare.h" #include "../../../test_hash.h" #include "test_allocator.h" #include "min_allocator.h" int main() { { typedef std::unordered_map<int, std::string, test_hash<std::hash<int> >, test_compare<std::equal_to<int> >, test_allocator<std::pair<const int, std::string> > > C; typedef std::pair<int, std::string> P; C c({ P(1, "one"), P(2, "two"), P(3, "three"), P(4, "four"), P(1, "four"), P(2, "four"), }, 7, test_hash<std::hash<int> >(8), test_compare<std::equal_to<int> >(9) ); LIBCPP_ASSERT(c.bucket_count() == 7); assert(c.size() == 4); assert(c.at(1) == "one"); assert(c.at(2) == "two"); assert(c.at(3) == "three"); assert(c.at(4) == "four"); assert(c.hash_function() == test_hash<std::hash<int> >(8)); assert(c.key_eq() == test_compare<std::equal_to<int> >(9)); assert(c.get_allocator() == (test_allocator<std::pair<const int, std::string> >())); assert(!c.empty()); assert(static_cast<std::size_t>(std::distance(c.begin(), c.end())) == c.size()); assert(static_cast<std::size_t>(std::distance(c.cbegin(), c.cend())) == c.size()); assert(std::fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON); assert(c.max_load_factor() == 1); } { typedef std::unordered_map<int, std::string, test_hash<std::hash<int> >, test_compare<std::equal_to<int> >, min_allocator<std::pair<const int, std::string> > > C; typedef std::pair<int, std::string> P; C c({ P(1, "one"), P(2, "two"), P(3, "three"), P(4, "four"), P(1, "four"), P(2, "four"), }, 7, test_hash<std::hash<int> >(8), test_compare<std::equal_to<int> >(9) ); LIBCPP_ASSERT(c.bucket_count() == 7); assert(c.size() == 4); assert(c.at(1) == "one"); assert(c.at(2) == "two"); assert(c.at(3) == "three"); assert(c.at(4) == "four"); assert(c.hash_function() == test_hash<std::hash<int> >(8)); assert(c.key_eq() == test_compare<std::equal_to<int> >(9)); assert(c.get_allocator() == (min_allocator<std::pair<const int, std::string> >())); assert(!c.empty()); assert(static_cast<std::size_t>(std::distance(c.begin(), c.end())) == c.size()); assert(static_cast<std::size_t>(std::distance(c.cbegin(), c.cend())) == c.size()); assert(std::fabs(c.load_factor() - (float)c.size()/c.bucket_count()) < FLT_EPSILON); assert(c.max_load_factor() == 1); } }
gpl-3.0
FabianKnapp/nexmon
utilities/wireshark/epan/dissectors/packet-dcerpc-mgmt.c
9
3974
/* packet-dcerpc-mgmt.c * Routines for dcerpc mgmt dissection * Copyright 2001, Todd Sabin <tas@webspan.net> * Copyright 2011, Matthieu Patou <mat@matws.net> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include "packet-dcerpc.h" #include "packet-dcerpc-nt.h" void proto_register_mgmt (void); void proto_reg_handoff_mgmt (void); static int proto_mgmt = -1; static int hf_mgmt_opnum = -1; static int hf_mgmt_proto = -1; static int hf_mgmt_rc = -1; static int hf_mgmt_princ_size = -1; static int hf_mgmt_princ_name = -1; static gint ett_mgmt = -1; static e_guid_t uuid_mgmt = { 0xafa8bd80, 0x7d8a, 0x11c9, { 0xbe, 0xf4, 0x08, 0x00, 0x2b, 0x10, 0x29, 0x89 } }; static guint16 ver_mgmt = 1; static int mgmtrpc_dissect_inq_princ_name_response(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { offset = dissect_ndr_cvstring(tvb, offset, pinfo, tree, di, drep, sizeof(guint8), hf_mgmt_princ_name, TRUE, NULL); offset = dissect_ntstatus(tvb, offset, pinfo, tree, di, drep, hf_mgmt_rc, NULL); return offset; } static int mgmtrpc_dissect_inq_princ_name_request(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf_mgmt_proto, NULL); offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf_mgmt_princ_size, NULL); return offset; } static dcerpc_sub_dissector mgmt_dissectors[] = { { 0, "rpc__mgmt_inq_if_ids", NULL, NULL }, { 1, "rpc__mgmt_inq_stats", NULL, NULL }, { 2, "rpc__mgmt_is_server_listening", NULL, NULL }, { 3, "rpc__mgmt_stop_server_listening", NULL, NULL }, { 4, "rpc__mgmt_inq_princ_name", mgmtrpc_dissect_inq_princ_name_request, mgmtrpc_dissect_inq_princ_name_response}, { 0, NULL, NULL, NULL } }; void proto_register_mgmt (void) { static hf_register_info hf[] = { { &hf_mgmt_opnum, { "Operation", "mgmt.opnum", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_mgmt_proto, {"Authn Proto", "mgmt.proto", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_mgmt_princ_name, {"Principal name", "mgmt.princ_name", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL }}, { &hf_mgmt_princ_size, {"Principal size", "mgmt.princ_size", FT_UINT32, BASE_DEC, NULL, 0x0, "Size of principal", HFILL }}, { &hf_mgmt_rc, {"Status", "mgmt.rc", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }}, }; static gint *ett[] = { &ett_mgmt }; proto_mgmt = proto_register_protocol ("DCE/RPC Remote Management", "MGMT", "mgmt"); proto_register_field_array (proto_mgmt, hf, array_length (hf)); proto_register_subtree_array (ett, array_length (ett)); } void proto_reg_handoff_mgmt (void) { /* Register the protocol as dcerpc */ dcerpc_init_uuid (proto_mgmt, ett_mgmt, &uuid_mgmt, ver_mgmt, mgmt_dissectors, hf_mgmt_opnum); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
gpl-3.0
10045125/xuggle-xuggler
captive/ffmpeg/csrc/libavformat/rtspenc.c
10
8161
/* * RTSP muxer * Copyright (c) 2010 Martin Storsjo * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include <sys/time.h> #if HAVE_POLL_H #include <poll.h> #endif #include "network.h" #include "os_support.h" #include "rtsp.h" #include "internal.h" #include "avio_internal.h" #include "libavutil/intreadwrite.h" #include "libavutil/avstring.h" #include "url.h" #define SDP_MAX_SIZE 16384 static const AVClass rtsp_muxer_class = { .class_name = "RTSP muxer", .item_name = av_default_item_name, .option = ff_rtsp_options, .version = LIBAVUTIL_VERSION_INT, }; int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; int i; char *sdp; AVFormatContext sdp_ctx, *ctx_array[1]; s->start_time_realtime = av_gettime(); /* Announce the stream */ sdp = av_mallocz(SDP_MAX_SIZE); if (sdp == NULL) return AVERROR(ENOMEM); /* We create the SDP based on the RTSP AVFormatContext where we * aren't allowed to change the filename field. (We create the SDP * based on the RTSP context since the contexts for the RTP streams * don't exist yet.) In order to specify a custom URL with the actual * peer IP instead of the originally specified hostname, we create * a temporary copy of the AVFormatContext, where the custom URL is set. * * FIXME: Create the SDP without copying the AVFormatContext. * This either requires setting up the RTP stream AVFormatContexts * already here (complicating things immensely) or getting a more * flexible SDP creation interface. */ sdp_ctx = *s; ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename), "rtsp", NULL, addr, -1, NULL); ctx_array[0] = &sdp_ctx; if (av_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) { av_free(sdp); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp); ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri, "Content-Type: application/sdp\r\n", reply, NULL, sdp, strlen(sdp)); av_free(sdp); if (reply->status_code != RTSP_STATUS_OK) return AVERROR_INVALIDDATA; /* Set up the RTSPStreams for each AVStream */ for (i = 0; i < s->nb_streams; i++) { RTSPStream *rtsp_st; rtsp_st = av_mallocz(sizeof(RTSPStream)); if (!rtsp_st) return AVERROR(ENOMEM); dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st); rtsp_st->stream_index = i; av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url)); /* Note, this must match the relative uri set in the sdp content */ av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url), "/streamid=%d", i); } return 0; } static int rtsp_write_record(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; char cmd[1024]; snprintf(cmd, sizeof(cmd), "Range: npt=0.000-\r\n"); ff_rtsp_send_cmd(s, "RECORD", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) return -1; rt->state = RTSP_STATE_STREAMING; return 0; } static int rtsp_write_header(AVFormatContext *s) { int ret; ret = ff_rtsp_connect(s); if (ret) return ret; if (rtsp_write_record(s) < 0) { ff_rtsp_close_streams(s); ff_rtsp_close_connections(s); return AVERROR_INVALIDDATA; } return 0; } static int tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st) { RTSPState *rt = s->priv_data; AVFormatContext *rtpctx = rtsp_st->transport_priv; uint8_t *buf, *ptr; int size; uint8_t *interleave_header, *interleaved_packet; size = avio_close_dyn_buf(rtpctx->pb, &buf); ptr = buf; while (size > 4) { uint32_t packet_len = AV_RB32(ptr); int id; /* The interleaving header is exactly 4 bytes, which happens to be * the same size as the packet length header from * ffio_open_dyn_packet_buf. So by writing the interleaving header * over these bytes, we get a consecutive interleaved packet * that can be written in one call. */ interleaved_packet = interleave_header = ptr; ptr += 4; size -= 4; if (packet_len > size || packet_len < 2) break; if (RTP_PT_IS_RTCP(ptr[1])) id = rtsp_st->interleaved_max; /* RTCP */ else id = rtsp_st->interleaved_min; /* RTP */ interleave_header[0] = '$'; interleave_header[1] = id; AV_WB16(interleave_header + 2, packet_len); ffurl_write(rt->rtsp_hd_out, interleaved_packet, 4 + packet_len); ptr += packet_len; size -= packet_len; } av_free(buf); ffio_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE); return 0; } static int rtsp_write_packet(AVFormatContext *s, AVPacket *pkt) { RTSPState *rt = s->priv_data; RTSPStream *rtsp_st; int n; struct pollfd p = {ffurl_get_file_handle(rt->rtsp_hd), POLLIN, 0}; AVFormatContext *rtpctx; int ret; while (1) { n = poll(&p, 1, 0); if (n <= 0) break; if (p.revents & POLLIN) { RTSPMessageHeader reply; /* Don't let ff_rtsp_read_reply handle interleaved packets, * since it would block and wait for an RTSP reply on the socket * (which may not be coming any time soon) if it handles * interleaved packets internally. */ ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL); if (ret < 0) return AVERROR(EPIPE); if (ret == 1) ff_rtsp_skip_packet(s); /* XXX: parse message */ if (rt->state != RTSP_STATE_STREAMING) return AVERROR(EPIPE); } } if (pkt->stream_index < 0 || pkt->stream_index >= rt->nb_rtsp_streams) return AVERROR_INVALIDDATA; rtsp_st = rt->rtsp_streams[pkt->stream_index]; rtpctx = rtsp_st->transport_priv; ret = ff_write_chained(rtpctx, 0, pkt, s); /* ff_write_chained does all the RTP packetization. If using TCP as * transport, rtpctx->pb is only a dyn_packet_buf that queues up the * packets, so we need to send them out on the TCP connection separately. */ if (!ret && rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) ret = tcp_write_packet(s, rtsp_st); return ret; } static int rtsp_write_close(AVFormatContext *s) { RTSPState *rt = s->priv_data; ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL); ff_rtsp_close_streams(s); ff_rtsp_close_connections(s); ff_network_close(); return 0; } AVOutputFormat ff_rtsp_muxer = { .name = "rtsp", .long_name = NULL_IF_CONFIG_SMALL("RTSP output format"), .priv_data_size = sizeof(RTSPState), .audio_codec = CODEC_ID_AAC, .video_codec = CODEC_ID_MPEG4, .write_header = rtsp_write_header, .write_packet = rtsp_write_packet, .write_trailer = rtsp_write_close, .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER, .priv_class = &rtsp_muxer_class, };
gpl-3.0
NHOrus/OpenXcom
src/Interface/ComboBox.cpp
11
10765
/* * Copyright 2010-2016 OpenXcom Developers. * * This file is part of OpenXcom. * * OpenXcom is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenXcom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ #include "ComboBox.h" #include <algorithm> #include "TextButton.h" #include "Window.h" #include "TextList.h" #include "../Engine/State.h" #include "../Engine/Language.h" #include "../Engine/Font.h" #include "../Engine/Action.h" #include "../Engine/Options.h" #include "../Engine/Screen.h" namespace OpenXcom { const int ComboBox::HORIZONTAL_MARGIN = 2; const int ComboBox::VERTICAL_MARGIN = 3; const int ComboBox::MAX_ITEMS = 10; const int ComboBox::BUTTON_WIDTH = 14; const int ComboBox::TEXT_HEIGHT = 8; static int getPopupWindowY(int buttonHeight, int buttonY, int popupHeight, bool popupAboveButton) { int belowButtonY = buttonY + buttonHeight; if (popupAboveButton) { // used when popup list won't fit below the button; display it above return buttonY - popupHeight; } return belowButtonY; } /** * Sets up a combobox with the specified size and position. * @param state Pointer to state the combobox belongs to. * @param width Width in pixels. * @param height Height in pixels. * @param x X position in pixels. * @param y Y position in pixels. */ ComboBox::ComboBox(State *state, int width, int height, int x, int y, bool popupAboveButton) : InteractiveSurface(width, height, x, y), _change(0), _sel(0), _state(state), _lang(0), _toggled(false), _popupAboveButton(popupAboveButton) { _button = new TextButton(width, height, x, y); _button->setComboBox(this); _arrow = new Surface(11, 8, x + width - BUTTON_WIDTH, y + 4); int popupHeight = MAX_ITEMS * TEXT_HEIGHT + VERTICAL_MARGIN * 2; int popupY = getPopupWindowY(height, y, popupHeight, popupAboveButton); _window = new Window(state, width, popupHeight, x, popupY); _window->setThinBorder(); _list = new TextList(width - HORIZONTAL_MARGIN * 2 - BUTTON_WIDTH + 1, popupHeight - (VERTICAL_MARGIN * 2 + 2), x + HORIZONTAL_MARGIN, popupY + VERTICAL_MARGIN); _list->setComboBox(this); _list->setColumns(1, _list->getWidth()); _list->setSelectable(true); _list->setBackground(_window); _list->setAlign(ALIGN_CENTER); _list->setScrolling(true, 0); toggle(true); } /** * Deletes all the stuff contained in the list. */ ComboBox::~ComboBox() { delete _button; delete _arrow; delete _window; delete _list; } /** * Changes the position of the surface in the X axis. * @param x X position in pixels. */ void ComboBox::setX(int x) { Surface::setX(x); _button->setX(x); _arrow->setX(x + getWidth() - BUTTON_WIDTH); _window->setX(x); _list->setX(x + HORIZONTAL_MARGIN); } /** * Changes the position of the surface in the Y axis. * @param y Y position in pixels. */ void ComboBox::setY(int y) { Surface::setY(y); _button->setY(y); _arrow->setY(y + 4); int popupHeight = _window->getHeight(); int popupY = getPopupWindowY(getHeight(), y, popupHeight, _popupAboveButton); _window->setY(popupY); _list->setY(popupY + VERTICAL_MARGIN); } /** * Replaces a certain amount of colors in the palette of all * the text contained in the list. * @param colors Pointer to the set of colors. * @param firstcolor Offset of the first color to replace. * @param ncolors Amount of colors to replace. */ void ComboBox::setPalette(SDL_Color *colors, int firstcolor, int ncolors) { Surface::setPalette(colors, firstcolor, ncolors); _button->setPalette(colors, firstcolor, ncolors); _arrow->setPalette(colors, firstcolor, ncolors); _window->setPalette(colors, firstcolor, ncolors); _list->setPalette(colors, firstcolor, ncolors); } /** * Changes the resources for the text in the combo box. * @param big Pointer to large-size font. * @param small Pointer to small-size font. * @param lang Pointer to current language. */ void ComboBox::initText(Font *big, Font *small, Language *lang) { _lang = lang; _button->initText(big, small, lang); _list->initText(big, small, lang); } /** * Changes the surface used to draw the background of the combo box. * @param bg New background. */ void ComboBox::setBackground(Surface *bg) { _window->setBackground(bg); } /** * Changes the color used to draw the combo box. * @param color Color value. */ void ComboBox::setColor(Uint8 color) { _color = color; drawArrow(); _button->setColor(_color); _window->setColor(_color); _list->setColor(_color); } /** * Returns the color used to draw the combo box. * @return Color value. */ Uint8 ComboBox::getColor() const { return _color; } /** * Draws the arrow used to indicate the combo box. */ void ComboBox::drawArrow() { _arrow->clear(); SDL_Rect square; int color = _color + 1; if (color == 256) color++; // Draw arrow triangle 1 square.x = 1; square.y = 2; square.w = 9; square.h = 1; for (; square.w > 1; square.w -= 2) { _arrow->drawRect(&square, color + 2); square.x++; square.y++; } _arrow->drawRect(&square, color + 2); // Draw arrow triangle 2 square.x = 2; square.y = 2; square.w = 7; square.h = 1; for (; square.w > 1; square.w -= 2) { _arrow->drawRect(&square, color); square.x++; square.y++; } _arrow->drawRect(&square, color); } /** * Enables/disables high contrast color. Mostly used for * Battlescape UI. * @param contrast High contrast setting. */ void ComboBox::setHighContrast(bool contrast) { _button->setHighContrast(contrast); _window->setHighContrast(contrast); _list->setHighContrast(contrast); } /** * Changes the color of the arrow buttons in the list. * @param color Color value. */ void ComboBox::setArrowColor(Uint8 color) { _list->setArrowColor(color); } /** * Returns the currently selected option. * @return Selected row. */ size_t ComboBox::getSelected() const { return _sel; } size_t ComboBox::getHoveredListIdx() const { size_t ret = -1; if (_list->getVisible()) { ret = _list->getSelectedRow(); } if ((size_t)-1 == ret) { ret = _sel; } return ret; } /** * sets the button text independent of the currently selected option. * @param text the text to display */ void ComboBox::setText(const std::string &text) { _button->setText(text); } /** * Changes the currently selected option. * @param sel Selected row. */ void ComboBox::setSelected(size_t sel) { _sel = sel; if (_sel < _list->getTexts()) { _button->setText(_list->getCellText(_sel, 0)); } } /** * Updates the size of the dropdown list based on * the number of options available. * @param options Number of options. */ void ComboBox::setDropdown(int options) { int items = std::min(options, MAX_ITEMS); int h = _button->getFont()->getHeight() + _button->getFont()->getSpacing(); int dy = (Options::baseYResolution - 200) / 2; while (_window->getY() + items * h + VERTICAL_MARGIN * 2 > 200 + dy) { items--; } int popupHeight = items * h + VERTICAL_MARGIN * 2; int popupY = getPopupWindowY(getHeight(), getY(), popupHeight, _popupAboveButton); _window->setY(popupY); _window->setHeight(popupHeight); _list->setY(popupY + VERTICAL_MARGIN); _list->setHeight(items * h); } /** * Changes the list of available options to choose from. * @param options List of strings. * @param translate True for a list of string IDs, false for a list of raw strings. */ void ComboBox::setOptions(const std::vector<std::string> &options, bool translate) { setDropdown(options.size()); _list->clearList(); for (std::vector<std::string>::const_iterator i = options.begin(); i != options.end(); ++i) { if (translate) _list->addRow(1, _lang->getString(*i).c_str()); else _list->addRow(1, i->c_str()); } setSelected(_sel); } /** * Blits the combo box components. * @param surface Pointer to surface to blit onto. */ void ComboBox::blit(Surface *surface) { Surface::blit(surface); _list->invalidate(); if (_visible && !_hidden) { _button->blit(surface); _arrow->blit(surface); _window->blit(surface); _list->blit(surface); } } /** * Passes events to internal components. * @param action Pointer to an action. * @param state State that the action handlers belong to. */ void ComboBox::handle(Action *action, State *state) { _button->handle(action, state); _list->handle(action, state); InteractiveSurface::handle(action, state); int topY = std::min(getY(), _window->getY()); if (_window->getVisible() && action->getDetails()->type == SDL_MOUSEBUTTONDOWN && (action->getAbsoluteXMouse() < getX() || action->getAbsoluteXMouse() >= getX() + getWidth() || action->getAbsoluteYMouse() < topY || action->getAbsoluteYMouse() >= topY + getHeight() + _window->getHeight())) { toggle(); } if (_toggled) { if (_change) { (state->*_change)(action); } _toggled = false; } } /** * Passes ticks to arrow buttons. */ void ComboBox::think() { _button->think(); _arrow->think(); _window->think(); _list->think(); InteractiveSurface::think(); } /** * Opens/closes the combo box list. * @param first Is it the initialization toggle? */ void ComboBox::toggle(bool first) { _window->setVisible(!_window->getVisible()); _list->setVisible(!_list->getVisible()); _state->setModal(_window->getVisible() ? this : 0); if (!first && !_window->getVisible()) { _toggled = true; } if (_list->getVisible()) { if (_sel < _list->getVisibleRows()/2) { _list->scrollTo(0); } else { _list->scrollTo(_sel - _list->getVisibleRows()/2); } } } /** * Sets a function to be called every time the slider's value changes. * @param handler Action handler. */ void ComboBox::onChange(ActionHandler handler) { _change = handler; } /** * Sets a function to be called every time the mouse moves in to the listbox surface. * @param handler Action handler. */ void ComboBox::onListMouseIn(ActionHandler handler) { _list->onMouseIn(handler); } /** * Sets a function to be called every time the mouse moves out of the listbox surface. * @param handler Action handler. */ void ComboBox::onListMouseOut(ActionHandler handler) { _list->onMouseOut(handler); } /** * Sets a function to be called every time the mouse moves over the listbox surface. * @param handler Action handler. */ void ComboBox::onListMouseOver(ActionHandler handler) { _list->onMouseOver(handler); } }
gpl-3.0
VanillaProject/platform_external_bash
lib/sh/casemod.c
11
5842
/* casemod.c -- functions to change case of strings */ /* Copyright (C) 2008,2009 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash. If not, see <http://www.gnu.org/licenses/>. */ #if defined (HAVE_CONFIG_H) # include <config.h> #endif #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif /* HAVE_UNISTD_H */ #include <stdc.h> #include <bashansi.h> #include <bashintl.h> #include <bashtypes.h> #include <stdio.h> #include <ctype.h> #include <xmalloc.h> #include <shmbutil.h> #include <chartypes.h> #include <glob/strmatch.h> #define _to_wupper(wc) (iswlower (wc) ? towupper (wc) : (wc)) #define _to_wlower(wc) (iswupper (wc) ? towlower (wc) : (wc)) #if !defined (HANDLE_MULTIBYTE) # define cval(s, i) ((s)[(i)]) # define iswalnum(c) (isalnum(c)) # define TOGGLE(x) (ISUPPER (x) ? tolower (x) : (TOUPPER (x))) #else # define TOGGLE(x) (iswupper (x) ? towlower (x) : (_to_wupper(x))) #endif /* These must agree with the defines in externs.h */ #define CASE_NOOP 0x0000 #define CASE_LOWER 0x0001 #define CASE_UPPER 0x0002 #define CASE_CAPITALIZE 0x0004 #define CASE_UNCAP 0x0008 #define CASE_TOGGLE 0x0010 #define CASE_TOGGLEALL 0x0020 #define CASE_UPFIRST 0x0040 #define CASE_LOWFIRST 0x0080 #define CASE_USEWORDS 0x1000 /* modify behavior to act on words in passed string */ extern char *substring __P((char *, int, int)); #if defined (HANDLE_MULTIBYTE) static wchar_t cval (s, i) char *s; int i; { size_t tmp; wchar_t wc; int l; mbstate_t mps; if (MB_CUR_MAX == 1) return ((wchar_t)s[i]); l = strlen (s); if (i >= (l - 1)) return ((wchar_t)s[i]); memset (&mps, 0, sizeof (mbstate_t)); tmp = mbrtowc (&wc, s + i, l - i, &mps); if (MB_INVALIDCH (tmp) || MB_NULLWCH (tmp)) return ((wchar_t)s[i]); return wc; } #endif /* Modify the case of characters in STRING matching PAT based on the value of FLAGS. If PAT is null, modify the case of each character */ char * sh_modcase (string, pat, flags) const char *string; char *pat; int flags; { int start, next, end; int inword, c, nc, nop, match, usewords; char *ret, *s; wchar_t wc; #if defined (HANDLE_MULTIBYTE) wchar_t nwc; char mb[MB_LEN_MAX+1]; int mlen; size_t m; mbstate_t state; #endif #if defined (HANDLE_MULTIBYTE) memset (&state, 0, sizeof (mbstate_t)); #endif start = 0; end = strlen (string); ret = (char *)xmalloc (end + 1); strcpy (ret, string); /* See if we are supposed to split on alphanumerics and operate on each word */ usewords = (flags & CASE_USEWORDS); flags &= ~CASE_USEWORDS; inword = 0; while (start < end) { wc = cval (ret, start); if (iswalnum (wc) == 0) { inword = 0; ADVANCE_CHAR (ret, end, start); continue; } if (pat) { next = start; ADVANCE_CHAR (ret, end, next); s = substring (ret, start, next); match = strmatch (pat, s, FNM_EXTMATCH) != FNM_NOMATCH; free (s); if (match == 0) { start = next; inword = 1; continue; } } /* XXX - for now, the toggling operators work on the individual words in the string, breaking on alphanumerics. Should I leave the capitalization operators to do that also? */ if (flags == CASE_CAPITALIZE) { if (usewords) nop = inword ? CASE_LOWER : CASE_UPPER; else nop = (start > 0) ? CASE_LOWER : CASE_UPPER; inword = 1; } else if (flags == CASE_UNCAP) { if (usewords) nop = inword ? CASE_UPPER : CASE_LOWER; else nop = (start > 0) ? CASE_UPPER : CASE_LOWER; inword = 1; } else if (flags == CASE_UPFIRST) { if (usewords) nop = inword ? CASE_NOOP : CASE_UPPER; else nop = (start > 0) ? CASE_NOOP : CASE_UPPER; inword = 1; } else if (flags == CASE_LOWFIRST) { if (usewords) nop = inword ? CASE_NOOP : CASE_LOWER; else nop = (start > 0) ? CASE_NOOP : CASE_LOWER; inword = 1; } else if (flags == CASE_TOGGLE) { nop = inword ? CASE_NOOP : CASE_TOGGLE; inword = 1; } else nop = flags; if (MB_CUR_MAX == 1 || isascii (wc)) { switch (nop) { default: case CASE_NOOP: nc = wc; break; case CASE_UPPER: nc = TOUPPER (wc); break; case CASE_LOWER: nc = TOLOWER (wc); break; case CASE_TOGGLEALL: case CASE_TOGGLE: nc = TOGGLE (wc); break; } ret[start] = nc; } #if defined (HANDLE_MULTIBYTE) else { m = mbrtowc (&wc, string + start, end - start, &state); if (MB_INVALIDCH (m)) wc = (wchar_t)string[start]; else if (MB_NULLWCH (m)) wc = L'\0'; switch (nop) { default: case CASE_NOOP: nwc = wc; break; case CASE_UPPER: nwc = TOUPPER (wc); break; case CASE_LOWER: nwc = TOLOWER (wc); break; case CASE_TOGGLEALL: case CASE_TOGGLE: nwc = TOGGLE (wc); break; } if (nwc != wc) /* just skip unchanged characters */ { mlen = wcrtomb (mb, nwc, &state); if (mlen > 0) mb[mlen] = '\0'; /* Assume the same width */ strncpy (ret + start, mb, mlen); } } #endif /* This assumes that the upper and lower case versions are the same width. */ ADVANCE_CHAR (ret, end, start); } return ret; }
gpl-3.0
shugaoye/u-boot
drivers/usb/host/ohci-s3c24xx.c
11
47066
/* * URB OHCI HCD (Host Controller Driver) for USB on the S3C2400. * * (C) Copyright 2003 * Gary Jennejohn, DENX Software Engineering <garyj@denx.de> * * Note: Much of this code has been derived from Linux 2.4 * (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at> * (C) Copyright 2000-2002 David Brownell * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ /* * IMPORTANT NOTES * 1 - this driver is intended for use with USB Mass Storage Devices * (BBB) ONLY. There is NO support for Interrupt or Isochronous pipes! */ #include <common.h> /* #include <pci.h> no PCI on the S3C24X0 */ #if defined(CONFIG_USB_OHCI) && defined(CONFIG_S3C24X0) #include <asm/arch/s3c24x0_cpu.h> #include <asm/io.h> #include <malloc.h> #include <usb.h> #include "ohci-s3c24xx.h" #define OHCI_USE_NPS /* force NoPowerSwitching mode */ #undef OHCI_VERBOSE_DEBUG /* not always helpful */ /* For initializing controller (mask in an HCFS mode too) */ #define OHCI_CONTROL_INIT \ (OHCI_CTRL_CBSR & 0x3) | OHCI_CTRL_IE | OHCI_CTRL_PLE #define min_t(type, x, y) \ ({ type __x = (x); type __y = (y); __x < __y ? __x : __y; }) #undef DEBUG #ifdef DEBUG #define dbg(format, arg...) printf("DEBUG: " format "\n", ## arg) #else #define dbg(format, arg...) do {} while(0) #endif /* DEBUG */ #define err(format, arg...) printf("ERROR: " format "\n", ## arg) #undef SHOW_INFO #ifdef SHOW_INFO #define info(format, arg...) printf("INFO: " format "\n", ## arg) #else #define info(format, arg...) do {} while(0) #endif #define m16_swap(x) swap_16(x) #define m32_swap(x) swap_32(x) /* global struct ohci */ static struct ohci gohci; /* this must be aligned to a 256 byte boundary */ struct ohci_hcca ghcca[1]; /* a pointer to the aligned storage */ struct ohci_hcca *phcca; /* this allocates EDs for all possible endpoints */ struct ohci_device ohci_dev; /* urb_priv */ struct urb_priv urb_priv; /* RHSC flag */ int got_rhsc; /* device which was disconnected */ struct usb_device *devgone; /* flag guarding URB transation */ int urb_finished = 0; /*-------------------------------------------------------------------------*/ /* AMD-756 (D2 rev) reports corrupt register contents in some cases. * The erratum (#4) description is incorrect. AMD's workaround waits * till some bits (mostly reserved) are clear; ok for all revs. */ #define OHCI_QUIRK_AMD756 0xabcd #define read_roothub(hc, register, mask) ({ \ u32 temp = readl (&hc->regs->roothub.register); \ if (hc->flags & OHCI_QUIRK_AMD756) \ while (temp & mask) \ temp = readl (&hc->regs->roothub.register); \ temp; }) static u32 roothub_a(struct ohci *hc) { return read_roothub(hc, a, 0xfc0fe000); } static inline u32 roothub_b(struct ohci *hc) { return readl(&hc->regs->roothub.b); } static inline u32 roothub_status(struct ohci *hc) { return readl(&hc->regs->roothub.status); } static u32 roothub_portstatus(struct ohci *hc, int i) { return read_roothub(hc, portstatus[i], 0xffe0fce0); } /* forward declaration */ static int hc_interrupt(void); static void td_submit_job(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *setup, struct urb_priv *urb, int interval); /*-------------------------------------------------------------------------* * URB support functions *-------------------------------------------------------------------------*/ /* free HCD-private data associated with this URB */ static void urb_free_priv(struct urb_priv *urb) { int i; int last; struct td *td; last = urb->length - 1; if (last >= 0) { for (i = 0; i <= last; i++) { td = urb->td[i]; if (td) { td->usb_dev = NULL; urb->td[i] = NULL; } } } } /*-------------------------------------------------------------------------*/ #ifdef DEBUG static int sohci_get_current_frame_number(struct usb_device *dev); /* debug| print the main components of an URB * small: 0) header + data packets 1) just header */ static void pkt_print(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *setup, char *str, int small) { struct urb_priv *purb = &urb_priv; dbg("%s URB:[%4x] dev:%2d,ep:%2d-%c,type:%s,len:%d/%d stat:%#lx", str, sohci_get_current_frame_number(dev), usb_pipedevice(pipe), usb_pipeendpoint(pipe), usb_pipeout(pipe) ? 'O' : 'I', usb_pipetype(pipe) < 2 ? (usb_pipeint(pipe) ? "INTR" : "ISOC") : (usb_pipecontrol(pipe) ? "CTRL" : "BULK"), purb->actual_length, transfer_len, dev->status); #ifdef OHCI_VERBOSE_DEBUG if (!small) { int i, len; if (usb_pipecontrol(pipe)) { printf(__FILE__ ": cmd(8):"); for (i = 0; i < 8; i++) printf(" %02x", ((__u8 *) setup)[i]); printf("\n"); } if (transfer_len > 0 && buffer) { printf(__FILE__ ": data(%d/%d):", purb->actual_length, transfer_len); len = usb_pipeout(pipe) ? transfer_len : purb->actual_length; for (i = 0; i < 16 && i < len; i++) printf(" %02x", ((__u8 *) buffer)[i]); printf("%s\n", i < len ? "..." : ""); } } #endif } /* just for debugging; prints non-empty branches of the int ed tree inclusive iso eds*/ void ep_print_int_eds(struct ohci *ohci, char *str) { int i, j; __u32 *ed_p; for (i = 0; i < 32; i++) { j = 5; ed_p = &(ohci->hcca->int_table[i]); if (*ed_p == 0) continue; printf(__FILE__ ": %s branch int %2d(%2x):", str, i, i); while (*ed_p != 0 && j--) { struct ed *ed = (struct ed *) m32_swap(ed_p); printf(" ed: %4x;", ed->hwINFO); ed_p = &ed->hwNextED; } printf("\n"); } } static void ohci_dump_intr_mask(char *label, __u32 mask) { dbg("%s: 0x%08x%s%s%s%s%s%s%s%s%s", label, mask, (mask & OHCI_INTR_MIE) ? " MIE" : "", (mask & OHCI_INTR_OC) ? " OC" : "", (mask & OHCI_INTR_RHSC) ? " RHSC" : "", (mask & OHCI_INTR_FNO) ? " FNO" : "", (mask & OHCI_INTR_UE) ? " UE" : "", (mask & OHCI_INTR_RD) ? " RD" : "", (mask & OHCI_INTR_SF) ? " SF" : "", (mask & OHCI_INTR_WDH) ? " WDH" : "", (mask & OHCI_INTR_SO) ? " SO" : ""); } static void maybe_print_eds(char *label, __u32 value) { struct ed *edp = (struct ed *) value; if (value) { dbg("%s %08x", label, value); dbg("%08x", edp->hwINFO); dbg("%08x", edp->hwTailP); dbg("%08x", edp->hwHeadP); dbg("%08x", edp->hwNextED); } } static char *hcfs2string(int state) { switch (state) { case OHCI_USB_RESET: return "reset"; case OHCI_USB_RESUME: return "resume"; case OHCI_USB_OPER: return "operational"; case OHCI_USB_SUSPEND: return "suspend"; } return "?"; } /* dump control and status registers */ static void ohci_dump_status(struct ohci *controller) { struct ohci_regs *regs = controller->regs; __u32 temp; temp = readl(&regs->revision) & 0xff; if (temp != 0x10) dbg("spec %d.%d", (temp >> 4), (temp & 0x0f)); temp = readl(&regs->control); dbg("control: 0x%08x%s%s%s HCFS=%s%s%s%s%s CBSR=%d", temp, (temp & OHCI_CTRL_RWE) ? " RWE" : "", (temp & OHCI_CTRL_RWC) ? " RWC" : "", (temp & OHCI_CTRL_IR) ? " IR" : "", hcfs2string(temp & OHCI_CTRL_HCFS), (temp & OHCI_CTRL_BLE) ? " BLE" : "", (temp & OHCI_CTRL_CLE) ? " CLE" : "", (temp & OHCI_CTRL_IE) ? " IE" : "", (temp & OHCI_CTRL_PLE) ? " PLE" : "", temp & OHCI_CTRL_CBSR); temp = readl(&regs->cmdstatus); dbg("cmdstatus: 0x%08x SOC=%d%s%s%s%s", temp, (temp & OHCI_SOC) >> 16, (temp & OHCI_OCR) ? " OCR" : "", (temp & OHCI_BLF) ? " BLF" : "", (temp & OHCI_CLF) ? " CLF" : "", (temp & OHCI_HCR) ? " HCR" : ""); ohci_dump_intr_mask("intrstatus", readl(&regs->intrstatus)); ohci_dump_intr_mask("intrenable", readl(&regs->intrenable)); maybe_print_eds("ed_periodcurrent", readl(&regs->ed_periodcurrent)); maybe_print_eds("ed_controlhead", readl(&regs->ed_controlhead)); maybe_print_eds("ed_controlcurrent", readl(&regs->ed_controlcurrent)); maybe_print_eds("ed_bulkhead", readl(&regs->ed_bulkhead)); maybe_print_eds("ed_bulkcurrent", readl(&regs->ed_bulkcurrent)); maybe_print_eds("donehead", readl(&regs->donehead)); } static void ohci_dump_roothub(struct ohci *controller, int verbose) { __u32 temp, ndp, i; temp = roothub_a(controller); ndp = (temp & RH_A_NDP); if (verbose) { dbg("roothub.a: %08x POTPGT=%d%s%s%s%s%s NDP=%d", temp, ((temp & RH_A_POTPGT) >> 24) & 0xff, (temp & RH_A_NOCP) ? " NOCP" : "", (temp & RH_A_OCPM) ? " OCPM" : "", (temp & RH_A_DT) ? " DT" : "", (temp & RH_A_NPS) ? " NPS" : "", (temp & RH_A_PSM) ? " PSM" : "", ndp); temp = roothub_b(controller); dbg("roothub.b: %08x PPCM=%04x DR=%04x", temp, (temp & RH_B_PPCM) >> 16, (temp & RH_B_DR) ); temp = roothub_status(controller); dbg("roothub.status: %08x%s%s%s%s%s%s", temp, (temp & RH_HS_CRWE) ? " CRWE" : "", (temp & RH_HS_OCIC) ? " OCIC" : "", (temp & RH_HS_LPSC) ? " LPSC" : "", (temp & RH_HS_DRWE) ? " DRWE" : "", (temp & RH_HS_OCI) ? " OCI" : "", (temp & RH_HS_LPS) ? " LPS" : ""); } for (i = 0; i < ndp; i++) { temp = roothub_portstatus(controller, i); dbg("roothub.portstatus [%d] = 0x%08x%s%s%s%s%s%s%s%s%s%s%s%s", i, temp, (temp & RH_PS_PRSC) ? " PRSC" : "", (temp & RH_PS_OCIC) ? " OCIC" : "", (temp & RH_PS_PSSC) ? " PSSC" : "", (temp & RH_PS_PESC) ? " PESC" : "", (temp & RH_PS_CSC) ? " CSC" : "", (temp & RH_PS_LSDA) ? " LSDA" : "", (temp & RH_PS_PPS) ? " PPS" : "", (temp & RH_PS_PRS) ? " PRS" : "", (temp & RH_PS_POCI) ? " POCI" : "", (temp & RH_PS_PSS) ? " PSS" : "", (temp & RH_PS_PES) ? " PES" : "", (temp & RH_PS_CCS) ? " CCS" : ""); } } static void ohci_dump(struct ohci *controller, int verbose) { dbg("OHCI controller usb-%s state", controller->slot_name); /* dumps some of the state we know about */ ohci_dump_status(controller); if (verbose) ep_print_int_eds(controller, "hcca"); dbg("hcca frame #%04x", controller->hcca->frame_no); ohci_dump_roothub(controller, 1); } #endif /* DEBUG */ /*-------------------------------------------------------------------------* * Interface functions (URB) *-------------------------------------------------------------------------*/ /* get a transfer request */ int sohci_submit_job(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *setup, int interval) { struct ohci *ohci; struct ed *ed; struct urb_priv *purb_priv; int i, size = 0; ohci = &gohci; /* when controller's hung, permit only roothub cleanup attempts * such as powering down ports */ if (ohci->disabled) { err("sohci_submit_job: EPIPE"); return -1; } /* if we have an unfinished URB from previous transaction let's * fail and scream as quickly as possible so as not to corrupt * further communication */ if (!urb_finished) { err("sohci_submit_job: URB NOT FINISHED"); return -1; } /* we're about to begin a new transaction here so mark the URB unfinished */ urb_finished = 0; /* every endpoint has a ed, locate and fill it */ ed = ep_add_ed(dev, pipe); if (!ed) { err("sohci_submit_job: ENOMEM"); return -1; } /* for the private part of the URB we need the number of TDs (size) */ switch (usb_pipetype(pipe)) { case PIPE_BULK: /* one TD for every 4096 Byte */ size = (transfer_len - 1) / 4096 + 1; break; case PIPE_CONTROL: /* 1 TD for setup, 1 for ACK and 1 for every 4096 B */ size = (transfer_len == 0) ? 2 : (transfer_len - 1) / 4096 + 3; break; } if (size >= (N_URB_TD - 1)) { err("need %d TDs, only have %d", size, N_URB_TD); return -1; } purb_priv = &urb_priv; purb_priv->pipe = pipe; /* fill the private part of the URB */ purb_priv->length = size; purb_priv->ed = ed; purb_priv->actual_length = 0; /* allocate the TDs */ /* note that td[0] was allocated in ep_add_ed */ for (i = 0; i < size; i++) { purb_priv->td[i] = td_alloc(dev); if (!purb_priv->td[i]) { purb_priv->length = i; urb_free_priv(purb_priv); err("sohci_submit_job: ENOMEM"); return -1; } } if (ed->state == ED_NEW || (ed->state & ED_DEL)) { urb_free_priv(purb_priv); err("sohci_submit_job: EINVAL"); return -1; } /* link the ed into a chain if is not already */ if (ed->state != ED_OPER) ep_link(ohci, ed); /* fill the TDs and link it to the ed */ td_submit_job(dev, pipe, buffer, transfer_len, setup, purb_priv, interval); return 0; } /*-------------------------------------------------------------------------*/ #ifdef DEBUG /* tell us the current USB frame number */ static int sohci_get_current_frame_number(struct usb_device *usb_dev) { struct ohci *ohci = &gohci; return m16_swap(ohci->hcca->frame_no); } #endif /*-------------------------------------------------------------------------* * ED handling functions *-------------------------------------------------------------------------*/ /* link an ed into one of the HC chains */ static int ep_link(struct ohci *ohci, struct ed *edi) { struct ed *ed = edi; ed->state = ED_OPER; switch (ed->type) { case PIPE_CONTROL: ed->hwNextED = 0; if (ohci->ed_controltail == NULL) { writel((u32)ed, &ohci->regs->ed_controlhead); } else { ohci->ed_controltail->hwNextED = (__u32) m32_swap(ed); } ed->ed_prev = ohci->ed_controltail; if (!ohci->ed_controltail && !ohci->ed_rm_list[0] && !ohci->ed_rm_list[1] && !ohci->sleeping) { ohci->hc_control |= OHCI_CTRL_CLE; writel(ohci->hc_control, &ohci->regs->control); } ohci->ed_controltail = edi; break; case PIPE_BULK: ed->hwNextED = 0; if (ohci->ed_bulktail == NULL) { writel((u32)ed, &ohci->regs->ed_bulkhead); } else { ohci->ed_bulktail->hwNextED = (__u32) m32_swap(ed); } ed->ed_prev = ohci->ed_bulktail; if (!ohci->ed_bulktail && !ohci->ed_rm_list[0] && !ohci->ed_rm_list[1] && !ohci->sleeping) { ohci->hc_control |= OHCI_CTRL_BLE; writel(ohci->hc_control, &ohci->regs->control); } ohci->ed_bulktail = edi; break; } return 0; } /*-------------------------------------------------------------------------*/ /* unlink an ed from one of the HC chains. * just the link to the ed is unlinked. * the link from the ed still points to another operational ed or 0 * so the HC can eventually finish the processing of the unlinked ed */ static int ep_unlink(struct ohci *ohci, struct ed *ed) { struct ed *next; ed->hwINFO |= m32_swap(OHCI_ED_SKIP); switch (ed->type) { case PIPE_CONTROL: if (ed->ed_prev == NULL) { if (!ed->hwNextED) { ohci->hc_control &= ~OHCI_CTRL_CLE; writel(ohci->hc_control, &ohci->regs->control); } writel(m32_swap(*((__u32 *) &ed->hwNextED)), &ohci->regs->ed_controlhead); } else { ed->ed_prev->hwNextED = ed->hwNextED; } if (ohci->ed_controltail == ed) { ohci->ed_controltail = ed->ed_prev; } else { next = (struct ed *)m32_swap(*((__u32 *)&ed->hwNextED)); next->ed_prev = ed->ed_prev; } break; case PIPE_BULK: if (ed->ed_prev == NULL) { if (!ed->hwNextED) { ohci->hc_control &= ~OHCI_CTRL_BLE; writel(ohci->hc_control, &ohci->regs->control); } writel(m32_swap(*((__u32 *) &ed->hwNextED)), &ohci->regs->ed_bulkhead); } else { ed->ed_prev->hwNextED = ed->hwNextED; } if (ohci->ed_bulktail == ed) { ohci->ed_bulktail = ed->ed_prev; } else { next = (struct ed *)m32_swap(*((__u32 *)&ed->hwNextED)); next->ed_prev = ed->ed_prev; } break; } ed->state = ED_UNLINK; return 0; } /*-------------------------------------------------------------------------*/ /* add/reinit an endpoint; this should be done once at the usb_set_configuration * command, but the USB stack is a little bit stateless so we do it at every * transaction. If the state of the ed is ED_NEW then a dummy td is added and * the state is changed to ED_UNLINK. In all other cases the state is left * unchanged. The ed info fields are setted anyway even though most of them * should not change */ static struct ed *ep_add_ed(struct usb_device *usb_dev, unsigned long pipe) { struct td *td; struct ed *ed_ret; struct ed *ed; ed = ed_ret = &ohci_dev.ed[(usb_pipeendpoint(pipe) << 1) | (usb_pipecontrol(pipe) ? 0 : usb_pipeout(pipe))]; if ((ed->state & ED_DEL) || (ed->state & ED_URB_DEL)) { err("ep_add_ed: pending delete"); /* pending delete request */ return NULL; } if (ed->state == ED_NEW) { ed->hwINFO = m32_swap(OHCI_ED_SKIP); /* skip ed */ /* dummy td; end of td list for ed */ td = td_alloc(usb_dev); ed->hwTailP = (__u32) m32_swap(td); ed->hwHeadP = ed->hwTailP; ed->state = ED_UNLINK; ed->type = usb_pipetype(pipe); ohci_dev.ed_cnt++; } ed->hwINFO = m32_swap(usb_pipedevice(pipe) | usb_pipeendpoint(pipe) << 7 | (usb_pipeisoc(pipe) ? 0x8000 : 0) | (usb_pipecontrol(pipe) ? 0 : (usb_pipeout(pipe) ? 0x800 : 0x1000)) | usb_pipeslow(pipe) << 13 | usb_maxpacket(usb_dev, pipe) << 16); return ed_ret; } /*-------------------------------------------------------------------------* * TD handling functions *-------------------------------------------------------------------------*/ /* enqueue next TD for this URB (OHCI spec 5.2.8.2) */ static void td_fill(struct ohci *ohci, unsigned int info, void *data, int len, struct usb_device *dev, int index, struct urb_priv *urb_priv) { struct td *td, *td_pt; #ifdef OHCI_FILL_TRACE int i; #endif if (index > urb_priv->length) { err("index > length"); return; } /* use this td as the next dummy */ td_pt = urb_priv->td[index]; td_pt->hwNextTD = 0; /* fill the old dummy TD */ td = urb_priv->td[index] = (struct td *) (m32_swap(urb_priv->ed->hwTailP) & ~0xf); td->ed = urb_priv->ed; td->next_dl_td = NULL; td->index = index; td->data = (__u32) data; #ifdef OHCI_FILL_TRACE if (usb_pipebulk(urb_priv->pipe) && usb_pipeout(urb_priv->pipe)) { for (i = 0; i < len; i++) printf("td->data[%d] %#2x ", i, ((unsigned char *)td->data)[i]); printf("\n"); } #endif if (!len) data = 0; td->hwINFO = (__u32) m32_swap(info); td->hwCBP = (__u32) m32_swap(data); if (data) td->hwBE = (__u32) m32_swap(data + len - 1); else td->hwBE = 0; td->hwNextTD = (__u32) m32_swap(td_pt); /* append to queue */ td->ed->hwTailP = td->hwNextTD; } /*-------------------------------------------------------------------------*/ /* prepare all TDs of a transfer */ static void td_submit_job(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *setup, struct urb_priv *urb, int interval) { struct ohci *ohci = &gohci; int data_len = transfer_len; void *data; int cnt = 0; __u32 info = 0; unsigned int toggle = 0; /* OHCI handles the DATA-toggles itself, we just use the USB-toggle bits for reseting */ if (usb_gettoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe))) { toggle = TD_T_TOGGLE; } else { toggle = TD_T_DATA0; usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 1); } urb->td_cnt = 0; if (data_len) data = buffer; else data = 0; switch (usb_pipetype(pipe)) { case PIPE_BULK: info = usb_pipeout(pipe) ? TD_CC | TD_DP_OUT : TD_CC | TD_DP_IN; while (data_len > 4096) { td_fill(ohci, info | (cnt ? TD_T_TOGGLE : toggle), data, 4096, dev, cnt, urb); data += 4096; data_len -= 4096; cnt++; } info = usb_pipeout(pipe) ? TD_CC | TD_DP_OUT : TD_CC | TD_R | TD_DP_IN; td_fill(ohci, info | (cnt ? TD_T_TOGGLE : toggle), data, data_len, dev, cnt, urb); cnt++; if (!ohci->sleeping) /* start bulk list */ writel(OHCI_BLF, &ohci->regs->cmdstatus); break; case PIPE_CONTROL: info = TD_CC | TD_DP_SETUP | TD_T_DATA0; td_fill(ohci, info, setup, 8, dev, cnt++, urb); if (data_len > 0) { info = usb_pipeout(pipe) ? TD_CC | TD_R | TD_DP_OUT | TD_T_DATA1 : TD_CC | TD_R | TD_DP_IN | TD_T_DATA1; /* NOTE: mishandles transfers >8K, some >4K */ td_fill(ohci, info, data, data_len, dev, cnt++, urb); } info = usb_pipeout(pipe) ? TD_CC | TD_DP_IN | TD_T_DATA1 : TD_CC | TD_DP_OUT | TD_T_DATA1; td_fill(ohci, info, data, 0, dev, cnt++, urb); if (!ohci->sleeping) /* start Control list */ writel(OHCI_CLF, &ohci->regs->cmdstatus); break; } if (urb->length != cnt) dbg("TD LENGTH %d != CNT %d", urb->length, cnt); } /*-------------------------------------------------------------------------* * Done List handling functions *-------------------------------------------------------------------------*/ /* calculate the transfer length and update the urb */ static void dl_transfer_length(struct td *td) { __u32 tdBE, tdCBP; struct urb_priv *lurb_priv = &urb_priv; tdBE = m32_swap(td->hwBE); tdCBP = m32_swap(td->hwCBP); if (!(usb_pipecontrol(lurb_priv->pipe) && ((td->index == 0) || (td->index == lurb_priv->length - 1)))) { if (tdBE != 0) { if (td->hwCBP == 0) lurb_priv->actual_length += tdBE - td->data + 1; else lurb_priv->actual_length += tdCBP - td->data; } } } /*-------------------------------------------------------------------------*/ /* replies to the request have to be on a FIFO basis so * we reverse the reversed done-list */ static struct td *dl_reverse_done_list(struct ohci *ohci) { __u32 td_list_hc; __u32 tmp; struct td *td_rev = NULL; struct td *td_list = NULL; struct urb_priv *lurb_priv = NULL; td_list_hc = m32_swap(ohci->hcca->done_head) & 0xfffffff0; ohci->hcca->done_head = 0; while (td_list_hc) { td_list = (struct td *) td_list_hc; if (TD_CC_GET(m32_swap(td_list->hwINFO))) { lurb_priv = &urb_priv; dbg(" USB-error/status: %x : %p", TD_CC_GET(m32_swap(td_list->hwINFO)), td_list); if (td_list->ed->hwHeadP & m32_swap(0x1)) { if (lurb_priv && ((td_list->index+1) < lurb_priv->length)) { tmp = lurb_priv->length - 1; td_list->ed->hwHeadP = (lurb_priv->td[tmp]->hwNextTD & m32_swap(0xfffffff0)) | (td_list->ed->hwHeadP & m32_swap(0x2)); lurb_priv->td_cnt += lurb_priv->length - td_list->index - 1; } else td_list->ed->hwHeadP &= m32_swap(0xfffffff2); } } td_list->next_dl_td = td_rev; td_rev = td_list; td_list_hc = m32_swap(td_list->hwNextTD) & 0xfffffff0; } return td_list; } /*-------------------------------------------------------------------------*/ /* td done list */ static int dl_done_list(struct ohci *ohci, struct td *td_list) { struct td *td_list_next = NULL; struct ed *ed; int cc = 0; int stat = 0; /* urb_t *urb; */ struct urb_priv *lurb_priv; __u32 tdINFO, edHeadP, edTailP; while (td_list) { td_list_next = td_list->next_dl_td; lurb_priv = &urb_priv; tdINFO = m32_swap(td_list->hwINFO); ed = td_list->ed; dl_transfer_length(td_list); /* error code of transfer */ cc = TD_CC_GET(tdINFO); if (cc != 0) { dbg("ConditionCode %#x", cc); stat = cc_to_error[cc]; } /* see if this done list makes for all TD's of current URB, * and mark the URB finished if so */ if (++(lurb_priv->td_cnt) == lurb_priv->length) { if ((ed->state & (ED_OPER | ED_UNLINK))) urb_finished = 1; else dbg("dl_done_list: strange.., ED state %x, " "ed->state\n"); } else dbg("dl_done_list: processing TD %x, len %x\n", lurb_priv->td_cnt, lurb_priv->length); if (ed->state != ED_NEW) { edHeadP = m32_swap(ed->hwHeadP) & 0xfffffff0; edTailP = m32_swap(ed->hwTailP); /* unlink eds if they are not busy */ if ((edHeadP == edTailP) && (ed->state == ED_OPER)) ep_unlink(ohci, ed); } td_list = td_list_next; } return stat; } /*-------------------------------------------------------------------------* * Virtual Root Hub *-------------------------------------------------------------------------*/ /* Device descriptor */ static __u8 root_hub_dev_des[] = { 0x12, /* __u8 bLength; */ 0x01, /* __u8 bDescriptorType; Device */ 0x10, /* __u16 bcdUSB; v1.1 */ 0x01, 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */ 0x00, /* __u8 bDeviceSubClass; */ 0x00, /* __u8 bDeviceProtocol; */ 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */ 0x00, /* __u16 idVendor; */ 0x00, 0x00, /* __u16 idProduct; */ 0x00, 0x00, /* __u16 bcdDevice; */ 0x00, 0x00, /* __u8 iManufacturer; */ 0x01, /* __u8 iProduct; */ 0x00, /* __u8 iSerialNumber; */ 0x01 /* __u8 bNumConfigurations; */ }; /* Configuration descriptor */ static __u8 root_hub_config_des[] = { 0x09, /* __u8 bLength; */ 0x02, /* __u8 bDescriptorType; Configuration */ 0x19, /* __u16 wTotalLength; */ 0x00, 0x01, /* __u8 bNumInterfaces; */ 0x01, /* __u8 bConfigurationValue; */ 0x00, /* __u8 iConfiguration; */ 0x40, /* __u8 bmAttributes; Bit 7: Bus-powered, 6: Self-powered, 5 Remote-wakwup, 4..0: resvd */ 0x00, /* __u8 MaxPower; */ /* interface */ 0x09, /* __u8 if_bLength; */ 0x04, /* __u8 if_bDescriptorType; Interface */ 0x00, /* __u8 if_bInterfaceNumber; */ 0x00, /* __u8 if_bAlternateSetting; */ 0x01, /* __u8 if_bNumEndpoints; */ 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */ 0x00, /* __u8 if_bInterfaceSubClass; */ 0x00, /* __u8 if_bInterfaceProtocol; */ 0x00, /* __u8 if_iInterface; */ /* endpoint */ 0x07, /* __u8 ep_bLength; */ 0x05, /* __u8 ep_bDescriptorType; Endpoint */ 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */ 0x03, /* __u8 ep_bmAttributes; Interrupt */ 0x02, /* __u16 ep_wMaxPacketSize; ((MAX_ROOT_PORTS + 1) / 8 */ 0x00, 0xff /* __u8 ep_bInterval; 255 ms */ }; static unsigned char root_hub_str_index0[] = { 0x04, /* __u8 bLength; */ 0x03, /* __u8 bDescriptorType; String-descriptor */ 0x09, /* __u8 lang ID */ 0x04, /* __u8 lang ID */ }; static unsigned char root_hub_str_index1[] = { 28, /* __u8 bLength; */ 0x03, /* __u8 bDescriptorType; String-descriptor */ 'O', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'H', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'C', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'I', /* __u8 Unicode */ 0, /* __u8 Unicode */ ' ', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'R', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'o', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'o', /* __u8 Unicode */ 0, /* __u8 Unicode */ 't', /* __u8 Unicode */ 0, /* __u8 Unicode */ ' ', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'H', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'u', /* __u8 Unicode */ 0, /* __u8 Unicode */ 'b', /* __u8 Unicode */ 0, /* __u8 Unicode */ }; /* Hub class-specific descriptor is constructed dynamically */ /*-------------------------------------------------------------------------*/ #define OK(x) len = (x); break #ifdef DEBUG #define WR_RH_STAT(x) \ { \ info("WR:status %#8x", (x)); \ writel((x), &gohci.regs->roothub.status); \ } #define WR_RH_PORTSTAT(x) \ { \ info("WR:portstatus[%d] %#8x", wIndex-1, (x)); \ writel((x), &gohci.regs->roothub.portstatus[wIndex-1]); \ } #else #define WR_RH_STAT(x) \ writel((x), &gohci.regs->roothub.status) #define WR_RH_PORTSTAT(x)\ writel((x), &gohci.regs->roothub.portstatus[wIndex-1]) #endif #define RD_RH_STAT roothub_status(&gohci) #define RD_RH_PORTSTAT roothub_portstatus(&gohci, wIndex-1) /* request to virtual root hub */ int rh_check_port_status(struct ohci *controller) { __u32 temp, ndp, i; int res; res = -1; temp = roothub_a(controller); ndp = (temp & RH_A_NDP); for (i = 0; i < ndp; i++) { temp = roothub_portstatus(controller, i); /* check for a device disconnect */ if (((temp & (RH_PS_PESC | RH_PS_CSC)) == (RH_PS_PESC | RH_PS_CSC)) && ((temp & RH_PS_CCS) == 0)) { res = i; break; } } return res; } static int ohci_submit_rh_msg(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *cmd) { void *data = buffer; int leni = transfer_len; int len = 0; int stat = 0; union { __u32 word[4]; __u16 hword[8]; __u8 byte[16]; } datab; __u8 *data_buf = datab.byte; __u16 bmRType_bReq; __u16 wValue; __u16 wIndex; __u16 wLength; #ifdef DEBUG urb_priv.actual_length = 0; pkt_print(dev, pipe, buffer, transfer_len, cmd, "SUB(rh)", usb_pipein(pipe)); #else mdelay(1); #endif if (usb_pipeint(pipe)) { info("Root-Hub submit IRQ: NOT implemented"); return 0; } bmRType_bReq = cmd->requesttype | (cmd->request << 8); wValue = m16_swap(cmd->value); wIndex = m16_swap(cmd->index); wLength = m16_swap(cmd->length); info("Root-Hub: adr: %2x cmd(%1x): %08x %04x %04x %04x", dev->devnum, 8, bmRType_bReq, wValue, wIndex, wLength); switch (bmRType_bReq) { /* Request Destination: without flags: Device, RH_INTERFACE: interface, RH_ENDPOINT: endpoint, RH_CLASS means HUB here, RH_OTHER | RH_CLASS almost ever means HUB_PORT here */ case RH_GET_STATUS: datab.hword[0] = m16_swap(1); OK(2); case RH_GET_STATUS | RH_INTERFACE: datab.hword[0] = m16_swap(0); OK(2); case RH_GET_STATUS | RH_ENDPOINT: datab.hword[0] = m16_swap(0); OK(2); case RH_GET_STATUS | RH_CLASS: datab.word[0] = m32_swap(RD_RH_STAT & ~(RH_HS_CRWE | RH_HS_DRWE)); OK(4); case RH_GET_STATUS | RH_OTHER | RH_CLASS: datab.word[0] = m32_swap(RD_RH_PORTSTAT); OK(4); case RH_CLEAR_FEATURE | RH_ENDPOINT: switch (wValue) { case (RH_ENDPOINT_STALL): OK(0); } break; case RH_CLEAR_FEATURE | RH_CLASS: switch (wValue) { case RH_C_HUB_LOCAL_POWER: OK(0); case (RH_C_HUB_OVER_CURRENT): WR_RH_STAT(RH_HS_OCIC); OK(0); } break; case RH_CLEAR_FEATURE | RH_OTHER | RH_CLASS: switch (wValue) { case (RH_PORT_ENABLE): WR_RH_PORTSTAT(RH_PS_CCS); OK(0); case (RH_PORT_SUSPEND): WR_RH_PORTSTAT(RH_PS_POCI); OK(0); case (RH_PORT_POWER): WR_RH_PORTSTAT(RH_PS_LSDA); OK(0); case (RH_C_PORT_CONNECTION): WR_RH_PORTSTAT(RH_PS_CSC); OK(0); case (RH_C_PORT_ENABLE): WR_RH_PORTSTAT(RH_PS_PESC); OK(0); case (RH_C_PORT_SUSPEND): WR_RH_PORTSTAT(RH_PS_PSSC); OK(0); case (RH_C_PORT_OVER_CURRENT): WR_RH_PORTSTAT(RH_PS_OCIC); OK(0); case (RH_C_PORT_RESET): WR_RH_PORTSTAT(RH_PS_PRSC); OK(0); } break; case RH_SET_FEATURE | RH_OTHER | RH_CLASS: switch (wValue) { case (RH_PORT_SUSPEND): WR_RH_PORTSTAT(RH_PS_PSS); OK(0); case (RH_PORT_RESET): /* BUG IN HUP CODE ******** */ if (RD_RH_PORTSTAT & RH_PS_CCS) WR_RH_PORTSTAT(RH_PS_PRS); OK(0); case (RH_PORT_POWER): WR_RH_PORTSTAT(RH_PS_PPS); OK(0); case (RH_PORT_ENABLE): /* BUG IN HUP CODE ******** */ if (RD_RH_PORTSTAT & RH_PS_CCS) WR_RH_PORTSTAT(RH_PS_PES); OK(0); } break; case RH_SET_ADDRESS: gohci.rh.devnum = wValue; OK(0); case RH_GET_DESCRIPTOR: switch ((wValue & 0xff00) >> 8) { case (0x01): /* device descriptor */ len = min_t(unsigned int, leni, min_t(unsigned int, sizeof(root_hub_dev_des), wLength)); data_buf = root_hub_dev_des; OK(len); case (0x02): /* configuration descriptor */ len = min_t(unsigned int, leni, min_t(unsigned int, sizeof(root_hub_config_des), wLength)); data_buf = root_hub_config_des; OK(len); case (0x03): /* string descriptors */ if (wValue == 0x0300) { len = min_t(unsigned int, leni, min_t(unsigned int, sizeof(root_hub_str_index0), wLength)); data_buf = root_hub_str_index0; OK(len); } if (wValue == 0x0301) { len = min_t(unsigned int, leni, min_t(unsigned int, sizeof(root_hub_str_index1), wLength)); data_buf = root_hub_str_index1; OK(len); } default: stat = USB_ST_STALLED; } break; case RH_GET_DESCRIPTOR | RH_CLASS: { __u32 temp = roothub_a(&gohci); data_buf[0] = 9; /* min length; */ data_buf[1] = 0x29; data_buf[2] = temp & RH_A_NDP; data_buf[3] = 0; if (temp & RH_A_PSM) /* per-port power switching? */ data_buf[3] |= 0x1; if (temp & RH_A_NOCP) /* no overcurrent reporting? */ data_buf[3] |= 0x10; else if (temp & RH_A_OCPM) /* per-port overcurrent reporting? */ data_buf[3] |= 0x8; /* corresponds to data_buf[4-7] */ datab.word[1] = 0; data_buf[5] = (temp & RH_A_POTPGT) >> 24; temp = roothub_b(&gohci); data_buf[7] = temp & RH_B_DR; if (data_buf[2] < 7) { data_buf[8] = 0xff; } else { data_buf[0] += 2; data_buf[8] = (temp & RH_B_DR) >> 8; data_buf[10] = data_buf[9] = 0xff; } len = min_t(unsigned int, leni, min_t(unsigned int, data_buf[0], wLength)); OK(len); } case RH_GET_CONFIGURATION: *(__u8 *) data_buf = 0x01; OK(1); case RH_SET_CONFIGURATION: WR_RH_STAT(0x10000); OK(0); default: dbg("unsupported root hub command"); stat = USB_ST_STALLED; } #ifdef DEBUG ohci_dump_roothub(&gohci, 1); #else mdelay(1); #endif len = min_t(int, len, leni); if (data != data_buf) memcpy(data, data_buf, len); dev->act_len = len; dev->status = stat; #ifdef DEBUG if (transfer_len) urb_priv.actual_length = transfer_len; pkt_print(dev, pipe, buffer, transfer_len, cmd, "RET(rh)", 0 /*usb_pipein(pipe) */); #else mdelay(1); #endif return stat; } /*-------------------------------------------------------------------------*/ /* common code for handling submit messages - used for all but root hub */ /* accesses. */ int submit_common_msg(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *setup, int interval) { int stat = 0; int maxsize = usb_maxpacket(dev, pipe); int timeout; /* device pulled? Shortcut the action. */ if (devgone == dev) { dev->status = USB_ST_CRC_ERR; return 0; } #ifdef DEBUG urb_priv.actual_length = 0; pkt_print(dev, pipe, buffer, transfer_len, setup, "SUB", usb_pipein(pipe)); #else mdelay(1); #endif if (!maxsize) { err("submit_common_message: pipesize for pipe %lx is zero", pipe); return -1; } if (sohci_submit_job(dev, pipe, buffer, transfer_len, setup, interval) < 0) { err("sohci_submit_job failed"); return -1; } mdelay(10); /* ohci_dump_status(&gohci); */ /* allow more time for a BULK device to react - some are slow */ #define BULK_TO 5000 /* timeout in milliseconds */ if (usb_pipebulk(pipe)) timeout = BULK_TO; else timeout = 100; /* wait for it to complete */ for (;;) { /* check whether the controller is done */ stat = hc_interrupt(); if (stat < 0) { stat = USB_ST_CRC_ERR; break; } /* NOTE: since we are not interrupt driven in U-Boot and always * handle only one URB at a time, we cannot assume the * transaction finished on the first successful return from * hc_interrupt().. unless the flag for current URB is set, * meaning that all TD's to/from device got actually * transferred and processed. If the current URB is not * finished we need to re-iterate this loop so as * hc_interrupt() gets called again as there needs to be some * more TD's to process still */ if ((stat >= 0) && (stat != 0xff) && (urb_finished)) { /* 0xff is returned for an SF-interrupt */ break; } if (--timeout) { mdelay(1); if (!urb_finished) dbg("\%"); } else { err("CTL:TIMEOUT "); dbg("submit_common_msg: TO status %x\n", stat); stat = USB_ST_CRC_ERR; urb_finished = 1; break; } } #if 0 /* we got an Root Hub Status Change interrupt */ if (got_rhsc) { #ifdef DEBUG ohci_dump_roothub(&gohci, 1); #endif got_rhsc = 0; /* abuse timeout */ timeout = rh_check_port_status(&gohci); if (timeout >= 0) { #if 0 /* this does nothing useful, but leave it here in case that changes */ /* the called routine adds 1 to the passed value */ usb_hub_port_connect_change(gohci.rh.dev, timeout - 1); #endif /* * XXX * This is potentially dangerous because it assumes * that only one device is ever plugged in! */ devgone = dev; } } #endif dev->status = stat; dev->act_len = transfer_len; #ifdef DEBUG pkt_print(dev, pipe, buffer, transfer_len, setup, "RET(ctlr)", usb_pipein(pipe)); #else mdelay(1); #endif /* free TDs in urb_priv */ urb_free_priv(&urb_priv); return 0; } /* submit routines called from usb.c */ int submit_bulk_msg(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len) { info("submit_bulk_msg"); return submit_common_msg(dev, pipe, buffer, transfer_len, NULL, 0); } int submit_control_msg(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, struct devrequest *setup) { int maxsize = usb_maxpacket(dev, pipe); info("submit_control_msg"); #ifdef DEBUG urb_priv.actual_length = 0; pkt_print(dev, pipe, buffer, transfer_len, setup, "SUB", usb_pipein(pipe)); #else mdelay(1); #endif if (!maxsize) { err("submit_control_message: pipesize for pipe %lx is zero", pipe); return -1; } if (((pipe >> 8) & 0x7f) == gohci.rh.devnum) { gohci.rh.dev = dev; /* root hub - redirect */ return ohci_submit_rh_msg(dev, pipe, buffer, transfer_len, setup); } return submit_common_msg(dev, pipe, buffer, transfer_len, setup, 0); } int submit_int_msg(struct usb_device *dev, unsigned long pipe, void *buffer, int transfer_len, int interval) { info("submit_int_msg"); return -1; } /*-------------------------------------------------------------------------* * HC functions *-------------------------------------------------------------------------*/ /* reset the HC and BUS */ static int hc_reset(struct ohci *ohci) { int timeout = 30; int smm_timeout = 50; /* 0,5 sec */ if (readl(&ohci->regs->control) & OHCI_CTRL_IR) { /* SMM owns the HC - request ownership */ writel(OHCI_OCR, &ohci->regs->cmdstatus); info("USB HC TakeOver from SMM"); while (readl(&ohci->regs->control) & OHCI_CTRL_IR) { mdelay(10); if (--smm_timeout == 0) { err("USB HC TakeOver failed!"); return -1; } } } /* Disable HC interrupts */ writel(OHCI_INTR_MIE, &ohci->regs->intrdisable); dbg("USB HC reset_hc usb-%s: ctrl = 0x%X ;", ohci->slot_name, readl(&ohci->regs->control)); /* Reset USB (needed by some controllers) */ writel(0, &ohci->regs->control); /* HC Reset requires max 10 us delay */ writel(OHCI_HCR, &ohci->regs->cmdstatus); while ((readl(&ohci->regs->cmdstatus) & OHCI_HCR) != 0) { if (--timeout == 0) { err("USB HC reset timed out!"); return -1; } udelay(1); } return 0; } /*-------------------------------------------------------------------------*/ /* Start an OHCI controller, set the BUS operational * enable interrupts * connect the virtual root hub */ static int hc_start(struct ohci *ohci) { __u32 mask; unsigned int fminterval; ohci->disabled = 1; /* Tell the controller where the control and bulk lists are * The lists are empty now. */ writel(0, &ohci->regs->ed_controlhead); writel(0, &ohci->regs->ed_bulkhead); /* a reset clears this */ writel((__u32) ohci->hcca, &ohci->regs->hcca); fminterval = 0x2edf; writel((fminterval * 9) / 10, &ohci->regs->periodicstart); fminterval |= ((((fminterval - 210) * 6) / 7) << 16); writel(fminterval, &ohci->regs->fminterval); writel(0x628, &ohci->regs->lsthresh); /* start controller operations */ ohci->hc_control = OHCI_CONTROL_INIT | OHCI_USB_OPER; ohci->disabled = 0; writel(ohci->hc_control, &ohci->regs->control); /* disable all interrupts */ mask = (OHCI_INTR_SO | OHCI_INTR_WDH | OHCI_INTR_SF | OHCI_INTR_RD | OHCI_INTR_UE | OHCI_INTR_FNO | OHCI_INTR_RHSC | OHCI_INTR_OC | OHCI_INTR_MIE); writel(mask, &ohci->regs->intrdisable); /* clear all interrupts */ mask &= ~OHCI_INTR_MIE; writel(mask, &ohci->regs->intrstatus); /* Choose the interrupts we care about now - but w/o MIE */ mask = OHCI_INTR_RHSC | OHCI_INTR_UE | OHCI_INTR_WDH | OHCI_INTR_SO; writel(mask, &ohci->regs->intrenable); #ifdef OHCI_USE_NPS /* required for AMD-756 and some Mac platforms */ writel((roothub_a(ohci) | RH_A_NPS) & ~RH_A_PSM, &ohci->regs->roothub.a); writel(RH_HS_LPSC, &ohci->regs->roothub.status); #endif /* OHCI_USE_NPS */ /* POTPGT delay is bits 24-31, in 2 ms units. */ mdelay((roothub_a(ohci) >> 23) & 0x1fe); /* connect the virtual root hub */ ohci->rh.devnum = 0; return 0; } /*-------------------------------------------------------------------------*/ /* an interrupt happens */ static int hc_interrupt(void) { struct ohci *ohci = &gohci; struct ohci_regs *regs = ohci->regs; int ints; int stat = -1; if ((ohci->hcca->done_head != 0) && !(m32_swap(ohci->hcca->done_head) & 0x01)) { ints = OHCI_INTR_WDH; } else { ints = readl(&regs->intrstatus); if (ints == ~(u32) 0) { ohci->disabled++; err("%s device removed!", ohci->slot_name); return -1; } ints &= readl(&regs->intrenable); if (ints == 0) { dbg("hc_interrupt: returning..\n"); return 0xff; } } /* dbg("Interrupt: %x frame: %x", ints, le16_to_cpu(ohci->hcca->frame_no)); */ if (ints & OHCI_INTR_RHSC) { got_rhsc = 1; stat = 0xff; } if (ints & OHCI_INTR_UE) { ohci->disabled++; err("OHCI Unrecoverable Error, controller usb-%s disabled", ohci->slot_name); /* e.g. due to PCI Master/Target Abort */ #ifdef DEBUG ohci_dump(ohci, 1); #else mdelay(1); #endif /* FIXME: be optimistic, hope that bug won't repeat often. */ /* Make some non-interrupt context restart the controller. */ /* Count and limit the retries though; either hardware or */ /* software errors can go forever... */ hc_reset(ohci); return -1; } if (ints & OHCI_INTR_WDH) { mdelay(1); writel(OHCI_INTR_WDH, &regs->intrdisable); stat = dl_done_list(&gohci, dl_reverse_done_list(&gohci)); writel(OHCI_INTR_WDH, &regs->intrenable); } if (ints & OHCI_INTR_SO) { dbg("USB Schedule overrun\n"); writel(OHCI_INTR_SO, &regs->intrenable); stat = -1; } /* FIXME: this assumes SOF (1/ms) interrupts don't get lost... */ if (ints & OHCI_INTR_SF) { unsigned int frame = m16_swap(ohci->hcca->frame_no) & 1; mdelay(1); writel(OHCI_INTR_SF, &regs->intrdisable); if (ohci->ed_rm_list[frame] != NULL) writel(OHCI_INTR_SF, &regs->intrenable); stat = 0xff; } writel(ints, &regs->intrstatus); return stat; } /*-------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------*/ /* De-allocate all resources.. */ static void hc_release_ohci(struct ohci *ohci) { dbg("USB HC release ohci usb-%s", ohci->slot_name); if (!ohci->disabled) hc_reset(ohci); } /*-------------------------------------------------------------------------*/ /* * low level initalisation routine, called from usb.c */ static char ohci_inited = 0; int usb_lowlevel_init(int index, void **controller) { struct s3c24x0_clock_power *clk_power = s3c24x0_get_base_clock_power(); struct s3c24x0_gpio *gpio = s3c24x0_get_base_gpio(); /* * Set the 48 MHz UPLL clocking. Values are taken from * "PLL value selection guide", 6-23, s3c2400_UM.pdf. */ clk_power->upllcon = ((40 << 12) + (1 << 4) + 2); gpio->misccr |= 0x8; /* 1 = use pads related USB for USB host */ /* * Enable USB host clock. */ clk_power->clkcon |= (1 << 4); memset(&gohci, 0, sizeof(struct ohci)); memset(&urb_priv, 0, sizeof(struct urb_priv)); /* align the storage */ if ((__u32) &ghcca[0] & 0xff) { err("HCCA not aligned!!"); return -1; } phcca = &ghcca[0]; info("aligned ghcca %p", phcca); memset(&ohci_dev, 0, sizeof(struct ohci_device)); if ((__u32) &ohci_dev.ed[0] & 0x7) { err("EDs not aligned!!"); return -1; } memset(gtd, 0, sizeof(struct td) * (NUM_TD + 1)); if ((__u32) gtd & 0x7) { err("TDs not aligned!!"); return -1; } ptd = gtd; gohci.hcca = phcca; memset(phcca, 0, sizeof(struct ohci_hcca)); gohci.disabled = 1; gohci.sleeping = 0; gohci.irq = -1; gohci.regs = (struct ohci_regs *)S3C24X0_USB_HOST_BASE; gohci.flags = 0; gohci.slot_name = "s3c2400"; if (hc_reset(&gohci) < 0) { hc_release_ohci(&gohci); /* Initialization failed */ clk_power->clkcon &= ~(1 << 4); return -1; } /* FIXME this is a second HC reset; why?? */ gohci.hc_control = OHCI_USB_RESET; writel(gohci.hc_control, &gohci.regs->control); mdelay(10); if (hc_start(&gohci) < 0) { err("can't start usb-%s", gohci.slot_name); hc_release_ohci(&gohci); /* Initialization failed */ clk_power->clkcon &= ~(1 << 4); return -1; } #ifdef DEBUG ohci_dump(&gohci, 1); #else mdelay(1); #endif ohci_inited = 1; urb_finished = 1; return 0; } int usb_lowlevel_stop(int index) { struct s3c24x0_clock_power *clk_power = s3c24x0_get_base_clock_power(); /* this gets called really early - before the controller has */ /* even been initialized! */ if (!ohci_inited) return 0; /* TODO release any interrupts, etc. */ /* call hc_release_ohci() here ? */ hc_reset(&gohci); /* may not want to do this */ clk_power->clkcon &= ~(1 << 4); return 0; } #endif /* defined(CONFIG_USB_OHCI) && defined(CONFIG_S3C24X0) */ #if defined(CONFIG_USB_OHCI_NEW) && \ defined(CONFIG_SYS_USB_OHCI_CPU_INIT) && \ defined(CONFIG_S3C24X0) int usb_cpu_init(void) { struct s3c24x0_clock_power *clk_power = s3c24x0_get_base_clock_power(); struct s3c24x0_gpio *gpio = s3c24x0_get_base_gpio(); /* * Set the 48 MHz UPLL clocking. Values are taken from * "PLL value selection guide", 6-23, s3c2400_UM.pdf. */ writel((40 << 12) + (1 << 4) + 2, &clk_power->upllcon); /* 1 = use pads related USB for USB host */ writel(readl(&gpio->misccr) | 0x8, &gpio->misccr); /* * Enable USB host clock. */ writel(readl(&clk_power->clkcon) | (1 << 4), &clk_power->clkcon); return 0; } int usb_cpu_stop(void) { struct s3c24x0_clock_power *clk_power = s3c24x0_get_base_clock_power(); /* may not want to do this */ writel(readl(&clk_power->clkcon) & ~(1 << 4), &clk_power->clkcon); return 0; } int usb_cpu_init_fail(void) { struct s3c24x0_clock_power *clk_power = s3c24x0_get_base_clock_power(); writel(readl(&clk_power->clkcon) & ~(1 << 4), &clk_power->clkcon); return 0; } #endif /* defined(CONFIG_USB_OHCI_NEW) && \ defined(CONFIG_SYS_USB_OHCI_CPU_INIT) && \ defined(CONFIG_S3C24X0) */
gpl-3.0
stahta01/codeblocks_PCH_fixes
src/plugins/contrib/source_exporter/wxPdfDocument/samples/minimal/tutorial4.cpp
11
3896
/////////////////////////////////////////////////////////////////////////////// // Name: tutorial4.cpp // Purpose: Tutorial 4: Test program for wxPdfDocument // Author: Ulrich Telle // Modified by: // Created: 2005-08-29 // Copyright: (c) Ulrich Telle // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <wx/wfstream.h> #include "wx/pdfdoc.h" /** * Multi-columns * * This example is a variant of the previous one showing how to lay the text * across multiple columns. * * The key method used is AcceptPageBreak(). It allows to accept or not an * automatic page break. By refusing it and altering the margin and current * position, the desired column layout is achieved. * For the rest, not much change; two properties have been added to the class * to save the current column number and the position where columns begin, and * the MultiCell() call specifies a 6 centimeter width. */ class PdfTuto4 : public wxPdfDocument { public: PdfTuto4() { m_col = 0; } void SetMyTitle(const wxString& title) { m_myTitle = title; SetTitle(title); } void Header() { // Page header SetFont(wxT("Helvetica"),wxT("B"),15); double w = GetStringWidth(m_myTitle)+6; SetX((210-w)/2); SetDrawColour(wxColour(0,80,180)); SetFillColour(wxColour(230,230,0)); SetTextColour(wxColour(220,50,50)); SetLineWidth(1); Cell(w,9,m_myTitle,wxPDF_BORDER_FRAME,1,wxPDF_ALIGN_CENTER,1); Ln(10); // Save ordinate m_y0 = GetY(); } void Footer() { // Page footer SetY(-15); SetFont(wxT("Helvetica"),wxT("I"),8); SetTextColour(128); Cell(0,10,wxString::Format(wxT("Page %d"),PageNo()),0,0,wxPDF_ALIGN_CENTER); } void SetCol(int col) { // Set position at a given column m_col = col; double x = 10 + col * 65; SetLeftMargin(x); SetX(x); } bool AcceptPageBreak() { // Method accepting or not automatic page break if (m_col < 2) { // Go to next column SetCol(m_col+1); // Set ordinate to top SetY(m_y0); // Keep on page return false; } else { // Go back to first column SetCol(0); // Page break return true; } } void ChapterTitle(int num, const wxString& label) { // Title SetFont(wxT("Helvetica"),wxT(""),12); SetFillColour(wxColour(200,220,255)); Cell(0,6,wxString::Format(wxT("Chapter %d : "),num)+label,0,1,wxPDF_ALIGN_LEFT,1); Ln(4); // Save ordinate m_y0 = GetY(); } void ChapterBody(const wxString& file) { // Read text file wxFileInputStream f(file); int len = f.GetLength(); char* ctxt = new char[len+1]; f.Read(ctxt,len); ctxt[len] = '\0'; wxString txt(ctxt,*wxConvCurrent); // Font SetFont(wxT("Times"),wxT(""),12); // Output text in a 6 cm width column MultiCell(60,5,txt); Ln(); // Mention SetFont(wxT(""),wxT("I")); Cell(0,5,wxT("(end of excerpt)")); // Go back to first column SetCol(0); delete [] ctxt; } void PrintChapter(int num, const wxString& title, const wxString& file) { // Add chapter AddPage(); ChapterTitle(num,title); ChapterBody(file); } private: // Current column int m_col; // Ordinate of column start double m_y0; wxString m_myTitle; }; void tutorial4() { PdfTuto4 pdf; pdf.SetMyTitle(wxT("20000 Leagues Under the Seas")); pdf.SetAuthor(wxT("Jules Verne")); pdf.PrintChapter(1,wxT("A RUNAWAY REEF"),wxT("20k_c1.txt")); pdf.PrintChapter(2,wxT("THE PROS AND CONS"),wxT("20k_c2.txt")); pdf.SaveAsFile(wxT("tutorial4.pdf")); }
gpl-3.0
shadowofreality/ShadowCore
src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp
12
10551
/* * Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Silverpine_Forest SD%Complete: 100 SDComment: Quest support: 435, 452 SDCategory: Silverpine Forest EndScriptData */ /* ContentData npc_deathstalker_erland pyrewood_ambush EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedEscortAI.h" #include "Player.h" /*###### ## npc_deathstalker_erland ######*/ enum Erland { SAY_QUESTACCEPT = 0, SAY_START = 1, SAY_AGGRO = 2, SAY_PROGRESS = 3, SAY_LAST = 4, SAY_RANE = 0, SAY_RANE_ANSWER = 5, SAY_MOVE_QUINN = 6, SAY_QUINN = 7, SAY_QUINN_ANSWER = 0, SAY_BYE = 8, QUEST_ESCORTING = 435, NPC_RANE = 1950, NPC_QUINN = 1951 }; class npc_deathstalker_erland : public CreatureScript { public: npc_deathstalker_erland() : CreatureScript("npc_deathstalker_erland") { } struct npc_deathstalker_erlandAI : public npc_escortAI { npc_deathstalker_erlandAI(Creature* creature) : npc_escortAI(creature) { } void WaypointReached(uint32 waypointId) override { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 1: Talk(SAY_START, player); break; case 10: Talk(SAY_PROGRESS); break; case 13: Talk(SAY_LAST, player); player->GroupEventHappens(QUEST_ESCORTING, me); break; case 15: if (Creature* rane = me->FindNearestCreature(NPC_RANE, 20.0f)) rane->AI()->Talk(SAY_RANE); break; case 16: Talk(SAY_RANE_ANSWER); break; case 17: Talk(SAY_MOVE_QUINN); break; case 24: Talk(SAY_QUINN); break; case 25: if (Creature* quinn = me->FindNearestCreature(NPC_QUINN, 20.0f)) quinn->AI()->Talk(SAY_QUINN_ANSWER); break; case 26: Talk(SAY_BYE); break; } } void Reset() override { } void EnterCombat(Unit* who) override { Talk(SAY_AGGRO, who); } }; bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override { if (quest->GetQuestId() == QUEST_ESCORTING) { creature->AI()->Talk(SAY_QUESTACCEPT, player); if (npc_escortAI* pEscortAI = CAST_AI(npc_deathstalker_erland::npc_deathstalker_erlandAI, creature->AI())) pEscortAI->Start(true, false, player->GetGUID()); } return true; } CreatureAI* GetAI(Creature* creature) const override { return new npc_deathstalker_erlandAI(creature); } }; /*###### ## pyrewood_ambush #######*/ enum PyrewoodAmbush { SAY_PREPARE_TO_AMBUSH = 0, SAY_A_BLOW_TO_ARUGAL = 1, FACTION_ENEMY = 168, QUEST_PYREWOOD_AMBUSH = 452, COUNCILMAN_SMITHERS = 2060, COUNCILMAN_THATCHER = 2061, COUNCILMAN_HENDRICKS = 2062, COUNCILMAN_WILHELM = 2063, COUNCILMAN_HARTIN = 2064, COUNCILMAN_COOPER = 2065, COUNCILMAN_HIGARTH = 2066, COUNCILMAN_BRUNSWICK = 2067, LORD_MAYOR_MORRISON = 2068 }; static float PyrewoodSpawnPoints[3][4] = { //pos_x pos_y pos_z orien //outside /* {-400.85f, 1513.64f, 18.67f, 0}, {-397.32f, 1514.12f, 18.67f, 0}, {-397.44f, 1511.09f, 18.67f, 0}, */ //door {-396.17f, 1505.86f, 19.77f, 0}, {-396.91f, 1505.77f, 19.77f, 0}, {-397.94f, 1504.74f, 19.77f, 0}, }; class pyrewood_ambush : public CreatureScript { public: pyrewood_ambush() : CreatureScript("pyrewood_ambush") { } bool OnQuestAccept(Player* player, Creature* creature, const Quest *quest) override { if (quest->GetQuestId() == QUEST_PYREWOOD_AMBUSH && !ENSURE_AI(pyrewood_ambush::pyrewood_ambushAI, creature->AI())->QuestInProgress) { ENSURE_AI(pyrewood_ambush::pyrewood_ambushAI, creature->AI())->QuestInProgress = true; ENSURE_AI(pyrewood_ambush::pyrewood_ambushAI, creature->AI())->Phase = 0; ENSURE_AI(pyrewood_ambush::pyrewood_ambushAI, creature->AI())->KillCount = 0; ENSURE_AI(pyrewood_ambush::pyrewood_ambushAI, creature->AI())->PlayerGUID = player->GetGUID(); } return true; } CreatureAI* GetAI(Creature* creature) const override { return new pyrewood_ambushAI(creature); } struct pyrewood_ambushAI : public ScriptedAI { pyrewood_ambushAI(Creature* creature) : ScriptedAI(creature), Summons(me) { Initialize(); WaitTimer = 6 * IN_MILLISECONDS; QuestInProgress = false; } void Initialize() { Phase = 0; KillCount = 0; PlayerGUID.Clear(); } uint32 Phase; int8 KillCount; uint32 WaitTimer; ObjectGuid PlayerGUID; SummonList Summons; bool QuestInProgress; void Reset() override { WaitTimer = 6 * IN_MILLISECONDS; if (!QuestInProgress) //fix reset values (see UpdateVictim) { Initialize(); Summons.DespawnAll(); } } void EnterCombat(Unit* /*who*/) override { } void JustSummoned(Creature* summoned) override { Summons.Summon(summoned); ++KillCount; } void SummonedCreatureDespawn(Creature* summoned) override { Summons.Despawn(summoned); --KillCount; } void SummonCreatureWithRandomTarget(uint32 creatureId, int position) { if (Creature* summoned = me->SummonCreature(creatureId, PyrewoodSpawnPoints[position][0], PyrewoodSpawnPoints[position][1], PyrewoodSpawnPoints[position][2], PyrewoodSpawnPoints[position][3], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000)) { Unit* target = NULL; if (PlayerGUID) if (Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID)) if (player->IsAlive() && RAND(0, 1)) target = player; if (!target) target = me; summoned->setFaction(FACTION_ENEMY); summoned->AddThreat(target, 32.0f); summoned->AI()->AttackStart(target); } } void JustDied(Unit* /*killer*/) override { if (PlayerGUID) if (Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID)) if (player->GetQuestStatus(QUEST_PYREWOOD_AMBUSH) == QUEST_STATUS_INCOMPLETE) player->FailQuest(QUEST_PYREWOOD_AMBUSH); } void UpdateAI(uint32 diff) override { //TC_LOG_INFO("scripts", "DEBUG: p(%i) k(%i) d(%u) W(%i)", Phase, KillCount, diff, WaitTimer); if (!QuestInProgress) return; if (KillCount && Phase < 6) { if (!UpdateVictim()) //reset() on target Despawn... return; DoMeleeAttackIfReady(); return; } switch (Phase) { case 0: if (WaitTimer == 6 * IN_MILLISECONDS) if (Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID)) Talk(SAY_PREPARE_TO_AMBUSH, player); if (WaitTimer <= diff) { WaitTimer -= diff; return; } break; case 1: SummonCreatureWithRandomTarget(COUNCILMAN_SMITHERS, 1); break; case 2: SummonCreatureWithRandomTarget(COUNCILMAN_THATCHER, 2); SummonCreatureWithRandomTarget(COUNCILMAN_HENDRICKS, 0); break; case 3: SummonCreatureWithRandomTarget(COUNCILMAN_WILHELM, 1); SummonCreatureWithRandomTarget(COUNCILMAN_HARTIN, 2); SummonCreatureWithRandomTarget(COUNCILMAN_COOPER, 0); break; case 4: SummonCreatureWithRandomTarget(COUNCILMAN_HIGARTH, 1); SummonCreatureWithRandomTarget(COUNCILMAN_BRUNSWICK, 0); SummonCreatureWithRandomTarget(LORD_MAYOR_MORRISON, 2); break; case 5: //end if (PlayerGUID) { if (Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID)) { Talk(SAY_A_BLOW_TO_ARUGAL); player->GroupEventHappens(QUEST_PYREWOOD_AMBUSH, me); } } QuestInProgress = false; Reset(); break; } ++Phase; //prepare next phase } }; }; /*###### ## AddSC ######*/ void AddSC_silverpine_forest() { new npc_deathstalker_erland(); new pyrewood_ambush(); }
gpl-3.0
elektroll/etaimp
app/plug-in/plug-in-enums.c
13
2572
/* Generated data (by gimp-mkenums) */ #include "config.h" #include <glib-object.h> #include "libgimpbase/gimpbase.h" #include "plug-in-enums.h" #include "gimp-intl.h" /* enumerations from "./plug-in-enums.h" */ GType gimp_plug_in_image_type_get_type (void) { static const GFlagsValue values[] = { { GIMP_PLUG_IN_RGB_IMAGE, "GIMP_PLUG_IN_RGB_IMAGE", "rgb-image" }, { GIMP_PLUG_IN_GRAY_IMAGE, "GIMP_PLUG_IN_GRAY_IMAGE", "gray-image" }, { GIMP_PLUG_IN_INDEXED_IMAGE, "GIMP_PLUG_IN_INDEXED_IMAGE", "indexed-image" }, { GIMP_PLUG_IN_RGBA_IMAGE, "GIMP_PLUG_IN_RGBA_IMAGE", "rgba-image" }, { GIMP_PLUG_IN_GRAYA_IMAGE, "GIMP_PLUG_IN_GRAYA_IMAGE", "graya-image" }, { GIMP_PLUG_IN_INDEXEDA_IMAGE, "GIMP_PLUG_IN_INDEXEDA_IMAGE", "indexeda-image" }, { 0, NULL, NULL } }; static const GimpFlagsDesc descs[] = { { GIMP_PLUG_IN_RGB_IMAGE, "GIMP_PLUG_IN_RGB_IMAGE", NULL }, { GIMP_PLUG_IN_GRAY_IMAGE, "GIMP_PLUG_IN_GRAY_IMAGE", NULL }, { GIMP_PLUG_IN_INDEXED_IMAGE, "GIMP_PLUG_IN_INDEXED_IMAGE", NULL }, { GIMP_PLUG_IN_RGBA_IMAGE, "GIMP_PLUG_IN_RGBA_IMAGE", NULL }, { GIMP_PLUG_IN_GRAYA_IMAGE, "GIMP_PLUG_IN_GRAYA_IMAGE", NULL }, { GIMP_PLUG_IN_INDEXEDA_IMAGE, "GIMP_PLUG_IN_INDEXEDA_IMAGE", NULL }, { 0, NULL, NULL } }; static GType type = 0; if (G_UNLIKELY (! type)) { type = g_flags_register_static ("GimpPlugInImageType", values); gimp_type_set_translation_context (type, "plug-in-image-type"); gimp_flags_set_value_descriptions (type, descs); } return type; } GType gimp_plug_in_call_mode_get_type (void) { static const GEnumValue values[] = { { GIMP_PLUG_IN_CALL_NONE, "GIMP_PLUG_IN_CALL_NONE", "none" }, { GIMP_PLUG_IN_CALL_RUN, "GIMP_PLUG_IN_CALL_RUN", "run" }, { GIMP_PLUG_IN_CALL_QUERY, "GIMP_PLUG_IN_CALL_QUERY", "query" }, { GIMP_PLUG_IN_CALL_INIT, "GIMP_PLUG_IN_CALL_INIT", "init" }, { 0, NULL, NULL } }; static const GimpEnumDesc descs[] = { { GIMP_PLUG_IN_CALL_NONE, "GIMP_PLUG_IN_CALL_NONE", NULL }, { GIMP_PLUG_IN_CALL_RUN, "GIMP_PLUG_IN_CALL_RUN", NULL }, { GIMP_PLUG_IN_CALL_QUERY, "GIMP_PLUG_IN_CALL_QUERY", NULL }, { GIMP_PLUG_IN_CALL_INIT, "GIMP_PLUG_IN_CALL_INIT", NULL }, { 0, NULL, NULL } }; static GType type = 0; if (G_UNLIKELY (! type)) { type = g_enum_register_static ("GimpPlugInCallMode", values); gimp_type_set_translation_context (type, "plug-in-call-mode"); gimp_enum_set_value_descriptions (type, descs); } return type; } /* Generated data ends here */
gpl-3.0
waninkoko/dip-plugin
swi_mload.c
14
1460
/* * DIP plugin for Custom IOS. * * Copyright (C) 2008-2010 Waninkoko, WiiGator. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tools.h" #include "types.h" void Swi_Memcpy(void *dst, void *src, s32 len) { /* Wrong length */ if (len <= 0) return; /* Call function */ Swi_MLoad(2, (u32)dst, (u32)src, (u32)len); } void Swi_uMemcpy(void *dst, void *src, s32 len) { /* Wrong length */ if (len <= 0) return; /* Call function */ Swi_MLoad(9, (u32)dst, (u32)src, (u32)len); } s32 Swi_CallFunc(s32 (*func)(void *in, void *out), void *in, void *out) { /* Call function */ return Swi_MLoad(16, (u32)func, (u32)in, (u32)out); } u32 Swi_GetSyscallBase(void) { return Swi_MLoad(17, 0, 0, 0); } u32 Swi_GetIosInfo(void *buffer) { return Swi_MLoad(18, (u32)buffer, 0, 0); }
gpl-3.0
estei-master/segment_SOL
PJ/uboot_kernel/u-boot-sunxi/board/rpxsuper/rpxsuper.c
14
12604
/* * (C) Copyright 2000 * Sysgo Real-Time Solutions, GmbH <www.elinos.com> * Marius Groeger <mgroeger@sysgo.de> * * (C) Copyright 2001 * Advent Networks, Inc. <http://www.adventnetworks.com> * Jay Monkman <jtm@smoothsmoothie.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <ioports.h> #include <mpc8260.h> #include "rpxsuper.h" /* * I/O Port configuration table * * if conf is 1, then that port pin will be configured at boot time * according to the five values podr/pdir/ppar/psor/pdat for that entry */ const iop_conf_t iop_conf_tab[4][32] = { /* Port A configuration */ { /* conf ppar psor pdir podr pdat */ /* PA31 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 *ATMTXEN */ /* PA30 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTCA */ /* PA29 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTSOC */ /* PA28 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 *ATMRXEN */ /* PA27 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRSOC */ /* PA26 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRCA */ /* PA25 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[0] */ /* PA24 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[1] */ /* PA23 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[2] */ /* PA22 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[3] */ /* PA21 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[4] */ /* PA20 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[5] */ /* PA19 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[6] */ /* PA18 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXD[7] */ /* PA17 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[7] */ /* PA16 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[6] */ /* PA15 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[5] */ /* PA14 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[4] */ /* PA13 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[3] */ /* PA12 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[2] */ /* PA11 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[1] */ /* PA10 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXD[0] */ /* PA9 */ { 1, 1, 0, 1, 0, 0 }, /* SMC2 TXD */ /* PA8 */ { 1, 1, 0, 0, 0, 0 }, /* SMC2 RXD */ /* PA7 */ { 1, 0, 0, 0, 0, 0 }, /* PA7 */ /* PA6 */ { 1, 0, 0, 0, 0, 0 }, /* PA6 */ /* PA5 */ { 1, 0, 0, 0, 0, 0 }, /* PA5 */ /* PA4 */ { 1, 0, 0, 0, 0, 0 }, /* PA4 */ /* PA3 */ { 1, 0, 0, 0, 0, 0 }, /* PA3 */ /* PA2 */ { 1, 0, 0, 0, 0, 0 }, /* PA2 */ /* PA1 */ { 1, 0, 0, 0, 0, 0 }, /* PA1 */ /* PA0 */ { 1, 0, 0, 0, 0, 0 } /* PA0 */ }, /* Port B configuration */ { /* conf ppar psor pdir podr pdat */ /* PB31 */ { 1, 1, 0, 1, 0, 0 }, /* FCC2 MII TX_ER */ /* PB30 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RX_DV */ /* PB29 */ { 1, 1, 1, 1, 0, 0 }, /* FCC2 MII TX_EN */ /* PB28 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RX_ER */ /* PB27 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII COL */ /* PB26 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII CRS */ /* PB25 */ { 1, 1, 0, 1, 0, 0 }, /* FCC2 MII TxD[3] */ /* PB24 */ { 1, 1, 0, 1, 0, 0 }, /* FCC2 MII TxD[2] */ /* PB23 */ { 1, 1, 0, 1, 0, 0 }, /* FCC2 MII TxD[1] */ /* PB22 */ { 1, 1, 0, 1, 0, 0 }, /* FCC2 MII TxD[0] */ /* PB21 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RxD[0] */ /* PB20 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RxD[1] */ /* PB19 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RxD[2] */ /* PB18 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RxD[3] */ /* PB17 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RX_DV */ /* PB16 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RX_ER */ /* PB15 */ { 1, 1, 0, 1, 0, 0 }, /* FCC3 MII TX_ER */ /* PB14 */ { 1, 1, 0, 1, 0, 0 }, /* FCC3 MII TX_EN */ /* PB13 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII COL */ /* PB12 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII CRS */ /* PB11 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RxD[3] */ /* PB10 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RxD[2] */ /* PB9 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RxD[1] */ /* PB8 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RxD[0] */ /* PB7 */ { 0, 0, 0, 0, 0, 0 }, /* PB7 */ /* PB6 */ { 1, 1, 0, 1, 0, 0 }, /* FCC3 MII TxD[1] */ /* PB5 */ { 1, 1, 0, 1, 0, 0 }, /* FCC3 MII TxD[2] */ /* PB4 */ { 1, 1, 0, 1, 0, 0 }, /* FCC3 MII TxD[3] */ /* PB3 */ { 0, 0, 0, 0, 0, 0 }, /* pin doesn't exist */ /* PB2 */ { 0, 0, 0, 0, 0, 0 }, /* pin doesn't exist */ /* PB1 */ { 0, 0, 0, 0, 0, 0 }, /* pin doesn't exist */ /* PB0 */ { 0, 0, 0, 0, 0, 0 } /* pin doesn't exist */ }, /* Port C */ { /* conf ppar psor pdir podr pdat */ /* PC31 */ { 1, 0, 0, 1, 0, 0 }, /* PC31 */ /* PC30 */ { 1, 0, 0, 1, 0, 0 }, /* PC30 */ /* PC29 */ { 1, 1, 1, 0, 0, 0 }, /* SCC1 EN *CLSN */ /* PC28 */ { 1, 0, 0, 1, 0, 0 }, /* PC28 */ /* PC27 */ { 1, 1, 0, 1, 0, 0 }, /* FCC3 MII TxD[0] */ /* PC26 */ { 1, 0, 0, 1, 0, 0 }, /* PC26 */ /* PC25 */ { 1, 0, 0, 1, 0, 0 }, /* PC25 */ /* PC24 */ { 1, 0, 0, 1, 0, 0 }, /* PC24 */ /* PC23 */ { 1, 1, 0, 1, 0, 0 }, /* ATMTFCLK */ /* PC22 */ { 1, 1, 0, 0, 0, 0 }, /* ATMRFCLK */ /* PC21 */ { 1, 1, 0, 0, 0, 0 }, /* SCC1 EN RXCLK */ /* PC20 */ { 1, 1, 0, 0, 0, 0 }, /* SCC1 EN TXCLK */ /* PC19 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII RX_CLK */ /* PC18 */ { 1, 1, 0, 0, 0, 0 }, /* FCC2 MII TX_CLK */ /* PC17 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII RX_CLK */ /* PC16 */ { 1, 1, 0, 0, 0, 0 }, /* FCC3 MII TX_CLK */ /* PC15 */ { 1, 0, 0, 0, 0, 0 }, /* PC15 */ /* PC14 */ { 1, 1, 0, 0, 0, 0 }, /* SCC1 EN *CD */ /* PC13 */ { 1, 0, 0, 1, 0, 0 }, /* PC13 */ /* PC12 */ { 1, 0, 0, 1, 0, 0 }, /* PC12 */ /* PC11 */ { 1, 0, 0, 1, 0, 0 }, /* PC11 */ /* PC10 */ { 1, 0, 0, 1, 0, 0 }, /* FCC2 MDC */ /* PC9 */ { 1, 0, 0, 1, 0, 0 }, /* FCC2 MDIO */ /* PC8 */ { 1, 0, 0, 1, 0, 0 }, /* PC8 */ /* PC7 */ { 1, 0, 0, 1, 0, 0 }, /* PC7 */ /* PC6 */ { 1, 0, 0, 1, 0, 0 }, /* PC6 */ /* PC5 */ { 1, 0, 0, 1, 0, 0 }, /* PC5 */ /* PC4 */ { 1, 0, 0, 1, 0, 0 }, /* PC4 */ /* PC3 */ { 1, 0, 0, 1, 0, 0 }, /* PC3 */ /* PC2 */ { 1, 0, 0, 1, 0, 1 }, /* ENET FDE */ /* PC1 */ { 1, 0, 0, 1, 0, 0 }, /* ENET DSQE */ /* PC0 */ { 1, 0, 0, 1, 0, 0 }, /* ENET LBK */ }, /* Port D */ { /* conf ppar psor pdir podr pdat */ /* PD31 */ { 1, 0, 0, 0, 0, 0 }, /* SCC1 EN RxD */ /* PD30 */ { 1, 0, 0, 0, 0, 0 }, /* SCC1 EN TxD */ /* PD29 */ { 1, 0, 0, 0, 0, 0 }, /* SCC1 EN TENA */ /* PD28 */ { 1, 0, 0, 0, 0, 0 }, /* PD28 */ /* PD27 */ { 1, 0, 0, 0, 0, 0 }, /* PD27 */ /* PD26 */ { 1, 0, 0, 0, 0, 0 }, /* PD26 */ /* PD25 */ { 1, 0, 0, 0, 0, 0 }, /* PD25 */ /* PD24 */ { 1, 0, 0, 0, 0, 0 }, /* PD24 */ /* PD23 */ { 1, 0, 0, 0, 0, 0 }, /* PD23 */ /* PD22 */ { 1, 0, 0, 0, 0, 0 }, /* PD22 */ /* PD21 */ { 1, 0, 0, 0, 0, 0 }, /* PD21 */ /* PD20 */ { 1, 0, 0, 0, 0, 0 }, /* PD20 */ /* PD19 */ { 1, 0, 0, 0, 0, 0 }, /* PD19 */ /* PD18 */ { 1, 0, 0, 0, 0, 0 }, /* PD19 */ /* PD17 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMRXPRTY */ /* PD16 */ { 1, 0, 0, 0, 0, 0 }, /* FCC1 ATMTXPRTY */ /* PD15 */ { 1, 1, 1, 0, 1, 0 }, /* I2C SDA */ /* PD14 */ { 1, 1, 1, 0, 1, 0 }, /* I2C SCL */ /* PD13 */ { 1, 0, 0, 0, 0, 0 }, /* PD13 */ /* PD12 */ { 1, 0, 0, 0, 0, 0 }, /* PD12 */ /* PD11 */ { 1, 0, 0, 0, 0, 0 }, /* PD11 */ /* PD10 */ { 1, 0, 0, 0, 0, 0 }, /* PD10 */ /* PD9 */ { 1, 1, 0, 1, 0, 0 }, /* SMC1 TXD */ /* PD8 */ { 1, 1, 0, 0, 0, 0 }, /* SMC1 RXD */ /* PD7 */ { 1, 0, 0, 0, 0, 0 }, /* PD7 */ /* PD6 */ { 1, 0, 0, 0, 0, 0 }, /* PD6 */ /* PD5 */ { 1, 0, 0, 0, 0, 0 }, /* PD5 */ /* PD4 */ { 1, 0, 0, 0, 0, 0 }, /* PD4 */ /* PD3 */ { 0, 0, 0, 0, 0, 0 }, /* pin doesn't exist */ /* PD2 */ { 0, 0, 0, 0, 0, 0 }, /* pin doesn't exist */ /* PD1 */ { 0, 0, 0, 0, 0, 0 }, /* pin doesn't exist */ /* PD0 */ { 0, 0, 0, 0, 0, 0 } /* pin doesn't exist */ } }; /* ------------------------------------------------------------------------- */ /* * Setup CS4 to enable the Board Control/Status registers. * Otherwise the smcs won't work. */ int board_early_init_f (void) { volatile t_rpx_regs *regs = (t_rpx_regs*)CONFIG_SYS_REGS_BASE; volatile immap_t *immap = (immap_t *)CONFIG_SYS_IMMR; volatile memctl8260_t *memctl = &immap->im_memctl; memctl->memc_br4 = CONFIG_SYS_BR4_PRELIM; memctl->memc_or4 = CONFIG_SYS_OR4_PRELIM; regs->bcsr1 = 0x70; /* to enable terminal no SMC1 */ regs->bcsr2 = 0x20; /* mut be written to enable writing FLASH */ return 0; } void reset_phy(void) { volatile t_rpx_regs *regs = (t_rpx_regs*)CONFIG_SYS_REGS_BASE; regs->bcsr4 = 0xC3; } /* * Check Board Identity: */ int checkboard(void) { volatile t_rpx_regs *regs = (t_rpx_regs*)CONFIG_SYS_REGS_BASE; printf ("Board: Embedded Planet RPX Super, Revision %d\n", regs->bcsr0 >> 4); return 0; } /* ------------------------------------------------------------------------- */ phys_size_t initdram(int board_type) { volatile immap_t *immap = (immap_t *)CONFIG_SYS_IMMR; volatile memctl8260_t *memctl = &immap->im_memctl; volatile uchar c = 0, *ramaddr; ulong psdmr, lsdmr, bcr; long size = 0; int i; psdmr = CONFIG_SYS_PSDMR; lsdmr = CONFIG_SYS_LSDMR; /* * Quote from 8260 UM (10.4.2 SDRAM Power-On Initialization, 10-35): * * "At system reset, initialization software must set up the * programmable parameters in the memory controller banks registers * (ORx, BRx, P/LSDMR). After all memory parameters are configured, * system software should execute the following initialization sequence * for each SDRAM device. * * 1. Issue a PRECHARGE-ALL-BANKS command * 2. Issue eight CBR REFRESH commands * 3. Issue a MODE-SET command to initialize the mode register * * The initial commands are executed by setting P/LSDMR[OP] and * accessing the SDRAM with a single-byte transaction." * * The appropriate BRx/ORx registers have already been set when we * get here. The SDRAM can be accessed at the address CONFIG_SYS_SDRAM_BASE. */ size = CONFIG_SYS_SDRAM0_SIZE; bcr = immap->im_siu_conf.sc_bcr; immap->im_siu_conf.sc_bcr = (bcr & ~BCR_EBM); memctl->memc_mptpr = CONFIG_SYS_MPTPR; ramaddr = (uchar *)(CONFIG_SYS_SDRAM0_BASE); memctl->memc_psrt = CONFIG_SYS_PSRT; memctl->memc_psdmr = psdmr | PSDMR_OP_PREA; *ramaddr = c; memctl->memc_psdmr = psdmr | PSDMR_OP_CBRR; for (i = 0; i < 8; i++) *ramaddr = c; memctl->memc_psdmr = psdmr | PSDMR_OP_MRW; *ramaddr = c; memctl->memc_psdmr = psdmr | PSDMR_OP_NORM | PSDMR_RFEN; *ramaddr = c; immap->im_siu_conf.sc_bcr = bcr; #ifndef CONFIG_SYS_RAMBOOT /* size += CONFIG_SYS_SDRAM1_SIZE; */ ramaddr = (uchar *)(CONFIG_SYS_SDRAM1_BASE); memctl->memc_lsrt = CONFIG_SYS_LSRT; memctl->memc_lsdmr = lsdmr | PSDMR_OP_PREA; *ramaddr = c; memctl->memc_lsdmr = lsdmr | PSDMR_OP_CBRR; for (i = 0; i < 8; i++) *ramaddr = c; memctl->memc_lsdmr = lsdmr | PSDMR_OP_MRW; *ramaddr = c; memctl->memc_lsdmr = lsdmr | PSDMR_OP_NORM | PSDMR_RFEN; *ramaddr = c; #endif /* return total ram size */ return (size * 1024 * 1024); }
gpl-3.0
youssef-emad/shogun
src/shogun/mathematics/linalg/linop/SparseMatrixOperator.cpp
15
7604
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Soumyajit De */ #include <shogun/lib/config.h> #include <shogun/lib/SGVector.h> #include <shogun/lib/SGSparseMatrix.h> #include <shogun/lib/SGSparseVector.h> #include <shogun/base/Parameter.h> #include <shogun/mathematics/linalg/linop/SparseMatrixOperator.h> #include <shogun/mathematics/eigen3.h> namespace shogun { template<class T> CSparseMatrixOperator<T>::CSparseMatrixOperator() : CMatrixOperator<T>() { init(); } template<class T> CSparseMatrixOperator<T>::CSparseMatrixOperator(SGSparseMatrix<T> op) : CMatrixOperator<T>(op.num_features), m_operator(op) { init(); } template<class T> CSparseMatrixOperator<T>::CSparseMatrixOperator (const CSparseMatrixOperator<T>& orig) : CMatrixOperator<T>(orig.get_dimension()) { init(); typedef SGSparseVector<T> vector; typedef SGSparseVectorEntry<T> entry; m_operator=SGSparseMatrix<T>(orig.m_operator.num_vectors, orig.m_operator.num_features); vector* rows=SG_MALLOC(vector, m_operator.num_features); for (index_t i=0; i<m_operator.num_vectors; ++i) { entry* features=SG_MALLOC(entry, orig.m_operator[i].num_feat_entries); for (index_t j=0; j<orig.m_operator[i].num_feat_entries; ++j) { features[j].feat_index=orig.m_operator[i].features[j].feat_index; features[j].entry=orig.m_operator[i].features[j].entry; } rows[i].features=features; rows[i].num_feat_entries=m_operator[i].num_feat_entries; } m_operator.sparse_matrix=rows; SG_SGCDEBUG("%s deep copy created (%p)\n", this->get_name(), this); } template<class T> void CSparseMatrixOperator<T>::init() { CSGObject::set_generic<T>(); this->m_parameters->add_vector(&m_operator.sparse_matrix, &m_operator.num_vectors, "sparse_matrix", "The sparse matrix of the linear operator."); this->m_parameters->add(&m_operator.num_features, "m_operator.num_features", "Number of features."); } template<class T> CSparseMatrixOperator<T>::~CSparseMatrixOperator() { } template<class T> SGSparseMatrix<T> CSparseMatrixOperator<T>::get_matrix_operator() const { return m_operator; } template<class T> SparsityStructure* CSparseMatrixOperator<T>::get_sparsity_structure( int64_t power) const { REQUIRE(power>0, "matrix-power is non-positive!\n"); // create casted operator in bool for capturing the sparsity CSparseMatrixOperator<bool>* sp_str =static_cast<CSparseMatrixOperator<bool>*>(*this); // eigen3 map for this sparse matrix in which we compute current power Eigen::SparseMatrix<bool> current_power =EigenSparseUtil<bool>::toEigenSparse(sp_str->get_matrix_operator()); // final power of the matrix goes into this one Eigen::SparseMatrix<bool> matrix_power; // compute matrix power with O(log(n)) matrix-multiplication! // traverse the bits of the power and compute the powers of 2 which // makes up this number. in the process multiply these to get the result bool lsb=true; while (power) { // if the current bit is on, it should contribute to the final result if (1 & power) { if (lsb) { // if seeing a 1 for the first time, then this should be the first // power we should consider matrix_power=current_power; lsb=false; } else matrix_power=matrix_power*current_power; } power=power>>1; // save unnecessary matrix-multiplication if (power) current_power=current_power*current_power; } // create the sparsity structure using the final power int32_t* outerIndexPtr=const_cast<int32_t*>(matrix_power.outerIndexPtr()); int32_t* innerIndexPtr=const_cast<int32_t*>(matrix_power.innerIndexPtr()); SG_UNREF(sp_str); return new SparsityStructure(outerIndexPtr, innerIndexPtr, matrix_power.rows()); } template<> \ SparsityStructure* CSparseMatrixOperator<complex128_t> ::get_sparsity_structure(int64_t power) const { SG_SERROR("Not supported for complex128_t\n"); return new SparsityStructure(); } template<class T> SGVector<T> CSparseMatrixOperator<T>::get_diagonal() const { REQUIRE(m_operator.sparse_matrix, "Operator not initialized!\n"); const int32_t diag_size=m_operator.num_vectors>m_operator.num_features ? m_operator.num_features : m_operator.num_vectors; SGVector<T> diag(diag_size); diag.set_const(static_cast<T>(0)); for (index_t i=0; i<diag_size; ++i) { SGSparseVectorEntry<T>* current_row=m_operator[i].features; for (index_t j=0; j<m_operator[i].num_feat_entries; ++j) { if (i==current_row[j].feat_index) { diag[i]=current_row[j].entry; break; } } } return diag; } template<class T> void CSparseMatrixOperator<T>::set_diagonal(SGVector<T> diag) { REQUIRE(m_operator.sparse_matrix, "Operator not initialized!\n"); REQUIRE(diag.vector, "Diagonal not initialized!\n"); const int32_t diag_size=m_operator.num_vectors>m_operator.num_features ? m_operator.num_features : m_operator.num_vectors; REQUIRE(diag_size==diag.vlen, "Dimension mismatch!\n"); bool need_sorting=false; for (index_t i=0; i<diag_size; ++i) { SGSparseVectorEntry<T>* current_row=m_operator[i].features; bool inserted=false; // we just change the entry if the diagonal element for this row exists for (index_t j=0; j<m_operator[i].num_feat_entries; ++j) { if (i==current_row[j].feat_index) { current_row[j].entry=diag[i]; inserted=true; break; } } // we create a new entry if the diagonal element for this row doesn't exist if (!inserted) { index_t j=m_operator[i].num_feat_entries; m_operator[i].num_feat_entries=j+1; m_operator[i].features=SG_REALLOC(SGSparseVectorEntry<T>, m_operator[i].features, j, j+1); m_operator[i].features[j].feat_index=i; m_operator[i].features[j].entry=diag[i]; need_sorting=true; } } if (need_sorting) m_operator.sort_features(); } template<class T> SGVector<T> CSparseMatrixOperator<T>::apply(SGVector<T> b) const { REQUIRE(m_operator.sparse_matrix, "Operator not initialized!\n"); REQUIRE(this->get_dimension()==b.vlen, "Number of rows of vector must be equal to the " "number of cols of the operator!\n"); SGVector<T> result(m_operator.num_vectors); result=m_operator*b; return result; } #define UNDEFINED(type) \ template<> \ SGVector<type> CSparseMatrixOperator<type>::apply(SGVector<type> b) const \ { \ SG_SERROR("Not supported for %s\n", #type);\ return b; \ } UNDEFINED(bool) UNDEFINED(char) UNDEFINED(int8_t) UNDEFINED(uint8_t) UNDEFINED(int16_t) UNDEFINED(uint16_t) UNDEFINED(int32_t) UNDEFINED(uint32_t) UNDEFINED(int64_t) UNDEFINED(uint64_t) UNDEFINED(float32_t) UNDEFINED(floatmax_t) #undef UNDEFINED template class CSparseMatrixOperator<bool>; template class CSparseMatrixOperator<char>; template class CSparseMatrixOperator<int8_t>; template class CSparseMatrixOperator<uint8_t>; template class CSparseMatrixOperator<int16_t>; template class CSparseMatrixOperator<uint16_t>; template class CSparseMatrixOperator<int32_t>; template class CSparseMatrixOperator<uint32_t>; template class CSparseMatrixOperator<int64_t>; template class CSparseMatrixOperator<uint64_t>; template class CSparseMatrixOperator<float32_t>; template class CSparseMatrixOperator<float64_t>; template class CSparseMatrixOperator<floatmax_t>; template class CSparseMatrixOperator<complex128_t>; }
gpl-3.0
obfuscated/codeblocks_sf
src/plugins/debuggergdb/editwatchdlg.cpp
15
2010
/* * This file is part of the Code::Blocks IDE and licensed under the GNU General Public License, version 3 * http://www.gnu.org/licenses/gpl-3.0.html * * $Revision$ * $Id$ * $HeadURL$ */ #include <sdk.h> #include "editwatchdlg.h" #ifndef CB_PRECOMP #include <wx/button.h> #include <wx/checkbox.h> #include <wx/defs.h> #include <wx/intl.h> #include <wx/radiobox.h> #include <wx/sizer.h> #include <wx/spinctrl.h> #include <wx/textctrl.h> #include <wx/xrc/xmlres.h> #endif // CB_PRECOMP #include "debugger_defs.h" EditWatchDlg::EditWatchDlg(cb::shared_ptr<GDBWatch> w, wxWindow* parent) : m_watch(w) { //ctor wxXmlResource::Get()->LoadObject(this, parent, _T("dlgEditWatch"),_T("wxScrollingDialog")); if (m_watch) { wxString symbol; m_watch->GetSymbol(symbol); XRCCTRL(*this, "txtKeyword", wxTextCtrl)->SetValue(symbol); XRCCTRL(*this, "rbFormat", wxRadioBox)->SetSelection((int)m_watch->GetFormat()); XRCCTRL(*this, "chkArray", wxCheckBox)->SetValue(m_watch->IsArray()); XRCCTRL(*this, "spnArrStart", wxSpinCtrl)->SetValue(m_watch->GetArrayStart()); XRCCTRL(*this, "spnArrCount", wxSpinCtrl)->SetValue(m_watch->GetArrayCount()); } XRCCTRL(*this, "txtKeyword", wxTextCtrl)->SetFocus(); XRCCTRL(*this, "wxID_OK", wxButton)->SetDefault(); } EditWatchDlg::~EditWatchDlg() { //dtor } void EditWatchDlg::EndModal(int retCode) { if (retCode == wxID_OK && m_watch) { m_watch->SetSymbol(CleanStringValue(XRCCTRL(*this, "txtKeyword", wxTextCtrl)->GetValue())); m_watch->SetFormat((WatchFormat)XRCCTRL(*this, "rbFormat", wxRadioBox)->GetSelection()); m_watch->SetArray(XRCCTRL(*this, "chkArray", wxCheckBox)->GetValue()); m_watch->SetArrayParams(XRCCTRL(*this, "spnArrStart", wxSpinCtrl)->GetValue(), XRCCTRL(*this, "spnArrCount", wxSpinCtrl)->GetValue()); } wxScrollingDialog::EndModal(retCode); }
gpl-3.0
danialbehzadi/Nokia-RM-1013-2.0.0.11
kernel/drivers/staging/iio/accel/adis16209_ring.c
4879
3569
#include <linux/export.h> #include <linux/interrupt.h> #include <linux/mutex.h> #include <linux/kernel.h> #include <linux/spi/spi.h> #include <linux/slab.h> #include "../iio.h" #include "../ring_sw.h" #include "../trigger_consumer.h" #include "adis16209.h" /** * adis16209_read_ring_data() read data registers which will be placed into ring * @dev: device associated with child of actual device (iio_dev or iio_trig) * @rx: somewhere to pass back the value read **/ static int adis16209_read_ring_data(struct device *dev, u8 *rx) { struct spi_message msg; struct iio_dev *indio_dev = dev_get_drvdata(dev); struct adis16209_state *st = iio_priv(indio_dev); struct spi_transfer xfers[ADIS16209_OUTPUTS + 1]; int ret; int i; mutex_lock(&st->buf_lock); spi_message_init(&msg); memset(xfers, 0, sizeof(xfers)); for (i = 0; i <= ADIS16209_OUTPUTS; i++) { xfers[i].bits_per_word = 8; xfers[i].cs_change = 1; xfers[i].len = 2; xfers[i].delay_usecs = 30; xfers[i].tx_buf = st->tx + 2 * i; st->tx[2 * i] = ADIS16209_READ_REG(ADIS16209_SUPPLY_OUT + 2 * i); st->tx[2 * i + 1] = 0; if (i >= 1) xfers[i].rx_buf = rx + 2 * (i - 1); spi_message_add_tail(&xfers[i], &msg); } ret = spi_sync(st->us, &msg); if (ret) dev_err(&st->us->dev, "problem when burst reading"); mutex_unlock(&st->buf_lock); return ret; } /* Whilst this makes a lot of calls to iio_sw_ring functions - it is to device * specific to be rolled into the core. */ static irqreturn_t adis16209_trigger_handler(int irq, void *p) { struct iio_poll_func *pf = p; struct iio_dev *indio_dev = pf->indio_dev; struct adis16209_state *st = iio_priv(indio_dev); struct iio_buffer *ring = indio_dev->buffer; int i = 0; s16 *data; size_t datasize = ring->access->get_bytes_per_datum(ring); data = kmalloc(datasize , GFP_KERNEL); if (data == NULL) { dev_err(&st->us->dev, "memory alloc failed in ring bh"); return -ENOMEM; } if (!bitmap_empty(indio_dev->active_scan_mask, indio_dev->masklength) && adis16209_read_ring_data(&indio_dev->dev, st->rx) >= 0) for (; i < bitmap_weight(indio_dev->active_scan_mask, indio_dev->masklength); i++) data[i] = be16_to_cpup((__be16 *)&(st->rx[i*2])); /* Guaranteed to be aligned with 8 byte boundary */ if (ring->scan_timestamp) *((s64 *)(data + ((i + 3)/4)*4)) = pf->timestamp; ring->access->store_to(ring, (u8 *)data, pf->timestamp); iio_trigger_notify_done(indio_dev->trig); kfree(data); return IRQ_HANDLED; } void adis16209_unconfigure_ring(struct iio_dev *indio_dev) { iio_dealloc_pollfunc(indio_dev->pollfunc); iio_sw_rb_free(indio_dev->buffer); } static const struct iio_buffer_setup_ops adis16209_ring_setup_ops = { .preenable = &iio_sw_buffer_preenable, .postenable = &iio_triggered_buffer_postenable, .predisable = &iio_triggered_buffer_predisable, }; int adis16209_configure_ring(struct iio_dev *indio_dev) { int ret = 0; struct iio_buffer *ring; ring = iio_sw_rb_allocate(indio_dev); if (!ring) { ret = -ENOMEM; return ret; } indio_dev->buffer = ring; ring->scan_timestamp = true; indio_dev->setup_ops = &adis16209_ring_setup_ops; indio_dev->pollfunc = iio_alloc_pollfunc(&iio_pollfunc_store_time, &adis16209_trigger_handler, IRQF_ONESHOT, indio_dev, "%s_consumer%d", indio_dev->name, indio_dev->id); if (indio_dev->pollfunc == NULL) { ret = -ENOMEM; goto error_iio_sw_rb_free; } indio_dev->modes |= INDIO_BUFFER_TRIGGERED; return 0; error_iio_sw_rb_free: iio_sw_rb_free(indio_dev->buffer); return ret; }
gpl-3.0
nloewen/ORB_SLAM2_Android
ORB_SLAM2_Android/jni/Thirdparty/clapack/TESTING/EIG/ddrges.c
21
39179
/* ddrges.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; static integer c_n1 = -1; static doublereal c_b26 = 0.; static integer c__2 = 2; static doublereal c_b32 = 1.; static integer c__3 = 3; static integer c__4 = 4; static integer c__0 = 0; /* Subroutine */ int ddrges_(integer *nsizes, integer *nn, integer *ntypes, logical *dotype, integer *iseed, doublereal *thresh, integer *nounit, doublereal *a, integer *lda, doublereal *b, doublereal *s, doublereal *t, doublereal *q, integer *ldq, doublereal *z__, doublereal *alphar, doublereal *alphai, doublereal *beta, doublereal *work, integer * lwork, doublereal *result, logical *bwork, integer *info) { /* Initialized data */ static integer kclass[26] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2, 2,2,2,3 }; static integer kbmagn[26] = { 1,1,1,1,1,1,1,1,3,2,3,2,2,3,1,1,1,1,1,1,1,3, 2,3,2,1 }; static integer ktrian[26] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1, 1,1,1,1 }; static integer iasign[26] = { 0,0,0,0,0,0,2,0,2,2,0,0,2,2,2,0,2,0,0,0,2,2, 2,2,2,0 }; static integer ibsign[26] = { 0,0,0,0,0,0,0,2,0,0,2,2,0,0,2,0,2,0,0,0,0,0, 0,0,0,0 }; static integer kz1[6] = { 0,1,2,1,3,3 }; static integer kz2[6] = { 0,0,1,2,1,1 }; static integer kadd[6] = { 0,0,0,0,3,2 }; static integer katype[26] = { 0,1,0,1,2,3,4,1,4,4,1,1,4,4,4,2,4,5,8,7,9,4, 4,4,4,0 }; static integer kbtype[26] = { 0,0,1,1,2,-3,1,4,1,1,4,4,1,1,-4,2,-4,8,8,8, 8,8,8,8,8,0 }; static integer kazero[26] = { 1,1,1,1,1,1,2,1,2,2,1,1,2,2,3,1,3,5,5,5,5,3, 3,3,3,1 }; static integer kbzero[26] = { 1,1,1,1,1,1,1,2,1,1,2,2,1,1,4,1,4,6,6,6,6,4, 4,4,4,1 }; static integer kamagn[26] = { 1,1,1,1,1,1,1,1,2,3,2,3,2,3,1,1,1,1,1,1,1,2, 3,3,2,1 }; /* Format strings */ static char fmt_9999[] = "(\002 DDRGES: \002,a,\002 returned INFO=\002,i" "6,\002.\002,/9x,\002N=\002,i6,\002, JTYPE=\002,i6,\002, ISEED=" "(\002,4(i4,\002,\002),i5,\002)\002)"; static char fmt_9998[] = "(\002 DDRGES: DGET53 returned INFO=\002,i1," "\002 for eigenvalue \002,i6,\002.\002,/9x,\002N=\002,i6,\002, JT" "YPE=\002,i6,\002, ISEED=(\002,4(i4,\002,\002),i5,\002)\002)"; static char fmt_9997[] = "(\002 DDRGES: S not in Schur form at eigenvalu" "e \002,i6,\002.\002,/9x,\002N=\002,i6,\002, JTYPE=\002,i6,\002, " "ISEED=(\002,3(i5,\002,\002),i5,\002)\002)"; static char fmt_9996[] = "(/1x,a3,\002 -- Real Generalized Schur form dr" "iver\002)"; static char fmt_9995[] = "(\002 Matrix types (see DDRGES for details):" " \002)"; static char fmt_9994[] = "(\002 Special Matrices:\002,23x,\002(J'=transp" "osed Jordan block)\002,/\002 1=(0,0) 2=(I,0) 3=(0,I) 4=(I,I" ") 5=(J',J') \002,\0026=(diag(J',I), diag(I,J'))\002,/\002 Diag" "onal Matrices: ( \002,\002D=diag(0,1,2,...) )\002,/\002 7=(D," "I) 9=(large*D, small*I\002,\002) 11=(large*I, small*D) 13=(l" "arge*D, large*I)\002,/\002 8=(I,D) 10=(small*D, large*I) 12=" "(small*I, large*D) \002,\002 14=(small*D, small*I)\002,/\002 15" "=(D, reversed D)\002)"; static char fmt_9993[] = "(\002 Matrices Rotated by Random \002,a,\002 M" "atrices U, V:\002,/\002 16=Transposed Jordan Blocks " " 19=geometric \002,\002alpha, beta=0,1\002,/\002 17=arithm. alp" "ha&beta \002,\002 20=arithmetic alpha, beta=0," "1\002,/\002 18=clustered \002,\002alpha, beta=0,1 21" "=random alpha, beta=0,1\002,/\002 Large & Small Matrices:\002," "/\002 22=(large, small) \002,\00223=(small,large) 24=(smal" "l,small) 25=(large,large)\002,/\002 26=random O(1) matrices" ".\002)"; static char fmt_9992[] = "(/\002 Tests performed: (S is Schur, T is tri" "angular, \002,\002Q and Z are \002,a,\002,\002,/19x,\002l and r " "are the appropriate left and right\002,/19x,\002eigenvectors, re" "sp., a is alpha, b is beta, and\002,/19x,a,\002 means \002,a," "\002.)\002,/\002 Without ordering: \002,/\002 1 = | A - Q S " "Z\002,a,\002 | / ( |A| n ulp ) 2 = | B - Q T Z\002,a,\002 |" " / ( |B| n ulp )\002,/\002 3 = | I - QQ\002,a,\002 | / ( n ulp " ") 4 = | I - ZZ\002,a,\002 | / ( n ulp )\002,/\002 5" " = A is in Schur form S\002,/\002 6 = difference between (alpha" ",beta)\002,\002 and diagonals of (S,T)\002,/\002 With ordering:" " \002,/\002 7 = | (A,B) - Q (S,T) Z\002,a,\002 | / ( |(A,B)| n " "ulp ) \002,/\002 8 = | I - QQ\002,a,\002 | / ( n ulp ) " " 9 = | I - ZZ\002,a,\002 | / ( n ulp )\002,/\002 10 = A is in" " Schur form S\002,/\002 11 = difference between (alpha,beta) and" " diagonals\002,\002 of (S,T)\002,/\002 12 = SDIM is the correct " "number of \002,\002selected eigenvalues\002,/)"; static char fmt_9991[] = "(\002 Matrix order=\002,i5,\002, type=\002,i2" ",\002, seed=\002,4(i4,\002,\002),\002 result \002,i2,\002 is\002" ",0p,f8.2)"; static char fmt_9990[] = "(\002 Matrix order=\002,i5,\002, type=\002,i2" ",\002, seed=\002,4(i4,\002,\002),\002 result \002,i2,\002 is\002" ",1p,d10.3)"; /* System generated locals */ integer a_dim1, a_offset, b_dim1, b_offset, q_dim1, q_offset, s_dim1, s_offset, t_dim1, t_offset, z_dim1, z_offset, i__1, i__2, i__3, i__4; doublereal d__1, d__2, d__3, d__4, d__5, d__6, d__7, d__8, d__9, d__10; /* Builtin functions */ double d_sign(doublereal *, doublereal *); integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(void); /* Local variables */ integer i__, j, n, i1, n1, jc, nb, in, jr; doublereal ulp; integer iadd, sdim, ierr, nmax, rsub; char sort[1]; doublereal temp1, temp2; logical badnn; extern /* Subroutine */ int dget51_(integer *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *), dget53_( doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *), dget54_( integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *), dgges_(char *, char *, char *, L_fp, integer *, doublereal *, integer *, doublereal *, integer *, integer *, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *, logical *, integer *); integer iinfo; doublereal rmagn[4]; integer nmats, jsize, nerrs, jtype, ntest, isort; extern /* Subroutine */ int dlatm4_(integer *, integer *, integer *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *, integer *, doublereal *, integer *), dorm2r_(char *, char *, integer *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *), dlabad_(doublereal *, doublereal *); logical ilabad; extern doublereal dlamch_(char *); extern /* Subroutine */ int dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); extern doublereal dlarnd_(integer *, integer *); extern /* Subroutine */ int dlacpy_(char *, integer *, integer *, doublereal *, integer *, doublereal *, integer *); doublereal safmin; integer ioldsd[4]; doublereal safmax; integer knteig; extern logical dlctes_(doublereal *, doublereal *, doublereal *); extern integer ilaenv_(integer *, char *, char *, integer *, integer *, integer *, integer *); extern /* Subroutine */ int alasvm_(char *, integer *, integer *, integer *, integer *), dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *); integer minwrk, maxwrk; doublereal ulpinv; integer mtypes, ntestt; /* Fortran I/O blocks */ static cilist io___40 = { 0, 0, 0, fmt_9999, 0 }; static cilist io___46 = { 0, 0, 0, fmt_9999, 0 }; static cilist io___52 = { 0, 0, 0, fmt_9998, 0 }; static cilist io___53 = { 0, 0, 0, fmt_9997, 0 }; static cilist io___55 = { 0, 0, 0, fmt_9996, 0 }; static cilist io___56 = { 0, 0, 0, fmt_9995, 0 }; static cilist io___57 = { 0, 0, 0, fmt_9994, 0 }; static cilist io___58 = { 0, 0, 0, fmt_9993, 0 }; static cilist io___59 = { 0, 0, 0, fmt_9992, 0 }; static cilist io___60 = { 0, 0, 0, fmt_9991, 0 }; static cilist io___61 = { 0, 0, 0, fmt_9990, 0 }; /* -- LAPACK test routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DDRGES checks the nonsymmetric generalized eigenvalue (Schur form) */ /* problem driver DGGES. */ /* DGGES factors A and B as Q S Z' and Q T Z' , where ' means */ /* transpose, T is upper triangular, S is in generalized Schur form */ /* (block upper triangular, with 1x1 and 2x2 blocks on the diagonal, */ /* the 2x2 blocks corresponding to complex conjugate pairs of */ /* generalized eigenvalues), and Q and Z are orthogonal. It also */ /* computes the generalized eigenvalues (alpha(j),beta(j)), j=1,...,n, */ /* Thus, w(j) = alpha(j)/beta(j) is a root of the characteristic */ /* equation */ /* det( A - w(j) B ) = 0 */ /* Optionally it also reorder the eigenvalues so that a selected */ /* cluster of eigenvalues appears in the leading diagonal block of the */ /* Schur forms. */ /* When DDRGES is called, a number of matrix "sizes" ("N's") and a */ /* number of matrix "TYPES" are specified. For each size ("N") */ /* and each TYPE of matrix, a pair of matrices (A, B) will be generated */ /* and used for testing. For each matrix pair, the following 13 tests */ /* will be performed and compared with the threshhold THRESH except */ /* the tests (5), (11) and (13). */ /* (1) | A - Q S Z' | / ( |A| n ulp ) (no sorting of eigenvalues) */ /* (2) | B - Q T Z' | / ( |B| n ulp ) (no sorting of eigenvalues) */ /* (3) | I - QQ' | / ( n ulp ) (no sorting of eigenvalues) */ /* (4) | I - ZZ' | / ( n ulp ) (no sorting of eigenvalues) */ /* (5) if A is in Schur form (i.e. quasi-triangular form) */ /* (no sorting of eigenvalues) */ /* (6) if eigenvalues = diagonal blocks of the Schur form (S, T), */ /* i.e., test the maximum over j of D(j) where: */ /* if alpha(j) is real: */ /* |alpha(j) - S(j,j)| |beta(j) - T(j,j)| */ /* D(j) = ------------------------ + ----------------------- */ /* max(|alpha(j)|,|S(j,j)|) max(|beta(j)|,|T(j,j)|) */ /* if alpha(j) is complex: */ /* | det( s S - w T ) | */ /* D(j) = --------------------------------------------------- */ /* ulp max( s norm(S), |w| norm(T) )*norm( s S - w T ) */ /* and S and T are here the 2 x 2 diagonal blocks of S and T */ /* corresponding to the j-th and j+1-th eigenvalues. */ /* (no sorting of eigenvalues) */ /* (7) | (A,B) - Q (S,T) Z' | / ( | (A,B) | n ulp ) */ /* (with sorting of eigenvalues). */ /* (8) | I - QQ' | / ( n ulp ) (with sorting of eigenvalues). */ /* (9) | I - ZZ' | / ( n ulp ) (with sorting of eigenvalues). */ /* (10) if A is in Schur form (i.e. quasi-triangular form) */ /* (with sorting of eigenvalues). */ /* (11) if eigenvalues = diagonal blocks of the Schur form (S, T), */ /* i.e. test the maximum over j of D(j) where: */ /* if alpha(j) is real: */ /* |alpha(j) - S(j,j)| |beta(j) - T(j,j)| */ /* D(j) = ------------------------ + ----------------------- */ /* max(|alpha(j)|,|S(j,j)|) max(|beta(j)|,|T(j,j)|) */ /* if alpha(j) is complex: */ /* | det( s S - w T ) | */ /* D(j) = --------------------------------------------------- */ /* ulp max( s norm(S), |w| norm(T) )*norm( s S - w T ) */ /* and S and T are here the 2 x 2 diagonal blocks of S and T */ /* corresponding to the j-th and j+1-th eigenvalues. */ /* (with sorting of eigenvalues). */ /* (12) if sorting worked and SDIM is the number of eigenvalues */ /* which were SELECTed. */ /* Test Matrices */ /* ============= */ /* The sizes of the test matrices are specified by an array */ /* NN(1:NSIZES); the value of each element NN(j) specifies one size. */ /* The "types" are specified by a logical array DOTYPE( 1:NTYPES ); if */ /* DOTYPE(j) is .TRUE., then matrix type "j" will be generated. */ /* Currently, the list of possible types is: */ /* (1) ( 0, 0 ) (a pair of zero matrices) */ /* (2) ( I, 0 ) (an identity and a zero matrix) */ /* (3) ( 0, I ) (an identity and a zero matrix) */ /* (4) ( I, I ) (a pair of identity matrices) */ /* t t */ /* (5) ( J , J ) (a pair of transposed Jordan blocks) */ /* t ( I 0 ) */ /* (6) ( X, Y ) where X = ( J 0 ) and Y = ( t ) */ /* ( 0 I ) ( 0 J ) */ /* and I is a k x k identity and J a (k+1)x(k+1) */ /* Jordan block; k=(N-1)/2 */ /* (7) ( D, I ) where D is diag( 0, 1,..., N-1 ) (a diagonal */ /* matrix with those diagonal entries.) */ /* (8) ( I, D ) */ /* (9) ( big*D, small*I ) where "big" is near overflow and small=1/big */ /* (10) ( small*D, big*I ) */ /* (11) ( big*I, small*D ) */ /* (12) ( small*I, big*D ) */ /* (13) ( big*D, big*I ) */ /* (14) ( small*D, small*I ) */ /* (15) ( D1, D2 ) where D1 is diag( 0, 0, 1, ..., N-3, 0 ) and */ /* D2 is diag( 0, N-3, N-4,..., 1, 0, 0 ) */ /* t t */ /* (16) Q ( J , J ) Z where Q and Z are random orthogonal matrices. */ /* (17) Q ( T1, T2 ) Z where T1 and T2 are upper triangular matrices */ /* with random O(1) entries above the diagonal */ /* and diagonal entries diag(T1) = */ /* ( 0, 0, 1, ..., N-3, 0 ) and diag(T2) = */ /* ( 0, N-3, N-4,..., 1, 0, 0 ) */ /* (18) Q ( T1, T2 ) Z diag(T1) = ( 0, 0, 1, 1, s, ..., s, 0 ) */ /* diag(T2) = ( 0, 1, 0, 1,..., 1, 0 ) */ /* s = machine precision. */ /* (19) Q ( T1, T2 ) Z diag(T1)=( 0,0,1,1, 1-d, ..., 1-(N-5)*d=s, 0 ) */ /* diag(T2) = ( 0, 1, 0, 1, ..., 1, 0 ) */ /* N-5 */ /* (20) Q ( T1, T2 ) Z diag(T1)=( 0, 0, 1, 1, a, ..., a =s, 0 ) */ /* diag(T2) = ( 0, 1, 0, 1, ..., 1, 0, 0 ) */ /* (21) Q ( T1, T2 ) Z diag(T1)=( 0, 0, 1, r1, r2, ..., r(N-4), 0 ) */ /* diag(T2) = ( 0, 1, 0, 1, ..., 1, 0, 0 ) */ /* where r1,..., r(N-4) are random. */ /* (22) Q ( big*T1, small*T2 ) Z diag(T1) = ( 0, 0, 1, ..., N-3, 0 ) */ /* diag(T2) = ( 0, 1, ..., 1, 0, 0 ) */ /* (23) Q ( small*T1, big*T2 ) Z diag(T1) = ( 0, 0, 1, ..., N-3, 0 ) */ /* diag(T2) = ( 0, 1, ..., 1, 0, 0 ) */ /* (24) Q ( small*T1, small*T2 ) Z diag(T1) = ( 0, 0, 1, ..., N-3, 0 ) */ /* diag(T2) = ( 0, 1, ..., 1, 0, 0 ) */ /* (25) Q ( big*T1, big*T2 ) Z diag(T1) = ( 0, 0, 1, ..., N-3, 0 ) */ /* diag(T2) = ( 0, 1, ..., 1, 0, 0 ) */ /* (26) Q ( T1, T2 ) Z where T1 and T2 are random upper-triangular */ /* matrices. */ /* Arguments */ /* ========= */ /* NSIZES (input) INTEGER */ /* The number of sizes of matrices to use. If it is zero, */ /* DDRGES does nothing. NSIZES >= 0. */ /* NN (input) INTEGER array, dimension (NSIZES) */ /* An array containing the sizes to be used for the matrices. */ /* Zero values will be skipped. NN >= 0. */ /* NTYPES (input) INTEGER */ /* The number of elements in DOTYPE. If it is zero, DDRGES */ /* does nothing. It must be at least zero. If it is MAXTYP+1 */ /* and NSIZES is 1, then an additional type, MAXTYP+1 is */ /* defined, which is to use whatever matrix is in A on input. */ /* This is only useful if DOTYPE(1:MAXTYP) is .FALSE. and */ /* DOTYPE(MAXTYP+1) is .TRUE. . */ /* DOTYPE (input) LOGICAL array, dimension (NTYPES) */ /* If DOTYPE(j) is .TRUE., then for each size in NN a */ /* matrix of that size and of type j will be generated. */ /* If NTYPES is smaller than the maximum number of types */ /* defined (PARAMETER MAXTYP), then types NTYPES+1 through */ /* MAXTYP will not be generated. If NTYPES is larger */ /* than MAXTYP, DOTYPE(MAXTYP+1) through DOTYPE(NTYPES) */ /* will be ignored. */ /* ISEED (input/output) INTEGER array, dimension (4) */ /* On entry ISEED specifies the seed of the random number */ /* generator. The array elements should be between 0 and 4095; */ /* if not they will be reduced mod 4096. Also, ISEED(4) must */ /* be odd. The random number generator uses a linear */ /* congruential sequence limited to small integers, and so */ /* should produce machine independent random numbers. The */ /* values of ISEED are changed on exit, and can be used in the */ /* next call to DDRGES to continue the same random number */ /* sequence. */ /* THRESH (input) DOUBLE PRECISION */ /* A test will count as "failed" if the "error", computed as */ /* described above, exceeds THRESH. Note that the error is */ /* scaled to be O(1), so THRESH should be a reasonably small */ /* multiple of 1, e.g., 10 or 100. In particular, it should */ /* not depend on the precision (single vs. double) or the size */ /* of the matrix. THRESH >= 0. */ /* NOUNIT (input) INTEGER */ /* The FORTRAN unit number for printing out error messages */ /* (e.g., if a routine returns IINFO not equal to 0.) */ /* A (input/workspace) DOUBLE PRECISION array, */ /* dimension(LDA, max(NN)) */ /* Used to hold the original A matrix. Used as input only */ /* if NTYPES=MAXTYP+1, DOTYPE(1:MAXTYP)=.FALSE., and */ /* DOTYPE(MAXTYP+1)=.TRUE. */ /* LDA (input) INTEGER */ /* The leading dimension of A, B, S, and T. */ /* It must be at least 1 and at least max( NN ). */ /* B (input/workspace) DOUBLE PRECISION array, */ /* dimension(LDA, max(NN)) */ /* Used to hold the original B matrix. Used as input only */ /* if NTYPES=MAXTYP+1, DOTYPE(1:MAXTYP)=.FALSE., and */ /* DOTYPE(MAXTYP+1)=.TRUE. */ /* S (workspace) DOUBLE PRECISION array, dimension (LDA, max(NN)) */ /* The Schur form matrix computed from A by DGGES. On exit, S */ /* contains the Schur form matrix corresponding to the matrix */ /* in A. */ /* T (workspace) DOUBLE PRECISION array, dimension (LDA, max(NN)) */ /* The upper triangular matrix computed from B by DGGES. */ /* Q (workspace) DOUBLE PRECISION array, dimension (LDQ, max(NN)) */ /* The (left) orthogonal matrix computed by DGGES. */ /* LDQ (input) INTEGER */ /* The leading dimension of Q and Z. It must */ /* be at least 1 and at least max( NN ). */ /* Z (workspace) DOUBLE PRECISION array, dimension( LDQ, max(NN) ) */ /* The (right) orthogonal matrix computed by DGGES. */ /* ALPHAR (workspace) DOUBLE PRECISION array, dimension (max(NN)) */ /* ALPHAI (workspace) DOUBLE PRECISION array, dimension (max(NN)) */ /* BETA (workspace) DOUBLE PRECISION array, dimension (max(NN)) */ /* The generalized eigenvalues of (A,B) computed by DGGES. */ /* ( ALPHAR(k)+ALPHAI(k)*i ) / BETA(k) is the k-th */ /* generalized eigenvalue of A and B. */ /* WORK (workspace) DOUBLE PRECISION array, dimension (LWORK) */ /* LWORK (input) INTEGER */ /* The dimension of the array WORK. */ /* LWORK >= MAX( 10*(N+1), 3*N*N ), where N is the largest */ /* matrix dimension. */ /* RESULT (output) DOUBLE PRECISION array, dimension (15) */ /* The values computed by the tests described above. */ /* The values are currently limited to 1/ulp, to avoid overflow. */ /* BWORK (workspace) LOGICAL array, dimension (N) */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value. */ /* > 0: A routine returned an error code. INFO is the */ /* absolute value of the INFO value returned. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. Local Arrays .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Data statements .. */ /* Parameter adjustments */ --nn; --dotype; --iseed; t_dim1 = *lda; t_offset = 1 + t_dim1; t -= t_offset; s_dim1 = *lda; s_offset = 1 + s_dim1; s -= s_offset; b_dim1 = *lda; b_offset = 1 + b_dim1; b -= b_offset; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; z_dim1 = *ldq; z_offset = 1 + z_dim1; z__ -= z_offset; q_dim1 = *ldq; q_offset = 1 + q_dim1; q -= q_offset; --alphar; --alphai; --beta; --work; --result; --bwork; /* Function Body */ /* .. */ /* .. Executable Statements .. */ /* Check for errors */ *info = 0; badnn = FALSE_; nmax = 1; i__1 = *nsizes; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = nmax, i__3 = nn[j]; nmax = max(i__2,i__3); if (nn[j] < 0) { badnn = TRUE_; } /* L10: */ } if (*nsizes < 0) { *info = -1; } else if (badnn) { *info = -2; } else if (*ntypes < 0) { *info = -3; } else if (*thresh < 0.) { *info = -6; } else if (*lda <= 1 || *lda < nmax) { *info = -9; } else if (*ldq <= 1 || *ldq < nmax) { *info = -14; } /* Compute workspace */ /* (Note: Comments in the code beginning "Workspace:" describe the */ /* minimal amount of workspace needed at that point in the code, */ /* as well as the preferred amount for good performance. */ /* NB refers to the optimal block size for the immediately */ /* following subroutine, as returned by ILAENV. */ minwrk = 1; if (*info == 0 && *lwork >= 1) { /* Computing MAX */ i__1 = (nmax + 1) * 10, i__2 = nmax * 3 * nmax; minwrk = max(i__1,i__2); /* Computing MAX */ i__1 = 1, i__2 = ilaenv_(&c__1, "DGEQRF", " ", &nmax, &nmax, &c_n1, & c_n1), i__1 = max(i__1,i__2), i__2 = ilaenv_(&c__1, "DORMQR", "LT", &nmax, &nmax, &nmax, &c_n1), i__1 = max(i__1,i__2), i__2 = ilaenv_(& c__1, "DORGQR", " ", &nmax, &nmax, &nmax, &c_n1); nb = max(i__1,i__2); /* Computing MAX */ i__1 = (nmax + 1) * 10, i__2 = (nmax << 1) + nmax * nb, i__1 = max( i__1,i__2), i__2 = nmax * 3 * nmax; maxwrk = max(i__1,i__2); work[1] = (doublereal) maxwrk; } if (*lwork < minwrk) { *info = -20; } if (*info != 0) { i__1 = -(*info); xerbla_("DDRGES", &i__1); return 0; } /* Quick return if possible */ if (*nsizes == 0 || *ntypes == 0) { return 0; } safmin = dlamch_("Safe minimum"); ulp = dlamch_("Epsilon") * dlamch_("Base"); safmin /= ulp; safmax = 1. / safmin; dlabad_(&safmin, &safmax); ulpinv = 1. / ulp; /* The values RMAGN(2:3) depend on N, see below. */ rmagn[0] = 0.; rmagn[1] = 1.; /* Loop over matrix sizes */ ntestt = 0; nerrs = 0; nmats = 0; i__1 = *nsizes; for (jsize = 1; jsize <= i__1; ++jsize) { n = nn[jsize]; n1 = max(1,n); rmagn[2] = safmax * ulp / (doublereal) n1; rmagn[3] = safmin * ulpinv * (doublereal) n1; if (*nsizes != 1) { mtypes = min(26,*ntypes); } else { mtypes = min(27,*ntypes); } /* Loop over matrix types */ i__2 = mtypes; for (jtype = 1; jtype <= i__2; ++jtype) { if (! dotype[jtype]) { goto L180; } ++nmats; ntest = 0; /* Save ISEED in case of an error. */ for (j = 1; j <= 4; ++j) { ioldsd[j - 1] = iseed[j]; /* L20: */ } /* Initialize RESULT */ for (j = 1; j <= 13; ++j) { result[j] = 0.; /* L30: */ } /* Generate test matrices A and B */ /* Description of control parameters: */ /* KZLASS: =1 means w/o rotation, =2 means w/ rotation, */ /* =3 means random. */ /* KATYPE: the "type" to be passed to DLATM4 for computing A. */ /* KAZERO: the pattern of zeros on the diagonal for A: */ /* =1: ( xxx ), =2: (0, xxx ) =3: ( 0, 0, xxx, 0 ), */ /* =4: ( 0, xxx, 0, 0 ), =5: ( 0, 0, 1, xxx, 0 ), */ /* =6: ( 0, 1, 0, xxx, 0 ). (xxx means a string of */ /* non-zero entries.) */ /* KAMAGN: the magnitude of the matrix: =0: zero, =1: O(1), */ /* =2: large, =3: small. */ /* IASIGN: 1 if the diagonal elements of A are to be */ /* multiplied by a random magnitude 1 number, =2 if */ /* randomly chosen diagonal blocks are to be rotated */ /* to form 2x2 blocks. */ /* KBTYPE, KBZERO, KBMAGN, IBSIGN: the same, but for B. */ /* KTRIAN: =0: don't fill in the upper triangle, =1: do. */ /* KZ1, KZ2, KADD: used to implement KAZERO and KBZERO. */ /* RMAGN: used to implement KAMAGN and KBMAGN. */ if (mtypes > 26) { goto L110; } iinfo = 0; if (kclass[jtype - 1] < 3) { /* Generate A (w/o rotation) */ if ((i__3 = katype[jtype - 1], abs(i__3)) == 3) { in = ((n - 1) / 2 << 1) + 1; if (in != n) { dlaset_("Full", &n, &n, &c_b26, &c_b26, &a[a_offset], lda); } } else { in = n; } dlatm4_(&katype[jtype - 1], &in, &kz1[kazero[jtype - 1] - 1], &kz2[kazero[jtype - 1] - 1], &iasign[jtype - 1], & rmagn[kamagn[jtype - 1]], &ulp, &rmagn[ktrian[jtype - 1] * kamagn[jtype - 1]], &c__2, &iseed[1], &a[ a_offset], lda); iadd = kadd[kazero[jtype - 1] - 1]; if (iadd > 0 && iadd <= n) { a[iadd + iadd * a_dim1] = 1.; } /* Generate B (w/o rotation) */ if ((i__3 = kbtype[jtype - 1], abs(i__3)) == 3) { in = ((n - 1) / 2 << 1) + 1; if (in != n) { dlaset_("Full", &n, &n, &c_b26, &c_b26, &b[b_offset], lda); } } else { in = n; } dlatm4_(&kbtype[jtype - 1], &in, &kz1[kbzero[jtype - 1] - 1], &kz2[kbzero[jtype - 1] - 1], &ibsign[jtype - 1], & rmagn[kbmagn[jtype - 1]], &c_b32, &rmagn[ktrian[jtype - 1] * kbmagn[jtype - 1]], &c__2, &iseed[1], &b[ b_offset], lda); iadd = kadd[kbzero[jtype - 1] - 1]; if (iadd != 0 && iadd <= n) { b[iadd + iadd * b_dim1] = 1.; } if (kclass[jtype - 1] == 2 && n > 0) { /* Include rotations */ /* Generate Q, Z as Householder transformations times */ /* a diagonal matrix. */ i__3 = n - 1; for (jc = 1; jc <= i__3; ++jc) { i__4 = n; for (jr = jc; jr <= i__4; ++jr) { q[jr + jc * q_dim1] = dlarnd_(&c__3, &iseed[1]); z__[jr + jc * z_dim1] = dlarnd_(&c__3, &iseed[1]); /* L40: */ } i__4 = n + 1 - jc; dlarfg_(&i__4, &q[jc + jc * q_dim1], &q[jc + 1 + jc * q_dim1], &c__1, &work[jc]); work[(n << 1) + jc] = d_sign(&c_b32, &q[jc + jc * q_dim1]); q[jc + jc * q_dim1] = 1.; i__4 = n + 1 - jc; dlarfg_(&i__4, &z__[jc + jc * z_dim1], &z__[jc + 1 + jc * z_dim1], &c__1, &work[n + jc]); work[n * 3 + jc] = d_sign(&c_b32, &z__[jc + jc * z_dim1]); z__[jc + jc * z_dim1] = 1.; /* L50: */ } q[n + n * q_dim1] = 1.; work[n] = 0.; d__1 = dlarnd_(&c__2, &iseed[1]); work[n * 3] = d_sign(&c_b32, &d__1); z__[n + n * z_dim1] = 1.; work[n * 2] = 0.; d__1 = dlarnd_(&c__2, &iseed[1]); work[n * 4] = d_sign(&c_b32, &d__1); /* Apply the diagonal matrices */ i__3 = n; for (jc = 1; jc <= i__3; ++jc) { i__4 = n; for (jr = 1; jr <= i__4; ++jr) { a[jr + jc * a_dim1] = work[(n << 1) + jr] * work[ n * 3 + jc] * a[jr + jc * a_dim1]; b[jr + jc * b_dim1] = work[(n << 1) + jr] * work[ n * 3 + jc] * b[jr + jc * b_dim1]; /* L60: */ } /* L70: */ } i__3 = n - 1; dorm2r_("L", "N", &n, &n, &i__3, &q[q_offset], ldq, &work[ 1], &a[a_offset], lda, &work[(n << 1) + 1], & iinfo); if (iinfo != 0) { goto L100; } i__3 = n - 1; dorm2r_("R", "T", &n, &n, &i__3, &z__[z_offset], ldq, & work[n + 1], &a[a_offset], lda, &work[(n << 1) + 1], &iinfo); if (iinfo != 0) { goto L100; } i__3 = n - 1; dorm2r_("L", "N", &n, &n, &i__3, &q[q_offset], ldq, &work[ 1], &b[b_offset], lda, &work[(n << 1) + 1], & iinfo); if (iinfo != 0) { goto L100; } i__3 = n - 1; dorm2r_("R", "T", &n, &n, &i__3, &z__[z_offset], ldq, & work[n + 1], &b[b_offset], lda, &work[(n << 1) + 1], &iinfo); if (iinfo != 0) { goto L100; } } } else { /* Random matrices */ i__3 = n; for (jc = 1; jc <= i__3; ++jc) { i__4 = n; for (jr = 1; jr <= i__4; ++jr) { a[jr + jc * a_dim1] = rmagn[kamagn[jtype - 1]] * dlarnd_(&c__2, &iseed[1]); b[jr + jc * b_dim1] = rmagn[kbmagn[jtype - 1]] * dlarnd_(&c__2, &iseed[1]); /* L80: */ } /* L90: */ } } L100: if (iinfo != 0) { io___40.ciunit = *nounit; s_wsfe(&io___40); do_fio(&c__1, "Generator", (ftnlen)9); do_fio(&c__1, (char *)&iinfo, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&n, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&jtype, (ftnlen)sizeof(integer)); do_fio(&c__4, (char *)&ioldsd[0], (ftnlen)sizeof(integer)); e_wsfe(); *info = abs(iinfo); return 0; } L110: for (i__ = 1; i__ <= 13; ++i__) { result[i__] = -1.; /* L120: */ } /* Test with and without sorting of eigenvalues */ for (isort = 0; isort <= 1; ++isort) { if (isort == 0) { *(unsigned char *)sort = 'N'; rsub = 0; } else { *(unsigned char *)sort = 'S'; rsub = 5; } /* Call DGGES to compute H, T, Q, Z, alpha, and beta. */ dlacpy_("Full", &n, &n, &a[a_offset], lda, &s[s_offset], lda); dlacpy_("Full", &n, &n, &b[b_offset], lda, &t[t_offset], lda); ntest = rsub + 1 + isort; result[rsub + 1 + isort] = ulpinv; dgges_("V", "V", sort, (L_fp)dlctes_, &n, &s[s_offset], lda, & t[t_offset], lda, &sdim, &alphar[1], &alphai[1], & beta[1], &q[q_offset], ldq, &z__[z_offset], ldq, & work[1], lwork, &bwork[1], &iinfo); if (iinfo != 0 && iinfo != n + 2) { result[rsub + 1 + isort] = ulpinv; io___46.ciunit = *nounit; s_wsfe(&io___46); do_fio(&c__1, "DGGES", (ftnlen)5); do_fio(&c__1, (char *)&iinfo, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&n, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&jtype, (ftnlen)sizeof(integer)); do_fio(&c__4, (char *)&ioldsd[0], (ftnlen)sizeof(integer)) ; e_wsfe(); *info = abs(iinfo); goto L160; } ntest = rsub + 4; /* Do tests 1--4 (or tests 7--9 when reordering ) */ if (isort == 0) { dget51_(&c__1, &n, &a[a_offset], lda, &s[s_offset], lda, & q[q_offset], ldq, &z__[z_offset], ldq, &work[1], & result[1]); dget51_(&c__1, &n, &b[b_offset], lda, &t[t_offset], lda, & q[q_offset], ldq, &z__[z_offset], ldq, &work[1], & result[2]); } else { dget54_(&n, &a[a_offset], lda, &b[b_offset], lda, &s[ s_offset], lda, &t[t_offset], lda, &q[q_offset], ldq, &z__[z_offset], ldq, &work[1], &result[7]); } dget51_(&c__3, &n, &a[a_offset], lda, &t[t_offset], lda, &q[ q_offset], ldq, &q[q_offset], ldq, &work[1], &result[ rsub + 3]); dget51_(&c__3, &n, &b[b_offset], lda, &t[t_offset], lda, &z__[ z_offset], ldq, &z__[z_offset], ldq, &work[1], & result[rsub + 4]); /* Do test 5 and 6 (or Tests 10 and 11 when reordering): */ /* check Schur form of A and compare eigenvalues with */ /* diagonals. */ ntest = rsub + 6; temp1 = 0.; i__3 = n; for (j = 1; j <= i__3; ++j) { ilabad = FALSE_; if (alphai[j] == 0.) { /* Computing MAX */ d__7 = safmin, d__8 = (d__2 = alphar[j], abs(d__2)), d__7 = max(d__7,d__8), d__8 = (d__3 = s[j + j * s_dim1], abs(d__3)); /* Computing MAX */ d__9 = safmin, d__10 = (d__5 = beta[j], abs(d__5)), d__9 = max(d__9,d__10), d__10 = (d__6 = t[j + j * t_dim1], abs(d__6)); temp2 = ((d__1 = alphar[j] - s[j + j * s_dim1], abs( d__1)) / max(d__7,d__8) + (d__4 = beta[j] - t[ j + j * t_dim1], abs(d__4)) / max(d__9,d__10)) / ulp; if (j < n) { if (s[j + 1 + j * s_dim1] != 0.) { ilabad = TRUE_; result[rsub + 5] = ulpinv; } } if (j > 1) { if (s[j + (j - 1) * s_dim1] != 0.) { ilabad = TRUE_; result[rsub + 5] = ulpinv; } } } else { if (alphai[j] > 0.) { i1 = j; } else { i1 = j - 1; } if (i1 <= 0 || i1 >= n) { ilabad = TRUE_; } else if (i1 < n - 1) { if (s[i1 + 2 + (i1 + 1) * s_dim1] != 0.) { ilabad = TRUE_; result[rsub + 5] = ulpinv; } } else if (i1 > 1) { if (s[i1 + (i1 - 1) * s_dim1] != 0.) { ilabad = TRUE_; result[rsub + 5] = ulpinv; } } if (! ilabad) { dget53_(&s[i1 + i1 * s_dim1], lda, &t[i1 + i1 * t_dim1], lda, &beta[j], &alphar[j], & alphai[j], &temp2, &ierr); if (ierr >= 3) { io___52.ciunit = *nounit; s_wsfe(&io___52); do_fio(&c__1, (char *)&ierr, (ftnlen)sizeof( integer)); do_fio(&c__1, (char *)&j, (ftnlen)sizeof( integer)); do_fio(&c__1, (char *)&n, (ftnlen)sizeof( integer)); do_fio(&c__1, (char *)&jtype, (ftnlen)sizeof( integer)); do_fio(&c__4, (char *)&ioldsd[0], (ftnlen) sizeof(integer)); e_wsfe(); *info = abs(ierr); } } else { temp2 = ulpinv; } } temp1 = max(temp1,temp2); if (ilabad) { io___53.ciunit = *nounit; s_wsfe(&io___53); do_fio(&c__1, (char *)&j, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&n, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&jtype, (ftnlen)sizeof(integer)) ; do_fio(&c__4, (char *)&ioldsd[0], (ftnlen)sizeof( integer)); e_wsfe(); } /* L130: */ } result[rsub + 6] = temp1; if (isort >= 1) { /* Do test 12 */ ntest = 12; result[12] = 0.; knteig = 0; i__3 = n; for (i__ = 1; i__ <= i__3; ++i__) { d__1 = -alphai[i__]; if (dlctes_(&alphar[i__], &alphai[i__], &beta[i__]) || dlctes_(&alphar[i__], &d__1, &beta[i__])) { ++knteig; } if (i__ < n) { d__1 = -alphai[i__ + 1]; d__2 = -alphai[i__]; if ((dlctes_(&alphar[i__ + 1], &alphai[i__ + 1], & beta[i__ + 1]) || dlctes_(&alphar[i__ + 1] , &d__1, &beta[i__ + 1])) && ! (dlctes_(& alphar[i__], &alphai[i__], &beta[i__]) || dlctes_(&alphar[i__], &d__2, &beta[i__])) && iinfo != n + 2) { result[12] = ulpinv; } } /* L140: */ } if (sdim != knteig) { result[12] = ulpinv; } } /* L150: */ } /* End of Loop -- Check for RESULT(j) > THRESH */ L160: ntestt += ntest; /* Print out tests which fail. */ i__3 = ntest; for (jr = 1; jr <= i__3; ++jr) { if (result[jr] >= *thresh) { /* If this is the first test to fail, */ /* print a header to the data file. */ if (nerrs == 0) { io___55.ciunit = *nounit; s_wsfe(&io___55); do_fio(&c__1, "DGS", (ftnlen)3); e_wsfe(); /* Matrix types */ io___56.ciunit = *nounit; s_wsfe(&io___56); e_wsfe(); io___57.ciunit = *nounit; s_wsfe(&io___57); e_wsfe(); io___58.ciunit = *nounit; s_wsfe(&io___58); do_fio(&c__1, "Orthogonal", (ftnlen)10); e_wsfe(); /* Tests performed */ io___59.ciunit = *nounit; s_wsfe(&io___59); do_fio(&c__1, "orthogonal", (ftnlen)10); do_fio(&c__1, "'", (ftnlen)1); do_fio(&c__1, "transpose", (ftnlen)9); for (j = 1; j <= 8; ++j) { do_fio(&c__1, "'", (ftnlen)1); } e_wsfe(); } ++nerrs; if (result[jr] < 1e4) { io___60.ciunit = *nounit; s_wsfe(&io___60); do_fio(&c__1, (char *)&n, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&jtype, (ftnlen)sizeof(integer)) ; do_fio(&c__4, (char *)&ioldsd[0], (ftnlen)sizeof( integer)); do_fio(&c__1, (char *)&jr, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&result[jr], (ftnlen)sizeof( doublereal)); e_wsfe(); } else { io___61.ciunit = *nounit; s_wsfe(&io___61); do_fio(&c__1, (char *)&n, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&jtype, (ftnlen)sizeof(integer)) ; do_fio(&c__4, (char *)&ioldsd[0], (ftnlen)sizeof( integer)); do_fio(&c__1, (char *)&jr, (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&result[jr], (ftnlen)sizeof( doublereal)); e_wsfe(); } } /* L170: */ } L180: ; } /* L190: */ } /* Summary */ alasvm_("DGS", nounit, &nerrs, &ntestt, &c__0); work[1] = (doublereal) maxwrk; return 0; /* End of DDRGES */ } /* ddrges_ */
gpl-3.0
lasting-yang/shadowsocks-android
src/main/jni/openssl/crypto/ec/ecp_nistp256.c
535
64918
/* crypto/ec/ecp_nistp256.c */ /* * Written by Adam Langley (Google) for the OpenSSL project */ /* Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * A 64-bit implementation of the NIST P-256 elliptic curve point multiplication * * OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c. * Otherwise based on Emilia's P224 work, which was inspired by my curve25519 * work which got its smarts from Daniel J. Bernstein's work on the same. */ #include <openssl/opensslconf.h> #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 #ifndef OPENSSL_SYS_VMS #include <stdint.h> #else #include <inttypes.h> #endif #include <string.h> #include <openssl/err.h> #include "ec_lcl.h" #if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) /* even with gcc, the typedef won't work for 32-bit platforms */ typedef __uint128_t uint128_t; /* nonstandard; implemented by gcc on 64-bit platforms */ typedef __int128_t int128_t; #else #error "Need GCC 3.1 or later to define type uint128_t" #endif typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; typedef int64_t s64; /* The underlying field. * * P256 operates over GF(2^256-2^224+2^192+2^96-1). We can serialise an element * of this field into 32 bytes. We call this an felem_bytearray. */ typedef u8 felem_bytearray[32]; /* These are the parameters of P256, taken from FIPS 186-3, page 86. These * values are big-endian. */ static const felem_bytearray nistp256_curve_params[5] = { {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, /* p */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, /* a = -3 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc}, /* b */ {0x5a, 0xc6, 0x35, 0xd8, 0xaa, 0x3a, 0x93, 0xe7, 0xb3, 0xeb, 0xbd, 0x55, 0x76, 0x98, 0x86, 0xbc, 0x65, 0x1d, 0x06, 0xb0, 0xcc, 0x53, 0xb0, 0xf6, 0x3b, 0xce, 0x3c, 0x3e, 0x27, 0xd2, 0x60, 0x4b}, {0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, /* x */ 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4, 0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45, 0xd8, 0x98, 0xc2, 0x96}, {0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, /* y */ 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f, 0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68, 0x37, 0xbf, 0x51, 0xf5} }; /* The representation of field elements. * ------------------------------------ * * We represent field elements with either four 128-bit values, eight 128-bit * values, or four 64-bit values. The field element represented is: * v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + v[3]*2^192 (mod p) * or: * v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + ... + v[8]*2^512 (mod p) * * 128-bit values are called 'limbs'. Since the limbs are spaced only 64 bits * apart, but are 128-bits wide, the most significant bits of each limb overlap * with the least significant bits of the next. * * A field element with four limbs is an 'felem'. One with eight limbs is a * 'longfelem' * * A field element with four, 64-bit values is called a 'smallfelem'. Small * values are used as intermediate values before multiplication. */ #define NLIMBS 4 typedef uint128_t limb; typedef limb felem[NLIMBS]; typedef limb longfelem[NLIMBS * 2]; typedef u64 smallfelem[NLIMBS]; /* This is the value of the prime as four 64-bit words, little-endian. */ static const u64 kPrime[4] = { 0xfffffffffffffffful, 0xffffffff, 0, 0xffffffff00000001ul }; static const limb bottom32bits = 0xffffffff; static const u64 bottom63bits = 0x7ffffffffffffffful; /* bin32_to_felem takes a little-endian byte array and converts it into felem * form. This assumes that the CPU is little-endian. */ static void bin32_to_felem(felem out, const u8 in[32]) { out[0] = *((u64*) &in[0]); out[1] = *((u64*) &in[8]); out[2] = *((u64*) &in[16]); out[3] = *((u64*) &in[24]); } /* smallfelem_to_bin32 takes a smallfelem and serialises into a little endian, * 32 byte array. This assumes that the CPU is little-endian. */ static void smallfelem_to_bin32(u8 out[32], const smallfelem in) { *((u64*) &out[0]) = in[0]; *((u64*) &out[8]) = in[1]; *((u64*) &out[16]) = in[2]; *((u64*) &out[24]) = in[3]; } /* To preserve endianness when using BN_bn2bin and BN_bin2bn */ static void flip_endian(u8 *out, const u8 *in, unsigned len) { unsigned i; for (i = 0; i < len; ++i) out[i] = in[len-1-i]; } /* BN_to_felem converts an OpenSSL BIGNUM into an felem */ static int BN_to_felem(felem out, const BIGNUM *bn) { felem_bytearray b_in; felem_bytearray b_out; unsigned num_bytes; /* BN_bn2bin eats leading zeroes */ memset(b_out, 0, sizeof b_out); num_bytes = BN_num_bytes(bn); if (num_bytes > sizeof b_out) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } if (BN_is_negative(bn)) { ECerr(EC_F_BN_TO_FELEM, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } num_bytes = BN_bn2bin(bn, b_in); flip_endian(b_out, b_in, num_bytes); bin32_to_felem(out, b_out); return 1; } /* felem_to_BN converts an felem into an OpenSSL BIGNUM */ static BIGNUM *smallfelem_to_BN(BIGNUM *out, const smallfelem in) { felem_bytearray b_in, b_out; smallfelem_to_bin32(b_in, in); flip_endian(b_out, b_in, sizeof b_out); return BN_bin2bn(b_out, sizeof b_out, out); } /* Field operations * ---------------- */ static void smallfelem_one(smallfelem out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; } static void smallfelem_assign(smallfelem out, const smallfelem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } static void felem_assign(felem out, const felem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } /* felem_sum sets out = out + in. */ static void felem_sum(felem out, const felem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } /* felem_small_sum sets out = out + in. */ static void felem_small_sum(felem out, const smallfelem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } /* felem_scalar sets out = out * scalar */ static void felem_scalar(felem out, const u64 scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; } /* longfelem_scalar sets out = out * scalar */ static void longfelem_scalar(longfelem out, const u64 scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; } #define two105m41m9 (((limb)1) << 105) - (((limb)1) << 41) - (((limb)1) << 9) #define two105 (((limb)1) << 105) #define two105m41p9 (((limb)1) << 105) - (((limb)1) << 41) + (((limb)1) << 9) /* zero105 is 0 mod p */ static const felem zero105 = { two105m41m9, two105, two105m41p9, two105m41p9 }; /* smallfelem_neg sets |out| to |-small| * On exit: * out[i] < out[i] + 2^105 */ static void smallfelem_neg(felem out, const smallfelem small) { /* In order to prevent underflow, we subtract from 0 mod p. */ out[0] = zero105[0] - small[0]; out[1] = zero105[1] - small[1]; out[2] = zero105[2] - small[2]; out[3] = zero105[3] - small[3]; } /* felem_diff subtracts |in| from |out| * On entry: * in[i] < 2^104 * On exit: * out[i] < out[i] + 2^105 */ static void felem_diff(felem out, const felem in) { /* In order to prevent underflow, we add 0 mod p before subtracting. */ out[0] += zero105[0]; out[1] += zero105[1]; out[2] += zero105[2]; out[3] += zero105[3]; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } #define two107m43m11 (((limb)1) << 107) - (((limb)1) << 43) - (((limb)1) << 11) #define two107 (((limb)1) << 107) #define two107m43p11 (((limb)1) << 107) - (((limb)1) << 43) + (((limb)1) << 11) /* zero107 is 0 mod p */ static const felem zero107 = { two107m43m11, two107, two107m43p11, two107m43p11 }; /* An alternative felem_diff for larger inputs |in| * felem_diff_zero107 subtracts |in| from |out| * On entry: * in[i] < 2^106 * On exit: * out[i] < out[i] + 2^107 */ static void felem_diff_zero107(felem out, const felem in) { /* In order to prevent underflow, we add 0 mod p before subtracting. */ out[0] += zero107[0]; out[1] += zero107[1]; out[2] += zero107[2]; out[3] += zero107[3]; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } /* longfelem_diff subtracts |in| from |out| * On entry: * in[i] < 7*2^67 * On exit: * out[i] < out[i] + 2^70 + 2^40 */ static void longfelem_diff(longfelem out, const longfelem in) { static const limb two70m8p6 = (((limb)1) << 70) - (((limb)1) << 8) + (((limb)1) << 6); static const limb two70p40 = (((limb)1) << 70) + (((limb)1) << 40); static const limb two70 = (((limb)1) << 70); static const limb two70m40m38p6 = (((limb)1) << 70) - (((limb)1) << 40) - (((limb)1) << 38) + (((limb)1) << 6); static const limb two70m6 = (((limb)1) << 70) - (((limb)1) << 6); /* add 0 mod p to avoid underflow */ out[0] += two70m8p6; out[1] += two70p40; out[2] += two70; out[3] += two70m40m38p6; out[4] += two70m6; out[5] += two70m6; out[6] += two70m6; out[7] += two70m6; /* in[i] < 7*2^67 < 2^70 - 2^40 - 2^38 + 2^6 */ out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; out[4] -= in[4]; out[5] -= in[5]; out[6] -= in[6]; out[7] -= in[7]; } #define two64m0 (((limb)1) << 64) - 1 #define two110p32m0 (((limb)1) << 110) + (((limb)1) << 32) - 1 #define two64m46 (((limb)1) << 64) - (((limb)1) << 46) #define two64m32 (((limb)1) << 64) - (((limb)1) << 32) /* zero110 is 0 mod p */ static const felem zero110 = { two64m0, two110p32m0, two64m46, two64m32 }; /* felem_shrink converts an felem into a smallfelem. The result isn't quite * minimal as the value may be greater than p. * * On entry: * in[i] < 2^109 * On exit: * out[i] < 2^64 */ static void felem_shrink(smallfelem out, const felem in) { felem tmp; u64 a, b, mask; s64 high, low; static const u64 kPrime3Test = 0x7fffffff00000001ul; /* 2^63 - 2^32 + 1 */ /* Carry 2->3 */ tmp[3] = zero110[3] + in[3] + ((u64) (in[2] >> 64)); /* tmp[3] < 2^110 */ tmp[2] = zero110[2] + (u64) in[2]; tmp[0] = zero110[0] + in[0]; tmp[1] = zero110[1] + in[1]; /* tmp[0] < 2**110, tmp[1] < 2^111, tmp[2] < 2**65 */ /* We perform two partial reductions where we eliminate the * high-word of tmp[3]. We don't update the other words till the end. */ a = tmp[3] >> 64; /* a < 2^46 */ tmp[3] = (u64) tmp[3]; tmp[3] -= a; tmp[3] += ((limb)a) << 32; /* tmp[3] < 2^79 */ b = a; a = tmp[3] >> 64; /* a < 2^15 */ b += a; /* b < 2^46 + 2^15 < 2^47 */ tmp[3] = (u64) tmp[3]; tmp[3] -= a; tmp[3] += ((limb)a) << 32; /* tmp[3] < 2^64 + 2^47 */ /* This adjusts the other two words to complete the two partial * reductions. */ tmp[0] += b; tmp[1] -= (((limb)b) << 32); /* In order to make space in tmp[3] for the carry from 2 -> 3, we * conditionally subtract kPrime if tmp[3] is large enough. */ high = tmp[3] >> 64; /* As tmp[3] < 2^65, high is either 1 or 0 */ high <<= 63; high >>= 63; /* high is: * all ones if the high word of tmp[3] is 1 * all zeros if the high word of tmp[3] if 0 */ low = tmp[3]; mask = low >> 63; /* mask is: * all ones if the MSB of low is 1 * all zeros if the MSB of low if 0 */ low &= bottom63bits; low -= kPrime3Test; /* if low was greater than kPrime3Test then the MSB is zero */ low = ~low; low >>= 63; /* low is: * all ones if low was > kPrime3Test * all zeros if low was <= kPrime3Test */ mask = (mask & low) | high; tmp[0] -= mask & kPrime[0]; tmp[1] -= mask & kPrime[1]; /* kPrime[2] is zero, so omitted */ tmp[3] -= mask & kPrime[3]; /* tmp[3] < 2**64 - 2**32 + 1 */ tmp[1] += ((u64) (tmp[0] >> 64)); tmp[0] = (u64) tmp[0]; tmp[2] += ((u64) (tmp[1] >> 64)); tmp[1] = (u64) tmp[1]; tmp[3] += ((u64) (tmp[2] >> 64)); tmp[2] = (u64) tmp[2]; /* tmp[i] < 2^64 */ out[0] = tmp[0]; out[1] = tmp[1]; out[2] = tmp[2]; out[3] = tmp[3]; } /* smallfelem_expand converts a smallfelem to an felem */ static void smallfelem_expand(felem out, const smallfelem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } /* smallfelem_square sets |out| = |small|^2 * On entry: * small[i] < 2^64 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void smallfelem_square(longfelem out, const smallfelem small) { limb a; u64 high, low; a = ((uint128_t) small[0]) * small[0]; low = a; high = a >> 64; out[0] = low; out[1] = high; a = ((uint128_t) small[0]) * small[1]; low = a; high = a >> 64; out[1] += low; out[1] += low; out[2] = high; a = ((uint128_t) small[0]) * small[2]; low = a; high = a >> 64; out[2] += low; out[2] *= 2; out[3] = high; a = ((uint128_t) small[0]) * small[3]; low = a; high = a >> 64; out[3] += low; out[4] = high; a = ((uint128_t) small[1]) * small[2]; low = a; high = a >> 64; out[3] += low; out[3] *= 2; out[4] += high; a = ((uint128_t) small[1]) * small[1]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t) small[1]) * small[3]; low = a; high = a >> 64; out[4] += low; out[4] *= 2; out[5] = high; a = ((uint128_t) small[2]) * small[3]; low = a; high = a >> 64; out[5] += low; out[5] *= 2; out[6] = high; out[6] += high; a = ((uint128_t) small[2]) * small[2]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t) small[3]) * small[3]; low = a; high = a >> 64; out[6] += low; out[7] = high; } /* felem_square sets |out| = |in|^2 * On entry: * in[i] < 2^109 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void felem_square(longfelem out, const felem in) { u64 small[4]; felem_shrink(small, in); smallfelem_square(out, small); } /* smallfelem_mul sets |out| = |small1| * |small2| * On entry: * small1[i] < 2^64 * small2[i] < 2^64 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void smallfelem_mul(longfelem out, const smallfelem small1, const smallfelem small2) { limb a; u64 high, low; a = ((uint128_t) small1[0]) * small2[0]; low = a; high = a >> 64; out[0] = low; out[1] = high; a = ((uint128_t) small1[0]) * small2[1]; low = a; high = a >> 64; out[1] += low; out[2] = high; a = ((uint128_t) small1[1]) * small2[0]; low = a; high = a >> 64; out[1] += low; out[2] += high; a = ((uint128_t) small1[0]) * small2[2]; low = a; high = a >> 64; out[2] += low; out[3] = high; a = ((uint128_t) small1[1]) * small2[1]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t) small1[2]) * small2[0]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t) small1[0]) * small2[3]; low = a; high = a >> 64; out[3] += low; out[4] = high; a = ((uint128_t) small1[1]) * small2[2]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t) small1[2]) * small2[1]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t) small1[3]) * small2[0]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t) small1[1]) * small2[3]; low = a; high = a >> 64; out[4] += low; out[5] = high; a = ((uint128_t) small1[2]) * small2[2]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t) small1[3]) * small2[1]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t) small1[2]) * small2[3]; low = a; high = a >> 64; out[5] += low; out[6] = high; a = ((uint128_t) small1[3]) * small2[2]; low = a; high = a >> 64; out[5] += low; out[6] += high; a = ((uint128_t) small1[3]) * small2[3]; low = a; high = a >> 64; out[6] += low; out[7] = high; } /* felem_mul sets |out| = |in1| * |in2| * On entry: * in1[i] < 2^109 * in2[i] < 2^109 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void felem_mul(longfelem out, const felem in1, const felem in2) { smallfelem small1, small2; felem_shrink(small1, in1); felem_shrink(small2, in2); smallfelem_mul(out, small1, small2); } /* felem_small_mul sets |out| = |small1| * |in2| * On entry: * small1[i] < 2^64 * in2[i] < 2^109 * On exit: * out[i] < 7 * 2^64 < 2^67 */ static void felem_small_mul(longfelem out, const smallfelem small1, const felem in2) { smallfelem small2; felem_shrink(small2, in2); smallfelem_mul(out, small1, small2); } #define two100m36m4 (((limb)1) << 100) - (((limb)1) << 36) - (((limb)1) << 4) #define two100 (((limb)1) << 100) #define two100m36p4 (((limb)1) << 100) - (((limb)1) << 36) + (((limb)1) << 4) /* zero100 is 0 mod p */ static const felem zero100 = { two100m36m4, two100, two100m36p4, two100m36p4 }; /* Internal function for the different flavours of felem_reduce. * felem_reduce_ reduces the higher coefficients in[4]-in[7]. * On entry: * out[0] >= in[6] + 2^32*in[6] + in[7] + 2^32*in[7] * out[1] >= in[7] + 2^32*in[4] * out[2] >= in[5] + 2^32*in[5] * out[3] >= in[4] + 2^32*in[5] + 2^32*in[6] * On exit: * out[0] <= out[0] + in[4] + 2^32*in[5] * out[1] <= out[1] + in[5] + 2^33*in[6] * out[2] <= out[2] + in[7] + 2*in[6] + 2^33*in[7] * out[3] <= out[3] + 2^32*in[4] + 3*in[7] */ static void felem_reduce_(felem out, const longfelem in) { int128_t c; /* combine common terms from below */ c = in[4] + (in[5] << 32); out[0] += c; out[3] -= c; c = in[5] - in[7]; out[1] += c; out[2] -= c; /* the remaining terms */ /* 256: [(0,1),(96,-1),(192,-1),(224,1)] */ out[1] -= (in[4] << 32); out[3] += (in[4] << 32); /* 320: [(32,1),(64,1),(128,-1),(160,-1),(224,-1)] */ out[2] -= (in[5] << 32); /* 384: [(0,-1),(32,-1),(96,2),(128,2),(224,-1)] */ out[0] -= in[6]; out[0] -= (in[6] << 32); out[1] += (in[6] << 33); out[2] += (in[6] * 2); out[3] -= (in[6] << 32); /* 448: [(0,-1),(32,-1),(64,-1),(128,1),(160,2),(192,3)] */ out[0] -= in[7]; out[0] -= (in[7] << 32); out[2] += (in[7] << 33); out[3] += (in[7] * 3); } /* felem_reduce converts a longfelem into an felem. * To be called directly after felem_square or felem_mul. * On entry: * in[0] < 2^64, in[1] < 3*2^64, in[2] < 5*2^64, in[3] < 7*2^64 * in[4] < 7*2^64, in[5] < 5*2^64, in[6] < 3*2^64, in[7] < 2*64 * On exit: * out[i] < 2^101 */ static void felem_reduce(felem out, const longfelem in) { out[0] = zero100[0] + in[0]; out[1] = zero100[1] + in[1]; out[2] = zero100[2] + in[2]; out[3] = zero100[3] + in[3]; felem_reduce_(out, in); /* out[0] > 2^100 - 2^36 - 2^4 - 3*2^64 - 3*2^96 - 2^64 - 2^96 > 0 * out[1] > 2^100 - 2^64 - 7*2^96 > 0 * out[2] > 2^100 - 2^36 + 2^4 - 5*2^64 - 5*2^96 > 0 * out[3] > 2^100 - 2^36 + 2^4 - 7*2^64 - 5*2^96 - 3*2^96 > 0 * * out[0] < 2^100 + 2^64 + 7*2^64 + 5*2^96 < 2^101 * out[1] < 2^100 + 3*2^64 + 5*2^64 + 3*2^97 < 2^101 * out[2] < 2^100 + 5*2^64 + 2^64 + 3*2^65 + 2^97 < 2^101 * out[3] < 2^100 + 7*2^64 + 7*2^96 + 3*2^64 < 2^101 */ } /* felem_reduce_zero105 converts a larger longfelem into an felem. * On entry: * in[0] < 2^71 * On exit: * out[i] < 2^106 */ static void felem_reduce_zero105(felem out, const longfelem in) { out[0] = zero105[0] + in[0]; out[1] = zero105[1] + in[1]; out[2] = zero105[2] + in[2]; out[3] = zero105[3] + in[3]; felem_reduce_(out, in); /* out[0] > 2^105 - 2^41 - 2^9 - 2^71 - 2^103 - 2^71 - 2^103 > 0 * out[1] > 2^105 - 2^71 - 2^103 > 0 * out[2] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 > 0 * out[3] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 - 2^103 > 0 * * out[0] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106 * out[1] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106 * out[2] < 2^105 + 2^71 + 2^71 + 2^71 + 2^103 < 2^106 * out[3] < 2^105 + 2^71 + 2^103 + 2^71 < 2^106 */ } /* subtract_u64 sets *result = *result - v and *carry to one if the subtraction * underflowed. */ static void subtract_u64(u64* result, u64* carry, u64 v) { uint128_t r = *result; r -= v; *carry = (r >> 64) & 1; *result = (u64) r; } /* felem_contract converts |in| to its unique, minimal representation. * On entry: * in[i] < 2^109 */ static void felem_contract(smallfelem out, const felem in) { unsigned i; u64 all_equal_so_far = 0, result = 0, carry; felem_shrink(out, in); /* small is minimal except that the value might be > p */ all_equal_so_far--; /* We are doing a constant time test if out >= kPrime. We need to * compare each u64, from most-significant to least significant. For * each one, if all words so far have been equal (m is all ones) then a * non-equal result is the answer. Otherwise we continue. */ for (i = 3; i < 4; i--) { u64 equal; uint128_t a = ((uint128_t) kPrime[i]) - out[i]; /* if out[i] > kPrime[i] then a will underflow and the high * 64-bits will all be set. */ result |= all_equal_so_far & ((u64) (a >> 64)); /* if kPrime[i] == out[i] then |equal| will be all zeros and * the decrement will make it all ones. */ equal = kPrime[i] ^ out[i]; equal--; equal &= equal << 32; equal &= equal << 16; equal &= equal << 8; equal &= equal << 4; equal &= equal << 2; equal &= equal << 1; equal = ((s64) equal) >> 63; all_equal_so_far &= equal; } /* if all_equal_so_far is still all ones then the two values are equal * and so out >= kPrime is true. */ result |= all_equal_so_far; /* if out >= kPrime then we subtract kPrime. */ subtract_u64(&out[0], &carry, result & kPrime[0]); subtract_u64(&out[1], &carry, carry); subtract_u64(&out[2], &carry, carry); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[1], &carry, result & kPrime[1]); subtract_u64(&out[2], &carry, carry); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[2], &carry, result & kPrime[2]); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[3], &carry, result & kPrime[3]); } static void smallfelem_square_contract(smallfelem out, const smallfelem in) { longfelem longtmp; felem tmp; smallfelem_square(longtmp, in); felem_reduce(tmp, longtmp); felem_contract(out, tmp); } static void smallfelem_mul_contract(smallfelem out, const smallfelem in1, const smallfelem in2) { longfelem longtmp; felem tmp; smallfelem_mul(longtmp, in1, in2); felem_reduce(tmp, longtmp); felem_contract(out, tmp); } /* felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0 * otherwise. * On entry: * small[i] < 2^64 */ static limb smallfelem_is_zero(const smallfelem small) { limb result; u64 is_p; u64 is_zero = small[0] | small[1] | small[2] | small[3]; is_zero--; is_zero &= is_zero << 32; is_zero &= is_zero << 16; is_zero &= is_zero << 8; is_zero &= is_zero << 4; is_zero &= is_zero << 2; is_zero &= is_zero << 1; is_zero = ((s64) is_zero) >> 63; is_p = (small[0] ^ kPrime[0]) | (small[1] ^ kPrime[1]) | (small[2] ^ kPrime[2]) | (small[3] ^ kPrime[3]); is_p--; is_p &= is_p << 32; is_p &= is_p << 16; is_p &= is_p << 8; is_p &= is_p << 4; is_p &= is_p << 2; is_p &= is_p << 1; is_p = ((s64) is_p) >> 63; is_zero |= is_p; result = is_zero; result |= ((limb) is_zero) << 64; return result; } static int smallfelem_is_zero_int(const smallfelem small) { return (int) (smallfelem_is_zero(small) & ((limb)1)); } /* felem_inv calculates |out| = |in|^{-1} * * Based on Fermat's Little Theorem: * a^p = a (mod p) * a^{p-1} = 1 (mod p) * a^{p-2} = a^{-1} (mod p) */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2; /* each e_I will hold |in|^{2^I - 1} */ felem e2, e4, e8, e16, e32, e64; longfelem tmp; unsigned i; felem_square(tmp, in); felem_reduce(ftmp, tmp); /* 2^1 */ felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */ felem_assign(e2, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^4 - 2^2 */ felem_mul(tmp, ftmp, e2); felem_reduce(ftmp, tmp); /* 2^4 - 2^0 */ felem_assign(e4, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^5 - 2^1 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^6 - 2^2 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^7 - 2^3 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* 2^8 - 2^4 */ felem_mul(tmp, ftmp, e4); felem_reduce(ftmp, tmp); /* 2^8 - 2^0 */ felem_assign(e8, ftmp); for (i = 0; i < 8; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^16 - 2^8 */ felem_mul(tmp, ftmp, e8); felem_reduce(ftmp, tmp); /* 2^16 - 2^0 */ felem_assign(e16, ftmp); for (i = 0; i < 16; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^32 - 2^16 */ felem_mul(tmp, ftmp, e16); felem_reduce(ftmp, tmp); /* 2^32 - 2^0 */ felem_assign(e32, ftmp); for (i = 0; i < 32; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^64 - 2^32 */ felem_assign(e64, ftmp); felem_mul(tmp, ftmp, in); felem_reduce(ftmp, tmp); /* 2^64 - 2^32 + 2^0 */ for (i = 0; i < 192; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } /* 2^256 - 2^224 + 2^192 */ felem_mul(tmp, e64, e32); felem_reduce(ftmp2, tmp); /* 2^64 - 2^0 */ for (i = 0; i < 16; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } /* 2^80 - 2^16 */ felem_mul(tmp, ftmp2, e16); felem_reduce(ftmp2, tmp); /* 2^80 - 2^0 */ for (i = 0; i < 8; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } /* 2^88 - 2^8 */ felem_mul(tmp, ftmp2, e8); felem_reduce(ftmp2, tmp); /* 2^88 - 2^0 */ for (i = 0; i < 4; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } /* 2^92 - 2^4 */ felem_mul(tmp, ftmp2, e4); felem_reduce(ftmp2, tmp); /* 2^92 - 2^0 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^93 - 2^1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^94 - 2^2 */ felem_mul(tmp, ftmp2, e2); felem_reduce(ftmp2, tmp); /* 2^94 - 2^0 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^95 - 2^1 */ felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); /* 2^96 - 2^2 */ felem_mul(tmp, ftmp2, in); felem_reduce(ftmp2, tmp); /* 2^96 - 3 */ felem_mul(tmp, ftmp2, ftmp); felem_reduce(out, tmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */ } static void smallfelem_inv_contract(smallfelem out, const smallfelem in) { felem tmp; smallfelem_expand(tmp, in); felem_inv(tmp, tmp); felem_contract(out, tmp); } /* Group operations * ---------------- * * Building on top of the field operations we have the operations on the * elliptic curve group itself. Points on the curve are represented in Jacobian * coordinates */ /* point_double calculates 2*(x_in, y_in, z_in) * * The method is taken from: * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b * * Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed. * while x_out == y_in is not (maybe this works, but it's not tested). */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x_in, const felem y_in, const felem z_in) { longfelem tmp, tmp2; felem delta, gamma, beta, alpha, ftmp, ftmp2; smallfelem small1, small2; felem_assign(ftmp, x_in); /* ftmp[i] < 2^106 */ felem_assign(ftmp2, x_in); /* ftmp2[i] < 2^106 */ /* delta = z^2 */ felem_square(tmp, z_in); felem_reduce(delta, tmp); /* delta[i] < 2^101 */ /* gamma = y^2 */ felem_square(tmp, y_in); felem_reduce(gamma, tmp); /* gamma[i] < 2^101 */ felem_shrink(small1, gamma); /* beta = x*gamma */ felem_small_mul(tmp, small1, x_in); felem_reduce(beta, tmp); /* beta[i] < 2^101 */ /* alpha = 3*(x-delta)*(x+delta) */ felem_diff(ftmp, delta); /* ftmp[i] < 2^105 + 2^106 < 2^107 */ felem_sum(ftmp2, delta); /* ftmp2[i] < 2^105 + 2^106 < 2^107 */ felem_scalar(ftmp2, 3); /* ftmp2[i] < 3 * 2^107 < 2^109 */ felem_mul(tmp, ftmp, ftmp2); felem_reduce(alpha, tmp); /* alpha[i] < 2^101 */ felem_shrink(small2, alpha); /* x' = alpha^2 - 8*beta */ smallfelem_square(tmp, small2); felem_reduce(x_out, tmp); felem_assign(ftmp, beta); felem_scalar(ftmp, 8); /* ftmp[i] < 8 * 2^101 = 2^104 */ felem_diff(x_out, ftmp); /* x_out[i] < 2^105 + 2^101 < 2^106 */ /* z' = (y + z)^2 - gamma - delta */ felem_sum(delta, gamma); /* delta[i] < 2^101 + 2^101 = 2^102 */ felem_assign(ftmp, y_in); felem_sum(ftmp, z_in); /* ftmp[i] < 2^106 + 2^106 = 2^107 */ felem_square(tmp, ftmp); felem_reduce(z_out, tmp); felem_diff(z_out, delta); /* z_out[i] < 2^105 + 2^101 < 2^106 */ /* y' = alpha*(4*beta - x') - 8*gamma^2 */ felem_scalar(beta, 4); /* beta[i] < 4 * 2^101 = 2^103 */ felem_diff_zero107(beta, x_out); /* beta[i] < 2^107 + 2^103 < 2^108 */ felem_small_mul(tmp, small2, beta); /* tmp[i] < 7 * 2^64 < 2^67 */ smallfelem_square(tmp2, small1); /* tmp2[i] < 7 * 2^64 */ longfelem_scalar(tmp2, 8); /* tmp2[i] < 8 * 7 * 2^64 = 7 * 2^67 */ longfelem_diff(tmp, tmp2); /* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */ felem_reduce_zero105(y_out, tmp); /* y_out[i] < 2^106 */ } /* point_double_small is the same as point_double, except that it operates on * smallfelems */ static void point_double_small(smallfelem x_out, smallfelem y_out, smallfelem z_out, const smallfelem x_in, const smallfelem y_in, const smallfelem z_in) { felem felem_x_out, felem_y_out, felem_z_out; felem felem_x_in, felem_y_in, felem_z_in; smallfelem_expand(felem_x_in, x_in); smallfelem_expand(felem_y_in, y_in); smallfelem_expand(felem_z_in, z_in); point_double(felem_x_out, felem_y_out, felem_z_out, felem_x_in, felem_y_in, felem_z_in); felem_shrink(x_out, felem_x_out); felem_shrink(y_out, felem_y_out); felem_shrink(z_out, felem_z_out); } /* copy_conditional copies in to out iff mask is all ones. */ static void copy_conditional(felem out, const felem in, limb mask) { unsigned i; for (i = 0; i < NLIMBS; ++i) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } /* copy_small_conditional copies in to out iff mask is all ones. */ static void copy_small_conditional(felem out, const smallfelem in, limb mask) { unsigned i; const u64 mask64 = mask; for (i = 0; i < NLIMBS; ++i) { out[i] = ((limb) (in[i] & mask64)) | (out[i] & ~mask); } } /* point_add calcuates (x1, y1, z1) + (x2, y2, z2) * * The method is taken from: * http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl, * adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity). * * This function includes a branch for checking whether the two input points * are equal, (while not equal to the point at infinity). This case never * happens during single point multiplication, so there is no timing leak for * ECDH or ECDSA signing. */ static void point_add(felem x3, felem y3, felem z3, const felem x1, const felem y1, const felem z1, const int mixed, const smallfelem x2, const smallfelem y2, const smallfelem z2) { felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out; longfelem tmp, tmp2; smallfelem small1, small2, small3, small4, small5; limb x_equal, y_equal, z1_is_zero, z2_is_zero; felem_shrink(small3, z1); z1_is_zero = smallfelem_is_zero(small3); z2_is_zero = smallfelem_is_zero(z2); /* ftmp = z1z1 = z1**2 */ smallfelem_square(tmp, small3); felem_reduce(ftmp, tmp); /* ftmp[i] < 2^101 */ felem_shrink(small1, ftmp); if(!mixed) { /* ftmp2 = z2z2 = z2**2 */ smallfelem_square(tmp, z2); felem_reduce(ftmp2, tmp); /* ftmp2[i] < 2^101 */ felem_shrink(small2, ftmp2); felem_shrink(small5, x1); /* u1 = ftmp3 = x1*z2z2 */ smallfelem_mul(tmp, small5, small2); felem_reduce(ftmp3, tmp); /* ftmp3[i] < 2^101 */ /* ftmp5 = z1 + z2 */ felem_assign(ftmp5, z1); felem_small_sum(ftmp5, z2); /* ftmp5[i] < 2^107 */ /* ftmp5 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 */ felem_square(tmp, ftmp5); felem_reduce(ftmp5, tmp); /* ftmp2 = z2z2 + z1z1 */ felem_sum(ftmp2, ftmp); /* ftmp2[i] < 2^101 + 2^101 = 2^102 */ felem_diff(ftmp5, ftmp2); /* ftmp5[i] < 2^105 + 2^101 < 2^106 */ /* ftmp2 = z2 * z2z2 */ smallfelem_mul(tmp, small2, z2); felem_reduce(ftmp2, tmp); /* s1 = ftmp2 = y1 * z2**3 */ felem_mul(tmp, y1, ftmp2); felem_reduce(ftmp6, tmp); /* ftmp6[i] < 2^101 */ } else { /* We'll assume z2 = 1 (special case z2 = 0 is handled later) */ /* u1 = ftmp3 = x1*z2z2 */ felem_assign(ftmp3, x1); /* ftmp3[i] < 2^106 */ /* ftmp5 = 2z1z2 */ felem_assign(ftmp5, z1); felem_scalar(ftmp5, 2); /* ftmp5[i] < 2*2^106 = 2^107 */ /* s1 = ftmp2 = y1 * z2**3 */ felem_assign(ftmp6, y1); /* ftmp6[i] < 2^106 */ } /* u2 = x2*z1z1 */ smallfelem_mul(tmp, x2, small1); felem_reduce(ftmp4, tmp); /* h = ftmp4 = u2 - u1 */ felem_diff_zero107(ftmp4, ftmp3); /* ftmp4[i] < 2^107 + 2^101 < 2^108 */ felem_shrink(small4, ftmp4); x_equal = smallfelem_is_zero(small4); /* z_out = ftmp5 * h */ felem_small_mul(tmp, small4, ftmp5); felem_reduce(z_out, tmp); /* z_out[i] < 2^101 */ /* ftmp = z1 * z1z1 */ smallfelem_mul(tmp, small1, small3); felem_reduce(ftmp, tmp); /* s2 = tmp = y2 * z1**3 */ felem_small_mul(tmp, y2, ftmp); felem_reduce(ftmp5, tmp); /* r = ftmp5 = (s2 - s1)*2 */ felem_diff_zero107(ftmp5, ftmp6); /* ftmp5[i] < 2^107 + 2^107 = 2^108*/ felem_scalar(ftmp5, 2); /* ftmp5[i] < 2^109 */ felem_shrink(small1, ftmp5); y_equal = smallfelem_is_zero(small1); if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { point_double(x3, y3, z3, x1, y1, z1); return; } /* I = ftmp = (2h)**2 */ felem_assign(ftmp, ftmp4); felem_scalar(ftmp, 2); /* ftmp[i] < 2*2^108 = 2^109 */ felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); /* J = ftmp2 = h * I */ felem_mul(tmp, ftmp4, ftmp); felem_reduce(ftmp2, tmp); /* V = ftmp4 = U1 * I */ felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); /* x_out = r**2 - J - 2V */ smallfelem_square(tmp, small1); felem_reduce(x_out, tmp); felem_assign(ftmp3, ftmp4); felem_scalar(ftmp4, 2); felem_sum(ftmp4, ftmp2); /* ftmp4[i] < 2*2^101 + 2^101 < 2^103 */ felem_diff(x_out, ftmp4); /* x_out[i] < 2^105 + 2^101 */ /* y_out = r(V-x_out) - 2 * s1 * J */ felem_diff_zero107(ftmp3, x_out); /* ftmp3[i] < 2^107 + 2^101 < 2^108 */ felem_small_mul(tmp, small1, ftmp3); felem_mul(tmp2, ftmp6, ftmp2); longfelem_scalar(tmp2, 2); /* tmp2[i] < 2*2^67 = 2^68 */ longfelem_diff(tmp, tmp2); /* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */ felem_reduce_zero105(y_out, tmp); /* y_out[i] < 2^106 */ copy_small_conditional(x_out, x2, z1_is_zero); copy_conditional(x_out, x1, z2_is_zero); copy_small_conditional(y_out, y2, z1_is_zero); copy_conditional(y_out, y1, z2_is_zero); copy_small_conditional(z_out, z2, z1_is_zero); copy_conditional(z_out, z1, z2_is_zero); felem_assign(x3, x_out); felem_assign(y3, y_out); felem_assign(z3, z_out); } /* point_add_small is the same as point_add, except that it operates on * smallfelems */ static void point_add_small(smallfelem x3, smallfelem y3, smallfelem z3, smallfelem x1, smallfelem y1, smallfelem z1, smallfelem x2, smallfelem y2, smallfelem z2) { felem felem_x3, felem_y3, felem_z3; felem felem_x1, felem_y1, felem_z1; smallfelem_expand(felem_x1, x1); smallfelem_expand(felem_y1, y1); smallfelem_expand(felem_z1, z1); point_add(felem_x3, felem_y3, felem_z3, felem_x1, felem_y1, felem_z1, 0, x2, y2, z2); felem_shrink(x3, felem_x3); felem_shrink(y3, felem_y3); felem_shrink(z3, felem_z3); } /* Base point pre computation * -------------------------- * * Two different sorts of precomputed tables are used in the following code. * Each contain various points on the curve, where each point is three field * elements (x, y, z). * * For the base point table, z is usually 1 (0 for the point at infinity). * This table has 2 * 16 elements, starting with the following: * index | bits | point * ------+---------+------------------------------ * 0 | 0 0 0 0 | 0G * 1 | 0 0 0 1 | 1G * 2 | 0 0 1 0 | 2^64G * 3 | 0 0 1 1 | (2^64 + 1)G * 4 | 0 1 0 0 | 2^128G * 5 | 0 1 0 1 | (2^128 + 1)G * 6 | 0 1 1 0 | (2^128 + 2^64)G * 7 | 0 1 1 1 | (2^128 + 2^64 + 1)G * 8 | 1 0 0 0 | 2^192G * 9 | 1 0 0 1 | (2^192 + 1)G * 10 | 1 0 1 0 | (2^192 + 2^64)G * 11 | 1 0 1 1 | (2^192 + 2^64 + 1)G * 12 | 1 1 0 0 | (2^192 + 2^128)G * 13 | 1 1 0 1 | (2^192 + 2^128 + 1)G * 14 | 1 1 1 0 | (2^192 + 2^128 + 2^64)G * 15 | 1 1 1 1 | (2^192 + 2^128 + 2^64 + 1)G * followed by a copy of this with each element multiplied by 2^32. * * The reason for this is so that we can clock bits into four different * locations when doing simple scalar multiplies against the base point, * and then another four locations using the second 16 elements. * * Tables for other points have table[i] = iG for i in 0 .. 16. */ /* gmul is the table of precomputed base points */ static const smallfelem gmul[2][16][3] = {{{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0xf4a13945d898c296, 0x77037d812deb33a0, 0xf8bce6e563a440f2, 0x6b17d1f2e12c4247}, {0xcbb6406837bf51f5, 0x2bce33576b315ece, 0x8ee7eb4a7c0f9e16, 0x4fe342e2fe1a7f9b}, {1, 0, 0, 0}}, {{0x90e75cb48e14db63, 0x29493baaad651f7e, 0x8492592e326e25de, 0x0fa822bc2811aaa5}, {0xe41124545f462ee7, 0x34b1a65050fe82f5, 0x6f4ad4bcb3df188b, 0xbff44ae8f5dba80d}, {1, 0, 0, 0}}, {{0x93391ce2097992af, 0xe96c98fd0d35f1fa, 0xb257c0de95e02789, 0x300a4bbc89d6726f}, {0xaa54a291c08127a0, 0x5bb1eeada9d806a5, 0x7f1ddb25ff1e3c6f, 0x72aac7e0d09b4644}, {1, 0, 0, 0}}, {{0x57c84fc9d789bd85, 0xfc35ff7dc297eac3, 0xfb982fd588c6766e, 0x447d739beedb5e67}, {0x0c7e33c972e25b32, 0x3d349b95a7fae500, 0xe12e9d953a4aaff7, 0x2d4825ab834131ee}, {1, 0, 0, 0}}, {{0x13949c932a1d367f, 0xef7fbd2b1a0a11b7, 0xddc6068bb91dfc60, 0xef9519328a9c72ff}, {0x196035a77376d8a8, 0x23183b0895ca1740, 0xc1ee9807022c219c, 0x611e9fc37dbb2c9b}, {1, 0, 0, 0}}, {{0xcae2b1920b57f4bc, 0x2936df5ec6c9bc36, 0x7dea6482e11238bf, 0x550663797b51f5d8}, {0x44ffe216348a964c, 0x9fb3d576dbdefbe1, 0x0afa40018d9d50e5, 0x157164848aecb851}, {1, 0, 0, 0}}, {{0xe48ecafffc5cde01, 0x7ccd84e70d715f26, 0xa2e8f483f43e4391, 0xeb5d7745b21141ea}, {0xcac917e2731a3479, 0x85f22cfe2844b645, 0x0990e6a158006cee, 0xeafd72ebdbecc17b}, {1, 0, 0, 0}}, {{0x6cf20ffb313728be, 0x96439591a3c6b94a, 0x2736ff8344315fc5, 0xa6d39677a7849276}, {0xf2bab833c357f5f4, 0x824a920c2284059b, 0x66b8babd2d27ecdf, 0x674f84749b0b8816}, {1, 0, 0, 0}}, {{0x2df48c04677c8a3e, 0x74e02f080203a56b, 0x31855f7db8c7fedb, 0x4e769e7672c9ddad}, {0xa4c36165b824bbb0, 0xfb9ae16f3b9122a5, 0x1ec0057206947281, 0x42b99082de830663}, {1, 0, 0, 0}}, {{0x6ef95150dda868b9, 0xd1f89e799c0ce131, 0x7fdc1ca008a1c478, 0x78878ef61c6ce04d}, {0x9c62b9121fe0d976, 0x6ace570ebde08d4f, 0xde53142c12309def, 0xb6cb3f5d7b72c321}, {1, 0, 0, 0}}, {{0x7f991ed2c31a3573, 0x5b82dd5bd54fb496, 0x595c5220812ffcae, 0x0c88bc4d716b1287}, {0x3a57bf635f48aca8, 0x7c8181f4df2564f3, 0x18d1b5b39c04e6aa, 0xdd5ddea3f3901dc6}, {1, 0, 0, 0}}, {{0xe96a79fb3e72ad0c, 0x43a0a28c42ba792f, 0xefe0a423083e49f3, 0x68f344af6b317466}, {0xcdfe17db3fb24d4a, 0x668bfc2271f5c626, 0x604ed93c24d67ff3, 0x31b9c405f8540a20}, {1, 0, 0, 0}}, {{0xd36b4789a2582e7f, 0x0d1a10144ec39c28, 0x663c62c3edbad7a0, 0x4052bf4b6f461db9}, {0x235a27c3188d25eb, 0xe724f33999bfcc5b, 0x862be6bd71d70cc8, 0xfecf4d5190b0fc61}, {1, 0, 0, 0}}, {{0x74346c10a1d4cfac, 0xafdf5cc08526a7a4, 0x123202a8f62bff7a, 0x1eddbae2c802e41a}, {0x8fa0af2dd603f844, 0x36e06b7e4c701917, 0x0c45f45273db33a0, 0x43104d86560ebcfc}, {1, 0, 0, 0}}, {{0x9615b5110d1d78e5, 0x66b0de3225c4744b, 0x0a4a46fb6aaf363a, 0xb48e26b484f7a21c}, {0x06ebb0f621a01b2d, 0xc004e4048b7b0f98, 0x64131bcdfed6f668, 0xfac015404d4d3dab}, {1, 0, 0, 0}}}, {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0x3a5a9e22185a5943, 0x1ab919365c65dfb6, 0x21656b32262c71da, 0x7fe36b40af22af89}, {0xd50d152c699ca101, 0x74b3d5867b8af212, 0x9f09f40407dca6f1, 0xe697d45825b63624}, {1, 0, 0, 0}}, {{0xa84aa9397512218e, 0xe9a521b074ca0141, 0x57880b3a18a2e902, 0x4a5b506612a677a6}, {0x0beada7a4c4f3840, 0x626db15419e26d9d, 0xc42604fbe1627d40, 0xeb13461ceac089f1}, {1, 0, 0, 0}}, {{0xf9faed0927a43281, 0x5e52c4144103ecbc, 0xc342967aa815c857, 0x0781b8291c6a220a}, {0x5a8343ceeac55f80, 0x88f80eeee54a05e3, 0x97b2a14f12916434, 0x690cde8df0151593}, {1, 0, 0, 0}}, {{0xaee9c75df7f82f2a, 0x9e4c35874afdf43a, 0xf5622df437371326, 0x8a535f566ec73617}, {0xc5f9a0ac223094b7, 0xcde533864c8c7669, 0x37e02819085a92bf, 0x0455c08468b08bd7}, {1, 0, 0, 0}}, {{0x0c0a6e2c9477b5d9, 0xf9a4bf62876dc444, 0x5050a949b6cdc279, 0x06bada7ab77f8276}, {0xc8b4aed1ea48dac9, 0xdebd8a4b7ea1070f, 0x427d49101366eb70, 0x5b476dfd0e6cb18a}, {1, 0, 0, 0}}, {{0x7c5c3e44278c340a, 0x4d54606812d66f3b, 0x29a751b1ae23c5d8, 0x3e29864e8a2ec908}, {0x142d2a6626dbb850, 0xad1744c4765bd780, 0x1f150e68e322d1ed, 0x239b90ea3dc31e7e}, {1, 0, 0, 0}}, {{0x78c416527a53322a, 0x305dde6709776f8e, 0xdbcab759f8862ed4, 0x820f4dd949f72ff7}, {0x6cc544a62b5debd4, 0x75be5d937b4e8cc4, 0x1b481b1b215c14d3, 0x140406ec783a05ec}, {1, 0, 0, 0}}, {{0x6a703f10e895df07, 0xfd75f3fa01876bd8, 0xeb5b06e70ce08ffe, 0x68f6b8542783dfee}, {0x90c76f8a78712655, 0xcf5293d2f310bf7f, 0xfbc8044dfda45028, 0xcbe1feba92e40ce6}, {1, 0, 0, 0}}, {{0xe998ceea4396e4c1, 0xfc82ef0b6acea274, 0x230f729f2250e927, 0xd0b2f94d2f420109}, {0x4305adddb38d4966, 0x10b838f8624c3b45, 0x7db2636658954e7a, 0x971459828b0719e5}, {1, 0, 0, 0}}, {{0x4bd6b72623369fc9, 0x57f2929e53d0b876, 0xc2d5cba4f2340687, 0x961610004a866aba}, {0x49997bcd2e407a5e, 0x69ab197d92ddcb24, 0x2cf1f2438fe5131c, 0x7acb9fadcee75e44}, {1, 0, 0, 0}}, {{0x254e839423d2d4c0, 0xf57f0c917aea685b, 0xa60d880f6f75aaea, 0x24eb9acca333bf5b}, {0xe3de4ccb1cda5dea, 0xfeef9341c51a6b4f, 0x743125f88bac4c4d, 0x69f891c5acd079cc}, {1, 0, 0, 0}}, {{0xeee44b35702476b5, 0x7ed031a0e45c2258, 0xb422d1e7bd6f8514, 0xe51f547c5972a107}, {0xa25bcd6fc9cf343d, 0x8ca922ee097c184e, 0xa62f98b3a9fe9a06, 0x1c309a2b25bb1387}, {1, 0, 0, 0}}, {{0x9295dbeb1967c459, 0xb00148833472c98e, 0xc504977708011828, 0x20b87b8aa2c4e503}, {0x3063175de057c277, 0x1bd539338fe582dd, 0x0d11adef5f69a044, 0xf5c6fa49919776be}, {1, 0, 0, 0}}, {{0x8c944e760fd59e11, 0x3876cba1102fad5f, 0xa454c3fad83faa56, 0x1ed7d1b9332010b9}, {0xa1011a270024b889, 0x05e4d0dcac0cd344, 0x52b520f0eb6a2a24, 0x3a2b03f03217257a}, {1, 0, 0, 0}}, {{0xf20fc2afdf1d043d, 0xf330240db58d5a62, 0xfc7d229ca0058c3b, 0x15fee545c78dd9f6}, {0x501e82885bc98cda, 0x41ef80e5d046ac04, 0x557d9f49461210fb, 0x4ab5b6b2b8753f81}, {1, 0, 0, 0}}}}; /* select_point selects the |idx|th point from a precomputation table and * copies it to out. */ static void select_point(const u64 idx, unsigned int size, const smallfelem pre_comp[16][3], smallfelem out[3]) { unsigned i, j; u64 *outlimbs = &out[0][0]; memset(outlimbs, 0, 3 * sizeof(smallfelem)); for (i = 0; i < size; i++) { const u64 *inlimbs = (u64*) &pre_comp[i][0][0]; u64 mask = i ^ idx; mask |= mask >> 4; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS * 3; j++) outlimbs[j] |= inlimbs[j] & mask; } } /* get_bit returns the |i|th bit in |in| */ static char get_bit(const felem_bytearray in, int i) { if ((i < 0) || (i >= 256)) return 0; return (in[i >> 3] >> (i & 7)) & 1; } /* Interleaved point multiplication using precomputed point multiples: * The small point multiples 0*P, 1*P, ..., 17*P are in pre_comp[], * the scalars in scalars[]. If g_scalar is non-NULL, we also add this multiple * of the generator, using certain (large) precomputed multiples in g_pre_comp. * Output point (X, Y, Z) is stored in x_out, y_out, z_out */ static void batch_mul(felem x_out, felem y_out, felem z_out, const felem_bytearray scalars[], const unsigned num_points, const u8 *g_scalar, const int mixed, const smallfelem pre_comp[][17][3], const smallfelem g_pre_comp[2][16][3]) { int i, skip; unsigned num, gen_mul = (g_scalar != NULL); felem nq[3], ftmp; smallfelem tmp[3]; u64 bits; u8 sign, digit; /* set nq to the point at infinity */ memset(nq, 0, 3 * sizeof(felem)); /* Loop over all scalars msb-to-lsb, interleaving additions * of multiples of the generator (two in each of the last 32 rounds) * and additions of other points multiples (every 5th round). */ skip = 1; /* save two point operations in the first round */ for (i = (num_points ? 255 : 31); i >= 0; --i) { /* double */ if (!skip) point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); /* add multiples of the generator */ if (gen_mul && (i <= 31)) { /* first, look 32 bits upwards */ bits = get_bit(g_scalar, i + 224) << 3; bits |= get_bit(g_scalar, i + 160) << 2; bits |= get_bit(g_scalar, i + 96) << 1; bits |= get_bit(g_scalar, i + 32); /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp[1], tmp); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], tmp[1], tmp[2]); } else { smallfelem_expand(nq[0], tmp[0]); smallfelem_expand(nq[1], tmp[1]); smallfelem_expand(nq[2], tmp[2]); skip = 0; } /* second, look at the current position */ bits = get_bit(g_scalar, i + 192) << 3; bits |= get_bit(g_scalar, i + 128) << 2; bits |= get_bit(g_scalar, i + 64) << 1; bits |= get_bit(g_scalar, i); /* select the point to add, in constant time */ select_point(bits, 16, g_pre_comp[0], tmp); point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], tmp[1], tmp[2]); } /* do other additions every 5 doublings */ if (num_points && (i % 5 == 0)) { /* loop over all scalars */ for (num = 0; num < num_points; ++num) { bits = get_bit(scalars[num], i + 4) << 5; bits |= get_bit(scalars[num], i + 3) << 4; bits |= get_bit(scalars[num], i + 2) << 3; bits |= get_bit(scalars[num], i + 1) << 2; bits |= get_bit(scalars[num], i) << 1; bits |= get_bit(scalars[num], i - 1); ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); /* select the point to add or subtract, in constant time */ select_point(digit, 17, pre_comp[num], tmp); smallfelem_neg(ftmp, tmp[1]); /* (X, -Y, Z) is the negative point */ copy_small_conditional(ftmp, tmp[1], (((limb) sign) - 1)); felem_contract(tmp[1], ftmp); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], mixed, tmp[0], tmp[1], tmp[2]); } else { smallfelem_expand(nq[0], tmp[0]); smallfelem_expand(nq[1], tmp[1]); smallfelem_expand(nq[2], tmp[2]); skip = 0; } } } } felem_assign(x_out, nq[0]); felem_assign(y_out, nq[1]); felem_assign(z_out, nq[2]); } /* Precomputation for the group generator. */ typedef struct { smallfelem g_pre_comp[2][16][3]; int references; } NISTP256_PRE_COMP; const EC_METHOD *EC_GFp_nistp256_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_nistp256_group_init, ec_GFp_simple_group_finish, ec_GFp_simple_group_clear_finish, ec_GFp_nist_group_copy, ec_GFp_nistp256_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_nistp256_point_get_affine_coordinates, 0 /* point_set_compressed_coordinates */, 0 /* point2oct */, 0 /* oct2point */, ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, ec_GFp_nistp256_points_mul, ec_GFp_nistp256_precompute_mult, ec_GFp_nistp256_have_precompute_mult, ec_GFp_nist_field_mul, ec_GFp_nist_field_sqr, 0 /* field_div */, 0 /* field_encode */, 0 /* field_decode */, 0 /* field_set_to_one */ }; return &ret; } /******************************************************************************/ /* FUNCTIONS TO MANAGE PRECOMPUTATION */ static NISTP256_PRE_COMP *nistp256_pre_comp_new() { NISTP256_PRE_COMP *ret = NULL; ret = (NISTP256_PRE_COMP *) OPENSSL_malloc(sizeof *ret); if (!ret) { ECerr(EC_F_NISTP256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE); return ret; } memset(ret->g_pre_comp, 0, sizeof(ret->g_pre_comp)); ret->references = 1; return ret; } static void *nistp256_pre_comp_dup(void *src_) { NISTP256_PRE_COMP *src = src_; /* no need to actually copy, these objects never change! */ CRYPTO_add(&src->references, 1, CRYPTO_LOCK_EC_PRE_COMP); return src_; } static void nistp256_pre_comp_free(void *pre_) { int i; NISTP256_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_free(pre); } static void nistp256_pre_comp_clear_free(void *pre_) { int i; NISTP256_PRE_COMP *pre = pre_; if (!pre) return; i = CRYPTO_add(&pre->references, -1, CRYPTO_LOCK_EC_PRE_COMP); if (i > 0) return; OPENSSL_cleanse(pre, sizeof *pre); OPENSSL_free(pre); } /******************************************************************************/ /* OPENSSL EC_METHOD FUNCTIONS */ int ec_GFp_nistp256_group_init(EC_GROUP *group) { int ret; ret = ec_GFp_simple_group_init(group); group->a_is_minus3 = 1; return ret; } int ec_GFp_nistp256_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; BIGNUM *curve_p, *curve_a, *curve_b; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((curve_p = BN_CTX_get(ctx)) == NULL) || ((curve_a = BN_CTX_get(ctx)) == NULL) || ((curve_b = BN_CTX_get(ctx)) == NULL)) goto err; BN_bin2bn(nistp256_curve_params[0], sizeof(felem_bytearray), curve_p); BN_bin2bn(nistp256_curve_params[1], sizeof(felem_bytearray), curve_a); BN_bin2bn(nistp256_curve_params[2], sizeof(felem_bytearray), curve_b); if ((BN_cmp(curve_p, p)) || (BN_cmp(curve_a, a)) || (BN_cmp(curve_b, b))) { ECerr(EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE, EC_R_WRONG_CURVE_PARAMETERS); goto err; } group->field_mod_func = BN_nist_mod_256; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); err: BN_CTX_end(ctx); if (new_ctx != NULL) BN_CTX_free(new_ctx); return ret; } /* Takes the Jacobian coordinates (X, Y, Z) of a point and returns * (X', Y') = (X/Z^2, Y/Z^3) */ int ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { felem z1, z2, x_in, y_in; smallfelem x_out, y_out; longfelem tmp; if (EC_POINT_is_at_infinity(group, point)) { ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, EC_R_POINT_AT_INFINITY); return 0; } if ((!BN_to_felem(x_in, &point->X)) || (!BN_to_felem(y_in, &point->Y)) || (!BN_to_felem(z1, &point->Z))) return 0; felem_inv(z2, z1); felem_square(tmp, z2); felem_reduce(z1, tmp); felem_mul(tmp, x_in, z1); felem_reduce(x_in, tmp); felem_contract(x_out, x_in); if (x != NULL) { if (!smallfelem_to_BN(x, x_out)) { ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } felem_mul(tmp, z1, z2); felem_reduce(z1, tmp); felem_mul(tmp, y_in, z1); felem_reduce(y_in, tmp); felem_contract(y_out, y_in); if (y != NULL) { if (!smallfelem_to_BN(y, y_out)) { ECerr(EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES, ERR_R_BN_LIB); return 0; } } return 1; } static void make_points_affine(size_t num, smallfelem points[/* num */][3], smallfelem tmp_smallfelems[/* num+1 */]) { /* Runs in constant time, unless an input is the point at infinity * (which normally shouldn't happen). */ ec_GFp_nistp_points_make_affine_internal( num, points, sizeof(smallfelem), tmp_smallfelems, (void (*)(void *)) smallfelem_one, (int (*)(const void *)) smallfelem_is_zero_int, (void (*)(void *, const void *)) smallfelem_assign, (void (*)(void *, const void *)) smallfelem_square_contract, (void (*)(void *, const void *, const void *)) smallfelem_mul_contract, (void (*)(void *, const void *)) smallfelem_inv_contract, (void (*)(void *, const void *)) smallfelem_assign /* nothing to contract */); } /* Computes scalar*generator + \sum scalars[i]*points[i], ignoring NULL values * Result is stored in r (r can equal one of the inputs). */ int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, size_t num, const EC_POINT *points[], const BIGNUM *scalars[], BN_CTX *ctx) { int ret = 0; int j; int mixed = 0; BN_CTX *new_ctx = NULL; BIGNUM *x, *y, *z, *tmp_scalar; felem_bytearray g_secret; felem_bytearray *secrets = NULL; smallfelem (*pre_comp)[17][3] = NULL; smallfelem *tmp_smallfelems = NULL; felem_bytearray tmp; unsigned i, num_bytes; int have_pre_comp = 0; size_t num_points = num; smallfelem x_in, y_in, z_in; felem x_out, y_out, z_out; NISTP256_PRE_COMP *pre = NULL; const smallfelem (*g_pre_comp)[16][3] = NULL; EC_POINT *generator = NULL; const EC_POINT *p = NULL; const BIGNUM *p_scalar = NULL; if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL) || ((z = BN_CTX_get(ctx)) == NULL) || ((tmp_scalar = BN_CTX_get(ctx)) == NULL)) goto err; if (scalar != NULL) { pre = EC_EX_DATA_get_data(group->extra_data, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free); if (pre) /* we have precomputation, try to use it */ g_pre_comp = (const smallfelem (*)[16][3]) pre->g_pre_comp; else /* try to use the standard precomputation */ g_pre_comp = &gmul[0]; generator = EC_POINT_new(group); if (generator == NULL) goto err; /* get the generator from precomputation */ if (!smallfelem_to_BN(x, g_pre_comp[0][1][0]) || !smallfelem_to_BN(y, g_pre_comp[0][1][1]) || !smallfelem_to_BN(z, g_pre_comp[0][1][2])) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } if (!EC_POINT_set_Jprojective_coordinates_GFp(group, generator, x, y, z, ctx)) goto err; if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) /* precomputation matches generator */ have_pre_comp = 1; else /* we don't have valid precomputation: * treat the generator as a random point */ num_points++; } if (num_points > 0) { if (num_points >= 3) { /* unless we precompute multiples for just one or two points, * converting those into affine form is time well spent */ mixed = 1; } secrets = OPENSSL_malloc(num_points * sizeof(felem_bytearray)); pre_comp = OPENSSL_malloc(num_points * 17 * 3 * sizeof(smallfelem)); if (mixed) tmp_smallfelems = OPENSSL_malloc((num_points * 17 + 1) * sizeof(smallfelem)); if ((secrets == NULL) || (pre_comp == NULL) || (mixed && (tmp_smallfelems == NULL))) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_MALLOC_FAILURE); goto err; } /* we treat NULL scalars as 0, and NULL points as points at infinity, * i.e., they contribute nothing to the linear combination */ memset(secrets, 0, num_points * sizeof(felem_bytearray)); memset(pre_comp, 0, num_points * 17 * 3 * sizeof(smallfelem)); for (i = 0; i < num_points; ++i) { if (i == num) /* we didn't have a valid precomputation, so we pick * the generator */ { p = EC_GROUP_get0_generator(group); p_scalar = scalar; } else /* the i^th point */ { p = points[i]; p_scalar = scalars[i]; } if ((p_scalar != NULL) && (p != NULL)) { /* reduce scalar to 0 <= scalar < 2^256 */ if ((BN_num_bits(p_scalar) > 256) || (BN_is_negative(p_scalar))) { /* this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(p_scalar, tmp); flip_endian(secrets[i], tmp, num_bytes); /* precompute multiples */ if ((!BN_to_felem(x_out, &p->X)) || (!BN_to_felem(y_out, &p->Y)) || (!BN_to_felem(z_out, &p->Z))) goto err; felem_shrink(pre_comp[i][1][0], x_out); felem_shrink(pre_comp[i][1][1], y_out); felem_shrink(pre_comp[i][1][2], z_out); for (j = 2; j <= 16; ++j) { if (j & 1) { point_add_small( pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][1][0], pre_comp[i][1][1], pre_comp[i][1][2], pre_comp[i][j-1][0], pre_comp[i][j-1][1], pre_comp[i][j-1][2]); } else { point_double_small( pre_comp[i][j][0], pre_comp[i][j][1], pre_comp[i][j][2], pre_comp[i][j/2][0], pre_comp[i][j/2][1], pre_comp[i][j/2][2]); } } } } if (mixed) make_points_affine(num_points * 17, pre_comp[0], tmp_smallfelems); } /* the scalar for the generator */ if ((scalar != NULL) && (have_pre_comp)) { memset(g_secret, 0, sizeof(g_secret)); /* reduce scalar to 0 <= scalar < 2^256 */ if ((BN_num_bits(scalar) > 256) || (BN_is_negative(scalar))) { /* this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(tmp_scalar, scalar, &group->order, ctx)) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } num_bytes = BN_bn2bin(tmp_scalar, tmp); } else num_bytes = BN_bn2bin(scalar, tmp); flip_endian(g_secret, tmp, num_bytes); /* do the multiplication with generator precomputation*/ batch_mul(x_out, y_out, z_out, (const felem_bytearray (*)) secrets, num_points, g_secret, mixed, (const smallfelem (*)[17][3]) pre_comp, g_pre_comp); } else /* do the multiplication without generator precomputation */ batch_mul(x_out, y_out, z_out, (const felem_bytearray (*)) secrets, num_points, NULL, mixed, (const smallfelem (*)[17][3]) pre_comp, NULL); /* reduce the output to its unique minimal representation */ felem_contract(x_in, x_out); felem_contract(y_in, y_out); felem_contract(z_in, z_out); if ((!smallfelem_to_BN(x, x_in)) || (!smallfelem_to_BN(y, y_in)) || (!smallfelem_to_BN(z, z_in))) { ECerr(EC_F_EC_GFP_NISTP256_POINTS_MUL, ERR_R_BN_LIB); goto err; } ret = EC_POINT_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx); err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (secrets != NULL) OPENSSL_free(secrets); if (pre_comp != NULL) OPENSSL_free(pre_comp); if (tmp_smallfelems != NULL) OPENSSL_free(tmp_smallfelems); return ret; } int ec_GFp_nistp256_precompute_mult(EC_GROUP *group, BN_CTX *ctx) { int ret = 0; NISTP256_PRE_COMP *pre = NULL; int i, j; BN_CTX *new_ctx = NULL; BIGNUM *x, *y; EC_POINT *generator = NULL; smallfelem tmp_smallfelems[32]; felem x_tmp, y_tmp, z_tmp; /* throw away old precomputation */ EC_EX_DATA_free_data(&group->extra_data, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free); if (ctx == NULL) if ((ctx = new_ctx = BN_CTX_new()) == NULL) return 0; BN_CTX_start(ctx); if (((x = BN_CTX_get(ctx)) == NULL) || ((y = BN_CTX_get(ctx)) == NULL)) goto err; /* get the generator */ if (group->generator == NULL) goto err; generator = EC_POINT_new(group); if (generator == NULL) goto err; BN_bin2bn(nistp256_curve_params[3], sizeof (felem_bytearray), x); BN_bin2bn(nistp256_curve_params[4], sizeof (felem_bytearray), y); if (!EC_POINT_set_affine_coordinates_GFp(group, generator, x, y, ctx)) goto err; if ((pre = nistp256_pre_comp_new()) == NULL) goto err; /* if the generator is the standard one, use built-in precomputation */ if (0 == EC_POINT_cmp(group, generator, group->generator, ctx)) { memcpy(pre->g_pre_comp, gmul, sizeof(pre->g_pre_comp)); ret = 1; goto err; } if ((!BN_to_felem(x_tmp, &group->generator->X)) || (!BN_to_felem(y_tmp, &group->generator->Y)) || (!BN_to_felem(z_tmp, &group->generator->Z))) goto err; felem_shrink(pre->g_pre_comp[0][1][0], x_tmp); felem_shrink(pre->g_pre_comp[0][1][1], y_tmp); felem_shrink(pre->g_pre_comp[0][1][2], z_tmp); /* compute 2^64*G, 2^128*G, 2^192*G for the first table, * 2^32*G, 2^96*G, 2^160*G, 2^224*G for the second one */ for (i = 1; i <= 8; i <<= 1) { point_double_small( pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2], pre->g_pre_comp[0][i][0], pre->g_pre_comp[0][i][1], pre->g_pre_comp[0][i][2]); for (j = 0; j < 31; ++j) { point_double_small( pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2], pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]); } if (i == 8) break; point_double_small( pre->g_pre_comp[0][2*i][0], pre->g_pre_comp[0][2*i][1], pre->g_pre_comp[0][2*i][2], pre->g_pre_comp[1][i][0], pre->g_pre_comp[1][i][1], pre->g_pre_comp[1][i][2]); for (j = 0; j < 31; ++j) { point_double_small( pre->g_pre_comp[0][2*i][0], pre->g_pre_comp[0][2*i][1], pre->g_pre_comp[0][2*i][2], pre->g_pre_comp[0][2*i][0], pre->g_pre_comp[0][2*i][1], pre->g_pre_comp[0][2*i][2]); } } for (i = 0; i < 2; i++) { /* g_pre_comp[i][0] is the point at infinity */ memset(pre->g_pre_comp[i][0], 0, sizeof(pre->g_pre_comp[i][0])); /* the remaining multiples */ /* 2^64*G + 2^128*G resp. 2^96*G + 2^160*G */ point_add_small( pre->g_pre_comp[i][6][0], pre->g_pre_comp[i][6][1], pre->g_pre_comp[i][6][2], pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2], pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); /* 2^64*G + 2^192*G resp. 2^96*G + 2^224*G */ point_add_small( pre->g_pre_comp[i][10][0], pre->g_pre_comp[i][10][1], pre->g_pre_comp[i][10][2], pre->g_pre_comp[i][8][0], pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2], pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); /* 2^128*G + 2^192*G resp. 2^160*G + 2^224*G */ point_add_small( pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][8][0], pre->g_pre_comp[i][8][1], pre->g_pre_comp[i][8][2], pre->g_pre_comp[i][4][0], pre->g_pre_comp[i][4][1], pre->g_pre_comp[i][4][2]); /* 2^64*G + 2^128*G + 2^192*G resp. 2^96*G + 2^160*G + 2^224*G */ point_add_small( pre->g_pre_comp[i][14][0], pre->g_pre_comp[i][14][1], pre->g_pre_comp[i][14][2], pre->g_pre_comp[i][12][0], pre->g_pre_comp[i][12][1], pre->g_pre_comp[i][12][2], pre->g_pre_comp[i][2][0], pre->g_pre_comp[i][2][1], pre->g_pre_comp[i][2][2]); for (j = 1; j < 8; ++j) { /* odd multiples: add G resp. 2^32*G */ point_add_small( pre->g_pre_comp[i][2*j+1][0], pre->g_pre_comp[i][2*j+1][1], pre->g_pre_comp[i][2*j+1][2], pre->g_pre_comp[i][2*j][0], pre->g_pre_comp[i][2*j][1], pre->g_pre_comp[i][2*j][2], pre->g_pre_comp[i][1][0], pre->g_pre_comp[i][1][1], pre->g_pre_comp[i][1][2]); } } make_points_affine(31, &(pre->g_pre_comp[0][1]), tmp_smallfelems); if (!EC_EX_DATA_set_data(&group->extra_data, pre, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free)) goto err; ret = 1; pre = NULL; err: BN_CTX_end(ctx); if (generator != NULL) EC_POINT_free(generator); if (new_ctx != NULL) BN_CTX_free(new_ctx); if (pre) nistp256_pre_comp_free(pre); return ret; } int ec_GFp_nistp256_have_precompute_mult(const EC_GROUP *group) { if (EC_EX_DATA_get_data(group->extra_data, nistp256_pre_comp_dup, nistp256_pre_comp_free, nistp256_pre_comp_clear_free) != NULL) return 1; else return 0; } #else static void *dummy=&dummy; #endif
gpl-3.0
OpenFOAM/OpenFOAM-2.3.x
wmake/src/wmkdependParser.cpp
25
11060
/*---------------------------------*- C++ -*---------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. @file wmkdependParser.atg Description An attributed Coco/R grammar to parse C/C++, Fortran and Java files for include and import statements. SourceFiles generated \*---------------------------------------------------------------------------*/ // This file was generated with Coco/R C++ (10 Mar 2010) // http://www.ssw.uni-linz.ac.at/coco/ // with these defines: // - FORCE_UTF8 #include <cstdio> #include <cstdlib> #include <cstring> #include <cwchar> #include <sstream> #include "wmkdependParser.h" namespace wmake { #include <sys/types.h> #include <dirent.h> std::set<std::string> Parser::visitedDirs_; std::set<std::string> Parser::visitedFiles; std::list<std::string> Parser::includeDirs; std::string Parser::sourceFile; std::string Parser::depFile; void Parser::dotToSlash(std::string& name) { std::string::size_type start = 0; while ((start = name.find('.', start)) != std::string::npos) { name.replace(start, 1, 1, '/'); start++; } } void Parser::ignoreDir(const std::string& name) { visitedDirs_.insert(name); } void Parser::includeFile(const std::string& name) { if (!visitedFiles.insert(name).second) { return; // already existed (did not insert) } // use stdio and buffering within Coco/R -- (faster) FILE *fh = fopen(name.c_str(), "r"); if (fh) { std::cout << depFile << ": " << name << "\n"; } else { for ( std::list<std::string>::const_iterator iter = includeDirs.begin(); iter != includeDirs.end(); ++iter ) { const std::string pathName = *iter + name; fh = fopen(pathName.c_str(), "r"); if (fh) { std::cout << depFile << ": " << pathName << "\n"; break; } } } if (fh) { Scanner scanner(fh); Parser parser(&scanner); parser.Parse(); fclose(fh); } else { fwprintf ( stderr, L"could not open file %s for source file %s\n", name.c_str(), sourceFile.c_str() ); // only report the first occurance visitedFiles.insert(name); } } void Parser::importFile(const std::string& name) { // check if a globbed form was already visited std::string::size_type dotPos = name.find('.'); if (dotPos != std::string::npos) { std::string dirGlob = name.substr(0, dotPos); dirGlob += ".*"; if (visitedDirs_.find(dirGlob) != visitedDirs_.end()) { return; } } std::string javaFileName = name; dotToSlash(javaFileName); javaFileName += ".java"; includeFile(javaFileName); } void Parser::importDir(const std::string& name) { if (!visitedDirs_.insert(name).second) { return; // already existed (did not insert) } std::string dirName = name; dotToSlash(dirName); DIR *source = opendir(dirName.c_str()); if (source) { struct dirent *list; // Read and parse all the entries in the directory while ((list = readdir(source)) != NULL) { const char* ext = strstr(list->d_name, ".java"); // avoid matching on something like '.java~' if (ext && strlen(ext) == 5) { std::string pathName = dirName + list->d_name; includeFile(pathName); } } closedir(source); } else { fwprintf ( stderr, L"could not open directory %s\n", dirName.c_str() ); return; } } //! @cond fileScope // // Create by copying str - only used locally inline static wchar_t* coco_string_create(const wchar_t* str) { const int len = wcslen(str); wchar_t* dst = new wchar_t[len + 1]; wcsncpy(dst, str, len); dst[len] = 0; return dst; } // Free storage and nullify the argument inline static void coco_string_delete(wchar_t* &str) { delete[] str; str = NULL; } // //! @endcond // ---------------------------------------------------------------------------- // Parser Implementation // ---------------------------------------------------------------------------- void Parser::SynErr(int n) { if (errDist >= minErrDist) errors->SynErr(la->line, la->col, n); errDist = 0; } void Parser::SemErr(const std::wstring& msg) { if (errDist >= minErrDist) errors->Error(t->line, t->col, msg); errDist = 0; } bool Parser::isUTF8() const { return scanner && scanner->buffer && scanner->buffer->isUTF8(); } void Parser::Get() { for (;;) { t = la; la = scanner->Scan(); if (la->kind <= maxT) { ++errDist; break; } if (dummyToken != t) { dummyToken->kind = t->kind; dummyToken->pos = t->pos; dummyToken->col = t->col; dummyToken->line = t->line; dummyToken->next = NULL; coco_string_delete(dummyToken->val); dummyToken->val = coco_string_create(t->val); t = dummyToken; } la = t; } } void Parser::Expect(int n) { if (la->kind == n) { Get(); } else { SynErr(n); } } void Parser::ExpectWeak(int n, int follow) { if (la->kind == n) { Get(); } else { SynErr(n); while (!StartOf(follow)) { Get(); } } } bool Parser::WeakSeparator(int n, int syFol, int repFol) { if (la->kind == n) { Get(); return true; } else if (StartOf(repFol)) { return false; } else { SynErr(n); while (!(StartOf(syFol) || StartOf(repFol) || StartOf(0))) { Get(); } return StartOf(syFol); } } void Parser::wmkdepend() { while (StartOf(1)) { if (la->kind == 5) { Get(); if (la->kind == 6) { Get(); if (la->kind == 1) { Get(); if (isUTF8()) { includeFile(t->toStringUTF8(1, t->length()-2)); } else { includeFile(t->toString(1, t->length()-2)); } } } if (StartOf(2)) { Get(); while (StartOf(3)) { Get(); } } Expect(7); } else if (la->kind == 6) { Get(); if (la->kind == 2) { Get(); if (isUTF8()) { includeFile(t->toStringUTF8(1, t->length()-2)); } else { includeFile(t->toString(1, t->length()-2)); } } if (StartOf(4)) { Get(); while (StartOf(3)) { Get(); } } Expect(7); } else if (la->kind == 8) { Get(); if (la->kind == 4) { Get(); if (isUTF8()) { importDir(t->toStringUTF8()); } else { importDir(t->toString()); } } else if (la->kind == 3) { Get(); if (isUTF8()) { importFile(t->toStringUTF8()); } else { importFile(t->toString()); } } else SynErr(11); Expect(9); if (StartOf(3)) { Get(); while (StartOf(3)) { Get(); } } Expect(7); } else { if (StartOf(5)) { Get(); while (StartOf(3)) { Get(); } } Expect(7); } } } void Parser::Parse() { t = NULL; // might call Parse() twice if (dummyToken) { coco_string_delete(dummyToken->val); delete dummyToken; } dummyToken = new Token(coco_string_create(L"Dummy Token")); la = dummyToken; Get(); wmkdepend(); Expect(0); // expect end-of-file automatically added } Parser::Parser(Scanner* scan, Errors* err) : dummyToken(NULL), deleteErrorsDestruct_(!err), errDist(minErrDist), scanner(scan), errors(err), t(NULL), la(NULL) { if (!errors) // add in default error handling { errors = new Errors(); } // user-defined initializations: } bool Parser::StartOf(int s) { const bool T = true; const bool x = false; static const bool set[6][12] = { {T,x,x,x, x,x,x,x, x,x,x,x}, {x,T,T,T, T,T,T,T, T,T,T,x}, {x,x,T,T, T,T,x,x, T,T,T,x}, {x,T,T,T, T,T,T,x, T,T,T,x}, {x,T,x,T, T,T,T,x, T,T,T,x}, {x,T,T,T, T,x,x,x, x,T,T,x} }; return set[s][la->kind]; } Parser::~Parser() { if (deleteErrorsDestruct_) { delete errors; } // delete default error handling if (dummyToken) { coco_string_delete(dummyToken->val); delete dummyToken; } // user-defined destruction: } // ---------------------------------------------------------------------------- // Errors Implementation // ---------------------------------------------------------------------------- Errors::Errors() : count(0) {} Errors::~Errors() {} void Errors::clear() { count = 0; } std::wstring Errors::strerror(int n) { switch (n) { case 0: return L"EOF expected"; break; case 1: return L"string expected"; break; case 2: return L"sqstring expected"; break; case 3: return L"package_name expected"; break; case 4: return L"package_dir expected"; break; case 5: return L"\"#\" expected"; break; case 6: return L"\"include\" expected"; break; case 7: return L"\"\\n\" expected"; break; case 8: return L"\"import\" expected"; break; case 9: return L"\";\" expected"; break; case 10: return L"??? expected"; break; case 11: return L"invalid wmkdepend"; break; default: { // std::wostringstream buf; (this typedef might be missing) std::basic_ostringstream<wchar_t> buf; buf << "error " << n; return buf.str(); } break; } } void Errors::Warning(const std::wstring& msg) { fwprintf(stderr, L"%ls\n", msg.c_str()); } void Errors::Warning(int line, int col, const std::wstring& msg) { fwprintf(stderr, L"-- line %d col %d: %ls\n", line, col, msg.c_str()); } void Errors::Error(int line, int col, const std::wstring& msg) { fwprintf(stderr, L"-- line %d col %d: %ls\n", line, col, msg.c_str()); count++; } void Errors::SynErr(int line, int col, int n) { this->Error(line, col, this->strerror(n)); } void Errors::Exception(const std::wstring& msg) { fwprintf(stderr, L"%ls", msg.c_str()); ::exit(1); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace // ************************************************************************* //
gpl-3.0
maoze/linux-3-14-for-arm
linux-3.14/block/blk-sysfs.c
281
16436
/* * Functions related to sysfs handling */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/blktrace_api.h> #include <linux/blk-mq.h> #include "blk.h" #include "blk-cgroup.h" #include "blk-mq.h" struct queue_sysfs_entry { struct attribute attr; ssize_t (*show)(struct request_queue *, char *); ssize_t (*store)(struct request_queue *, const char *, size_t); }; static ssize_t queue_var_show(unsigned long var, char *page) { return sprintf(page, "%lu\n", var); } static ssize_t queue_var_store(unsigned long *var, const char *page, size_t count) { int err; unsigned long v; err = kstrtoul(page, 10, &v); if (err || v > UINT_MAX) return -EINVAL; *var = v; return count; } static ssize_t queue_requests_show(struct request_queue *q, char *page) { return queue_var_show(q->nr_requests, (page)); } static ssize_t queue_requests_store(struct request_queue *q, const char *page, size_t count) { struct request_list *rl; unsigned long nr; int ret; if (!q->request_fn) return -EINVAL; ret = queue_var_store(&nr, page, count); if (ret < 0) return ret; if (nr < BLKDEV_MIN_RQ) nr = BLKDEV_MIN_RQ; spin_lock_irq(q->queue_lock); q->nr_requests = nr; blk_queue_congestion_threshold(q); /* congestion isn't cgroup aware and follows root blkcg for now */ rl = &q->root_rl; if (rl->count[BLK_RW_SYNC] >= queue_congestion_on_threshold(q)) blk_set_queue_congested(q, BLK_RW_SYNC); else if (rl->count[BLK_RW_SYNC] < queue_congestion_off_threshold(q)) blk_clear_queue_congested(q, BLK_RW_SYNC); if (rl->count[BLK_RW_ASYNC] >= queue_congestion_on_threshold(q)) blk_set_queue_congested(q, BLK_RW_ASYNC); else if (rl->count[BLK_RW_ASYNC] < queue_congestion_off_threshold(q)) blk_clear_queue_congested(q, BLK_RW_ASYNC); blk_queue_for_each_rl(rl, q) { if (rl->count[BLK_RW_SYNC] >= q->nr_requests) { blk_set_rl_full(rl, BLK_RW_SYNC); } else { blk_clear_rl_full(rl, BLK_RW_SYNC); wake_up(&rl->wait[BLK_RW_SYNC]); } if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) { blk_set_rl_full(rl, BLK_RW_ASYNC); } else { blk_clear_rl_full(rl, BLK_RW_ASYNC); wake_up(&rl->wait[BLK_RW_ASYNC]); } } spin_unlock_irq(q->queue_lock); return ret; } static ssize_t queue_ra_show(struct request_queue *q, char *page) { unsigned long ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10); return queue_var_show(ra_kb, (page)); } static ssize_t queue_ra_store(struct request_queue *q, const char *page, size_t count) { unsigned long ra_kb; ssize_t ret = queue_var_store(&ra_kb, page, count); if (ret < 0) return ret; q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10); return ret; } static ssize_t queue_max_sectors_show(struct request_queue *q, char *page) { int max_sectors_kb = queue_max_sectors(q) >> 1; return queue_var_show(max_sectors_kb, (page)); } static ssize_t queue_max_segments_show(struct request_queue *q, char *page) { return queue_var_show(queue_max_segments(q), (page)); } static ssize_t queue_max_integrity_segments_show(struct request_queue *q, char *page) { return queue_var_show(q->limits.max_integrity_segments, (page)); } static ssize_t queue_max_segment_size_show(struct request_queue *q, char *page) { if (blk_queue_cluster(q)) return queue_var_show(queue_max_segment_size(q), (page)); return queue_var_show(PAGE_CACHE_SIZE, (page)); } static ssize_t queue_logical_block_size_show(struct request_queue *q, char *page) { return queue_var_show(queue_logical_block_size(q), page); } static ssize_t queue_physical_block_size_show(struct request_queue *q, char *page) { return queue_var_show(queue_physical_block_size(q), page); } static ssize_t queue_io_min_show(struct request_queue *q, char *page) { return queue_var_show(queue_io_min(q), page); } static ssize_t queue_io_opt_show(struct request_queue *q, char *page) { return queue_var_show(queue_io_opt(q), page); } static ssize_t queue_discard_granularity_show(struct request_queue *q, char *page) { return queue_var_show(q->limits.discard_granularity, page); } static ssize_t queue_discard_max_show(struct request_queue *q, char *page) { return sprintf(page, "%llu\n", (unsigned long long)q->limits.max_discard_sectors << 9); } static ssize_t queue_discard_zeroes_data_show(struct request_queue *q, char *page) { return queue_var_show(queue_discard_zeroes_data(q), page); } static ssize_t queue_write_same_max_show(struct request_queue *q, char *page) { return sprintf(page, "%llu\n", (unsigned long long)q->limits.max_write_same_sectors << 9); } static ssize_t queue_max_sectors_store(struct request_queue *q, const char *page, size_t count) { unsigned long max_sectors_kb, max_hw_sectors_kb = queue_max_hw_sectors(q) >> 1, page_kb = 1 << (PAGE_CACHE_SHIFT - 10); ssize_t ret = queue_var_store(&max_sectors_kb, page, count); if (ret < 0) return ret; if (max_sectors_kb > max_hw_sectors_kb || max_sectors_kb < page_kb) return -EINVAL; spin_lock_irq(q->queue_lock); q->limits.max_sectors = max_sectors_kb << 1; spin_unlock_irq(q->queue_lock); return ret; } static ssize_t queue_max_hw_sectors_show(struct request_queue *q, char *page) { int max_hw_sectors_kb = queue_max_hw_sectors(q) >> 1; return queue_var_show(max_hw_sectors_kb, (page)); } #define QUEUE_SYSFS_BIT_FNS(name, flag, neg) \ static ssize_t \ queue_show_##name(struct request_queue *q, char *page) \ { \ int bit; \ bit = test_bit(QUEUE_FLAG_##flag, &q->queue_flags); \ return queue_var_show(neg ? !bit : bit, page); \ } \ static ssize_t \ queue_store_##name(struct request_queue *q, const char *page, size_t count) \ { \ unsigned long val; \ ssize_t ret; \ ret = queue_var_store(&val, page, count); \ if (ret < 0) \ return ret; \ if (neg) \ val = !val; \ \ spin_lock_irq(q->queue_lock); \ if (val) \ queue_flag_set(QUEUE_FLAG_##flag, q); \ else \ queue_flag_clear(QUEUE_FLAG_##flag, q); \ spin_unlock_irq(q->queue_lock); \ return ret; \ } QUEUE_SYSFS_BIT_FNS(nonrot, NONROT, 1); QUEUE_SYSFS_BIT_FNS(random, ADD_RANDOM, 0); QUEUE_SYSFS_BIT_FNS(iostats, IO_STAT, 0); #undef QUEUE_SYSFS_BIT_FNS static ssize_t queue_nomerges_show(struct request_queue *q, char *page) { return queue_var_show((blk_queue_nomerges(q) << 1) | blk_queue_noxmerges(q), page); } static ssize_t queue_nomerges_store(struct request_queue *q, const char *page, size_t count) { unsigned long nm; ssize_t ret = queue_var_store(&nm, page, count); if (ret < 0) return ret; spin_lock_irq(q->queue_lock); queue_flag_clear(QUEUE_FLAG_NOMERGES, q); queue_flag_clear(QUEUE_FLAG_NOXMERGES, q); if (nm == 2) queue_flag_set(QUEUE_FLAG_NOMERGES, q); else if (nm) queue_flag_set(QUEUE_FLAG_NOXMERGES, q); spin_unlock_irq(q->queue_lock); return ret; } static ssize_t queue_rq_affinity_show(struct request_queue *q, char *page) { bool set = test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags); bool force = test_bit(QUEUE_FLAG_SAME_FORCE, &q->queue_flags); return queue_var_show(set << force, page); } static ssize_t queue_rq_affinity_store(struct request_queue *q, const char *page, size_t count) { ssize_t ret = -EINVAL; #ifdef CONFIG_SMP unsigned long val; ret = queue_var_store(&val, page, count); if (ret < 0) return ret; spin_lock_irq(q->queue_lock); if (val == 2) { queue_flag_set(QUEUE_FLAG_SAME_COMP, q); queue_flag_set(QUEUE_FLAG_SAME_FORCE, q); } else if (val == 1) { queue_flag_set(QUEUE_FLAG_SAME_COMP, q); queue_flag_clear(QUEUE_FLAG_SAME_FORCE, q); } else if (val == 0) { queue_flag_clear(QUEUE_FLAG_SAME_COMP, q); queue_flag_clear(QUEUE_FLAG_SAME_FORCE, q); } spin_unlock_irq(q->queue_lock); #endif return ret; } static struct queue_sysfs_entry queue_requests_entry = { .attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR }, .show = queue_requests_show, .store = queue_requests_store, }; static struct queue_sysfs_entry queue_ra_entry = { .attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR }, .show = queue_ra_show, .store = queue_ra_store, }; static struct queue_sysfs_entry queue_max_sectors_entry = { .attr = {.name = "max_sectors_kb", .mode = S_IRUGO | S_IWUSR }, .show = queue_max_sectors_show, .store = queue_max_sectors_store, }; static struct queue_sysfs_entry queue_max_hw_sectors_entry = { .attr = {.name = "max_hw_sectors_kb", .mode = S_IRUGO }, .show = queue_max_hw_sectors_show, }; static struct queue_sysfs_entry queue_max_segments_entry = { .attr = {.name = "max_segments", .mode = S_IRUGO }, .show = queue_max_segments_show, }; static struct queue_sysfs_entry queue_max_integrity_segments_entry = { .attr = {.name = "max_integrity_segments", .mode = S_IRUGO }, .show = queue_max_integrity_segments_show, }; static struct queue_sysfs_entry queue_max_segment_size_entry = { .attr = {.name = "max_segment_size", .mode = S_IRUGO }, .show = queue_max_segment_size_show, }; static struct queue_sysfs_entry queue_iosched_entry = { .attr = {.name = "scheduler", .mode = S_IRUGO | S_IWUSR }, .show = elv_iosched_show, .store = elv_iosched_store, }; static struct queue_sysfs_entry queue_hw_sector_size_entry = { .attr = {.name = "hw_sector_size", .mode = S_IRUGO }, .show = queue_logical_block_size_show, }; static struct queue_sysfs_entry queue_logical_block_size_entry = { .attr = {.name = "logical_block_size", .mode = S_IRUGO }, .show = queue_logical_block_size_show, }; static struct queue_sysfs_entry queue_physical_block_size_entry = { .attr = {.name = "physical_block_size", .mode = S_IRUGO }, .show = queue_physical_block_size_show, }; static struct queue_sysfs_entry queue_io_min_entry = { .attr = {.name = "minimum_io_size", .mode = S_IRUGO }, .show = queue_io_min_show, }; static struct queue_sysfs_entry queue_io_opt_entry = { .attr = {.name = "optimal_io_size", .mode = S_IRUGO }, .show = queue_io_opt_show, }; static struct queue_sysfs_entry queue_discard_granularity_entry = { .attr = {.name = "discard_granularity", .mode = S_IRUGO }, .show = queue_discard_granularity_show, }; static struct queue_sysfs_entry queue_discard_max_entry = { .attr = {.name = "discard_max_bytes", .mode = S_IRUGO }, .show = queue_discard_max_show, }; static struct queue_sysfs_entry queue_discard_zeroes_data_entry = { .attr = {.name = "discard_zeroes_data", .mode = S_IRUGO }, .show = queue_discard_zeroes_data_show, }; static struct queue_sysfs_entry queue_write_same_max_entry = { .attr = {.name = "write_same_max_bytes", .mode = S_IRUGO }, .show = queue_write_same_max_show, }; static struct queue_sysfs_entry queue_nonrot_entry = { .attr = {.name = "rotational", .mode = S_IRUGO | S_IWUSR }, .show = queue_show_nonrot, .store = queue_store_nonrot, }; static struct queue_sysfs_entry queue_nomerges_entry = { .attr = {.name = "nomerges", .mode = S_IRUGO | S_IWUSR }, .show = queue_nomerges_show, .store = queue_nomerges_store, }; static struct queue_sysfs_entry queue_rq_affinity_entry = { .attr = {.name = "rq_affinity", .mode = S_IRUGO | S_IWUSR }, .show = queue_rq_affinity_show, .store = queue_rq_affinity_store, }; static struct queue_sysfs_entry queue_iostats_entry = { .attr = {.name = "iostats", .mode = S_IRUGO | S_IWUSR }, .show = queue_show_iostats, .store = queue_store_iostats, }; static struct queue_sysfs_entry queue_random_entry = { .attr = {.name = "add_random", .mode = S_IRUGO | S_IWUSR }, .show = queue_show_random, .store = queue_store_random, }; static struct attribute *default_attrs[] = { &queue_requests_entry.attr, &queue_ra_entry.attr, &queue_max_hw_sectors_entry.attr, &queue_max_sectors_entry.attr, &queue_max_segments_entry.attr, &queue_max_integrity_segments_entry.attr, &queue_max_segment_size_entry.attr, &queue_iosched_entry.attr, &queue_hw_sector_size_entry.attr, &queue_logical_block_size_entry.attr, &queue_physical_block_size_entry.attr, &queue_io_min_entry.attr, &queue_io_opt_entry.attr, &queue_discard_granularity_entry.attr, &queue_discard_max_entry.attr, &queue_discard_zeroes_data_entry.attr, &queue_write_same_max_entry.attr, &queue_nonrot_entry.attr, &queue_nomerges_entry.attr, &queue_rq_affinity_entry.attr, &queue_iostats_entry.attr, &queue_random_entry.attr, NULL, }; #define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr) static ssize_t queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page) { struct queue_sysfs_entry *entry = to_queue(attr); struct request_queue *q = container_of(kobj, struct request_queue, kobj); ssize_t res; if (!entry->show) return -EIO; mutex_lock(&q->sysfs_lock); if (blk_queue_dying(q)) { mutex_unlock(&q->sysfs_lock); return -ENOENT; } res = entry->show(q, page); mutex_unlock(&q->sysfs_lock); return res; } static ssize_t queue_attr_store(struct kobject *kobj, struct attribute *attr, const char *page, size_t length) { struct queue_sysfs_entry *entry = to_queue(attr); struct request_queue *q; ssize_t res; if (!entry->store) return -EIO; q = container_of(kobj, struct request_queue, kobj); mutex_lock(&q->sysfs_lock); if (blk_queue_dying(q)) { mutex_unlock(&q->sysfs_lock); return -ENOENT; } res = entry->store(q, page, length); mutex_unlock(&q->sysfs_lock); return res; } static void blk_free_queue_rcu(struct rcu_head *rcu_head) { struct request_queue *q = container_of(rcu_head, struct request_queue, rcu_head); kmem_cache_free(blk_requestq_cachep, q); } /** * blk_release_queue: - release a &struct request_queue when it is no longer needed * @kobj: the kobj belonging to the request queue to be released * * Description: * blk_release_queue is the pair to blk_init_queue() or * blk_queue_make_request(). It should be called when a request queue is * being released; typically when a block device is being de-registered. * Currently, its primary task it to free all the &struct request * structures that were allocated to the queue and the queue itself. * * Caveat: * Hopefully the low level driver will have finished any * outstanding requests first... **/ static void blk_release_queue(struct kobject *kobj) { struct request_queue *q = container_of(kobj, struct request_queue, kobj); blk_sync_queue(q); blkcg_exit_queue(q); if (q->elevator) { spin_lock_irq(q->queue_lock); ioc_clear_queue(q); spin_unlock_irq(q->queue_lock); elevator_exit(q->elevator); } blk_exit_rl(&q->root_rl); if (q->queue_tags) __blk_queue_free_tags(q); percpu_counter_destroy(&q->mq_usage_counter); if (q->mq_ops) blk_mq_free_queue(q); kfree(q->flush_rq); blk_trace_shutdown(q); bdi_destroy(&q->backing_dev_info); ida_simple_remove(&blk_queue_ida, q->id); call_rcu(&q->rcu_head, blk_free_queue_rcu); } static const struct sysfs_ops queue_sysfs_ops = { .show = queue_attr_show, .store = queue_attr_store, }; struct kobj_type blk_queue_ktype = { .sysfs_ops = &queue_sysfs_ops, .default_attrs = default_attrs, .release = blk_release_queue, }; int blk_register_queue(struct gendisk *disk) { int ret; struct device *dev = disk_to_dev(disk); struct request_queue *q = disk->queue; if (WARN_ON(!q)) return -ENXIO; /* * Initialization must be complete by now. Finish the initial * bypass from queue allocation. */ blk_queue_bypass_end(q); queue_flag_set_unlocked(QUEUE_FLAG_INIT_DONE, q); ret = blk_trace_init_sysfs(dev); if (ret) return ret; ret = kobject_add(&q->kobj, kobject_get(&dev->kobj), "%s", "queue"); if (ret < 0) { blk_trace_remove_sysfs(dev); return ret; } kobject_uevent(&q->kobj, KOBJ_ADD); if (q->mq_ops) blk_mq_register_disk(disk); if (!q->request_fn) return 0; ret = elv_register_queue(q); if (ret) { kobject_uevent(&q->kobj, KOBJ_REMOVE); kobject_del(&q->kobj); blk_trace_remove_sysfs(dev); kobject_put(&dev->kobj); return ret; } return 0; } void blk_unregister_queue(struct gendisk *disk) { struct request_queue *q = disk->queue; if (WARN_ON(!q)) return; if (q->mq_ops) blk_mq_unregister_disk(disk); if (q->request_fn) elv_unregister_queue(q); kobject_uevent(&q->kobj, KOBJ_REMOVE); kobject_del(&q->kobj); blk_trace_remove_sysfs(disk_to_dev(disk)); kobject_put(&disk_to_dev(disk)->kobj); }
gpl-3.0
rxwen/shadowsocks-android
src/main/jni/openssl/crypto/idea/i_skey.c
537
5193
/* crypto/idea/i_skey.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <openssl/crypto.h> #include <openssl/idea.h> #include "idea_lcl.h" static IDEA_INT inverse(unsigned int xin); void idea_set_encrypt_key(const unsigned char *key, IDEA_KEY_SCHEDULE *ks) #ifdef OPENSSL_FIPS { fips_cipher_abort(IDEA); private_idea_set_encrypt_key(key, ks); } void private_idea_set_encrypt_key(const unsigned char *key, IDEA_KEY_SCHEDULE *ks) #endif { int i; register IDEA_INT *kt,*kf,r0,r1,r2; kt= &(ks->data[0][0]); n2s(key,kt[0]); n2s(key,kt[1]); n2s(key,kt[2]); n2s(key,kt[3]); n2s(key,kt[4]); n2s(key,kt[5]); n2s(key,kt[6]); n2s(key,kt[7]); kf=kt; kt+=8; for (i=0; i<6; i++) { r2= kf[1]; r1= kf[2]; *(kt++)= ((r2<<9) | (r1>>7))&0xffff; r0= kf[3]; *(kt++)= ((r1<<9) | (r0>>7))&0xffff; r1= kf[4]; *(kt++)= ((r0<<9) | (r1>>7))&0xffff; r0= kf[5]; *(kt++)= ((r1<<9) | (r0>>7))&0xffff; r1= kf[6]; *(kt++)= ((r0<<9) | (r1>>7))&0xffff; r0= kf[7]; *(kt++)= ((r1<<9) | (r0>>7))&0xffff; r1= kf[0]; if (i >= 5) break; *(kt++)= ((r0<<9) | (r1>>7))&0xffff; *(kt++)= ((r1<<9) | (r2>>7))&0xffff; kf+=8; } } void idea_set_decrypt_key(IDEA_KEY_SCHEDULE *ek, IDEA_KEY_SCHEDULE *dk) { int r; register IDEA_INT *fp,*tp,t; tp= &(dk->data[0][0]); fp= &(ek->data[8][0]); for (r=0; r<9; r++) { *(tp++)=inverse(fp[0]); *(tp++)=((int)(0x10000L-fp[2])&0xffff); *(tp++)=((int)(0x10000L-fp[1])&0xffff); *(tp++)=inverse(fp[3]); if (r == 8) break; fp-=6; *(tp++)=fp[4]; *(tp++)=fp[5]; } tp= &(dk->data[0][0]); t=tp[1]; tp[1]=tp[2]; tp[2]=t; t=tp[49]; tp[49]=tp[50]; tp[50]=t; } /* taken directly from the 'paper' I'll have a look at it later */ static IDEA_INT inverse(unsigned int xin) { long n1,n2,q,r,b1,b2,t; if (xin == 0) b2=0; else { n1=0x10001; n2=xin; b2=1; b1=0; do { r=(n1%n2); q=(n1-r)/n2; if (r == 0) { if (b2 < 0) b2=0x10001+b2; } else { n1=n2; n2=r; t=b2; b2=b1-q*b2; b1=t; } } while (r != 0); } return((IDEA_INT)b2); }
gpl-3.0
mirkix/ardupilot
libraries/AP_RCProtocol/SoftSerial.cpp
27
3235
/* * This file is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* soft serial receive implementation, based on pulse width inputs */ #include "SoftSerial.h" #include <stdio.h> SoftSerial::SoftSerial(uint32_t _baudrate, serial_config _config) : baudrate(_baudrate), config(_config), half_bit((1000000U / baudrate)/2) { switch (config) { case SERIAL_CONFIG_8N1: case SERIAL_CONFIG_8N1I: data_width = 8; byte_width = 10; stop_mask = 0x200; break; case SERIAL_CONFIG_8E2I: data_width = 9; byte_width = 12; stop_mask = 0xC00; break; } } /* process a pulse made up of a width of values at high voltage followed by a width at low voltage */ bool SoftSerial::process_pulse(uint32_t width_high, uint32_t width_low, uint8_t &byte) { // convert to bit widths, allowing for a half bit error uint16_t bits_high = ((width_high+half_bit)*baudrate) / 1000000; uint16_t bits_low = ((width_low+half_bit)*baudrate) / 1000000; byte_timestamp_us = timestamp_us; timestamp_us += (width_high + width_low); if (bits_high == 0 || bits_low == 0) { // invalid data goto reset; } if (bits_high >= byte_width) { // if we have a start bit and a stop bit then we can have at // most 9 bits in high state for data. The rest must be idle // bits bits_high = byte_width-1; } if (state.bit_ofs == 0) { // we are in idle state, waiting for first low bit. swallow // the high bits bits_high = 0; } state.byte |= ((1U<<bits_high)-1) << state.bit_ofs; state.bit_ofs += bits_high + bits_low; if (state.bit_ofs >= byte_width) { // check start bit if ((state.byte & 1) != 0) { goto reset; } // check stop bits if ((state.byte & stop_mask) != stop_mask) { goto reset; } if (config == SERIAL_CONFIG_8E2I) { // check parity if (__builtin_parity((state.byte>>1)&0xFF) != (state.byte&0x200)>>9) { goto reset; } } byte = ((state.byte>>1) & 0xFF); state.byte >>= byte_width; state.bit_ofs -= byte_width; if (state.bit_ofs > byte_width) { state.byte = 0; state.bit_ofs = bits_low; } // swallow idle bits while (state.bit_ofs > 0 && (state.byte & 1)) { state.bit_ofs--; state.byte >>= 1; } return true; } return false; reset: state.byte = 0; state.bit_ofs = 0; return false; }
gpl-3.0
mkvdv/au-linux-kernel-autumn-2017
linux/fs/xfs/libxfs/xfs_alloc_btree.c
27
14052
/* * Copyright (c) 2000-2001,2005 Silicon Graphics, Inc. * All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_shared.h" #include "xfs_format.h" #include "xfs_log_format.h" #include "xfs_trans_resv.h" #include "xfs_sb.h" #include "xfs_mount.h" #include "xfs_btree.h" #include "xfs_alloc_btree.h" #include "xfs_alloc.h" #include "xfs_extent_busy.h" #include "xfs_error.h" #include "xfs_trace.h" #include "xfs_cksum.h" #include "xfs_trans.h" STATIC struct xfs_btree_cur * xfs_allocbt_dup_cursor( struct xfs_btree_cur *cur) { return xfs_allocbt_init_cursor(cur->bc_mp, cur->bc_tp, cur->bc_private.a.agbp, cur->bc_private.a.agno, cur->bc_btnum); } STATIC void xfs_allocbt_set_root( struct xfs_btree_cur *cur, union xfs_btree_ptr *ptr, int inc) { struct xfs_buf *agbp = cur->bc_private.a.agbp; struct xfs_agf *agf = XFS_BUF_TO_AGF(agbp); xfs_agnumber_t seqno = be32_to_cpu(agf->agf_seqno); int btnum = cur->bc_btnum; struct xfs_perag *pag = xfs_perag_get(cur->bc_mp, seqno); ASSERT(ptr->s != 0); agf->agf_roots[btnum] = ptr->s; be32_add_cpu(&agf->agf_levels[btnum], inc); pag->pagf_levels[btnum] += inc; xfs_perag_put(pag); xfs_alloc_log_agf(cur->bc_tp, agbp, XFS_AGF_ROOTS | XFS_AGF_LEVELS); } STATIC int xfs_allocbt_alloc_block( struct xfs_btree_cur *cur, union xfs_btree_ptr *start, union xfs_btree_ptr *new, int *stat) { int error; xfs_agblock_t bno; XFS_BTREE_TRACE_CURSOR(cur, XBT_ENTRY); /* Allocate the new block from the freelist. If we can't, give up. */ error = xfs_alloc_get_freelist(cur->bc_tp, cur->bc_private.a.agbp, &bno, 1); if (error) { XFS_BTREE_TRACE_CURSOR(cur, XBT_ERROR); return error; } if (bno == NULLAGBLOCK) { XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT); *stat = 0; return 0; } xfs_extent_busy_reuse(cur->bc_mp, cur->bc_private.a.agno, bno, 1, false); xfs_trans_agbtree_delta(cur->bc_tp, 1); new->s = cpu_to_be32(bno); XFS_BTREE_TRACE_CURSOR(cur, XBT_EXIT); *stat = 1; return 0; } STATIC int xfs_allocbt_free_block( struct xfs_btree_cur *cur, struct xfs_buf *bp) { struct xfs_buf *agbp = cur->bc_private.a.agbp; struct xfs_agf *agf = XFS_BUF_TO_AGF(agbp); xfs_agblock_t bno; int error; bno = xfs_daddr_to_agbno(cur->bc_mp, XFS_BUF_ADDR(bp)); error = xfs_alloc_put_freelist(cur->bc_tp, agbp, NULL, bno, 1); if (error) return error; xfs_extent_busy_insert(cur->bc_tp, be32_to_cpu(agf->agf_seqno), bno, 1, XFS_EXTENT_BUSY_SKIP_DISCARD); xfs_trans_agbtree_delta(cur->bc_tp, -1); return 0; } /* * Update the longest extent in the AGF */ STATIC void xfs_allocbt_update_lastrec( struct xfs_btree_cur *cur, struct xfs_btree_block *block, union xfs_btree_rec *rec, int ptr, int reason) { struct xfs_agf *agf = XFS_BUF_TO_AGF(cur->bc_private.a.agbp); xfs_agnumber_t seqno = be32_to_cpu(agf->agf_seqno); struct xfs_perag *pag; __be32 len; int numrecs; ASSERT(cur->bc_btnum == XFS_BTNUM_CNT); switch (reason) { case LASTREC_UPDATE: /* * If this is the last leaf block and it's the last record, * then update the size of the longest extent in the AG. */ if (ptr != xfs_btree_get_numrecs(block)) return; len = rec->alloc.ar_blockcount; break; case LASTREC_INSREC: if (be32_to_cpu(rec->alloc.ar_blockcount) <= be32_to_cpu(agf->agf_longest)) return; len = rec->alloc.ar_blockcount; break; case LASTREC_DELREC: numrecs = xfs_btree_get_numrecs(block); if (ptr <= numrecs) return; ASSERT(ptr == numrecs + 1); if (numrecs) { xfs_alloc_rec_t *rrp; rrp = XFS_ALLOC_REC_ADDR(cur->bc_mp, block, numrecs); len = rrp->ar_blockcount; } else { len = 0; } break; default: ASSERT(0); return; } agf->agf_longest = len; pag = xfs_perag_get(cur->bc_mp, seqno); pag->pagf_longest = be32_to_cpu(len); xfs_perag_put(pag); xfs_alloc_log_agf(cur->bc_tp, cur->bc_private.a.agbp, XFS_AGF_LONGEST); } STATIC int xfs_allocbt_get_minrecs( struct xfs_btree_cur *cur, int level) { return cur->bc_mp->m_alloc_mnr[level != 0]; } STATIC int xfs_allocbt_get_maxrecs( struct xfs_btree_cur *cur, int level) { return cur->bc_mp->m_alloc_mxr[level != 0]; } STATIC void xfs_allocbt_init_key_from_rec( union xfs_btree_key *key, union xfs_btree_rec *rec) { key->alloc.ar_startblock = rec->alloc.ar_startblock; key->alloc.ar_blockcount = rec->alloc.ar_blockcount; } STATIC void xfs_bnobt_init_high_key_from_rec( union xfs_btree_key *key, union xfs_btree_rec *rec) { __u32 x; x = be32_to_cpu(rec->alloc.ar_startblock); x += be32_to_cpu(rec->alloc.ar_blockcount) - 1; key->alloc.ar_startblock = cpu_to_be32(x); key->alloc.ar_blockcount = 0; } STATIC void xfs_cntbt_init_high_key_from_rec( union xfs_btree_key *key, union xfs_btree_rec *rec) { key->alloc.ar_blockcount = rec->alloc.ar_blockcount; key->alloc.ar_startblock = 0; } STATIC void xfs_allocbt_init_rec_from_cur( struct xfs_btree_cur *cur, union xfs_btree_rec *rec) { rec->alloc.ar_startblock = cpu_to_be32(cur->bc_rec.a.ar_startblock); rec->alloc.ar_blockcount = cpu_to_be32(cur->bc_rec.a.ar_blockcount); } STATIC void xfs_allocbt_init_ptr_from_cur( struct xfs_btree_cur *cur, union xfs_btree_ptr *ptr) { struct xfs_agf *agf = XFS_BUF_TO_AGF(cur->bc_private.a.agbp); ASSERT(cur->bc_private.a.agno == be32_to_cpu(agf->agf_seqno)); ASSERT(agf->agf_roots[cur->bc_btnum] != 0); ptr->s = agf->agf_roots[cur->bc_btnum]; } STATIC __int64_t xfs_bnobt_key_diff( struct xfs_btree_cur *cur, union xfs_btree_key *key) { xfs_alloc_rec_incore_t *rec = &cur->bc_rec.a; xfs_alloc_key_t *kp = &key->alloc; return (__int64_t)be32_to_cpu(kp->ar_startblock) - rec->ar_startblock; } STATIC __int64_t xfs_cntbt_key_diff( struct xfs_btree_cur *cur, union xfs_btree_key *key) { xfs_alloc_rec_incore_t *rec = &cur->bc_rec.a; xfs_alloc_key_t *kp = &key->alloc; __int64_t diff; diff = (__int64_t)be32_to_cpu(kp->ar_blockcount) - rec->ar_blockcount; if (diff) return diff; return (__int64_t)be32_to_cpu(kp->ar_startblock) - rec->ar_startblock; } STATIC __int64_t xfs_bnobt_diff_two_keys( struct xfs_btree_cur *cur, union xfs_btree_key *k1, union xfs_btree_key *k2) { return (__int64_t)be32_to_cpu(k1->alloc.ar_startblock) - be32_to_cpu(k2->alloc.ar_startblock); } STATIC __int64_t xfs_cntbt_diff_two_keys( struct xfs_btree_cur *cur, union xfs_btree_key *k1, union xfs_btree_key *k2) { __int64_t diff; diff = be32_to_cpu(k1->alloc.ar_blockcount) - be32_to_cpu(k2->alloc.ar_blockcount); if (diff) return diff; return be32_to_cpu(k1->alloc.ar_startblock) - be32_to_cpu(k2->alloc.ar_startblock); } static bool xfs_allocbt_verify( struct xfs_buf *bp) { struct xfs_mount *mp = bp->b_target->bt_mount; struct xfs_btree_block *block = XFS_BUF_TO_BLOCK(bp); struct xfs_perag *pag = bp->b_pag; unsigned int level; /* * magic number and level verification * * During growfs operations, we can't verify the exact level or owner as * the perag is not fully initialised and hence not attached to the * buffer. In this case, check against the maximum tree depth. * * Similarly, during log recovery we will have a perag structure * attached, but the agf information will not yet have been initialised * from the on disk AGF. Again, we can only check against maximum limits * in this case. */ level = be16_to_cpu(block->bb_level); switch (block->bb_magic) { case cpu_to_be32(XFS_ABTB_CRC_MAGIC): if (!xfs_btree_sblock_v5hdr_verify(bp)) return false; /* fall through */ case cpu_to_be32(XFS_ABTB_MAGIC): if (pag && pag->pagf_init) { if (level >= pag->pagf_levels[XFS_BTNUM_BNOi]) return false; } else if (level >= mp->m_ag_maxlevels) return false; break; case cpu_to_be32(XFS_ABTC_CRC_MAGIC): if (!xfs_btree_sblock_v5hdr_verify(bp)) return false; /* fall through */ case cpu_to_be32(XFS_ABTC_MAGIC): if (pag && pag->pagf_init) { if (level >= pag->pagf_levels[XFS_BTNUM_CNTi]) return false; } else if (level >= mp->m_ag_maxlevels) return false; break; default: return false; } return xfs_btree_sblock_verify(bp, mp->m_alloc_mxr[level != 0]); } static void xfs_allocbt_read_verify( struct xfs_buf *bp) { if (!xfs_btree_sblock_verify_crc(bp)) xfs_buf_ioerror(bp, -EFSBADCRC); else if (!xfs_allocbt_verify(bp)) xfs_buf_ioerror(bp, -EFSCORRUPTED); if (bp->b_error) { trace_xfs_btree_corrupt(bp, _RET_IP_); xfs_verifier_error(bp); } } static void xfs_allocbt_write_verify( struct xfs_buf *bp) { if (!xfs_allocbt_verify(bp)) { trace_xfs_btree_corrupt(bp, _RET_IP_); xfs_buf_ioerror(bp, -EFSCORRUPTED); xfs_verifier_error(bp); return; } xfs_btree_sblock_calc_crc(bp); } const struct xfs_buf_ops xfs_allocbt_buf_ops = { .name = "xfs_allocbt", .verify_read = xfs_allocbt_read_verify, .verify_write = xfs_allocbt_write_verify, }; #if defined(DEBUG) || defined(XFS_WARN) STATIC int xfs_bnobt_keys_inorder( struct xfs_btree_cur *cur, union xfs_btree_key *k1, union xfs_btree_key *k2) { return be32_to_cpu(k1->alloc.ar_startblock) < be32_to_cpu(k2->alloc.ar_startblock); } STATIC int xfs_bnobt_recs_inorder( struct xfs_btree_cur *cur, union xfs_btree_rec *r1, union xfs_btree_rec *r2) { return be32_to_cpu(r1->alloc.ar_startblock) + be32_to_cpu(r1->alloc.ar_blockcount) <= be32_to_cpu(r2->alloc.ar_startblock); } STATIC int xfs_cntbt_keys_inorder( struct xfs_btree_cur *cur, union xfs_btree_key *k1, union xfs_btree_key *k2) { return be32_to_cpu(k1->alloc.ar_blockcount) < be32_to_cpu(k2->alloc.ar_blockcount) || (k1->alloc.ar_blockcount == k2->alloc.ar_blockcount && be32_to_cpu(k1->alloc.ar_startblock) < be32_to_cpu(k2->alloc.ar_startblock)); } STATIC int xfs_cntbt_recs_inorder( struct xfs_btree_cur *cur, union xfs_btree_rec *r1, union xfs_btree_rec *r2) { return be32_to_cpu(r1->alloc.ar_blockcount) < be32_to_cpu(r2->alloc.ar_blockcount) || (r1->alloc.ar_blockcount == r2->alloc.ar_blockcount && be32_to_cpu(r1->alloc.ar_startblock) < be32_to_cpu(r2->alloc.ar_startblock)); } #endif /* DEBUG */ static const struct xfs_btree_ops xfs_bnobt_ops = { .rec_len = sizeof(xfs_alloc_rec_t), .key_len = sizeof(xfs_alloc_key_t), .dup_cursor = xfs_allocbt_dup_cursor, .set_root = xfs_allocbt_set_root, .alloc_block = xfs_allocbt_alloc_block, .free_block = xfs_allocbt_free_block, .update_lastrec = xfs_allocbt_update_lastrec, .get_minrecs = xfs_allocbt_get_minrecs, .get_maxrecs = xfs_allocbt_get_maxrecs, .init_key_from_rec = xfs_allocbt_init_key_from_rec, .init_high_key_from_rec = xfs_bnobt_init_high_key_from_rec, .init_rec_from_cur = xfs_allocbt_init_rec_from_cur, .init_ptr_from_cur = xfs_allocbt_init_ptr_from_cur, .key_diff = xfs_bnobt_key_diff, .buf_ops = &xfs_allocbt_buf_ops, .diff_two_keys = xfs_bnobt_diff_two_keys, #if defined(DEBUG) || defined(XFS_WARN) .keys_inorder = xfs_bnobt_keys_inorder, .recs_inorder = xfs_bnobt_recs_inorder, #endif }; static const struct xfs_btree_ops xfs_cntbt_ops = { .rec_len = sizeof(xfs_alloc_rec_t), .key_len = sizeof(xfs_alloc_key_t), .dup_cursor = xfs_allocbt_dup_cursor, .set_root = xfs_allocbt_set_root, .alloc_block = xfs_allocbt_alloc_block, .free_block = xfs_allocbt_free_block, .update_lastrec = xfs_allocbt_update_lastrec, .get_minrecs = xfs_allocbt_get_minrecs, .get_maxrecs = xfs_allocbt_get_maxrecs, .init_key_from_rec = xfs_allocbt_init_key_from_rec, .init_high_key_from_rec = xfs_cntbt_init_high_key_from_rec, .init_rec_from_cur = xfs_allocbt_init_rec_from_cur, .init_ptr_from_cur = xfs_allocbt_init_ptr_from_cur, .key_diff = xfs_cntbt_key_diff, .buf_ops = &xfs_allocbt_buf_ops, .diff_two_keys = xfs_cntbt_diff_two_keys, #if defined(DEBUG) || defined(XFS_WARN) .keys_inorder = xfs_cntbt_keys_inorder, .recs_inorder = xfs_cntbt_recs_inorder, #endif }; /* * Allocate a new allocation btree cursor. */ struct xfs_btree_cur * /* new alloc btree cursor */ xfs_allocbt_init_cursor( struct xfs_mount *mp, /* file system mount point */ struct xfs_trans *tp, /* transaction pointer */ struct xfs_buf *agbp, /* buffer for agf structure */ xfs_agnumber_t agno, /* allocation group number */ xfs_btnum_t btnum) /* btree identifier */ { struct xfs_agf *agf = XFS_BUF_TO_AGF(agbp); struct xfs_btree_cur *cur; ASSERT(btnum == XFS_BTNUM_BNO || btnum == XFS_BTNUM_CNT); cur = kmem_zone_zalloc(xfs_btree_cur_zone, KM_NOFS); cur->bc_tp = tp; cur->bc_mp = mp; cur->bc_btnum = btnum; cur->bc_blocklog = mp->m_sb.sb_blocklog; if (btnum == XFS_BTNUM_CNT) { cur->bc_statoff = XFS_STATS_CALC_INDEX(xs_abtc_2); cur->bc_ops = &xfs_cntbt_ops; cur->bc_nlevels = be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]); cur->bc_flags = XFS_BTREE_LASTREC_UPDATE; } else { cur->bc_statoff = XFS_STATS_CALC_INDEX(xs_abtb_2); cur->bc_ops = &xfs_bnobt_ops; cur->bc_nlevels = be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]); } cur->bc_private.a.agbp = agbp; cur->bc_private.a.agno = agno; if (xfs_sb_version_hascrc(&mp->m_sb)) cur->bc_flags |= XFS_BTREE_CRC_BLOCKS; return cur; } /* * Calculate number of records in an alloc btree block. */ int xfs_allocbt_maxrecs( struct xfs_mount *mp, int blocklen, int leaf) { blocklen -= XFS_ALLOC_BLOCK_LEN(mp); if (leaf) return blocklen / sizeof(xfs_alloc_rec_t); return blocklen / (sizeof(xfs_alloc_key_t) + sizeof(xfs_alloc_ptr_t)); }
gpl-3.0
Cazomino05/Test1
MTA10_Server/mods/deathmatch/logic/packets/CCameraSyncPacket.cpp
28
1492
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/packets/CCameraSyncPacket.cpp * PURPOSE: Camera synchronization packet class * DEVELOPERS: Jax <> * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include "StdInc.h" bool CCameraSyncPacket::Read ( NetBitStreamInterface& BitStream ) { if ( BitStream.Version() >= 0x5E ) { CPlayer* pPlayer = GetSourcePlayer(); if ( !pPlayer ) return false; // Check the time context uchar ucTimeContext = 0; BitStream.Read( ucTimeContext ); if ( !pPlayer->GetCamera()->CanUpdateSync( ucTimeContext ) ) { return false; } } if ( !BitStream.ReadBit ( m_bFixed ) ) return false; if ( m_bFixed ) { SPositionSync position ( false ); if ( !BitStream.Read ( &position ) ) return false; m_vecPosition = position.data.vecPosition; SPositionSync lookAt ( false ); if ( !BitStream.Read ( &lookAt ) ) return false; m_vecLookAt = lookAt.data.vecPosition; return true; } else { return BitStream.Read ( m_TargetID ); } }
gpl-3.0
craftandtheory/ardupilot
libraries/AC_AttitudeControl/AC_PosControl_Sub.cpp
29
4516
#include "AC_PosControl_Sub.h" AC_PosControl_Sub::AC_PosControl_Sub(const AP_AHRS_View& ahrs, const AP_InertialNav& inav, const AP_Motors& motors, AC_AttitudeControl& attitude_control, AC_P& p_pos_z, AC_P& p_vel_z, AC_PID& pid_accel_z, AC_P& p_pos_xy, AC_PI_2D& pi_vel_xy) : AC_PosControl(ahrs, inav, motors, attitude_control, p_pos_z, p_vel_z, pid_accel_z, p_pos_xy, pi_vel_xy), _alt_max(0.0f), _alt_min(0.0f) {} /// set_alt_target_from_climb_rate - adjusts target up or down using a climb rate in cm/s /// should be called continuously (with dt set to be the expected time between calls) /// actual position target will be moved no faster than the speed_down and speed_up /// target will also be stopped if the motors hit their limits or leash length is exceeded void AC_PosControl_Sub::set_alt_target_from_climb_rate(float climb_rate_cms, float dt, bool force_descend) { // adjust desired alt if motors have not hit their limits // To-Do: add check of _limit.pos_down? if ((climb_rate_cms<0 && (!_motors.limit.throttle_lower || force_descend)) || (climb_rate_cms>0 && !_motors.limit.throttle_upper && !_limit.pos_up)) { _pos_target.z += climb_rate_cms * dt; } // do not let target alt get above limit if (_alt_max < 100 && _pos_target.z > _alt_max) { _pos_target.z = _alt_max; _limit.pos_up = true; } // do not let target alt get below limit if (_alt_min < 0 && _alt_min < _alt_max && _pos_target.z < _alt_min) { _pos_target.z = _alt_min; _limit.pos_down = true; } // do not use z-axis desired velocity feed forward // vel_desired set to desired climb rate for reporting and land-detector _flags.use_desvel_ff_z = false; _vel_desired.z = climb_rate_cms; } /// set_alt_target_from_climb_rate_ff - adjusts target up or down using a climb rate in cm/s using feed-forward /// should be called continuously (with dt set to be the expected time between calls) /// actual position target will be moved no faster than the speed_down and speed_up /// target will also be stopped if the motors hit their limits or leash length is exceeded /// set force_descend to true during landing to allow target to move low enough to slow the motors void AC_PosControl_Sub::set_alt_target_from_climb_rate_ff(float climb_rate_cms, float dt, bool force_descend) { // calculated increased maximum acceleration if over speed float accel_z_cms = _accel_z_cms; if (_vel_desired.z < _speed_down_cms && !is_zero(_speed_down_cms)) { accel_z_cms *= POSCONTROL_OVERSPEED_GAIN_Z * _vel_desired.z / _speed_down_cms; } if (_vel_desired.z > _speed_up_cms && !is_zero(_speed_up_cms)) { accel_z_cms *= POSCONTROL_OVERSPEED_GAIN_Z * _vel_desired.z / _speed_up_cms; } accel_z_cms = constrain_float(accel_z_cms, 0.0f, 750.0f); // jerk_z is calculated to reach full acceleration in 1000ms. float jerk_z = accel_z_cms * POSCONTROL_JERK_RATIO; float accel_z_max = MIN(accel_z_cms, safe_sqrt(2.0f*fabsf(_vel_desired.z - climb_rate_cms)*jerk_z)); _accel_last_z_cms += jerk_z * dt; _accel_last_z_cms = MIN(accel_z_max, _accel_last_z_cms); float vel_change_limit = _accel_last_z_cms * dt; _vel_desired.z = constrain_float(climb_rate_cms, _vel_desired.z-vel_change_limit, _vel_desired.z+vel_change_limit); _flags.use_desvel_ff_z = true; // adjust desired alt if motors have not hit their limits // To-Do: add check of _limit.pos_down? if ((_vel_desired.z<0 && (!_motors.limit.throttle_lower || force_descend)) || (_vel_desired.z>0 && !_motors.limit.throttle_upper && !_limit.pos_up)) { _pos_target.z += _vel_desired.z * dt; } // do not let target alt get above limit if (_alt_max < 100 && _pos_target.z > _alt_max) { _pos_target.z = _alt_max; _limit.pos_up = true; // decelerate feed forward to zero _vel_desired.z = constrain_float(0.0f, _vel_desired.z-vel_change_limit, _vel_desired.z+vel_change_limit); } // do not let target alt get below limit if (_alt_min < 0 && _alt_min < _alt_max && _pos_target.z < _alt_min) { _pos_target.z = _alt_min; _limit.pos_down = true; // decelerate feed forward to zero _vel_desired.z = constrain_float(0.0f, _vel_desired.z-vel_change_limit, _vel_desired.z+vel_change_limit); } }
gpl-3.0
leo-wdls/popcorn
ffmpeg-2.4.2/libavcodec/sgirledec.c
30
5210
/* * Silicon Graphics RLE 8-bit video decoder * Copyright (c) 2012 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Silicon Graphics RLE 8-bit video decoder * @note Data is packed in rbg323 with rle, contained in mv or mov. * The algorithm and pixfmt are subtly different from SGI images. */ #include "libavutil/common.h" #include "avcodec.h" #include "internal.h" typedef struct SGIRLEContext { AVFrame *frame; } SGIRLEContext; static av_cold int sgirle_decode_init(AVCodecContext *avctx) { SGIRLEContext *s = avctx->priv_data; avctx->pix_fmt = AV_PIX_FMT_BGR8; s->frame = av_frame_alloc(); if (!s->frame) return AVERROR(ENOMEM); return 0; } /** * Convert SGI RBG323 pixel into AV_PIX_FMT_BGR8 * SGI RGB data is packed as 8bpp, (msb)3R 2B 3G(lsb) */ #define RBG323_TO_BGR8(x) ((((x) << 3) & 0xC0) | \ (((x) << 3) & 0x38) | \ (((x) >> 5) & 7)) static av_always_inline void rbg323_to_bgr8(uint8_t *dst, const uint8_t *src, int size) { int i; for (i = 0; i < size; i++) dst[i] = RBG323_TO_BGR8(src[i]); } /** * @param[out] dst Destination buffer * @param[in] src Source buffer * @param src_size Source buffer size (bytes) * @param width Width of destination buffer (pixels) * @param height Height of destination buffer (pixels) * @param linesize Line size of destination buffer (bytes) * * @return <0 on error */ static int decode_sgirle8(AVCodecContext *avctx, uint8_t *dst, const uint8_t *src, int src_size, int width, int height, ptrdiff_t linesize) { const uint8_t *src_end = src + src_size; int x = 0, y = 0; #define INC_XY(n) \ x += n; \ if (x >= width) { \ y++; \ if (y >= height) \ return 0; \ x = 0; \ } while (src_end - src >= 2) { uint8_t v = *src++; if (v > 0 && v < 0xC0) { do { int length = FFMIN(v, width - x); if (length <= 0) break; memset(dst + y * linesize + x, RBG323_TO_BGR8(*src), length); INC_XY(length); v -= length; } while (v > 0); src++; } else if (v >= 0xC1) { v -= 0xC0; do { int length = FFMIN3(v, width - x, src_end - src); if (src_end - src < length || length <= 0) break; rbg323_to_bgr8(dst + y * linesize + x, src, length); INC_XY(length); src += length; v -= length; } while (v > 0); } else { avpriv_request_sample(avctx, "opcode %d", v); return AVERROR_PATCHWELCOME; } } return 0; } static int sgirle_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { SGIRLEContext *s = avctx->priv_data; int ret; if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) return ret; ret = decode_sgirle8(avctx, s->frame->data[0], avpkt->data, avpkt->size, avctx->width, avctx->height, s->frame->linesize[0]); if (ret < 0) return ret; *got_frame = 1; if ((ret = av_frame_ref(data, s->frame)) < 0) return ret; return avpkt->size; } static av_cold int sgirle_decode_end(AVCodecContext *avctx) { SGIRLEContext *s = avctx->priv_data; av_frame_free(&s->frame); return 0; } AVCodec ff_sgirle_decoder = { .name = "sgirle", .long_name = NULL_IF_CONFIG_SMALL("Silicon Graphics RLE 8-bit video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_SGIRLE, .priv_data_size = sizeof(SGIRLEContext), .init = sgirle_decode_init, .close = sgirle_decode_end, .decode = sgirle_decode_frame, .capabilities = CODEC_CAP_DR1, };
gpl-3.0
devcline/mtasa-blue
vendor/curl/lib/curl_darwinssl.c
31
66720
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012-2013, Nick Zitzmann, <nickzman@gmail.com>. * Copyright (C) 2012-2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Source file for all iOS and Mac OS X SecureTransport-specific code for the * TLS/SSL layer. No code but sslgen.c should ever call or use these functions. */ #include "curl_setup.h" #ifdef USE_DARWINSSL #ifdef HAVE_LIMITS_H #include <limits.h> #endif #include <Security/Security.h> #include <Security/SecureTransport.h> #include <CoreFoundation/CoreFoundation.h> #include <CommonCrypto/CommonDigest.h> /* The Security framework has changed greatly between iOS and different OS X versions, and we will try to support as many of them as we can (back to Leopard and iOS 5) by using macros and weak-linking. IMPORTANT: If TLS 1.1 and 1.2 support are important for you on OS X, then you must build this project against the 10.8 SDK or later. */ #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) #if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 #error "The darwinssl back-end requires Leopard or later." #endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */ #define CURL_BUILD_IOS 0 #define CURL_BUILD_MAC 1 /* This is the maximum API level we are allowed to use when building: */ #define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 #define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 #define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 #define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 /* These macros mean "the following code is present to allow runtime backward compatibility with at least this cat or earlier": (You set this at build-time by setting the MACOSX_DEPLOYMENT_TARGET environmental variable.) */ #define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050 #define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060 #define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070 #define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 #elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE #define CURL_BUILD_IOS 1 #define CURL_BUILD_MAC 0 #define CURL_BUILD_MAC_10_5 0 #define CURL_BUILD_MAC_10_6 0 #define CURL_BUILD_MAC_10_7 0 #define CURL_BUILD_MAC_10_8 0 #define CURL_SUPPORT_MAC_10_5 0 #define CURL_SUPPORT_MAC_10_6 0 #define CURL_SUPPORT_MAC_10_7 0 #define CURL_SUPPORT_MAC_10_8 0 #else #error "The darwinssl back-end requires iOS or OS X." #endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */ #if CURL_BUILD_MAC #include <sys/sysctl.h> #endif /* CURL_BUILD_MAC */ #include "urldata.h" #include "sendf.h" #include "inet_pton.h" #include "connect.h" #include "select.h" #include "sslgen.h" #include "curl_darwinssl.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* From MacTypes.h (which we can't include because it isn't present in iOS: */ #define ioErr -36 #define paramErr -50 /* The following two functions were ripped from Apple sample code, * with some modifications: */ static OSStatus SocketRead(SSLConnectionRef connection, void *data, /* owned by * caller, data * RETURNED */ size_t *dataLength) /* IN/OUT */ { size_t bytesToGo = *dataLength; size_t initLen = bytesToGo; UInt8 *currData = (UInt8 *)data; /*int sock = *(int *)connection;*/ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection; int sock = connssl->ssl_sockfd; OSStatus rtn = noErr; size_t bytesRead; ssize_t rrtn; int theErr; *dataLength = 0; for(;;) { bytesRead = 0; rrtn = read(sock, currData, bytesToGo); if(rrtn <= 0) { /* this is guesswork... */ theErr = errno; if(rrtn == 0) { /* EOF = server hung up */ /* the framework will turn this into errSSLClosedNoNotify */ rtn = errSSLClosedGraceful; } else /* do the switch */ switch(theErr) { case ENOENT: /* connection closed */ rtn = errSSLClosedGraceful; break; case ECONNRESET: rtn = errSSLClosedAbort; break; case EAGAIN: rtn = errSSLWouldBlock; connssl->ssl_direction = false; break; default: rtn = ioErr; break; } break; } else { bytesRead = rrtn; } bytesToGo -= bytesRead; currData += bytesRead; if(bytesToGo == 0) { /* filled buffer with incoming data, done */ break; } } *dataLength = initLen - bytesToGo; return rtn; } static OSStatus SocketWrite(SSLConnectionRef connection, const void *data, size_t *dataLength) /* IN/OUT */ { size_t bytesSent = 0; /*int sock = *(int *)connection;*/ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection; int sock = connssl->ssl_sockfd; ssize_t length; size_t dataLen = *dataLength; const UInt8 *dataPtr = (UInt8 *)data; OSStatus ortn; int theErr; *dataLength = 0; do { length = write(sock, (char*)dataPtr + bytesSent, dataLen - bytesSent); } while((length > 0) && ( (bytesSent += length) < dataLen) ); if(length <= 0) { theErr = errno; if(theErr == EAGAIN) { ortn = errSSLWouldBlock; connssl->ssl_direction = true; } else { ortn = ioErr; } } else { ortn = noErr; } *dataLength = bytesSent; return ortn; } CF_INLINE const char *SSLCipherNameForNumber(SSLCipherSuite cipher) { switch (cipher) { /* SSL version 3.0 */ case SSL_RSA_WITH_NULL_MD5: return "SSL_RSA_WITH_NULL_MD5"; break; case SSL_RSA_WITH_NULL_SHA: return "SSL_RSA_WITH_NULL_SHA"; break; case SSL_RSA_EXPORT_WITH_RC4_40_MD5: return "SSL_RSA_EXPORT_WITH_RC4_40_MD5"; break; case SSL_RSA_WITH_RC4_128_MD5: return "SSL_RSA_WITH_RC4_128_MD5"; break; case SSL_RSA_WITH_RC4_128_SHA: return "SSL_RSA_WITH_RC4_128_SHA"; break; case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5: return "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5"; break; case SSL_RSA_WITH_IDEA_CBC_SHA: return "SSL_RSA_WITH_IDEA_CBC_SHA"; break; case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: return "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_RSA_WITH_DES_CBC_SHA: return "SSL_RSA_WITH_DES_CBC_SHA"; break; case SSL_RSA_WITH_3DES_EDE_CBC_SHA: return "SSL_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DH_DSS_WITH_DES_CBC_SHA: return "SSL_DH_DSS_WITH_DES_CBC_SHA"; break; case SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA: return "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DH_RSA_WITH_DES_CBC_SHA: return "SSL_DH_RSA_WITH_DES_CBC_SHA"; break; case SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA: return "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DHE_DSS_WITH_DES_CBC_SHA: return "SSL_DHE_DSS_WITH_DES_CBC_SHA"; break; case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA: return "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DHE_RSA_WITH_DES_CBC_SHA: return "SSL_DHE_RSA_WITH_DES_CBC_SHA"; break; case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA: return "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5: return "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"; break; case SSL_DH_anon_WITH_RC4_128_MD5: return "SSL_DH_anon_WITH_RC4_128_MD5"; break; case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA: return "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"; break; case SSL_DH_anon_WITH_DES_CBC_SHA: return "SSL_DH_anon_WITH_DES_CBC_SHA"; break; case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA: return "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"; break; case SSL_FORTEZZA_DMS_WITH_NULL_SHA: return "SSL_FORTEZZA_DMS_WITH_NULL_SHA"; break; case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA: return "SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA"; break; /* TLS 1.0 with AES (RFC 3268) (Apparently these are used in SSLv3 implementations as well.) */ case TLS_RSA_WITH_AES_128_CBC_SHA: return "TLS_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_128_CBC_SHA: return "TLS_DH_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_128_CBC_SHA: return "TLS_DH_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_128_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_128_CBC_SHA: return "TLS_DH_anon_WITH_AES_128_CBC_SHA"; break; case TLS_RSA_WITH_AES_256_CBC_SHA: return "TLS_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_256_CBC_SHA: return "TLS_DH_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_256_CBC_SHA: return "TLS_DH_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_256_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_256_CBC_SHA: return "TLS_DH_anon_WITH_AES_256_CBC_SHA"; break; /* SSL version 2.0 */ case SSL_RSA_WITH_RC2_CBC_MD5: return "SSL_RSA_WITH_RC2_CBC_MD5"; break; case SSL_RSA_WITH_IDEA_CBC_MD5: return "SSL_RSA_WITH_IDEA_CBC_MD5"; break; case SSL_RSA_WITH_DES_CBC_MD5: return "SSL_RSA_WITH_DES_CBC_MD5"; break; case SSL_RSA_WITH_3DES_EDE_CBC_MD5: return "SSL_RSA_WITH_3DES_EDE_CBC_MD5"; break; } return "SSL_NULL_WITH_NULL_NULL"; } CF_INLINE const char *TLSCipherNameForNumber(SSLCipherSuite cipher) { switch(cipher) { /* TLS 1.0 with AES (RFC 3268) */ case TLS_RSA_WITH_AES_128_CBC_SHA: return "TLS_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_128_CBC_SHA: return "TLS_DH_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_128_CBC_SHA: return "TLS_DH_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_128_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_128_CBC_SHA: return "TLS_DH_anon_WITH_AES_128_CBC_SHA"; break; case TLS_RSA_WITH_AES_256_CBC_SHA: return "TLS_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_256_CBC_SHA: return "TLS_DH_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DH_RSA_WITH_AES_256_CBC_SHA: return "TLS_DH_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_DSS_WITH_AES_256_CBC_SHA: return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"; break; case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_256_CBC_SHA: return "TLS_DH_anon_WITH_AES_256_CBC_SHA"; break; #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS /* TLS 1.0 with ECDSA (RFC 4492) */ case TLS_ECDH_ECDSA_WITH_NULL_SHA: return "TLS_ECDH_ECDSA_WITH_NULL_SHA"; break; case TLS_ECDH_ECDSA_WITH_RC4_128_SHA: return "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"; break; case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: return "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: return "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDHE_ECDSA_WITH_NULL_SHA: return "TLS_ECDHE_ECDSA_WITH_NULL_SHA"; break; case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: return "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"; break; case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDH_RSA_WITH_NULL_SHA: return "TLS_ECDH_RSA_WITH_NULL_SHA"; break; case TLS_ECDH_RSA_WITH_RC4_128_SHA: return "TLS_ECDH_RSA_WITH_RC4_128_SHA"; break; case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: return "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: return "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDHE_RSA_WITH_NULL_SHA: return "TLS_ECDHE_RSA_WITH_NULL_SHA"; break; case TLS_ECDHE_RSA_WITH_RC4_128_SHA: return "TLS_ECDHE_RSA_WITH_RC4_128_SHA"; break; case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"; break; case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"; break; case TLS_ECDH_anon_WITH_NULL_SHA: return "TLS_ECDH_anon_WITH_NULL_SHA"; break; case TLS_ECDH_anon_WITH_RC4_128_SHA: return "TLS_ECDH_anon_WITH_RC4_128_SHA"; break; case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: return "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"; break; case TLS_ECDH_anon_WITH_AES_128_CBC_SHA: return "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"; break; case TLS_ECDH_anon_WITH_AES_256_CBC_SHA: return "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"; break; #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS /* TLS 1.2 (RFC 5246) */ case TLS_RSA_WITH_NULL_MD5: return "TLS_RSA_WITH_NULL_MD5"; break; case TLS_RSA_WITH_NULL_SHA: return "TLS_RSA_WITH_NULL_SHA"; break; case TLS_RSA_WITH_RC4_128_MD5: return "TLS_RSA_WITH_RC4_128_MD5"; break; case TLS_RSA_WITH_RC4_128_SHA: return "TLS_RSA_WITH_RC4_128_SHA"; break; case TLS_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_RSA_WITH_NULL_SHA256: return "TLS_RSA_WITH_NULL_SHA256"; break; case TLS_RSA_WITH_AES_128_CBC_SHA256: return "TLS_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_RSA_WITH_AES_256_CBC_SHA256: return "TLS_RSA_WITH_AES_256_CBC_SHA256"; break; case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: return "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DH_DSS_WITH_AES_128_CBC_SHA256: return "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"; break; case TLS_DH_RSA_WITH_AES_128_CBC_SHA256: return "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"; break; case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_DH_DSS_WITH_AES_256_CBC_SHA256: return "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"; break; case TLS_DH_RSA_WITH_AES_256_CBC_SHA256: return "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"; break; case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"; break; case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"; break; case TLS_DH_anon_WITH_RC4_128_MD5: return "TLS_DH_anon_WITH_RC4_128_MD5"; break; case TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"; break; case TLS_DH_anon_WITH_AES_128_CBC_SHA256: return "TLS_DH_anon_WITH_AES_128_CBC_SHA256"; break; case TLS_DH_anon_WITH_AES_256_CBC_SHA256: return "TLS_DH_anon_WITH_AES_256_CBC_SHA256"; break; /* TLS 1.2 with AES GCM (RFC 5288) */ case TLS_RSA_WITH_AES_128_GCM_SHA256: return "TLS_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_RSA_WITH_AES_256_GCM_SHA384: return "TLS_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: return "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: return "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_DH_RSA_WITH_AES_128_GCM_SHA256: return "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_DH_RSA_WITH_AES_256_GCM_SHA384: return "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: return "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"; break; case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: return "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"; break; case TLS_DH_DSS_WITH_AES_128_GCM_SHA256: return "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"; break; case TLS_DH_DSS_WITH_AES_256_GCM_SHA384: return "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"; break; case TLS_DH_anon_WITH_AES_128_GCM_SHA256: return "TLS_DH_anon_WITH_AES_128_GCM_SHA256"; break; case TLS_DH_anon_WITH_AES_256_GCM_SHA384: return "TLS_DH_anon_WITH_AES_256_GCM_SHA384"; break; /* TLS 1.2 with elliptic curve ciphers (RFC 5289) */ case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: return "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"; break; case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: return "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"; break; case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"; break; case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"; break; case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: return "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"; break; case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"; break; case TLS_EMPTY_RENEGOTIATION_INFO_SCSV: return "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"; break; #else case SSL_RSA_WITH_NULL_MD5: return "TLS_RSA_WITH_NULL_MD5"; break; case SSL_RSA_WITH_NULL_SHA: return "TLS_RSA_WITH_NULL_SHA"; break; case SSL_RSA_WITH_RC4_128_MD5: return "TLS_RSA_WITH_RC4_128_MD5"; break; case SSL_RSA_WITH_RC4_128_SHA: return "TLS_RSA_WITH_RC4_128_SHA"; break; case SSL_RSA_WITH_3DES_EDE_CBC_SHA: return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"; break; case SSL_DH_anon_WITH_RC4_128_MD5: return "TLS_DH_anon_WITH_RC4_128_MD5"; break; case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA: return "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"; break; #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ } return "TLS_NULL_WITH_NULL_NULL"; } #if CURL_BUILD_MAC CF_INLINE void GetDarwinVersionNumber(int *major, int *minor) { int mib[2]; char *os_version; size_t os_version_len; char *os_version_major, *os_version_minor/*, *os_version_point*/; /* Get the Darwin kernel version from the kernel using sysctl(): */ mib[0] = CTL_KERN; mib[1] = KERN_OSRELEASE; if(sysctl(mib, 2, NULL, &os_version_len, NULL, 0) == -1) return; os_version = malloc(os_version_len*sizeof(char)); if(!os_version) return; if(sysctl(mib, 2, os_version, &os_version_len, NULL, 0) == -1) { free(os_version); return; } /* Parse the version: */ os_version_major = strtok(os_version, "."); os_version_minor = strtok(NULL, "."); /*os_version_point = strtok(NULL, ".");*/ *major = atoi(os_version_major); *minor = atoi(os_version_minor); free(os_version); } #endif /* CURL_BUILD_MAC */ /* Apple provides a myriad of ways of getting information about a certificate into a string. Some aren't available under iOS or newer cats. So here's a unified function for getting a string describing the certificate that ought to work in all cats starting with Leopard. */ CF_INLINE CFStringRef CopyCertSubject(SecCertificateRef cert) { CFStringRef server_cert_summary = CFSTR("(null)"); #if CURL_BUILD_IOS /* iOS: There's only one way to do this. */ server_cert_summary = SecCertificateCopySubjectSummary(cert); #else #if CURL_BUILD_MAC_10_7 /* Lion & later: Get the long description if we can. */ if(SecCertificateCopyLongDescription != NULL) server_cert_summary = SecCertificateCopyLongDescription(NULL, cert, NULL); else #endif /* CURL_BUILD_MAC_10_7 */ #if CURL_BUILD_MAC_10_6 /* Snow Leopard: Get the certificate summary. */ if(SecCertificateCopySubjectSummary != NULL) server_cert_summary = SecCertificateCopySubjectSummary(cert); else #endif /* CURL_BUILD_MAC_10_6 */ /* Leopard is as far back as we go... */ (void)SecCertificateCopyCommonName(cert, &server_cert_summary); #endif /* CURL_BUILD_IOS */ return server_cert_summary; } #if CURL_SUPPORT_MAC_10_7 /* The SecKeychainSearch API was deprecated in Lion, and using it will raise deprecation warnings, so let's not compile this unless it's necessary: */ static OSStatus CopyIdentityWithLabelOldSchool(char *label, SecIdentityRef *out_c_a_k) { OSStatus status = errSecItemNotFound; SecKeychainAttributeList attr_list; SecKeychainAttribute attr; SecKeychainSearchRef search = NULL; SecCertificateRef cert = NULL; /* Set up the attribute list: */ attr_list.count = 1L; attr_list.attr = &attr; /* Set up our lone search criterion: */ attr.tag = kSecLabelItemAttr; attr.data = label; attr.length = (UInt32)strlen(label); /* Start searching: */ status = SecKeychainSearchCreateFromAttributes(NULL, kSecCertificateItemClass, &attr_list, &search); if(status == noErr) { status = SecKeychainSearchCopyNext(search, (SecKeychainItemRef *)&cert); if(status == noErr && cert) { /* If we found a certificate, does it have a private key? */ status = SecIdentityCreateWithCertificate(NULL, cert, out_c_a_k); CFRelease(cert); } } if(search) CFRelease(search); return status; } #endif /* CURL_SUPPORT_MAC_10_7 */ static OSStatus CopyIdentityWithLabel(char *label, SecIdentityRef *out_cert_and_key) { OSStatus status = errSecItemNotFound; #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS /* SecItemCopyMatching() was introduced in iOS and Snow Leopard. kSecClassIdentity was introduced in Lion. If both exist, let's use them to find the certificate. */ if(SecItemCopyMatching != NULL && kSecClassIdentity != NULL) { CFTypeRef keys[4]; CFTypeRef values[4]; CFDictionaryRef query_dict; CFStringRef label_cf = CFStringCreateWithCString(NULL, label, kCFStringEncodingUTF8); /* Set up our search criteria and expected results: */ values[0] = kSecClassIdentity; /* we want a certificate and a key */ keys[0] = kSecClass; values[1] = kCFBooleanTrue; /* we want a reference */ keys[1] = kSecReturnRef; values[2] = kSecMatchLimitOne; /* one is enough, thanks */ keys[2] = kSecMatchLimit; /* identity searches need a SecPolicyRef in order to work */ values[3] = SecPolicyCreateSSL(false, label_cf); keys[3] = kSecMatchPolicy; query_dict = CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, 4L, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(values[3]); CFRelease(label_cf); /* Do we have a match? */ status = SecItemCopyMatching(query_dict, (CFTypeRef *)out_cert_and_key); CFRelease(query_dict); } else { #if CURL_SUPPORT_MAC_10_7 /* On Leopard and Snow Leopard, fall back to SecKeychainSearch. */ status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key); #endif /* CURL_SUPPORT_MAC_10_7 */ } #elif CURL_SUPPORT_MAC_10_7 /* For developers building on older cats, we have no choice but to fall back to SecKeychainSearch. */ status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key); #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ return status; } static CURLcode darwinssl_connect_step1(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif /* ENABLE_IPV6 */ size_t all_ciphers_count = 0UL, allowed_ciphers_count = 0UL, i; SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL; char *ssl_sessionid; size_t ssl_sessionid_len; OSStatus err = noErr; #if CURL_BUILD_MAC int darwinver_maj = 0, darwinver_min = 0; GetDarwinVersionNumber(&darwinver_maj, &darwinver_min); #endif /* CURL_BUILD_MAC */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLCreateContext != NULL) { /* use the newer API if avaialble */ if(connssl->ssl_ctx) CFRelease(connssl->ssl_ctx); connssl->ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType); if(!connssl->ssl_ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } } else { /* The old ST API does not exist under iOS, so don't compile it: */ #if CURL_SUPPORT_MAC_10_8 if(connssl->ssl_ctx) (void)SSLDisposeContext(connssl->ssl_ctx); err = SSLNewContext(false, &(connssl->ssl_ctx)); if(err != noErr) { failf(data, "SSL: couldn't create a context: OSStatus %d", err); return CURLE_OUT_OF_MEMORY; } #endif /* CURL_SUPPORT_MAC_10_8 */ } #else if(connssl->ssl_ctx) (void)SSLDisposeContext(connssl->ssl_ctx); err = SSLNewContext(false, &(connssl->ssl_ctx)); if(err != noErr) { failf(data, "SSL: couldn't create a context: OSStatus %d", err); return CURLE_OUT_OF_MEMORY; } #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ connssl->ssl_write_buffered_length = 0UL; /* reset buffered write length */ /* check to see if we've been told to use an explicit SSL/TLS version */ #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLSetProtocolVersionMax != NULL) { switch(data->set.ssl.version) { case CURL_SSLVERSION_DEFAULT: default: (void)SSLSetProtocolVersionMin(connssl->ssl_ctx, kSSLProtocol3); (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kTLSProtocol12); break; case CURL_SSLVERSION_TLSv1: (void)SSLSetProtocolVersionMin(connssl->ssl_ctx, kTLSProtocol1); (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kTLSProtocol12); break; case CURL_SSLVERSION_SSLv3: (void)SSLSetProtocolVersionMin(connssl->ssl_ctx, kSSLProtocol3); (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kSSLProtocol3); break; case CURL_SSLVERSION_SSLv2: err = SSLSetProtocolVersionMin(connssl->ssl_ctx, kSSLProtocol2); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kSSLProtocol2); } } else { #if CURL_SUPPORT_MAC_10_8 (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocolAll, false); switch (data->set.ssl.version) { case CURL_SSLVERSION_DEFAULT: default: (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocol3, true); (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol1, true); (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol11, true); (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol12, true); break; case CURL_SSLVERSION_TLSv1: (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol1, true); (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol11, true); (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol12, true); break; case CURL_SSLVERSION_SSLv3: (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocol3, true); break; case CURL_SSLVERSION_SSLv2: err = SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocol2, true); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } break; } #endif /* CURL_SUPPORT_MAC_10_8 */ } #else (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocolAll, false); switch(data->set.ssl.version) { default: case CURL_SSLVERSION_DEFAULT: (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocol3, true); (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol1, true); break; case CURL_SSLVERSION_TLSv1: (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kTLSProtocol1, true); break; case CURL_SSLVERSION_SSLv2: err = SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocol2, true); if(err != noErr) { failf(data, "Your version of the OS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } break; case CURL_SSLVERSION_SSLv3: (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocol3, true); break; } #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ if(data->set.str[STRING_KEY]) { infof(data, "WARNING: SSL: CURLOPT_SSLKEY is ignored by Secure " "Transport. The private key must be in the Keychain.\n"); } if(data->set.str[STRING_CERT]) { SecIdentityRef cert_and_key = NULL; /* User wants to authenticate with a client cert. Look for it: */ err = CopyIdentityWithLabel(data->set.str[STRING_CERT], &cert_and_key); if(err == noErr) { SecCertificateRef cert = NULL; CFTypeRef certs_c[1]; CFArrayRef certs; /* If we found one, print it out: */ err = SecIdentityCopyCertificate(cert_and_key, &cert); if(err == noErr) { CFStringRef cert_summary = CopyCertSubject(cert); char cert_summary_c[128]; if(cert_summary) { memset(cert_summary_c, 0, 128); if(CFStringGetCString(cert_summary, cert_summary_c, 128, kCFStringEncodingUTF8)) { infof(data, "Client certificate: %s\n", cert_summary_c); } CFRelease(cert_summary); CFRelease(cert); } } certs_c[0] = cert_and_key; certs = CFArrayCreate(NULL, (const void **)certs_c, 1L, &kCFTypeArrayCallBacks); err = SSLSetCertificate(connssl->ssl_ctx, certs); if(certs) CFRelease(certs); if(err != noErr) { failf(data, "SSL: SSLSetCertificate() failed: OSStatus %d", err); return CURLE_SSL_CERTPROBLEM; } CFRelease(cert_and_key); } else { failf(data, "SSL: Can't find the certificate \"%s\" and its private key " "in the Keychain.", data->set.str[STRING_CERT]); return CURLE_SSL_CERTPROBLEM; } } /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS /* Snow Leopard introduced the SSLSetSessionOption() function, but due to a library bug with the way the kSSLSessionOptionBreakOnServerAuth flag works, it doesn't work as expected under Snow Leopard or Lion. So we need to call SSLSetEnableCertVerify() on those older cats in order to disable certificate validation if the user turned that off. (SecureTransport will always validate the certificate chain by default.) */ /* (Note: Darwin 12.x.x is Mountain Lion.) */ #if CURL_BUILD_MAC if(SSLSetSessionOption != NULL && darwinver_maj >= 12) { #else if(SSLSetSessionOption != NULL) { #endif /* CURL_BUILD_MAC */ err = SSLSetSessionOption(connssl->ssl_ctx, kSSLSessionOptionBreakOnServerAuth, data->set.ssl.verifypeer?false:true); if(err != noErr) { failf(data, "SSL: SSLSetSessionOption() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } } else { #if CURL_SUPPORT_MAC_10_8 err = SSLSetEnableCertVerify(connssl->ssl_ctx, data->set.ssl.verifypeer?true:false); if(err != noErr) { failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } #endif /* CURL_SUPPORT_MAC_10_8 */ } #else err = SSLSetEnableCertVerify(connssl->ssl_ctx, data->set.ssl.verifypeer?true:false); if(err != noErr) { failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ /* If this is a domain name and not an IP address, then configure SNI. * Also: the verifyhost setting influences SNI usage */ /* If this is a domain name and not an IP address, then configure SNI: */ if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) && #ifdef ENABLE_IPV6 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) && #endif data->set.ssl.verifyhost) { err = SSLSetPeerDomainName(connssl->ssl_ctx, conn->host.name, strlen(conn->host.name)); if(err != noErr) { infof(data, "WARNING: SSL: SSLSetPeerDomainName() failed: OSStatus %d\n", err); } } /* Disable cipher suites that ST supports but are not safe. These ciphers are unlikely to be used in any case since ST gives other ciphers a much higher priority, but it's probably better that we not connect at all than to give the user a false sense of security if the server only supports insecure ciphers. (Note: We don't care about SSLv2-only ciphers.) */ (void)SSLGetNumberSupportedCiphers(connssl->ssl_ctx, &all_ciphers_count); all_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite)); allowed_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite)); if(all_ciphers && allowed_ciphers && SSLGetSupportedCiphers(connssl->ssl_ctx, all_ciphers, &all_ciphers_count) == noErr) { for(i = 0UL ; i < all_ciphers_count ; i++) { #if CURL_BUILD_MAC /* There's a known bug in early versions of Mountain Lion where ST's ECC ciphers (cipher suite 0xC001 through 0xC032) simply do not work. Work around the problem here by disabling those ciphers if we are running in an affected version of OS X. */ if(darwinver_maj == 12 && darwinver_min <= 3 && all_ciphers[i] >= 0xC001 && all_ciphers[i] <= 0xC032) { continue; } #endif /* CURL_BUILD_MAC */ switch(all_ciphers[i]) { /* Disable NULL ciphersuites: */ case SSL_NULL_WITH_NULL_NULL: case SSL_RSA_WITH_NULL_MD5: case SSL_RSA_WITH_NULL_SHA: case SSL_FORTEZZA_DMS_WITH_NULL_SHA: case 0xC001: /* TLS_ECDH_ECDSA_WITH_NULL_SHA */ case 0xC006: /* TLS_ECDHE_ECDSA_WITH_NULL_SHA */ case 0xC00B: /* TLS_ECDH_RSA_WITH_NULL_SHA */ case 0xC010: /* TLS_ECDHE_RSA_WITH_NULL_SHA */ /* Disable anonymous ciphersuites: */ case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5: case SSL_DH_anon_WITH_RC4_128_MD5: case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA: case SSL_DH_anon_WITH_DES_CBC_SHA: case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA: case TLS_DH_anon_WITH_AES_128_CBC_SHA: case TLS_DH_anon_WITH_AES_256_CBC_SHA: case 0xC015: /* TLS_ECDH_anon_WITH_NULL_SHA */ case 0xC016: /* TLS_ECDH_anon_WITH_RC4_128_SHA */ case 0xC017: /* TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA */ case 0xC018: /* TLS_ECDH_anon_WITH_AES_128_CBC_SHA */ case 0xC019: /* TLS_ECDH_anon_WITH_AES_256_CBC_SHA */ case 0x006C: /* TLS_DH_anon_WITH_AES_128_CBC_SHA256 */ case 0x006D: /* TLS_DH_anon_WITH_AES_256_CBC_SHA256 */ case 0x00A6: /* TLS_DH_anon_WITH_AES_128_GCM_SHA256 */ case 0x00A7: /* TLS_DH_anon_WITH_AES_256_GCM_SHA384 */ /* Disable weak key ciphersuites: */ case SSL_RSA_EXPORT_WITH_RC4_40_MD5: case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5: case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA: case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: case SSL_RSA_WITH_DES_CBC_SHA: case SSL_DH_DSS_WITH_DES_CBC_SHA: case SSL_DH_RSA_WITH_DES_CBC_SHA: case SSL_DHE_DSS_WITH_DES_CBC_SHA: case SSL_DHE_RSA_WITH_DES_CBC_SHA: /* Disable IDEA: */ case SSL_RSA_WITH_IDEA_CBC_SHA: case SSL_RSA_WITH_IDEA_CBC_MD5: break; default: /* enable everything else */ allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i]; break; } } err = SSLSetEnabledCiphers(connssl->ssl_ctx, allowed_ciphers, allowed_ciphers_count); if(err != noErr) { failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } } else { Curl_safefree(all_ciphers); Curl_safefree(allowed_ciphers); failf(data, "SSL: Failed to allocate memory for allowed ciphers"); return CURLE_OUT_OF_MEMORY; } Curl_safefree(all_ciphers); Curl_safefree(allowed_ciphers); /* Check if there's a cached ID we can/should use here! */ if(!Curl_ssl_getsessionid(conn, (void **)&ssl_sessionid, &ssl_sessionid_len)) { /* we got a session id, use it! */ err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len); if(err != noErr) { failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof(data, "SSL re-using session ID\n"); } /* If there isn't one, then let's make one up! This has to be done prior to starting the handshake. */ else { CURLcode retcode; ssl_sessionid = malloc(256*sizeof(char)); ssl_sessionid_len = snprintf(ssl_sessionid, 256, "curl:%s:%hu", conn->host.name, conn->remote_port); err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len); if(err != noErr) { failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } retcode = Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_sessionid_len); if(retcode!= CURLE_OK) { failf(data, "failed to store ssl session"); return retcode; } } err = SSLSetIOFuncs(connssl->ssl_ctx, SocketRead, SocketWrite); if(err != noErr) { failf(data, "SSL: SSLSetIOFuncs() failed: OSStatus %d", err); return CURLE_SSL_CONNECT_ERROR; } /* pass the raw socket into the SSL layers */ /* We need to store the FD in a constant memory address, because * SSLSetConnection() will not copy that address. I've found that * conn->sock[sockindex] may change on its own. */ connssl->ssl_sockfd = sockfd; err = SSLSetConnection(connssl->ssl_ctx, connssl); if(err != noErr) { failf(data, "SSL: SSLSetConnection() failed: %d", err); return CURLE_SSL_CONNECT_ERROR; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode darwinssl_connect_step2(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; OSStatus err; SSLCipherSuite cipher; SSLProtocol protocol = 0; DEBUGASSERT(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state); /* Here goes nothing: */ err = SSLHandshake(connssl->ssl_ctx); if(err != noErr) { switch (err) { case errSSLWouldBlock: /* they're not done with us yet */ connssl->connecting_state = connssl->ssl_direction ? ssl_connect_2_writing : ssl_connect_2_reading; return CURLE_OK; /* The below is errSSLServerAuthCompleted; it's not defined in Leopard's headers */ case -9841: /* the documentation says we need to call SSLHandshake() again */ return darwinssl_connect_step2(conn, sockindex); /* These are all certificate problems with the server: */ case errSSLXCertChainInvalid: failf(data, "SSL certificate problem: Invalid certificate chain"); return CURLE_SSL_CACERT; case errSSLUnknownRootCert: failf(data, "SSL certificate problem: Untrusted root certificate"); return CURLE_SSL_CACERT; case errSSLNoRootCert: failf(data, "SSL certificate problem: No root certificate"); return CURLE_SSL_CACERT; case errSSLCertExpired: failf(data, "SSL certificate problem: Certificate chain had an " "expired certificate"); return CURLE_SSL_CACERT; case errSSLBadCert: failf(data, "SSL certificate problem: Couldn't understand the server " "certificate format"); return CURLE_SSL_CONNECT_ERROR; /* These are all certificate problems with the client: */ case errSecAuthFailed: failf(data, "SSL authentication failed"); return CURLE_SSL_CONNECT_ERROR; case errSSLPeerHandshakeFail: failf(data, "SSL peer handshake failed, the server most likely " "requires a client certificate to connect"); return CURLE_SSL_CONNECT_ERROR; case errSSLPeerUnknownCA: failf(data, "SSL server rejected the client certificate due to " "the certificate being signed by an unknown certificate " "authority"); return CURLE_SSL_CONNECT_ERROR; /* This error is raised if the server's cert didn't match the server's host name: */ case errSSLHostNameMismatch: failf(data, "SSL certificate peer verification failed, the " "certificate did not match \"%s\"\n", conn->host.dispname); return CURLE_PEER_FAILED_VERIFICATION; /* Generic handshake errors: */ case errSSLConnectionRefused: failf(data, "Server dropped the connection during the SSL handshake"); return CURLE_SSL_CONNECT_ERROR; case errSSLClosedAbort: failf(data, "Server aborted the SSL handshake"); return CURLE_SSL_CONNECT_ERROR; case errSSLNegotiation: failf(data, "Could not negotiate an SSL cipher suite with the server"); return CURLE_SSL_CONNECT_ERROR; /* Sometimes paramErr happens with buggy ciphers: */ case paramErr: case errSSLInternal: failf(data, "Internal SSL engine error encountered during the " "SSL handshake"); return CURLE_SSL_CONNECT_ERROR; case errSSLFatalAlert: failf(data, "Fatal SSL engine error encountered during the SSL " "handshake"); return CURLE_SSL_CONNECT_ERROR; default: failf(data, "Unknown SSL protocol error in connection to %s:%d", conn->host.name, err); return CURLE_SSL_CONNECT_ERROR; } } else { /* we have been connected fine, we're not waiting for anything else. */ connssl->connecting_state = ssl_connect_3; /* Informational message */ (void)SSLGetNegotiatedCipher(connssl->ssl_ctx, &cipher); (void)SSLGetNegotiatedProtocolVersion(connssl->ssl_ctx, &protocol); switch (protocol) { case kSSLProtocol2: infof(data, "SSL 2.0 connection using %s\n", SSLCipherNameForNumber(cipher)); break; case kSSLProtocol3: infof(data, "SSL 3.0 connection using %s\n", SSLCipherNameForNumber(cipher)); break; case kTLSProtocol1: infof(data, "TLS 1.0 connection using %s\n", TLSCipherNameForNumber(cipher)); break; #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS case kTLSProtocol11: infof(data, "TLS 1.1 connection using %s\n", TLSCipherNameForNumber(cipher)); break; case kTLSProtocol12: infof(data, "TLS 1.2 connection using %s\n", TLSCipherNameForNumber(cipher)); break; #endif default: infof(data, "Unknown protocol connection\n"); break; } return CURLE_OK; } } static CURLcode darwinssl_connect_step3(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; CFStringRef server_cert_summary; char server_cert_summary_c[128]; CFArrayRef server_certs = NULL; SecCertificateRef server_cert; OSStatus err; CFIndex i, count; SecTrustRef trust = NULL; /* There is no step 3! * Well, okay, if verbose mode is on, let's print the details of the * server certificates. */ #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS #if CURL_BUILD_IOS #pragma unused(server_certs) err = SSLCopyPeerTrust(connssl->ssl_ctx, &trust); /* For some reason, SSLCopyPeerTrust() can return noErr and yet return a null trust, so be on guard for that: */ if(err == noErr && trust) { count = SecTrustGetCertificateCount(trust); for(i = 0L ; i < count ; i++) { server_cert = SecTrustGetCertificateAtIndex(trust, i); server_cert_summary = CopyCertSubject(server_cert); memset(server_cert_summary_c, 0, 128); if(CFStringGetCString(server_cert_summary, server_cert_summary_c, 128, kCFStringEncodingUTF8)) { infof(data, "Server certificate: %s\n", server_cert_summary_c); } CFRelease(server_cert_summary); } CFRelease(trust); } #else /* SSLCopyPeerCertificates() is deprecated as of Mountain Lion. The function SecTrustGetCertificateAtIndex() is officially present in Lion, but it is unfortunately also present in Snow Leopard as private API and doesn't work as expected. So we have to look for a different symbol to make sure this code is only executed under Lion or later. */ if(SecTrustEvaluateAsync != NULL) { #pragma unused(server_certs) err = SSLCopyPeerTrust(connssl->ssl_ctx, &trust); /* For some reason, SSLCopyPeerTrust() can return noErr and yet return a null trust, so be on guard for that: */ if(err == noErr && trust) { count = SecTrustGetCertificateCount(trust); for(i = 0L ; i < count ; i++) { server_cert = SecTrustGetCertificateAtIndex(trust, i); server_cert_summary = CopyCertSubject(server_cert); memset(server_cert_summary_c, 0, 128); if(CFStringGetCString(server_cert_summary, server_cert_summary_c, 128, kCFStringEncodingUTF8)) { infof(data, "Server certificate: %s\n", server_cert_summary_c); } CFRelease(server_cert_summary); } CFRelease(trust); } } else { #if CURL_SUPPORT_MAC_10_8 err = SSLCopyPeerCertificates(connssl->ssl_ctx, &server_certs); /* Just in case SSLCopyPeerCertificates() returns null too... */ if(err == noErr && server_certs) { count = CFArrayGetCount(server_certs); for(i = 0L ; i < count ; i++) { server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i); server_cert_summary = CopyCertSubject(server_cert); memset(server_cert_summary_c, 0, 128); if(CFStringGetCString(server_cert_summary, server_cert_summary_c, 128, kCFStringEncodingUTF8)) { infof(data, "Server certificate: %s\n", server_cert_summary_c); } CFRelease(server_cert_summary); } CFRelease(server_certs); } #endif /* CURL_SUPPORT_MAC_10_8 */ } #endif /* CURL_BUILD_IOS */ #else #pragma unused(trust) err = SSLCopyPeerCertificates(connssl->ssl_ctx, &server_certs); if(err == noErr) { count = CFArrayGetCount(server_certs); for(i = 0L ; i < count ; i++) { server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i); server_cert_summary = CopyCertSubject(server_cert); memset(server_cert_summary_c, 0, 128); if(CFStringGetCString(server_cert_summary, server_cert_summary_c, 128, kCFStringEncodingUTF8)) { infof(data, "Server certificate: %s\n", server_cert_summary_c); } CFRelease(server_cert_summary); } CFRelease(server_certs); } #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */ connssl->connecting_state = ssl_connect_done; return CURLE_OK; } static Curl_recv darwinssl_recv; static Curl_send darwinssl_send; static CURLcode darwinssl_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode retcode; struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; int what; /* check if the connection has already been established */ if(ssl_connection_complete == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1==connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } retcode = darwinssl_connect_step1(conn, sockindex); if(retcode) return retcode; } while(ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == ssl_connect_2_reading || connssl->connecting_state == ssl_connect_2_writing) { curl_socket_t writefd = ssl_connect_2_writing == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = ssl_connect_2_reading == connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return CURLE_SSL_CONNECT_ERROR; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if this * connection is done nonblocking and this loop would execute again. This * permits the owner of a multi handle to abort a connection attempt * before step2 has completed while ensuring that a client using select() * or epoll() will always have a valid fdset to wait on. */ retcode = darwinssl_connect_step2(conn, sockindex); if(retcode || (nonblocking && (ssl_connect_2 == connssl->connecting_state || ssl_connect_2_reading == connssl->connecting_state || ssl_connect_2_writing == connssl->connecting_state))) return retcode; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3==connssl->connecting_state) { retcode = darwinssl_connect_step3(conn, sockindex); if(retcode) return retcode; } if(ssl_connect_done==connssl->connecting_state) { connssl->state = ssl_connection_complete; conn->recv[sockindex] = darwinssl_recv; conn->send[sockindex] = darwinssl_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } CURLcode Curl_darwinssl_connect_nonblocking(struct connectdata *conn, int sockindex, bool *done) { return darwinssl_connect_common(conn, sockindex, TRUE, done); } CURLcode Curl_darwinssl_connect(struct connectdata *conn, int sockindex) { CURLcode retcode; bool done = FALSE; retcode = darwinssl_connect_common(conn, sockindex, FALSE, &done); if(retcode) return retcode; DEBUGASSERT(done); return CURLE_OK; } void Curl_darwinssl_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->ssl_ctx) { (void)SSLClose(connssl->ssl_ctx); #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS if(SSLCreateContext != NULL) CFRelease(connssl->ssl_ctx); #if CURL_SUPPORT_MAC_10_8 else (void)SSLDisposeContext(connssl->ssl_ctx); #endif /* CURL_SUPPORT_MAC_10_8 */ #else (void)SSLDisposeContext(connssl->ssl_ctx); #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ connssl->ssl_ctx = NULL; } connssl->ssl_sockfd = 0; } void Curl_darwinssl_close_all(struct SessionHandle *data) { /* SecureTransport doesn't separate sessions from contexts, so... */ (void)data; } int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct SessionHandle *data = conn->data; ssize_t nread; int what; int rc; char buf[120]; if(!connssl->ssl_ctx) return 0; if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE) return 0; Curl_darwinssl_close(conn, sockindex); rc = 0; what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT); for(;;) { if(what < 0) { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); rc = -1; break; } if(!what) { /* timeout */ failf(data, "SSL shutdown timeout"); break; } /* Something to read, let's do it and hope that it is the close notify alert from the server. No way to SSL_Read now, so use read(). */ nread = read(conn->sock[sockindex], buf, sizeof(buf)); if(nread < 0) { failf(data, "read: %s", strerror(errno)); rc = -1; } if(nread <= 0) break; what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, 0); } return rc; } void Curl_darwinssl_session_free(void *ptr) { /* ST, as of iOS 5 and Mountain Lion, has no public method of deleting a cached session ID inside the Security framework. There is a private function that does this, but I don't want to have to explain to you why I got your application rejected from the App Store due to the use of a private API, so the best we can do is free up our own char array that we created way back in darwinssl_connect_step1... */ Curl_safefree(ptr); } size_t Curl_darwinssl_version(char *buffer, size_t size) { return snprintf(buffer, size, "SecureTransport"); } /* * This function uses SSLGetSessionState to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */ int Curl_darwinssl_check_cxn(struct connectdata *conn) { struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET]; OSStatus err; SSLSessionState state; if(connssl->ssl_ctx) { err = SSLGetSessionState(connssl->ssl_ctx, &state); if(err == noErr) return state == kSSLConnected || state == kSSLHandshake; return -1; } return 0; } bool Curl_darwinssl_data_pending(const struct connectdata *conn, int connindex) { const struct ssl_connect_data *connssl = &conn->ssl[connindex]; OSStatus err; size_t buffer; if(connssl->ssl_ctx) { /* SSL is in use */ err = SSLGetBufferedReadSize(connssl->ssl_ctx, &buffer); if(err == noErr) return buffer > 0UL; return false; } else return false; } void Curl_darwinssl_random(struct SessionHandle *data, unsigned char *entropy, size_t length) { /* arc4random_buf() isn't available on cats older than Lion, so let's do this manually for the benefit of the older cats. */ size_t i; u_int32_t random_number = 0; for(i = 0 ; i < length ; i++) { if(i % sizeof(u_int32_t) == 0) random_number = arc4random(); entropy[i] = random_number & 0xFF; random_number >>= 8; } i = random_number = 0; (void)data; } void Curl_darwinssl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum, /* output */ size_t md5len) { (void)md5len; (void)CC_MD5(tmp, (CC_LONG)tmplen, md5sum); } static ssize_t darwinssl_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { /*struct SessionHandle *data = conn->data;*/ struct ssl_connect_data *connssl = &conn->ssl[sockindex]; size_t processed = 0UL; OSStatus err; /* The SSLWrite() function works a little differently than expected. The fourth argument (processed) is currently documented in Apple's documentation as: "On return, the length, in bytes, of the data actually written." Now, one could interpret that as "written to the socket," but actually, it returns the amount of data that was written to a buffer internal to the SSLContextRef instead. So it's possible for SSLWrite() to return errSSLWouldBlock and a number of bytes "written" because those bytes were encrypted and written to a buffer, not to the socket. So if this happens, then we need to keep calling SSLWrite() over and over again with no new data until it quits returning errSSLWouldBlock. */ /* Do we have buffered data to write from the last time we were called? */ if(connssl->ssl_write_buffered_length) { /* Write the buffered data: */ err = SSLWrite(connssl->ssl_ctx, NULL, 0UL, &processed); switch (err) { case noErr: /* processed is always going to be 0 because we didn't write to the buffer, so return how much was written to the socket */ processed = connssl->ssl_write_buffered_length; connssl->ssl_write_buffered_length = 0UL; break; case errSSLWouldBlock: /* argh, try again */ *curlcode = CURLE_AGAIN; return -1L; default: failf(conn->data, "SSLWrite() returned error %d", err); *curlcode = CURLE_SEND_ERROR; return -1L; } } else { /* We've got new data to write: */ err = SSLWrite(connssl->ssl_ctx, mem, len, &processed); if(err != noErr) { switch (err) { case errSSLWouldBlock: /* Data was buffered but not sent, we have to tell the caller to try sending again, and remember how much was buffered */ connssl->ssl_write_buffered_length = len; *curlcode = CURLE_AGAIN; return -1L; default: failf(conn->data, "SSLWrite() returned error %d", err); *curlcode = CURLE_SEND_ERROR; return -1L; } } } return (ssize_t)processed; } static ssize_t darwinssl_recv(struct connectdata *conn, int num, char *buf, size_t buffersize, CURLcode *curlcode) { /*struct SessionHandle *data = conn->data;*/ struct ssl_connect_data *connssl = &conn->ssl[num]; size_t processed = 0UL; OSStatus err = SSLRead(connssl->ssl_ctx, buf, buffersize, &processed); if(err != noErr) { switch (err) { case errSSLWouldBlock: /* return how much we read (if anything) */ if(processed) return (ssize_t)processed; *curlcode = CURLE_AGAIN; return -1L; break; /* errSSLClosedGraceful - server gracefully shut down the SSL session errSSLClosedNoNotify - server hung up on us instead of sending a closure alert notice, read() is returning 0 Either way, inform the caller that the server disconnected. */ case errSSLClosedGraceful: case errSSLClosedNoNotify: *curlcode = CURLE_OK; return -1L; break; default: failf(conn->data, "SSLRead() return error %d", err); *curlcode = CURLE_RECV_ERROR; return -1L; break; } } return (ssize_t)processed; } #endif /* USE_DARWINSSL */
gpl-3.0
SkyFireArchives/SkyFireEMU_406a
dep/zlib/uncompr.c
33
2086
/* uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. This function can be used to decompress a whole file at once if the input file is mmap'ed. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted. */ int ZEXPORT uncompress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; }
gpl-3.0
rickytan/shadowsocks-android
src/main/jni/openssl/crypto/ecdsa/ecs_err.c
545
4284
/* crypto/ecdsa/ecs_err.c */ /* ==================================================================== * Copyright (c) 1999-2011 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* NOTE: this file was auto generated by the mkerr.pl script: any changes * made to it will be overwritten when the script next updates this file, * only reason strings will be preserved. */ #include <stdio.h> #include <openssl/err.h> #include <openssl/ecdsa.h> /* BEGIN ERROR CODES */ #ifndef OPENSSL_NO_ERR #define ERR_FUNC(func) ERR_PACK(ERR_LIB_ECDSA,func,0) #define ERR_REASON(reason) ERR_PACK(ERR_LIB_ECDSA,0,reason) static ERR_STRING_DATA ECDSA_str_functs[]= { {ERR_FUNC(ECDSA_F_ECDSA_CHECK), "ECDSA_CHECK"}, {ERR_FUNC(ECDSA_F_ECDSA_DATA_NEW_METHOD), "ECDSA_DATA_NEW_METHOD"}, {ERR_FUNC(ECDSA_F_ECDSA_DO_SIGN), "ECDSA_do_sign"}, {ERR_FUNC(ECDSA_F_ECDSA_DO_VERIFY), "ECDSA_do_verify"}, {ERR_FUNC(ECDSA_F_ECDSA_SIGN_SETUP), "ECDSA_sign_setup"}, {0,NULL} }; static ERR_STRING_DATA ECDSA_str_reasons[]= { {ERR_REASON(ECDSA_R_BAD_SIGNATURE) ,"bad signature"}, {ERR_REASON(ECDSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE),"data too large for key size"}, {ERR_REASON(ECDSA_R_ERR_EC_LIB) ,"err ec lib"}, {ERR_REASON(ECDSA_R_MISSING_PARAMETERS) ,"missing parameters"}, {ERR_REASON(ECDSA_R_NEED_NEW_SETUP_VALUES),"need new setup values"}, {ERR_REASON(ECDSA_R_NON_FIPS_METHOD) ,"non fips method"}, {ERR_REASON(ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED),"random number generation failed"}, {ERR_REASON(ECDSA_R_SIGNATURE_MALLOC_FAILED),"signature malloc failed"}, {0,NULL} }; #endif void ERR_load_ECDSA_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(ECDSA_str_functs[0].error) == NULL) { ERR_load_strings(0,ECDSA_str_functs); ERR_load_strings(0,ECDSA_str_reasons); } #endif }
gpl-3.0
lexi6725/u-boot-2015-04
scripts/docproc.c
1571
14132
/* * docproc is a simple preprocessor for the template files * used as placeholders for the kernel internal documentation. * docproc is used for documentation-frontend and * dependency-generator. * The two usages have in common that they require * some knowledge of the .tmpl syntax, therefore they * are kept together. * * documentation-frontend * Scans the template file and call kernel-doc for * all occurrences of ![EIF]file * Beforehand each referenced file is scanned for * any symbols that are exported via these macros: * EXPORT_SYMBOL(), EXPORT_SYMBOL_GPL(), & * EXPORT_SYMBOL_GPL_FUTURE() * This is used to create proper -function and * -nofunction arguments in calls to kernel-doc. * Usage: docproc doc file.tmpl * * dependency-generator: * Scans the template file and list all files * referenced in a format recognized by make. * Usage: docproc depend file.tmpl * Writes dependency information to stdout * in the following format: * file.tmpl src.c src2.c * The filenames are obtained from the following constructs: * !Efilename * !Ifilename * !Dfilename * !Ffilename * !Pfilename * */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <limits.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> /* exitstatus is used to keep track of any failing calls to kernel-doc, * but execution continues. */ int exitstatus = 0; typedef void DFL(char *); DFL *defaultline; typedef void FILEONLY(char * file); FILEONLY *internalfunctions; FILEONLY *externalfunctions; FILEONLY *symbolsonly; FILEONLY *findall; typedef void FILELINE(char * file, char * line); FILELINE * singlefunctions; FILELINE * entity_system; FILELINE * docsection; #define MAXLINESZ 2048 #define MAXFILES 250 #define KERNELDOCPATH "scripts/" #define KERNELDOC "kernel-doc" #define DOCBOOK "-docbook" #define LIST "-list" #define FUNCTION "-function" #define NOFUNCTION "-nofunction" #define NODOCSECTIONS "-no-doc-sections" #define SHOWNOTFOUND "-show-not-found" static char *srctree, *kernsrctree; static char **all_list = NULL; static int all_list_len = 0; static void consume_symbol(const char *sym) { int i; for (i = 0; i < all_list_len; i++) { if (!all_list[i]) continue; if (strcmp(sym, all_list[i])) continue; all_list[i] = NULL; break; } } static void usage (void) { fprintf(stderr, "Usage: docproc {doc|depend} file\n"); fprintf(stderr, "Input is read from file.tmpl. Output is sent to stdout\n"); fprintf(stderr, "doc: frontend when generating kernel documentation\n"); fprintf(stderr, "depend: generate list of files referenced within file\n"); fprintf(stderr, "Environment variable SRCTREE: absolute path to sources.\n"); fprintf(stderr, " KBUILD_SRC: absolute path to kernel source tree.\n"); } /* * Execute kernel-doc with parameters given in svec */ static void exec_kernel_doc(char **svec) { pid_t pid; int ret; char real_filename[PATH_MAX + 1]; /* Make sure output generated so far are flushed */ fflush(stdout); switch (pid=fork()) { case -1: perror("fork"); exit(1); case 0: memset(real_filename, 0, sizeof(real_filename)); strncat(real_filename, kernsrctree, PATH_MAX); strncat(real_filename, "/" KERNELDOCPATH KERNELDOC, PATH_MAX - strlen(real_filename)); execvp(real_filename, svec); fprintf(stderr, "exec "); perror(real_filename); exit(1); default: waitpid(pid, &ret ,0); } if (WIFEXITED(ret)) exitstatus |= WEXITSTATUS(ret); else exitstatus = 0xff; } /* Types used to create list of all exported symbols in a number of files */ struct symbols { char *name; }; struct symfile { char *filename; struct symbols *symbollist; int symbolcnt; }; struct symfile symfilelist[MAXFILES]; int symfilecnt = 0; static void add_new_symbol(struct symfile *sym, char * symname) { sym->symbollist = realloc(sym->symbollist, (sym->symbolcnt + 1) * sizeof(char *)); sym->symbollist[sym->symbolcnt++].name = strdup(symname); } /* Add a filename to the list */ static struct symfile * add_new_file(char * filename) { symfilelist[symfilecnt++].filename = strdup(filename); return &symfilelist[symfilecnt - 1]; } /* Check if file already are present in the list */ static struct symfile * filename_exist(char * filename) { int i; for (i=0; i < symfilecnt; i++) if (strcmp(symfilelist[i].filename, filename) == 0) return &symfilelist[i]; return NULL; } /* * List all files referenced within the template file. * Files are separated by tabs. */ static void adddep(char * file) { printf("\t%s", file); } static void adddep2(char * file, char * line) { line = line; adddep(file); } static void noaction(char * line) { line = line; } static void noaction2(char * file, char * line) { file = file; line = line; } /* Echo the line without further action */ static void printline(char * line) { printf("%s", line); } /* * Find all symbols in filename that are exported with EXPORT_SYMBOL & * EXPORT_SYMBOL_GPL (& EXPORT_SYMBOL_GPL_FUTURE implicitly). * All symbols located are stored in symfilelist. */ static void find_export_symbols(char * filename) { FILE * fp; struct symfile *sym; char line[MAXLINESZ]; if (filename_exist(filename) == NULL) { char real_filename[PATH_MAX + 1]; memset(real_filename, 0, sizeof(real_filename)); strncat(real_filename, srctree, PATH_MAX); strncat(real_filename, "/", PATH_MAX - strlen(real_filename)); strncat(real_filename, filename, PATH_MAX - strlen(real_filename)); sym = add_new_file(filename); fp = fopen(real_filename, "r"); if (fp == NULL) { fprintf(stderr, "docproc: "); perror(real_filename); exit(1); } while (fgets(line, MAXLINESZ, fp)) { char *p; char *e; if (((p = strstr(line, "EXPORT_SYMBOL_GPL")) != NULL) || ((p = strstr(line, "EXPORT_SYMBOL")) != NULL)) { /* Skip EXPORT_SYMBOL{_GPL} */ while (isalnum(*p) || *p == '_') p++; /* Remove parentheses & additional whitespace */ while (isspace(*p)) p++; if (*p != '(') continue; /* Syntax error? */ else p++; while (isspace(*p)) p++; e = p; while (isalnum(*e) || *e == '_') e++; *e = '\0'; add_new_symbol(sym, p); } } fclose(fp); } } /* * Document all external or internal functions in a file. * Call kernel-doc with following parameters: * kernel-doc -docbook -nofunction function_name1 filename * Function names are obtained from all the src files * by find_export_symbols. * intfunc uses -nofunction * extfunc uses -function */ static void docfunctions(char * filename, char * type) { int i,j; int symcnt = 0; int idx = 0; char **vec; for (i=0; i <= symfilecnt; i++) symcnt += symfilelist[i].symbolcnt; vec = malloc((2 + 2 * symcnt + 3) * sizeof(char *)); if (vec == NULL) { perror("docproc: "); exit(1); } vec[idx++] = KERNELDOC; vec[idx++] = DOCBOOK; vec[idx++] = NODOCSECTIONS; for (i=0; i < symfilecnt; i++) { struct symfile * sym = &symfilelist[i]; for (j=0; j < sym->symbolcnt; j++) { vec[idx++] = type; consume_symbol(sym->symbollist[j].name); vec[idx++] = sym->symbollist[j].name; } } vec[idx++] = filename; vec[idx] = NULL; printf("<!-- %s -->\n", filename); exec_kernel_doc(vec); fflush(stdout); free(vec); } static void intfunc(char * filename) { docfunctions(filename, NOFUNCTION); } static void extfunc(char * filename) { docfunctions(filename, FUNCTION); } /* * Document specific function(s) in a file. * Call kernel-doc with the following parameters: * kernel-doc -docbook -function function1 [-function function2] */ static void singfunc(char * filename, char * line) { char *vec[200]; /* Enough for specific functions */ int i, idx = 0; int startofsym = 1; vec[idx++] = KERNELDOC; vec[idx++] = DOCBOOK; vec[idx++] = SHOWNOTFOUND; /* Split line up in individual parameters preceded by FUNCTION */ for (i=0; line[i]; i++) { if (isspace(line[i])) { line[i] = '\0'; startofsym = 1; continue; } if (startofsym) { startofsym = 0; vec[idx++] = FUNCTION; vec[idx++] = &line[i]; } } for (i = 0; i < idx; i++) { if (strcmp(vec[i], FUNCTION)) continue; consume_symbol(vec[i + 1]); } vec[idx++] = filename; vec[idx] = NULL; exec_kernel_doc(vec); } /* * Insert specific documentation section from a file. * Call kernel-doc with the following parameters: * kernel-doc -docbook -function "doc section" filename */ static void docsect(char *filename, char *line) { /* kerneldoc -docbook -show-not-found -function "section" file NULL */ char *vec[7]; char *s; for (s = line; *s; s++) if (*s == '\n') *s = '\0'; if (asprintf(&s, "DOC: %s", line) < 0) { perror("asprintf"); exit(1); } consume_symbol(s); free(s); vec[0] = KERNELDOC; vec[1] = DOCBOOK; vec[2] = SHOWNOTFOUND; vec[3] = FUNCTION; vec[4] = line; vec[5] = filename; vec[6] = NULL; exec_kernel_doc(vec); } static void find_all_symbols(char *filename) { char *vec[4]; /* kerneldoc -list file NULL */ pid_t pid; int ret, i, count, start; char real_filename[PATH_MAX + 1]; int pipefd[2]; char *data, *str; size_t data_len = 0; vec[0] = KERNELDOC; vec[1] = LIST; vec[2] = filename; vec[3] = NULL; if (pipe(pipefd)) { perror("pipe"); exit(1); } switch (pid=fork()) { case -1: perror("fork"); exit(1); case 0: close(pipefd[0]); dup2(pipefd[1], 1); memset(real_filename, 0, sizeof(real_filename)); strncat(real_filename, kernsrctree, PATH_MAX); strncat(real_filename, "/" KERNELDOCPATH KERNELDOC, PATH_MAX - strlen(real_filename)); execvp(real_filename, vec); fprintf(stderr, "exec "); perror(real_filename); exit(1); default: close(pipefd[1]); data = malloc(4096); do { while ((ret = read(pipefd[0], data + data_len, 4096)) > 0) { data_len += ret; data = realloc(data, data_len + 4096); } } while (ret == -EAGAIN); if (ret != 0) { perror("read"); exit(1); } waitpid(pid, &ret ,0); } if (WIFEXITED(ret)) exitstatus |= WEXITSTATUS(ret); else exitstatus = 0xff; count = 0; /* poor man's strtok, but with counting */ for (i = 0; i < data_len; i++) { if (data[i] == '\n') { count++; data[i] = '\0'; } } start = all_list_len; all_list_len += count; all_list = realloc(all_list, sizeof(char *) * all_list_len); str = data; for (i = 0; i < data_len && start != all_list_len; i++) { if (data[i] == '\0') { all_list[start] = str; str = data + i + 1; start++; } } } /* * Parse file, calling action specific functions for: * 1) Lines containing !E * 2) Lines containing !I * 3) Lines containing !D * 4) Lines containing !F * 5) Lines containing !P * 6) Lines containing !C * 7) Default lines - lines not matching the above */ static void parse_file(FILE *infile) { char line[MAXLINESZ]; char * s; while (fgets(line, MAXLINESZ, infile)) { if (line[0] == '!') { s = line + 2; switch (line[1]) { case 'E': while (*s && !isspace(*s)) s++; *s = '\0'; externalfunctions(line+2); break; case 'I': while (*s && !isspace(*s)) s++; *s = '\0'; internalfunctions(line+2); break; case 'D': while (*s && !isspace(*s)) s++; *s = '\0'; symbolsonly(line+2); break; case 'F': /* filename */ while (*s && !isspace(*s)) s++; *s++ = '\0'; /* function names */ while (isspace(*s)) s++; singlefunctions(line +2, s); break; case 'P': /* filename */ while (*s && !isspace(*s)) s++; *s++ = '\0'; /* DOC: section name */ while (isspace(*s)) s++; docsection(line + 2, s); break; case 'C': while (*s && !isspace(*s)) s++; *s = '\0'; if (findall) findall(line+2); break; default: defaultline(line); } } else { defaultline(line); } } fflush(stdout); } int main(int argc, char *argv[]) { FILE * infile; int i; srctree = getenv("SRCTREE"); if (!srctree) srctree = getcwd(NULL, 0); kernsrctree = getenv("KBUILD_SRC"); if (!kernsrctree || !*kernsrctree) kernsrctree = srctree; if (argc != 3) { usage(); exit(1); } /* Open file, exit on error */ infile = fopen(argv[2], "r"); if (infile == NULL) { fprintf(stderr, "docproc: "); perror(argv[2]); exit(2); } if (strcmp("doc", argv[1]) == 0) { /* Need to do this in two passes. * First pass is used to collect all symbols exported * in the various files; * Second pass generate the documentation. * This is required because some functions are declared * and exported in different files :-(( */ /* Collect symbols */ defaultline = noaction; internalfunctions = find_export_symbols; externalfunctions = find_export_symbols; symbolsonly = find_export_symbols; singlefunctions = noaction2; docsection = noaction2; findall = find_all_symbols; parse_file(infile); /* Rewind to start from beginning of file again */ fseek(infile, 0, SEEK_SET); defaultline = printline; internalfunctions = intfunc; externalfunctions = extfunc; symbolsonly = printline; singlefunctions = singfunc; docsection = docsect; findall = NULL; parse_file(infile); for (i = 0; i < all_list_len; i++) { if (!all_list[i]) continue; fprintf(stderr, "Warning: didn't use docs for %s\n", all_list[i]); } } else if (strcmp("depend", argv[1]) == 0) { /* Create first part of dependency chain * file.tmpl */ printf("%s\t", argv[2]); defaultline = noaction; internalfunctions = adddep; externalfunctions = adddep; symbolsonly = adddep; singlefunctions = adddep2; docsection = adddep2; findall = adddep; parse_file(infile); printf("\n"); } else { fprintf(stderr, "Unknown option: %s\n", argv[1]); exit(1); } fclose(infile); fflush(stdout); return exitstatus; }
gpl-3.0
acquaman/acquaman
source/Eigen/test/sparse_solvers.cpp
292
4691
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "sparse.h" template<typename Scalar> void initSPD(double density, Matrix<Scalar,Dynamic,Dynamic>& refMat, SparseMatrix<Scalar>& sparseMat) { Matrix<Scalar,Dynamic,Dynamic> aux(refMat.rows(),refMat.cols()); initSparse(density,refMat,sparseMat); refMat = refMat * refMat.adjoint(); for (int k=0; k<2; ++k) { initSparse(density,aux,sparseMat,ForceNonZeroDiag); refMat += aux * aux.adjoint(); } sparseMat.setZero(); for (int j=0 ; j<sparseMat.cols(); ++j) for (int i=j ; i<sparseMat.rows(); ++i) if (refMat(i,j)!=Scalar(0)) sparseMat.insert(i,j) = refMat(i,j); sparseMat.finalize(); } template<typename Scalar> void sparse_solvers(int rows, int cols) { double density = (std::max)(8./(rows*cols), 0.01); typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix; typedef Matrix<Scalar,Dynamic,1> DenseVector; // Scalar eps = 1e-6; DenseVector vec1 = DenseVector::Random(rows); std::vector<Vector2i> zeroCoords; std::vector<Vector2i> nonzeroCoords; // test triangular solver { DenseVector vec2 = vec1, vec3 = vec1; SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2 = DenseMatrix::Zero(rows, cols); // lower - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template triangularView<Lower>().solve(vec2), m2.template triangularView<Lower>().solve(vec3)); // upper - dense initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template triangularView<Upper>().solve(vec2), m2.template triangularView<Upper>().solve(vec3)); VERIFY_IS_APPROX(refMat2.conjugate().template triangularView<Upper>().solve(vec2), m2.conjugate().template triangularView<Upper>().solve(vec3)); { SparseMatrix<Scalar> cm2(m2); //Index rows, Index cols, Index nnz, Index* outerIndexPtr, Index* innerIndexPtr, Scalar* valuePtr MappedSparseMatrix<Scalar> mm2(rows, cols, cm2.nonZeros(), cm2.outerIndexPtr(), cm2.innerIndexPtr(), cm2.valuePtr()); VERIFY_IS_APPROX(refMat2.conjugate().template triangularView<Upper>().solve(vec2), mm2.conjugate().template triangularView<Upper>().solve(vec3)); } // lower - transpose initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.transpose().template triangularView<Upper>().solve(vec2), m2.transpose().template triangularView<Upper>().solve(vec3)); // upper - transpose initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.transpose().template triangularView<Lower>().solve(vec2), m2.transpose().template triangularView<Lower>().solve(vec3)); SparseMatrix<Scalar> matB(rows, rows); DenseMatrix refMatB = DenseMatrix::Zero(rows, rows); // lower - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template triangularView<Lower>().solveInPlace(refMatB); m2.template triangularView<Lower>().solveInPlace(matB); VERIFY_IS_APPROX(matB.toDense(), refMatB); // upper - sparse initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeUpperTriangular); initSparse<Scalar>(density, refMatB, matB); refMat2.template triangularView<Upper>().solveInPlace(refMatB); m2.template triangularView<Upper>().solveInPlace(matB); VERIFY_IS_APPROX(matB, refMatB); // test deprecated API initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, &zeroCoords, &nonzeroCoords); VERIFY_IS_APPROX(refMat2.template triangularView<Lower>().solve(vec2), m2.template triangularView<Lower>().solve(vec3)); } } void test_sparse_solvers() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1(sparse_solvers<double>(8, 8) ); int s = internal::random<int>(1,300); CALL_SUBTEST_2(sparse_solvers<std::complex<double> >(s,s) ); CALL_SUBTEST_1(sparse_solvers<double>(s,s) ); } }
gpl-3.0
MinghuaWang/DECAF
DroidScope/qemu/tap-win32.c
37
20609
/* * TAP-Win32 -- A kernel driver to provide virtual tap device functionality * on Windows. Originally derived from the CIPE-Win32 * project by Damion K. Wilson, with extensive modifications by * James Yonan. * * All source code which derives from the CIPE-Win32 project is * Copyright (C) Damion K. Wilson, 2003, and is released under the * GPL version 2 (see below). * * All other source code is Copyright (C) James Yonan, 2003-2004, * and is released under the GPL version 2 (see below). * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program (see the file COPYING included with this * distribution); if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "qemu-common.h" #include "net.h" #include "sysemu.h" #include <stdio.h> #include <windows.h> #include <winioctl.h> //============= // TAP IOCTLs //============= #define TAP_CONTROL_CODE(request,method) \ CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS) #define TAP_IOCTL_GET_MAC TAP_CONTROL_CODE (1, METHOD_BUFFERED) #define TAP_IOCTL_GET_VERSION TAP_CONTROL_CODE (2, METHOD_BUFFERED) #define TAP_IOCTL_GET_MTU TAP_CONTROL_CODE (3, METHOD_BUFFERED) #define TAP_IOCTL_GET_INFO TAP_CONTROL_CODE (4, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_POINT_TO_POINT TAP_CONTROL_CODE (5, METHOD_BUFFERED) #define TAP_IOCTL_SET_MEDIA_STATUS TAP_CONTROL_CODE (6, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_DHCP_MASQ TAP_CONTROL_CODE (7, METHOD_BUFFERED) #define TAP_IOCTL_GET_LOG_LINE TAP_CONTROL_CODE (8, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_DHCP_SET_OPT TAP_CONTROL_CODE (9, METHOD_BUFFERED) //================= // Registry keys //================= #define ADAPTER_KEY "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}" #define NETWORK_CONNECTIONS_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}" //====================== // Filesystem prefixes //====================== #define USERMODEDEVICEDIR "\\\\.\\Global\\" #define TAPSUFFIX ".tap" //====================== // Compile time configuration //====================== //#define DEBUG_TAP_WIN32 #define TUN_ASYNCHRONOUS_WRITES 1 #define TUN_BUFFER_SIZE 1560 #define TUN_MAX_BUFFER_COUNT 32 /* * The data member "buffer" must be the first element in the tun_buffer * structure. See the function, tap_win32_free_buffer. */ typedef struct tun_buffer_s { unsigned char buffer [TUN_BUFFER_SIZE]; unsigned long read_size; struct tun_buffer_s* next; } tun_buffer_t; typedef struct tap_win32_overlapped { HANDLE handle; HANDLE read_event; HANDLE write_event; HANDLE output_queue_semaphore; HANDLE free_list_semaphore; HANDLE tap_semaphore; CRITICAL_SECTION output_queue_cs; CRITICAL_SECTION free_list_cs; OVERLAPPED read_overlapped; OVERLAPPED write_overlapped; tun_buffer_t buffers[TUN_MAX_BUFFER_COUNT]; tun_buffer_t* free_list; tun_buffer_t* output_queue_front; tun_buffer_t* output_queue_back; } tap_win32_overlapped_t; static tap_win32_overlapped_t tap_overlapped; static tun_buffer_t* get_buffer_from_free_list(tap_win32_overlapped_t* const overlapped) { tun_buffer_t* buffer = NULL; WaitForSingleObject(overlapped->free_list_semaphore, INFINITE); EnterCriticalSection(&overlapped->free_list_cs); buffer = overlapped->free_list; // assert(buffer != NULL); overlapped->free_list = buffer->next; LeaveCriticalSection(&overlapped->free_list_cs); buffer->next = NULL; return buffer; } static void put_buffer_on_free_list(tap_win32_overlapped_t* const overlapped, tun_buffer_t* const buffer) { EnterCriticalSection(&overlapped->free_list_cs); buffer->next = overlapped->free_list; overlapped->free_list = buffer; LeaveCriticalSection(&overlapped->free_list_cs); ReleaseSemaphore(overlapped->free_list_semaphore, 1, NULL); } static tun_buffer_t* get_buffer_from_output_queue(tap_win32_overlapped_t* const overlapped, const int block) { tun_buffer_t* buffer = NULL; DWORD result, timeout = block ? INFINITE : 0L; // Non-blocking call result = WaitForSingleObject(overlapped->output_queue_semaphore, timeout); switch (result) { // The semaphore object was signaled. case WAIT_OBJECT_0: EnterCriticalSection(&overlapped->output_queue_cs); buffer = overlapped->output_queue_front; overlapped->output_queue_front = buffer->next; if(overlapped->output_queue_front == NULL) { overlapped->output_queue_back = NULL; } LeaveCriticalSection(&overlapped->output_queue_cs); break; // Semaphore was nonsignaled, so a time-out occurred. case WAIT_TIMEOUT: // Cannot open another window. break; } return buffer; } static tun_buffer_t* get_buffer_from_output_queue_immediate (tap_win32_overlapped_t* const overlapped) { return get_buffer_from_output_queue(overlapped, 0); } static void put_buffer_on_output_queue(tap_win32_overlapped_t* const overlapped, tun_buffer_t* const buffer) { EnterCriticalSection(&overlapped->output_queue_cs); if(overlapped->output_queue_front == NULL && overlapped->output_queue_back == NULL) { overlapped->output_queue_front = overlapped->output_queue_back = buffer; } else { buffer->next = NULL; overlapped->output_queue_back->next = buffer; overlapped->output_queue_back = buffer; } LeaveCriticalSection(&overlapped->output_queue_cs); ReleaseSemaphore(overlapped->output_queue_semaphore, 1, NULL); } static int is_tap_win32_dev(const char *guid) { HKEY netcard_key; LONG status; DWORD len; int i = 0; status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, ADAPTER_KEY, 0, KEY_READ, &netcard_key); if (status != ERROR_SUCCESS) { return FALSE; } for (;;) { char enum_name[256]; char unit_string[256]; HKEY unit_key; char component_id_string[] = "ComponentId"; char component_id[256]; char net_cfg_instance_id_string[] = "NetCfgInstanceId"; char net_cfg_instance_id[256]; DWORD data_type; len = sizeof (enum_name); status = RegEnumKeyEx( netcard_key, i, enum_name, &len, NULL, NULL, NULL, NULL); if (status == ERROR_NO_MORE_ITEMS) break; else if (status != ERROR_SUCCESS) { return FALSE; } snprintf (unit_string, sizeof(unit_string), "%s\\%s", ADAPTER_KEY, enum_name); status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, unit_string, 0, KEY_READ, &unit_key); if (status != ERROR_SUCCESS) { return FALSE; } else { len = sizeof (component_id); status = RegQueryValueEx( unit_key, component_id_string, NULL, &data_type, (LPBYTE)component_id, &len); if (!(status != ERROR_SUCCESS || data_type != REG_SZ)) { len = sizeof (net_cfg_instance_id); status = RegQueryValueEx( unit_key, net_cfg_instance_id_string, NULL, &data_type, (LPBYTE)net_cfg_instance_id, &len); if (status == ERROR_SUCCESS && data_type == REG_SZ) { if (/* !strcmp (component_id, TAP_COMPONENT_ID) &&*/ !strcmp (net_cfg_instance_id, guid)) { RegCloseKey (unit_key); RegCloseKey (netcard_key); return TRUE; } } } RegCloseKey (unit_key); } ++i; } RegCloseKey (netcard_key); return FALSE; } static int get_device_guid( char *name, int name_size, char *actual_name, int actual_name_size) { LONG status; HKEY control_net_key; DWORD len; int i = 0; int stop = 0; status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_READ, &control_net_key); if (status != ERROR_SUCCESS) { return -1; } while (!stop) { char enum_name[256]; char connection_string[256]; HKEY connection_key; char name_data[256]; DWORD name_type; const char name_string[] = "Name"; len = sizeof (enum_name); status = RegEnumKeyEx( control_net_key, i, enum_name, &len, NULL, NULL, NULL, NULL); if (status == ERROR_NO_MORE_ITEMS) break; else if (status != ERROR_SUCCESS) { return -1; } snprintf(connection_string, sizeof(connection_string), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, enum_name); status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, connection_string, 0, KEY_READ, &connection_key); if (status == ERROR_SUCCESS) { len = sizeof (name_data); status = RegQueryValueEx( connection_key, name_string, NULL, &name_type, (LPBYTE)name_data, &len); if (status != ERROR_SUCCESS || name_type != REG_SZ) { return -1; } else { if (is_tap_win32_dev(enum_name)) { snprintf(name, name_size, "%s", enum_name); if (actual_name) { if (strcmp(actual_name, "") != 0) { if (strcmp(name_data, actual_name) != 0) { RegCloseKey (connection_key); ++i; continue; } } else { snprintf(actual_name, actual_name_size, "%s", name_data); } } stop = 1; } } RegCloseKey (connection_key); } ++i; } RegCloseKey (control_net_key); if (stop == 0) return -1; return 0; } static int tap_win32_set_status(HANDLE handle, int status) { unsigned long len = 0; return DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof (status), &status, sizeof (status), &len, NULL); } static void tap_win32_overlapped_init(tap_win32_overlapped_t* const overlapped, const HANDLE handle) { overlapped->handle = handle; overlapped->read_event = CreateEvent(NULL, FALSE, FALSE, NULL); overlapped->write_event = CreateEvent(NULL, FALSE, FALSE, NULL); overlapped->read_overlapped.Offset = 0; overlapped->read_overlapped.OffsetHigh = 0; overlapped->read_overlapped.hEvent = overlapped->read_event; overlapped->write_overlapped.Offset = 0; overlapped->write_overlapped.OffsetHigh = 0; overlapped->write_overlapped.hEvent = overlapped->write_event; InitializeCriticalSection(&overlapped->output_queue_cs); InitializeCriticalSection(&overlapped->free_list_cs); overlapped->output_queue_semaphore = CreateSemaphore( NULL, // default security attributes 0, // initial count TUN_MAX_BUFFER_COUNT, // maximum count NULL); // unnamed semaphore if(!overlapped->output_queue_semaphore) { fprintf(stderr, "error creating output queue semaphore!\n"); } overlapped->free_list_semaphore = CreateSemaphore( NULL, // default security attributes TUN_MAX_BUFFER_COUNT, // initial count TUN_MAX_BUFFER_COUNT, // maximum count NULL); // unnamed semaphore if(!overlapped->free_list_semaphore) { fprintf(stderr, "error creating free list semaphore!\n"); } overlapped->free_list = overlapped->output_queue_front = overlapped->output_queue_back = NULL; { unsigned index; for(index = 0; index < TUN_MAX_BUFFER_COUNT; index++) { tun_buffer_t* element = &overlapped->buffers[index]; element->next = overlapped->free_list; overlapped->free_list = element; } } /* To count buffers, initially no-signal. */ overlapped->tap_semaphore = CreateSemaphore(NULL, 0, TUN_MAX_BUFFER_COUNT, NULL); if(!overlapped->tap_semaphore) fprintf(stderr, "error creating tap_semaphore.\n"); } static int tap_win32_write(tap_win32_overlapped_t *overlapped, const void *buffer, unsigned long size) { unsigned long write_size; BOOL result; DWORD error; result = GetOverlappedResult( overlapped->handle, &overlapped->write_overlapped, &write_size, FALSE); if (!result && GetLastError() == ERROR_IO_INCOMPLETE) WaitForSingleObject(overlapped->write_event, INFINITE); result = WriteFile(overlapped->handle, buffer, size, &write_size, &overlapped->write_overlapped); if (!result) { switch (error = GetLastError()) { case ERROR_IO_PENDING: #ifndef TUN_ASYNCHRONOUS_WRITES WaitForSingleObject(overlapped->write_event, INFINITE); #endif break; default: return -1; } } return 0; } static DWORD WINAPI tap_win32_thread_entry(LPVOID param) { tap_win32_overlapped_t *overlapped = (tap_win32_overlapped_t*)param; unsigned long read_size; BOOL result; DWORD dwError; tun_buffer_t* buffer = get_buffer_from_free_list(overlapped); for (;;) { result = ReadFile(overlapped->handle, buffer->buffer, sizeof(buffer->buffer), &read_size, &overlapped->read_overlapped); if (!result) { dwError = GetLastError(); if (dwError == ERROR_IO_PENDING) { WaitForSingleObject(overlapped->read_event, INFINITE); result = GetOverlappedResult( overlapped->handle, &overlapped->read_overlapped, &read_size, FALSE); if (!result) { #ifdef DEBUG_TAP_WIN32 LPVOID lpBuffer; dwError = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpBuffer, 0, NULL ); fprintf(stderr, "Tap-Win32: Error GetOverlappedResult %d - %s\n", dwError, lpBuffer); LocalFree( lpBuffer ); #endif } } else { #ifdef DEBUG_TAP_WIN32 LPVOID lpBuffer; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpBuffer, 0, NULL ); fprintf(stderr, "Tap-Win32: Error ReadFile %d - %s\n", dwError, lpBuffer); LocalFree( lpBuffer ); #endif } } if(read_size > 0) { buffer->read_size = read_size; put_buffer_on_output_queue(overlapped, buffer); ReleaseSemaphore(overlapped->tap_semaphore, 1, NULL); buffer = get_buffer_from_free_list(overlapped); } } return 0; } static int tap_win32_read(tap_win32_overlapped_t *overlapped, uint8_t **pbuf, int max_size) { int size = 0; tun_buffer_t* buffer = get_buffer_from_output_queue_immediate(overlapped); if(buffer != NULL) { *pbuf = buffer->buffer; size = (int)buffer->read_size; if(size > max_size) { size = max_size; } } return size; } static void tap_win32_free_buffer(tap_win32_overlapped_t *overlapped, uint8_t *pbuf) { tun_buffer_t* buffer = (tun_buffer_t*)pbuf; put_buffer_on_free_list(overlapped, buffer); } static int tap_win32_open(tap_win32_overlapped_t **phandle, const char *prefered_name) { char device_path[256]; char device_guid[0x100]; int rc; HANDLE handle; BOOL bret; char name_buffer[0x100] = {0, }; struct { unsigned long major; unsigned long minor; unsigned long debug; } version; DWORD version_len; DWORD idThread; HANDLE hThread; if (prefered_name != NULL) snprintf(name_buffer, sizeof(name_buffer), "%s", prefered_name); rc = get_device_guid(device_guid, sizeof(device_guid), name_buffer, sizeof(name_buffer)); if (rc) return -1; snprintf (device_path, sizeof(device_path), "%s%s%s", USERMODEDEVICEDIR, device_guid, TAPSUFFIX); handle = CreateFile ( device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0 ); if (handle == INVALID_HANDLE_VALUE) { return -1; } bret = DeviceIoControl(handle, TAP_IOCTL_GET_VERSION, &version, sizeof (version), &version, sizeof (version), &version_len, NULL); if (bret == FALSE) { CloseHandle(handle); return -1; } if (!tap_win32_set_status(handle, TRUE)) { return -1; } tap_win32_overlapped_init(&tap_overlapped, handle); *phandle = &tap_overlapped; hThread = CreateThread(NULL, 0, tap_win32_thread_entry, (LPVOID)&tap_overlapped, 0, &idThread); return 0; } /********************************************/ typedef struct TAPState { VLANClientState *vc; tap_win32_overlapped_t *handle; } TAPState; static void tap_cleanup(VLANClientState *vc) { TAPState *s = vc->opaque; qemu_del_wait_object(s->handle->tap_semaphore, NULL, NULL); /* FIXME: need to kill thread and close file handle: tap_win32_close(s); */ qemu_free(s); } static ssize_t tap_receive(VLANClientState *vc, const uint8_t *buf, size_t size) { TAPState *s = vc->opaque; return tap_win32_write(s->handle, buf, size); } static void tap_win32_send(void *opaque) { TAPState *s = opaque; uint8_t *buf; int max_size = 4096; int size; size = tap_win32_read(s->handle, &buf, max_size); if (size > 0) { qemu_send_packet(s->vc, buf, size); tap_win32_free_buffer(s->handle, buf); } } int tap_win32_init(VLANState *vlan, const char *model, const char *name, const char *ifname) { TAPState *s; s = qemu_mallocz(sizeof(TAPState)); if (!s) return -1; if (tap_win32_open(&s->handle, ifname) < 0) { printf("tap: Could not open '%s'\n", ifname); return -1; } s->vc = qemu_new_vlan_client(vlan, model, name, NULL, tap_receive, NULL, tap_cleanup, s); snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: ifname=%s", ifname); qemu_add_wait_object(s->handle->tap_semaphore, tap_win32_send, s); return 0; }
gpl-3.0
kelroy1990/ReflowOven
LibNoUsadas/Ucglib_Arduino-1.4.0/src/clib/ucg_box.c
37
5266
/* ucg_box.c Universal uC Color Graphics Library Copyright (c) 2013, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ucg.h" void ucg_DrawBox(ucg_t *ucg, ucg_int_t x, ucg_int_t y, ucg_int_t w, ucg_int_t h) { while( h > 0 ) { ucg_DrawHLine(ucg, x, y, w); h--; y++; } } /* - clear the screen with black color - reset clip range to max - set draw color to white */ void ucg_ClearScreen(ucg_t *ucg) { ucg_SetColor(ucg, 0, 0, 0, 0); ucg_SetMaxClipRange(ucg); ucg_DrawBox(ucg, 0, 0, ucg_GetWidth(ucg), ucg_GetHeight(ucg)); ucg_SetColor(ucg, 0, 255, 255, 255); } void ucg_DrawRBox(ucg_t *ucg, ucg_int_t x, ucg_int_t y, ucg_int_t w, ucg_int_t h, ucg_int_t r) { ucg_int_t xl, yu; ucg_int_t yl, xr; xl = x; xl += r; yu = y; yu += r; xr = x; xr += w; xr -= r; xr -= 1; yl = y; yl += h; yl -= r; yl -= 1; ucg_DrawDisc(ucg, xl, yu, r, UCG_DRAW_UPPER_LEFT); ucg_DrawDisc(ucg, xr, yu, r, UCG_DRAW_UPPER_RIGHT); ucg_DrawDisc(ucg, xl, yl, r, UCG_DRAW_LOWER_LEFT); ucg_DrawDisc(ucg, xr, yl, r, UCG_DRAW_LOWER_RIGHT); { ucg_int_t ww, hh; ww = w; ww -= r; ww -= r; ww -= 2; hh = h; hh -= r; hh -= r; hh -= 2; xl++; yu++; h--; ucg_DrawBox(ucg, xl, y, ww, r+1); ucg_DrawBox(ucg, xl, yl, ww, r+1); ucg_DrawBox(ucg, x, yu, w, hh); } } ucg_ccs_t ucg_ccs_box[6]; /* color component sliders used by GradientBox */ void ucg_DrawGradientBox(ucg_t *ucg, ucg_int_t x, ucg_int_t y, ucg_int_t w, ucg_int_t h) { uint8_t i; /* Setup ccs for l90se. This will be updated by ucg_clip_l90se if required */ /* 8. Jan 2014: correct? */ //printf("%d %d %d\n", ucg->arg.rgb[3].color[0], ucg->arg.rgb[3].color[1], ucg->arg.rgb[3].color[2]); for ( i = 0; i < 3; i++ ) { ucg_ccs_init(ucg_ccs_box+i, ucg->arg.rgb[0].color[i], ucg->arg.rgb[2].color[i], h); ucg_ccs_init(ucg_ccs_box+i+3, ucg->arg.rgb[1].color[i], ucg->arg.rgb[3].color[i], h); } while( h > 0 ) { ucg->arg.rgb[0].color[0] = ucg_ccs_box[0].current; ucg->arg.rgb[0].color[1] = ucg_ccs_box[1].current; ucg->arg.rgb[0].color[2] = ucg_ccs_box[2].current; ucg->arg.rgb[1].color[0] = ucg_ccs_box[3].current; ucg->arg.rgb[1].color[1] = ucg_ccs_box[4].current; ucg->arg.rgb[1].color[2] = ucg_ccs_box[5].current; //printf("%d %d %d\n", ucg_ccs_box[0].current, ucg_ccs_box[1].current, ucg_ccs_box[2].current); //printf("%d %d %d\n", ucg_ccs_box[3].current, ucg_ccs_box[4].current, ucg_ccs_box[5].current); ucg->arg.pixel.pos.x = x; ucg->arg.pixel.pos.y = y; ucg->arg.len = w; ucg->arg.dir = 0; ucg_DrawL90SEWithArg(ucg); for ( i = 0; i < 6; i++ ) ucg_ccs_step(ucg_ccs_box+i); h--; y++; } } /* restrictions: w > 0 && h > 0 */ void ucg_DrawFrame(ucg_t *ucg, ucg_int_t x, ucg_int_t y, ucg_int_t w, ucg_int_t h) { ucg_int_t xtmp = x; ucg_DrawHLine(ucg, x, y, w); ucg_DrawVLine(ucg, x, y, h); x+=w; x--; ucg_DrawVLine(ucg, x, y, h); y+=h; y--; ucg_DrawHLine(ucg, xtmp, y, w); } void ucg_DrawRFrame(ucg_t *ucg, ucg_int_t x, ucg_int_t y, ucg_int_t w, ucg_int_t h, ucg_int_t r) { ucg_int_t xl, yu; xl = x; xl += r; yu = y; yu += r; { ucg_int_t yl, xr; xr = x; xr += w; xr -= r; xr -= 1; yl = y; yl += h; yl -= r; yl -= 1; ucg_DrawCircle(ucg, xl, yu, r, UCG_DRAW_UPPER_LEFT); ucg_DrawCircle(ucg, xr, yu, r, UCG_DRAW_UPPER_RIGHT); ucg_DrawCircle(ucg, xl, yl, r, UCG_DRAW_LOWER_LEFT); ucg_DrawCircle(ucg, xr, yl, r, UCG_DRAW_LOWER_RIGHT); } { ucg_int_t ww, hh; ww = w; ww -= r; ww -= r; ww -= 2; hh = h; hh -= r; hh -= r; hh -= 2; xl++; yu++; h--; w--; ucg_DrawHLine(ucg, xl, y, ww); ucg_DrawHLine(ucg, xl, y+h, ww); ucg_DrawVLine(ucg, x, yu, hh); ucg_DrawVLine(ucg, x+w, yu, hh); } }
gpl-3.0
akamai/bash
lib/glob/gmisc.c
38
8121
/* gmisc.c -- miscellaneous pattern matching utility functions for Bash. Copyright (C) 2010 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne-Again SHell. Bash is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include "bashtypes.h" #if defined (HAVE_UNISTD_H) # include <unistd.h> #endif #include "bashansi.h" #include "shmbutil.h" #include "stdc.h" #ifndef LPAREN # define LPAREN '(' #endif #ifndef RPAREN # define RPAREN ')' #endif #if defined (HANDLE_MULTIBYTE) #define WLPAREN L'(' #define WRPAREN L')' extern char *glob_patscan __P((char *, char *, int)); /* Return 1 of the first character of WSTRING could match the first character of pattern WPAT. Wide character version. */ int match_pattern_wchar (wpat, wstring) wchar_t *wpat, *wstring; { wchar_t wc; if (*wstring == 0) return (0); switch (wc = *wpat++) { default: return (*wstring == wc); case L'\\': return (*wstring == *wpat); case L'?': return (*wpat == WLPAREN ? 1 : (*wstring != L'\0')); case L'*': return (1); case L'+': case L'!': case L'@': return (*wpat == WLPAREN ? 1 : (*wstring == wc)); case L'[': return (*wstring != L'\0'); } } int wmatchlen (wpat, wmax) wchar_t *wpat; size_t wmax; { wchar_t wc; int matlen, bracklen, t, in_cclass, in_collsym, in_equiv; if (*wpat == 0) return (0); matlen = in_cclass = in_collsym = in_equiv = 0; while (wc = *wpat++) { switch (wc) { default: matlen++; break; case L'\\': if (*wpat == 0) return ++matlen; else { matlen++; wpat++; } break; case L'?': if (*wpat == WLPAREN) return (matlen = -1); /* XXX for now */ else matlen++; break; case L'*': return (matlen = -1); case L'+': case L'!': case L'@': if (*wpat == WLPAREN) return (matlen = -1); /* XXX for now */ else matlen++; break; case L'[': /* scan for ending `]', skipping over embedded [:...:] */ bracklen = 1; wc = *wpat++; do { if (wc == 0) { wpat--; /* back up to NUL */ matlen += bracklen; goto bad_bracket; } else if (wc == L'\\') { /* *wpat == backslash-escaped character */ bracklen++; /* If the backslash or backslash-escape ends the string, bail. The ++wpat skips over the backslash escape */ if (*wpat == 0 || *++wpat == 0) { matlen += bracklen; goto bad_bracket; } } else if (wc == L'[' && *wpat == L':') /* character class */ { wpat++; bracklen++; in_cclass = 1; } else if (in_cclass && wc == L':' && *wpat == L']') { wpat++; bracklen++; in_cclass = 0; } else if (wc == L'[' && *wpat == L'.') /* collating symbol */ { wpat++; bracklen++; if (*wpat == L']') /* right bracket can appear as collating symbol */ { wpat++; bracklen++; } in_collsym = 1; } else if (in_collsym && wc == L'.' && *wpat == L']') { wpat++; bracklen++; in_collsym = 0; } else if (wc == L'[' && *wpat == L'=') /* equivalence class */ { wpat++; bracklen++; if (*wpat == L']') /* right bracket can appear as equivalence class */ { wpat++; bracklen++; } in_equiv = 1; } else if (in_equiv && wc == L'=' && *wpat == L']') { wpat++; bracklen++; in_equiv = 0; } else bracklen++; } while ((wc = *wpat++) != L']'); matlen++; /* bracket expression can only match one char */ bad_bracket: break; } } return matlen; } #endif int extglob_pattern_p (pat) char *pat; { switch (pat[0]) { case '*': case '+': case '!': case '@': case '?': return (pat[1] == LPAREN); default: return 0; } return 0; } /* Return 1 of the first character of STRING could match the first character of pattern PAT. Used to avoid n2 calls to strmatch(). */ int match_pattern_char (pat, string) char *pat, *string; { char c; if (*string == 0) return (0); switch (c = *pat++) { default: return (*string == c); case '\\': return (*string == *pat); case '?': return (*pat == LPAREN ? 1 : (*string != '\0')); case '*': return (1); case '+': case '!': case '@': return (*pat == LPAREN ? 1 : (*string == c)); case '[': return (*string != '\0'); } } int umatchlen (pat, max) char *pat; size_t max; { char c; int matlen, bracklen, t, in_cclass, in_collsym, in_equiv; if (*pat == 0) return (0); matlen = in_cclass = in_collsym = in_equiv = 0; while (c = *pat++) { switch (c) { default: matlen++; break; case '\\': if (*pat == 0) return ++matlen; else { matlen++; pat++; } break; case '?': if (*pat == LPAREN) return (matlen = -1); /* XXX for now */ else matlen++; break; case '*': return (matlen = -1); case '+': case '!': case '@': if (*pat == LPAREN) return (matlen = -1); /* XXX for now */ else matlen++; break; case '[': /* scan for ending `]', skipping over embedded [:...:] */ bracklen = 1; c = *pat++; do { if (c == 0) { pat--; /* back up to NUL */ matlen += bracklen; goto bad_bracket; } else if (c == '\\') { /* *pat == backslash-escaped character */ bracklen++; /* If the backslash or backslash-escape ends the string, bail. The ++pat skips over the backslash escape */ if (*pat == 0 || *++pat == 0) { matlen += bracklen; goto bad_bracket; } } else if (c == '[' && *pat == ':') /* character class */ { pat++; bracklen++; in_cclass = 1; } else if (in_cclass && c == ':' && *pat == ']') { pat++; bracklen++; in_cclass = 0; } else if (c == '[' && *pat == '.') /* collating symbol */ { pat++; bracklen++; if (*pat == ']') /* right bracket can appear as collating symbol */ { pat++; bracklen++; } in_collsym = 1; } else if (in_collsym && c == '.' && *pat == ']') { pat++; bracklen++; in_collsym = 0; } else if (c == '[' && *pat == '=') /* equivalence class */ { pat++; bracklen++; if (*pat == ']') /* right bracket can appear as equivalence class */ { pat++; bracklen++; } in_equiv = 1; } else if (in_equiv && c == '=' && *pat == ']') { pat++; bracklen++; in_equiv = 0; } else bracklen++; } while ((c = *pat++) != ']'); matlen++; /* bracket expression can only match one char */ bad_bracket: break; } } return matlen; } /* Skip characters in PAT and return the final occurrence of DIRSEP. This is only called when extended_glob is set, so we have to skip over extglob patterns x(...) */ char * glob_dirscan (pat, dirsep) char *pat; int dirsep; { char *p, *d, *pe, *se; d = pe = se = 0; for (p = pat; p && *p; p++) { if (extglob_pattern_p (p)) { if (se == 0) se = p + strlen (p) - 1; pe = glob_patscan (p + 2, se, 0); if (pe == 0) continue; else if (*pe == 0) break; p = pe - 1; /* will do increment above */ continue; } if (*p == dirsep) d = p; } return d; }
gpl-3.0
NDV123/emgucv
Emgu.CV.Extern/tesseract/libtesseract/leptonica/leptonica-1.72/src/pageseg.c
48
29621
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *====================================================================*/ /* * pageseg.c * * Top level page segmentation * l_int32 pixGetRegionsBinary() * * Halftone region extraction * PIX *pixGenHalftoneMask() * * Textline extraction * PIX *pixGenTextlineMask() * * Textblock extraction * PIX *pixGenTextblockMask() * * Location of page foreground * PIX *pixFindPageForeground() * * Extraction of characters from image with only text * l_int32 pixSplitIntoCharacters() * BOXA *pixSplitComponentWithProfile() */ #include "allheaders.h" /*------------------------------------------------------------------* * Top level page segmentation * *------------------------------------------------------------------*/ /*! * pixGetRegionsBinary() * * Input: pixs (1 bpp, assumed to be 300 to 400 ppi) * &pixhm (<optional return> halftone mask) * &pixtm (<optional return> textline mask) * &pixtb (<optional return> textblock mask) * debug (flag: set to 1 for debug output) * Return: 0 if OK, 1 on error * * Notes: * (1) It is best to deskew the image before segmenting. * (2) The debug flag enables a number of outputs. These * are included to show how to generate and save/display * these results. */ l_int32 pixGetRegionsBinary(PIX *pixs, PIX **ppixhm, PIX **ppixtm, PIX **ppixtb, l_int32 debug) { l_int32 htfound, tlfound; PIX *pixr, *pixt1, *pixt2; PIX *pixtext; /* text pixels only */ PIX *pixhm2; /* halftone mask; 2x reduction */ PIX *pixhm; /* halftone mask; */ PIX *pixtm2; /* textline mask; 2x reduction */ PIX *pixtm; /* textline mask */ PIX *pixvws; /* vertical white space mask */ PIX *pixtb2; /* textblock mask; 2x reduction */ PIX *pixtbf2; /* textblock mask; 2x reduction; small comps filtered */ PIX *pixtb; /* textblock mask */ PROCNAME("pixGetRegionsBinary"); if (ppixhm) *ppixhm = NULL; if (ppixtm) *ppixtm = NULL; if (ppixtb) *ppixtb = NULL; if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (pixGetDepth(pixs) != 1) return ERROR_INT("pixs not 1 bpp", procName, 1); /* 2x reduce, to 150 -200 ppi */ pixr = pixReduceRankBinaryCascade(pixs, 1, 0, 0, 0); pixDisplayWrite(pixr, debug); /* Get the halftone mask */ pixhm2 = pixGenHalftoneMask(pixr, &pixtext, &htfound, debug); /* Get the textline mask from the text pixels */ pixtm2 = pixGenTextlineMask(pixtext, &pixvws, &tlfound, debug); /* Get the textblock mask from the textline mask */ pixtb2 = pixGenTextblockMask(pixtm2, pixvws, debug); pixDestroy(&pixr); pixDestroy(&pixtext); pixDestroy(&pixvws); /* Remove small components from the mask, where a small * component is defined as one with both width and height < 60 */ pixtbf2 = pixSelectBySize(pixtb2, 60, 60, 4, L_SELECT_IF_EITHER, L_SELECT_IF_GTE, NULL); pixDestroy(&pixtb2); pixDisplayWriteFormat(pixtbf2, debug, IFF_PNG); /* Expand all masks to full resolution, and do filling or * small dilations for better coverage. */ pixhm = pixExpandReplicate(pixhm2, 2); pixt1 = pixSeedfillBinary(NULL, pixhm, pixs, 8); pixOr(pixhm, pixhm, pixt1); pixDestroy(&pixt1); pixDisplayWriteFormat(pixhm, debug, IFF_PNG); pixt1 = pixExpandReplicate(pixtm2, 2); pixtm = pixDilateBrick(NULL, pixt1, 3, 3); pixDestroy(&pixt1); pixDisplayWriteFormat(pixtm, debug, IFF_PNG); pixt1 = pixExpandReplicate(pixtbf2, 2); pixtb = pixDilateBrick(NULL, pixt1, 3, 3); pixDestroy(&pixt1); pixDisplayWriteFormat(pixtb, debug, IFF_PNG); pixDestroy(&pixhm2); pixDestroy(&pixtm2); pixDestroy(&pixtbf2); /* Debug: identify objects that are neither text nor halftone image */ if (debug) { pixt1 = pixSubtract(NULL, pixs, pixtm); /* remove text pixels */ pixt2 = pixSubtract(NULL, pixt1, pixhm); /* remove halftone pixels */ pixDisplayWriteFormat(pixt2, 1, IFF_PNG); pixDestroy(&pixt1); pixDestroy(&pixt2); } /* Debug: display textline components with random colors */ if (debug) { l_int32 w, h; BOXA *boxa; PIXA *pixa; boxa = pixConnComp(pixtm, &pixa, 8); pixGetDimensions(pixtm, &w, &h, NULL); pixt1 = pixaDisplayRandomCmap(pixa, w, h); pixcmapResetColor(pixGetColormap(pixt1), 0, 255, 255, 255); pixDisplay(pixt1, 100, 100); pixDisplayWriteFormat(pixt1, 1, IFF_PNG); pixaDestroy(&pixa); boxaDestroy(&boxa); pixDestroy(&pixt1); } /* Debug: identify the outlines of each textblock */ if (debug) { PIXCMAP *cmap; PTAA *ptaa; ptaa = pixGetOuterBordersPtaa(pixtb); lept_mkdir("pageseg"); ptaaWrite("/tmp/pageseg/tb_outlines.ptaa", ptaa, 1); pixt1 = pixRenderRandomCmapPtaa(pixtb, ptaa, 1, 16, 1); cmap = pixGetColormap(pixt1); pixcmapResetColor(cmap, 0, 130, 130, 130); pixDisplay(pixt1, 500, 100); pixDisplayWriteFormat(pixt1, 1, IFF_PNG); pixDestroy(&pixt1); ptaaDestroy(&ptaa); } /* Debug: get b.b. for all mask components */ if (debug) { BOXA *bahm, *batm, *batb; bahm = pixConnComp(pixhm, NULL, 4); batm = pixConnComp(pixtm, NULL, 4); batb = pixConnComp(pixtb, NULL, 4); boxaWrite("/tmp/pageseg/htmask.boxa", bahm); boxaWrite("/tmp/pageseg/textmask.boxa", batm); boxaWrite("/tmp/pageseg/textblock.boxa", batb); boxaDestroy(&bahm); boxaDestroy(&batm); boxaDestroy(&batb); } if (ppixhm) *ppixhm = pixhm; else pixDestroy(&pixhm); if (ppixtm) *ppixtm = pixtm; else pixDestroy(&pixtm); if (ppixtb) *ppixtb = pixtb; else pixDestroy(&pixtb); return 0; } /*------------------------------------------------------------------* * Halftone region extraction * *------------------------------------------------------------------*/ /*! * pixGenHalftoneMask() * * Input: pixs (1 bpp, assumed to be 150 to 200 ppi) * &pixtext (<optional return> text part of pixs) * &htfound (<optional return> 1 if the mask is not empty) * debug (flag: 1 for debug output) * Return: pixd (halftone mask), or null on error */ PIX * pixGenHalftoneMask(PIX *pixs, PIX **ppixtext, l_int32 *phtfound, l_int32 debug) { l_int32 empty; PIX *pixt1, *pixt2, *pixhs, *pixhm, *pixd; PROCNAME("pixGenHalftoneMask"); if (ppixtext) *ppixtext = NULL; if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (pixGetDepth(pixs) != 1) return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, NULL); /* Compute seed for halftone parts at 8x reduction */ pixt1 = pixReduceRankBinaryCascade(pixs, 4, 4, 3, 0); pixt2 = pixOpenBrick(NULL, pixt1, 5, 5); pixhs = pixExpandReplicate(pixt2, 8); /* back to 2x reduction */ pixDestroy(&pixt1); pixDestroy(&pixt2); pixDisplayWriteFormat(pixhs, debug, IFF_PNG); /* Compute mask for connected regions */ pixhm = pixCloseSafeBrick(NULL, pixs, 4, 4); pixDisplayWriteFormat(pixhm, debug, IFF_PNG); /* Fill seed into mask to get halftone mask */ pixd = pixSeedfillBinary(NULL, pixhs, pixhm, 4); #if 0 /* Moderate opening to remove thin lines, etc. */ pixOpenBrick(pixd, pixd, 10, 10); pixDisplayWrite(pixd, debug); #endif /* Check if mask is empty */ pixZero(pixd, &empty); if (phtfound) { *phtfound = 0; if (!empty) *phtfound = 1; } /* Optionally, get all pixels that are not under the halftone mask */ if (ppixtext) { if (empty) *ppixtext = pixCopy(NULL, pixs); else *ppixtext = pixSubtract(NULL, pixs, pixd); pixDisplayWriteFormat(*ppixtext, debug, IFF_PNG); } pixDestroy(&pixhs); pixDestroy(&pixhm); return pixd; } /*------------------------------------------------------------------* * Textline extraction * *------------------------------------------------------------------*/ /*! * pixGenTextlineMask() * * Input: pixs (1 bpp, assumed to be 150 to 200 ppi) * &pixvws (<return> vertical whitespace mask) * &tlfound (<optional return> 1 if the mask is not empty) * debug (flag: 1 for debug output) * Return: pixd (textline mask), or null on error * * Notes: * (1) The input pixs should be deskewed. * (2) pixs should have no halftone pixels. * (3) Both the input image and the returned textline mask * are at the same resolution. */ PIX * pixGenTextlineMask(PIX *pixs, PIX **ppixvws, l_int32 *ptlfound, l_int32 debug) { l_int32 empty; PIX *pixt1, *pixt2, *pixvws, *pixd; PROCNAME("pixGenTextlineMask"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (!ppixvws) return (PIX *)ERROR_PTR("&pixvws not defined", procName, NULL); if (pixGetDepth(pixs) != 1) return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, NULL); /* First we need a vertical whitespace mask. Invert the image. */ pixt1 = pixInvert(NULL, pixs); /* The whitespace mask will break textlines where there * is a large amount of white space below or above. * This can be prevented by identifying regions of the * inverted image that have large horizontal extent (bigger than * the separation between columns) and significant * vertical extent (bigger than the separation between * textlines), and subtracting this from the bg. */ pixt2 = pixMorphCompSequence(pixt1, "o80.60", 0); pixSubtract(pixt1, pixt1, pixt2); pixDisplayWriteFormat(pixt1, debug, IFF_PNG); pixDestroy(&pixt2); /* Identify vertical whitespace by opening the remaining bg. * o5.1 removes thin vertical bg lines and o1.200 extracts * long vertical bg lines. */ pixvws = pixMorphCompSequence(pixt1, "o5.1 + o1.200", 0); *ppixvws = pixvws; pixDisplayWriteFormat(pixvws, debug, IFF_PNG); pixDestroy(&pixt1); /* Three steps to getting text line mask: * (1) close the characters and words in the textlines * (2) open the vertical whitespace corridors back up * (3) small opening to remove noise */ pixt1 = pixCloseSafeBrick(NULL, pixs, 30, 1); pixDisplayWrite(pixt1, debug); pixd = pixSubtract(NULL, pixt1, pixvws); pixOpenBrick(pixd, pixd, 3, 3); pixDisplayWriteFormat(pixd, debug, IFF_PNG); pixDestroy(&pixt1); /* Check if text line mask is empty */ if (ptlfound) { *ptlfound = 0; pixZero(pixd, &empty); if (!empty) *ptlfound = 1; } return pixd; } /*------------------------------------------------------------------* * Textblock extraction * *------------------------------------------------------------------*/ /*! * pixGenTextblockMask() * * Input: pixs (1 bpp, textline mask, assumed to be 150 to 200 ppi) * pixvws (vertical white space mask) * debug (flag: 1 for debug output) * Return: pixd (textblock mask), or null on error * * Notes: * (1) Both the input masks (textline and vertical white space) and * the returned textblock mask are at the same resolution. * (2) The result is somewhat noisy, in that small "blocks" of * text may be included. These can be removed by post-processing, * using, e.g., * pixSelectBySize(pix, 60, 60, 4, L_SELECT_IF_EITHER, * L_SELECT_IF_GTE, NULL); */ PIX * pixGenTextblockMask(PIX *pixs, PIX *pixvws, l_int32 debug) { PIX *pixt1, *pixt2, *pixt3, *pixd; PROCNAME("pixGenTextblockMask"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (!pixvws) return (PIX *)ERROR_PTR("pixvws not defined", procName, NULL); if (pixGetDepth(pixs) != 1) return (PIX *)ERROR_PTR("pixs not 1 bpp", procName, NULL); /* Join pixels vertically to make a textblock mask */ pixt1 = pixMorphSequence(pixs, "c1.10 + o4.1", 0); pixDisplayWriteFormat(pixt1, debug, IFF_PNG); /* Solidify the textblock mask and remove noise: * (1) For each cc, close the blocks and dilate slightly * to form a solid mask. * (2) Small horizontal closing between components. * (3) Open the white space between columns, again. * (4) Remove small components. */ pixt2 = pixMorphSequenceByComponent(pixt1, "c30.30 + d3.3", 8, 0, 0, NULL); pixCloseSafeBrick(pixt2, pixt2, 10, 1); pixDisplayWriteFormat(pixt2, debug, IFF_PNG); pixt3 = pixSubtract(NULL, pixt2, pixvws); pixDisplayWriteFormat(pixt3, debug, IFF_PNG); pixd = pixSelectBySize(pixt3, 25, 5, 8, L_SELECT_IF_BOTH, L_SELECT_IF_GTE, NULL); pixDisplayWriteFormat(pixd, debug, IFF_PNG); pixDestroy(&pixt1); pixDestroy(&pixt2); pixDestroy(&pixt3); return pixd; } /*------------------------------------------------------------------* * Location of page foreground * *------------------------------------------------------------------*/ /*! * pixFindPageForeground() * * Input: pixs (full resolution (any type or depth) * threshold (for binarization; typically about 128) * mindist (min distance of text from border to allow * cleaning near border; at 2x reduction, this * should be larger than 50; typically about 70) * erasedist (when conditions are satisfied, erase anything * within this distance of the edge; * typically 30 at 2x reduction) * pagenum (use for debugging when called repeatedly; labels * debug images that are assembled into pdfdir) * showmorph (set to a negative integer to show steps in * generating masks; this is typically used * for debugging region extraction) * display (set to 1 to display mask and selected region * for debugging a single page) * pdfdir (subdirectory of /tmp where images showing the * result are placed when called repeatedly; use * null if no output requested) * Return: box (region including foreground, with some pixel noise * removed), or null if not found * * Notes: * (1) This doesn't simply crop to the fg. It attempts to remove * pixel noise and junk at the edge of the image before cropping. * The input @threshold is used if pixs is not 1 bpp. * (2) There are several debugging options, determined by the * last 4 arguments. * (3) If you want pdf output of results when called repeatedly, * the pagenum arg labels the images written, which go into * /tmp/<pdfdir>/<pagenum>.png. In that case, * you would clean out the /tmp directory before calling this * function on each page: * lept_rmdir(pdfdir); * lept_mkdir(pdfdir); */ BOX * pixFindPageForeground(PIX *pixs, l_int32 threshold, l_int32 mindist, l_int32 erasedist, l_int32 pagenum, l_int32 showmorph, l_int32 display, const char *pdfdir) { char buf[64]; l_int32 flag, nbox, intersects; l_int32 w, h, bx, by, bw, bh, left, right, top, bottom; PIX *pixb, *pixb2, *pixseed, *pixsf, *pixm, *pix1, *pixg2; BOX *box, *boxfg, *boxin, *boxd; BOXA *ba1, *ba2; PROCNAME("pixFindPageForeground"); if (!pixs) return (BOX *)ERROR_PTR("pixs not defined", procName, NULL); /* Binarize, downscale by 0.5, remove the noise to generate a seed, * and do a seedfill back from the seed into those 8-connected * components of the binarized image for which there was at least * one seed pixel. Also clear out any components that are within * 10 pixels of the edge at 2x reduction. */ flag = (showmorph) ? -1 : 0; /* if showmorph == -1, write intermediate * images to /tmp/seq_output_1.pdf */ pixb = pixConvertTo1(pixs, threshold); pixb2 = pixScale(pixb, 0.5, 0.5); pixseed = pixMorphSequence(pixb2, "o1.2 + c9.9 + o3.5", flag); pixsf = pixSeedfillBinary(NULL, pixseed, pixb2, 8); pixSetOrClearBorder(pixsf, 10, 10, 10, 10, PIX_SET); pixm = pixRemoveBorderConnComps(pixsf, 8); if (display) pixDisplay(pixm, 100, 100); /* Now, where is the main block of text? We want to remove noise near * the edge of the image, but to do that, we have to be convinced that * (1) there is noise and (2) it is far enough from the text block * and close enough to the edge. For each edge, if the block * is more than mindist from that edge, then clean 'erasedist' * pixels from the edge. */ pix1 = pixMorphSequence(pixm, "c50.50", flag - 1); ba1 = pixConnComp(pix1, NULL, 8); ba2 = boxaSort(ba1, L_SORT_BY_AREA, L_SORT_DECREASING, NULL); pixGetDimensions(pix1, &w, &h, NULL); nbox = boxaGetCount(ba2); if (nbox > 1) { box = boxaGetBox(ba2, 0, L_CLONE); boxGetGeometry(box, &bx, &by, &bw, &bh); left = (bx > mindist) ? erasedist : 0; right = (w - bx - bw > mindist) ? erasedist : 0; top = (by > mindist) ? erasedist : 0; bottom = (h - by - bh > mindist) ? erasedist : 0; pixSetOrClearBorder(pixm, left, right, top, bottom, PIX_CLR); boxDestroy(&box); } pixDestroy(&pix1); boxaDestroy(&ba1); boxaDestroy(&ba2); /* Locate the foreground region; don't bother cropping */ pixClipToForeground(pixm, NULL, &boxfg); /* Sanity check the fg region. Make sure it's not confined * to a thin boundary on the left and right sides of the image, * in which case it is likely to be noise. */ if (boxfg) { boxin = boxCreate(0.1 * w, 0, 0.8 * w, h); boxIntersects(boxfg, boxin, &intersects); if (!intersects) { L_INFO("found only noise on page %d\n", procName, pagenum); boxDestroy(&boxfg); } boxDestroy(&boxin); } boxd = NULL; if (!boxfg) { L_INFO("no fg region found for page %d\n", procName, pagenum); } else { boxAdjustSides(boxfg, boxfg, -2, 2, -2, 2); /* tiny expansion */ boxd = boxTransform(boxfg, 0, 0, 2.0, 2.0); /* Write image showing box for this page. This is to be * bundled up into a pdf of all the pages, which can be * generated by convertFilesToPdf() */ if (pdfdir) { pixg2 = pixConvert1To4Cmap(pixb); pixRenderBoxArb(pixg2, boxd, 3, 255, 0, 0); snprintf(buf, sizeof(buf), "/tmp/%s/%05d.png", pdfdir, pagenum); if (display) pixDisplay(pixg2, 700, 100); pixWrite(buf, pixg2, IFF_PNG); pixDestroy(&pixg2); } } pixDestroy(&pixb); pixDestroy(&pixb2); pixDestroy(&pixseed); pixDestroy(&pixsf); pixDestroy(&pixm); boxDestroy(&boxfg); return boxd; } /*------------------------------------------------------------------* * Extraction of characters from image with only text * *------------------------------------------------------------------*/ /*! * pixSplitIntoCharacters() * * Input: pixs (1 bpp, contains only deskewed text) * minw (minimum component width for initial filtering; typ. 4) * minh (minimum component height for initial filtering; typ. 4) * &boxa (<optional return> character bounding boxes) * &pixa (<optional return> character images) * &pixdebug (<optional return> showing splittings) * * Return: 0 if OK, 1 on error * * Notes: * (1) This is a simple function that attempts to find split points * based on vertical pixel profiles. * (2) It should be given an image that has an arbitrary number * of text characters. * (3) The returned pixa includes the boxes from which the * (possibly split) components are extracted. */ l_int32 pixSplitIntoCharacters(PIX *pixs, l_int32 minw, l_int32 minh, BOXA **pboxa, PIXA **ppixa, PIX **ppixdebug) { l_int32 ncomp, i, xoff, yoff; BOXA *boxa1, *boxa2, *boxat1, *boxat2, *boxad; BOXAA *baa; PIX *pix, *pix1, *pix2, *pixdb; PIXA *pixa1, *pixadb; PROCNAME("pixSplitIntoCharacters"); if (pboxa) *pboxa = NULL; if (ppixa) *ppixa = NULL; if (ppixdebug) *ppixdebug = NULL; if (!pixs || pixGetDepth(pixs) != 1) return ERROR_INT("pixs not defined or not 1 bpp", procName, 1); /* Remove the small stuff */ pix1 = pixSelectBySize(pixs, minw, minh, 8, L_SELECT_IF_BOTH, L_SELECT_IF_GT, NULL); /* Small vertical close for consolidation */ pix2 = pixMorphSequence(pix1, "c1.10", 0); pixDestroy(&pix1); /* Get the 8-connected components */ boxa1 = pixConnComp(pix2, &pixa1, 8); pixDestroy(&pix2); boxaDestroy(&boxa1); /* Split the components if obvious */ ncomp = pixaGetCount(pixa1); boxa2 = boxaCreate(ncomp); pixadb = (ppixdebug) ? pixaCreate(ncomp) : NULL; for (i = 0; i < ncomp; i++) { pix = pixaGetPix(pixa1, i, L_CLONE); if (ppixdebug) { boxat1 = pixSplitComponentWithProfile(pix, 10, 7, &pixdb); if (pixdb) pixaAddPix(pixadb, pixdb, L_INSERT); } else { boxat1 = pixSplitComponentWithProfile(pix, 10, 7, NULL); } pixaGetBoxGeometry(pixa1, i, &xoff, &yoff, NULL, NULL); boxat2 = boxaTransform(boxat1, xoff, yoff, 1.0, 1.0); boxaJoin(boxa2, boxat2, 0, -1); pixDestroy(&pix); boxaDestroy(&boxat1); boxaDestroy(&boxat2); } pixaDestroy(&pixa1); /* Generate the debug image */ if (ppixdebug) { if (pixaGetCount(pixadb) > 0) { *ppixdebug = pixaDisplayTiledInRows(pixadb, 32, 1500, 1.0, 0, 20, 1); } pixaDestroy(&pixadb); } /* Do a 2D sort on the bounding boxes, and flatten the result to 1D */ baa = boxaSort2d(boxa2, NULL, 0, 0, 5); boxad = boxaaFlattenToBoxa(baa, NULL, L_CLONE); boxaaDestroy(&baa); boxaDestroy(&boxa2); /* Optionally extract the pieces from the input image */ if (ppixa) *ppixa = pixClipRectangles(pixs, boxad); if (pboxa) *pboxa = boxad; else boxaDestroy(&boxad); return 0; } /*! * pixSplitComponentWithProfile() * * Input: pixs (1 bpp, exactly one connected component) * delta (distance used in extrema finding in a numa; typ. 10) * mindel (minimum required difference between profile minimum * and profile values +2 and -2 away; typ. 7) * &pixdebug (<optional return> debug image of splitting) * Return: boxa (of c.c. after splitting), or null on error * * Notes: * (1) This will split the most obvious cases of touching characters. * The split points it is searching for are narrow and deep * minimima in the vertical pixel projection profile, after a * large vertical closing has been applied to the component. */ BOXA * pixSplitComponentWithProfile(PIX *pixs, l_int32 delta, l_int32 mindel, PIX **ppixdebug) { l_int32 w, h, n2, i, firstmin, xmin, xshift; l_int32 nmin, nleft, nright, nsplit, isplit, ncomp; l_int32 *array1, *array2; BOX *box; BOXA *boxad; NUMA *na1, *na2, *nasplit; PIX *pix1, *pixdb; PROCNAME("pixSplitComponentsWithProfile"); if (ppixdebug) *ppixdebug = NULL; if (!pixs || pixGetDepth(pixs) != 1) return (BOXA *)ERROR_PTR("pixa undefined or not 1 bpp", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); /* Closing to consolidate characters vertically */ pix1 = pixCloseSafeBrick(NULL, pixs, 1, 100); /* Get extrema of column projections */ boxad = boxaCreate(2); na1 = pixCountPixelsByColumn(pix1); /* w elements */ pixDestroy(&pix1); na2 = numaFindExtrema(na1, delta); n2 = numaGetCount(na2); if (n2 < 3) { /* no split possible */ box = boxCreate(0, 0, w, h); boxaAddBox(boxad, box, L_INSERT); numaDestroy(&na1); numaDestroy(&na2); return boxad; } /* Look for sufficiently deep and narrow minima. * All minima of of interest must be surrounded by max on each * side. firstmin is the index of first possible minimum. */ array1 = numaGetIArray(na1); array2 = numaGetIArray(na2); if (ppixdebug) numaWriteStream(stderr, na2); firstmin = (array1[array2[0]] > array1[array2[1]]) ? 1 : 2; nasplit = numaCreate(n2); /* will hold split locations */ for (i = firstmin; i < n2 - 1; i+= 2) { xmin = array2[i]; nmin = array1[xmin]; if (xmin + 2 >= w) break; /* no more splits possible */ nleft = array1[xmin - 2]; nright = array1[xmin + 2]; if (ppixdebug) { fprintf(stderr, "Splitting: xmin = %d, w = %d; nl = %d, nmin = %d, nr = %d\n", xmin, w, nleft, nmin, nright); } if (nleft - nmin >= mindel && nright - nmin >= mindel) /* split */ numaAddNumber(nasplit, xmin); } nsplit = numaGetCount(nasplit); #if 0 if (ppixdebug && nsplit > 0) gplotSimple1(na1, GPLOT_X11, "/tmp/splitroot", NULL); #endif numaDestroy(&na1); numaDestroy(&na2); FREE(array1); FREE(array2); if (nsplit == 0) { /* no splitting */ box = boxCreate(0, 0, w, h); boxaAddBox(boxad, box, L_INSERT); return boxad; } /* Use split points to generate b.b. after splitting */ for (i = 0, xshift = 0; i < nsplit; i++) { numaGetIValue(nasplit, i, &isplit); box = boxCreate(xshift, 0, isplit - xshift, h); boxaAddBox(boxad, box, L_INSERT); xshift = isplit + 1; } box = boxCreate(xshift, 0, w - xshift, h); boxaAddBox(boxad, box, L_INSERT); numaDestroy(&nasplit); if (ppixdebug) { pixdb = pixConvertTo32(pixs); ncomp = boxaGetCount(boxad); for (i = 0; i < ncomp; i++) { box = boxaGetBox(boxad, i, L_CLONE); pixRenderBoxBlend(pixdb, box, 1, 255, 0, 0, 0.5); boxDestroy(&box); } *ppixdebug = pixdb; } return boxad; }
gpl-3.0
dandan94/OpenGLTest
finalOpenGL/HelloGLFW/lib/boost_1_59_0/libs/multiprecision/test/test_cpp_int_conv.cpp
49
1765
/////////////////////////////////////////////////////////////// // Copyright 2012 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_ // #ifdef _MSC_VER # define _SCL_SECURE_NO_WARNINGS #endif #include <boost/detail/lightweight_test.hpp> #include <boost/array.hpp> #include "test.hpp" #include <boost/multiprecision/cpp_int.hpp> int main() { using namespace boost::multiprecision; // // Test interconversions between different precisions: // cpp_int i1(2); int128_t i2(3); int256_t i3(4); number<cpp_int_backend<32, 32, signed_magnitude, checked, void> > i4(5); i1 = i3; BOOST_TEST(i1 == 4); i1 = i4; BOOST_TEST(i1 == 5); i3 = -1234567; i4 = -5677334; i1 = i3; BOOST_TEST(i1 == -1234567); i1 = i4; BOOST_TEST(i1 == -5677334); i3 = i2; BOOST_TEST(i3 == 3); i3 = -1234567; uint128_t i5(i3); BOOST_TEST(i5 == -1234567); int128_t i6(i4); BOOST_TEST(i6 == -5677334); number<cpp_int_backend<32, 32, signed_magnitude, unchecked, void>, et_off> i7(i3); BOOST_TEST(i7 == -1234567); int256_t i8(i6); BOOST_TEST(i8 == -5677334); i7.assign(4.0); BOOST_TEST(i7 == 4); number<cpp_int_backend<30, 30, signed_magnitude, checked, void>, et_off> i9(-5677334); i7 = i9; BOOST_TEST(i7 == -5677334); i7 = number<cpp_int_backend<32, 32, signed_magnitude, checked, void>, et_off>(i9); BOOST_TEST(i7 == -5677334); i9 = static_cast<number<cpp_int_backend<30, 30, signed_magnitude, checked, void>, et_off> >(i7); BOOST_TEST(i9 == -5677334); ++i9; i7 = i9; BOOST_TEST(i7 == 1 - 5677334); return boost::report_errors(); }
gpl-3.0
lmangani/ntopng
third-party/zeromq-4.1.3/src/null_mechanism.cpp
52
10675
/* Copyright (c) 2007-2015 Contributors as noted in the AUTHORS file This file is part of libzmq, the ZeroMQ core engine in C++. libzmq is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. As a special exception, the Contributors give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. libzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "platform.hpp" #ifdef ZMQ_HAVE_WINDOWS #include "windows.hpp" #endif #include <stddef.h> #include <string.h> #include <stdlib.h> #include "err.hpp" #include "msg.hpp" #include "session_base.hpp" #include "wire.hpp" #include "null_mechanism.hpp" zmq::null_mechanism_t::null_mechanism_t (session_base_t *session_, const std::string &peer_address_, const options_t &options_) : mechanism_t (options_), session (session_), peer_address (peer_address_), ready_command_sent (false), error_command_sent (false), ready_command_received (false), error_command_received (false), zap_connected (false), zap_request_sent (false), zap_reply_received (false) { // NULL mechanism only uses ZAP if there's a domain defined // This prevents ZAP requests on naive sockets if (options.zap_domain.size () > 0 && session->zap_connect () == 0) zap_connected = true; } zmq::null_mechanism_t::~null_mechanism_t () { } int zmq::null_mechanism_t::next_handshake_command (msg_t *msg_) { if (ready_command_sent || error_command_sent) { errno = EAGAIN; return -1; } if (zap_connected && !zap_reply_received) { if (zap_request_sent) { errno = EAGAIN; return -1; } send_zap_request (); zap_request_sent = true; const int rc = receive_and_process_zap_reply (); if (rc != 0) return -1; zap_reply_received = true; } if (zap_reply_received && strncmp (status_code, "200", sizeof status_code) != 0) { const int rc = msg_->init_size (6 + 1 + sizeof status_code); zmq_assert (rc == 0); unsigned char *msg_data = static_cast <unsigned char *> (msg_->data ()); memcpy (msg_data, "\5ERROR", 6); msg_data [6] = sizeof status_code; memcpy (msg_data + 7, status_code, sizeof status_code); error_command_sent = true; return 0; } unsigned char *const command_buffer = (unsigned char *) malloc (512); alloc_assert (command_buffer); unsigned char *ptr = command_buffer; // Add mechanism string memcpy (ptr, "\5READY", 6); ptr += 6; // Add socket type property const char *socket_type = socket_type_string (options.type); ptr += add_property (ptr, "Socket-Type", socket_type, strlen (socket_type)); // Add identity property if (options.type == ZMQ_REQ || options.type == ZMQ_DEALER || options.type == ZMQ_ROUTER) ptr += add_property (ptr, "Identity", options.identity, options.identity_size); const size_t command_size = ptr - command_buffer; const int rc = msg_->init_size (command_size); errno_assert (rc == 0); memcpy (msg_->data (), command_buffer, command_size); free (command_buffer); ready_command_sent = true; return 0; } int zmq::null_mechanism_t::process_handshake_command (msg_t *msg_) { if (ready_command_received || error_command_received) { // Temporary support for security debugging puts ("NULL I: client sent invalid NULL handshake (duplicate READY)"); errno = EPROTO; return -1; } const unsigned char *cmd_data = static_cast <unsigned char *> (msg_->data ()); const size_t data_size = msg_->size (); int rc = 0; if (data_size >= 6 && !memcmp (cmd_data, "\5READY", 6)) rc = process_ready_command (cmd_data, data_size); else if (data_size >= 6 && !memcmp (cmd_data, "\5ERROR", 6)) rc = process_error_command (cmd_data, data_size); else { // Temporary support for security debugging puts ("NULL I: client sent invalid NULL handshake (not READY)"); errno = EPROTO; rc = -1; } if (rc == 0) { int rc = msg_->close (); errno_assert (rc == 0); rc = msg_->init (); errno_assert (rc == 0); } return rc; } int zmq::null_mechanism_t::process_ready_command ( const unsigned char *cmd_data, size_t data_size) { ready_command_received = true; return parse_metadata (cmd_data + 6, data_size - 6); } int zmq::null_mechanism_t::process_error_command ( const unsigned char *cmd_data, size_t data_size) { if (data_size < 7) { errno = EPROTO; return -1; } const size_t error_reason_len = static_cast <size_t> (cmd_data [6]); if (error_reason_len > data_size - 7) { errno = EPROTO; return -1; } error_command_received = true; return 0; } int zmq::null_mechanism_t::zap_msg_available () { if (zap_reply_received) { errno = EFSM; return -1; } const int rc = receive_and_process_zap_reply (); if (rc == 0) zap_reply_received = true; return rc; } zmq::mechanism_t::status_t zmq::null_mechanism_t::status () const { const bool command_sent = ready_command_sent || error_command_sent; const bool command_received = ready_command_received || error_command_received; if (ready_command_sent && ready_command_received) return ready; else if (command_sent && command_received) return error; else return handshaking; } void zmq::null_mechanism_t::send_zap_request () { int rc; msg_t msg; // Address delimiter frame rc = msg.init (); errno_assert (rc == 0); msg.set_flags (msg_t::more); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); // Version frame rc = msg.init_size (3); errno_assert (rc == 0); memcpy (msg.data (), "1.0", 3); msg.set_flags (msg_t::more); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); // Request id frame rc = msg.init_size (1); errno_assert (rc == 0); memcpy (msg.data (), "1", 1); msg.set_flags (msg_t::more); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); // Domain frame rc = msg.init_size (options.zap_domain.length ()); errno_assert (rc == 0); memcpy (msg.data (), options.zap_domain.c_str (), options.zap_domain.length ()); msg.set_flags (msg_t::more); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); // Address frame rc = msg.init_size (peer_address.length ()); errno_assert (rc == 0); memcpy (msg.data (), peer_address.c_str (), peer_address.length ()); msg.set_flags (msg_t::more); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); // Identity frame rc = msg.init_size (options.identity_size); errno_assert (rc == 0); memcpy (msg.data (), options.identity, options.identity_size); msg.set_flags (msg_t::more); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); // Mechanism frame rc = msg.init_size (4); errno_assert (rc == 0); memcpy (msg.data (), "NULL", 4); rc = session->write_zap_msg (&msg); errno_assert (rc == 0); } int zmq::null_mechanism_t::receive_and_process_zap_reply () { int rc = 0; msg_t msg [7]; // ZAP reply consists of 7 frames // Initialize all reply frames for (int i = 0; i < 7; i++) { rc = msg [i].init (); errno_assert (rc == 0); } for (int i = 0; i < 7; i++) { rc = session->read_zap_msg (&msg [i]); if (rc == -1) break; if ((msg [i].flags () & msg_t::more) == (i < 6? 0: msg_t::more)) { // Temporary support for security debugging puts ("NULL I: ZAP handler sent incomplete reply message"); errno = EPROTO; rc = -1; break; } } if (rc != 0) goto error; // Address delimiter frame if (msg [0].size () > 0) { // Temporary support for security debugging puts ("NULL I: ZAP handler sent malformed reply message"); errno = EPROTO; rc = -1; goto error; } // Version frame if (msg [1].size () != 3 || memcmp (msg [1].data (), "1.0", 3)) { // Temporary support for security debugging puts ("NULL I: ZAP handler sent bad version number"); errno = EPROTO; rc = -1; goto error; } // Request id frame if (msg [2].size () != 1 || memcmp (msg [2].data (), "1", 1)) { // Temporary support for security debugging puts ("NULL I: ZAP handler sent bad request ID"); errno = EPROTO; rc = -1; goto error; } // Status code frame if (msg [3].size () != 3) { // Temporary support for security debugging puts ("NULL I: ZAP handler rejected client authentication"); errno = EPROTO; rc = -1; goto error; } // Save status code memcpy (status_code, msg [3].data (), sizeof status_code); // Save user id set_user_id (msg [5].data (), msg [5].size ()); // Process metadata frame rc = parse_metadata (static_cast <const unsigned char*> (msg [6].data ()), msg [6].size (), true); error: for (int i = 0; i < 7; i++) { const int rc2 = msg [i].close (); errno_assert (rc2 == 0); } return rc; }
gpl-3.0
RobsonRojas/frertos-udemy
FreeRTOSKeil/FreeRTOSv9.0.0/FreeRTOS/Demo/CORTEX_A53_64-bit_UltraScale_MPSoC/RTOSDemo_A53_bsp/psu_cortexa53_0/libsrc/standalone_v5_4/src/xil_testcache.c
53
9133
/****************************************************************************** * * Copyright (C) 2009 - 2015 Xilinx, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ /*****************************************************************************/ /** * * @file xil_testcache.c * * Contains utility functions to test cache. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ------------------------------------------------------- * 1.00a hbm 07/28/09 Initial release * 4.1 asa 05/09/14 Ensured that the address uses for cache test is aligned * cache line. * </pre> * * @note * * This file contain functions that all operate on HAL. * ******************************************************************************/ #ifdef __ARM__ #include "xil_cache.h" #include "xil_testcache.h" #include "xil_types.h" #include "xpseudo_asm.h" #ifdef __aarch64__ #include "xreg_cortexa53.h" #else #include "xreg_cortexr5.h" #endif #include "xil_types.h" extern void xil_printf(const char8 *ctrl1, ...); #define DATA_LENGTH 128 #ifdef __aarch64__ static INTPTR Data[DATA_LENGTH] __attribute__ ((aligned(64))); #else static INTPTR Data[DATA_LENGTH] __attribute__ ((aligned(32))); #endif /** * Perform DCache range related API test such as Xil_DCacheFlushRange and * Xil_DCacheInvalidateRange. This test function writes a constant value * to the Data array, flushes the range, writes a new value, then invalidates * the corresponding range. * * @return * * - 0 is returned for a pass * - -1 is returned for a failure */ s32 Xil_TestDCacheRange(void) { s32 Index; s32 Status = 0; u32 CtrlReg; INTPTR Value; xil_printf("-- Cache Range Test --\n\r"); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = 0xA0A00505; xil_printf(" initialize Data done:\r\n"); Xil_DCacheFlushRange((INTPTR)Data, DATA_LENGTH * sizeof(INTPTR)); xil_printf(" flush range done\r\n"); dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg &= ~(XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg &= ~(XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); Status = 0; for (Index = 0; Index < DATA_LENGTH; Index++) { Value = Data[Index]; if (Value != 0xA0A00505) { Status = -1; xil_printf("Data[%d] = %x\r\n", Index, Value); break; } } if (!Status) { xil_printf(" Flush worked\r\n"); } else { xil_printf("Error: flush dcache range not working\r\n"); } dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg |= (XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg |= (XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = 0xA0A0C505; Xil_DCacheFlushRange((INTPTR)Data, DATA_LENGTH * sizeof(INTPTR)); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = Index + 3; Xil_DCacheInvalidateRange((INTPTR)Data, DATA_LENGTH * sizeof(INTPTR)); xil_printf(" invalidate dcache range done\r\n"); dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg &= ~(XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg &= ~(XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = 0xA0A0A05; dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg |= (XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg |= (XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); Status = 0; for (Index = 0; Index < DATA_LENGTH; Index++) { Value = Data[Index]; if (Value != 0xA0A0A05) { Status = -1; xil_printf("Data[%d] = %x\r\n", Index, Value); break; } } if (!Status) { xil_printf(" Invalidate worked\r\n"); } else { xil_printf("Error: Invalidate dcache range not working\r\n"); } xil_printf("-- Cache Range Test Complete --\r\n"); return Status; } /** * Perform DCache all related API test such as Xil_DCacheFlush and * Xil_DCacheInvalidate. This test function writes a constant value * to the Data array, flushes the DCache, writes a new value, then invalidates * the DCache. * * @return * - 0 is returned for a pass * - -1 is returned for a failure */ s32 Xil_TestDCacheAll(void) { s32 Index; s32 Status; INTPTR Value; u32 CtrlReg; xil_printf("-- Cache All Test --\n\r"); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = 0x50500A0A; xil_printf(" initialize Data done:\r\n"); Xil_DCacheFlush(); xil_printf(" flush all done\r\n"); dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg &= ~(XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg &= ~(XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); Status = 0; for (Index = 0; Index < DATA_LENGTH; Index++) { Value = Data[Index]; if (Value != 0x50500A0A) { Status = -1; xil_printf("Data[%d] = %x\r\n", Index, Value); break; } } if (!Status) { xil_printf(" Flush all worked\r\n"); } else { xil_printf("Error: Flush dcache all not working\r\n"); } dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg |= (XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg |= (XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = 0x505FFA0A; Xil_DCacheFlush(); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = Index + 3; Xil_DCacheInvalidate(); xil_printf(" invalidate all done\r\n"); dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg &= ~(XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg &= ~(XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); for (Index = 0; Index < DATA_LENGTH; Index++) Data[Index] = 0x50CFA0A; dsb(); #ifdef __aarch64__ CtrlReg = mfcp(SCTLR_EL3); CtrlReg |= (XREG_CONTROL_DCACHE_BIT); mtcp(SCTLR_EL3,CtrlReg); #else CtrlReg = mfcp(XREG_CP15_SYS_CONTROL); CtrlReg |= (XREG_CP15_CONTROL_C_BIT); mtcp(XREG_CP15_SYS_CONTROL, CtrlReg); #endif dsb(); Status = 0; for (Index = 0; Index < DATA_LENGTH; Index++) { Value = Data[Index]; if (Value != 0x50CFA0A) { Status = -1; xil_printf("Data[%d] = %x\r\n", Index, Value); break; } } if (!Status) { xil_printf(" Invalidate all worked\r\n"); } else { xil_printf("Error: Invalidate dcache all not working\r\n"); } xil_printf("-- DCache all Test Complete --\n\r"); return Status; } /** * Perform Xil_ICacheInvalidateRange() on a few function pointers. * * @return * * - 0 is returned for a pass * The function will hang if it fails. */ s32 Xil_TestICacheRange(void) { Xil_ICacheInvalidateRange((INTPTR)Xil_TestICacheRange, 1024); Xil_ICacheInvalidateRange((INTPTR)Xil_TestDCacheRange, 1024); Xil_ICacheInvalidateRange((INTPTR)Xil_TestDCacheAll, 1024); xil_printf("-- Invalidate icache range done --\r\n"); return 0; } /** * Perform Xil_ICacheInvalidate(). * * @return * * - 0 is returned for a pass * The function will hang if it fails. */ s32 Xil_TestICacheAll(void) { Xil_ICacheInvalidate(); xil_printf("-- Invalidate icache all done --\r\n"); return 0; } #endif
gpl-3.0
pinkywafer/cleanflight
lib/main/STM32F7xx_HAL_Driver/Src/stm32f7xx_hal_rtc_ex.c
54
59328
/** ****************************************************************************** * @file stm32f7xx_hal_rtc_ex.c * @author MCD Application Team * @version V1.2.2 * @date 14-April-2017 * @brief RTC HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Real Time Clock (RTC) Extension peripheral: * + RTC Time Stamp functions * + RTC Tamper functions * + RTC Wake-up functions * + Extension Control functions * + Extension RTC features functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] (+) Enable the RTC domain access. (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour format using the HAL_RTC_Init() function. *** RTC Wakeup configuration *** ================================ [..] (+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTC_SetWakeUpTimer() function. You can also configure the RTC Wakeup timer in interrupt mode using the HAL_RTC_SetWakeUpTimer_IT() function. (+) To read the RTC WakeUp Counter register, use the HAL_RTC_GetWakeUpTimer() function. *** TimeStamp configuration *** =============================== [..] (+) Enables the RTC TimeStamp using the HAL_RTC_SetTimeStamp() function. You can also configure the RTC TimeStamp with interrupt mode using the HAL_RTC_SetTimeStamp_IT() function. (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTC_GetTimeStamp() function. *** Internal TimeStamp configuration *** =============================== [..] (+) Enables the RTC internal TimeStamp using the HAL_RTC_SetInternalTimeStamp() function. (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTC_GetTimeStamp() function. *** Tamper configuration *** ============================ [..] (+) Enable the RTC Tamper and Configure the Tamper filter count, trigger Edge or Level according to the Tamper filter (if equal to 0 Edge else Level) value, sampling frequency, NoErase, MaskFlag, precharge or discharge and Pull-UP using the HAL_RTC_SetTamper() function. You can configure RTC Tamper with interrupt mode using HAL_RTC_SetTamper_IT() function. (+) The default configuration of the Tamper erases the backup registers. To avoid erase, enable the NoErase field on the RTC_TAMPCR register. *** Backup Data Registers configuration *** =========================================== [..] (+) To write to the RTC Backup Data registers, use the HAL_RTC_BKUPWrite() function. (+) To read the RTC Backup Data registers, use the HAL_RTC_BKUPRead() function. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f7xx_hal.h" /** @addtogroup STM32F7xx_HAL_Driver * @{ */ /** @defgroup RTCEx RTCEx * @brief RTC Extended HAL module driver * @{ */ #ifdef HAL_RTC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup RTCEx_Exported_Functions RTCEx Exported Functions * @{ */ /** @defgroup RTCEx_Group1 RTC TimeStamp and Tamper functions * @brief RTC TimeStamp and Tamper functions * @verbatim =============================================================================== ##### RTC TimeStamp and Tamper functions ##### =============================================================================== [..] This section provides functions allowing to configure TimeStamp feature @endverbatim * @{ */ /** * @brief Sets TimeStamp. * @note This API must be called before enabling the TimeStamp feature. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is * activated. * This parameter can be one of the following values: * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the * rising edge of the related pin. * @arg RTC_TIMESTAMPEDGE_FALLING: the Time stamp event occurs on the * falling edge of the related pin. * @param RTC_TimeStampPin: specifies the RTC TimeStamp Pin. * This parameter can be one of the following values: * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin. * @arg RTC_TIMESTAMPPIN_PI8: PI8 is selected as RTC TimeStamp Pin. * @arg RTC_TIMESTAMPPIN_PC1: PC1 is selected as RTC TimeStamp Pin. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Get the RTC_CR register and clear the bits to be configured */ tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); tmpreg|= TimeStampEdge; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); hrtc->Instance->OR &= (uint32_t)~RTC_OR_TSINSEL; hrtc->Instance->OR |= (uint32_t)(RTC_TimeStampPin); /* Configure the Time Stamp TSEDGE and Enable bits */ hrtc->Instance->CR = (uint32_t)tmpreg; __HAL_RTC_TIMESTAMP_ENABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Sets TimeStamp with Interrupt. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @note This API must be called before enabling the TimeStamp feature. * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is * activated. * This parameter can be one of the following values: * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the * rising edge of the related pin. * @arg RTC_TIMESTAMPEDGE_FALLING: the Time stamp event occurs on the * falling edge of the related pin. * @param RTC_TimeStampPin: Specifies the RTC TimeStamp Pin. * This parameter can be one of the following values: * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin. * @arg RTC_TIMESTAMPPIN_PI8: PI8 is selected as RTC TimeStamp Pin. * @arg RTC_TIMESTAMPPIN_PC1: PC1 is selected as RTC TimeStamp Pin. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Get the RTC_CR register and clear the bits to be configured */ tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); tmpreg |= TimeStampEdge; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Configure the Time Stamp TSEDGE and Enable bits */ hrtc->Instance->CR = (uint32_t)tmpreg; hrtc->Instance->OR &= (uint32_t)~RTC_OR_TSINSEL; hrtc->Instance->OR |= (uint32_t)(RTC_TimeStampPin); /* Clear RTC Timestamp flag */ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); __HAL_RTC_TIMESTAMP_ENABLE(hrtc); /* Enable IT timestamp */ __HAL_RTC_TIMESTAMP_ENABLE_IT(hrtc,RTC_IT_TS); /* RTC timestamp Interrupt Configuration: EXTI configuration */ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT(); EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT; /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Deactivates TimeStamp. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) { uint32_t tmpreg = 0; /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* In case of interrupt mode is used, the interrupt source must disabled */ __HAL_RTC_TIMESTAMP_DISABLE_IT(hrtc, RTC_IT_TS); /* Get the RTC_CR register and clear the bits to be configured */ tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); /* Configure the Time Stamp TSEDGE and Enable bits */ hrtc->Instance->CR = (uint32_t)tmpreg; /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Sets Internal TimeStamp. * @note This API must be called before enabling the internal TimeStamp feature. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetInternalTimeStamp(RTC_HandleTypeDef *hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Configure the internal Time Stamp Enable bits */ __HAL_RTC_INTERNAL_TIMESTAMP_ENABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Deactivates internal TimeStamp. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_DeactivateInternalTimeStamp(RTC_HandleTypeDef *hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Configure the internal Time Stamp Enable bits */ __HAL_RTC_INTERNAL_TIMESTAMP_DISABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Gets the RTC TimeStamp value. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param sTimeStamp: Pointer to Time structure * @param sTimeStampDate: Pointer to Date structure * @param Format: specifies the format of the entered parameters. * This parameter can be one of the following values: * FORMAT_BIN: Binary data format * FORMAT_BCD: BCD data format * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef* sTimeStamp, RTC_DateTypeDef* sTimeStampDate, uint32_t Format) { uint32_t tmptime = 0, tmpdate = 0; /* Check the parameters */ assert_param(IS_RTC_FORMAT(Format)); /* Get the TimeStamp time and date registers values */ tmptime = (uint32_t)(hrtc->Instance->TSTR & RTC_TR_RESERVED_MASK); tmpdate = (uint32_t)(hrtc->Instance->TSDR & RTC_DR_RESERVED_MASK); /* Fill the Time structure fields with the read parameters */ sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TR_HT | RTC_TR_HU)) >> 16); sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TR_MNT | RTC_TR_MNU)) >> 8); sTimeStamp->Seconds = (uint8_t)(tmptime & (RTC_TR_ST | RTC_TR_SU)); sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TR_PM)) >> 16); sTimeStamp->SubSeconds = (uint32_t) hrtc->Instance->TSSSR; /* Fill the Date structure fields with the read parameters */ sTimeStampDate->Year = 0; sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_DR_MT | RTC_DR_MU)) >> 8); sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_DR_DT | RTC_DR_DU)); sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_DR_WDU)) >> 13); /* Check the input parameters format */ if(Format == RTC_FORMAT_BIN) { /* Convert the TimeStamp structure parameters to Binary format */ sTimeStamp->Hours = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Hours); sTimeStamp->Minutes = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Minutes); sTimeStamp->Seconds = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Seconds); /* Convert the DateTimeStamp structure parameters to Binary format */ sTimeStampDate->Month = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Month); sTimeStampDate->Date = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Date); sTimeStampDate->WeekDay = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->WeekDay); } /* Clear the TIMESTAMP Flag */ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); return HAL_OK; } /** * @brief Sets Tamper * @note By calling this API we disable the tamper interrupt for all tampers. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param sTamper: Pointer to Tamper Structure. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_RTC_TAMPER(sTamper->Tamper)); assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); assert_param(IS_RTC_TAMPER_ERASE_MODE(sTamper->NoErase)); assert_param(IS_RTC_TAMPER_MASKFLAG_STATE(sTamper->MaskFlag)); assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter)); assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE) { sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1); } if(sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) { sTamper->NoErase = 0; if((sTamper->Tamper & RTC_TAMPER_1) != 0) { sTamper->NoErase |= RTC_TAMPCR_TAMP1NOERASE; } if((sTamper->Tamper & RTC_TAMPER_2) != 0) { sTamper->NoErase |= RTC_TAMPCR_TAMP2NOERASE; } if((sTamper->Tamper & RTC_TAMPER_3) != 0) { sTamper->NoErase |= RTC_TAMPCR_TAMP3NOERASE; } } if(sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) { sTamper->MaskFlag = 0; if((sTamper->Tamper & RTC_TAMPER_1) != 0) { sTamper->MaskFlag |= RTC_TAMPCR_TAMP1MF; } if((sTamper->Tamper & RTC_TAMPER_2) != 0) { sTamper->MaskFlag |= RTC_TAMPCR_TAMP2MF; } if((sTamper->Tamper & RTC_TAMPER_3) != 0) { sTamper->MaskFlag |= RTC_TAMPCR_TAMP3MF; } } tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->NoErase |\ (uint32_t)sTamper->MaskFlag | (uint32_t)sTamper->Filter | (uint32_t)sTamper->SamplingFrequency |\ (uint32_t)sTamper->PrechargeDuration | (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection); hrtc->Instance->TAMPCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAMPCR_TAMPTS |\ (uint32_t)RTC_TAMPCR_TAMPFREQ | (uint32_t)RTC_TAMPCR_TAMPFLT | (uint32_t)RTC_TAMPCR_TAMPPRCH |\ (uint32_t)RTC_TAMPCR_TAMPPUDIS | (uint32_t)RTC_TAMPCR_TAMPIE | (uint32_t)RTC_TAMPCR_TAMP1IE |\ (uint32_t)RTC_TAMPCR_TAMP2IE | (uint32_t)RTC_TAMPCR_TAMP3IE | (uint32_t)RTC_TAMPCR_TAMP1NOERASE |\ (uint32_t)RTC_TAMPCR_TAMP2NOERASE | (uint32_t)RTC_TAMPCR_TAMP3NOERASE | (uint32_t)RTC_TAMPCR_TAMP1MF |\ (uint32_t)RTC_TAMPCR_TAMP2MF | (uint32_t)RTC_TAMPCR_TAMP3MF); hrtc->Instance->TAMPCR |= tmpreg; hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Sets Tamper with interrupt. * @note By calling this API we force the tamper interrupt for all tampers. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param sTamper: Pointer to RTC Tamper. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_RTC_TAMPER(sTamper->Tamper)); assert_param(IS_RTC_TAMPER_INTERRUPT(sTamper->Interrupt)); assert_param(IS_RTC_TAMPER_TRIGGER(sTamper->Trigger)); assert_param(IS_RTC_TAMPER_ERASE_MODE(sTamper->NoErase)); assert_param(IS_RTC_TAMPER_MASKFLAG_STATE(sTamper->MaskFlag)); assert_param(IS_RTC_TAMPER_FILTER(sTamper->Filter)); assert_param(IS_RTC_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); assert_param(IS_RTC_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); assert_param(IS_RTC_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); assert_param(IS_RTC_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Configure the tamper trigger */ if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE) { sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1); } if(sTamper->NoErase != RTC_TAMPER_ERASE_BACKUP_ENABLE) { sTamper->NoErase = 0; if((sTamper->Tamper & RTC_TAMPER_1) != 0) { sTamper->NoErase |= RTC_TAMPCR_TAMP1NOERASE; } if((sTamper->Tamper & RTC_TAMPER_2) != 0) { sTamper->NoErase |= RTC_TAMPCR_TAMP2NOERASE; } if((sTamper->Tamper & RTC_TAMPER_3) != 0) { sTamper->NoErase |= RTC_TAMPCR_TAMP3NOERASE; } } if(sTamper->MaskFlag != RTC_TAMPERMASK_FLAG_DISABLE) { sTamper->MaskFlag = 0; if((sTamper->Tamper & RTC_TAMPER_1) != 0) { sTamper->MaskFlag |= RTC_TAMPCR_TAMP1MF; } if((sTamper->Tamper & RTC_TAMPER_2) != 0) { sTamper->MaskFlag |= RTC_TAMPCR_TAMP2MF; } if((sTamper->Tamper & RTC_TAMPER_3) != 0) { sTamper->MaskFlag |= RTC_TAMPCR_TAMP3MF; } } tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Interrupt | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->NoErase |\ (uint32_t)sTamper->MaskFlag | (uint32_t)sTamper->Filter | (uint32_t)sTamper->SamplingFrequency |\ (uint32_t)sTamper->PrechargeDuration | (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection); hrtc->Instance->TAMPCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAMPCR_TAMPTS |\ (uint32_t)RTC_TAMPCR_TAMPFREQ | (uint32_t)RTC_TAMPCR_TAMPFLT | (uint32_t)RTC_TAMPCR_TAMPPRCH |\ (uint32_t)RTC_TAMPCR_TAMPPUDIS | (uint32_t)RTC_TAMPCR_TAMPIE | (uint32_t)RTC_TAMPCR_TAMP1IE |\ (uint32_t)RTC_TAMPCR_TAMP2IE | (uint32_t)RTC_TAMPCR_TAMP3IE | (uint32_t)RTC_TAMPCR_TAMP1NOERASE |\ (uint32_t)RTC_TAMPCR_TAMP2NOERASE | (uint32_t)RTC_TAMPCR_TAMP3NOERASE | (uint32_t)RTC_TAMPCR_TAMP1MF |\ (uint32_t)RTC_TAMPCR_TAMP2MF | (uint32_t)RTC_TAMPCR_TAMP3MF); hrtc->Instance->TAMPCR |= tmpreg; if(sTamper->Tamper == RTC_TAMPER_1) { /* Clear RTC Tamper 1 flag */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP1F); } else if(sTamper->Tamper == RTC_TAMPER_2) { /* Clear RTC Tamper 2 flag */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F); } else { /* Clear RTC Tamper 3 flag */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP3F); } /* RTC Tamper Interrupt Configuration: EXTI configuration */ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_ENABLE_IT(); EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT; hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Deactivates Tamper. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param Tamper: Selected tamper pin. * This parameter can be RTC_Tamper_1 and/or RTC_TAMPER_2. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper) { assert_param(IS_RTC_TAMPER(Tamper)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the selected Tamper pin */ hrtc->Instance->TAMPCR &= (uint32_t)~Tamper; if ((Tamper & RTC_TAMPER_1) != 0) { /* Disable the Tamper1 interrupt */ hrtc->Instance->TAMPCR &= (uint32_t)~(RTC_IT_TAMP | RTC_IT_TAMP1); } if ((Tamper & RTC_TAMPER_2) != 0) { /* Disable the Tamper2 interrupt */ hrtc->Instance->TAMPCR &= (uint32_t)~(RTC_IT_TAMP | RTC_IT_TAMP2); } if ((Tamper & RTC_TAMPER_3) != 0) { /* Disable the Tamper2 interrupt */ hrtc->Instance->TAMPCR &= (uint32_t)~(RTC_IT_TAMP | RTC_IT_TAMP3); } hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief This function handles TimeStamp interrupt request. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc) { if(__HAL_RTC_TIMESTAMP_GET_IT(hrtc, RTC_IT_TS)) { /* Get the status of the Interrupt */ if((uint32_t)(hrtc->Instance->CR & RTC_IT_TS) != (uint32_t)RESET) { /* TIMESTAMP callback */ HAL_RTCEx_TimeStampEventCallback(hrtc); /* Clear the TIMESTAMP interrupt pending bit */ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc,RTC_FLAG_TSF); } } /* Get the status of the Interrupt */ if(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F)== SET) { /* Get the TAMPER Interrupt enable bit and pending bit */ if((((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMPIE)) != (uint32_t)RESET) || \ (((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMP1IE)) != (uint32_t)RESET)) { /* Tamper callback */ HAL_RTCEx_Tamper1EventCallback(hrtc); /* Clear the Tamper interrupt pending bit */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F); } } /* Get the status of the Interrupt */ if(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F)== SET) { /* Get the TAMPER Interrupt enable bit and pending bit */ if((((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMPIE)) != (uint32_t)RESET) || \ (((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMP2IE)) != (uint32_t)RESET)) { /* Tamper callback */ HAL_RTCEx_Tamper2EventCallback(hrtc); /* Clear the Tamper interrupt pending bit */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F); } } /* Get the status of the Interrupt */ if(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP3F)== SET) { /* Get the TAMPER Interrupt enable bit and pending bit */ if((((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMPIE)) != (uint32_t)RESET) || \ (((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMP3IE)) != (uint32_t)RESET)) { /* Tamper callback */ HAL_RTCEx_Tamper3EventCallback(hrtc); /* Clear the Tamper interrupt pending bit */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP3F); } } /* Clear the EXTI's Flag for RTC TimeStamp and Tamper */ __HAL_RTC_TAMPER_TIMESTAMP_EXTI_CLEAR_FLAG(); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; } /** * @brief TimeStamp callback. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ __weak void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrtc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_RTC_TimeStampEventCallback could be implemented in the user file */ } /** * @brief Tamper 1 callback. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ __weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrtc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_RTC_Tamper1EventCallback could be implemented in the user file */ } /** * @brief Tamper 2 callback. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ __weak void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrtc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_RTC_Tamper2EventCallback could be implemented in the user file */ } /** * @brief Tamper 3 callback. * @param hrtc: RTC handle * @retval None */ __weak void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrtc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_RTCEx_Tamper3EventCallback could be implemented in the user file */ } /** * @brief This function handles TimeStamp polling request. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); while(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) == RESET) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; } } } if(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSOVF) != RESET) { /* Clear the TIMESTAMP OverRun Flag */ __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF); /* Change TIMESTAMP state */ hrtc->State = HAL_RTC_STATE_ERROR; return HAL_ERROR; } /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; return HAL_OK; } /** * @brief This function handles Tamper1 Polling. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); /* Get the status of the Interrupt */ while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F)== RESET) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; } } } /* Clear the Tamper Flag */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; return HAL_OK; } /** * @brief This function handles Tamper2 Polling. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); /* Get the status of the Interrupt */ while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) == RESET) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; } } } /* Clear the Tamper Flag */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP2F); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; return HAL_OK; } /** * @brief This function handles Tamper3 Polling. * @param hrtc: RTC handle * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_PollForTamper3Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) { uint32_t tickstart = HAL_GetTick(); /* Get the status of the Interrupt */ while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP3F) == RESET) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; } } } /* Clear the Tamper Flag */ __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP3F); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; return HAL_OK; } /** * @} */ /** @defgroup RTCEx_Group2 RTC Wake-up functions * @brief RTC Wake-up functions * @verbatim =============================================================================== ##### RTC Wake-up functions ##### =============================================================================== [..] This section provides functions allowing to configure Wake-up feature @endverbatim * @{ */ /** * @brief Sets wake up timer. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param WakeUpCounter: Wake up counter * @param WakeUpClock: Wake up clock * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) { uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); /* Get tick */ tickstart = HAL_GetTick(); /*Check RTC WUTWF flag is reset only when wake up timer enabled*/ if((hrtc->Instance->CR & RTC_CR_WUTE) != RESET) { /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) { if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_TIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_TIMEOUT; } } } /* Clear the Wakeup Timer clock source bits in CR register */ hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL; /* Configure the clock source */ hrtc->Instance->CR |= (uint32_t)WakeUpClock; /* Configure the Wakeup Timer counter */ hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; /* Enable the Wakeup Timer */ __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Sets wake up timer with interrupt * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param WakeUpCounter: Wake up counter * @param WakeUpClock: Wake up clock * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) { uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_RTC_WAKEUP_CLOCK(WakeUpClock)); assert_param(IS_RTC_WAKEUP_COUNTER(WakeUpCounter)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); /* Get tick */ tickstart = HAL_GetTick(); /*Check RTC WUTWF flag is reset only when wake up timer enabled*/ if((hrtc->Instance->CR & RTC_CR_WUTE) != RESET) { /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) { if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_TIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_TIMEOUT; } } } /* Configure the Wakeup Timer counter */ hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; /* Clear the Wakeup Timer clock source bits in CR register */ hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL; /* Configure the clock source */ hrtc->Instance->CR |= (uint32_t)WakeUpClock; /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */ __HAL_RTC_WAKEUPTIMER_EXTI_ENABLE_IT(); EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT; /* Clear RTC Wake Up timer Flag */ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); /* Configure the Interrupt in the RTC_CR register */ __HAL_RTC_WAKEUPTIMER_ENABLE_IT(hrtc,RTC_IT_WUT); /* Enable the Wakeup Timer */ __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Deactivates wake up timer counter. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) { uint32_t tickstart = 0; /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Disable the Wakeup Timer */ __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); /* In case of interrupt mode is used, the interrupt source must disabled */ __HAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc,RTC_IT_WUT); /* Get tick */ tickstart = HAL_GetTick(); /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) { if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_TIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_TIMEOUT; } } /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Gets wake up timer counter. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval Counter value */ uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc) { /* Get the counter value */ return ((uint32_t)(hrtc->Instance->WUTR & RTC_WUTR_WUT)); } /** * @brief This function handles Wake Up Timer interrupt request. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) { if(__HAL_RTC_WAKEUPTIMER_GET_IT(hrtc, RTC_IT_WUT)) { /* Get the status of the Interrupt */ if((uint32_t)(hrtc->Instance->CR & RTC_IT_WUT) != (uint32_t)RESET) { /* WAKEUPTIMER callback */ HAL_RTCEx_WakeUpTimerEventCallback(hrtc); /* Clear the WAKEUPTIMER interrupt pending bit */ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); } } /* Clear the EXTI's line Flag for RTC WakeUpTimer */ __HAL_RTC_WAKEUPTIMER_EXTI_CLEAR_FLAG(); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; } /** * @brief Wake Up Timer callback. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ __weak void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrtc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_RTC_WakeUpTimerEventCallback could be implemented in the user file */ } /** * @brief This function handles Wake Up Timer Polling. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) == RESET) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; } } } /* Clear the WAKEUPTIMER Flag */ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; return HAL_OK; } /** * @} */ /** @defgroup RTCEx_Group3 Extension Peripheral Control functions * @brief Extension Peripheral Control functions * @verbatim =============================================================================== ##### Extension Peripheral Control functions ##### =============================================================================== [..] This subsection provides functions allowing to (+) Write a data in a specified RTC Backup data register (+) Read a data in a specified RTC Backup data register (+) Set the Coarse calibration parameters. (+) Deactivate the Coarse calibration parameters (+) Set the Smooth calibration parameters. (+) Configure the Synchronization Shift Control Settings. (+) Configure the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). (+) Deactivate the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). (+) Enable the RTC reference clock detection. (+) Disable the RTC reference clock detection. (+) Enable the Bypass Shadow feature. (+) Disable the Bypass Shadow feature. @endverbatim * @{ */ /** * @brief Writes a data in a specified RTC Backup data register. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param BackupRegister: RTC Backup data Register number. * This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to * specify the register. * @param Data: Data to be written in the specified RTC Backup data register. * @retval None */ void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) { uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_RTC_BKP(BackupRegister)); tmp = (uint32_t)&(hrtc->Instance->BKP0R); tmp += (BackupRegister * 4); /* Write the specified register */ *(__IO uint32_t *)tmp = (uint32_t)Data; } /** * @brief Reads data from the specified RTC Backup data Register. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param BackupRegister: RTC Backup data Register number. * This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to * specify the register. * @retval Read value */ uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) { uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_RTC_BKP(BackupRegister)); tmp = (uint32_t)&(hrtc->Instance->BKP0R); tmp += (BackupRegister * 4); /* Read the specified register */ return (*(__IO uint32_t *)tmp); } /** * @brief Sets the Smooth calibration parameters. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param SmoothCalibPeriod: Select the Smooth Calibration Period. * This parameter can be can be one of the following values : * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration period is 32s. * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration period is 16s. * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibration period is 8s. * @param SmoothCalibPlusPulses: Select to Set or reset the CALP bit. * This parameter can be one of the following values: * @arg RTC_SMOOTHCALIB_PLUSPULSES_SET: Add one RTCCLK pulses every 2*11 pulses. * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added. * @param SmouthCalibMinusPulsesValue: Select the value of CALM[8:0] bits. * This parameter can be one any value from 0 to 0x000001FF. * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field * SmouthCalibMinusPulsesValue must be equal to 0. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef* hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue) { uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_RTC_SMOOTH_CALIB_PERIOD(SmoothCalibPeriod)); assert_param(IS_RTC_SMOOTH_CALIB_PLUS(SmoothCalibPlusPulses)); assert_param(IS_RTC_SMOOTH_CALIB_MINUS(SmouthCalibMinusPulsesValue)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* check if a calibration is pending*/ if((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET) { /* Get tick */ tickstart = HAL_GetTick(); /* check if a calibration is pending*/ while((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET) { if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_TIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_TIMEOUT; } } } /* Configure the Smooth calibration settings */ hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | (uint32_t)SmouthCalibMinusPulsesValue); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Configures the Synchronization Shift Control Settings. * @note When REFCKON is set, firmware must not write to Shift control register. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param ShiftAdd1S: Select to add or not 1 second to the time calendar. * This parameter can be one of the following values : * @arg RTC_SHIFTADD1S_SET: Add one second to the clock calendar. * @arg RTC_SHIFTADD1S_RESET: No effect. * @param ShiftSubFS: Select the number of Second Fractions to substitute. * This parameter can be one any value from 0 to 0x7FFF. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef* hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS) { uint32_t tickstart = 0; /* Check the parameters */ assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S)); assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Get tick */ tickstart = HAL_GetTick(); /* Wait until the shift is completed*/ while((hrtc->Instance->ISR & RTC_ISR_SHPF) != RESET) { if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_TIMEOUT; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_TIMEOUT; } } /* Check if the reference clock detection is disabled */ if((hrtc->Instance->CR & RTC_CR_REFCKON) == RESET) { /* Configure the Shift settings */ hrtc->Instance->SHIFTR = (uint32_t)(uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S); /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) { if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); hrtc->State = HAL_RTC_STATE_ERROR; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_ERROR; } } } else { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_ERROR; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_ERROR; } /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param CalibOutput: Select the Calibration output Selection . * This parameter can be one of the following values: * @arg RTC_CALIBOUTPUT_512HZ: A signal has a regular waveform at 512Hz. * @arg RTC_CALIBOUTPUT_1HZ: A signal has a regular waveform at 1Hz. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef* hrtc, uint32_t CalibOutput) { /* Check the parameters */ assert_param(IS_RTC_CALIB_OUTPUT(CalibOutput)); /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Clear flags before config */ hrtc->Instance->CR &= (uint32_t)~RTC_CR_COSEL; /* Configure the RTC_CR register */ hrtc->Instance->CR |= (uint32_t)CalibOutput; __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef* hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(hrtc); /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Enables the RTC reference clock detection. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef* hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Set Initialization mode */ if(RTC_EnterInitMode(hrtc) != HAL_OK) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Set RTC state*/ hrtc->State = HAL_RTC_STATE_ERROR; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_ERROR; } else { __HAL_RTC_CLOCKREF_DETECTION_ENABLE(hrtc); /* Exit Initialization mode */ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; } /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Disable the RTC reference clock detection. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef* hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Set Initialization mode */ if(RTC_EnterInitMode(hrtc) != HAL_OK) { /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Set RTC state*/ hrtc->State = HAL_RTC_STATE_ERROR; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_ERROR; } else { __HAL_RTC_CLOCKREF_DETECTION_DISABLE(hrtc); /* Exit Initialization mode */ hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; } /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Enables the Bypass Shadow feature. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @note When the Bypass Shadow is enabled the calendar value are taken * directly from the Calendar counter. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef* hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Set the BYPSHAD bit */ hrtc->Instance->CR |= (uint8_t)RTC_CR_BYPSHAD; /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @brief Disables the Bypass Shadow feature. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @note When the Bypass Shadow is enabled the calendar value are taken * directly from the Calendar counter. * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef* hrtc) { /* Process Locked */ __HAL_LOCK(hrtc); hrtc->State = HAL_RTC_STATE_BUSY; /* Disable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); /* Reset the BYPSHAD bit */ hrtc->Instance->CR &= (uint8_t)~RTC_CR_BYPSHAD; /* Enable the write protection for RTC registers */ __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hrtc); return HAL_OK; } /** * @} */ /** @defgroup RTCEx_Group4 Extended features functions * @brief Extended features functions * @verbatim =============================================================================== ##### Extended features functions ##### =============================================================================== [..] This section provides functions allowing to: (+) RTC Alram B callback (+) RTC Poll for Alarm B request @endverbatim * @{ */ /** * @brief Alarm B callback. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @retval None */ __weak void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hrtc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_RTC_AlarmBEventCallback could be implemented in the user file */ } /** * @brief This function handles AlarmB Polling request. * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains * the configuration information for RTC. * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBF) == RESET) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hrtc->State = HAL_RTC_STATE_TIMEOUT; return HAL_TIMEOUT; } } } /* Clear the Alarm Flag */ __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); /* Change RTC state */ hrtc->State = HAL_RTC_STATE_READY; return HAL_OK; } /** * @} */ /** * @} */ #endif /* HAL_RTC_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
gpl-3.0
modulexcite/robomongo
src/third-party/qjson/parserrunnable.cpp
59
1801
/* This file is part of qjson * * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "parserrunnable.h" #include "parser.h" #include <QtCore/QDebug> #include <QtCore/QVariant> using namespace QJson; class QJson::ParserRunnable::Private { public: QByteArray m_data; }; ParserRunnable::ParserRunnable(QObject* parent) : QObject(parent), QRunnable(), d(new Private) { qRegisterMetaType<QVariant>("QVariant"); } ParserRunnable::~ParserRunnable() { delete d; } void ParserRunnable::setData( const QByteArray& data ) { d->m_data = data; } void ParserRunnable::run() { qDebug() << Q_FUNC_INFO; bool ok; Parser parser; QVariant result = parser.parse (d->m_data, &ok); if (ok) { qDebug() << "successfully converted json item to QVariant object"; emit parsingFinished(result, true, QString()); } else { const QString errorText = tr("An error occurred while parsing json: %1").arg(parser.errorString()); qCritical() << errorText; emit parsingFinished(QVariant(), false, errorText); } }
gpl-3.0
BlastarIndia/Blastarix
qemu-1.7.0/hw/i2c/bitbang_i2c.c
59
6309
/* * Bit-Bang i2c emulation extracted from * Marvell MV88W8618 / Freecom MusicPal emulation. * * Copyright (c) 2008 Jan Kiszka * * This code is licensed under the GNU GPL v2. * * Contributions after 2012-01-13 are licensed under the terms of the * GNU GPL, version 2 or (at your option) any later version. */ #include "hw/hw.h" #include "bitbang_i2c.h" #include "hw/sysbus.h" //#define DEBUG_BITBANG_I2C #ifdef DEBUG_BITBANG_I2C #define DPRINTF(fmt, ...) \ do { printf("bitbang_i2c: " fmt , ## __VA_ARGS__); } while (0) #else #define DPRINTF(fmt, ...) do {} while(0) #endif typedef enum bitbang_i2c_state { STOPPED = 0, SENDING_BIT7, SENDING_BIT6, SENDING_BIT5, SENDING_BIT4, SENDING_BIT3, SENDING_BIT2, SENDING_BIT1, SENDING_BIT0, WAITING_FOR_ACK, RECEIVING_BIT7, RECEIVING_BIT6, RECEIVING_BIT5, RECEIVING_BIT4, RECEIVING_BIT3, RECEIVING_BIT2, RECEIVING_BIT1, RECEIVING_BIT0, SENDING_ACK, SENT_NACK } bitbang_i2c_state; struct bitbang_i2c_interface { i2c_bus *bus; bitbang_i2c_state state; int last_data; int last_clock; int device_out; uint8_t buffer; int current_addr; }; static void bitbang_i2c_enter_stop(bitbang_i2c_interface *i2c) { DPRINTF("STOP\n"); if (i2c->current_addr >= 0) i2c_end_transfer(i2c->bus); i2c->current_addr = -1; i2c->state = STOPPED; } /* Set device data pin. */ static int bitbang_i2c_ret(bitbang_i2c_interface *i2c, int level) { i2c->device_out = level; //DPRINTF("%d %d %d\n", i2c->last_clock, i2c->last_data, i2c->device_out); return level & i2c->last_data; } /* Leave device data pin unodified. */ static int bitbang_i2c_nop(bitbang_i2c_interface *i2c) { return bitbang_i2c_ret(i2c, i2c->device_out); } /* Returns data line level. */ int bitbang_i2c_set(bitbang_i2c_interface *i2c, int line, int level) { int data; if (level != 0 && level != 1) { abort(); } if (line == BITBANG_I2C_SDA) { if (level == i2c->last_data) { return bitbang_i2c_nop(i2c); } i2c->last_data = level; if (i2c->last_clock == 0) { return bitbang_i2c_nop(i2c); } if (level == 0) { DPRINTF("START\n"); /* START condition. */ i2c->state = SENDING_BIT7; i2c->current_addr = -1; } else { /* STOP condition. */ bitbang_i2c_enter_stop(i2c); } return bitbang_i2c_ret(i2c, 1); } data = i2c->last_data; if (i2c->last_clock == level) { return bitbang_i2c_nop(i2c); } i2c->last_clock = level; if (level == 0) { /* State is set/read at the start of the clock pulse. release the data line at the end. */ return bitbang_i2c_ret(i2c, 1); } switch (i2c->state) { case STOPPED: case SENT_NACK: return bitbang_i2c_ret(i2c, 1); case SENDING_BIT7 ... SENDING_BIT0: i2c->buffer = (i2c->buffer << 1) | data; /* will end up in WAITING_FOR_ACK */ i2c->state++; return bitbang_i2c_ret(i2c, 1); case WAITING_FOR_ACK: if (i2c->current_addr < 0) { i2c->current_addr = i2c->buffer; DPRINTF("Address 0x%02x\n", i2c->current_addr); i2c_start_transfer(i2c->bus, i2c->current_addr >> 1, i2c->current_addr & 1); } else { DPRINTF("Sent 0x%02x\n", i2c->buffer); i2c_send(i2c->bus, i2c->buffer); } if (i2c->current_addr & 1) { i2c->state = RECEIVING_BIT7; } else { i2c->state = SENDING_BIT7; } return bitbang_i2c_ret(i2c, 0); case RECEIVING_BIT7: i2c->buffer = i2c_recv(i2c->bus); DPRINTF("RX byte 0x%02x\n", i2c->buffer); /* Fall through... */ case RECEIVING_BIT6 ... RECEIVING_BIT0: data = i2c->buffer >> 7; /* will end up in SENDING_ACK */ i2c->state++; i2c->buffer <<= 1; return bitbang_i2c_ret(i2c, data); case SENDING_ACK: i2c->state = RECEIVING_BIT7; if (data != 0) { DPRINTF("NACKED\n"); i2c->state = SENT_NACK; i2c_nack(i2c->bus); } else { DPRINTF("ACKED\n"); } return bitbang_i2c_ret(i2c, 1); } abort(); } bitbang_i2c_interface *bitbang_i2c_init(i2c_bus *bus) { bitbang_i2c_interface *s; s = g_malloc0(sizeof(bitbang_i2c_interface)); s->bus = bus; s->last_data = 1; s->last_clock = 1; s->device_out = 1; return s; } /* GPIO interface. */ #define TYPE_GPIO_I2C "gpio_i2c" #define GPIO_I2C(obj) OBJECT_CHECK(GPIOI2CState, (obj), TYPE_GPIO_I2C) typedef struct GPIOI2CState { SysBusDevice parent_obj; MemoryRegion dummy_iomem; bitbang_i2c_interface *bitbang; int last_level; qemu_irq out; } GPIOI2CState; static void bitbang_i2c_gpio_set(void *opaque, int irq, int level) { GPIOI2CState *s = opaque; level = bitbang_i2c_set(s->bitbang, irq, level); if (level != s->last_level) { s->last_level = level; qemu_set_irq(s->out, level); } } static int gpio_i2c_init(SysBusDevice *sbd) { DeviceState *dev = DEVICE(sbd); GPIOI2CState *s = GPIO_I2C(dev); i2c_bus *bus; memory_region_init(&s->dummy_iomem, OBJECT(s), "gpio_i2c", 0); sysbus_init_mmio(sbd, &s->dummy_iomem); bus = i2c_init_bus(dev, "i2c"); s->bitbang = bitbang_i2c_init(bus); qdev_init_gpio_in(dev, bitbang_i2c_gpio_set, 2); qdev_init_gpio_out(dev, &s->out, 1); return 0; } static void gpio_i2c_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); k->init = gpio_i2c_init; set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories); dc->desc = "Virtual GPIO to I2C bridge"; } static const TypeInfo gpio_i2c_info = { .name = TYPE_GPIO_I2C, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(GPIOI2CState), .class_init = gpio_i2c_class_init, }; static void bitbang_i2c_register_types(void) { type_register_static(&gpio_i2c_info); } type_init(bitbang_i2c_register_types)
gpl-3.0
invisiblek/kernel_lge_v700
arch/alpha/kernel/sys_ruffian.c
9020
5930
/* * linux/arch/alpha/kernel/sys_ruffian.c * * Copyright (C) 1995 David A Rusling * Copyright (C) 1996 Jay A Estabrook * Copyright (C) 1998, 1999, 2000 Richard Henderson * * Code supporting the RUFFIAN. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/pci.h> #include <linux/ioport.h> #include <linux/timex.h> #include <linux/init.h> #include <asm/ptrace.h> #include <asm/dma.h> #include <asm/irq.h> #include <asm/mmu_context.h> #include <asm/io.h> #include <asm/pgtable.h> #include <asm/core_cia.h> #include <asm/tlbflush.h> #include "proto.h" #include "irq_impl.h" #include "pci_impl.h" #include "machvec_impl.h" static void __init ruffian_init_irq(void) { /* Invert 6&7 for i82371 */ *(vulp)PYXIS_INT_HILO = 0x000000c0UL; mb(); *(vulp)PYXIS_INT_CNFG = 0x00002064UL; mb(); /* all clear */ outb(0x11,0xA0); outb(0x08,0xA1); outb(0x02,0xA1); outb(0x01,0xA1); outb(0xFF,0xA1); outb(0x11,0x20); outb(0x00,0x21); outb(0x04,0x21); outb(0x01,0x21); outb(0xFF,0x21); /* Finish writing the 82C59A PIC Operation Control Words */ outb(0x20,0xA0); outb(0x20,0x20); init_i8259a_irqs(); /* Not interested in the bogus interrupts (0,3,6), NMI (1), HALT (2), flash (5), or 21142 (8). */ init_pyxis_irqs(0x16f0000); common_init_isa_dma(); } #define RUFFIAN_LATCH DIV_ROUND_CLOSEST(PIT_TICK_RATE, HZ) static void __init ruffian_init_rtc(void) { /* Ruffian does not have the RTC connected to the CPU timer interrupt. Instead, it uses the PIT connected to IRQ 0. */ /* Setup interval timer. */ outb(0x34, 0x43); /* binary, mode 2, LSB/MSB, ch 0 */ outb(RUFFIAN_LATCH & 0xff, 0x40); /* LSB */ outb(RUFFIAN_LATCH >> 8, 0x40); /* MSB */ outb(0xb6, 0x43); /* pit counter 2: speaker */ outb(0x31, 0x42); outb(0x13, 0x42); setup_irq(0, &timer_irqaction); } static void ruffian_kill_arch (int mode) { cia_kill_arch(mode); #if 0 /* This only causes re-entry to ARCSBIOS */ /* Perhaps this works for other PYXIS as well? */ *(vuip) PYXIS_RESET = 0x0000dead; mb(); #endif } /* * Interrupt routing: * * Primary bus * IdSel INTA INTB INTC INTD * 21052 13 - - - - * SIO 14 23 - - - * 21143 15 44 - - - * Slot 0 17 43 42 41 40 * * Secondary bus * IdSel INTA INTB INTC INTD * Slot 0 8 (18) 19 18 17 16 * Slot 1 9 (19) 31 30 29 28 * Slot 2 10 (20) 27 26 25 24 * Slot 3 11 (21) 39 38 37 36 * Slot 4 12 (22) 35 34 33 32 * 53c875 13 (23) 20 - - - * */ static int __init ruffian_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { static char irq_tab[11][5] __initdata = { /*INT INTA INTB INTC INTD */ {-1, -1, -1, -1, -1}, /* IdSel 13, 21052 */ {-1, -1, -1, -1, -1}, /* IdSel 14, SIO */ {44, 44, 44, 44, 44}, /* IdSel 15, 21143 */ {-1, -1, -1, -1, -1}, /* IdSel 16, none */ {43, 43, 42, 41, 40}, /* IdSel 17, 64-bit slot */ /* the next 6 are actually on PCI bus 1, across the bridge */ {19, 19, 18, 17, 16}, /* IdSel 8, slot 0 */ {31, 31, 30, 29, 28}, /* IdSel 9, slot 1 */ {27, 27, 26, 25, 24}, /* IdSel 10, slot 2 */ {39, 39, 38, 37, 36}, /* IdSel 11, slot 3 */ {35, 35, 34, 33, 32}, /* IdSel 12, slot 4 */ {20, 20, 20, 20, 20}, /* IdSel 13, 53c875 */ }; const long min_idsel = 13, max_idsel = 23, irqs_per_slot = 5; return COMMON_TABLE_LOOKUP; } static u8 __init ruffian_swizzle(struct pci_dev *dev, u8 *pinp) { int slot, pin = *pinp; if (dev->bus->number == 0) { slot = PCI_SLOT(dev->devfn); } /* Check for the built-in bridge. */ else if (PCI_SLOT(dev->bus->self->devfn) == 13) { slot = PCI_SLOT(dev->devfn) + 10; } else { /* Must be a card-based bridge. */ do { if (PCI_SLOT(dev->bus->self->devfn) == 13) { slot = PCI_SLOT(dev->devfn) + 10; break; } pin = pci_swizzle_interrupt_pin(dev, pin); /* Move up the chain of bridges. */ dev = dev->bus->self; /* Slot of the next bridge. */ slot = PCI_SLOT(dev->devfn); } while (dev->bus->self); } *pinp = pin; return slot; } #ifdef BUILDING_FOR_MILO /* * The DeskStation Ruffian motherboard firmware does not place * the memory size in the PALimpure area. Therefore, we use * the Bank Configuration Registers in PYXIS to obtain the size. */ static unsigned long __init ruffian_get_bank_size(unsigned long offset) { unsigned long bank_addr, bank, ret = 0; /* Valid offsets are: 0x800, 0x840 and 0x880 since Ruffian only uses three banks. */ bank_addr = (unsigned long)PYXIS_MCR + offset; bank = *(vulp)bank_addr; /* Check BANK_ENABLE */ if (bank & 0x01) { static unsigned long size[] __initdata = { 0x40000000UL, /* 0x00, 1G */ 0x20000000UL, /* 0x02, 512M */ 0x10000000UL, /* 0x04, 256M */ 0x08000000UL, /* 0x06, 128M */ 0x04000000UL, /* 0x08, 64M */ 0x02000000UL, /* 0x0a, 32M */ 0x01000000UL, /* 0x0c, 16M */ 0x00800000UL, /* 0x0e, 8M */ 0x80000000UL, /* 0x10, 2G */ }; bank = (bank & 0x1e) >> 1; if (bank < ARRAY_SIZE(size)) ret = size[bank]; } return ret; } #endif /* BUILDING_FOR_MILO */ /* * The System Vector */ struct alpha_machine_vector ruffian_mv __initmv = { .vector_name = "Ruffian", DO_EV5_MMU, DO_DEFAULT_RTC, DO_PYXIS_IO, .machine_check = cia_machine_check, .max_isa_dma_address = ALPHA_RUFFIAN_MAX_ISA_DMA_ADDRESS, .min_io_address = DEFAULT_IO_BASE, .min_mem_address = DEFAULT_MEM_BASE, .pci_dac_offset = PYXIS_DAC_OFFSET, .nr_irqs = 48, .device_interrupt = pyxis_device_interrupt, .init_arch = pyxis_init_arch, .init_irq = ruffian_init_irq, .init_rtc = ruffian_init_rtc, .init_pci = cia_init_pci, .kill_arch = ruffian_kill_arch, .pci_map_irq = ruffian_map_irq, .pci_swizzle = ruffian_swizzle, }; ALIAS_MV(ruffian)
gpl-3.0
Gazzonyx/samba
source4/heimdal/lib/krb5/appdefault.c
65
4514
/* * Copyright (c) 2000 - 2001 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "krb5_locl.h" KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_boolean(krb5_context context, const char *appname, krb5_const_realm realm, const char *option, krb5_boolean def_val, krb5_boolean *ret_val) { if(appname == NULL) appname = getprogname(); def_val = krb5_config_get_bool_default(context, NULL, def_val, "libdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_bool_default(context, NULL, def_val, "realms", realm, option, NULL); def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", realm, option, NULL); if(appname != NULL) { def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", appname, option, NULL); if(realm != NULL) def_val = krb5_config_get_bool_default(context, NULL, def_val, "appdefaults", appname, realm, option, NULL); } *ret_val = def_val; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_string(krb5_context context, const char *appname, krb5_const_realm realm, const char *option, const char *def_val, char **ret_val) { if(appname == NULL) appname = getprogname(); def_val = krb5_config_get_string_default(context, NULL, def_val, "libdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_string_default(context, NULL, def_val, "realms", realm, option, NULL); def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", option, NULL); if(realm != NULL) def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", realm, option, NULL); if(appname != NULL) { def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", appname, option, NULL); if(realm != NULL) def_val = krb5_config_get_string_default(context, NULL, def_val, "appdefaults", appname, realm, option, NULL); } if(def_val != NULL) *ret_val = strdup(def_val); else *ret_val = NULL; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_appdefault_time(krb5_context context, const char *appname, krb5_const_realm realm, const char *option, time_t def_val, time_t *ret_val) { krb5_deltat t; char *val; krb5_appdefault_string(context, appname, realm, option, NULL, &val); if (val == NULL) { *ret_val = def_val; return; } if (krb5_string_to_deltat(val, &t)) *ret_val = def_val; else *ret_val = t; free(val); }
gpl-3.0
Kovensky/mplayer-kovensky
loader/drv.c
65
4081
/* * Modified for use with MPlayer, detailed changelog at * http://svn.mplayerhq.hu/mplayer/trunk/ */ #include "config.h" #include "debug.h" #include <stdio.h> #include <stdlib.h> #ifdef __FreeBSD__ #include <sys/time.h> #endif #include "win32.h" #include "wine/driver.h" #include "wine/pe_image.h" #include "wine/winreg.h" #include "wine/vfw.h" #include "registry.h" #ifdef WIN32_LOADER #include "ldt_keeper.h" #endif #include "drv.h" #ifndef __MINGW32__ #include "ext.h" #endif #include "path.h" #if 1 /* * STORE_ALL/REST_ALL seems like an attempt to workaround problems due to * WINAPI/no-WINAPI bustage. * * There should be no need for the STORE_ALL/REST_ALL hack once all * function definitions agree with their prototypes (WINAPI-wise) and * we make sure, that we do not call these functions without a proper * prototype in scope. */ #define STORE_ALL #define REST_ALL #else // this asm code is no longer needed #define STORE_ALL \ __asm__ volatile ( \ "push %%ebx\n\t" \ "push %%ecx\n\t" \ "push %%edx\n\t" \ "push %%esi\n\t" \ "push %%edi\n\t"::) #define REST_ALL \ __asm__ volatile ( \ "pop %%edi\n\t" \ "pop %%esi\n\t" \ "pop %%edx\n\t" \ "pop %%ecx\n\t" \ "pop %%ebx\n\t"::) #endif static DWORD dwDrvID = 0; LRESULT WINAPI SendDriverMessage(HDRVR hDriver, UINT message, LPARAM lParam1, LPARAM lParam2) { DRVR* module=(DRVR*)hDriver; int result; #ifndef __svr4__ char qw[300]; #endif #ifdef DETAILED_OUT printf("SendDriverMessage: driver %X, message %X, arg1 %X, arg2 %X\n", hDriver, message, lParam1, lParam2); #endif if (!module || !module->hDriverModule || !module->DriverProc) return -1; #ifndef __svr4__ __asm__ volatile ("fsave (%0)\n\t": :"r"(&qw)); #endif #ifdef WIN32_LOADER Setup_FS_Segment(); #endif STORE_ALL; result=module->DriverProc(module->dwDriverID, hDriver, message, lParam1, lParam2); REST_ALL; #ifndef __svr4__ __asm__ volatile ("frstor (%0)\n\t": :"r"(&qw)); #endif #ifdef DETAILED_OUT printf("\t\tResult: %X\n", result); #endif return result; } void DrvClose(HDRVR hDriver) { if (hDriver) { DRVR* d = (DRVR*)hDriver; if (d->hDriverModule) { #ifdef WIN32_LOADER Setup_FS_Segment(); #endif if (d->DriverProc) { SendDriverMessage(hDriver, DRV_CLOSE, 0, 0); d->dwDriverID = 0; SendDriverMessage(hDriver, DRV_FREE, 0, 0); } FreeLibrary(d->hDriverModule); } free(d); } #ifdef WIN32_LOADER CodecRelease(); #endif } //DrvOpen(LPCSTR lpszDriverName, LPCSTR lpszSectionName, LPARAM lParam2) HDRVR DrvOpen(LPARAM lParam2) { NPDRVR hDriver; char unknown[0x124]; const char* filename = (const char*) ((ICOPEN*) lParam2)->pV1Reserved; #ifdef WIN32_LOADER Setup_LDT_Keeper(); #endif printf("Loading codec DLL: '%s'\n",filename); hDriver = malloc(sizeof(DRVR)); if (!hDriver) return (HDRVR) 0; memset((void*)hDriver, 0, sizeof(DRVR)); #ifdef WIN32_LOADER CodecAlloc(); Setup_FS_Segment(); #endif hDriver->hDriverModule = LoadLibraryA(filename); if (!hDriver->hDriverModule) { printf("Can't open library %s\n", filename); DrvClose((HDRVR)hDriver); return (HDRVR) 0; } hDriver->DriverProc = (DRIVERPROC) GetProcAddress(hDriver->hDriverModule, "DriverProc"); if (!hDriver->DriverProc) { printf("Library %s is not a valid VfW/ACM codec\n", filename); DrvClose((HDRVR)hDriver); return (HDRVR) 0; } TRACE("DriverProc == %X\n", hDriver->DriverProc); SendDriverMessage((HDRVR)hDriver, DRV_LOAD, 0, 0); TRACE("DRV_LOAD Ok!\n"); SendDriverMessage((HDRVR)hDriver, DRV_ENABLE, 0, 0); TRACE("DRV_ENABLE Ok!\n"); hDriver->dwDriverID = ++dwDrvID; // generate new id // open driver and remmeber proper DriverID hDriver->dwDriverID = SendDriverMessage((HDRVR)hDriver, DRV_OPEN, (LPARAM) unknown, lParam2); TRACE("DRV_OPEN Ok!(%X)\n", hDriver->dwDriverID); printf("Loaded DLL driver %s at %x\n", filename, hDriver->hDriverModule); return (HDRVR)hDriver; }
gpl-3.0