repo_name
string
path
string
copies
string
size
string
content
string
license
string
CyanogenMod/android_kernel_htc_flounder
arch/arm/mach-ux500/board-mop500-sdi.c
2045
6396
/* * Copyright (C) ST-Ericsson SA 2010 * * Author: Hanumath Prasad <hanumath.prasad@stericsson.com> * License terms: GNU General Public License (GPL) version 2 */ #include <linux/kernel.h> #include <linux/gpio.h> #include <linux/amba/bus.h> #include <linux/amba/mmci.h> #include <linux/mmc/host.h> #include <linux/platform_device.h> #include <linux/platform_data/dma-ste-dma40.h> #include <asm/mach-types.h> #include "devices.h" #include "db8500-regs.h" #include "devices-db8500.h" #include "board-mop500.h" #include "ste-dma40-db8500.h" /* * v2 has a new version of this block that need to be forced, the number found * in hardware is incorrect */ #define U8500_SDI_V2_PERIPHID 0x10480180 /* * SDI 0 (MicroSD slot) */ #ifdef CONFIG_STE_DMA40 struct stedma40_chan_cfg mop500_sdi0_dma_cfg_rx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_PERIPH_TO_MEM, .src_dev_type = DB8500_DMA_DEV29_SD_MM0_RX, .dst_dev_type = STEDMA40_DEV_DST_MEMORY, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; static struct stedma40_chan_cfg mop500_sdi0_dma_cfg_tx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_MEM_TO_PERIPH, .src_dev_type = STEDMA40_DEV_SRC_MEMORY, .dst_dev_type = DB8500_DMA_DEV29_SD_MM0_TX, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; #endif struct mmci_platform_data mop500_sdi0_data = { .ocr_mask = MMC_VDD_29_30, .f_max = 50000000, .capabilities = MMC_CAP_4_BIT_DATA | MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED, .gpio_wp = -1, .sigdir = MCI_ST_FBCLKEN | MCI_ST_CMDDIREN | MCI_ST_DATA0DIREN | MCI_ST_DATA2DIREN, #ifdef CONFIG_STE_DMA40 .dma_filter = stedma40_filter, .dma_rx_param = &mop500_sdi0_dma_cfg_rx, .dma_tx_param = &mop500_sdi0_dma_cfg_tx, #endif }; static void sdi0_configure(struct device *parent) { /* Add the device, force v2 to subrevision 1 */ db8500_add_sdi0(parent, &mop500_sdi0_data, U8500_SDI_V2_PERIPHID); } void mop500_sdi_tc35892_init(struct device *parent) { mop500_sdi0_data.gpio_cd = GPIO_SDMMC_CD; sdi0_configure(parent); } /* * SDI1 (SDIO WLAN) */ #ifdef CONFIG_STE_DMA40 static struct stedma40_chan_cfg sdi1_dma_cfg_rx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_PERIPH_TO_MEM, .src_dev_type = DB8500_DMA_DEV32_SD_MM1_RX, .dst_dev_type = STEDMA40_DEV_DST_MEMORY, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; static struct stedma40_chan_cfg sdi1_dma_cfg_tx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_MEM_TO_PERIPH, .src_dev_type = STEDMA40_DEV_SRC_MEMORY, .dst_dev_type = DB8500_DMA_DEV32_SD_MM1_TX, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; #endif struct mmci_platform_data mop500_sdi1_data = { .ocr_mask = MMC_VDD_29_30, .f_max = 50000000, .capabilities = MMC_CAP_4_BIT_DATA, .gpio_cd = -1, .gpio_wp = -1, #ifdef CONFIG_STE_DMA40 .dma_filter = stedma40_filter, .dma_rx_param = &sdi1_dma_cfg_rx, .dma_tx_param = &sdi1_dma_cfg_tx, #endif }; /* * SDI 2 (POP eMMC, not on DB8500ed) */ #ifdef CONFIG_STE_DMA40 struct stedma40_chan_cfg mop500_sdi2_dma_cfg_rx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_PERIPH_TO_MEM, .src_dev_type = DB8500_DMA_DEV28_SD_MM2_RX, .dst_dev_type = STEDMA40_DEV_DST_MEMORY, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; static struct stedma40_chan_cfg mop500_sdi2_dma_cfg_tx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_MEM_TO_PERIPH, .src_dev_type = STEDMA40_DEV_SRC_MEMORY, .dst_dev_type = DB8500_DMA_DEV28_SD_MM2_TX, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; #endif struct mmci_platform_data mop500_sdi2_data = { .ocr_mask = MMC_VDD_165_195, .f_max = 50000000, .capabilities = MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA | MMC_CAP_MMC_HIGHSPEED, .gpio_cd = -1, .gpio_wp = -1, #ifdef CONFIG_STE_DMA40 .dma_filter = stedma40_filter, .dma_rx_param = &mop500_sdi2_dma_cfg_rx, .dma_tx_param = &mop500_sdi2_dma_cfg_tx, #endif }; /* * SDI 4 (on-board eMMC) */ #ifdef CONFIG_STE_DMA40 struct stedma40_chan_cfg mop500_sdi4_dma_cfg_rx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_PERIPH_TO_MEM, .src_dev_type = DB8500_DMA_DEV42_SD_MM4_RX, .dst_dev_type = STEDMA40_DEV_DST_MEMORY, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; static struct stedma40_chan_cfg mop500_sdi4_dma_cfg_tx = { .mode = STEDMA40_MODE_LOGICAL, .dir = STEDMA40_MEM_TO_PERIPH, .src_dev_type = STEDMA40_DEV_SRC_MEMORY, .dst_dev_type = DB8500_DMA_DEV42_SD_MM4_TX, .src_info.data_width = STEDMA40_WORD_WIDTH, .dst_info.data_width = STEDMA40_WORD_WIDTH, }; #endif struct mmci_platform_data mop500_sdi4_data = { .ocr_mask = MMC_VDD_29_30, .f_max = 50000000, .capabilities = MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA | MMC_CAP_MMC_HIGHSPEED, .gpio_cd = -1, .gpio_wp = -1, #ifdef CONFIG_STE_DMA40 .dma_filter = stedma40_filter, .dma_rx_param = &mop500_sdi4_dma_cfg_rx, .dma_tx_param = &mop500_sdi4_dma_cfg_tx, #endif }; void __init mop500_sdi_init(struct device *parent) { /* PoP:ed eMMC */ db8500_add_sdi2(parent, &mop500_sdi2_data, U8500_SDI_V2_PERIPHID); /* On-board eMMC */ db8500_add_sdi4(parent, &mop500_sdi4_data, U8500_SDI_V2_PERIPHID); /* * On boards with the TC35892 GPIO expander, sdi0 will finally * be added when the TC35892 initializes and calls * mop500_sdi_tc35892_init() above. */ } void __init snowball_sdi_init(struct device *parent) { /* On Snowball MMC_CAP_SD_HIGHSPEED isn't supported (Hardware issue?) */ mop500_sdi0_data.capabilities &= ~MMC_CAP_SD_HIGHSPEED; /* On-board eMMC */ db8500_add_sdi4(parent, &mop500_sdi4_data, U8500_SDI_V2_PERIPHID); /* External Micro SD slot */ mop500_sdi0_data.gpio_cd = SNOWBALL_SDMMC_CD_GPIO; mop500_sdi0_data.cd_invert = true; sdi0_configure(parent); } void __init hrefv60_sdi_init(struct device *parent) { /* PoP:ed eMMC */ db8500_add_sdi2(parent, &mop500_sdi2_data, U8500_SDI_V2_PERIPHID); /* On-board eMMC */ db8500_add_sdi4(parent, &mop500_sdi4_data, U8500_SDI_V2_PERIPHID); /* External Micro SD slot */ mop500_sdi0_data.gpio_cd = HREFV60_SDMMC_CD_GPIO; sdi0_configure(parent); /* WLAN SDIO channel */ db8500_add_sdi1(parent, &mop500_sdi1_data, U8500_SDI_V2_PERIPHID); }
gpl-2.0
noba3/KoTos
lib/libUPnP/Neptune/ThirdParty/zlib-1.2.3/infback.c
2301
22164
/* infback.c -- inflate using a call-back interface * Copyright (C) 1995-2005 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* This code is largely copied from inflate.c. Normally either infback.o or inflate.o would be linked into an application--not both. The interface with inffast.c is retained so that optimized assembler-coded versions of inflate_fast() can be used with either inflate.c or infback.c. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); /* strm provides memory allocation functions in zalloc and zfree, or Z_NULL to use the library memory allocation functions. windowBits is in the range 8..15, and window is a user-supplied window and output buffer that is 2**windowBits bytes. */ int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) z_streamp strm; int windowBits; unsigned char FAR *window; const char *version; int stream_size; { struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL || window == Z_NULL || windowBits < 8 || windowBits > 15) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; state = (struct inflate_state FAR *)ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->dmax = 32768U; state->wbits = windowBits; state->wsize = 1U << windowBits; state->window = window; state->write = 0; state->whave = 0; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } /* Macros for inflateBack(): */ /* Load returned state from inflate_fast() */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Set state from registers for inflate_fast() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Assure that some input is available. If input is requested, but denied, then return a Z_BUF_ERROR from inflateBack(). */ #define PULL() \ do { \ if (have == 0) { \ have = in(in_desc, &next); \ if (have == 0) { \ next = Z_NULL; \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflateBack() with an error if there is no input available. */ #define PULLBYTE() \ do { \ PULL(); \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflateBack() with an error. */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Assure that some output space is available, by writing out the window if it's full. If the write fails, return from inflateBack() with a Z_BUF_ERROR. */ #define ROOM() \ do { \ if (left == 0) { \ put = state->window; \ left = state->wsize; \ state->whave = left; \ if (out(out_desc, put, left)) { \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* strm provides the memory allocation functions and window buffer on input, and provides information on the unused input on return. For Z_DATA_ERROR returns, strm will also provide an error message. in() and out() are the call-back input and output functions. When inflateBack() needs more input, it calls in(). When inflateBack() has filled the window with output, or when it completes with data in the window, it calls out() to write out the data. The application must not change the provided input until in() is called again or inflateBack() returns. The application must not change the window/output buffer until inflateBack() returns. in() and out() are called with a descriptor parameter provided in the inflateBack() call. This parameter can be a structure that provides the information required to do the read or write, as well as accumulated information on the input and output such as totals and check values. in() should return zero on failure. out() should return non-zero on failure. If either in() or out() fails, than inflateBack() returns a Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it was in() or out() that caused in the error. Otherwise, inflateBack() returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format error, or Z_MEM_ERROR if it could not allocate memory for the state. inflateBack() can also return Z_STREAM_ERROR if the input parameters are not correct, i.e. strm is Z_NULL or the state was not initialized. */ int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) z_streamp strm; in_func in; void FAR *in_desc; out_func out; void FAR *out_desc; { struct inflate_state FAR *state; unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code this; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* Check that the strm exists and that the state was initialized */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* Reset the state */ strm->msg = Z_NULL; state->mode = TYPE; state->last = 0; state->whave = 0; next = strm->next_in; have = next != Z_NULL ? strm->avail_in : 0; hold = 0; bits = 0; put = state->window; left = state->wsize; /* Inflate until end of block marked as last */ for (;;) switch (state->mode) { case TYPE: /* determine and dispatch block type */ if (state->last) { BYTEBITS(); state->mode = DONE; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN; /* decode codes */ break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: /* get and verify stored block length */ BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); /* copy stored block from input to output */ while (state->length != 0) { copy = state->length; PULL(); ROOM(); if (copy > have) copy = have; if (copy > left) copy = left; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: /* get dynamic table entries descriptor */ NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); /* get code length code lengths (not a typo) */ state->have = 0; while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); /* get length and distance code code lengths */ state->have = 0; while (state->have < state->nlen + state->ndist) { for (;;) { this = state->lencode[BITS(state->lenbits)]; if ((unsigned)(this.bits) <= bits) break; PULLBYTE(); } if (this.val < 16) { NEEDBITS(this.bits); DROPBITS(this.bits); state->lens[state->have++] = this.val; } else { if (this.val == 16) { NEEDBITS(this.bits + 2); DROPBITS(this.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = (unsigned)(state->lens[state->have - 1]); copy = 3 + BITS(2); DROPBITS(2); } else if (this.val == 17) { NEEDBITS(this.bits + 3); DROPBITS(this.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(this.bits + 7); DROPBITS(this.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* build code tables */ state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (code const FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN; case LEN: /* use inflate_fast() if we have enough input and output */ if (have >= 6 && left >= 258) { RESTORE(); if (state->whave < state->wsize) state->whave = state->wsize - left; inflate_fast(strm, state->wsize); LOAD(); break; } /* get a literal, length, or end-of-block code */ for (;;) { this = state->lencode[BITS(state->lenbits)]; if ((unsigned)(this.bits) <= bits) break; PULLBYTE(); } if (this.op && (this.op & 0xf0) == 0) { last = this; for (;;) { this = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + this.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(this.bits); state->length = (unsigned)this.val; /* process literal */ if (this.op == 0) { Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", this.val)); ROOM(); *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; } /* process end of block */ if (this.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } /* invalid code */ if (this.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } /* length code -- get extra bits, if any */ state->extra = (unsigned)(this.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); } Tracevv((stderr, "inflate: length %u\n", state->length)); /* get distance code */ for (;;) { this = state->distcode[BITS(state->distbits)]; if ((unsigned)(this.bits) <= bits) break; PULLBYTE(); } if ((this.op & 0xf0) == 0) { last = this; for (;;) { this = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + this.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(this.bits); if (this.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)this.val; /* get distance extra bits, if any */ state->extra = (unsigned)(this.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); } if (state->offset > state->wsize - (state->whave < state->wsize ? left : 0)) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } Tracevv((stderr, "inflate: distance %u\n", state->offset)); /* copy match from window to output */ do { ROOM(); copy = state->wsize - state->offset; if (copy < left) { from = put + copy; copy = left - copy; } else { from = put - state->offset; copy = left; } if (copy > state->length) copy = state->length; state->length -= copy; left -= copy; do { *put++ = *from++; } while (--copy); } while (state->length != 0); break; case DONE: /* inflate stream terminated properly -- write leftover output */ ret = Z_STREAM_END; if (left < state->wsize) { if (out(out_desc, state->window, state->wsize - left)) ret = Z_BUF_ERROR; } goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; default: /* can't happen, but makes compilers happy */ ret = Z_STREAM_ERROR; goto inf_leave; } /* Return unused input */ inf_leave: strm->next_in = next; strm->avail_in = have; return ret; } int ZEXPORT inflateBackEnd(strm) z_streamp strm; { if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) return Z_STREAM_ERROR; ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; }
gpl-2.0
mathkid95/linux_samsung_jb
fs/afs/write.c
2301
18323
/* handling of writes to regular files and writing back to the server * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@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 * 2 of the License, or (at your option) any later version. */ #include <linux/backing-dev.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <linux/writeback.h> #include <linux/pagevec.h> #include "internal.h" static int afs_write_back_from_locked_page(struct afs_writeback *wb, struct page *page); /* * mark a page as having been made dirty and thus needing writeback */ int afs_set_page_dirty(struct page *page) { _enter(""); return __set_page_dirty_nobuffers(page); } /* * unlink a writeback record because its usage has reached zero * - must be called with the wb->vnode->writeback_lock held */ static void afs_unlink_writeback(struct afs_writeback *wb) { struct afs_writeback *front; struct afs_vnode *vnode = wb->vnode; list_del_init(&wb->link); if (!list_empty(&vnode->writebacks)) { /* if an fsync rises to the front of the queue then wake it * up */ front = list_entry(vnode->writebacks.next, struct afs_writeback, link); if (front->state == AFS_WBACK_SYNCING) { _debug("wake up sync"); front->state = AFS_WBACK_COMPLETE; wake_up(&front->waitq); } } } /* * free a writeback record */ static void afs_free_writeback(struct afs_writeback *wb) { _enter(""); key_put(wb->key); kfree(wb); } /* * dispose of a reference to a writeback record */ void afs_put_writeback(struct afs_writeback *wb) { struct afs_vnode *vnode = wb->vnode; _enter("{%d}", wb->usage); spin_lock(&vnode->writeback_lock); if (--wb->usage == 0) afs_unlink_writeback(wb); else wb = NULL; spin_unlock(&vnode->writeback_lock); if (wb) afs_free_writeback(wb); } /* * partly or wholly fill a page that's under preparation for writing */ static int afs_fill_page(struct afs_vnode *vnode, struct key *key, loff_t pos, struct page *page) { loff_t i_size; int ret; int len; _enter(",,%llu", (unsigned long long)pos); i_size = i_size_read(&vnode->vfs_inode); if (pos + PAGE_CACHE_SIZE > i_size) len = i_size - pos; else len = PAGE_CACHE_SIZE; ret = afs_vnode_fetch_data(vnode, key, pos, len, page); if (ret < 0) { if (ret == -ENOENT) { _debug("got NOENT from server" " - marking file deleted and stale"); set_bit(AFS_VNODE_DELETED, &vnode->flags); ret = -ESTALE; } } _leave(" = %d", ret); return ret; } /* * prepare to perform part of a write to a page */ int afs_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct afs_writeback *candidate, *wb; struct afs_vnode *vnode = AFS_FS_I(file->f_dentry->d_inode); struct page *page; struct key *key = file->private_data; unsigned from = pos & (PAGE_CACHE_SIZE - 1); unsigned to = from + len; pgoff_t index = pos >> PAGE_CACHE_SHIFT; int ret; _enter("{%x:%u},{%lx},%u,%u", vnode->fid.vid, vnode->fid.vnode, index, from, to); candidate = kzalloc(sizeof(*candidate), GFP_KERNEL); if (!candidate) return -ENOMEM; candidate->vnode = vnode; candidate->first = candidate->last = index; candidate->offset_first = from; candidate->to_last = to; INIT_LIST_HEAD(&candidate->link); candidate->usage = 1; candidate->state = AFS_WBACK_PENDING; init_waitqueue_head(&candidate->waitq); page = grab_cache_page_write_begin(mapping, index, flags); if (!page) { kfree(candidate); return -ENOMEM; } *pagep = page; /* page won't leak in error case: it eventually gets cleaned off LRU */ if (!PageUptodate(page) && len != PAGE_CACHE_SIZE) { ret = afs_fill_page(vnode, key, index << PAGE_CACHE_SHIFT, page); if (ret < 0) { kfree(candidate); _leave(" = %d [prep]", ret); return ret; } SetPageUptodate(page); } try_again: spin_lock(&vnode->writeback_lock); /* see if this page is already pending a writeback under a suitable key * - if so we can just join onto that one */ wb = (struct afs_writeback *) page_private(page); if (wb) { if (wb->key == key && wb->state == AFS_WBACK_PENDING) goto subsume_in_current_wb; goto flush_conflicting_wb; } if (index > 0) { /* see if we can find an already pending writeback that we can * append this page to */ list_for_each_entry(wb, &vnode->writebacks, link) { if (wb->last == index - 1 && wb->key == key && wb->state == AFS_WBACK_PENDING) goto append_to_previous_wb; } } list_add_tail(&candidate->link, &vnode->writebacks); candidate->key = key_get(key); spin_unlock(&vnode->writeback_lock); SetPagePrivate(page); set_page_private(page, (unsigned long) candidate); _leave(" = 0 [new]"); return 0; subsume_in_current_wb: _debug("subsume"); ASSERTRANGE(wb->first, <=, index, <=, wb->last); if (index == wb->first && from < wb->offset_first) wb->offset_first = from; if (index == wb->last && to > wb->to_last) wb->to_last = to; spin_unlock(&vnode->writeback_lock); kfree(candidate); _leave(" = 0 [sub]"); return 0; append_to_previous_wb: _debug("append into %lx-%lx", wb->first, wb->last); wb->usage++; wb->last++; wb->to_last = to; spin_unlock(&vnode->writeback_lock); SetPagePrivate(page); set_page_private(page, (unsigned long) wb); kfree(candidate); _leave(" = 0 [app]"); return 0; /* the page is currently bound to another context, so if it's dirty we * need to flush it before we can use the new context */ flush_conflicting_wb: _debug("flush conflict"); if (wb->state == AFS_WBACK_PENDING) wb->state = AFS_WBACK_CONFLICTING; spin_unlock(&vnode->writeback_lock); if (PageDirty(page)) { ret = afs_write_back_from_locked_page(wb, page); if (ret < 0) { afs_put_writeback(candidate); _leave(" = %d", ret); return ret; } } /* the page holds a ref on the writeback record */ afs_put_writeback(wb); set_page_private(page, 0); ClearPagePrivate(page); goto try_again; } /* * finalise part of a write to a page */ int afs_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { struct afs_vnode *vnode = AFS_FS_I(file->f_dentry->d_inode); loff_t i_size, maybe_i_size; _enter("{%x:%u},{%lx}", vnode->fid.vid, vnode->fid.vnode, page->index); maybe_i_size = pos + copied; i_size = i_size_read(&vnode->vfs_inode); if (maybe_i_size > i_size) { spin_lock(&vnode->writeback_lock); i_size = i_size_read(&vnode->vfs_inode); if (maybe_i_size > i_size) i_size_write(&vnode->vfs_inode, maybe_i_size); spin_unlock(&vnode->writeback_lock); } set_page_dirty(page); if (PageDirty(page)) _debug("dirtied"); unlock_page(page); page_cache_release(page); return copied; } /* * kill all the pages in the given range */ static void afs_kill_pages(struct afs_vnode *vnode, bool error, pgoff_t first, pgoff_t last) { struct pagevec pv; unsigned count, loop; _enter("{%x:%u},%lx-%lx", vnode->fid.vid, vnode->fid.vnode, first, last); pagevec_init(&pv, 0); do { _debug("kill %lx-%lx", first, last); count = last - first + 1; if (count > PAGEVEC_SIZE) count = PAGEVEC_SIZE; pv.nr = find_get_pages_contig(vnode->vfs_inode.i_mapping, first, count, pv.pages); ASSERTCMP(pv.nr, ==, count); for (loop = 0; loop < count; loop++) { ClearPageUptodate(pv.pages[loop]); if (error) SetPageError(pv.pages[loop]); end_page_writeback(pv.pages[loop]); } __pagevec_release(&pv); } while (first < last); _leave(""); } /* * synchronously write back the locked page and any subsequent non-locked dirty * pages also covered by the same writeback record */ static int afs_write_back_from_locked_page(struct afs_writeback *wb, struct page *primary_page) { struct page *pages[8], *page; unsigned long count; unsigned n, offset, to; pgoff_t start, first, last; int loop, ret; _enter(",%lx", primary_page->index); count = 1; if (!clear_page_dirty_for_io(primary_page)) BUG(); if (test_set_page_writeback(primary_page)) BUG(); /* find all consecutive lockable dirty pages, stopping when we find a * page that is not immediately lockable, is not dirty or is missing, * or we reach the end of the range */ start = primary_page->index; if (start >= wb->last) goto no_more; start++; do { _debug("more %lx [%lx]", start, count); n = wb->last - start + 1; if (n > ARRAY_SIZE(pages)) n = ARRAY_SIZE(pages); n = find_get_pages_contig(wb->vnode->vfs_inode.i_mapping, start, n, pages); _debug("fgpc %u", n); if (n == 0) goto no_more; if (pages[0]->index != start) { do { put_page(pages[--n]); } while (n > 0); goto no_more; } for (loop = 0; loop < n; loop++) { page = pages[loop]; if (page->index > wb->last) break; if (!trylock_page(page)) break; if (!PageDirty(page) || page_private(page) != (unsigned long) wb) { unlock_page(page); break; } if (!clear_page_dirty_for_io(page)) BUG(); if (test_set_page_writeback(page)) BUG(); unlock_page(page); put_page(page); } count += loop; if (loop < n) { for (; loop < n; loop++) put_page(pages[loop]); goto no_more; } start += loop; } while (start <= wb->last && count < 65536); no_more: /* we now have a contiguous set of dirty pages, each with writeback set * and the dirty mark cleared; the first page is locked and must remain * so, all the rest are unlocked */ first = primary_page->index; last = first + count - 1; offset = (first == wb->first) ? wb->offset_first : 0; to = (last == wb->last) ? wb->to_last : PAGE_SIZE; _debug("write back %lx[%u..] to %lx[..%u]", first, offset, last, to); ret = afs_vnode_store_data(wb, first, last, offset, to); if (ret < 0) { switch (ret) { case -EDQUOT: case -ENOSPC: set_bit(AS_ENOSPC, &wb->vnode->vfs_inode.i_mapping->flags); break; case -EROFS: case -EIO: case -EREMOTEIO: case -EFBIG: case -ENOENT: case -ENOMEDIUM: case -ENXIO: afs_kill_pages(wb->vnode, true, first, last); set_bit(AS_EIO, &wb->vnode->vfs_inode.i_mapping->flags); break; case -EACCES: case -EPERM: case -ENOKEY: case -EKEYEXPIRED: case -EKEYREJECTED: case -EKEYREVOKED: afs_kill_pages(wb->vnode, false, first, last); break; default: break; } } else { ret = count; } _leave(" = %d", ret); return ret; } /* * write a page back to the server * - the caller locked the page for us */ int afs_writepage(struct page *page, struct writeback_control *wbc) { struct afs_writeback *wb; int ret; _enter("{%lx},", page->index); wb = (struct afs_writeback *) page_private(page); ASSERT(wb != NULL); ret = afs_write_back_from_locked_page(wb, page); unlock_page(page); if (ret < 0) { _leave(" = %d", ret); return 0; } wbc->nr_to_write -= ret; _leave(" = 0"); return 0; } /* * write a region of pages back to the server */ static int afs_writepages_region(struct address_space *mapping, struct writeback_control *wbc, pgoff_t index, pgoff_t end, pgoff_t *_next) { struct afs_writeback *wb; struct page *page; int ret, n; _enter(",,%lx,%lx,", index, end); do { n = find_get_pages_tag(mapping, &index, PAGECACHE_TAG_DIRTY, 1, &page); if (!n) break; _debug("wback %lx", page->index); if (page->index > end) { *_next = index; page_cache_release(page); _leave(" = 0 [%lx]", *_next); return 0; } /* at this point we hold neither mapping->tree_lock nor lock on * the page itself: the page may be truncated or invalidated * (changing page->mapping to NULL), or even swizzled back from * swapper_space to tmpfs file mapping */ lock_page(page); if (page->mapping != mapping) { unlock_page(page); page_cache_release(page); continue; } if (wbc->sync_mode != WB_SYNC_NONE) wait_on_page_writeback(page); if (PageWriteback(page) || !PageDirty(page)) { unlock_page(page); continue; } wb = (struct afs_writeback *) page_private(page); ASSERT(wb != NULL); spin_lock(&wb->vnode->writeback_lock); wb->state = AFS_WBACK_WRITING; spin_unlock(&wb->vnode->writeback_lock); ret = afs_write_back_from_locked_page(wb, page); unlock_page(page); page_cache_release(page); if (ret < 0) { _leave(" = %d", ret); return ret; } wbc->nr_to_write -= ret; cond_resched(); } while (index < end && wbc->nr_to_write > 0); *_next = index; _leave(" = 0 [%lx]", *_next); return 0; } /* * write some of the pending data back to the server */ int afs_writepages(struct address_space *mapping, struct writeback_control *wbc) { pgoff_t start, end, next; int ret; _enter(""); if (wbc->range_cyclic) { start = mapping->writeback_index; end = -1; ret = afs_writepages_region(mapping, wbc, start, end, &next); if (start > 0 && wbc->nr_to_write > 0 && ret == 0) ret = afs_writepages_region(mapping, wbc, 0, start, &next); mapping->writeback_index = next; } else if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) { end = (pgoff_t)(LLONG_MAX >> PAGE_CACHE_SHIFT); ret = afs_writepages_region(mapping, wbc, 0, end, &next); if (wbc->nr_to_write > 0) mapping->writeback_index = next; } else { start = wbc->range_start >> PAGE_CACHE_SHIFT; end = wbc->range_end >> PAGE_CACHE_SHIFT; ret = afs_writepages_region(mapping, wbc, start, end, &next); } _leave(" = %d", ret); return ret; } /* * completion of write to server */ void afs_pages_written_back(struct afs_vnode *vnode, struct afs_call *call) { struct afs_writeback *wb = call->wb; struct pagevec pv; unsigned count, loop; pgoff_t first = call->first, last = call->last; bool free_wb; _enter("{%x:%u},{%lx-%lx}", vnode->fid.vid, vnode->fid.vnode, first, last); ASSERT(wb != NULL); pagevec_init(&pv, 0); do { _debug("done %lx-%lx", first, last); count = last - first + 1; if (count > PAGEVEC_SIZE) count = PAGEVEC_SIZE; pv.nr = find_get_pages_contig(call->mapping, first, count, pv.pages); ASSERTCMP(pv.nr, ==, count); spin_lock(&vnode->writeback_lock); for (loop = 0; loop < count; loop++) { struct page *page = pv.pages[loop]; end_page_writeback(page); if (page_private(page) == (unsigned long) wb) { set_page_private(page, 0); ClearPagePrivate(page); wb->usage--; } } free_wb = false; if (wb->usage == 0) { afs_unlink_writeback(wb); free_wb = true; } spin_unlock(&vnode->writeback_lock); first += count; if (free_wb) { afs_free_writeback(wb); wb = NULL; } __pagevec_release(&pv); } while (first <= last); _leave(""); } /* * write to an AFS file */ ssize_t afs_file_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct dentry *dentry = iocb->ki_filp->f_path.dentry; struct afs_vnode *vnode = AFS_FS_I(dentry->d_inode); ssize_t result; size_t count = iov_length(iov, nr_segs); _enter("{%x.%u},{%zu},%lu,", vnode->fid.vid, vnode->fid.vnode, count, nr_segs); if (IS_SWAPFILE(&vnode->vfs_inode)) { printk(KERN_INFO "AFS: Attempt to write to active swap file!\n"); return -EBUSY; } if (!count) return 0; result = generic_file_aio_write(iocb, iov, nr_segs, pos); if (IS_ERR_VALUE(result)) { _leave(" = %zd", result); return result; } _leave(" = %zd", result); return result; } /* * flush the vnode to the fileserver */ int afs_writeback_all(struct afs_vnode *vnode) { struct address_space *mapping = vnode->vfs_inode.i_mapping; struct writeback_control wbc = { .sync_mode = WB_SYNC_ALL, .nr_to_write = LONG_MAX, .range_cyclic = 1, }; int ret; _enter(""); ret = mapping->a_ops->writepages(mapping, &wbc); __mark_inode_dirty(mapping->host, I_DIRTY_PAGES); _leave(" = %d", ret); return ret; } /* * flush any dirty pages for this process, and check for write errors. * - the return status from this call provides a reliable indication of * whether any write errors occurred for this process. */ int afs_fsync(struct file *file, int datasync) { struct dentry *dentry = file->f_path.dentry; struct afs_writeback *wb, *xwb; struct afs_vnode *vnode = AFS_FS_I(dentry->d_inode); int ret; _enter("{%x:%u},{n=%s},%d", vnode->fid.vid, vnode->fid.vnode, dentry->d_name.name, datasync); /* use a writeback record as a marker in the queue - when this reaches * the front of the queue, all the outstanding writes are either * completed or rejected */ wb = kzalloc(sizeof(*wb), GFP_KERNEL); if (!wb) return -ENOMEM; wb->vnode = vnode; wb->first = 0; wb->last = -1; wb->offset_first = 0; wb->to_last = PAGE_SIZE; wb->usage = 1; wb->state = AFS_WBACK_SYNCING; init_waitqueue_head(&wb->waitq); spin_lock(&vnode->writeback_lock); list_for_each_entry(xwb, &vnode->writebacks, link) { if (xwb->state == AFS_WBACK_PENDING) xwb->state = AFS_WBACK_CONFLICTING; } list_add_tail(&wb->link, &vnode->writebacks); spin_unlock(&vnode->writeback_lock); /* push all the outstanding writebacks to the server */ ret = afs_writeback_all(vnode); if (ret < 0) { afs_put_writeback(wb); _leave(" = %d [wb]", ret); return ret; } /* wait for the preceding writes to actually complete */ ret = wait_event_interruptible(wb->waitq, wb->state == AFS_WBACK_COMPLETE || vnode->writebacks.next == &wb->link); afs_put_writeback(wb); _leave(" = %d", ret); return ret; } /* * notification that a previously read-only page is about to become writable * - if it returns an error, the caller will deliver a bus error signal */ int afs_page_mkwrite(struct vm_area_struct *vma, struct page *page) { struct afs_vnode *vnode = AFS_FS_I(vma->vm_file->f_mapping->host); _enter("{{%x:%u}},{%lx}", vnode->fid.vid, vnode->fid.vnode, page->index); /* wait for the page to be written to the cache before we allow it to * be modified */ #ifdef CONFIG_AFS_FSCACHE fscache_wait_on_page_write(vnode->cache, page); #endif _leave(" = 0"); return 0; }
gpl-2.0
newkid313/android_kernel_samsung_l300
arch/m68k/apollo/dn_ints.c
4605
1049
#include <linux/interrupt.h> #include <asm/irq.h> #include <asm/traps.h> #include <asm/apollohw.h> void dn_process_int(unsigned int irq, struct pt_regs *fp) { __m68k_handle_int(irq, fp); *(volatile unsigned char *)(pica)=0x20; *(volatile unsigned char *)(picb)=0x20; } int apollo_irq_startup(unsigned int irq) { if (irq < 8) *(volatile unsigned char *)(pica+1) &= ~(1 << irq); else *(volatile unsigned char *)(picb+1) &= ~(1 << (irq - 8)); return 0; } void apollo_irq_shutdown(unsigned int irq) { if (irq < 8) *(volatile unsigned char *)(pica+1) |= (1 << irq); else *(volatile unsigned char *)(picb+1) |= (1 << (irq - 8)); } static struct irq_controller apollo_irq_controller = { .name = "apollo", .lock = __SPIN_LOCK_UNLOCKED(apollo_irq_controller.lock), .startup = apollo_irq_startup, .shutdown = apollo_irq_shutdown, }; void __init dn_init_IRQ(void) { m68k_setup_user_interrupt(VEC_USER + 96, 16, dn_process_int); m68k_setup_irq_controller(&apollo_irq_controller, IRQ_APOLLO, 16); }
gpl-2.0
maxwen/primou-kernel-KISS
drivers/watchdog/w83697hf_wdt.c
4861
10188
/* * w83697hf/hg WDT driver * * (c) Copyright 2006 Samuel Tardieu <sam@rfc1149.net> * (c) Copyright 2006 Marcus Junker <junker@anduras.de> * * Based on w83627hf_wdt.c which is based on advantechwdt.c * which is based on wdt.c. * Original copyright messages: * * (c) Copyright 2003 Pádraig Brady <P@draigBrady.com> * * (c) Copyright 2000-2001 Marek Michalkiewicz <marekm@linux.org.pl> * * (c) Copyright 1996 Alan Cox <alan@lxorguk.ukuu.org.uk>, * 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; either version * 2 of the License, or (at your option) any later version. * * Neither Marcus Junker nor ANDURAS AG admit liability nor provide * warranty for any of this software. This material is provided * "AS-IS" and at no charge. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/miscdevice.h> #include <linux/watchdog.h> #include <linux/fs.h> #include <linux/ioport.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/io.h> #include <linux/uaccess.h> #include <asm/system.h> #define WATCHDOG_NAME "w83697hf/hg WDT" #define PFX WATCHDOG_NAME ": " #define WATCHDOG_TIMEOUT 60 /* 60 sec default timeout */ #define WATCHDOG_EARLY_DISABLE 1 /* Disable until userland kicks in */ static unsigned long wdt_is_open; static char expect_close; static DEFINE_SPINLOCK(io_lock); /* You must set this - there is no sane way to probe for this board. */ static int wdt_io = 0x2e; module_param(wdt_io, int, 0); MODULE_PARM_DESC(wdt_io, "w83697hf/hg WDT io port (default 0x2e, 0 = autodetect)"); static int timeout = WATCHDOG_TIMEOUT; /* in seconds */ module_param(timeout, int, 0); MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds. 1<= timeout <=255 (default=" __MODULE_STRING(WATCHDOG_TIMEOUT) ")"); static int nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, int, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); static int early_disable = WATCHDOG_EARLY_DISABLE; module_param(early_disable, int, 0); MODULE_PARM_DESC(early_disable, "Watchdog gets disabled at boot time (default=" __MODULE_STRING(WATCHDOG_EARLY_DISABLE) ")"); /* * Kernel methods. */ #define W83697HF_EFER (wdt_io + 0) /* Extended Function Enable Register */ #define W83697HF_EFIR (wdt_io + 0) /* Extended Function Index Register (same as EFER) */ #define W83697HF_EFDR (wdt_io + 1) /* Extended Function Data Register */ static inline void w83697hf_unlock(void) { outb_p(0x87, W83697HF_EFER); /* Enter extended function mode */ outb_p(0x87, W83697HF_EFER); /* Again according to manual */ } static inline void w83697hf_lock(void) { outb_p(0xAA, W83697HF_EFER); /* Leave extended function mode */ } /* * The three functions w83697hf_get_reg(), w83697hf_set_reg() and * w83697hf_write_timeout() must be called with the device unlocked. */ static unsigned char w83697hf_get_reg(unsigned char reg) { outb_p(reg, W83697HF_EFIR); return inb_p(W83697HF_EFDR); } static void w83697hf_set_reg(unsigned char reg, unsigned char data) { outb_p(reg, W83697HF_EFIR); outb_p(data, W83697HF_EFDR); } static void w83697hf_write_timeout(int timeout) { /* Write Timeout counter to CRF4 */ w83697hf_set_reg(0xF4, timeout); } static void w83697hf_select_wdt(void) { w83697hf_unlock(); w83697hf_set_reg(0x07, 0x08); /* Switch to logic device 8 (GPIO2) */ } static inline void w83697hf_deselect_wdt(void) { w83697hf_lock(); } static void w83697hf_init(void) { unsigned char bbuf; w83697hf_select_wdt(); bbuf = w83697hf_get_reg(0x29); bbuf &= ~0x60; bbuf |= 0x20; /* Set pin 119 to WDTO# mode (= CR29, WDT0) */ w83697hf_set_reg(0x29, bbuf); bbuf = w83697hf_get_reg(0xF3); bbuf &= ~0x04; w83697hf_set_reg(0xF3, bbuf); /* Count mode is seconds */ w83697hf_deselect_wdt(); } static void wdt_ping(void) { spin_lock(&io_lock); w83697hf_select_wdt(); w83697hf_write_timeout(timeout); w83697hf_deselect_wdt(); spin_unlock(&io_lock); } static void wdt_enable(void) { spin_lock(&io_lock); w83697hf_select_wdt(); w83697hf_write_timeout(timeout); w83697hf_set_reg(0x30, 1); /* Enable timer */ w83697hf_deselect_wdt(); spin_unlock(&io_lock); } static void wdt_disable(void) { spin_lock(&io_lock); w83697hf_select_wdt(); w83697hf_set_reg(0x30, 0); /* Disable timer */ w83697hf_write_timeout(0); w83697hf_deselect_wdt(); spin_unlock(&io_lock); } static unsigned char wdt_running(void) { unsigned char t; spin_lock(&io_lock); w83697hf_select_wdt(); t = w83697hf_get_reg(0xF4); /* Read timer */ w83697hf_deselect_wdt(); spin_unlock(&io_lock); return t; } static int wdt_set_heartbeat(int t) { if (t < 1 || t > 255) return -EINVAL; timeout = t; return 0; } static ssize_t wdt_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { if (count) { if (!nowayout) { size_t i; expect_close = 0; for (i = 0; i != count; i++) { char c; if (get_user(c, buf + i)) return -EFAULT; if (c == 'V') expect_close = 42; } } wdt_ping(); } return count; } static long wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int __user *p = argp; int new_timeout; static const struct watchdog_info ident = { .options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE, .firmware_version = 1, .identity = "W83697HF WDT", }; switch (cmd) { case WDIOC_GETSUPPORT: if (copy_to_user(argp, &ident, sizeof(ident))) return -EFAULT; break; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, p); case WDIOC_SETOPTIONS: { int options, retval = -EINVAL; if (get_user(options, p)) return -EFAULT; if (options & WDIOS_DISABLECARD) { wdt_disable(); retval = 0; } if (options & WDIOS_ENABLECARD) { wdt_enable(); retval = 0; } return retval; } case WDIOC_KEEPALIVE: wdt_ping(); break; case WDIOC_SETTIMEOUT: if (get_user(new_timeout, p)) return -EFAULT; if (wdt_set_heartbeat(new_timeout)) return -EINVAL; wdt_ping(); /* Fall */ case WDIOC_GETTIMEOUT: return put_user(timeout, p); default: return -ENOTTY; } return 0; } static int wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(0, &wdt_is_open)) return -EBUSY; /* * Activate */ wdt_enable(); return nonseekable_open(inode, file); } static int wdt_close(struct inode *inode, struct file *file) { if (expect_close == 42) wdt_disable(); else { printk(KERN_CRIT PFX "Unexpected close, not stopping watchdog!\n"); wdt_ping(); } expect_close = 0; clear_bit(0, &wdt_is_open); return 0; } /* * Notifier for system down */ static int wdt_notify_sys(struct notifier_block *this, unsigned long code, void *unused) { if (code == SYS_DOWN || code == SYS_HALT) wdt_disable(); /* Turn the WDT off */ return NOTIFY_DONE; } /* * Kernel Interfaces */ static const struct file_operations wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = wdt_write, .unlocked_ioctl = wdt_ioctl, .open = wdt_open, .release = wdt_close, }; static struct miscdevice wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &wdt_fops, }; /* * The WDT needs to learn about soft shutdowns in order to * turn the timebomb registers off. */ static struct notifier_block wdt_notifier = { .notifier_call = wdt_notify_sys, }; static int w83697hf_check_wdt(void) { if (!request_region(wdt_io, 2, WATCHDOG_NAME)) { printk(KERN_ERR PFX "I/O address 0x%x already in use\n", wdt_io); return -EIO; } printk(KERN_DEBUG PFX "Looking for watchdog at address 0x%x\n", wdt_io); w83697hf_unlock(); if (w83697hf_get_reg(0x20) == 0x60) { printk(KERN_INFO PFX "watchdog found at address 0x%x\n", wdt_io); w83697hf_lock(); return 0; } /* Reprotect in case it was a compatible device */ w83697hf_lock(); printk(KERN_INFO PFX "watchdog not found at address 0x%x\n", wdt_io); release_region(wdt_io, 2); return -EIO; } static int w83697hf_ioports[] = { 0x2e, 0x4e, 0x00 }; static int __init wdt_init(void) { int ret, i, found = 0; printk(KERN_INFO PFX "WDT driver for W83697HF/HG initializing\n"); if (wdt_io == 0) { /* we will autodetect the W83697HF/HG watchdog */ for (i = 0; ((!found) && (w83697hf_ioports[i] != 0)); i++) { wdt_io = w83697hf_ioports[i]; if (!w83697hf_check_wdt()) found++; } } else { if (!w83697hf_check_wdt()) found++; } if (!found) { printk(KERN_ERR PFX "No W83697HF/HG could be found\n"); ret = -EIO; goto out; } w83697hf_init(); if (early_disable) { if (wdt_running()) printk(KERN_WARNING PFX "Stopping previously enabled " "watchdog until userland kicks in\n"); wdt_disable(); } if (wdt_set_heartbeat(timeout)) { wdt_set_heartbeat(WATCHDOG_TIMEOUT); printk(KERN_INFO PFX "timeout value must be 1 <= timeout <= 255, using %d\n", WATCHDOG_TIMEOUT); } ret = register_reboot_notifier(&wdt_notifier); if (ret != 0) { printk(KERN_ERR PFX "cannot register reboot notifier (err=%d)\n", ret); goto unreg_regions; } ret = misc_register(&wdt_miscdev); if (ret != 0) { printk(KERN_ERR PFX "cannot register miscdev on minor=%d (err=%d)\n", WATCHDOG_MINOR, ret); goto unreg_reboot; } printk(KERN_INFO PFX "initialized. timeout=%d sec (nowayout=%d)\n", timeout, nowayout); out: return ret; unreg_reboot: unregister_reboot_notifier(&wdt_notifier); unreg_regions: release_region(wdt_io, 2); goto out; } static void __exit wdt_exit(void) { misc_deregister(&wdt_miscdev); unregister_reboot_notifier(&wdt_notifier); release_region(wdt_io, 2); } module_init(wdt_init); module_exit(wdt_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Marcus Junker <junker@anduras.de>, " "Samuel Tardieu <sam@rfc1149.net>"); MODULE_DESCRIPTION("w83697hf/hg WDT driver"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
gpl-2.0
mordesku/Solid_Kernel-GEEHRC
sound/pci/ymfpci/ymfpci.c
4861
11201
/* * The driver for the Yamaha's DS1/DS1E cards * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * * 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/init.h> #include <linux/pci.h> #include <linux/time.h> #include <linux/module.h> #include <sound/core.h> #include <sound/ymfpci.h> #include <sound/mpu401.h> #include <sound/opl3.h> #include <sound/initval.h> MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>"); MODULE_DESCRIPTION("Yamaha DS-1 PCI"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Yamaha,YMF724}," "{Yamaha,YMF724F}," "{Yamaha,YMF740}," "{Yamaha,YMF740C}," "{Yamaha,YMF744}," "{Yamaha,YMF754}}"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */ static long fm_port[SNDRV_CARDS]; static long mpu_port[SNDRV_CARDS]; #ifdef SUPPORT_JOYSTICK static long joystick_port[SNDRV_CARDS]; #endif static bool rear_switch[SNDRV_CARDS]; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for the Yamaha DS-1 PCI soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for the Yamaha DS-1 PCI soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable Yamaha DS-1 soundcard."); module_param_array(mpu_port, long, NULL, 0444); MODULE_PARM_DESC(mpu_port, "MPU-401 Port."); module_param_array(fm_port, long, NULL, 0444); MODULE_PARM_DESC(fm_port, "FM OPL-3 Port."); #ifdef SUPPORT_JOYSTICK module_param_array(joystick_port, long, NULL, 0444); MODULE_PARM_DESC(joystick_port, "Joystick port address"); #endif module_param_array(rear_switch, bool, NULL, 0444); MODULE_PARM_DESC(rear_switch, "Enable shared rear/line-in switch"); static DEFINE_PCI_DEVICE_TABLE(snd_ymfpci_ids) = { { PCI_VDEVICE(YAMAHA, 0x0004), 0, }, /* YMF724 */ { PCI_VDEVICE(YAMAHA, 0x000d), 0, }, /* YMF724F */ { PCI_VDEVICE(YAMAHA, 0x000a), 0, }, /* YMF740 */ { PCI_VDEVICE(YAMAHA, 0x000c), 0, }, /* YMF740C */ { PCI_VDEVICE(YAMAHA, 0x0010), 0, }, /* YMF744 */ { PCI_VDEVICE(YAMAHA, 0x0012), 0, }, /* YMF754 */ { 0, } }; MODULE_DEVICE_TABLE(pci, snd_ymfpci_ids); #ifdef SUPPORT_JOYSTICK static int __devinit snd_ymfpci_create_gameport(struct snd_ymfpci *chip, int dev, int legacy_ctrl, int legacy_ctrl2) { struct gameport *gp; struct resource *r = NULL; int io_port = joystick_port[dev]; if (!io_port) return -ENODEV; if (chip->pci->device >= 0x0010) { /* YMF 744/754 */ if (io_port == 1) { /* auto-detect */ if (!(io_port = pci_resource_start(chip->pci, 2))) return -ENODEV; } } else { if (io_port == 1) { /* auto-detect */ for (io_port = 0x201; io_port <= 0x205; io_port++) { if (io_port == 0x203) continue; if ((r = request_region(io_port, 1, "YMFPCI gameport")) != NULL) break; } if (!r) { printk(KERN_ERR "ymfpci: no gameport ports available\n"); return -EBUSY; } } switch (io_port) { case 0x201: legacy_ctrl2 |= 0 << 6; break; case 0x202: legacy_ctrl2 |= 1 << 6; break; case 0x204: legacy_ctrl2 |= 2 << 6; break; case 0x205: legacy_ctrl2 |= 3 << 6; break; default: printk(KERN_ERR "ymfpci: invalid joystick port %#x", io_port); return -EINVAL; } } if (!r && !(r = request_region(io_port, 1, "YMFPCI gameport"))) { printk(KERN_ERR "ymfpci: joystick port %#x is in use.\n", io_port); return -EBUSY; } chip->gameport = gp = gameport_allocate_port(); if (!gp) { printk(KERN_ERR "ymfpci: cannot allocate memory for gameport\n"); release_and_free_resource(r); return -ENOMEM; } gameport_set_name(gp, "Yamaha YMF Gameport"); gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci)); gameport_set_dev_parent(gp, &chip->pci->dev); gp->io = io_port; gameport_set_port_data(gp, r); if (chip->pci->device >= 0x0010) /* YMF 744/754 */ pci_write_config_word(chip->pci, PCIR_DSXG_JOYBASE, io_port); pci_write_config_word(chip->pci, PCIR_DSXG_LEGACY, legacy_ctrl | YMFPCI_LEGACY_JPEN); pci_write_config_word(chip->pci, PCIR_DSXG_ELEGACY, legacy_ctrl2); gameport_register_port(chip->gameport); return 0; } void snd_ymfpci_free_gameport(struct snd_ymfpci *chip) { if (chip->gameport) { struct resource *r = gameport_get_port_data(chip->gameport); gameport_unregister_port(chip->gameport); chip->gameport = NULL; release_and_free_resource(r); } } #else static inline int snd_ymfpci_create_gameport(struct snd_ymfpci *chip, int dev, int l, int l2) { return -ENOSYS; } void snd_ymfpci_free_gameport(struct snd_ymfpci *chip) { } #endif /* SUPPORT_JOYSTICK */ static int __devinit snd_card_ymfpci_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_card *card; struct resource *fm_res = NULL; struct resource *mpu_res = NULL; struct snd_ymfpci *chip; struct snd_opl3 *opl3; const char *str, *model; int err; u16 legacy_ctrl, legacy_ctrl2, old_legacy_ctrl; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card); if (err < 0) return err; switch (pci_id->device) { case 0x0004: str = "YMF724"; model = "DS-1"; break; case 0x000d: str = "YMF724F"; model = "DS-1"; break; case 0x000a: str = "YMF740"; model = "DS-1L"; break; case 0x000c: str = "YMF740C"; model = "DS-1L"; break; case 0x0010: str = "YMF744"; model = "DS-1S"; break; case 0x0012: str = "YMF754"; model = "DS-1E"; break; default: model = str = "???"; break; } legacy_ctrl = 0; legacy_ctrl2 = 0x0800; /* SBEN = 0, SMOD = 01, LAD = 0 */ if (pci_id->device >= 0x0010) { /* YMF 744/754 */ if (fm_port[dev] == 1) { /* auto-detect */ fm_port[dev] = pci_resource_start(pci, 1); } if (fm_port[dev] > 0 && (fm_res = request_region(fm_port[dev], 4, "YMFPCI OPL3")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_FMEN; pci_write_config_word(pci, PCIR_DSXG_FMBASE, fm_port[dev]); } if (mpu_port[dev] == 1) { /* auto-detect */ mpu_port[dev] = pci_resource_start(pci, 1) + 0x20; } if (mpu_port[dev] > 0 && (mpu_res = request_region(mpu_port[dev], 2, "YMFPCI MPU401")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_MEN; pci_write_config_word(pci, PCIR_DSXG_MPU401BASE, mpu_port[dev]); } } else { switch (fm_port[dev]) { case 0x388: legacy_ctrl2 |= 0; break; case 0x398: legacy_ctrl2 |= 1; break; case 0x3a0: legacy_ctrl2 |= 2; break; case 0x3a8: legacy_ctrl2 |= 3; break; default: fm_port[dev] = 0; break; } if (fm_port[dev] > 0 && (fm_res = request_region(fm_port[dev], 4, "YMFPCI OPL3")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_FMEN; } else { legacy_ctrl2 &= ~YMFPCI_LEGACY2_FMIO; fm_port[dev] = 0; } switch (mpu_port[dev]) { case 0x330: legacy_ctrl2 |= 0 << 4; break; case 0x300: legacy_ctrl2 |= 1 << 4; break; case 0x332: legacy_ctrl2 |= 2 << 4; break; case 0x334: legacy_ctrl2 |= 3 << 4; break; default: mpu_port[dev] = 0; break; } if (mpu_port[dev] > 0 && (mpu_res = request_region(mpu_port[dev], 2, "YMFPCI MPU401")) != NULL) { legacy_ctrl |= YMFPCI_LEGACY_MEN; } else { legacy_ctrl2 &= ~YMFPCI_LEGACY2_MPUIO; mpu_port[dev] = 0; } } if (mpu_res) { legacy_ctrl |= YMFPCI_LEGACY_MIEN; legacy_ctrl2 |= YMFPCI_LEGACY2_IMOD; } pci_read_config_word(pci, PCIR_DSXG_LEGACY, &old_legacy_ctrl); pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl); pci_write_config_word(pci, PCIR_DSXG_ELEGACY, legacy_ctrl2); if ((err = snd_ymfpci_create(card, pci, old_legacy_ctrl, &chip)) < 0) { snd_card_free(card); release_and_free_resource(mpu_res); release_and_free_resource(fm_res); return err; } chip->fm_res = fm_res; chip->mpu_res = mpu_res; card->private_data = chip; strcpy(card->driver, str); sprintf(card->shortname, "Yamaha %s (%s)", model, str); sprintf(card->longname, "%s at 0x%lx, irq %i", card->shortname, chip->reg_area_phys, chip->irq); if ((err = snd_ymfpci_pcm(chip, 0, NULL)) < 0) { snd_card_free(card); return err; } if ((err = snd_ymfpci_pcm_spdif(chip, 1, NULL)) < 0) { snd_card_free(card); return err; } err = snd_ymfpci_mixer(chip, rear_switch[dev]); if (err < 0) { snd_card_free(card); return err; } if (chip->ac97->ext_id & AC97_EI_SDAC) { err = snd_ymfpci_pcm_4ch(chip, 2, NULL); if (err < 0) { snd_card_free(card); return err; } err = snd_ymfpci_pcm2(chip, 3, NULL); if (err < 0) { snd_card_free(card); return err; } } if ((err = snd_ymfpci_timer(chip, 0)) < 0) { snd_card_free(card); return err; } if (chip->mpu_res) { if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_YMFPCI, mpu_port[dev], MPU401_INFO_INTEGRATED | MPU401_INFO_IRQ_HOOK, -1, &chip->rawmidi)) < 0) { printk(KERN_WARNING "ymfpci: cannot initialize MPU401 at 0x%lx, skipping...\n", mpu_port[dev]); legacy_ctrl &= ~YMFPCI_LEGACY_MIEN; /* disable MPU401 irq */ pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl); } } if (chip->fm_res) { if ((err = snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2, OPL3_HW_OPL3, 1, &opl3)) < 0) { printk(KERN_WARNING "ymfpci: cannot initialize FM OPL3 at 0x%lx, skipping...\n", fm_port[dev]); legacy_ctrl &= ~YMFPCI_LEGACY_FMEN; pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl); } else if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) { snd_card_free(card); snd_printk(KERN_ERR "cannot create opl3 hwdep\n"); return err; } } snd_ymfpci_create_gameport(chip, dev, legacy_ctrl, legacy_ctrl2); if ((err = snd_card_register(card)) < 0) { snd_card_free(card); return err; } pci_set_drvdata(pci, card); dev++; return 0; } static void __devexit snd_card_ymfpci_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); pci_set_drvdata(pci, NULL); } static struct pci_driver driver = { .name = KBUILD_MODNAME, .id_table = snd_ymfpci_ids, .probe = snd_card_ymfpci_probe, .remove = __devexit_p(snd_card_ymfpci_remove), #ifdef CONFIG_PM .suspend = snd_ymfpci_suspend, .resume = snd_ymfpci_resume, #endif }; static int __init alsa_card_ymfpci_init(void) { return pci_register_driver(&driver); } static void __exit alsa_card_ymfpci_exit(void) { pci_unregister_driver(&driver); } module_init(alsa_card_ymfpci_init) module_exit(alsa_card_ymfpci_exit)
gpl-2.0
vovanx500/ConceptKernel
drivers/leds/leds-tca6507.c
4861
20536
/* * leds-tca6507 * * The TCA6507 is a programmable LED controller that can drive 7 * separate lines either by holding them low, or by pulsing them * with modulated width. * The modulation can be varied in a simple pattern to produce a blink or * double-blink. * * This driver can configure each line either as a 'GPIO' which is out-only * (no pull-up) or as an LED with variable brightness and hardware-assisted * blinking. * * Apart from OFF and ON there are three programmable brightness levels which * can be programmed from 0 to 15 and indicate how many 500usec intervals in * each 8msec that the led is 'on'. The levels are named MASTER, BANK0 and * BANK1. * * There are two different blink rates that can be programmed, each with * separate time for rise, on, fall, off and second-off. Thus if 3 or more * different non-trivial rates are required, software must be used for the extra * rates. The two different blink rates must align with the two levels BANK0 and * BANK1. * This driver does not support double-blink so 'second-off' always matches * 'off'. * * Only 16 different times can be programmed in a roughly logarithmic scale from * 64ms to 16320ms. To be precise the possible times are: * 0, 64, 128, 192, 256, 384, 512, 768, * 1024, 1536, 2048, 3072, 4096, 5760, 8128, 16320 * * Times that cannot be closely matched with these must be * handled in software. This driver allows 12.5% error in matching. * * This driver does not allow rise/fall rates to be set explicitly. When trying * to match a given 'on' or 'off' period, an appropriate pair of 'change' and * 'hold' times are chosen to get a close match. If the target delay is even, * the 'change' number will be the smaller; if odd, the 'hold' number will be * the smaller. * Choosing pairs of delays with 12.5% errors allows us to match delays in the * ranges: 56-72, 112-144, 168-216, 224-27504, 28560-36720. * 26% of the achievable sums can be matched by multiple pairings. For example * 1536 == 1536+0, 1024+512, or 768+768. This driver will always choose the * pairing with the least maximum - 768+768 in this case. Other pairings are * not available. * * Access to the 3 levels and 2 blinks are on a first-come, first-served basis. * Access can be shared by multiple leds if they have the same level and * either same blink rates, or some don't blink. * When a led changes, it relinquishes access and tries again, so it might * lose access to hardware blink. * If a blink engine cannot be allocated, software blink is used. * If the desired brightness cannot be allocated, the closest available non-zero * brightness is used. As 'full' is always available, the worst case would be * to have two different blink rates at '1', with Max at '2', then other leds * will have to choose between '2' and '16'. Hopefully this is not likely. * * Each bank (BANK0 and BANK1) has two usage counts - LEDs using the brightness * and LEDs using the blink. It can only be reprogrammed when the appropriate * counter is zero. The MASTER level has a single usage count. * * Each Led has programmable 'on' and 'off' time as milliseconds. With each * there is a flag saying if it was explicitly requested or defaulted. * Similarly the banks know if each time was explicit or a default. Defaults * are permitted to be changed freely - they are not recognised when matching. * * * An led-tca6507 device must be provided with platform data. This data * lists for each output: the name, default trigger, and whether the signal * is being used as a GPiO rather than an led. 'struct led_plaform_data' * is used for this. If 'name' is NULL, the output isn't used. If 'flags' * is TCA6507_MAKE_CPIO, the output is a GPO. * The "struct led_platform_data" can be embedded in a * "struct tca6507_platform_data" which adds a 'gpio_base' for the GPiOs, * and a 'setup' callback which is called once the GPiOs are available. * */ #include <linux/module.h> #include <linux/slab.h> #include <linux/leds.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/gpio.h> #include <linux/workqueue.h> #include <linux/leds-tca6507.h> /* LED select registers determine the source that drives LED outputs */ #define TCA6507_LS_LED_OFF 0x0 /* Output HI-Z (off) */ #define TCA6507_LS_LED_OFF1 0x1 /* Output HI-Z (off) - not used */ #define TCA6507_LS_LED_PWM0 0x2 /* Output LOW with Bank0 rate */ #define TCA6507_LS_LED_PWM1 0x3 /* Output LOW with Bank1 rate */ #define TCA6507_LS_LED_ON 0x4 /* Output LOW (on) */ #define TCA6507_LS_LED_MIR 0x5 /* Output LOW with Master Intensity */ #define TCA6507_LS_BLINK0 0x6 /* Blink at Bank0 rate */ #define TCA6507_LS_BLINK1 0x7 /* Blink at Bank1 rate */ enum { BANK0, BANK1, MASTER, }; static int bank_source[3] = { TCA6507_LS_LED_PWM0, TCA6507_LS_LED_PWM1, TCA6507_LS_LED_MIR, }; static int blink_source[2] = { TCA6507_LS_BLINK0, TCA6507_LS_BLINK1, }; /* PWM registers */ #define TCA6507_REG_CNT 11 /* * 0x00, 0x01, 0x02 encode the TCA6507_LS_* values, each output * owns one bit in each register */ #define TCA6507_FADE_ON 0x03 #define TCA6507_FULL_ON 0x04 #define TCA6507_FADE_OFF 0x05 #define TCA6507_FIRST_OFF 0x06 #define TCA6507_SECOND_OFF 0x07 #define TCA6507_MAX_INTENSITY 0x08 #define TCA6507_MASTER_INTENSITY 0x09 #define TCA6507_INITIALIZE 0x0A #define INIT_CODE 0x8 #define TIMECODES 16 static int time_codes[TIMECODES] = { 0, 64, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5760, 8128, 16320 }; /* Convert an led.brightness level (0..255) to a TCA6507 level (0..15) */ static inline int TO_LEVEL(int brightness) { return brightness >> 4; } /* ...and convert back */ static inline int TO_BRIGHT(int level) { if (level) return (level << 4) | 0xf; return 0; } #define NUM_LEDS 7 struct tca6507_chip { int reg_set; /* One bit per register where * a '1' means the register * should be written */ u8 reg_file[TCA6507_REG_CNT]; /* Bank 2 is Master Intensity and doesn't use times */ struct bank { int level; int ontime, offtime; int on_dflt, off_dflt; int time_use, level_use; } bank[3]; struct i2c_client *client; struct work_struct work; spinlock_t lock; struct tca6507_led { struct tca6507_chip *chip; struct led_classdev led_cdev; int num; int ontime, offtime; int on_dflt, off_dflt; int bank; /* Bank used, or -1 */ int blink; /* Set if hardware-blinking */ } leds[NUM_LEDS]; #ifdef CONFIG_GPIOLIB struct gpio_chip gpio; const char *gpio_name[NUM_LEDS]; int gpio_map[NUM_LEDS]; #endif }; static const struct i2c_device_id tca6507_id[] = { { "tca6507" }, { } }; MODULE_DEVICE_TABLE(i2c, tca6507_id); static int choose_times(int msec, int *c1p, int *c2p) { /* * Choose two timecodes which add to 'msec' as near as possible. * The first returned is the 'on' or 'off' time. The second is to be * used as a 'fade-on' or 'fade-off' time. If 'msec' is even, * the first will not be smaller than the second. If 'msec' is odd, * the first will not be larger than the second. * If we cannot get a sum within 1/8 of 'msec' fail with -EINVAL, * otherwise return the sum that was achieved, plus 1 if the first is * smaller. * If two possibilities are equally good (e.g. 512+0, 256+256), choose * the first pair so there is more change-time visible (i.e. it is * softer). */ int c1, c2; int tmax = msec * 9 / 8; int tmin = msec * 7 / 8; int diff = 65536; /* We start at '1' to ensure we never even think of choosing a * total time of '0'. */ for (c1 = 1; c1 < TIMECODES; c1++) { int t = time_codes[c1]; if (t*2 < tmin) continue; if (t > tmax) break; for (c2 = 0; c2 <= c1; c2++) { int tt = t + time_codes[c2]; int d; if (tt < tmin) continue; if (tt > tmax) break; /* This works! */ d = abs(msec - tt); if (d >= diff) continue; /* Best yet */ *c1p = c1; *c2p = c2; diff = d; if (d == 0) return msec; } } if (diff < 65536) { int actual; if (msec & 1) { c1 = *c2p; *c2p = *c1p; *c1p = c1; } actual = time_codes[*c1p] + time_codes[*c2p]; if (*c1p < *c2p) return actual + 1; else return actual; } /* No close match */ return -EINVAL; } /* * Update the register file with the appropriate 3-bit state for * the given led. */ static void set_select(struct tca6507_chip *tca, int led, int val) { int mask = (1 << led); int bit; for (bit = 0; bit < 3; bit++) { int n = tca->reg_file[bit] & ~mask; if (val & (1 << bit)) n |= mask; if (tca->reg_file[bit] != n) { tca->reg_file[bit] = n; tca->reg_set |= (1 << bit); } } } /* Update the register file with the appropriate 4-bit code for * one bank or other. This can be used for timers, for levels, or * for initialisation. */ static void set_code(struct tca6507_chip *tca, int reg, int bank, int new) { int mask = 0xF; int n; if (bank) { mask <<= 4; new <<= 4; } n = tca->reg_file[reg] & ~mask; n |= new; if (tca->reg_file[reg] != n) { tca->reg_file[reg] = n; tca->reg_set |= 1 << reg; } } /* Update brightness level. */ static void set_level(struct tca6507_chip *tca, int bank, int level) { switch (bank) { case BANK0: case BANK1: set_code(tca, TCA6507_MAX_INTENSITY, bank, level); break; case MASTER: set_code(tca, TCA6507_MASTER_INTENSITY, 0, level); break; } tca->bank[bank].level = level; } /* Record all relevant time code for a given bank */ static void set_times(struct tca6507_chip *tca, int bank) { int c1, c2; int result; result = choose_times(tca->bank[bank].ontime, &c1, &c2); dev_dbg(&tca->client->dev, "Chose on times %d(%d) %d(%d) for %dms\n", c1, time_codes[c1], c2, time_codes[c2], tca->bank[bank].ontime); set_code(tca, TCA6507_FADE_ON, bank, c2); set_code(tca, TCA6507_FULL_ON, bank, c1); tca->bank[bank].ontime = result; result = choose_times(tca->bank[bank].offtime, &c1, &c2); dev_dbg(&tca->client->dev, "Chose off times %d(%d) %d(%d) for %dms\n", c1, time_codes[c1], c2, time_codes[c2], tca->bank[bank].offtime); set_code(tca, TCA6507_FADE_OFF, bank, c2); set_code(tca, TCA6507_FIRST_OFF, bank, c1); set_code(tca, TCA6507_SECOND_OFF, bank, c1); tca->bank[bank].offtime = result; set_code(tca, TCA6507_INITIALIZE, bank, INIT_CODE); } /* Write all needed register of tca6507 */ static void tca6507_work(struct work_struct *work) { struct tca6507_chip *tca = container_of(work, struct tca6507_chip, work); struct i2c_client *cl = tca->client; int set; u8 file[TCA6507_REG_CNT]; int r; spin_lock_irq(&tca->lock); set = tca->reg_set; memcpy(file, tca->reg_file, TCA6507_REG_CNT); tca->reg_set = 0; spin_unlock_irq(&tca->lock); for (r = 0; r < TCA6507_REG_CNT; r++) if (set & (1<<r)) i2c_smbus_write_byte_data(cl, r, file[r]); } static void led_release(struct tca6507_led *led) { /* If led owns any resource, release it. */ struct tca6507_chip *tca = led->chip; if (led->bank >= 0) { struct bank *b = tca->bank + led->bank; if (led->blink) b->time_use--; b->level_use--; } led->blink = 0; led->bank = -1; } static int led_prepare(struct tca6507_led *led) { /* Assign this led to a bank, configuring that bank if necessary. */ int level = TO_LEVEL(led->led_cdev.brightness); struct tca6507_chip *tca = led->chip; int c1, c2; int i; struct bank *b; int need_init = 0; led->led_cdev.brightness = TO_BRIGHT(level); if (level == 0) { set_select(tca, led->num, TCA6507_LS_LED_OFF); return 0; } if (led->ontime == 0 || led->offtime == 0) { /* * Just set the brightness, choosing first usable bank. * If none perfect, choose best. * Count backwards so we check MASTER bank first * to avoid wasting a timer. */ int best = -1;/* full-on */ int diff = 15-level; if (level == 15) { set_select(tca, led->num, TCA6507_LS_LED_ON); return 0; } for (i = MASTER; i >= BANK0; i--) { int d; if (tca->bank[i].level == level || tca->bank[i].level_use == 0) { best = i; break; } d = abs(level - tca->bank[i].level); if (d < diff) { diff = d; best = i; } } if (best == -1) { /* Best brightness is full-on */ set_select(tca, led->num, TCA6507_LS_LED_ON); led->led_cdev.brightness = LED_FULL; return 0; } if (!tca->bank[best].level_use) set_level(tca, best, level); tca->bank[best].level_use++; led->bank = best; set_select(tca, led->num, bank_source[best]); led->led_cdev.brightness = TO_BRIGHT(tca->bank[best].level); return 0; } /* * We have on/off time so we need to try to allocate a timing bank. * First check if times are compatible with hardware and give up if * not. */ if (choose_times(led->ontime, &c1, &c2) < 0) return -EINVAL; if (choose_times(led->offtime, &c1, &c2) < 0) return -EINVAL; for (i = BANK0; i <= BANK1; i++) { if (tca->bank[i].level_use == 0) /* not in use - it is ours! */ break; if (tca->bank[i].level != level) /* Incompatible level - skip */ /* FIX: if timer matches we maybe should consider * this anyway... */ continue; if (tca->bank[i].time_use == 0) /* Timer not in use, and level matches - use it */ break; if (!(tca->bank[i].on_dflt || led->on_dflt || tca->bank[i].ontime == led->ontime)) /* on time is incompatible */ continue; if (!(tca->bank[i].off_dflt || led->off_dflt || tca->bank[i].offtime == led->offtime)) /* off time is incompatible */ continue; /* looks like a suitable match */ break; } if (i > BANK1) /* Nothing matches - how sad */ return -EINVAL; b = &tca->bank[i]; if (b->level_use == 0) set_level(tca, i, level); b->level_use++; led->bank = i; if (b->on_dflt || !led->on_dflt || b->time_use == 0) { b->ontime = led->ontime; b->on_dflt = led->on_dflt; need_init = 1; } if (b->off_dflt || !led->off_dflt || b->time_use == 0) { b->offtime = led->offtime; b->off_dflt = led->off_dflt; need_init = 1; } if (need_init) set_times(tca, i); led->ontime = b->ontime; led->offtime = b->offtime; b->time_use++; led->blink = 1; led->led_cdev.brightness = TO_BRIGHT(b->level); set_select(tca, led->num, blink_source[i]); return 0; } static int led_assign(struct tca6507_led *led) { struct tca6507_chip *tca = led->chip; int err; unsigned long flags; spin_lock_irqsave(&tca->lock, flags); led_release(led); err = led_prepare(led); if (err) { /* * Can only fail on timer setup. In that case we need to * re-establish as steady level. */ led->ontime = 0; led->offtime = 0; led_prepare(led); } spin_unlock_irqrestore(&tca->lock, flags); if (tca->reg_set) schedule_work(&tca->work); return err; } static void tca6507_brightness_set(struct led_classdev *led_cdev, enum led_brightness brightness) { struct tca6507_led *led = container_of(led_cdev, struct tca6507_led, led_cdev); led->led_cdev.brightness = brightness; led->ontime = 0; led->offtime = 0; led_assign(led); } static int tca6507_blink_set(struct led_classdev *led_cdev, unsigned long *delay_on, unsigned long *delay_off) { struct tca6507_led *led = container_of(led_cdev, struct tca6507_led, led_cdev); if (*delay_on == 0) led->on_dflt = 1; else if (delay_on != &led_cdev->blink_delay_on) led->on_dflt = 0; led->ontime = *delay_on; if (*delay_off == 0) led->off_dflt = 1; else if (delay_off != &led_cdev->blink_delay_off) led->off_dflt = 0; led->offtime = *delay_off; if (led->ontime == 0) led->ontime = 512; if (led->offtime == 0) led->offtime = 512; if (led->led_cdev.brightness == LED_OFF) led->led_cdev.brightness = LED_FULL; if (led_assign(led) < 0) { led->ontime = 0; led->offtime = 0; led->led_cdev.brightness = LED_OFF; return -EINVAL; } *delay_on = led->ontime; *delay_off = led->offtime; return 0; } #ifdef CONFIG_GPIOLIB static void tca6507_gpio_set_value(struct gpio_chip *gc, unsigned offset, int val) { struct tca6507_chip *tca = container_of(gc, struct tca6507_chip, gpio); unsigned long flags; spin_lock_irqsave(&tca->lock, flags); /* * 'OFF' is floating high, and 'ON' is pulled down, so it has the * inverse sense of 'val'. */ set_select(tca, tca->gpio_map[offset], val ? TCA6507_LS_LED_OFF : TCA6507_LS_LED_ON); spin_unlock_irqrestore(&tca->lock, flags); if (tca->reg_set) schedule_work(&tca->work); } static int tca6507_gpio_direction_output(struct gpio_chip *gc, unsigned offset, int val) { tca6507_gpio_set_value(gc, offset, val); return 0; } static int tca6507_probe_gpios(struct i2c_client *client, struct tca6507_chip *tca, struct tca6507_platform_data *pdata) { int err; int i = 0; int gpios = 0; for (i = 0; i < NUM_LEDS; i++) if (pdata->leds.leds[i].name && pdata->leds.leds[i].flags) { /* Configure as a gpio */ tca->gpio_name[gpios] = pdata->leds.leds[i].name; tca->gpio_map[gpios] = i; gpios++; } if (!gpios) return 0; tca->gpio.label = "gpio-tca6507"; tca->gpio.names = tca->gpio_name; tca->gpio.ngpio = gpios; tca->gpio.base = pdata->gpio_base; tca->gpio.owner = THIS_MODULE; tca->gpio.direction_output = tca6507_gpio_direction_output; tca->gpio.set = tca6507_gpio_set_value; tca->gpio.dev = &client->dev; err = gpiochip_add(&tca->gpio); if (err) { tca->gpio.ngpio = 0; return err; } if (pdata->setup) pdata->setup(tca->gpio.base, tca->gpio.ngpio); return 0; } static void tca6507_remove_gpio(struct tca6507_chip *tca) { if (tca->gpio.ngpio) { int err = gpiochip_remove(&tca->gpio); dev_err(&tca->client->dev, "%s failed, %d\n", "gpiochip_remove()", err); } } #else /* CONFIG_GPIOLIB */ static int tca6507_probe_gpios(struct i2c_client *client, struct tca6507_chip *tca, struct tca6507_platform_data *pdata) { return 0; } static void tca6507_remove_gpio(struct tca6507_chip *tca) { } #endif /* CONFIG_GPIOLIB */ static int __devinit tca6507_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct tca6507_chip *tca; struct i2c_adapter *adapter; struct tca6507_platform_data *pdata; int err; int i = 0; adapter = to_i2c_adapter(client->dev.parent); pdata = client->dev.platform_data; if (!i2c_check_functionality(adapter, I2C_FUNC_I2C)) return -EIO; if (!pdata || pdata->leds.num_leds != NUM_LEDS) { dev_err(&client->dev, "Need %d entries in platform-data list\n", NUM_LEDS); return -ENODEV; } tca = kzalloc(sizeof(*tca), GFP_KERNEL); if (!tca) return -ENOMEM; tca->client = client; INIT_WORK(&tca->work, tca6507_work); spin_lock_init(&tca->lock); i2c_set_clientdata(client, tca); for (i = 0; i < NUM_LEDS; i++) { struct tca6507_led *l = tca->leds + i; l->chip = tca; l->num = i; if (pdata->leds.leds[i].name && !pdata->leds.leds[i].flags) { l->led_cdev.name = pdata->leds.leds[i].name; l->led_cdev.default_trigger = pdata->leds.leds[i].default_trigger; l->led_cdev.brightness_set = tca6507_brightness_set; l->led_cdev.blink_set = tca6507_blink_set; l->bank = -1; err = led_classdev_register(&client->dev, &l->led_cdev); if (err < 0) goto exit; } } err = tca6507_probe_gpios(client, tca, pdata); if (err) goto exit; /* set all registers to known state - zero */ tca->reg_set = 0x7f; schedule_work(&tca->work); return 0; exit: while (i--) { if (tca->leds[i].led_cdev.name) led_classdev_unregister(&tca->leds[i].led_cdev); } kfree(tca); return err; } static int __devexit tca6507_remove(struct i2c_client *client) { int i; struct tca6507_chip *tca = i2c_get_clientdata(client); struct tca6507_led *tca_leds = tca->leds; for (i = 0; i < NUM_LEDS; i++) { if (tca_leds[i].led_cdev.name) led_classdev_unregister(&tca_leds[i].led_cdev); } tca6507_remove_gpio(tca); cancel_work_sync(&tca->work); kfree(tca); return 0; } static struct i2c_driver tca6507_driver = { .driver = { .name = "leds-tca6507", .owner = THIS_MODULE, }, .probe = tca6507_probe, .remove = __devexit_p(tca6507_remove), .id_table = tca6507_id, }; static int __init tca6507_leds_init(void) { return i2c_add_driver(&tca6507_driver); } static void __exit tca6507_leds_exit(void) { i2c_del_driver(&tca6507_driver); } module_init(tca6507_leds_init); module_exit(tca6507_leds_exit); MODULE_AUTHOR("NeilBrown <neilb@suse.de>"); MODULE_DESCRIPTION("TCA6507 LED/GPO driver"); MODULE_LICENSE("GPL v2");
gpl-2.0
OESF/linux-linaro-natty
drivers/net/wireless/rtl818x/rtl8187/leds.c
5117
6573
/* * Linux LED driver for RTL8187 * * Copyright 2009 Larry Finger <Larry.Finger@lwfinger.net> * * Based on the LED handling in the r8187 driver, which is: * Copyright (c) Realtek Semiconductor Corp. All rights reserved. * * Thanks to Realtek for their support! * * 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. */ #ifdef CONFIG_RTL8187_LEDS #include <net/mac80211.h> #include <linux/usb.h> #include <linux/eeprom_93cx6.h> #include "rtl8187.h" #include "leds.h" static void led_turn_on(struct work_struct *work) { /* As this routine does read/write operations on the hardware, it must * be run from a work queue. */ u8 reg; struct rtl8187_priv *priv = container_of(work, struct rtl8187_priv, led_on.work); struct rtl8187_led *led = &priv->led_tx; /* Don't change the LED, when the device is down. */ if (!priv->vif || priv->vif->type == NL80211_IFTYPE_UNSPECIFIED) return ; /* Skip if the LED is not registered. */ if (!led->dev) return; mutex_lock(&priv->conf_mutex); switch (led->ledpin) { case LED_PIN_GPIO0: rtl818x_iowrite8(priv, &priv->map->GPIO0, 0x01); rtl818x_iowrite8(priv, &priv->map->GP_ENABLE, 0x00); break; case LED_PIN_LED0: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) & ~(1 << 4); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_LED1: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) & ~(1 << 5); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_HW: default: break; } mutex_unlock(&priv->conf_mutex); } static void led_turn_off(struct work_struct *work) { /* As this routine does read/write operations on the hardware, it must * be run from a work queue. */ u8 reg; struct rtl8187_priv *priv = container_of(work, struct rtl8187_priv, led_off.work); struct rtl8187_led *led = &priv->led_tx; /* Don't change the LED, when the device is down. */ if (!priv->vif || priv->vif->type == NL80211_IFTYPE_UNSPECIFIED) return ; /* Skip if the LED is not registered. */ if (!led->dev) return; mutex_lock(&priv->conf_mutex); switch (led->ledpin) { case LED_PIN_GPIO0: rtl818x_iowrite8(priv, &priv->map->GPIO0, 0x01); rtl818x_iowrite8(priv, &priv->map->GP_ENABLE, 0x01); break; case LED_PIN_LED0: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) | (1 << 4); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_LED1: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) | (1 << 5); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_HW: default: break; } mutex_unlock(&priv->conf_mutex); } /* Callback from the LED subsystem. */ static void rtl8187_led_brightness_set(struct led_classdev *led_dev, enum led_brightness brightness) { struct rtl8187_led *led = container_of(led_dev, struct rtl8187_led, led_dev); struct ieee80211_hw *hw = led->dev; struct rtl8187_priv *priv; static bool radio_on; if (!hw) return; priv = hw->priv; if (led->is_radio) { if (brightness == LED_FULL) { ieee80211_queue_delayed_work(hw, &priv->led_on, 0); radio_on = true; } else if (radio_on) { radio_on = false; cancel_delayed_work_sync(&priv->led_on); ieee80211_queue_delayed_work(hw, &priv->led_off, 0); } } else if (radio_on) { if (brightness == LED_OFF) { ieee80211_queue_delayed_work(hw, &priv->led_off, 0); /* The LED is off for 1/20 sec - it just blinks. */ ieee80211_queue_delayed_work(hw, &priv->led_on, HZ / 20); } else ieee80211_queue_delayed_work(hw, &priv->led_on, 0); } } static int rtl8187_register_led(struct ieee80211_hw *dev, struct rtl8187_led *led, const char *name, const char *default_trigger, u8 ledpin, bool is_radio) { int err; struct rtl8187_priv *priv = dev->priv; if (led->dev) return -EEXIST; if (!default_trigger) return -EINVAL; led->dev = dev; led->ledpin = ledpin; led->is_radio = is_radio; strncpy(led->name, name, sizeof(led->name)); led->led_dev.name = led->name; led->led_dev.default_trigger = default_trigger; led->led_dev.brightness_set = rtl8187_led_brightness_set; err = led_classdev_register(&priv->udev->dev, &led->led_dev); if (err) { printk(KERN_INFO "LEDs: Failed to register %s\n", name); led->dev = NULL; return err; } return 0; } static void rtl8187_unregister_led(struct rtl8187_led *led) { struct ieee80211_hw *hw = led->dev; struct rtl8187_priv *priv = hw->priv; led_classdev_unregister(&led->led_dev); flush_delayed_work(&priv->led_off); led->dev = NULL; } void rtl8187_leds_init(struct ieee80211_hw *dev, u16 custid) { struct rtl8187_priv *priv = dev->priv; char name[RTL8187_LED_MAX_NAME_LEN + 1]; u8 ledpin; int err; /* According to the vendor driver, the LED operation depends on the * customer ID encoded in the EEPROM */ printk(KERN_INFO "rtl8187: Customer ID is 0x%02X\n", custid); switch (custid) { case EEPROM_CID_RSVD0: case EEPROM_CID_RSVD1: case EEPROM_CID_SERCOMM_PS: case EEPROM_CID_QMI: case EEPROM_CID_DELL: case EEPROM_CID_TOSHIBA: ledpin = LED_PIN_GPIO0; break; case EEPROM_CID_ALPHA0: ledpin = LED_PIN_LED0; break; case EEPROM_CID_HW: ledpin = LED_PIN_HW; break; default: ledpin = LED_PIN_GPIO0; } INIT_DELAYED_WORK(&priv->led_on, led_turn_on); INIT_DELAYED_WORK(&priv->led_off, led_turn_off); snprintf(name, sizeof(name), "rtl8187-%s::radio", wiphy_name(dev->wiphy)); err = rtl8187_register_led(dev, &priv->led_radio, name, ieee80211_get_radio_led_name(dev), ledpin, true); if (err) return; snprintf(name, sizeof(name), "rtl8187-%s::tx", wiphy_name(dev->wiphy)); err = rtl8187_register_led(dev, &priv->led_tx, name, ieee80211_get_tx_led_name(dev), ledpin, false); if (err) goto err_tx; snprintf(name, sizeof(name), "rtl8187-%s::rx", wiphy_name(dev->wiphy)); err = rtl8187_register_led(dev, &priv->led_rx, name, ieee80211_get_rx_led_name(dev), ledpin, false); if (!err) return; /* registration of RX LED failed - unregister */ rtl8187_unregister_led(&priv->led_tx); err_tx: rtl8187_unregister_led(&priv->led_radio); } void rtl8187_leds_exit(struct ieee80211_hw *dev) { struct rtl8187_priv *priv = dev->priv; rtl8187_unregister_led(&priv->led_radio); rtl8187_unregister_led(&priv->led_rx); rtl8187_unregister_led(&priv->led_tx); cancel_delayed_work_sync(&priv->led_off); cancel_delayed_work_sync(&priv->led_on); } #endif /* def CONFIG_RTL8187_LEDS */
gpl-2.0
shengdie/l01f_kernel_10c
drivers/mtd/onenand/onenand_sim.c
8189
13804
/* * linux/drivers/mtd/onenand/onenand_sim.c * * The OneNAND simulator * * Copyright © 2005-2007 Samsung Electronics * Kyungmin Park <kyungmin.park@samsung.com> * * Vishak G <vishak.g at samsung.com>, Rohit Hagargundgi <h.rohit at samsung.com> * Flex-OneNAND simulator support * Copyright (C) Samsung Electronics, 2008 * * 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/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/vmalloc.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <linux/mtd/onenand.h> #include <linux/io.h> #ifndef CONFIG_ONENAND_SIM_MANUFACTURER #define CONFIG_ONENAND_SIM_MANUFACTURER 0xec #endif #ifndef CONFIG_ONENAND_SIM_DEVICE_ID #define CONFIG_ONENAND_SIM_DEVICE_ID 0x04 #endif #define CONFIG_FLEXONENAND ((CONFIG_ONENAND_SIM_DEVICE_ID >> 9) & 1) #ifndef CONFIG_ONENAND_SIM_VERSION_ID #define CONFIG_ONENAND_SIM_VERSION_ID 0x1e #endif #ifndef CONFIG_ONENAND_SIM_TECHNOLOGY_ID #define CONFIG_ONENAND_SIM_TECHNOLOGY_ID CONFIG_FLEXONENAND #endif /* Initial boundary values for Flex-OneNAND Simulator */ #ifndef CONFIG_FLEXONENAND_SIM_DIE0_BOUNDARY #define CONFIG_FLEXONENAND_SIM_DIE0_BOUNDARY 0x01 #endif #ifndef CONFIG_FLEXONENAND_SIM_DIE1_BOUNDARY #define CONFIG_FLEXONENAND_SIM_DIE1_BOUNDARY 0x01 #endif static int manuf_id = CONFIG_ONENAND_SIM_MANUFACTURER; static int device_id = CONFIG_ONENAND_SIM_DEVICE_ID; static int version_id = CONFIG_ONENAND_SIM_VERSION_ID; static int technology_id = CONFIG_ONENAND_SIM_TECHNOLOGY_ID; static int boundary[] = { CONFIG_FLEXONENAND_SIM_DIE0_BOUNDARY, CONFIG_FLEXONENAND_SIM_DIE1_BOUNDARY, }; struct onenand_flash { void __iomem *base; void __iomem *data; }; #define ONENAND_CORE(flash) (flash->data) #define ONENAND_CORE_SPARE(flash, this, offset) \ ((flash->data) + (this->chipsize) + (offset >> 5)) #define ONENAND_MAIN_AREA(this, offset) \ (this->base + ONENAND_DATARAM + offset) #define ONENAND_SPARE_AREA(this, offset) \ (this->base + ONENAND_SPARERAM + offset) #define ONENAND_GET_WP_STATUS(this) \ (readw(this->base + ONENAND_REG_WP_STATUS)) #define ONENAND_SET_WP_STATUS(v, this) \ (writew(v, this->base + ONENAND_REG_WP_STATUS)) /* It has all 0xff chars */ #define MAX_ONENAND_PAGESIZE (4096 + 128) static unsigned char *ffchars; #if CONFIG_FLEXONENAND #define PARTITION_NAME "Flex-OneNAND simulator partition" #else #define PARTITION_NAME "OneNAND simulator partition" #endif static struct mtd_partition os_partitions[] = { { .name = PARTITION_NAME, .offset = 0, .size = MTDPART_SIZ_FULL, }, }; /* * OneNAND simulator mtd */ struct onenand_info { struct mtd_info mtd; struct mtd_partition *parts; struct onenand_chip onenand; struct onenand_flash flash; }; static struct onenand_info *info; #define DPRINTK(format, args...) \ do { \ printk(KERN_DEBUG "%s[%d]: " format "\n", __func__, \ __LINE__, ##args); \ } while (0) /** * onenand_lock_handle - Handle Lock scheme * @this: OneNAND device structure * @cmd: The command to be sent * * Send lock command to OneNAND device. * The lock scheme depends on chip type. */ static void onenand_lock_handle(struct onenand_chip *this, int cmd) { int block_lock_scheme; int status; status = ONENAND_GET_WP_STATUS(this); block_lock_scheme = !(this->options & ONENAND_HAS_CONT_LOCK); switch (cmd) { case ONENAND_CMD_UNLOCK: case ONENAND_CMD_UNLOCK_ALL: if (block_lock_scheme) ONENAND_SET_WP_STATUS(ONENAND_WP_US, this); else ONENAND_SET_WP_STATUS(status | ONENAND_WP_US, this); break; case ONENAND_CMD_LOCK: if (block_lock_scheme) ONENAND_SET_WP_STATUS(ONENAND_WP_LS, this); else ONENAND_SET_WP_STATUS(status | ONENAND_WP_LS, this); break; case ONENAND_CMD_LOCK_TIGHT: if (block_lock_scheme) ONENAND_SET_WP_STATUS(ONENAND_WP_LTS, this); else ONENAND_SET_WP_STATUS(status | ONENAND_WP_LTS, this); break; default: break; } } /** * onenand_bootram_handle - Handle BootRAM area * @this: OneNAND device structure * @cmd: The command to be sent * * Emulate BootRAM area. It is possible to do basic operation using BootRAM. */ static void onenand_bootram_handle(struct onenand_chip *this, int cmd) { switch (cmd) { case ONENAND_CMD_READID: writew(manuf_id, this->base); writew(device_id, this->base + 2); writew(version_id, this->base + 4); break; default: /* REVIST: Handle other commands */ break; } } /** * onenand_update_interrupt - Set interrupt register * @this: OneNAND device structure * @cmd: The command to be sent * * Update interrupt register. The status depends on command. */ static void onenand_update_interrupt(struct onenand_chip *this, int cmd) { int interrupt = ONENAND_INT_MASTER; switch (cmd) { case ONENAND_CMD_READ: case ONENAND_CMD_READOOB: interrupt |= ONENAND_INT_READ; break; case ONENAND_CMD_PROG: case ONENAND_CMD_PROGOOB: interrupt |= ONENAND_INT_WRITE; break; case ONENAND_CMD_ERASE: interrupt |= ONENAND_INT_ERASE; break; case ONENAND_CMD_RESET: interrupt |= ONENAND_INT_RESET; break; default: break; } writew(interrupt, this->base + ONENAND_REG_INTERRUPT); } /** * onenand_check_overwrite - Check if over-write happened * @dest: The destination pointer * @src: The source pointer * @count: The length to be check * * Returns: 0 on same, otherwise 1 * * Compare the source with destination */ static int onenand_check_overwrite(void *dest, void *src, size_t count) { unsigned int *s = (unsigned int *) src; unsigned int *d = (unsigned int *) dest; int i; count >>= 2; for (i = 0; i < count; i++) if ((*s++ ^ *d++) != 0) return 1; return 0; } /** * onenand_data_handle - Handle OneNAND Core and DataRAM * @this: OneNAND device structure * @cmd: The command to be sent * @dataram: Which dataram used * @offset: The offset to OneNAND Core * * Copy data from OneNAND Core to DataRAM (read) * Copy data from DataRAM to OneNAND Core (write) * Erase the OneNAND Core (erase) */ static void onenand_data_handle(struct onenand_chip *this, int cmd, int dataram, unsigned int offset) { struct mtd_info *mtd = &info->mtd; struct onenand_flash *flash = this->priv; int main_offset, spare_offset, die = 0; void __iomem *src; void __iomem *dest; unsigned int i; static int pi_operation; int erasesize, rgn; if (dataram) { main_offset = mtd->writesize; spare_offset = mtd->oobsize; } else { main_offset = 0; spare_offset = 0; } if (pi_operation) { die = readw(this->base + ONENAND_REG_START_ADDRESS2); die >>= ONENAND_DDP_SHIFT; } switch (cmd) { case FLEXONENAND_CMD_PI_ACCESS: pi_operation = 1; break; case ONENAND_CMD_RESET: pi_operation = 0; break; case ONENAND_CMD_READ: src = ONENAND_CORE(flash) + offset; dest = ONENAND_MAIN_AREA(this, main_offset); if (pi_operation) { writew(boundary[die], this->base + ONENAND_DATARAM); break; } memcpy(dest, src, mtd->writesize); /* Fall through */ case ONENAND_CMD_READOOB: src = ONENAND_CORE_SPARE(flash, this, offset); dest = ONENAND_SPARE_AREA(this, spare_offset); memcpy(dest, src, mtd->oobsize); break; case ONENAND_CMD_PROG: src = ONENAND_MAIN_AREA(this, main_offset); dest = ONENAND_CORE(flash) + offset; if (pi_operation) { boundary[die] = readw(this->base + ONENAND_DATARAM); break; } /* To handle partial write */ for (i = 0; i < (1 << mtd->subpage_sft); i++) { int off = i * this->subpagesize; if (!memcmp(src + off, ffchars, this->subpagesize)) continue; if (memcmp(dest + off, ffchars, this->subpagesize) && onenand_check_overwrite(dest + off, src + off, this->subpagesize)) printk(KERN_ERR "over-write happened at 0x%08x\n", offset); memcpy(dest + off, src + off, this->subpagesize); } /* Fall through */ case ONENAND_CMD_PROGOOB: src = ONENAND_SPARE_AREA(this, spare_offset); /* Check all data is 0xff chars */ if (!memcmp(src, ffchars, mtd->oobsize)) break; dest = ONENAND_CORE_SPARE(flash, this, offset); if (memcmp(dest, ffchars, mtd->oobsize) && onenand_check_overwrite(dest, src, mtd->oobsize)) printk(KERN_ERR "OOB: over-write happened at 0x%08x\n", offset); memcpy(dest, src, mtd->oobsize); break; case ONENAND_CMD_ERASE: if (pi_operation) break; if (FLEXONENAND(this)) { rgn = flexonenand_region(mtd, offset); erasesize = mtd->eraseregions[rgn].erasesize; } else erasesize = mtd->erasesize; memset(ONENAND_CORE(flash) + offset, 0xff, erasesize); memset(ONENAND_CORE_SPARE(flash, this, offset), 0xff, (erasesize >> 5)); break; default: break; } } /** * onenand_command_handle - Handle command * @this: OneNAND device structure * @cmd: The command to be sent * * Emulate OneNAND command. */ static void onenand_command_handle(struct onenand_chip *this, int cmd) { unsigned long offset = 0; int block = -1, page = -1, bufferram = -1; int dataram = 0; switch (cmd) { case ONENAND_CMD_UNLOCK: case ONENAND_CMD_LOCK: case ONENAND_CMD_LOCK_TIGHT: case ONENAND_CMD_UNLOCK_ALL: onenand_lock_handle(this, cmd); break; case ONENAND_CMD_BUFFERRAM: /* Do nothing */ return; default: block = (int) readw(this->base + ONENAND_REG_START_ADDRESS1); if (block & (1 << ONENAND_DDP_SHIFT)) { block &= ~(1 << ONENAND_DDP_SHIFT); /* The half of chip block */ block += this->chipsize >> (this->erase_shift + 1); } if (cmd == ONENAND_CMD_ERASE) break; page = (int) readw(this->base + ONENAND_REG_START_ADDRESS8); page = (page >> ONENAND_FPA_SHIFT); bufferram = (int) readw(this->base + ONENAND_REG_START_BUFFER); bufferram >>= ONENAND_BSA_SHIFT; bufferram &= ONENAND_BSA_DATARAM1; dataram = (bufferram == ONENAND_BSA_DATARAM1) ? 1 : 0; break; } if (block != -1) offset = onenand_addr(this, block); if (page != -1) offset += page << this->page_shift; onenand_data_handle(this, cmd, dataram, offset); onenand_update_interrupt(this, cmd); } /** * onenand_writew - [OneNAND Interface] Emulate write operation * @value: value to write * @addr: address to write * * Write OneNAND register with value */ static void onenand_writew(unsigned short value, void __iomem * addr) { struct onenand_chip *this = info->mtd.priv; /* BootRAM handling */ if (addr < this->base + ONENAND_DATARAM) { onenand_bootram_handle(this, value); return; } /* Command handling */ if (addr == this->base + ONENAND_REG_COMMAND) onenand_command_handle(this, value); writew(value, addr); } /** * flash_init - Initialize OneNAND simulator * @flash: OneNAND simulator data strucutres * * Initialize OneNAND simulator. */ static int __init flash_init(struct onenand_flash *flash) { int density, size; int buffer_size; flash->base = kzalloc(131072, GFP_KERNEL); if (!flash->base) { printk(KERN_ERR "Unable to allocate base address.\n"); return -ENOMEM; } density = device_id >> ONENAND_DEVICE_DENSITY_SHIFT; density &= ONENAND_DEVICE_DENSITY_MASK; size = ((16 << 20) << density); ONENAND_CORE(flash) = vmalloc(size + (size >> 5)); if (!ONENAND_CORE(flash)) { printk(KERN_ERR "Unable to allocate nand core address.\n"); kfree(flash->base); return -ENOMEM; } memset(ONENAND_CORE(flash), 0xff, size + (size >> 5)); /* Setup registers */ writew(manuf_id, flash->base + ONENAND_REG_MANUFACTURER_ID); writew(device_id, flash->base + ONENAND_REG_DEVICE_ID); writew(version_id, flash->base + ONENAND_REG_VERSION_ID); writew(technology_id, flash->base + ONENAND_REG_TECHNOLOGY); if (density < 2 && (!CONFIG_FLEXONENAND)) buffer_size = 0x0400; /* 1KiB page */ else buffer_size = 0x0800; /* 2KiB page */ writew(buffer_size, flash->base + ONENAND_REG_DATA_BUFFER_SIZE); return 0; } /** * flash_exit - Clean up OneNAND simulator * @flash: OneNAND simulator data structures * * Clean up OneNAND simulator. */ static void flash_exit(struct onenand_flash *flash) { vfree(ONENAND_CORE(flash)); kfree(flash->base); } static int __init onenand_sim_init(void) { /* Allocate all 0xff chars pointer */ ffchars = kmalloc(MAX_ONENAND_PAGESIZE, GFP_KERNEL); if (!ffchars) { printk(KERN_ERR "Unable to allocate ff chars.\n"); return -ENOMEM; } memset(ffchars, 0xff, MAX_ONENAND_PAGESIZE); /* Allocate OneNAND simulator mtd pointer */ info = kzalloc(sizeof(struct onenand_info), GFP_KERNEL); if (!info) { printk(KERN_ERR "Unable to allocate core structures.\n"); kfree(ffchars); return -ENOMEM; } /* Override write_word function */ info->onenand.write_word = onenand_writew; if (flash_init(&info->flash)) { printk(KERN_ERR "Unable to allocate flash.\n"); kfree(ffchars); kfree(info); return -ENOMEM; } info->parts = os_partitions; info->onenand.base = info->flash.base; info->onenand.priv = &info->flash; info->mtd.name = "OneNAND simulator"; info->mtd.priv = &info->onenand; info->mtd.owner = THIS_MODULE; if (onenand_scan(&info->mtd, 1)) { flash_exit(&info->flash); kfree(ffchars); kfree(info); return -ENXIO; } mtd_device_register(&info->mtd, info->parts, ARRAY_SIZE(os_partitions)); return 0; } static void __exit onenand_sim_exit(void) { struct onenand_chip *this = info->mtd.priv; struct onenand_flash *flash = this->priv; onenand_release(&info->mtd); flash_exit(flash); kfree(ffchars); kfree(info); } module_init(onenand_sim_init); module_exit(onenand_sim_exit); MODULE_AUTHOR("Kyungmin Park <kyungmin.park@samsung.com>"); MODULE_DESCRIPTION("The OneNAND flash simulator"); MODULE_LICENSE("GPL");
gpl-2.0
Bdaman80/BDA-ACTV
arch/powerpc/boot/oflib.c
12029
4906
/* * Copyright (C) Paul Mackerras 1997. * * 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 <stddef.h> #include "types.h" #include "elf.h" #include "string.h" #include "stdio.h" #include "page.h" #include "ops.h" #include "of.h" static int (*prom) (void *); void of_init(void *promptr) { prom = (int (*)(void *))promptr; } int of_call_prom(const char *service, int nargs, int nret, ...) { int i; struct prom_args { const char *service; int nargs; int nret; unsigned int args[12]; } args; va_list list; args.service = service; args.nargs = nargs; args.nret = nret; va_start(list, nret); for (i = 0; i < nargs; i++) args.args[i] = va_arg(list, unsigned int); va_end(list); for (i = 0; i < nret; i++) args.args[nargs+i] = 0; if (prom(&args) < 0) return -1; return (nret > 0)? args.args[nargs]: 0; } static int of_call_prom_ret(const char *service, int nargs, int nret, unsigned int *rets, ...) { int i; struct prom_args { const char *service; int nargs; int nret; unsigned int args[12]; } args; va_list list; args.service = service; args.nargs = nargs; args.nret = nret; va_start(list, rets); for (i = 0; i < nargs; i++) args.args[i] = va_arg(list, unsigned int); va_end(list); for (i = 0; i < nret; i++) args.args[nargs+i] = 0; if (prom(&args) < 0) return -1; if (rets != (void *) 0) for (i = 1; i < nret; ++i) rets[i-1] = args.args[nargs+i]; return (nret > 0)? args.args[nargs]: 0; } /* returns true if s2 is a prefix of s1 */ static int string_match(const char *s1, const char *s2) { for (; *s2; ++s2) if (*s1++ != *s2) return 0; return 1; } /* * Older OF's require that when claiming a specific range of addresses, * we claim the physical space in the /memory node and the virtual * space in the chosen mmu node, and then do a map operation to * map virtual to physical. */ static int need_map = -1; static ihandle chosen_mmu; static phandle memory; static int check_of_version(void) { phandle oprom, chosen; char version[64]; oprom = of_finddevice("/openprom"); if (oprom == (phandle) -1) return 0; if (of_getprop(oprom, "model", version, sizeof(version)) <= 0) return 0; version[sizeof(version)-1] = 0; printf("OF version = '%s'\r\n", version); if (!string_match(version, "Open Firmware, 1.") && !string_match(version, "FirmWorks,3.")) return 0; chosen = of_finddevice("/chosen"); if (chosen == (phandle) -1) { chosen = of_finddevice("/chosen@0"); if (chosen == (phandle) -1) { printf("no chosen\n"); return 0; } } if (of_getprop(chosen, "mmu", &chosen_mmu, sizeof(chosen_mmu)) <= 0) { printf("no mmu\n"); return 0; } memory = (ihandle) of_call_prom("open", 1, 1, "/memory"); if (memory == (ihandle) -1) { memory = (ihandle) of_call_prom("open", 1, 1, "/memory@0"); if (memory == (ihandle) -1) { printf("no memory node\n"); return 0; } } printf("old OF detected\r\n"); return 1; } void *of_claim(unsigned long virt, unsigned long size, unsigned long align) { int ret; unsigned int result; if (need_map < 0) need_map = check_of_version(); if (align || !need_map) return (void *) of_call_prom("claim", 3, 1, virt, size, align); ret = of_call_prom_ret("call-method", 5, 2, &result, "claim", memory, align, size, virt); if (ret != 0 || result == -1) return (void *) -1; ret = of_call_prom_ret("call-method", 5, 2, &result, "claim", chosen_mmu, align, size, virt); /* 0x12 == coherent + read/write */ ret = of_call_prom("call-method", 6, 1, "map", chosen_mmu, 0x12, size, virt, virt); return (void *) virt; } void *of_vmlinux_alloc(unsigned long size) { unsigned long start = (unsigned long)_start, end = (unsigned long)_end; void *addr; void *p; /* With some older POWER4 firmware we need to claim the area the kernel * will reside in. Newer firmwares don't need this so we just ignore * the return value. */ addr = of_claim(start, end - start, 0); printf("Trying to claim from 0x%lx to 0x%lx (0x%lx) got %p\r\n", start, end, end - start, addr); p = malloc(size); if (!p) fatal("Can't allocate memory for kernel image!\n\r"); return p; } void of_exit(void) { of_call_prom("exit", 0, 0); } /* * OF device tree routines */ void *of_finddevice(const char *name) { return (phandle) of_call_prom("finddevice", 1, 1, name); } int of_getprop(const void *phandle, const char *name, void *buf, const int buflen) { return of_call_prom("getprop", 4, 1, phandle, name, buf, buflen); } int of_setprop(const void *phandle, const char *name, const void *buf, const int buflen) { return of_call_prom("setprop", 4, 1, phandle, name, buf, buflen); }
gpl-2.0
Dinjesk/android_kernel_oneplus_msm8996
net/bridge/netfilter/nft_reject_bridge.c
254
10735
/* * Copyright (c) 2014 Pablo Neira Ayuso <pablo@netfilter.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/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/netlink.h> #include <linux/netfilter.h> #include <linux/netfilter/nf_tables.h> #include <net/netfilter/nf_tables.h> #include <net/netfilter/nft_reject.h> #include <net/netfilter/ipv4/nf_reject.h> #include <net/netfilter/ipv6/nf_reject.h> #include <linux/ip.h> #include <net/ip.h> #include <net/ip6_checksum.h> #include <linux/netfilter_bridge.h> #include "../br_private.h" static void nft_reject_br_push_etherhdr(struct sk_buff *oldskb, struct sk_buff *nskb) { struct ethhdr *eth; eth = (struct ethhdr *)skb_push(nskb, ETH_HLEN); skb_reset_mac_header(nskb); ether_addr_copy(eth->h_source, eth_hdr(oldskb)->h_dest); ether_addr_copy(eth->h_dest, eth_hdr(oldskb)->h_source); eth->h_proto = eth_hdr(oldskb)->h_proto; skb_pull(nskb, ETH_HLEN); } static int nft_reject_iphdr_validate(struct sk_buff *oldskb) { struct iphdr *iph; u32 len; if (!pskb_may_pull(oldskb, sizeof(struct iphdr))) return 0; iph = ip_hdr(oldskb); if (iph->ihl < 5 || iph->version != 4) return 0; len = ntohs(iph->tot_len); if (oldskb->len < len) return 0; else if (len < (iph->ihl*4)) return 0; if (!pskb_may_pull(oldskb, iph->ihl*4)) return 0; return 1; } static void nft_reject_br_send_v4_tcp_reset(struct sk_buff *oldskb, int hook) { struct sk_buff *nskb; struct iphdr *niph; const struct tcphdr *oth; struct tcphdr _oth; if (!nft_reject_iphdr_validate(oldskb)) return; oth = nf_reject_ip_tcphdr_get(oldskb, &_oth, hook); if (!oth) return; nskb = alloc_skb(sizeof(struct iphdr) + sizeof(struct tcphdr) + LL_MAX_HEADER, GFP_ATOMIC); if (!nskb) return; skb_reserve(nskb, LL_MAX_HEADER); niph = nf_reject_iphdr_put(nskb, oldskb, IPPROTO_TCP, sysctl_ip_default_ttl); nf_reject_ip_tcphdr_put(nskb, oldskb, oth); niph->ttl = sysctl_ip_default_ttl; niph->tot_len = htons(nskb->len); ip_send_check(niph); nft_reject_br_push_etherhdr(oldskb, nskb); br_deliver(br_port_get_rcu(oldskb->dev), nskb); } static void nft_reject_br_send_v4_unreach(struct sk_buff *oldskb, int hook, u8 code) { struct sk_buff *nskb; struct iphdr *niph; struct icmphdr *icmph; unsigned int len; void *payload; __wsum csum; if (!nft_reject_iphdr_validate(oldskb)) return; /* IP header checks: fragment. */ if (ip_hdr(oldskb)->frag_off & htons(IP_OFFSET)) return; /* RFC says return as much as we can without exceeding 576 bytes. */ len = min_t(unsigned int, 536, oldskb->len); if (!pskb_may_pull(oldskb, len)) return; if (nf_ip_checksum(oldskb, hook, ip_hdrlen(oldskb), 0)) return; nskb = alloc_skb(sizeof(struct iphdr) + sizeof(struct icmphdr) + LL_MAX_HEADER + len, GFP_ATOMIC); if (!nskb) return; skb_reserve(nskb, LL_MAX_HEADER); niph = nf_reject_iphdr_put(nskb, oldskb, IPPROTO_ICMP, sysctl_ip_default_ttl); skb_reset_transport_header(nskb); icmph = (struct icmphdr *)skb_put(nskb, sizeof(struct icmphdr)); memset(icmph, 0, sizeof(*icmph)); icmph->type = ICMP_DEST_UNREACH; icmph->code = code; payload = skb_put(nskb, len); memcpy(payload, skb_network_header(oldskb), len); csum = csum_partial((void *)icmph, len + sizeof(struct icmphdr), 0); icmph->checksum = csum_fold(csum); niph->tot_len = htons(nskb->len); ip_send_check(niph); nft_reject_br_push_etherhdr(oldskb, nskb); br_deliver(br_port_get_rcu(oldskb->dev), nskb); } static int nft_reject_ip6hdr_validate(struct sk_buff *oldskb) { struct ipv6hdr *hdr; u32 pkt_len; if (!pskb_may_pull(oldskb, sizeof(struct ipv6hdr))) return 0; hdr = ipv6_hdr(oldskb); if (hdr->version != 6) return 0; pkt_len = ntohs(hdr->payload_len); if (pkt_len + sizeof(struct ipv6hdr) > oldskb->len) return 0; return 1; } static void nft_reject_br_send_v6_tcp_reset(struct net *net, struct sk_buff *oldskb, int hook) { struct sk_buff *nskb; const struct tcphdr *oth; struct tcphdr _oth; unsigned int otcplen; struct ipv6hdr *nip6h; if (!nft_reject_ip6hdr_validate(oldskb)) return; oth = nf_reject_ip6_tcphdr_get(oldskb, &_oth, &otcplen, hook); if (!oth) return; nskb = alloc_skb(sizeof(struct ipv6hdr) + sizeof(struct tcphdr) + LL_MAX_HEADER, GFP_ATOMIC); if (!nskb) return; skb_reserve(nskb, LL_MAX_HEADER); nip6h = nf_reject_ip6hdr_put(nskb, oldskb, IPPROTO_TCP, net->ipv6.devconf_all->hop_limit); nf_reject_ip6_tcphdr_put(nskb, oldskb, oth, otcplen); nip6h->payload_len = htons(nskb->len - sizeof(struct ipv6hdr)); nft_reject_br_push_etherhdr(oldskb, nskb); br_deliver(br_port_get_rcu(oldskb->dev), nskb); } static void nft_reject_br_send_v6_unreach(struct net *net, struct sk_buff *oldskb, int hook, u8 code) { struct sk_buff *nskb; struct ipv6hdr *nip6h; struct icmp6hdr *icmp6h; unsigned int len; void *payload; if (!nft_reject_ip6hdr_validate(oldskb)) return; /* Include "As much of invoking packet as possible without the ICMPv6 * packet exceeding the minimum IPv6 MTU" in the ICMP payload. */ len = min_t(unsigned int, 1220, oldskb->len); if (!pskb_may_pull(oldskb, len)) return; nskb = alloc_skb(sizeof(struct iphdr) + sizeof(struct icmp6hdr) + LL_MAX_HEADER + len, GFP_ATOMIC); if (!nskb) return; skb_reserve(nskb, LL_MAX_HEADER); nip6h = nf_reject_ip6hdr_put(nskb, oldskb, IPPROTO_ICMPV6, net->ipv6.devconf_all->hop_limit); skb_reset_transport_header(nskb); icmp6h = (struct icmp6hdr *)skb_put(nskb, sizeof(struct icmp6hdr)); memset(icmp6h, 0, sizeof(*icmp6h)); icmp6h->icmp6_type = ICMPV6_DEST_UNREACH; icmp6h->icmp6_code = code; payload = skb_put(nskb, len); memcpy(payload, skb_network_header(oldskb), len); nip6h->payload_len = htons(nskb->len - sizeof(struct ipv6hdr)); icmp6h->icmp6_cksum = csum_ipv6_magic(&nip6h->saddr, &nip6h->daddr, nskb->len - sizeof(struct ipv6hdr), IPPROTO_ICMPV6, csum_partial(icmp6h, nskb->len - sizeof(struct ipv6hdr), 0)); nft_reject_br_push_etherhdr(oldskb, nskb); br_deliver(br_port_get_rcu(oldskb->dev), nskb); } static void nft_reject_bridge_eval(const struct nft_expr *expr, struct nft_data data[NFT_REG_MAX + 1], const struct nft_pktinfo *pkt) { struct nft_reject *priv = nft_expr_priv(expr); struct net *net = dev_net((pkt->in != NULL) ? pkt->in : pkt->out); const unsigned char *dest = eth_hdr(pkt->skb)->h_dest; if (is_broadcast_ether_addr(dest) || is_multicast_ether_addr(dest)) goto out; switch (eth_hdr(pkt->skb)->h_proto) { case htons(ETH_P_IP): switch (priv->type) { case NFT_REJECT_ICMP_UNREACH: nft_reject_br_send_v4_unreach(pkt->skb, pkt->ops->hooknum, priv->icmp_code); break; case NFT_REJECT_TCP_RST: nft_reject_br_send_v4_tcp_reset(pkt->skb, pkt->ops->hooknum); break; case NFT_REJECT_ICMPX_UNREACH: nft_reject_br_send_v4_unreach(pkt->skb, pkt->ops->hooknum, nft_reject_icmp_code(priv->icmp_code)); break; } break; case htons(ETH_P_IPV6): switch (priv->type) { case NFT_REJECT_ICMP_UNREACH: nft_reject_br_send_v6_unreach(net, pkt->skb, pkt->ops->hooknum, priv->icmp_code); break; case NFT_REJECT_TCP_RST: nft_reject_br_send_v6_tcp_reset(net, pkt->skb, pkt->ops->hooknum); break; case NFT_REJECT_ICMPX_UNREACH: nft_reject_br_send_v6_unreach(net, pkt->skb, pkt->ops->hooknum, nft_reject_icmpv6_code(priv->icmp_code)); break; } break; default: /* No explicit way to reject this protocol, drop it. */ break; } out: data[NFT_REG_VERDICT].verdict = NF_DROP; } static int nft_reject_bridge_validate_hooks(const struct nft_chain *chain) { struct nft_base_chain *basechain; if (chain->flags & NFT_BASE_CHAIN) { basechain = nft_base_chain(chain); switch (basechain->ops[0].hooknum) { case NF_BR_PRE_ROUTING: case NF_BR_LOCAL_IN: break; default: return -EOPNOTSUPP; } } return 0; } static int nft_reject_bridge_init(const struct nft_ctx *ctx, const struct nft_expr *expr, const struct nlattr * const tb[]) { struct nft_reject *priv = nft_expr_priv(expr); int icmp_code, err; err = nft_reject_bridge_validate_hooks(ctx->chain); if (err < 0) return err; if (tb[NFTA_REJECT_TYPE] == NULL) return -EINVAL; priv->type = ntohl(nla_get_be32(tb[NFTA_REJECT_TYPE])); switch (priv->type) { case NFT_REJECT_ICMP_UNREACH: case NFT_REJECT_ICMPX_UNREACH: if (tb[NFTA_REJECT_ICMP_CODE] == NULL) return -EINVAL; icmp_code = nla_get_u8(tb[NFTA_REJECT_ICMP_CODE]); if (priv->type == NFT_REJECT_ICMPX_UNREACH && icmp_code > NFT_REJECT_ICMPX_MAX) return -EINVAL; priv->icmp_code = icmp_code; break; case NFT_REJECT_TCP_RST: break; default: return -EINVAL; } return 0; } static int nft_reject_bridge_dump(struct sk_buff *skb, const struct nft_expr *expr) { const struct nft_reject *priv = nft_expr_priv(expr); if (nla_put_be32(skb, NFTA_REJECT_TYPE, htonl(priv->type))) goto nla_put_failure; switch (priv->type) { case NFT_REJECT_ICMP_UNREACH: case NFT_REJECT_ICMPX_UNREACH: if (nla_put_u8(skb, NFTA_REJECT_ICMP_CODE, priv->icmp_code)) goto nla_put_failure; break; } return 0; nla_put_failure: return -1; } static int nft_reject_bridge_validate(const struct nft_ctx *ctx, const struct nft_expr *expr, const struct nft_data **data) { return nft_reject_bridge_validate_hooks(ctx->chain); } static struct nft_expr_type nft_reject_bridge_type; static const struct nft_expr_ops nft_reject_bridge_ops = { .type = &nft_reject_bridge_type, .size = NFT_EXPR_SIZE(sizeof(struct nft_reject)), .eval = nft_reject_bridge_eval, .init = nft_reject_bridge_init, .dump = nft_reject_bridge_dump, .validate = nft_reject_bridge_validate, }; static struct nft_expr_type nft_reject_bridge_type __read_mostly = { .family = NFPROTO_BRIDGE, .name = "reject", .ops = &nft_reject_bridge_ops, .policy = nft_reject_policy, .maxattr = NFTA_REJECT_MAX, .owner = THIS_MODULE, }; static int __init nft_reject_bridge_module_init(void) { return nft_register_expr(&nft_reject_bridge_type); } static void __exit nft_reject_bridge_module_exit(void) { nft_unregister_expr(&nft_reject_bridge_type); } module_init(nft_reject_bridge_module_init); module_exit(nft_reject_bridge_module_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Pablo Neira Ayuso <pablo@netfilter.org>"); MODULE_ALIAS_NFT_AF_EXPR(AF_BRIDGE, "reject");
gpl-2.0
matachi/linux-2.6.32.y
sound/soc/s3c24xx/s3c24xx_simtec_tlv320aic23.c
510
3639
/* sound/soc/s3c24xx/s3c24xx_simtec_tlv320aic23.c * * Copyright 2009 Simtec Electronics * * 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/module.h> #include <linux/clk.h> #include <linux/platform_device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <plat/audio-simtec.h> #include "s3c24xx-pcm.h" #include "s3c24xx-i2s.h" #include "s3c24xx_simtec.h" #include "../codecs/tlv320aic23.h" /* supported machines: * * Machine Connections AMP * ------- ----------- --- * BAST MIC, HPOUT, LOUT, LIN TPA2001D1 (HPOUTL,R) (gain hardwired) * VR1000 HPOUT, LIN None * VR2000 LIN, LOUT, MIC, HP LM4871 (HPOUTL,R) * DePicture LIN, LOUT, MIC, HP LM4871 (HPOUTL,R) * Anubis LIN, LOUT, MIC, HP TPA2001D1 (HPOUTL,R) */ static const struct snd_soc_dapm_widget dapm_widgets[] = { SND_SOC_DAPM_HP("Headphone Jack", NULL), SND_SOC_DAPM_LINE("Line In", NULL), SND_SOC_DAPM_LINE("Line Out", NULL), SND_SOC_DAPM_MIC("Mic Jack", NULL), }; static const struct snd_soc_dapm_route base_map[] = { { "Headphone Jack", NULL, "LHPOUT"}, { "Headphone Jack", NULL, "RHPOUT"}, { "Line Out", NULL, "LOUT" }, { "Line Out", NULL, "ROUT" }, { "LLINEIN", NULL, "Line In"}, { "RLINEIN", NULL, "Line In"}, { "MICIN", NULL, "Mic Jack"}, }; /** * simtec_tlv320aic23_init - initialise and add controls * @codec; The codec instance to attach to. * * Attach our controls and configure the necessary codec * mappings for our sound card instance. */ static int simtec_tlv320aic23_init(struct snd_soc_codec *codec) { snd_soc_dapm_new_controls(codec, dapm_widgets, ARRAY_SIZE(dapm_widgets)); snd_soc_dapm_add_routes(codec, base_map, ARRAY_SIZE(base_map)); snd_soc_dapm_enable_pin(codec, "Headphone Jack"); snd_soc_dapm_enable_pin(codec, "Line In"); snd_soc_dapm_enable_pin(codec, "Line Out"); snd_soc_dapm_enable_pin(codec, "Mic Jack"); simtec_audio_init(codec); snd_soc_dapm_sync(codec); return 0; } static struct snd_soc_dai_link simtec_dai_aic23 = { .name = "tlv320aic23", .stream_name = "TLV320AIC23", .cpu_dai = &s3c24xx_i2s_dai, .codec_dai = &tlv320aic23_dai, .init = simtec_tlv320aic23_init, }; /* simtec audio machine driver */ static struct snd_soc_card snd_soc_machine_simtec_aic23 = { .name = "Simtec", .platform = &s3c24xx_soc_platform, .dai_link = &simtec_dai_aic23, .num_links = 1, }; /* simtec audio subsystem */ static struct snd_soc_device simtec_snd_devdata_aic23 = { .card = &snd_soc_machine_simtec_aic23, .codec_dev = &soc_codec_dev_tlv320aic23, }; static int __devinit simtec_audio_tlv320aic23_probe(struct platform_device *pd) { return simtec_audio_core_probe(pd, &simtec_snd_devdata_aic23); } static struct platform_driver simtec_audio_tlv320aic23_platdrv = { .driver = { .owner = THIS_MODULE, .name = "s3c24xx-simtec-tlv320aic23", .pm = simtec_audio_pm, }, .probe = simtec_audio_tlv320aic23_probe, .remove = __devexit_p(simtec_audio_remove), }; MODULE_ALIAS("platform:s3c24xx-simtec-tlv320aic23"); static int __init simtec_tlv320aic23_modinit(void) { return platform_driver_register(&simtec_audio_tlv320aic23_platdrv); } static void __exit simtec_tlv320aic23_modexit(void) { platform_driver_unregister(&simtec_audio_tlv320aic23_platdrv); } module_init(simtec_tlv320aic23_modinit); module_exit(simtec_tlv320aic23_modexit); MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>"); MODULE_DESCRIPTION("ALSA SoC Simtec Audio support"); MODULE_LICENSE("GPL");
gpl-2.0
Shabbypenguin/Kettle_Corn_Kernel
fs/coda/file.c
2558
6186
/* * File operations for Coda. * Original version: (C) 1996 Peter Braam * Rewritten for Linux 2.1: (C) 1997 Carnegie Mellon University * * Carnegie Mellon encourages users of this code to contribute improvements * to the Coda project. Contact Peter Braam <coda@cs.cmu.edu>. */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/time.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/stat.h> #include <linux/cred.h> #include <linux/errno.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <linux/coda.h> #include <linux/coda_psdev.h> #include "coda_linux.h" #include "coda_int.h" static ssize_t coda_file_read(struct file *coda_file, char __user *buf, size_t count, loff_t *ppos) { struct coda_file_info *cfi; struct file *host_file; cfi = CODA_FTOC(coda_file); BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC); host_file = cfi->cfi_container; if (!host_file->f_op || !host_file->f_op->read) return -EINVAL; return host_file->f_op->read(host_file, buf, count, ppos); } static ssize_t coda_file_splice_read(struct file *coda_file, loff_t *ppos, struct pipe_inode_info *pipe, size_t count, unsigned int flags) { ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); struct coda_file_info *cfi; struct file *host_file; cfi = CODA_FTOC(coda_file); BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC); host_file = cfi->cfi_container; splice_read = host_file->f_op->splice_read; if (!splice_read) splice_read = default_file_splice_read; return splice_read(host_file, ppos, pipe, count, flags); } static ssize_t coda_file_write(struct file *coda_file, const char __user *buf, size_t count, loff_t *ppos) { struct inode *host_inode, *coda_inode = coda_file->f_path.dentry->d_inode; struct coda_file_info *cfi; struct file *host_file; ssize_t ret; cfi = CODA_FTOC(coda_file); BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC); host_file = cfi->cfi_container; if (!host_file->f_op || !host_file->f_op->write) return -EINVAL; host_inode = host_file->f_path.dentry->d_inode; mutex_lock(&coda_inode->i_mutex); ret = host_file->f_op->write(host_file, buf, count, ppos); coda_inode->i_size = host_inode->i_size; coda_inode->i_blocks = (coda_inode->i_size + 511) >> 9; coda_inode->i_mtime = coda_inode->i_ctime = CURRENT_TIME_SEC; mutex_unlock(&coda_inode->i_mutex); return ret; } static int coda_file_mmap(struct file *coda_file, struct vm_area_struct *vma) { struct coda_file_info *cfi; struct coda_inode_info *cii; struct file *host_file; struct inode *coda_inode, *host_inode; cfi = CODA_FTOC(coda_file); BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC); host_file = cfi->cfi_container; if (!host_file->f_op || !host_file->f_op->mmap) return -ENODEV; coda_inode = coda_file->f_path.dentry->d_inode; host_inode = host_file->f_path.dentry->d_inode; cii = ITOC(coda_inode); spin_lock(&cii->c_lock); coda_file->f_mapping = host_file->f_mapping; if (coda_inode->i_mapping == &coda_inode->i_data) coda_inode->i_mapping = host_inode->i_mapping; /* only allow additional mmaps as long as userspace isn't changing * the container file on us! */ else if (coda_inode->i_mapping != host_inode->i_mapping) { spin_unlock(&cii->c_lock); return -EBUSY; } /* keep track of how often the coda_inode/host_file has been mmapped */ cii->c_mapcount++; cfi->cfi_mapcount++; spin_unlock(&cii->c_lock); return host_file->f_op->mmap(host_file, vma); } int coda_open(struct inode *coda_inode, struct file *coda_file) { struct file *host_file = NULL; int error; unsigned short flags = coda_file->f_flags & (~O_EXCL); unsigned short coda_flags = coda_flags_to_cflags(flags); struct coda_file_info *cfi; cfi = kmalloc(sizeof(struct coda_file_info), GFP_KERNEL); if (!cfi) return -ENOMEM; error = venus_open(coda_inode->i_sb, coda_i2f(coda_inode), coda_flags, &host_file); if (!host_file) error = -EIO; if (error) { kfree(cfi); return error; } host_file->f_flags |= coda_file->f_flags & (O_APPEND | O_SYNC); cfi->cfi_magic = CODA_MAGIC; cfi->cfi_mapcount = 0; cfi->cfi_container = host_file; BUG_ON(coda_file->private_data != NULL); coda_file->private_data = cfi; return 0; } int coda_release(struct inode *coda_inode, struct file *coda_file) { unsigned short flags = (coda_file->f_flags) & (~O_EXCL); unsigned short coda_flags = coda_flags_to_cflags(flags); struct coda_file_info *cfi; struct coda_inode_info *cii; struct inode *host_inode; int err; cfi = CODA_FTOC(coda_file); BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC); err = venus_close(coda_inode->i_sb, coda_i2f(coda_inode), coda_flags, coda_file->f_cred->fsuid); host_inode = cfi->cfi_container->f_path.dentry->d_inode; cii = ITOC(coda_inode); /* did we mmap this file? */ spin_lock(&cii->c_lock); if (coda_inode->i_mapping == &host_inode->i_data) { cii->c_mapcount -= cfi->cfi_mapcount; if (!cii->c_mapcount) coda_inode->i_mapping = &coda_inode->i_data; } spin_unlock(&cii->c_lock); fput(cfi->cfi_container); kfree(coda_file->private_data); coda_file->private_data = NULL; /* VFS fput ignores the return value from file_operations->release, so * there is no use returning an error here */ return 0; } int coda_fsync(struct file *coda_file, int datasync) { struct file *host_file; struct inode *coda_inode = coda_file->f_path.dentry->d_inode; struct coda_file_info *cfi; int err; if (!(S_ISREG(coda_inode->i_mode) || S_ISDIR(coda_inode->i_mode) || S_ISLNK(coda_inode->i_mode))) return -EINVAL; cfi = CODA_FTOC(coda_file); BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC); host_file = cfi->cfi_container; err = vfs_fsync(host_file, datasync); if (!err && !datasync) err = venus_fsync(coda_inode->i_sb, coda_i2f(coda_inode)); return err; } const struct file_operations coda_file_operations = { .llseek = generic_file_llseek, .read = coda_file_read, .write = coda_file_write, .mmap = coda_file_mmap, .open = coda_open, .release = coda_release, .fsync = coda_fsync, .splice_read = coda_file_splice_read, };
gpl-2.0
Stuxnet-Kernel/kernel_g3
net/ceph/mon_client.c
3326
25343
#include <linux/ceph/ceph_debug.h> #include <linux/module.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/random.h> #include <linux/sched.h> #include <linux/ceph/mon_client.h> #include <linux/ceph/libceph.h> #include <linux/ceph/debugfs.h> #include <linux/ceph/decode.h> #include <linux/ceph/auth.h> /* * Interact with Ceph monitor cluster. Handle requests for new map * versions, and periodically resend as needed. Also implement * statfs() and umount(). * * A small cluster of Ceph "monitors" are responsible for managing critical * cluster configuration and state information. An odd number (e.g., 3, 5) * of cmon daemons use a modified version of the Paxos part-time parliament * algorithm to manage the MDS map (mds cluster membership), OSD map, and * list of clients who have mounted the file system. * * We maintain an open, active session with a monitor at all times in order to * receive timely MDSMap updates. We periodically send a keepalive byte on the * TCP socket to ensure we detect a failure. If the connection does break, we * randomly hunt for a new monitor. Once the connection is reestablished, we * resend any outstanding requests. */ static const struct ceph_connection_operations mon_con_ops; static int __validate_auth(struct ceph_mon_client *monc); /* * Decode a monmap blob (e.g., during mount). */ struct ceph_monmap *ceph_monmap_decode(void *p, void *end) { struct ceph_monmap *m = NULL; int i, err = -EINVAL; struct ceph_fsid fsid; u32 epoch, num_mon; u16 version; u32 len; ceph_decode_32_safe(&p, end, len, bad); ceph_decode_need(&p, end, len, bad); dout("monmap_decode %p %p len %d\n", p, end, (int)(end-p)); ceph_decode_16_safe(&p, end, version, bad); ceph_decode_need(&p, end, sizeof(fsid) + 2*sizeof(u32), bad); ceph_decode_copy(&p, &fsid, sizeof(fsid)); epoch = ceph_decode_32(&p); num_mon = ceph_decode_32(&p); ceph_decode_need(&p, end, num_mon*sizeof(m->mon_inst[0]), bad); if (num_mon >= CEPH_MAX_MON) goto bad; m = kmalloc(sizeof(*m) + sizeof(m->mon_inst[0])*num_mon, GFP_NOFS); if (m == NULL) return ERR_PTR(-ENOMEM); m->fsid = fsid; m->epoch = epoch; m->num_mon = num_mon; ceph_decode_copy(&p, m->mon_inst, num_mon*sizeof(m->mon_inst[0])); for (i = 0; i < num_mon; i++) ceph_decode_addr(&m->mon_inst[i].addr); dout("monmap_decode epoch %d, num_mon %d\n", m->epoch, m->num_mon); for (i = 0; i < m->num_mon; i++) dout("monmap_decode mon%d is %s\n", i, ceph_pr_addr(&m->mon_inst[i].addr.in_addr)); return m; bad: dout("monmap_decode failed with %d\n", err); kfree(m); return ERR_PTR(err); } /* * return true if *addr is included in the monmap. */ int ceph_monmap_contains(struct ceph_monmap *m, struct ceph_entity_addr *addr) { int i; for (i = 0; i < m->num_mon; i++) if (memcmp(addr, &m->mon_inst[i].addr, sizeof(*addr)) == 0) return 1; return 0; } /* * Send an auth request. */ static void __send_prepared_auth_request(struct ceph_mon_client *monc, int len) { monc->pending_auth = 1; monc->m_auth->front.iov_len = len; monc->m_auth->hdr.front_len = cpu_to_le32(len); ceph_con_revoke(monc->con, monc->m_auth); ceph_msg_get(monc->m_auth); /* keep our ref */ ceph_con_send(monc->con, monc->m_auth); } /* * Close monitor session, if any. */ static void __close_session(struct ceph_mon_client *monc) { dout("__close_session closing mon%d\n", monc->cur_mon); ceph_con_revoke(monc->con, monc->m_auth); ceph_con_close(monc->con); monc->cur_mon = -1; monc->pending_auth = 0; ceph_auth_reset(monc->auth); } /* * Open a session with a (new) monitor. */ static int __open_session(struct ceph_mon_client *monc) { char r; int ret; if (monc->cur_mon < 0) { get_random_bytes(&r, 1); monc->cur_mon = r % monc->monmap->num_mon; dout("open_session num=%d r=%d -> mon%d\n", monc->monmap->num_mon, r, monc->cur_mon); monc->sub_sent = 0; monc->sub_renew_after = jiffies; /* i.e., expired */ monc->want_next_osdmap = !!monc->want_next_osdmap; dout("open_session mon%d opening\n", monc->cur_mon); monc->con->peer_name.type = CEPH_ENTITY_TYPE_MON; monc->con->peer_name.num = cpu_to_le64(monc->cur_mon); ceph_con_open(monc->con, &monc->monmap->mon_inst[monc->cur_mon].addr); /* initiatiate authentication handshake */ ret = ceph_auth_build_hello(monc->auth, monc->m_auth->front.iov_base, monc->m_auth->front_max); __send_prepared_auth_request(monc, ret); } else { dout("open_session mon%d already open\n", monc->cur_mon); } return 0; } static bool __sub_expired(struct ceph_mon_client *monc) { return time_after_eq(jiffies, monc->sub_renew_after); } /* * Reschedule delayed work timer. */ static void __schedule_delayed(struct ceph_mon_client *monc) { unsigned delay; if (monc->cur_mon < 0 || __sub_expired(monc)) delay = 10 * HZ; else delay = 20 * HZ; dout("__schedule_delayed after %u\n", delay); schedule_delayed_work(&monc->delayed_work, delay); } /* * Send subscribe request for mdsmap and/or osdmap. */ static void __send_subscribe(struct ceph_mon_client *monc) { dout("__send_subscribe sub_sent=%u exp=%u want_osd=%d\n", (unsigned)monc->sub_sent, __sub_expired(monc), monc->want_next_osdmap); if ((__sub_expired(monc) && !monc->sub_sent) || monc->want_next_osdmap == 1) { struct ceph_msg *msg = monc->m_subscribe; struct ceph_mon_subscribe_item *i; void *p, *end; int num; p = msg->front.iov_base; end = p + msg->front_max; num = 1 + !!monc->want_next_osdmap + !!monc->want_mdsmap; ceph_encode_32(&p, num); if (monc->want_next_osdmap) { dout("__send_subscribe to 'osdmap' %u\n", (unsigned)monc->have_osdmap); ceph_encode_string(&p, end, "osdmap", 6); i = p; i->have = cpu_to_le64(monc->have_osdmap); i->onetime = 1; p += sizeof(*i); monc->want_next_osdmap = 2; /* requested */ } if (monc->want_mdsmap) { dout("__send_subscribe to 'mdsmap' %u+\n", (unsigned)monc->have_mdsmap); ceph_encode_string(&p, end, "mdsmap", 6); i = p; i->have = cpu_to_le64(monc->have_mdsmap); i->onetime = 0; p += sizeof(*i); } ceph_encode_string(&p, end, "monmap", 6); i = p; i->have = 0; i->onetime = 0; p += sizeof(*i); msg->front.iov_len = p - msg->front.iov_base; msg->hdr.front_len = cpu_to_le32(msg->front.iov_len); ceph_con_revoke(monc->con, msg); ceph_con_send(monc->con, ceph_msg_get(msg)); monc->sub_sent = jiffies | 1; /* never 0 */ } } static void handle_subscribe_ack(struct ceph_mon_client *monc, struct ceph_msg *msg) { unsigned seconds; struct ceph_mon_subscribe_ack *h = msg->front.iov_base; if (msg->front.iov_len < sizeof(*h)) goto bad; seconds = le32_to_cpu(h->duration); mutex_lock(&monc->mutex); if (monc->hunting) { pr_info("mon%d %s session established\n", monc->cur_mon, ceph_pr_addr(&monc->con->peer_addr.in_addr)); monc->hunting = false; } dout("handle_subscribe_ack after %d seconds\n", seconds); monc->sub_renew_after = monc->sub_sent + (seconds >> 1)*HZ - 1; monc->sub_sent = 0; mutex_unlock(&monc->mutex); return; bad: pr_err("got corrupt subscribe-ack msg\n"); ceph_msg_dump(msg); } /* * Keep track of which maps we have */ int ceph_monc_got_mdsmap(struct ceph_mon_client *monc, u32 got) { mutex_lock(&monc->mutex); monc->have_mdsmap = got; mutex_unlock(&monc->mutex); return 0; } EXPORT_SYMBOL(ceph_monc_got_mdsmap); int ceph_monc_got_osdmap(struct ceph_mon_client *monc, u32 got) { mutex_lock(&monc->mutex); monc->have_osdmap = got; monc->want_next_osdmap = 0; mutex_unlock(&monc->mutex); return 0; } /* * Register interest in the next osdmap */ void ceph_monc_request_next_osdmap(struct ceph_mon_client *monc) { dout("request_next_osdmap have %u\n", monc->have_osdmap); mutex_lock(&monc->mutex); if (!monc->want_next_osdmap) monc->want_next_osdmap = 1; if (monc->want_next_osdmap < 2) __send_subscribe(monc); mutex_unlock(&monc->mutex); } /* * */ int ceph_monc_open_session(struct ceph_mon_client *monc) { mutex_lock(&monc->mutex); __open_session(monc); __schedule_delayed(monc); mutex_unlock(&monc->mutex); return 0; } EXPORT_SYMBOL(ceph_monc_open_session); /* * The monitor responds with mount ack indicate mount success. The * included client ticket allows the client to talk to MDSs and OSDs. */ static void ceph_monc_handle_map(struct ceph_mon_client *monc, struct ceph_msg *msg) { struct ceph_client *client = monc->client; struct ceph_monmap *monmap = NULL, *old = monc->monmap; void *p, *end; mutex_lock(&monc->mutex); dout("handle_monmap\n"); p = msg->front.iov_base; end = p + msg->front.iov_len; monmap = ceph_monmap_decode(p, end); if (IS_ERR(monmap)) { pr_err("problem decoding monmap, %d\n", (int)PTR_ERR(monmap)); goto out; } if (ceph_check_fsid(monc->client, &monmap->fsid) < 0) { kfree(monmap); goto out; } client->monc.monmap = monmap; kfree(old); if (!client->have_fsid) { client->have_fsid = true; mutex_unlock(&monc->mutex); /* * do debugfs initialization without mutex to avoid * creating a locking dependency */ ceph_debugfs_client_init(client); goto out_unlocked; } out: mutex_unlock(&monc->mutex); out_unlocked: wake_up_all(&client->auth_wq); } /* * generic requests (e.g., statfs, poolop) */ static struct ceph_mon_generic_request *__lookup_generic_req( struct ceph_mon_client *monc, u64 tid) { struct ceph_mon_generic_request *req; struct rb_node *n = monc->generic_request_tree.rb_node; while (n) { req = rb_entry(n, struct ceph_mon_generic_request, node); if (tid < req->tid) n = n->rb_left; else if (tid > req->tid) n = n->rb_right; else return req; } return NULL; } static void __insert_generic_request(struct ceph_mon_client *monc, struct ceph_mon_generic_request *new) { struct rb_node **p = &monc->generic_request_tree.rb_node; struct rb_node *parent = NULL; struct ceph_mon_generic_request *req = NULL; while (*p) { parent = *p; req = rb_entry(parent, struct ceph_mon_generic_request, node); if (new->tid < req->tid) p = &(*p)->rb_left; else if (new->tid > req->tid) p = &(*p)->rb_right; else BUG(); } rb_link_node(&new->node, parent, p); rb_insert_color(&new->node, &monc->generic_request_tree); } static void release_generic_request(struct kref *kref) { struct ceph_mon_generic_request *req = container_of(kref, struct ceph_mon_generic_request, kref); if (req->reply) ceph_msg_put(req->reply); if (req->request) ceph_msg_put(req->request); kfree(req); } static void put_generic_request(struct ceph_mon_generic_request *req) { kref_put(&req->kref, release_generic_request); } static void get_generic_request(struct ceph_mon_generic_request *req) { kref_get(&req->kref); } static struct ceph_msg *get_generic_reply(struct ceph_connection *con, struct ceph_msg_header *hdr, int *skip) { struct ceph_mon_client *monc = con->private; struct ceph_mon_generic_request *req; u64 tid = le64_to_cpu(hdr->tid); struct ceph_msg *m; mutex_lock(&monc->mutex); req = __lookup_generic_req(monc, tid); if (!req) { dout("get_generic_reply %lld dne\n", tid); *skip = 1; m = NULL; } else { dout("get_generic_reply %lld got %p\n", tid, req->reply); m = ceph_msg_get(req->reply); /* * we don't need to track the connection reading into * this reply because we only have one open connection * at a time, ever. */ } mutex_unlock(&monc->mutex); return m; } static int do_generic_request(struct ceph_mon_client *monc, struct ceph_mon_generic_request *req) { int err; /* register request */ mutex_lock(&monc->mutex); req->tid = ++monc->last_tid; req->request->hdr.tid = cpu_to_le64(req->tid); __insert_generic_request(monc, req); monc->num_generic_requests++; ceph_con_send(monc->con, ceph_msg_get(req->request)); mutex_unlock(&monc->mutex); err = wait_for_completion_interruptible(&req->completion); mutex_lock(&monc->mutex); rb_erase(&req->node, &monc->generic_request_tree); monc->num_generic_requests--; mutex_unlock(&monc->mutex); if (!err) err = req->result; return err; } /* * statfs */ static void handle_statfs_reply(struct ceph_mon_client *monc, struct ceph_msg *msg) { struct ceph_mon_generic_request *req; struct ceph_mon_statfs_reply *reply = msg->front.iov_base; u64 tid = le64_to_cpu(msg->hdr.tid); if (msg->front.iov_len != sizeof(*reply)) goto bad; dout("handle_statfs_reply %p tid %llu\n", msg, tid); mutex_lock(&monc->mutex); req = __lookup_generic_req(monc, tid); if (req) { *(struct ceph_statfs *)req->buf = reply->st; req->result = 0; get_generic_request(req); } mutex_unlock(&monc->mutex); if (req) { complete_all(&req->completion); put_generic_request(req); } return; bad: pr_err("corrupt generic reply, tid %llu\n", tid); ceph_msg_dump(msg); } /* * Do a synchronous statfs(). */ int ceph_monc_do_statfs(struct ceph_mon_client *monc, struct ceph_statfs *buf) { struct ceph_mon_generic_request *req; struct ceph_mon_statfs *h; int err; req = kzalloc(sizeof(*req), GFP_NOFS); if (!req) return -ENOMEM; kref_init(&req->kref); req->buf = buf; req->buf_len = sizeof(*buf); init_completion(&req->completion); err = -ENOMEM; req->request = ceph_msg_new(CEPH_MSG_STATFS, sizeof(*h), GFP_NOFS, true); if (!req->request) goto out; req->reply = ceph_msg_new(CEPH_MSG_STATFS_REPLY, 1024, GFP_NOFS, true); if (!req->reply) goto out; /* fill out request */ h = req->request->front.iov_base; h->monhdr.have_version = 0; h->monhdr.session_mon = cpu_to_le16(-1); h->monhdr.session_mon_tid = 0; h->fsid = monc->monmap->fsid; err = do_generic_request(monc, req); out: kref_put(&req->kref, release_generic_request); return err; } EXPORT_SYMBOL(ceph_monc_do_statfs); /* * pool ops */ static int get_poolop_reply_buf(const char *src, size_t src_len, char *dst, size_t dst_len) { u32 buf_len; if (src_len != sizeof(u32) + dst_len) return -EINVAL; buf_len = le32_to_cpu(*(u32 *)src); if (buf_len != dst_len) return -EINVAL; memcpy(dst, src + sizeof(u32), dst_len); return 0; } static void handle_poolop_reply(struct ceph_mon_client *monc, struct ceph_msg *msg) { struct ceph_mon_generic_request *req; struct ceph_mon_poolop_reply *reply = msg->front.iov_base; u64 tid = le64_to_cpu(msg->hdr.tid); if (msg->front.iov_len < sizeof(*reply)) goto bad; dout("handle_poolop_reply %p tid %llu\n", msg, tid); mutex_lock(&monc->mutex); req = __lookup_generic_req(monc, tid); if (req) { if (req->buf_len && get_poolop_reply_buf(msg->front.iov_base + sizeof(*reply), msg->front.iov_len - sizeof(*reply), req->buf, req->buf_len) < 0) { mutex_unlock(&monc->mutex); goto bad; } req->result = le32_to_cpu(reply->reply_code); get_generic_request(req); } mutex_unlock(&monc->mutex); if (req) { complete(&req->completion); put_generic_request(req); } return; bad: pr_err("corrupt generic reply, tid %llu\n", tid); ceph_msg_dump(msg); } /* * Do a synchronous pool op. */ int ceph_monc_do_poolop(struct ceph_mon_client *monc, u32 op, u32 pool, u64 snapid, char *buf, int len) { struct ceph_mon_generic_request *req; struct ceph_mon_poolop *h; int err; req = kzalloc(sizeof(*req), GFP_NOFS); if (!req) return -ENOMEM; kref_init(&req->kref); req->buf = buf; req->buf_len = len; init_completion(&req->completion); err = -ENOMEM; req->request = ceph_msg_new(CEPH_MSG_POOLOP, sizeof(*h), GFP_NOFS, true); if (!req->request) goto out; req->reply = ceph_msg_new(CEPH_MSG_POOLOP_REPLY, 1024, GFP_NOFS, true); if (!req->reply) goto out; /* fill out request */ req->request->hdr.version = cpu_to_le16(2); h = req->request->front.iov_base; h->monhdr.have_version = 0; h->monhdr.session_mon = cpu_to_le16(-1); h->monhdr.session_mon_tid = 0; h->fsid = monc->monmap->fsid; h->pool = cpu_to_le32(pool); h->op = cpu_to_le32(op); h->auid = 0; h->snapid = cpu_to_le64(snapid); h->name_len = 0; err = do_generic_request(monc, req); out: kref_put(&req->kref, release_generic_request); return err; } int ceph_monc_create_snapid(struct ceph_mon_client *monc, u32 pool, u64 *snapid) { return ceph_monc_do_poolop(monc, POOL_OP_CREATE_UNMANAGED_SNAP, pool, 0, (char *)snapid, sizeof(*snapid)); } EXPORT_SYMBOL(ceph_monc_create_snapid); int ceph_monc_delete_snapid(struct ceph_mon_client *monc, u32 pool, u64 snapid) { return ceph_monc_do_poolop(monc, POOL_OP_CREATE_UNMANAGED_SNAP, pool, snapid, 0, 0); } /* * Resend pending generic requests. */ static void __resend_generic_request(struct ceph_mon_client *monc) { struct ceph_mon_generic_request *req; struct rb_node *p; for (p = rb_first(&monc->generic_request_tree); p; p = rb_next(p)) { req = rb_entry(p, struct ceph_mon_generic_request, node); ceph_con_revoke(monc->con, req->request); ceph_con_send(monc->con, ceph_msg_get(req->request)); } } /* * Delayed work. If we haven't mounted yet, retry. Otherwise, * renew/retry subscription as needed (in case it is timing out, or we * got an ENOMEM). And keep the monitor connection alive. */ static void delayed_work(struct work_struct *work) { struct ceph_mon_client *monc = container_of(work, struct ceph_mon_client, delayed_work.work); dout("monc delayed_work\n"); mutex_lock(&monc->mutex); if (monc->hunting) { __close_session(monc); __open_session(monc); /* continue hunting */ } else { ceph_con_keepalive(monc->con); __validate_auth(monc); if (monc->auth->ops->is_authenticated(monc->auth)) __send_subscribe(monc); } __schedule_delayed(monc); mutex_unlock(&monc->mutex); } /* * On startup, we build a temporary monmap populated with the IPs * provided by mount(2). */ static int build_initial_monmap(struct ceph_mon_client *monc) { struct ceph_options *opt = monc->client->options; struct ceph_entity_addr *mon_addr = opt->mon_addr; int num_mon = opt->num_mon; int i; /* build initial monmap */ monc->monmap = kzalloc(sizeof(*monc->monmap) + num_mon*sizeof(monc->monmap->mon_inst[0]), GFP_KERNEL); if (!monc->monmap) return -ENOMEM; for (i = 0; i < num_mon; i++) { monc->monmap->mon_inst[i].addr = mon_addr[i]; monc->monmap->mon_inst[i].addr.nonce = 0; monc->monmap->mon_inst[i].name.type = CEPH_ENTITY_TYPE_MON; monc->monmap->mon_inst[i].name.num = cpu_to_le64(i); } monc->monmap->num_mon = num_mon; monc->have_fsid = false; return 0; } int ceph_monc_init(struct ceph_mon_client *monc, struct ceph_client *cl) { int err = 0; dout("init\n"); memset(monc, 0, sizeof(*monc)); monc->client = cl; monc->monmap = NULL; mutex_init(&monc->mutex); err = build_initial_monmap(monc); if (err) goto out; /* connection */ monc->con = kmalloc(sizeof(*monc->con), GFP_KERNEL); if (!monc->con) goto out_monmap; ceph_con_init(monc->client->msgr, monc->con); monc->con->private = monc; monc->con->ops = &mon_con_ops; /* authentication */ monc->auth = ceph_auth_init(cl->options->name, cl->options->key); if (IS_ERR(monc->auth)) { err = PTR_ERR(monc->auth); goto out_con; } monc->auth->want_keys = CEPH_ENTITY_TYPE_AUTH | CEPH_ENTITY_TYPE_MON | CEPH_ENTITY_TYPE_OSD | CEPH_ENTITY_TYPE_MDS; /* msgs */ err = -ENOMEM; monc->m_subscribe_ack = ceph_msg_new(CEPH_MSG_MON_SUBSCRIBE_ACK, sizeof(struct ceph_mon_subscribe_ack), GFP_NOFS, true); if (!monc->m_subscribe_ack) goto out_auth; monc->m_subscribe = ceph_msg_new(CEPH_MSG_MON_SUBSCRIBE, 96, GFP_NOFS, true); if (!monc->m_subscribe) goto out_subscribe_ack; monc->m_auth_reply = ceph_msg_new(CEPH_MSG_AUTH_REPLY, 4096, GFP_NOFS, true); if (!monc->m_auth_reply) goto out_subscribe; monc->m_auth = ceph_msg_new(CEPH_MSG_AUTH, 4096, GFP_NOFS, true); monc->pending_auth = 0; if (!monc->m_auth) goto out_auth_reply; monc->cur_mon = -1; monc->hunting = true; monc->sub_renew_after = jiffies; monc->sub_sent = 0; INIT_DELAYED_WORK(&monc->delayed_work, delayed_work); monc->generic_request_tree = RB_ROOT; monc->num_generic_requests = 0; monc->last_tid = 0; monc->have_mdsmap = 0; monc->have_osdmap = 0; monc->want_next_osdmap = 1; return 0; out_auth_reply: ceph_msg_put(monc->m_auth_reply); out_subscribe: ceph_msg_put(monc->m_subscribe); out_subscribe_ack: ceph_msg_put(monc->m_subscribe_ack); out_auth: ceph_auth_destroy(monc->auth); out_con: monc->con->ops->put(monc->con); out_monmap: kfree(monc->monmap); out: return err; } EXPORT_SYMBOL(ceph_monc_init); void ceph_monc_stop(struct ceph_mon_client *monc) { dout("stop\n"); cancel_delayed_work_sync(&monc->delayed_work); mutex_lock(&monc->mutex); __close_session(monc); monc->con->private = NULL; monc->con->ops->put(monc->con); monc->con = NULL; mutex_unlock(&monc->mutex); ceph_auth_destroy(monc->auth); ceph_msg_put(monc->m_auth); ceph_msg_put(monc->m_auth_reply); ceph_msg_put(monc->m_subscribe); ceph_msg_put(monc->m_subscribe_ack); kfree(monc->monmap); } EXPORT_SYMBOL(ceph_monc_stop); static void handle_auth_reply(struct ceph_mon_client *monc, struct ceph_msg *msg) { int ret; int was_auth = 0; mutex_lock(&monc->mutex); if (monc->auth->ops) was_auth = monc->auth->ops->is_authenticated(monc->auth); monc->pending_auth = 0; ret = ceph_handle_auth_reply(monc->auth, msg->front.iov_base, msg->front.iov_len, monc->m_auth->front.iov_base, monc->m_auth->front_max); if (ret < 0) { monc->client->auth_err = ret; wake_up_all(&monc->client->auth_wq); } else if (ret > 0) { __send_prepared_auth_request(monc, ret); } else if (!was_auth && monc->auth->ops->is_authenticated(monc->auth)) { dout("authenticated, starting session\n"); monc->client->msgr->inst.name.type = CEPH_ENTITY_TYPE_CLIENT; monc->client->msgr->inst.name.num = cpu_to_le64(monc->auth->global_id); __send_subscribe(monc); __resend_generic_request(monc); } mutex_unlock(&monc->mutex); } static int __validate_auth(struct ceph_mon_client *monc) { int ret; if (monc->pending_auth) return 0; ret = ceph_build_auth(monc->auth, monc->m_auth->front.iov_base, monc->m_auth->front_max); if (ret <= 0) return ret; /* either an error, or no need to authenticate */ __send_prepared_auth_request(monc, ret); return 0; } int ceph_monc_validate_auth(struct ceph_mon_client *monc) { int ret; mutex_lock(&monc->mutex); ret = __validate_auth(monc); mutex_unlock(&monc->mutex); return ret; } EXPORT_SYMBOL(ceph_monc_validate_auth); /* * handle incoming message */ static void dispatch(struct ceph_connection *con, struct ceph_msg *msg) { struct ceph_mon_client *monc = con->private; int type = le16_to_cpu(msg->hdr.type); if (!monc) return; switch (type) { case CEPH_MSG_AUTH_REPLY: handle_auth_reply(monc, msg); break; case CEPH_MSG_MON_SUBSCRIBE_ACK: handle_subscribe_ack(monc, msg); break; case CEPH_MSG_STATFS_REPLY: handle_statfs_reply(monc, msg); break; case CEPH_MSG_POOLOP_REPLY: handle_poolop_reply(monc, msg); break; case CEPH_MSG_MON_MAP: ceph_monc_handle_map(monc, msg); break; case CEPH_MSG_OSD_MAP: ceph_osdc_handle_map(&monc->client->osdc, msg); break; default: /* can the chained handler handle it? */ if (monc->client->extra_mon_dispatch && monc->client->extra_mon_dispatch(monc->client, msg) == 0) break; pr_err("received unknown message type %d %s\n", type, ceph_msg_type_name(type)); } ceph_msg_put(msg); } /* * Allocate memory for incoming message */ static struct ceph_msg *mon_alloc_msg(struct ceph_connection *con, struct ceph_msg_header *hdr, int *skip) { struct ceph_mon_client *monc = con->private; int type = le16_to_cpu(hdr->type); int front_len = le32_to_cpu(hdr->front_len); struct ceph_msg *m = NULL; *skip = 0; switch (type) { case CEPH_MSG_MON_SUBSCRIBE_ACK: m = ceph_msg_get(monc->m_subscribe_ack); break; case CEPH_MSG_POOLOP_REPLY: case CEPH_MSG_STATFS_REPLY: return get_generic_reply(con, hdr, skip); case CEPH_MSG_AUTH_REPLY: m = ceph_msg_get(monc->m_auth_reply); break; case CEPH_MSG_MON_MAP: case CEPH_MSG_MDS_MAP: case CEPH_MSG_OSD_MAP: m = ceph_msg_new(type, front_len, GFP_NOFS, false); break; } if (!m) { pr_info("alloc_msg unknown type %d\n", type); *skip = 1; } return m; } /* * If the monitor connection resets, pick a new monitor and resubmit * any pending requests. */ static void mon_fault(struct ceph_connection *con) { struct ceph_mon_client *monc = con->private; if (!monc) return; dout("mon_fault\n"); mutex_lock(&monc->mutex); if (!con->private) goto out; if (!monc->hunting) pr_info("mon%d %s session lost, " "hunting for new mon\n", monc->cur_mon, ceph_pr_addr(&monc->con->peer_addr.in_addr)); __close_session(monc); if (!monc->hunting) { /* start hunting */ monc->hunting = true; __open_session(monc); } else { /* already hunting, let's wait a bit */ __schedule_delayed(monc); } out: mutex_unlock(&monc->mutex); } static const struct ceph_connection_operations mon_con_ops = { .get = ceph_con_get, .put = ceph_con_put, .dispatch = dispatch, .fault = mon_fault, .alloc_msg = mon_alloc_msg, };
gpl-2.0
h8rift/android_kernel_htc_m7ul
drivers/video/omap2/displays/panel-picodlp.c
5118
13735
/* * picodlp panel driver * picodlp_i2c_driver: i2c_client driver * * Copyright (C) 2009-2011 Texas Instruments * Author: Mythri P K <mythripk@ti.com> * Mayuresh Janorkar <mayur@ti.com> * * 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. * * 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 <linux/module.h> #include <linux/input.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/firmware.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/gpio.h> #include <video/omapdss.h> #include <video/omap-panel-picodlp.h> #include "panel-picodlp.h" struct picodlp_data { struct mutex lock; struct i2c_client *picodlp_i2c_client; }; static struct i2c_board_info picodlp_i2c_board_info = { I2C_BOARD_INFO("picodlp_i2c_driver", 0x1b), }; struct picodlp_i2c_data { struct mutex xfer_lock; }; static struct i2c_device_id picodlp_i2c_id[] = { { "picodlp_i2c_driver", 0 }, }; struct picodlp_i2c_command { u8 reg; u32 value; }; static struct omap_video_timings pico_ls_timings = { .x_res = 864, .y_res = 480, .hsw = 7, .hfp = 11, .hbp = 7, .pixel_clock = 19200, .vsw = 2, .vfp = 3, .vbp = 14, }; static inline struct picodlp_panel_data *get_panel_data(const struct omap_dss_device *dssdev) { return (struct picodlp_panel_data *) dssdev->data; } static u32 picodlp_i2c_read(struct i2c_client *client, u8 reg) { u8 read_cmd[] = {READ_REG_SELECT, reg}, data[4]; struct picodlp_i2c_data *picodlp_i2c_data = i2c_get_clientdata(client); struct i2c_msg msg[2]; mutex_lock(&picodlp_i2c_data->xfer_lock); msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = 2; msg[0].buf = read_cmd; msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].len = 4; msg[1].buf = data; i2c_transfer(client->adapter, msg, 2); mutex_unlock(&picodlp_i2c_data->xfer_lock); return (data[3] | (data[2] << 8) | (data[1] << 16) | (data[0] << 24)); } static int picodlp_i2c_write_block(struct i2c_client *client, u8 *data, int len) { struct i2c_msg msg; int i, r, msg_count = 1; struct picodlp_i2c_data *picodlp_i2c_data = i2c_get_clientdata(client); if (len < 1 || len > 32) { dev_err(&client->dev, "too long syn_write_block len %d\n", len); return -EIO; } mutex_lock(&picodlp_i2c_data->xfer_lock); msg.addr = client->addr; msg.flags = 0; msg.len = len; msg.buf = data; r = i2c_transfer(client->adapter, &msg, msg_count); mutex_unlock(&picodlp_i2c_data->xfer_lock); /* * i2c_transfer returns: * number of messages sent in case of success * a negative error number in case of failure */ if (r != msg_count) goto err; /* In case of success */ for (i = 0; i < len; i++) dev_dbg(&client->dev, "addr %x bw 0x%02x[%d]: 0x%02x\n", client->addr, data[0] + i, i, data[i]); return 0; err: dev_err(&client->dev, "picodlp_i2c_write error\n"); return r; } static int picodlp_i2c_write(struct i2c_client *client, u8 reg, u32 value) { u8 data[5]; int i; data[0] = reg; for (i = 1; i < 5; i++) data[i] = (value >> (32 - (i) * 8)) & 0xFF; return picodlp_i2c_write_block(client, data, 5); } static int picodlp_i2c_write_array(struct i2c_client *client, const struct picodlp_i2c_command commands[], int count) { int i, r = 0; for (i = 0; i < count; i++) { r = picodlp_i2c_write(client, commands[i].reg, commands[i].value); if (r) return r; } return r; } static int picodlp_wait_for_dma_done(struct i2c_client *client) { u8 trial = 100; do { msleep(1); if (!trial--) return -ETIMEDOUT; } while (picodlp_i2c_read(client, MAIN_STATUS) & DMA_STATUS); return 0; } /** * picodlp_i2c_init: i2c_initialization routine * client: i2c_client for communication * * return * 0 : Success, no error * error code : Failure */ static int picodlp_i2c_init(struct i2c_client *client) { int r; static const struct picodlp_i2c_command init_cmd_set1[] = { {SOFT_RESET, 1}, {DMD_PARK_TRIGGER, 1}, {MISC_REG, 5}, {SEQ_CONTROL, 0}, {SEQ_VECTOR, 0x100}, {DMD_BLOCK_COUNT, 7}, {DMD_VCC_CONTROL, 0x109}, {DMD_PARK_PULSE_COUNT, 0xA}, {DMD_PARK_PULSE_WIDTH, 0xB}, {DMD_PARK_DELAY, 0x2ED}, {DMD_SHADOW_ENABLE, 0}, {FLASH_OPCODE, 0xB}, {FLASH_DUMMY_BYTES, 1}, {FLASH_ADDR_BYTES, 3}, {PBC_CONTROL, 0}, {FLASH_START_ADDR, CMT_LUT_0_START_ADDR}, {FLASH_READ_BYTES, CMT_LUT_0_SIZE}, {CMT_SPLASH_LUT_START_ADDR, 0}, {CMT_SPLASH_LUT_DEST_SELECT, CMT_LUT_ALL}, {PBC_CONTROL, 1}, }; static const struct picodlp_i2c_command init_cmd_set2[] = { {PBC_CONTROL, 0}, {CMT_SPLASH_LUT_DEST_SELECT, 0}, {PBC_CONTROL, 0}, {FLASH_START_ADDR, SEQUENCE_0_START_ADDR}, {FLASH_READ_BYTES, SEQUENCE_0_SIZE}, {SEQ_RESET_LUT_START_ADDR, 0}, {SEQ_RESET_LUT_DEST_SELECT, SEQ_SEQ_LUT}, {PBC_CONTROL, 1}, }; static const struct picodlp_i2c_command init_cmd_set3[] = { {PBC_CONTROL, 0}, {SEQ_RESET_LUT_DEST_SELECT, 0}, {PBC_CONTROL, 0}, {FLASH_START_ADDR, DRC_TABLE_0_START_ADDR}, {FLASH_READ_BYTES, DRC_TABLE_0_SIZE}, {SEQ_RESET_LUT_START_ADDR, 0}, {SEQ_RESET_LUT_DEST_SELECT, SEQ_DRC_LUT_ALL}, {PBC_CONTROL, 1}, }; static const struct picodlp_i2c_command init_cmd_set4[] = { {PBC_CONTROL, 0}, {SEQ_RESET_LUT_DEST_SELECT, 0}, {SDC_ENABLE, 1}, {AGC_CTRL, 7}, {CCA_C1A, 0x100}, {CCA_C1B, 0x0}, {CCA_C1C, 0x0}, {CCA_C2A, 0x0}, {CCA_C2B, 0x100}, {CCA_C2C, 0x0}, {CCA_C3A, 0x0}, {CCA_C3B, 0x0}, {CCA_C3C, 0x100}, {CCA_C7A, 0x100}, {CCA_C7B, 0x100}, {CCA_C7C, 0x100}, {CCA_ENABLE, 1}, {CPU_IF_MODE, 1}, {SHORT_FLIP, 1}, {CURTAIN_CONTROL, 0}, {DMD_PARK_TRIGGER, 0}, {R_DRIVE_CURRENT, 0x298}, {G_DRIVE_CURRENT, 0x298}, {B_DRIVE_CURRENT, 0x298}, {RGB_DRIVER_ENABLE, 7}, {SEQ_CONTROL, 0}, {ACTGEN_CONTROL, 0x10}, {SEQUENCE_MODE, SEQ_LOCK}, {DATA_FORMAT, RGB888}, {INPUT_RESOLUTION, WVGA_864_LANDSCAPE}, {INPUT_SOURCE, PARALLEL_RGB}, {CPU_IF_SYNC_METHOD, 1}, {SEQ_CONTROL, 1} }; r = picodlp_i2c_write_array(client, init_cmd_set1, ARRAY_SIZE(init_cmd_set1)); if (r) return r; r = picodlp_wait_for_dma_done(client); if (r) return r; r = picodlp_i2c_write_array(client, init_cmd_set2, ARRAY_SIZE(init_cmd_set2)); if (r) return r; r = picodlp_wait_for_dma_done(client); if (r) return r; r = picodlp_i2c_write_array(client, init_cmd_set3, ARRAY_SIZE(init_cmd_set3)); if (r) return r; r = picodlp_wait_for_dma_done(client); if (r) return r; r = picodlp_i2c_write_array(client, init_cmd_set4, ARRAY_SIZE(init_cmd_set4)); if (r) return r; return 0; } static int picodlp_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct picodlp_i2c_data *picodlp_i2c_data; picodlp_i2c_data = kzalloc(sizeof(struct picodlp_i2c_data), GFP_KERNEL); if (!picodlp_i2c_data) return -ENOMEM; mutex_init(&picodlp_i2c_data->xfer_lock); i2c_set_clientdata(client, picodlp_i2c_data); return 0; } static int picodlp_i2c_remove(struct i2c_client *client) { struct picodlp_i2c_data *picodlp_i2c_data = i2c_get_clientdata(client); kfree(picodlp_i2c_data); return 0; } static struct i2c_driver picodlp_i2c_driver = { .driver = { .name = "picodlp_i2c_driver", }, .probe = picodlp_i2c_probe, .remove = picodlp_i2c_remove, .id_table = picodlp_i2c_id, }; static int picodlp_panel_power_on(struct omap_dss_device *dssdev) { int r, trial = 100; struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev); struct picodlp_panel_data *picodlp_pdata = get_panel_data(dssdev); if (dssdev->platform_enable) { r = dssdev->platform_enable(dssdev); if (r) return r; } gpio_set_value(picodlp_pdata->pwrgood_gpio, 0); msleep(1); gpio_set_value(picodlp_pdata->pwrgood_gpio, 1); while (!gpio_get_value(picodlp_pdata->emu_done_gpio)) { if (!trial--) { dev_err(&dssdev->dev, "emu_done signal not" " going high\n"); return -ETIMEDOUT; } msleep(5); } /* * As per dpp2600 programming guide, * it is required to sleep for 1000ms after emu_done signal goes high * then only i2c commands can be successfully sent to dpp2600 */ msleep(1000); r = omapdss_dpi_display_enable(dssdev); if (r) { dev_err(&dssdev->dev, "failed to enable DPI\n"); goto err1; } r = picodlp_i2c_init(picod->picodlp_i2c_client); if (r) goto err; dssdev->state = OMAP_DSS_DISPLAY_ACTIVE; return r; err: omapdss_dpi_display_disable(dssdev); err1: if (dssdev->platform_disable) dssdev->platform_disable(dssdev); return r; } static void picodlp_panel_power_off(struct omap_dss_device *dssdev) { struct picodlp_panel_data *picodlp_pdata = get_panel_data(dssdev); omapdss_dpi_display_disable(dssdev); gpio_set_value(picodlp_pdata->emu_done_gpio, 0); gpio_set_value(picodlp_pdata->pwrgood_gpio, 0); if (dssdev->platform_disable) dssdev->platform_disable(dssdev); } static int picodlp_panel_probe(struct omap_dss_device *dssdev) { struct picodlp_data *picod; struct picodlp_panel_data *picodlp_pdata = get_panel_data(dssdev); struct i2c_adapter *adapter; struct i2c_client *picodlp_i2c_client; int r = 0, picodlp_adapter_id; dssdev->panel.config = OMAP_DSS_LCD_TFT | OMAP_DSS_LCD_ONOFF | OMAP_DSS_LCD_IHS | OMAP_DSS_LCD_IVS; dssdev->panel.acb = 0x0; dssdev->panel.timings = pico_ls_timings; picod = kzalloc(sizeof(struct picodlp_data), GFP_KERNEL); if (!picod) return -ENOMEM; mutex_init(&picod->lock); picodlp_adapter_id = picodlp_pdata->picodlp_adapter_id; adapter = i2c_get_adapter(picodlp_adapter_id); if (!adapter) { dev_err(&dssdev->dev, "can't get i2c adapter\n"); r = -ENODEV; goto err; } picodlp_i2c_client = i2c_new_device(adapter, &picodlp_i2c_board_info); if (!picodlp_i2c_client) { dev_err(&dssdev->dev, "can't add i2c device::" " picodlp_i2c_client is NULL\n"); r = -ENODEV; goto err; } picod->picodlp_i2c_client = picodlp_i2c_client; dev_set_drvdata(&dssdev->dev, picod); return r; err: kfree(picod); return r; } static void picodlp_panel_remove(struct omap_dss_device *dssdev) { struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev); i2c_unregister_device(picod->picodlp_i2c_client); dev_set_drvdata(&dssdev->dev, NULL); dev_dbg(&dssdev->dev, "removing picodlp panel\n"); kfree(picod); } static int picodlp_panel_enable(struct omap_dss_device *dssdev) { struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev); int r; dev_dbg(&dssdev->dev, "enabling picodlp panel\n"); mutex_lock(&picod->lock); if (dssdev->state != OMAP_DSS_DISPLAY_DISABLED) { mutex_unlock(&picod->lock); return -EINVAL; } r = picodlp_panel_power_on(dssdev); mutex_unlock(&picod->lock); return r; } static void picodlp_panel_disable(struct omap_dss_device *dssdev) { struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev); mutex_lock(&picod->lock); /* Turn off DLP Power */ if (dssdev->state == OMAP_DSS_DISPLAY_ACTIVE) picodlp_panel_power_off(dssdev); dssdev->state = OMAP_DSS_DISPLAY_DISABLED; mutex_unlock(&picod->lock); dev_dbg(&dssdev->dev, "disabling picodlp panel\n"); } static int picodlp_panel_suspend(struct omap_dss_device *dssdev) { struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev); mutex_lock(&picod->lock); /* Turn off DLP Power */ if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE) { mutex_unlock(&picod->lock); dev_err(&dssdev->dev, "unable to suspend picodlp panel," " panel is not ACTIVE\n"); return -EINVAL; } picodlp_panel_power_off(dssdev); dssdev->state = OMAP_DSS_DISPLAY_SUSPENDED; mutex_unlock(&picod->lock); dev_dbg(&dssdev->dev, "suspending picodlp panel\n"); return 0; } static int picodlp_panel_resume(struct omap_dss_device *dssdev) { struct picodlp_data *picod = dev_get_drvdata(&dssdev->dev); int r; mutex_lock(&picod->lock); if (dssdev->state != OMAP_DSS_DISPLAY_SUSPENDED) { mutex_unlock(&picod->lock); dev_err(&dssdev->dev, "unable to resume picodlp panel," " panel is not ACTIVE\n"); return -EINVAL; } r = picodlp_panel_power_on(dssdev); mutex_unlock(&picod->lock); dev_dbg(&dssdev->dev, "resuming picodlp panel\n"); return r; } static void picodlp_get_resolution(struct omap_dss_device *dssdev, u16 *xres, u16 *yres) { *xres = dssdev->panel.timings.x_res; *yres = dssdev->panel.timings.y_res; } static struct omap_dss_driver picodlp_driver = { .probe = picodlp_panel_probe, .remove = picodlp_panel_remove, .enable = picodlp_panel_enable, .disable = picodlp_panel_disable, .get_resolution = picodlp_get_resolution, .suspend = picodlp_panel_suspend, .resume = picodlp_panel_resume, .driver = { .name = "picodlp_panel", .owner = THIS_MODULE, }, }; static int __init picodlp_init(void) { int r = 0; r = i2c_add_driver(&picodlp_i2c_driver); if (r) { printk(KERN_WARNING "picodlp_i2c_driver" \ " registration failed\n"); return r; } r = omap_dss_register_driver(&picodlp_driver); if (r) i2c_del_driver(&picodlp_i2c_driver); return r; } static void __exit picodlp_exit(void) { i2c_del_driver(&picodlp_i2c_driver); omap_dss_unregister_driver(&picodlp_driver); } module_init(picodlp_init); module_exit(picodlp_exit); MODULE_AUTHOR("Mythri P K <mythripk@ti.com>"); MODULE_DESCRIPTION("picodlp driver"); MODULE_LICENSE("GPL");
gpl-2.0
ztemt/NX505J_Lollipop_kernel
drivers/media/video/cx88/cx88-video.c
5118
58058
/* * * device driver for Conexant 2388x based TV cards * video4linux video interface * * (c) 2003-04 Gerd Knorr <kraxel@bytesex.org> [SuSE Labs] * * (c) 2005-2006 Mauro Carvalho Chehab <mchehab@infradead.org> * - Multituner support * - video_ioctl2 conversion * - PAL/M fixes * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/init.h> #include <linux/list.h> #include <linux/module.h> #include <linux/kmod.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/delay.h> #include <linux/kthread.h> #include <asm/div64.h> #include "cx88.h" #include <media/v4l2-common.h> #include <media/v4l2-ioctl.h> #include <media/wm8775.h> MODULE_DESCRIPTION("v4l2 driver module for cx2388x based TV cards"); MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]"); MODULE_LICENSE("GPL"); MODULE_VERSION(CX88_VERSION); /* ------------------------------------------------------------------ */ static unsigned int video_nr[] = {[0 ... (CX88_MAXBOARDS - 1)] = UNSET }; static unsigned int vbi_nr[] = {[0 ... (CX88_MAXBOARDS - 1)] = UNSET }; static unsigned int radio_nr[] = {[0 ... (CX88_MAXBOARDS - 1)] = UNSET }; module_param_array(video_nr, int, NULL, 0444); module_param_array(vbi_nr, int, NULL, 0444); module_param_array(radio_nr, int, NULL, 0444); MODULE_PARM_DESC(video_nr,"video device numbers"); MODULE_PARM_DESC(vbi_nr,"vbi device numbers"); MODULE_PARM_DESC(radio_nr,"radio device numbers"); static unsigned int video_debug; module_param(video_debug,int,0644); MODULE_PARM_DESC(video_debug,"enable debug messages [video]"); static unsigned int irq_debug; module_param(irq_debug,int,0644); MODULE_PARM_DESC(irq_debug,"enable debug messages [IRQ handler]"); static unsigned int vid_limit = 16; module_param(vid_limit,int,0644); MODULE_PARM_DESC(vid_limit,"capture memory limit in megabytes"); #define dprintk(level,fmt, arg...) if (video_debug >= level) \ printk(KERN_DEBUG "%s/0: " fmt, core->name , ## arg) /* ------------------------------------------------------------------- */ /* static data */ static const struct cx8800_fmt formats[] = { { .name = "8 bpp, gray", .fourcc = V4L2_PIX_FMT_GREY, .cxformat = ColorFormatY8, .depth = 8, .flags = FORMAT_FLAGS_PACKED, },{ .name = "15 bpp RGB, le", .fourcc = V4L2_PIX_FMT_RGB555, .cxformat = ColorFormatRGB15, .depth = 16, .flags = FORMAT_FLAGS_PACKED, },{ .name = "15 bpp RGB, be", .fourcc = V4L2_PIX_FMT_RGB555X, .cxformat = ColorFormatRGB15 | ColorFormatBSWAP, .depth = 16, .flags = FORMAT_FLAGS_PACKED, },{ .name = "16 bpp RGB, le", .fourcc = V4L2_PIX_FMT_RGB565, .cxformat = ColorFormatRGB16, .depth = 16, .flags = FORMAT_FLAGS_PACKED, },{ .name = "16 bpp RGB, be", .fourcc = V4L2_PIX_FMT_RGB565X, .cxformat = ColorFormatRGB16 | ColorFormatBSWAP, .depth = 16, .flags = FORMAT_FLAGS_PACKED, },{ .name = "24 bpp RGB, le", .fourcc = V4L2_PIX_FMT_BGR24, .cxformat = ColorFormatRGB24, .depth = 24, .flags = FORMAT_FLAGS_PACKED, },{ .name = "32 bpp RGB, le", .fourcc = V4L2_PIX_FMT_BGR32, .cxformat = ColorFormatRGB32, .depth = 32, .flags = FORMAT_FLAGS_PACKED, },{ .name = "32 bpp RGB, be", .fourcc = V4L2_PIX_FMT_RGB32, .cxformat = ColorFormatRGB32 | ColorFormatBSWAP | ColorFormatWSWAP, .depth = 32, .flags = FORMAT_FLAGS_PACKED, },{ .name = "4:2:2, packed, YUYV", .fourcc = V4L2_PIX_FMT_YUYV, .cxformat = ColorFormatYUY2, .depth = 16, .flags = FORMAT_FLAGS_PACKED, },{ .name = "4:2:2, packed, UYVY", .fourcc = V4L2_PIX_FMT_UYVY, .cxformat = ColorFormatYUY2 | ColorFormatBSWAP, .depth = 16, .flags = FORMAT_FLAGS_PACKED, }, }; static const struct cx8800_fmt* format_by_fourcc(unsigned int fourcc) { unsigned int i; for (i = 0; i < ARRAY_SIZE(formats); i++) if (formats[i].fourcc == fourcc) return formats+i; return NULL; } /* ------------------------------------------------------------------- */ static const struct v4l2_queryctrl no_ctl = { .name = "42", .flags = V4L2_CTRL_FLAG_DISABLED, }; static const struct cx88_ctrl cx8800_ctls[] = { /* --- video --- */ { .v = { .id = V4L2_CID_BRIGHTNESS, .name = "Brightness", .minimum = 0x00, .maximum = 0xff, .step = 1, .default_value = 0x7f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 128, .reg = MO_CONTR_BRIGHT, .mask = 0x00ff, .shift = 0, },{ .v = { .id = V4L2_CID_CONTRAST, .name = "Contrast", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0x3f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 0, .reg = MO_CONTR_BRIGHT, .mask = 0xff00, .shift = 8, },{ .v = { .id = V4L2_CID_HUE, .name = "Hue", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0x7f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 128, .reg = MO_HUE, .mask = 0x00ff, .shift = 0, },{ /* strictly, this only describes only U saturation. * V saturation is handled specially through code. */ .v = { .id = V4L2_CID_SATURATION, .name = "Saturation", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0x7f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 0, .reg = MO_UV_SATURATION, .mask = 0x00ff, .shift = 0, }, { .v = { .id = V4L2_CID_SHARPNESS, .name = "Sharpness", .minimum = 0, .maximum = 4, .step = 1, .default_value = 0x0, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 0, /* NOTE: the value is converted and written to both even and odd registers in the code */ .reg = MO_FILTER_ODD, .mask = 7 << 7, .shift = 7, }, { .v = { .id = V4L2_CID_CHROMA_AGC, .name = "Chroma AGC", .minimum = 0, .maximum = 1, .default_value = 0x1, .type = V4L2_CTRL_TYPE_BOOLEAN, }, .reg = MO_INPUT_FORMAT, .mask = 1 << 10, .shift = 10, }, { .v = { .id = V4L2_CID_COLOR_KILLER, .name = "Color killer", .minimum = 0, .maximum = 1, .default_value = 0x1, .type = V4L2_CTRL_TYPE_BOOLEAN, }, .reg = MO_INPUT_FORMAT, .mask = 1 << 9, .shift = 9, }, { .v = { .id = V4L2_CID_BAND_STOP_FILTER, .name = "Notch filter", .minimum = 0, .maximum = 1, .step = 1, .default_value = 0x0, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 0, .reg = MO_HTOTAL, .mask = 3 << 11, .shift = 11, }, { /* --- audio --- */ .v = { .id = V4L2_CID_AUDIO_MUTE, .name = "Mute", .minimum = 0, .maximum = 1, .default_value = 1, .type = V4L2_CTRL_TYPE_BOOLEAN, }, .reg = AUD_VOL_CTL, .sreg = SHADOW_AUD_VOL_CTL, .mask = (1 << 6), .shift = 6, },{ .v = { .id = V4L2_CID_AUDIO_VOLUME, .name = "Volume", .minimum = 0, .maximum = 0x3f, .step = 1, .default_value = 0x3f, .type = V4L2_CTRL_TYPE_INTEGER, }, .reg = AUD_VOL_CTL, .sreg = SHADOW_AUD_VOL_CTL, .mask = 0x3f, .shift = 0, },{ .v = { .id = V4L2_CID_AUDIO_BALANCE, .name = "Balance", .minimum = 0, .maximum = 0x7f, .step = 1, .default_value = 0x40, .type = V4L2_CTRL_TYPE_INTEGER, }, .reg = AUD_BAL_CTL, .sreg = SHADOW_AUD_BAL_CTL, .mask = 0x7f, .shift = 0, } }; enum { CX8800_CTLS = ARRAY_SIZE(cx8800_ctls) }; /* Must be sorted from low to high control ID! */ const u32 cx88_user_ctrls[] = { V4L2_CID_USER_CLASS, V4L2_CID_BRIGHTNESS, V4L2_CID_CONTRAST, V4L2_CID_SATURATION, V4L2_CID_HUE, V4L2_CID_AUDIO_VOLUME, V4L2_CID_AUDIO_BALANCE, V4L2_CID_AUDIO_MUTE, V4L2_CID_SHARPNESS, V4L2_CID_CHROMA_AGC, V4L2_CID_COLOR_KILLER, V4L2_CID_BAND_STOP_FILTER, 0 }; EXPORT_SYMBOL(cx88_user_ctrls); static const u32 * const ctrl_classes[] = { cx88_user_ctrls, NULL }; int cx8800_ctrl_query(struct cx88_core *core, struct v4l2_queryctrl *qctrl) { int i; if (qctrl->id < V4L2_CID_BASE || qctrl->id >= V4L2_CID_LASTP1) return -EINVAL; for (i = 0; i < CX8800_CTLS; i++) if (cx8800_ctls[i].v.id == qctrl->id) break; if (i == CX8800_CTLS) { *qctrl = no_ctl; return 0; } *qctrl = cx8800_ctls[i].v; /* Report chroma AGC as inactive when SECAM is selected */ if (cx8800_ctls[i].v.id == V4L2_CID_CHROMA_AGC && core->tvnorm & V4L2_STD_SECAM) qctrl->flags |= V4L2_CTRL_FLAG_INACTIVE; return 0; } EXPORT_SYMBOL(cx8800_ctrl_query); /* ------------------------------------------------------------------- */ /* resource management */ static int res_get(struct cx8800_dev *dev, struct cx8800_fh *fh, unsigned int bit) { struct cx88_core *core = dev->core; if (fh->resources & bit) /* have it already allocated */ return 1; /* is it free? */ mutex_lock(&core->lock); if (dev->resources & bit) { /* no, someone else uses it */ mutex_unlock(&core->lock); return 0; } /* it's free, grab it */ fh->resources |= bit; dev->resources |= bit; dprintk(1,"res: get %d\n",bit); mutex_unlock(&core->lock); return 1; } static int res_check(struct cx8800_fh *fh, unsigned int bit) { return (fh->resources & bit); } static int res_locked(struct cx8800_dev *dev, unsigned int bit) { return (dev->resources & bit); } static void res_free(struct cx8800_dev *dev, struct cx8800_fh *fh, unsigned int bits) { struct cx88_core *core = dev->core; BUG_ON((fh->resources & bits) != bits); mutex_lock(&core->lock); fh->resources &= ~bits; dev->resources &= ~bits; dprintk(1,"res: put %d\n",bits); mutex_unlock(&core->lock); } /* ------------------------------------------------------------------ */ int cx88_video_mux(struct cx88_core *core, unsigned int input) { /* struct cx88_core *core = dev->core; */ dprintk(1,"video_mux: %d [vmux=%d,gpio=0x%x,0x%x,0x%x,0x%x]\n", input, INPUT(input).vmux, INPUT(input).gpio0,INPUT(input).gpio1, INPUT(input).gpio2,INPUT(input).gpio3); core->input = input; cx_andor(MO_INPUT_FORMAT, 0x03 << 14, INPUT(input).vmux << 14); cx_write(MO_GP3_IO, INPUT(input).gpio3); cx_write(MO_GP0_IO, INPUT(input).gpio0); cx_write(MO_GP1_IO, INPUT(input).gpio1); cx_write(MO_GP2_IO, INPUT(input).gpio2); switch (INPUT(input).type) { case CX88_VMUX_SVIDEO: cx_set(MO_AFECFG_IO, 0x00000001); cx_set(MO_INPUT_FORMAT, 0x00010010); cx_set(MO_FILTER_EVEN, 0x00002020); cx_set(MO_FILTER_ODD, 0x00002020); break; default: cx_clear(MO_AFECFG_IO, 0x00000001); cx_clear(MO_INPUT_FORMAT, 0x00010010); cx_clear(MO_FILTER_EVEN, 0x00002020); cx_clear(MO_FILTER_ODD, 0x00002020); break; } /* if there are audioroutes defined, we have an external ADC to deal with audio */ if (INPUT(input).audioroute) { /* The wm8775 module has the "2" route hardwired into the initialization. Some boards may use different routes for different inputs. HVR-1300 surely does */ if (core->board.audio_chip && core->board.audio_chip == V4L2_IDENT_WM8775) { call_all(core, audio, s_routing, INPUT(input).audioroute, 0, 0); } /* cx2388's C-ADC is connected to the tuner only. When used with S-Video, that ADC is busy dealing with chroma, so an external must be used for baseband audio */ if (INPUT(input).type != CX88_VMUX_TELEVISION && INPUT(input).type != CX88_VMUX_CABLE) { /* "I2S ADC mode" */ core->tvaudio = WW_I2SADC; cx88_set_tvaudio(core); } else { /* Normal mode */ cx_write(AUD_I2SCNTL, 0x0); cx_clear(AUD_CTL, EN_I2SIN_ENABLE); } } return 0; } EXPORT_SYMBOL(cx88_video_mux); /* ------------------------------------------------------------------ */ static int start_video_dma(struct cx8800_dev *dev, struct cx88_dmaqueue *q, struct cx88_buffer *buf) { struct cx88_core *core = dev->core; /* setup fifo + format */ cx88_sram_channel_setup(core, &cx88_sram_channels[SRAM_CH21], buf->bpl, buf->risc.dma); cx88_set_scale(core, buf->vb.width, buf->vb.height, buf->vb.field); cx_write(MO_COLOR_CTRL, buf->fmt->cxformat | ColorFormatGamma); /* reset counter */ cx_write(MO_VIDY_GPCNTRL,GP_COUNT_CONTROL_RESET); q->count = 1; /* enable irqs */ cx_set(MO_PCI_INTMSK, core->pci_irqmask | PCI_INT_VIDINT); /* Enables corresponding bits at PCI_INT_STAT: bits 0 to 4: video, audio, transport stream, VIP, Host bit 7: timer bits 8 and 9: DMA complete for: SRC, DST bits 10 and 11: BERR signal asserted for RISC: RD, WR bits 12 to 15: BERR signal asserted for: BRDG, SRC, DST, IPB */ cx_set(MO_VID_INTMSK, 0x0f0011); /* enable capture */ cx_set(VID_CAPTURE_CONTROL,0x06); /* start dma */ cx_set(MO_DEV_CNTRL2, (1<<5)); cx_set(MO_VID_DMACNTRL, 0x11); /* Planar Y and packed FIFO and RISC enable */ return 0; } #ifdef CONFIG_PM static int stop_video_dma(struct cx8800_dev *dev) { struct cx88_core *core = dev->core; /* stop dma */ cx_clear(MO_VID_DMACNTRL, 0x11); /* disable capture */ cx_clear(VID_CAPTURE_CONTROL,0x06); /* disable irqs */ cx_clear(MO_PCI_INTMSK, PCI_INT_VIDINT); cx_clear(MO_VID_INTMSK, 0x0f0011); return 0; } #endif static int restart_video_queue(struct cx8800_dev *dev, struct cx88_dmaqueue *q) { struct cx88_core *core = dev->core; struct cx88_buffer *buf, *prev; if (!list_empty(&q->active)) { buf = list_entry(q->active.next, struct cx88_buffer, vb.queue); dprintk(2,"restart_queue [%p/%d]: restart dma\n", buf, buf->vb.i); start_video_dma(dev, q, buf); list_for_each_entry(buf, &q->active, vb.queue) buf->count = q->count++; mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT); return 0; } prev = NULL; for (;;) { if (list_empty(&q->queued)) return 0; buf = list_entry(q->queued.next, struct cx88_buffer, vb.queue); if (NULL == prev) { list_move_tail(&buf->vb.queue, &q->active); start_video_dma(dev, q, buf); buf->vb.state = VIDEOBUF_ACTIVE; buf->count = q->count++; mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT); dprintk(2,"[%p/%d] restart_queue - first active\n", buf,buf->vb.i); } else if (prev->vb.width == buf->vb.width && prev->vb.height == buf->vb.height && prev->fmt == buf->fmt) { list_move_tail(&buf->vb.queue, &q->active); buf->vb.state = VIDEOBUF_ACTIVE; buf->count = q->count++; prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma); dprintk(2,"[%p/%d] restart_queue - move to active\n", buf,buf->vb.i); } else { return 0; } prev = buf; } } /* ------------------------------------------------------------------ */ static int buffer_setup(struct videobuf_queue *q, unsigned int *count, unsigned int *size) { struct cx8800_fh *fh = q->priv_data; *size = fh->fmt->depth*fh->width*fh->height >> 3; if (0 == *count) *count = 32; if (*size * *count > vid_limit * 1024 * 1024) *count = (vid_limit * 1024 * 1024) / *size; return 0; } static int buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb, enum v4l2_field field) { struct cx8800_fh *fh = q->priv_data; struct cx8800_dev *dev = fh->dev; struct cx88_core *core = dev->core; struct cx88_buffer *buf = container_of(vb,struct cx88_buffer,vb); struct videobuf_dmabuf *dma=videobuf_to_dma(&buf->vb); int rc, init_buffer = 0; BUG_ON(NULL == fh->fmt); if (fh->width < 48 || fh->width > norm_maxw(core->tvnorm) || fh->height < 32 || fh->height > norm_maxh(core->tvnorm)) return -EINVAL; buf->vb.size = (fh->width * fh->height * fh->fmt->depth) >> 3; if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size) return -EINVAL; if (buf->fmt != fh->fmt || buf->vb.width != fh->width || buf->vb.height != fh->height || buf->vb.field != field) { buf->fmt = fh->fmt; buf->vb.width = fh->width; buf->vb.height = fh->height; buf->vb.field = field; init_buffer = 1; } if (VIDEOBUF_NEEDS_INIT == buf->vb.state) { init_buffer = 1; if (0 != (rc = videobuf_iolock(q,&buf->vb,NULL))) goto fail; } if (init_buffer) { buf->bpl = buf->vb.width * buf->fmt->depth >> 3; switch (buf->vb.field) { case V4L2_FIELD_TOP: cx88_risc_buffer(dev->pci, &buf->risc, dma->sglist, 0, UNSET, buf->bpl, 0, buf->vb.height); break; case V4L2_FIELD_BOTTOM: cx88_risc_buffer(dev->pci, &buf->risc, dma->sglist, UNSET, 0, buf->bpl, 0, buf->vb.height); break; case V4L2_FIELD_INTERLACED: cx88_risc_buffer(dev->pci, &buf->risc, dma->sglist, 0, buf->bpl, buf->bpl, buf->bpl, buf->vb.height >> 1); break; case V4L2_FIELD_SEQ_TB: cx88_risc_buffer(dev->pci, &buf->risc, dma->sglist, 0, buf->bpl * (buf->vb.height >> 1), buf->bpl, 0, buf->vb.height >> 1); break; case V4L2_FIELD_SEQ_BT: cx88_risc_buffer(dev->pci, &buf->risc, dma->sglist, buf->bpl * (buf->vb.height >> 1), 0, buf->bpl, 0, buf->vb.height >> 1); break; default: BUG(); } } dprintk(2,"[%p/%d] buffer_prepare - %dx%d %dbpp \"%s\" - dma=0x%08lx\n", buf, buf->vb.i, fh->width, fh->height, fh->fmt->depth, fh->fmt->name, (unsigned long)buf->risc.dma); buf->vb.state = VIDEOBUF_PREPARED; return 0; fail: cx88_free_buffer(q,buf); return rc; } static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb) { struct cx88_buffer *buf = container_of(vb,struct cx88_buffer,vb); struct cx88_buffer *prev; struct cx8800_fh *fh = vq->priv_data; struct cx8800_dev *dev = fh->dev; struct cx88_core *core = dev->core; struct cx88_dmaqueue *q = &dev->vidq; /* add jump to stopper */ buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC); buf->risc.jmp[1] = cpu_to_le32(q->stopper.dma); if (!list_empty(&q->queued)) { list_add_tail(&buf->vb.queue,&q->queued); buf->vb.state = VIDEOBUF_QUEUED; dprintk(2,"[%p/%d] buffer_queue - append to queued\n", buf, buf->vb.i); } else if (list_empty(&q->active)) { list_add_tail(&buf->vb.queue,&q->active); start_video_dma(dev, q, buf); buf->vb.state = VIDEOBUF_ACTIVE; buf->count = q->count++; mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT); dprintk(2,"[%p/%d] buffer_queue - first active\n", buf, buf->vb.i); } else { prev = list_entry(q->active.prev, struct cx88_buffer, vb.queue); if (prev->vb.width == buf->vb.width && prev->vb.height == buf->vb.height && prev->fmt == buf->fmt) { list_add_tail(&buf->vb.queue,&q->active); buf->vb.state = VIDEOBUF_ACTIVE; buf->count = q->count++; prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma); dprintk(2,"[%p/%d] buffer_queue - append to active\n", buf, buf->vb.i); } else { list_add_tail(&buf->vb.queue,&q->queued); buf->vb.state = VIDEOBUF_QUEUED; dprintk(2,"[%p/%d] buffer_queue - first queued\n", buf, buf->vb.i); } } } static void buffer_release(struct videobuf_queue *q, struct videobuf_buffer *vb) { struct cx88_buffer *buf = container_of(vb,struct cx88_buffer,vb); cx88_free_buffer(q,buf); } static const struct videobuf_queue_ops cx8800_video_qops = { .buf_setup = buffer_setup, .buf_prepare = buffer_prepare, .buf_queue = buffer_queue, .buf_release = buffer_release, }; /* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */ static struct videobuf_queue* get_queue(struct cx8800_fh *fh) { switch (fh->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: return &fh->vidq; case V4L2_BUF_TYPE_VBI_CAPTURE: return &fh->vbiq; default: BUG(); return NULL; } } static int get_ressource(struct cx8800_fh *fh) { switch (fh->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: return RESOURCE_VIDEO; case V4L2_BUF_TYPE_VBI_CAPTURE: return RESOURCE_VBI; default: BUG(); return 0; } } static int video_open(struct file *file) { struct video_device *vdev = video_devdata(file); struct cx8800_dev *dev = video_drvdata(file); struct cx88_core *core = dev->core; struct cx8800_fh *fh; enum v4l2_buf_type type = 0; int radio = 0; switch (vdev->vfl_type) { case VFL_TYPE_GRABBER: type = V4L2_BUF_TYPE_VIDEO_CAPTURE; break; case VFL_TYPE_VBI: type = V4L2_BUF_TYPE_VBI_CAPTURE; break; case VFL_TYPE_RADIO: radio = 1; break; } dprintk(1, "open dev=%s radio=%d type=%s\n", video_device_node_name(vdev), radio, v4l2_type_names[type]); /* allocate + initialize per filehandle data */ fh = kzalloc(sizeof(*fh),GFP_KERNEL); if (unlikely(!fh)) return -ENOMEM; file->private_data = fh; fh->dev = dev; fh->radio = radio; fh->type = type; fh->width = 320; fh->height = 240; fh->fmt = format_by_fourcc(V4L2_PIX_FMT_BGR24); mutex_lock(&core->lock); videobuf_queue_sg_init(&fh->vidq, &cx8800_video_qops, &dev->pci->dev, &dev->slock, V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_FIELD_INTERLACED, sizeof(struct cx88_buffer), fh, NULL); videobuf_queue_sg_init(&fh->vbiq, &cx8800_vbi_qops, &dev->pci->dev, &dev->slock, V4L2_BUF_TYPE_VBI_CAPTURE, V4L2_FIELD_SEQ_TB, sizeof(struct cx88_buffer), fh, NULL); if (fh->radio) { dprintk(1,"video_open: setting radio device\n"); cx_write(MO_GP3_IO, core->board.radio.gpio3); cx_write(MO_GP0_IO, core->board.radio.gpio0); cx_write(MO_GP1_IO, core->board.radio.gpio1); cx_write(MO_GP2_IO, core->board.radio.gpio2); if (core->board.radio.audioroute) { if(core->board.audio_chip && core->board.audio_chip == V4L2_IDENT_WM8775) { call_all(core, audio, s_routing, core->board.radio.audioroute, 0, 0); } /* "I2S ADC mode" */ core->tvaudio = WW_I2SADC; cx88_set_tvaudio(core); } else { /* FM Mode */ core->tvaudio = WW_FM; cx88_set_tvaudio(core); cx88_set_stereo(core,V4L2_TUNER_MODE_STEREO,1); } call_all(core, tuner, s_radio); } core->users++; mutex_unlock(&core->lock); return 0; } static ssize_t video_read(struct file *file, char __user *data, size_t count, loff_t *ppos) { struct cx8800_fh *fh = file->private_data; switch (fh->type) { case V4L2_BUF_TYPE_VIDEO_CAPTURE: if (res_locked(fh->dev,RESOURCE_VIDEO)) return -EBUSY; return videobuf_read_one(&fh->vidq, data, count, ppos, file->f_flags & O_NONBLOCK); case V4L2_BUF_TYPE_VBI_CAPTURE: if (!res_get(fh->dev,fh,RESOURCE_VBI)) return -EBUSY; return videobuf_read_stream(&fh->vbiq, data, count, ppos, 1, file->f_flags & O_NONBLOCK); default: BUG(); return 0; } } static unsigned int video_poll(struct file *file, struct poll_table_struct *wait) { struct cx8800_fh *fh = file->private_data; struct cx88_buffer *buf; unsigned int rc = POLLERR; if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) { if (!res_get(fh->dev,fh,RESOURCE_VBI)) return POLLERR; return videobuf_poll_stream(file, &fh->vbiq, wait); } mutex_lock(&fh->vidq.vb_lock); if (res_check(fh,RESOURCE_VIDEO)) { /* streaming capture */ if (list_empty(&fh->vidq.stream)) goto done; buf = list_entry(fh->vidq.stream.next,struct cx88_buffer,vb.stream); } else { /* read() capture */ buf = (struct cx88_buffer*)fh->vidq.read_buf; if (NULL == buf) goto done; } poll_wait(file, &buf->vb.done, wait); if (buf->vb.state == VIDEOBUF_DONE || buf->vb.state == VIDEOBUF_ERROR) rc = POLLIN|POLLRDNORM; else rc = 0; done: mutex_unlock(&fh->vidq.vb_lock); return rc; } static int video_release(struct file *file) { struct cx8800_fh *fh = file->private_data; struct cx8800_dev *dev = fh->dev; /* turn off overlay */ if (res_check(fh, RESOURCE_OVERLAY)) { /* FIXME */ res_free(dev,fh,RESOURCE_OVERLAY); } /* stop video capture */ if (res_check(fh, RESOURCE_VIDEO)) { videobuf_queue_cancel(&fh->vidq); res_free(dev,fh,RESOURCE_VIDEO); } if (fh->vidq.read_buf) { buffer_release(&fh->vidq,fh->vidq.read_buf); kfree(fh->vidq.read_buf); } /* stop vbi capture */ if (res_check(fh, RESOURCE_VBI)) { videobuf_stop(&fh->vbiq); res_free(dev,fh,RESOURCE_VBI); } videobuf_mmap_free(&fh->vidq); videobuf_mmap_free(&fh->vbiq); mutex_lock(&dev->core->lock); file->private_data = NULL; kfree(fh); dev->core->users--; if (!dev->core->users) call_all(dev->core, core, s_power, 0); mutex_unlock(&dev->core->lock); return 0; } static int video_mmap(struct file *file, struct vm_area_struct * vma) { struct cx8800_fh *fh = file->private_data; return videobuf_mmap_mapper(get_queue(fh), vma); } /* ------------------------------------------------------------------ */ /* VIDEO CTRL IOCTLS */ int cx88_get_control (struct cx88_core *core, struct v4l2_control *ctl) { const struct cx88_ctrl *c = NULL; u32 value; int i; for (i = 0; i < CX8800_CTLS; i++) if (cx8800_ctls[i].v.id == ctl->id) c = &cx8800_ctls[i]; if (unlikely(NULL == c)) return -EINVAL; value = c->sreg ? cx_sread(c->sreg) : cx_read(c->reg); switch (ctl->id) { case V4L2_CID_AUDIO_BALANCE: ctl->value = ((value & 0x7f) < 0x40) ? ((value & 0x7f) + 0x40) : (0x7f - (value & 0x7f)); break; case V4L2_CID_AUDIO_VOLUME: ctl->value = 0x3f - (value & 0x3f); break; case V4L2_CID_SHARPNESS: ctl->value = ((value & 0x0200) ? (((value & 0x0180) >> 7) + 1) : 0); break; default: ctl->value = ((value + (c->off << c->shift)) & c->mask) >> c->shift; break; } dprintk(1,"get_control id=0x%X(%s) ctrl=0x%02x, reg=0x%02x val=0x%02x (mask 0x%02x)%s\n", ctl->id, c->v.name, ctl->value, c->reg, value,c->mask, c->sreg ? " [shadowed]" : ""); return 0; } EXPORT_SYMBOL(cx88_get_control); int cx88_set_control(struct cx88_core *core, struct v4l2_control *ctl) { const struct cx88_ctrl *c = NULL; u32 value,mask; int i; for (i = 0; i < CX8800_CTLS; i++) { if (cx8800_ctls[i].v.id == ctl->id) { c = &cx8800_ctls[i]; } } if (unlikely(NULL == c)) return -EINVAL; if (ctl->value < c->v.minimum) ctl->value = c->v.minimum; if (ctl->value > c->v.maximum) ctl->value = c->v.maximum; /* Pass changes onto any WM8775 */ if (core->board.audio_chip == V4L2_IDENT_WM8775) { struct v4l2_control client_ctl; memset(&client_ctl, 0, sizeof(client_ctl)); client_ctl.id = ctl->id; switch (ctl->id) { case V4L2_CID_AUDIO_MUTE: client_ctl.value = ctl->value; break; case V4L2_CID_AUDIO_VOLUME: client_ctl.value = (ctl->value) ? (0x90 + ctl->value) << 8 : 0; break; case V4L2_CID_AUDIO_BALANCE: client_ctl.value = ctl->value << 9; break; default: client_ctl.id = 0; break; } if (client_ctl.id) call_hw(core, WM8775_GID, core, s_ctrl, &client_ctl); } mask=c->mask; switch (ctl->id) { case V4L2_CID_AUDIO_BALANCE: value = (ctl->value < 0x40) ? (0x7f - ctl->value) : (ctl->value - 0x40); break; case V4L2_CID_AUDIO_VOLUME: value = 0x3f - (ctl->value & 0x3f); break; case V4L2_CID_SATURATION: /* special v_sat handling */ value = ((ctl->value - c->off) << c->shift) & c->mask; if (core->tvnorm & V4L2_STD_SECAM) { /* For SECAM, both U and V sat should be equal */ value=value<<8|value; } else { /* Keeps U Saturation proportional to V Sat */ value=(value*0x5a)/0x7f<<8|value; } mask=0xffff; break; case V4L2_CID_SHARPNESS: /* 0b000, 0b100, 0b101, 0b110, or 0b111 */ value = (ctl->value < 1 ? 0 : ((ctl->value + 3) << 7)); /* needs to be set for both fields */ cx_andor(MO_FILTER_EVEN, mask, value); break; case V4L2_CID_CHROMA_AGC: /* Do not allow chroma AGC to be enabled for SECAM */ value = ((ctl->value - c->off) << c->shift) & c->mask; if (core->tvnorm & V4L2_STD_SECAM && value) return -EINVAL; break; default: value = ((ctl->value - c->off) << c->shift) & c->mask; break; } dprintk(1,"set_control id=0x%X(%s) ctrl=0x%02x, reg=0x%02x val=0x%02x (mask 0x%02x)%s\n", ctl->id, c->v.name, ctl->value, c->reg, value, mask, c->sreg ? " [shadowed]" : ""); if (c->sreg) { cx_sandor(c->sreg, c->reg, mask, value); } else { cx_andor(c->reg, mask, value); } return 0; } EXPORT_SYMBOL(cx88_set_control); static void init_controls(struct cx88_core *core) { struct v4l2_control ctrl; int i; for (i = 0; i < CX8800_CTLS; i++) { ctrl.id=cx8800_ctls[i].v.id; ctrl.value=cx8800_ctls[i].v.default_value; cx88_set_control(core, &ctrl); } } /* ------------------------------------------------------------------ */ /* VIDEO IOCTLS */ static int vidioc_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx8800_fh *fh = priv; f->fmt.pix.width = fh->width; f->fmt.pix.height = fh->height; f->fmt.pix.field = fh->vidq.field; f->fmt.pix.pixelformat = fh->fmt->fourcc; f->fmt.pix.bytesperline = (f->fmt.pix.width * fh->fmt->depth) >> 3; f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline; return 0; } static int vidioc_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; const struct cx8800_fmt *fmt; enum v4l2_field field; unsigned int maxw, maxh; fmt = format_by_fourcc(f->fmt.pix.pixelformat); if (NULL == fmt) return -EINVAL; field = f->fmt.pix.field; maxw = norm_maxw(core->tvnorm); maxh = norm_maxh(core->tvnorm); if (V4L2_FIELD_ANY == field) { field = (f->fmt.pix.height > maxh/2) ? V4L2_FIELD_INTERLACED : V4L2_FIELD_BOTTOM; } switch (field) { case V4L2_FIELD_TOP: case V4L2_FIELD_BOTTOM: maxh = maxh / 2; break; case V4L2_FIELD_INTERLACED: break; default: return -EINVAL; } f->fmt.pix.field = field; v4l_bound_align_image(&f->fmt.pix.width, 48, maxw, 2, &f->fmt.pix.height, 32, maxh, 0, 0); f->fmt.pix.bytesperline = (f->fmt.pix.width * fmt->depth) >> 3; f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline; return 0; } static int vidioc_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx8800_fh *fh = priv; int err = vidioc_try_fmt_vid_cap (file,priv,f); if (0 != err) return err; fh->fmt = format_by_fourcc(f->fmt.pix.pixelformat); fh->width = f->fmt.pix.width; fh->height = f->fmt.pix.height; fh->vidq.field = f->fmt.pix.field; return 0; } static int vidioc_querycap (struct file *file, void *priv, struct v4l2_capability *cap) { struct cx8800_dev *dev = ((struct cx8800_fh *)priv)->dev; struct cx88_core *core = dev->core; strcpy(cap->driver, "cx8800"); strlcpy(cap->card, core->board.name, sizeof(cap->card)); sprintf(cap->bus_info,"PCI:%s",pci_name(dev->pci)); cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING | V4L2_CAP_VBI_CAPTURE; if (UNSET != core->board.tuner_type) cap->capabilities |= V4L2_CAP_TUNER; return 0; } static int vidioc_enum_fmt_vid_cap (struct file *file, void *priv, struct v4l2_fmtdesc *f) { if (unlikely(f->index >= ARRAY_SIZE(formats))) return -EINVAL; strlcpy(f->description,formats[f->index].name,sizeof(f->description)); f->pixelformat = formats[f->index].fourcc; return 0; } static int vidioc_reqbufs (struct file *file, void *priv, struct v4l2_requestbuffers *p) { struct cx8800_fh *fh = priv; return (videobuf_reqbufs(get_queue(fh), p)); } static int vidioc_querybuf (struct file *file, void *priv, struct v4l2_buffer *p) { struct cx8800_fh *fh = priv; return (videobuf_querybuf(get_queue(fh), p)); } static int vidioc_qbuf (struct file *file, void *priv, struct v4l2_buffer *p) { struct cx8800_fh *fh = priv; return (videobuf_qbuf(get_queue(fh), p)); } static int vidioc_dqbuf (struct file *file, void *priv, struct v4l2_buffer *p) { struct cx8800_fh *fh = priv; return (videobuf_dqbuf(get_queue(fh), p, file->f_flags & O_NONBLOCK)); } static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i) { struct cx8800_fh *fh = priv; struct cx8800_dev *dev = fh->dev; /* We should remember that this driver also supports teletext, */ /* so we have to test if the v4l2_buf_type is VBI capture data. */ if (unlikely((fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) && (fh->type != V4L2_BUF_TYPE_VBI_CAPTURE))) return -EINVAL; if (unlikely(i != fh->type)) return -EINVAL; if (unlikely(!res_get(dev,fh,get_ressource(fh)))) return -EBUSY; return videobuf_streamon(get_queue(fh)); } static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i) { struct cx8800_fh *fh = priv; struct cx8800_dev *dev = fh->dev; int err, res; if ((fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) && (fh->type != V4L2_BUF_TYPE_VBI_CAPTURE)) return -EINVAL; if (i != fh->type) return -EINVAL; res = get_ressource(fh); err = videobuf_streamoff(get_queue(fh)); if (err < 0) return err; res_free(dev,fh,res); return 0; } static int vidioc_s_std (struct file *file, void *priv, v4l2_std_id *tvnorms) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; mutex_lock(&core->lock); cx88_set_tvnorm(core,*tvnorms); mutex_unlock(&core->lock); return 0; } /* only one input in this sample driver */ int cx88_enum_input (struct cx88_core *core,struct v4l2_input *i) { static const char * const iname[] = { [ CX88_VMUX_COMPOSITE1 ] = "Composite1", [ CX88_VMUX_COMPOSITE2 ] = "Composite2", [ CX88_VMUX_COMPOSITE3 ] = "Composite3", [ CX88_VMUX_COMPOSITE4 ] = "Composite4", [ CX88_VMUX_SVIDEO ] = "S-Video", [ CX88_VMUX_TELEVISION ] = "Television", [ CX88_VMUX_CABLE ] = "Cable TV", [ CX88_VMUX_DVB ] = "DVB", [ CX88_VMUX_DEBUG ] = "for debug only", }; unsigned int n = i->index; if (n >= 4) return -EINVAL; if (0 == INPUT(n).type) return -EINVAL; i->type = V4L2_INPUT_TYPE_CAMERA; strcpy(i->name,iname[INPUT(n).type]); if ((CX88_VMUX_TELEVISION == INPUT(n).type) || (CX88_VMUX_CABLE == INPUT(n).type)) { i->type = V4L2_INPUT_TYPE_TUNER; i->std = CX88_NORMS; } return 0; } EXPORT_SYMBOL(cx88_enum_input); static int vidioc_enum_input (struct file *file, void *priv, struct v4l2_input *i) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; return cx88_enum_input (core,i); } static int vidioc_g_input (struct file *file, void *priv, unsigned int *i) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; *i = core->input; return 0; } static int vidioc_s_input (struct file *file, void *priv, unsigned int i) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; if (i >= 4) return -EINVAL; mutex_lock(&core->lock); cx88_newstation(core); cx88_video_mux(core,i); mutex_unlock(&core->lock); return 0; } static int vidioc_queryctrl (struct file *file, void *priv, struct v4l2_queryctrl *qctrl) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; qctrl->id = v4l2_ctrl_next(ctrl_classes, qctrl->id); if (unlikely(qctrl->id == 0)) return -EINVAL; return cx8800_ctrl_query(core, qctrl); } static int vidioc_g_ctrl (struct file *file, void *priv, struct v4l2_control *ctl) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; return cx88_get_control(core,ctl); } static int vidioc_s_ctrl (struct file *file, void *priv, struct v4l2_control *ctl) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; return cx88_set_control(core,ctl); } static int vidioc_g_tuner (struct file *file, void *priv, struct v4l2_tuner *t) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; u32 reg; if (unlikely(UNSET == core->board.tuner_type)) return -EINVAL; if (0 != t->index) return -EINVAL; strcpy(t->name, "Television"); t->type = V4L2_TUNER_ANALOG_TV; t->capability = V4L2_TUNER_CAP_NORM; t->rangehigh = 0xffffffffUL; cx88_get_stereo(core ,t); reg = cx_read(MO_DEVICE_STATUS); t->signal = (reg & (1<<5)) ? 0xffff : 0x0000; return 0; } static int vidioc_s_tuner (struct file *file, void *priv, struct v4l2_tuner *t) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; if (UNSET == core->board.tuner_type) return -EINVAL; if (0 != t->index) return -EINVAL; cx88_set_stereo(core, t->audmode, 1); return 0; } static int vidioc_g_frequency (struct file *file, void *priv, struct v4l2_frequency *f) { struct cx8800_fh *fh = priv; struct cx88_core *core = fh->dev->core; if (unlikely(UNSET == core->board.tuner_type)) return -EINVAL; /* f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; */ f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; f->frequency = core->freq; call_all(core, tuner, g_frequency, f); return 0; } int cx88_set_freq (struct cx88_core *core, struct v4l2_frequency *f) { if (unlikely(UNSET == core->board.tuner_type)) return -EINVAL; if (unlikely(f->tuner != 0)) return -EINVAL; mutex_lock(&core->lock); core->freq = f->frequency; cx88_newstation(core); call_all(core, tuner, s_frequency, f); /* When changing channels it is required to reset TVAUDIO */ msleep (10); cx88_set_tvaudio(core); mutex_unlock(&core->lock); return 0; } EXPORT_SYMBOL(cx88_set_freq); static int vidioc_s_frequency (struct file *file, void *priv, struct v4l2_frequency *f) { struct cx8800_fh *fh = priv; struct cx88_core *core = fh->dev->core; if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV)) return -EINVAL; if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO)) return -EINVAL; return cx88_set_freq (core,f); } #ifdef CONFIG_VIDEO_ADV_DEBUG static int vidioc_g_register (struct file *file, void *fh, struct v4l2_dbg_register *reg) { struct cx88_core *core = ((struct cx8800_fh*)fh)->dev->core; if (!v4l2_chip_match_host(&reg->match)) return -EINVAL; /* cx2388x has a 24-bit register space */ reg->val = cx_read(reg->reg & 0xffffff); reg->size = 4; return 0; } static int vidioc_s_register (struct file *file, void *fh, struct v4l2_dbg_register *reg) { struct cx88_core *core = ((struct cx8800_fh*)fh)->dev->core; if (!v4l2_chip_match_host(&reg->match)) return -EINVAL; cx_write(reg->reg & 0xffffff, reg->val); return 0; } #endif /* ----------------------------------------------------------- */ /* RADIO ESPECIFIC IOCTLS */ /* ----------------------------------------------------------- */ static int radio_querycap (struct file *file, void *priv, struct v4l2_capability *cap) { struct cx8800_dev *dev = ((struct cx8800_fh *)priv)->dev; struct cx88_core *core = dev->core; strcpy(cap->driver, "cx8800"); strlcpy(cap->card, core->board.name, sizeof(cap->card)); sprintf(cap->bus_info,"PCI:%s", pci_name(dev->pci)); cap->capabilities = V4L2_CAP_TUNER; return 0; } static int radio_g_tuner (struct file *file, void *priv, struct v4l2_tuner *t) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; if (unlikely(t->index > 0)) return -EINVAL; strcpy(t->name, "Radio"); t->type = V4L2_TUNER_RADIO; call_all(core, tuner, g_tuner, t); return 0; } static int radio_enum_input (struct file *file, void *priv, struct v4l2_input *i) { if (i->index != 0) return -EINVAL; strcpy(i->name,"Radio"); i->type = V4L2_INPUT_TYPE_TUNER; return 0; } static int radio_g_audio (struct file *file, void *priv, struct v4l2_audio *a) { if (unlikely(a->index)) return -EINVAL; strcpy(a->name,"Radio"); return 0; } /* FIXME: Should add a standard for radio */ static int radio_s_tuner (struct file *file, void *priv, struct v4l2_tuner *t) { struct cx88_core *core = ((struct cx8800_fh *)priv)->dev->core; if (0 != t->index) return -EINVAL; call_all(core, tuner, s_tuner, t); return 0; } static int radio_s_audio (struct file *file, void *fh, struct v4l2_audio *a) { return 0; } static int radio_s_input (struct file *file, void *fh, unsigned int i) { return 0; } static int radio_queryctrl (struct file *file, void *priv, struct v4l2_queryctrl *c) { int i; if (c->id < V4L2_CID_BASE || c->id >= V4L2_CID_LASTP1) return -EINVAL; if (c->id == V4L2_CID_AUDIO_MUTE || c->id == V4L2_CID_AUDIO_VOLUME || c->id == V4L2_CID_AUDIO_BALANCE) { for (i = 0; i < CX8800_CTLS; i++) { if (cx8800_ctls[i].v.id == c->id) break; } if (i == CX8800_CTLS) return -EINVAL; *c = cx8800_ctls[i].v; } else *c = no_ctl; return 0; } /* ----------------------------------------------------------- */ static void cx8800_vid_timeout(unsigned long data) { struct cx8800_dev *dev = (struct cx8800_dev*)data; struct cx88_core *core = dev->core; struct cx88_dmaqueue *q = &dev->vidq; struct cx88_buffer *buf; unsigned long flags; cx88_sram_channel_dump(core, &cx88_sram_channels[SRAM_CH21]); cx_clear(MO_VID_DMACNTRL, 0x11); cx_clear(VID_CAPTURE_CONTROL, 0x06); spin_lock_irqsave(&dev->slock,flags); while (!list_empty(&q->active)) { buf = list_entry(q->active.next, struct cx88_buffer, vb.queue); list_del(&buf->vb.queue); buf->vb.state = VIDEOBUF_ERROR; wake_up(&buf->vb.done); printk("%s/0: [%p/%d] timeout - dma=0x%08lx\n", core->name, buf, buf->vb.i, (unsigned long)buf->risc.dma); } restart_video_queue(dev,q); spin_unlock_irqrestore(&dev->slock,flags); } static const char *cx88_vid_irqs[32] = { "y_risci1", "u_risci1", "v_risci1", "vbi_risc1", "y_risci2", "u_risci2", "v_risci2", "vbi_risc2", "y_oflow", "u_oflow", "v_oflow", "vbi_oflow", "y_sync", "u_sync", "v_sync", "vbi_sync", "opc_err", "par_err", "rip_err", "pci_abort", }; static void cx8800_vid_irq(struct cx8800_dev *dev) { struct cx88_core *core = dev->core; u32 status, mask, count; status = cx_read(MO_VID_INTSTAT); mask = cx_read(MO_VID_INTMSK); if (0 == (status & mask)) return; cx_write(MO_VID_INTSTAT, status); if (irq_debug || (status & mask & ~0xff)) cx88_print_irqbits(core->name, "irq vid", cx88_vid_irqs, ARRAY_SIZE(cx88_vid_irqs), status, mask); /* risc op code error */ if (status & (1 << 16)) { printk(KERN_WARNING "%s/0: video risc op code error\n",core->name); cx_clear(MO_VID_DMACNTRL, 0x11); cx_clear(VID_CAPTURE_CONTROL, 0x06); cx88_sram_channel_dump(core, &cx88_sram_channels[SRAM_CH21]); } /* risc1 y */ if (status & 0x01) { spin_lock(&dev->slock); count = cx_read(MO_VIDY_GPCNT); cx88_wakeup(core, &dev->vidq, count); spin_unlock(&dev->slock); } /* risc1 vbi */ if (status & 0x08) { spin_lock(&dev->slock); count = cx_read(MO_VBI_GPCNT); cx88_wakeup(core, &dev->vbiq, count); spin_unlock(&dev->slock); } /* risc2 y */ if (status & 0x10) { dprintk(2,"stopper video\n"); spin_lock(&dev->slock); restart_video_queue(dev,&dev->vidq); spin_unlock(&dev->slock); } /* risc2 vbi */ if (status & 0x80) { dprintk(2,"stopper vbi\n"); spin_lock(&dev->slock); cx8800_restart_vbi_queue(dev,&dev->vbiq); spin_unlock(&dev->slock); } } static irqreturn_t cx8800_irq(int irq, void *dev_id) { struct cx8800_dev *dev = dev_id; struct cx88_core *core = dev->core; u32 status; int loop, handled = 0; for (loop = 0; loop < 10; loop++) { status = cx_read(MO_PCI_INTSTAT) & (core->pci_irqmask | PCI_INT_VIDINT); if (0 == status) goto out; cx_write(MO_PCI_INTSTAT, status); handled = 1; if (status & core->pci_irqmask) cx88_core_irq(core,status); if (status & PCI_INT_VIDINT) cx8800_vid_irq(dev); }; if (10 == loop) { printk(KERN_WARNING "%s/0: irq loop -- clearing mask\n", core->name); cx_write(MO_PCI_INTMSK,0); } out: return IRQ_RETVAL(handled); } /* ----------------------------------------------------------- */ /* exported stuff */ static const struct v4l2_file_operations video_fops = { .owner = THIS_MODULE, .open = video_open, .release = video_release, .read = video_read, .poll = video_poll, .mmap = video_mmap, .unlocked_ioctl = video_ioctl2, }; static const struct v4l2_ioctl_ops video_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap, .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap, .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap, .vidioc_g_fmt_vbi_cap = cx8800_vbi_fmt, .vidioc_try_fmt_vbi_cap = cx8800_vbi_fmt, .vidioc_s_fmt_vbi_cap = cx8800_vbi_fmt, .vidioc_reqbufs = vidioc_reqbufs, .vidioc_querybuf = vidioc_querybuf, .vidioc_qbuf = vidioc_qbuf, .vidioc_dqbuf = vidioc_dqbuf, .vidioc_s_std = vidioc_s_std, .vidioc_enum_input = vidioc_enum_input, .vidioc_g_input = vidioc_g_input, .vidioc_s_input = vidioc_s_input, .vidioc_queryctrl = vidioc_queryctrl, .vidioc_g_ctrl = vidioc_g_ctrl, .vidioc_s_ctrl = vidioc_s_ctrl, .vidioc_streamon = vidioc_streamon, .vidioc_streamoff = vidioc_streamoff, .vidioc_g_tuner = vidioc_g_tuner, .vidioc_s_tuner = vidioc_s_tuner, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_frequency = vidioc_s_frequency, #ifdef CONFIG_VIDEO_ADV_DEBUG .vidioc_g_register = vidioc_g_register, .vidioc_s_register = vidioc_s_register, #endif }; static struct video_device cx8800_vbi_template; static const struct video_device cx8800_video_template = { .name = "cx8800-video", .fops = &video_fops, .ioctl_ops = &video_ioctl_ops, .tvnorms = CX88_NORMS, .current_norm = V4L2_STD_NTSC_M, }; static const struct v4l2_file_operations radio_fops = { .owner = THIS_MODULE, .open = video_open, .release = video_release, .unlocked_ioctl = video_ioctl2, }; static const struct v4l2_ioctl_ops radio_ioctl_ops = { .vidioc_querycap = radio_querycap, .vidioc_g_tuner = radio_g_tuner, .vidioc_enum_input = radio_enum_input, .vidioc_g_audio = radio_g_audio, .vidioc_s_tuner = radio_s_tuner, .vidioc_s_audio = radio_s_audio, .vidioc_s_input = radio_s_input, .vidioc_queryctrl = radio_queryctrl, .vidioc_g_ctrl = vidioc_g_ctrl, .vidioc_s_ctrl = vidioc_s_ctrl, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_frequency = vidioc_s_frequency, #ifdef CONFIG_VIDEO_ADV_DEBUG .vidioc_g_register = vidioc_g_register, .vidioc_s_register = vidioc_s_register, #endif }; static const struct video_device cx8800_radio_template = { .name = "cx8800-radio", .fops = &radio_fops, .ioctl_ops = &radio_ioctl_ops, }; /* ----------------------------------------------------------- */ static void cx8800_unregister_video(struct cx8800_dev *dev) { if (dev->radio_dev) { if (video_is_registered(dev->radio_dev)) video_unregister_device(dev->radio_dev); else video_device_release(dev->radio_dev); dev->radio_dev = NULL; } if (dev->vbi_dev) { if (video_is_registered(dev->vbi_dev)) video_unregister_device(dev->vbi_dev); else video_device_release(dev->vbi_dev); dev->vbi_dev = NULL; } if (dev->video_dev) { if (video_is_registered(dev->video_dev)) video_unregister_device(dev->video_dev); else video_device_release(dev->video_dev); dev->video_dev = NULL; } } static int __devinit cx8800_initdev(struct pci_dev *pci_dev, const struct pci_device_id *pci_id) { struct cx8800_dev *dev; struct cx88_core *core; int err; dev = kzalloc(sizeof(*dev),GFP_KERNEL); if (NULL == dev) return -ENOMEM; /* pci init */ dev->pci = pci_dev; if (pci_enable_device(pci_dev)) { err = -EIO; goto fail_free; } core = cx88_core_get(dev->pci); if (NULL == core) { err = -EINVAL; goto fail_free; } dev->core = core; /* print pci info */ dev->pci_rev = pci_dev->revision; pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &dev->pci_lat); printk(KERN_INFO "%s/0: found at %s, rev: %d, irq: %d, " "latency: %d, mmio: 0x%llx\n", core->name, pci_name(pci_dev), dev->pci_rev, pci_dev->irq, dev->pci_lat,(unsigned long long)pci_resource_start(pci_dev,0)); pci_set_master(pci_dev); if (!pci_dma_supported(pci_dev,DMA_BIT_MASK(32))) { printk("%s/0: Oops: no 32bit PCI DMA ???\n",core->name); err = -EIO; goto fail_core; } /* Initialize VBI template */ memcpy( &cx8800_vbi_template, &cx8800_video_template, sizeof(cx8800_vbi_template) ); strcpy(cx8800_vbi_template.name,"cx8800-vbi"); /* initialize driver struct */ spin_lock_init(&dev->slock); core->tvnorm = cx8800_video_template.current_norm; /* init video dma queues */ INIT_LIST_HEAD(&dev->vidq.active); INIT_LIST_HEAD(&dev->vidq.queued); dev->vidq.timeout.function = cx8800_vid_timeout; dev->vidq.timeout.data = (unsigned long)dev; init_timer(&dev->vidq.timeout); cx88_risc_stopper(dev->pci,&dev->vidq.stopper, MO_VID_DMACNTRL,0x11,0x00); /* init vbi dma queues */ INIT_LIST_HEAD(&dev->vbiq.active); INIT_LIST_HEAD(&dev->vbiq.queued); dev->vbiq.timeout.function = cx8800_vbi_timeout; dev->vbiq.timeout.data = (unsigned long)dev; init_timer(&dev->vbiq.timeout); cx88_risc_stopper(dev->pci,&dev->vbiq.stopper, MO_VID_DMACNTRL,0x88,0x00); /* get irq */ err = request_irq(pci_dev->irq, cx8800_irq, IRQF_SHARED | IRQF_DISABLED, core->name, dev); if (err < 0) { printk(KERN_ERR "%s/0: can't get IRQ %d\n", core->name,pci_dev->irq); goto fail_core; } cx_set(MO_PCI_INTMSK, core->pci_irqmask); /* load and configure helper modules */ if (core->board.audio_chip == V4L2_IDENT_WM8775) { struct i2c_board_info wm8775_info = { .type = "wm8775", .addr = 0x36 >> 1, .platform_data = &core->wm8775_data, }; struct v4l2_subdev *sd; if (core->boardnr == CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1) core->wm8775_data.is_nova_s = true; else core->wm8775_data.is_nova_s = false; sd = v4l2_i2c_new_subdev_board(&core->v4l2_dev, &core->i2c_adap, &wm8775_info, NULL); if (sd != NULL) sd->grp_id = WM8775_GID; } if (core->board.audio_chip == V4L2_IDENT_TVAUDIO) { /* This probes for a tda9874 as is used on some Pixelview Ultra boards. */ v4l2_i2c_new_subdev(&core->v4l2_dev, &core->i2c_adap, "tvaudio", 0, I2C_ADDRS(0xb0 >> 1)); } switch (core->boardnr) { case CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD: case CX88_BOARD_DVICO_FUSIONHDTV_7_GOLD: { static const struct i2c_board_info rtc_info = { I2C_BOARD_INFO("isl1208", 0x6f) }; request_module("rtc-isl1208"); core->i2c_rtc = i2c_new_device(&core->i2c_adap, &rtc_info); } /* break intentionally omitted */ case CX88_BOARD_DVICO_FUSIONHDTV_5_PCI_NANO: request_module("ir-kbd-i2c"); } /* Sets device info at pci_dev */ pci_set_drvdata(pci_dev, dev); /* initial device configuration */ mutex_lock(&core->lock); cx88_set_tvnorm(core, core->tvnorm); init_controls(core); cx88_video_mux(core, 0); /* register v4l devices */ dev->video_dev = cx88_vdev_init(core,dev->pci, &cx8800_video_template,"video"); video_set_drvdata(dev->video_dev, dev); err = video_register_device(dev->video_dev,VFL_TYPE_GRABBER, video_nr[core->nr]); if (err < 0) { printk(KERN_ERR "%s/0: can't register video device\n", core->name); goto fail_unreg; } printk(KERN_INFO "%s/0: registered device %s [v4l2]\n", core->name, video_device_node_name(dev->video_dev)); dev->vbi_dev = cx88_vdev_init(core,dev->pci,&cx8800_vbi_template,"vbi"); video_set_drvdata(dev->vbi_dev, dev); err = video_register_device(dev->vbi_dev,VFL_TYPE_VBI, vbi_nr[core->nr]); if (err < 0) { printk(KERN_ERR "%s/0: can't register vbi device\n", core->name); goto fail_unreg; } printk(KERN_INFO "%s/0: registered device %s\n", core->name, video_device_node_name(dev->vbi_dev)); if (core->board.radio.type == CX88_RADIO) { dev->radio_dev = cx88_vdev_init(core,dev->pci, &cx8800_radio_template,"radio"); video_set_drvdata(dev->radio_dev, dev); err = video_register_device(dev->radio_dev,VFL_TYPE_RADIO, radio_nr[core->nr]); if (err < 0) { printk(KERN_ERR "%s/0: can't register radio device\n", core->name); goto fail_unreg; } printk(KERN_INFO "%s/0: registered device %s\n", core->name, video_device_node_name(dev->radio_dev)); } /* start tvaudio thread */ if (core->board.tuner_type != TUNER_ABSENT) { core->kthread = kthread_run(cx88_audio_thread, core, "cx88 tvaudio"); if (IS_ERR(core->kthread)) { err = PTR_ERR(core->kthread); printk(KERN_ERR "%s/0: failed to create cx88 audio thread, err=%d\n", core->name, err); } } mutex_unlock(&core->lock); return 0; fail_unreg: cx8800_unregister_video(dev); free_irq(pci_dev->irq, dev); mutex_unlock(&core->lock); fail_core: cx88_core_put(core,dev->pci); fail_free: kfree(dev); return err; } static void __devexit cx8800_finidev(struct pci_dev *pci_dev) { struct cx8800_dev *dev = pci_get_drvdata(pci_dev); struct cx88_core *core = dev->core; /* stop thread */ if (core->kthread) { kthread_stop(core->kthread); core->kthread = NULL; } if (core->ir) cx88_ir_stop(core); cx88_shutdown(core); /* FIXME */ pci_disable_device(pci_dev); /* unregister stuff */ free_irq(pci_dev->irq, dev); cx8800_unregister_video(dev); pci_set_drvdata(pci_dev, NULL); /* free memory */ btcx_riscmem_free(dev->pci,&dev->vidq.stopper); cx88_core_put(core,dev->pci); kfree(dev); } #ifdef CONFIG_PM static int cx8800_suspend(struct pci_dev *pci_dev, pm_message_t state) { struct cx8800_dev *dev = pci_get_drvdata(pci_dev); struct cx88_core *core = dev->core; /* stop video+vbi capture */ spin_lock(&dev->slock); if (!list_empty(&dev->vidq.active)) { printk("%s/0: suspend video\n", core->name); stop_video_dma(dev); del_timer(&dev->vidq.timeout); } if (!list_empty(&dev->vbiq.active)) { printk("%s/0: suspend vbi\n", core->name); cx8800_stop_vbi_dma(dev); del_timer(&dev->vbiq.timeout); } spin_unlock(&dev->slock); if (core->ir) cx88_ir_stop(core); /* FIXME -- shutdown device */ cx88_shutdown(core); pci_save_state(pci_dev); if (0 != pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state))) { pci_disable_device(pci_dev); dev->state.disabled = 1; } return 0; } static int cx8800_resume(struct pci_dev *pci_dev) { struct cx8800_dev *dev = pci_get_drvdata(pci_dev); struct cx88_core *core = dev->core; int err; if (dev->state.disabled) { err=pci_enable_device(pci_dev); if (err) { printk(KERN_ERR "%s/0: can't enable device\n", core->name); return err; } dev->state.disabled = 0; } err= pci_set_power_state(pci_dev, PCI_D0); if (err) { printk(KERN_ERR "%s/0: can't set power state\n", core->name); pci_disable_device(pci_dev); dev->state.disabled = 1; return err; } pci_restore_state(pci_dev); /* FIXME: re-initialize hardware */ cx88_reset(core); if (core->ir) cx88_ir_start(core); cx_set(MO_PCI_INTMSK, core->pci_irqmask); /* restart video+vbi capture */ spin_lock(&dev->slock); if (!list_empty(&dev->vidq.active)) { printk("%s/0: resume video\n", core->name); restart_video_queue(dev,&dev->vidq); } if (!list_empty(&dev->vbiq.active)) { printk("%s/0: resume vbi\n", core->name); cx8800_restart_vbi_queue(dev,&dev->vbiq); } spin_unlock(&dev->slock); return 0; } #endif /* ----------------------------------------------------------- */ static const struct pci_device_id cx8800_pci_tbl[] = { { .vendor = 0x14f1, .device = 0x8800, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, },{ /* --- end of list --- */ } }; MODULE_DEVICE_TABLE(pci, cx8800_pci_tbl); static struct pci_driver cx8800_pci_driver = { .name = "cx8800", .id_table = cx8800_pci_tbl, .probe = cx8800_initdev, .remove = __devexit_p(cx8800_finidev), #ifdef CONFIG_PM .suspend = cx8800_suspend, .resume = cx8800_resume, #endif }; static int __init cx8800_init(void) { printk(KERN_INFO "cx88/0: cx2388x v4l2 driver version %s loaded\n", CX88_VERSION); return pci_register_driver(&cx8800_pci_driver); } static void __exit cx8800_fini(void) { pci_unregister_driver(&cx8800_pci_driver); } module_init(cx8800_init); module_exit(cx8800_fini);
gpl-2.0
thoemy/android_kernel_htc_endeavoru
arch/x86/mm/pageattr-test.c
5630
5387
/* * self test for change_page_attr. * * Clears the a test pte bit on random pages in the direct mapping, * then reverts and compares page tables forwards and afterwards. */ #include <linux/bootmem.h> #include <linux/kthread.h> #include <linux/random.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/mm.h> #include <asm/cacheflush.h> #include <asm/pgtable.h> #include <asm/kdebug.h> /* * Only print the results of the first pass: */ static __read_mostly int print = 1; enum { NTEST = 400, #ifdef CONFIG_X86_64 LPS = (1 << PMD_SHIFT), #elif defined(CONFIG_X86_PAE) LPS = (1 << PMD_SHIFT), #else LPS = (1 << 22), #endif GPS = (1<<30) }; #define PAGE_CPA_TEST __pgprot(_PAGE_CPA_TEST) static int pte_testbit(pte_t pte) { return pte_flags(pte) & _PAGE_UNUSED1; } struct split_state { long lpg, gpg, spg, exec; long min_exec, max_exec; }; static int print_split(struct split_state *s) { long i, expected, missed = 0; int err = 0; s->lpg = s->gpg = s->spg = s->exec = 0; s->min_exec = ~0UL; s->max_exec = 0; for (i = 0; i < max_pfn_mapped; ) { unsigned long addr = (unsigned long)__va(i << PAGE_SHIFT); unsigned int level; pte_t *pte; pte = lookup_address(addr, &level); if (!pte) { missed++; i++; continue; } if (level == PG_LEVEL_1G && sizeof(long) == 8) { s->gpg++; i += GPS/PAGE_SIZE; } else if (level == PG_LEVEL_2M) { if (!(pte_val(*pte) & _PAGE_PSE)) { printk(KERN_ERR "%lx level %d but not PSE %Lx\n", addr, level, (u64)pte_val(*pte)); err = 1; } s->lpg++; i += LPS/PAGE_SIZE; } else { s->spg++; i++; } if (!(pte_val(*pte) & _PAGE_NX)) { s->exec++; if (addr < s->min_exec) s->min_exec = addr; if (addr > s->max_exec) s->max_exec = addr; } } if (print) { printk(KERN_INFO " 4k %lu large %lu gb %lu x %lu[%lx-%lx] miss %lu\n", s->spg, s->lpg, s->gpg, s->exec, s->min_exec != ~0UL ? s->min_exec : 0, s->max_exec, missed); } expected = (s->gpg*GPS + s->lpg*LPS)/PAGE_SIZE + s->spg + missed; if (expected != i) { printk(KERN_ERR "CPA max_pfn_mapped %lu but expected %lu\n", max_pfn_mapped, expected); return 1; } return err; } static unsigned long addr[NTEST]; static unsigned int len[NTEST]; /* Change the global bit on random pages in the direct mapping */ static int pageattr_test(void) { struct split_state sa, sb, sc; unsigned long *bm; pte_t *pte, pte0; int failed = 0; unsigned int level; int i, k; int err; unsigned long test_addr; if (print) printk(KERN_INFO "CPA self-test:\n"); bm = vzalloc((max_pfn_mapped + 7) / 8); if (!bm) { printk(KERN_ERR "CPA Cannot vmalloc bitmap\n"); return -ENOMEM; } failed += print_split(&sa); srandom32(100); for (i = 0; i < NTEST; i++) { unsigned long pfn = random32() % max_pfn_mapped; addr[i] = (unsigned long)__va(pfn << PAGE_SHIFT); len[i] = random32() % 100; len[i] = min_t(unsigned long, len[i], max_pfn_mapped - pfn - 1); if (len[i] == 0) len[i] = 1; pte = NULL; pte0 = pfn_pte(0, __pgprot(0)); /* shut gcc up */ for (k = 0; k < len[i]; k++) { pte = lookup_address(addr[i] + k*PAGE_SIZE, &level); if (!pte || pgprot_val(pte_pgprot(*pte)) == 0 || !(pte_val(*pte) & _PAGE_PRESENT)) { addr[i] = 0; break; } if (k == 0) { pte0 = *pte; } else { if (pgprot_val(pte_pgprot(*pte)) != pgprot_val(pte_pgprot(pte0))) { len[i] = k; break; } } if (test_bit(pfn + k, bm)) { len[i] = k; break; } __set_bit(pfn + k, bm); } if (!addr[i] || !pte || !k) { addr[i] = 0; continue; } test_addr = addr[i]; err = change_page_attr_set(&test_addr, len[i], PAGE_CPA_TEST, 0); if (err < 0) { printk(KERN_ERR "CPA %d failed %d\n", i, err); failed++; } pte = lookup_address(addr[i], &level); if (!pte || !pte_testbit(*pte) || pte_huge(*pte)) { printk(KERN_ERR "CPA %lx: bad pte %Lx\n", addr[i], pte ? (u64)pte_val(*pte) : 0ULL); failed++; } if (level != PG_LEVEL_4K) { printk(KERN_ERR "CPA %lx: unexpected level %d\n", addr[i], level); failed++; } } vfree(bm); failed += print_split(&sb); for (i = 0; i < NTEST; i++) { if (!addr[i]) continue; pte = lookup_address(addr[i], &level); if (!pte) { printk(KERN_ERR "CPA lookup of %lx failed\n", addr[i]); failed++; continue; } test_addr = addr[i]; err = change_page_attr_clear(&test_addr, len[i], PAGE_CPA_TEST, 0); if (err < 0) { printk(KERN_ERR "CPA reverting failed: %d\n", err); failed++; } pte = lookup_address(addr[i], &level); if (!pte || pte_testbit(*pte)) { printk(KERN_ERR "CPA %lx: bad pte after revert %Lx\n", addr[i], pte ? (u64)pte_val(*pte) : 0ULL); failed++; } } failed += print_split(&sc); if (failed) { WARN(1, KERN_ERR "NOT PASSED. Please report.\n"); return -EINVAL; } else { if (print) printk(KERN_INFO "ok.\n"); } return 0; } static int do_pageattr_test(void *__unused) { while (!kthread_should_stop()) { schedule_timeout_interruptible(HZ*30); if (pageattr_test() < 0) break; if (print) print--; } return 0; } static int start_pageattr_test(void) { struct task_struct *p; p = kthread_create(do_pageattr_test, NULL, "pageattr-test"); if (!IS_ERR(p)) wake_up_process(p); else WARN_ON(1); return 0; } module_init(start_pageattr_test);
gpl-2.0
ztemt/Z5mini_H112_kernel
arch/x86/mm/pageattr-test.c
5630
5387
/* * self test for change_page_attr. * * Clears the a test pte bit on random pages in the direct mapping, * then reverts and compares page tables forwards and afterwards. */ #include <linux/bootmem.h> #include <linux/kthread.h> #include <linux/random.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/mm.h> #include <asm/cacheflush.h> #include <asm/pgtable.h> #include <asm/kdebug.h> /* * Only print the results of the first pass: */ static __read_mostly int print = 1; enum { NTEST = 400, #ifdef CONFIG_X86_64 LPS = (1 << PMD_SHIFT), #elif defined(CONFIG_X86_PAE) LPS = (1 << PMD_SHIFT), #else LPS = (1 << 22), #endif GPS = (1<<30) }; #define PAGE_CPA_TEST __pgprot(_PAGE_CPA_TEST) static int pte_testbit(pte_t pte) { return pte_flags(pte) & _PAGE_UNUSED1; } struct split_state { long lpg, gpg, spg, exec; long min_exec, max_exec; }; static int print_split(struct split_state *s) { long i, expected, missed = 0; int err = 0; s->lpg = s->gpg = s->spg = s->exec = 0; s->min_exec = ~0UL; s->max_exec = 0; for (i = 0; i < max_pfn_mapped; ) { unsigned long addr = (unsigned long)__va(i << PAGE_SHIFT); unsigned int level; pte_t *pte; pte = lookup_address(addr, &level); if (!pte) { missed++; i++; continue; } if (level == PG_LEVEL_1G && sizeof(long) == 8) { s->gpg++; i += GPS/PAGE_SIZE; } else if (level == PG_LEVEL_2M) { if (!(pte_val(*pte) & _PAGE_PSE)) { printk(KERN_ERR "%lx level %d but not PSE %Lx\n", addr, level, (u64)pte_val(*pte)); err = 1; } s->lpg++; i += LPS/PAGE_SIZE; } else { s->spg++; i++; } if (!(pte_val(*pte) & _PAGE_NX)) { s->exec++; if (addr < s->min_exec) s->min_exec = addr; if (addr > s->max_exec) s->max_exec = addr; } } if (print) { printk(KERN_INFO " 4k %lu large %lu gb %lu x %lu[%lx-%lx] miss %lu\n", s->spg, s->lpg, s->gpg, s->exec, s->min_exec != ~0UL ? s->min_exec : 0, s->max_exec, missed); } expected = (s->gpg*GPS + s->lpg*LPS)/PAGE_SIZE + s->spg + missed; if (expected != i) { printk(KERN_ERR "CPA max_pfn_mapped %lu but expected %lu\n", max_pfn_mapped, expected); return 1; } return err; } static unsigned long addr[NTEST]; static unsigned int len[NTEST]; /* Change the global bit on random pages in the direct mapping */ static int pageattr_test(void) { struct split_state sa, sb, sc; unsigned long *bm; pte_t *pte, pte0; int failed = 0; unsigned int level; int i, k; int err; unsigned long test_addr; if (print) printk(KERN_INFO "CPA self-test:\n"); bm = vzalloc((max_pfn_mapped + 7) / 8); if (!bm) { printk(KERN_ERR "CPA Cannot vmalloc bitmap\n"); return -ENOMEM; } failed += print_split(&sa); srandom32(100); for (i = 0; i < NTEST; i++) { unsigned long pfn = random32() % max_pfn_mapped; addr[i] = (unsigned long)__va(pfn << PAGE_SHIFT); len[i] = random32() % 100; len[i] = min_t(unsigned long, len[i], max_pfn_mapped - pfn - 1); if (len[i] == 0) len[i] = 1; pte = NULL; pte0 = pfn_pte(0, __pgprot(0)); /* shut gcc up */ for (k = 0; k < len[i]; k++) { pte = lookup_address(addr[i] + k*PAGE_SIZE, &level); if (!pte || pgprot_val(pte_pgprot(*pte)) == 0 || !(pte_val(*pte) & _PAGE_PRESENT)) { addr[i] = 0; break; } if (k == 0) { pte0 = *pte; } else { if (pgprot_val(pte_pgprot(*pte)) != pgprot_val(pte_pgprot(pte0))) { len[i] = k; break; } } if (test_bit(pfn + k, bm)) { len[i] = k; break; } __set_bit(pfn + k, bm); } if (!addr[i] || !pte || !k) { addr[i] = 0; continue; } test_addr = addr[i]; err = change_page_attr_set(&test_addr, len[i], PAGE_CPA_TEST, 0); if (err < 0) { printk(KERN_ERR "CPA %d failed %d\n", i, err); failed++; } pte = lookup_address(addr[i], &level); if (!pte || !pte_testbit(*pte) || pte_huge(*pte)) { printk(KERN_ERR "CPA %lx: bad pte %Lx\n", addr[i], pte ? (u64)pte_val(*pte) : 0ULL); failed++; } if (level != PG_LEVEL_4K) { printk(KERN_ERR "CPA %lx: unexpected level %d\n", addr[i], level); failed++; } } vfree(bm); failed += print_split(&sb); for (i = 0; i < NTEST; i++) { if (!addr[i]) continue; pte = lookup_address(addr[i], &level); if (!pte) { printk(KERN_ERR "CPA lookup of %lx failed\n", addr[i]); failed++; continue; } test_addr = addr[i]; err = change_page_attr_clear(&test_addr, len[i], PAGE_CPA_TEST, 0); if (err < 0) { printk(KERN_ERR "CPA reverting failed: %d\n", err); failed++; } pte = lookup_address(addr[i], &level); if (!pte || pte_testbit(*pte)) { printk(KERN_ERR "CPA %lx: bad pte after revert %Lx\n", addr[i], pte ? (u64)pte_val(*pte) : 0ULL); failed++; } } failed += print_split(&sc); if (failed) { WARN(1, KERN_ERR "NOT PASSED. Please report.\n"); return -EINVAL; } else { if (print) printk(KERN_INFO "ok.\n"); } return 0; } static int do_pageattr_test(void *__unused) { while (!kthread_should_stop()) { schedule_timeout_interruptible(HZ*30); if (pageattr_test() < 0) break; if (print) print--; } return 0; } static int start_pageattr_test(void) { struct task_struct *p; p = kthread_create(do_pageattr_test, NULL, "pageattr-test"); if (!IS_ERR(p)) wake_up_process(p); else WARN_ON(1); return 0; } module_init(start_pageattr_test);
gpl-2.0
OpenFPGAduino/linux
drivers/hid/hid-monterey.c
7422
2139
/* * HID driver for some monterey "special" devices * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2007 Jiri Kosina * Copyright (c) 2007 Paul Walmsley * Copyright (c) 2008 Jiri Slaby */ /* * 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 <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "hid-ids.h" static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 30 && rdesc[29] == 0x05 && rdesc[30] == 0x09) { hid_info(hdev, "fixing up button/consumer in HID report descriptor\n"); rdesc[30] = 0x0c; } return rdesc; } #define mr_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \ EV_KEY, (c)) static int mr_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER) return 0; switch (usage->hid & HID_USAGE) { case 0x156: mr_map_key_clear(KEY_WORDPROCESSOR); break; case 0x157: mr_map_key_clear(KEY_SPREADSHEET); break; case 0x158: mr_map_key_clear(KEY_PRESENTATION); break; case 0x15c: mr_map_key_clear(KEY_STOP); break; default: return 0; } return 1; } static const struct hid_device_id mr_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_MONTEREY, USB_DEVICE_ID_GENIUS_KB29E) }, { } }; MODULE_DEVICE_TABLE(hid, mr_devices); static struct hid_driver mr_driver = { .name = "monterey", .id_table = mr_devices, .report_fixup = mr_report_fixup, .input_mapping = mr_input_mapping, }; static int __init mr_init(void) { return hid_register_driver(&mr_driver); } static void __exit mr_exit(void) { hid_unregister_driver(&mr_driver); } module_init(mr_init); module_exit(mr_exit); MODULE_LICENSE("GPL");
gpl-2.0
andi34/kernel_samsung_espresso-cm
drivers/staging/speakup/keyhelp.c
7422
6108
/* speakup_keyhelp.c * help module for speakup * *written by David Borowski. * * Copyright (C) 2003 David Borowski. * * 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/keyboard.h> #include "spk_priv.h" #include "speakup.h" #define MAXFUNCS 130 #define MAXKEYS 256 static const int num_key_names = MSG_KEYNAMES_END - MSG_KEYNAMES_START + 1; static u_short key_offsets[MAXFUNCS], key_data[MAXKEYS]; static u_short masks[] = { 32, 16, 8, 4, 2, 1 }; static short letter_offsets[26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static u_char funcvals[] = { ATTRIB_BLEEP_DEC, ATTRIB_BLEEP_INC, BLEEPS_DEC, BLEEPS_INC, SAY_FIRST_CHAR, SAY_LAST_CHAR, SAY_CHAR, SAY_CHAR_NUM, SAY_NEXT_CHAR, SAY_PHONETIC_CHAR, SAY_PREV_CHAR, SPEAKUP_PARKED, SPEAKUP_CUT, EDIT_DELIM, EDIT_EXNUM, EDIT_MOST, EDIT_REPEAT, EDIT_SOME, SPEAKUP_GOTO, BOTTOM_EDGE, LEFT_EDGE, RIGHT_EDGE, TOP_EDGE, SPEAKUP_HELP, SAY_LINE, SAY_NEXT_LINE, SAY_PREV_LINE, SAY_LINE_INDENT, SPEAKUP_PASTE, PITCH_DEC, PITCH_INC, PUNCT_DEC, PUNCT_INC, PUNC_LEVEL_DEC, PUNC_LEVEL_INC, SPEAKUP_QUIET, RATE_DEC, RATE_INC, READING_PUNC_DEC, READING_PUNC_INC, SAY_ATTRIBUTES, SAY_FROM_LEFT, SAY_FROM_TOP, SAY_POSITION, SAY_SCREEN, SAY_TO_BOTTOM, SAY_TO_RIGHT, SPK_KEY, SPK_LOCK, SPEAKUP_OFF, SPEECH_KILL, SPELL_DELAY_DEC, SPELL_DELAY_INC, SPELL_WORD, SPELL_PHONETIC, TONE_DEC, TONE_INC, VOICE_DEC, VOICE_INC, VOL_DEC, VOL_INC, CLEAR_WIN, SAY_WIN, SET_WIN, ENABLE_WIN, SAY_WORD, SAY_NEXT_WORD, SAY_PREV_WORD, 0 }; static u_char *state_tbl; static int cur_item, nstates; static void build_key_data(void) { u_char *kp, counters[MAXFUNCS], ch, ch1; u_short *p_key = key_data, key; int i, offset = 1; nstates = (int)(state_tbl[-1]); memset(counters, 0, sizeof(counters)); memset(key_offsets, 0, sizeof(key_offsets)); kp = state_tbl + nstates + 1; while (*kp++) { /* count occurrences of each function */ for (i = 0; i < nstates; i++, kp++) { if (!*kp) continue; if ((state_tbl[i]&16) != 0 && *kp == SPK_KEY) continue; counters[*kp]++; } } for (i = 0; i < MAXFUNCS; i++) { if (counters[i] == 0) continue; key_offsets[i] = offset; offset += (counters[i]+1); if (offset >= MAXKEYS) break; } /* leave counters set so high keycodes come first. * this is done so num pad and other extended keys maps are spoken before * the alpha with speakup type mapping. */ kp = state_tbl + nstates + 1; while ((ch = *kp++)) { for (i = 0; i < nstates; i++) { ch1 = *kp++; if (!ch1) continue; if ((state_tbl[i]&16) != 0 && ch1 == SPK_KEY) continue; key = (state_tbl[i] << 8) + ch; counters[ch1]--; offset = key_offsets[ch1]; if (!offset) continue; p_key = key_data + offset + counters[ch1]; *p_key = key; } } } static void say_key(int key) { int i, state = key >> 8; key &= 0xff; for (i = 0; i < 6; i++) { if (state & masks[i]) synth_printf(" %s", msg_get(MSG_STATES_START + i)); } if ((key > 0) && (key <= num_key_names)) synth_printf(" %s\n", msg_get(MSG_KEYNAMES_START + (key - 1))); } static int help_init(void) { char start = SPACE; int i; int num_funcs = MSG_FUNCNAMES_END - MSG_FUNCNAMES_START + 1; state_tbl = our_keys[0]+SHIFT_TBL_SIZE+2; for (i = 0; i < num_funcs; i++) { char *cur_funcname = msg_get(MSG_FUNCNAMES_START + i); if (start == *cur_funcname) continue; start = *cur_funcname; letter_offsets[(start&31)-1] = i; } return 0; } int handle_help(struct vc_data *vc, u_char type, u_char ch, u_short key) { int i, n; char *name; u_char func, *kp; u_short *p_keys, val; if (letter_offsets[0] == -1) help_init(); if (type == KT_LATIN) { if (ch == SPACE) { special_handler = NULL; synth_printf("%s\n", msg_get(MSG_LEAVING_HELP)); return 1; } ch |= 32; /* lower case */ if (ch < 'a' || ch > 'z') return -1; if (letter_offsets[ch-'a'] == -1) { synth_printf(msg_get(MSG_NO_COMMAND), ch); synth_printf("\n"); return 1; } cur_item = letter_offsets[ch-'a']; } else if (type == KT_CUR) { if (ch == 0 && (MSG_FUNCNAMES_START + cur_item + 1) <= MSG_FUNCNAMES_END) cur_item++; else if (ch == 3 && cur_item > 0) cur_item--; else return -1; } else if (type == KT_SPKUP && ch == SPEAKUP_HELP && !special_handler) { special_handler = handle_help; synth_printf("%s\n", msg_get(MSG_HELP_INFO)); build_key_data(); /* rebuild each time in case new mapping */ return 1; } else { name = NULL; if ((type != KT_SPKUP) && (key > 0) && (key <= num_key_names)) { synth_printf("%s\n", msg_get(MSG_KEYNAMES_START + key-1)); return 1; } for (i = 0; funcvals[i] != 0 && !name; i++) { if (ch == funcvals[i]) name = msg_get(MSG_FUNCNAMES_START + i); } if (!name) return -1; kp = our_keys[key]+1; for (i = 0; i < nstates; i++) { if (ch == kp[i]) break; } key += (state_tbl[i] << 8); say_key(key); synth_printf(msg_get(MSG_KEYDESC), name); synth_printf("\n"); return 1; } name = msg_get(MSG_FUNCNAMES_START + cur_item); func = funcvals[cur_item]; synth_printf("%s", name); if (key_offsets[func] == 0) { synth_printf(" %s\n", msg_get(MSG_IS_UNASSIGNED)); return 1; } p_keys = key_data + key_offsets[func]; for (n = 0; p_keys[n]; n++) { val = p_keys[n]; if (n > 0) synth_printf("%s ", msg_get(MSG_DISJUNCTION)); say_key(val); } return 1; }
gpl-2.0
zombah/ubuntu-ac100
drivers/staging/speakup/keyhelp.c
7422
6108
/* speakup_keyhelp.c * help module for speakup * *written by David Borowski. * * Copyright (C) 2003 David Borowski. * * 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/keyboard.h> #include "spk_priv.h" #include "speakup.h" #define MAXFUNCS 130 #define MAXKEYS 256 static const int num_key_names = MSG_KEYNAMES_END - MSG_KEYNAMES_START + 1; static u_short key_offsets[MAXFUNCS], key_data[MAXKEYS]; static u_short masks[] = { 32, 16, 8, 4, 2, 1 }; static short letter_offsets[26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static u_char funcvals[] = { ATTRIB_BLEEP_DEC, ATTRIB_BLEEP_INC, BLEEPS_DEC, BLEEPS_INC, SAY_FIRST_CHAR, SAY_LAST_CHAR, SAY_CHAR, SAY_CHAR_NUM, SAY_NEXT_CHAR, SAY_PHONETIC_CHAR, SAY_PREV_CHAR, SPEAKUP_PARKED, SPEAKUP_CUT, EDIT_DELIM, EDIT_EXNUM, EDIT_MOST, EDIT_REPEAT, EDIT_SOME, SPEAKUP_GOTO, BOTTOM_EDGE, LEFT_EDGE, RIGHT_EDGE, TOP_EDGE, SPEAKUP_HELP, SAY_LINE, SAY_NEXT_LINE, SAY_PREV_LINE, SAY_LINE_INDENT, SPEAKUP_PASTE, PITCH_DEC, PITCH_INC, PUNCT_DEC, PUNCT_INC, PUNC_LEVEL_DEC, PUNC_LEVEL_INC, SPEAKUP_QUIET, RATE_DEC, RATE_INC, READING_PUNC_DEC, READING_PUNC_INC, SAY_ATTRIBUTES, SAY_FROM_LEFT, SAY_FROM_TOP, SAY_POSITION, SAY_SCREEN, SAY_TO_BOTTOM, SAY_TO_RIGHT, SPK_KEY, SPK_LOCK, SPEAKUP_OFF, SPEECH_KILL, SPELL_DELAY_DEC, SPELL_DELAY_INC, SPELL_WORD, SPELL_PHONETIC, TONE_DEC, TONE_INC, VOICE_DEC, VOICE_INC, VOL_DEC, VOL_INC, CLEAR_WIN, SAY_WIN, SET_WIN, ENABLE_WIN, SAY_WORD, SAY_NEXT_WORD, SAY_PREV_WORD, 0 }; static u_char *state_tbl; static int cur_item, nstates; static void build_key_data(void) { u_char *kp, counters[MAXFUNCS], ch, ch1; u_short *p_key = key_data, key; int i, offset = 1; nstates = (int)(state_tbl[-1]); memset(counters, 0, sizeof(counters)); memset(key_offsets, 0, sizeof(key_offsets)); kp = state_tbl + nstates + 1; while (*kp++) { /* count occurrences of each function */ for (i = 0; i < nstates; i++, kp++) { if (!*kp) continue; if ((state_tbl[i]&16) != 0 && *kp == SPK_KEY) continue; counters[*kp]++; } } for (i = 0; i < MAXFUNCS; i++) { if (counters[i] == 0) continue; key_offsets[i] = offset; offset += (counters[i]+1); if (offset >= MAXKEYS) break; } /* leave counters set so high keycodes come first. * this is done so num pad and other extended keys maps are spoken before * the alpha with speakup type mapping. */ kp = state_tbl + nstates + 1; while ((ch = *kp++)) { for (i = 0; i < nstates; i++) { ch1 = *kp++; if (!ch1) continue; if ((state_tbl[i]&16) != 0 && ch1 == SPK_KEY) continue; key = (state_tbl[i] << 8) + ch; counters[ch1]--; offset = key_offsets[ch1]; if (!offset) continue; p_key = key_data + offset + counters[ch1]; *p_key = key; } } } static void say_key(int key) { int i, state = key >> 8; key &= 0xff; for (i = 0; i < 6; i++) { if (state & masks[i]) synth_printf(" %s", msg_get(MSG_STATES_START + i)); } if ((key > 0) && (key <= num_key_names)) synth_printf(" %s\n", msg_get(MSG_KEYNAMES_START + (key - 1))); } static int help_init(void) { char start = SPACE; int i; int num_funcs = MSG_FUNCNAMES_END - MSG_FUNCNAMES_START + 1; state_tbl = our_keys[0]+SHIFT_TBL_SIZE+2; for (i = 0; i < num_funcs; i++) { char *cur_funcname = msg_get(MSG_FUNCNAMES_START + i); if (start == *cur_funcname) continue; start = *cur_funcname; letter_offsets[(start&31)-1] = i; } return 0; } int handle_help(struct vc_data *vc, u_char type, u_char ch, u_short key) { int i, n; char *name; u_char func, *kp; u_short *p_keys, val; if (letter_offsets[0] == -1) help_init(); if (type == KT_LATIN) { if (ch == SPACE) { special_handler = NULL; synth_printf("%s\n", msg_get(MSG_LEAVING_HELP)); return 1; } ch |= 32; /* lower case */ if (ch < 'a' || ch > 'z') return -1; if (letter_offsets[ch-'a'] == -1) { synth_printf(msg_get(MSG_NO_COMMAND), ch); synth_printf("\n"); return 1; } cur_item = letter_offsets[ch-'a']; } else if (type == KT_CUR) { if (ch == 0 && (MSG_FUNCNAMES_START + cur_item + 1) <= MSG_FUNCNAMES_END) cur_item++; else if (ch == 3 && cur_item > 0) cur_item--; else return -1; } else if (type == KT_SPKUP && ch == SPEAKUP_HELP && !special_handler) { special_handler = handle_help; synth_printf("%s\n", msg_get(MSG_HELP_INFO)); build_key_data(); /* rebuild each time in case new mapping */ return 1; } else { name = NULL; if ((type != KT_SPKUP) && (key > 0) && (key <= num_key_names)) { synth_printf("%s\n", msg_get(MSG_KEYNAMES_START + key-1)); return 1; } for (i = 0; funcvals[i] != 0 && !name; i++) { if (ch == funcvals[i]) name = msg_get(MSG_FUNCNAMES_START + i); } if (!name) return -1; kp = our_keys[key]+1; for (i = 0; i < nstates; i++) { if (ch == kp[i]) break; } key += (state_tbl[i] << 8); say_key(key); synth_printf(msg_get(MSG_KEYDESC), name); synth_printf("\n"); return 1; } name = msg_get(MSG_FUNCNAMES_START + cur_item); func = funcvals[cur_item]; synth_printf("%s", name); if (key_offsets[func] == 0) { synth_printf(" %s\n", msg_get(MSG_IS_UNASSIGNED)); return 1; } p_keys = key_data + key_offsets[func]; for (n = 0; p_keys[n]; n++) { val = p_keys[n]; if (n > 0) synth_printf("%s ", msg_get(MSG_DISJUNCTION)); say_key(val); } return 1; }
gpl-2.0
Donny3000/Gumstix-Overo-Kernel
arch/mips/math-emu/sp_mul.c
7678
4799
/* IEEE754 floating point arithmetic * single precision */ /* * MIPS floating point support * Copyright (C) 1994-2000 Algorithmics Ltd. * * ######################################################################## * * This program is free software; you can distribute it and/or modify it * under the terms of the GNU General Public License (Version 2) as * published by the Free Software Foundation. * * This program is distributed in the hope 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 "ieee754sp.h" ieee754sp ieee754sp_mul(ieee754sp x, ieee754sp y) { COMPXSP; COMPYSP; EXPLODEXSP; EXPLODEYSP; CLEARCX; FLUSHXSP; FLUSHYSP; switch (CLPAIR(xc, yc)) { case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_QNAN): case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_SNAN): case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_SNAN): case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_SNAN): case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_SNAN): case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_SNAN): case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_SNAN): case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_ZERO): case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_NORM): case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_DNORM): case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_INF): SETCX(IEEE754_INVALID_OPERATION); return ieee754sp_nanxcpt(ieee754sp_indef(), "mul", x, y); case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_QNAN): case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_QNAN): case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_QNAN): case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_QNAN): return y; case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_QNAN): case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_ZERO): case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_NORM): case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_DNORM): case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_INF): return x; /* Infinity handling */ case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_ZERO): case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_INF): SETCX(IEEE754_INVALID_OPERATION); return ieee754sp_xcpt(ieee754sp_indef(), "mul", x, y); case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_INF): case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_INF): case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_NORM): case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_DNORM): case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_INF): return ieee754sp_inf(xs ^ ys); case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_ZERO): case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_NORM): case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_DNORM): case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_ZERO): case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_ZERO): return ieee754sp_zero(xs ^ ys); case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_DNORM): SPDNORMX; case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_DNORM): SPDNORMY; break; case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_NORM): SPDNORMX; break; case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_NORM): break; } /* rm = xm * ym, re = xe+ye basically */ assert(xm & SP_HIDDEN_BIT); assert(ym & SP_HIDDEN_BIT); { int re = xe + ye; int rs = xs ^ ys; unsigned rm; /* shunt to top of word */ xm <<= 32 - (SP_MBITS + 1); ym <<= 32 - (SP_MBITS + 1); /* multiply 32bits xm,ym to give high 32bits rm with stickness */ { unsigned short lxm = xm & 0xffff; unsigned short hxm = xm >> 16; unsigned short lym = ym & 0xffff; unsigned short hym = ym >> 16; unsigned lrm; unsigned hrm; lrm = lxm * lym; /* 16 * 16 => 32 */ hrm = hxm * hym; /* 16 * 16 => 32 */ { unsigned t = lxm * hym; /* 16 * 16 => 32 */ { unsigned at = lrm + (t << 16); hrm += at < lrm; lrm = at; } hrm = hrm + (t >> 16); } { unsigned t = hxm * lym; /* 16 * 16 => 32 */ { unsigned at = lrm + (t << 16); hrm += at < lrm; lrm = at; } hrm = hrm + (t >> 16); } rm = hrm | (lrm != 0); } /* * sticky shift down to normal rounding precision */ if ((int) rm < 0) { rm = (rm >> (32 - (SP_MBITS + 1 + 3))) | ((rm << (SP_MBITS + 1 + 3)) != 0); re++; } else { rm = (rm >> (32 - (SP_MBITS + 1 + 3 + 1))) | ((rm << (SP_MBITS + 1 + 3 + 1)) != 0); } assert(rm & (SP_HIDDEN_BIT << 3)); SPNORMRET2(rs, re, rm, "mul", x, y); } }
gpl-2.0
guopengpeng/ap-module-kernel-renying
drivers/staging/rtl8192u/ieee80211/arc4.c
9470
2060
/* * Cryptographic API * * ARC4 Cipher Algorithm * * Jon Oberheide <jon@oberheide.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 2 of the License, or * (at your option) any later version. * */ #include <linux/module.h> #include <linux/init.h> #include "rtl_crypto.h" #define ARC4_MIN_KEY_SIZE 1 #define ARC4_MAX_KEY_SIZE 256 #define ARC4_BLOCK_SIZE 1 struct arc4_ctx { u8 S[256]; u8 x, y; }; static int arc4_set_key(void *ctx_arg, const u8 *in_key, unsigned int key_len, u32 *flags) { struct arc4_ctx *ctx = ctx_arg; int i, j = 0, k = 0; ctx->x = 1; ctx->y = 0; for(i = 0; i < 256; i++) ctx->S[i] = i; for(i = 0; i < 256; i++) { u8 a = ctx->S[i]; j = (j + in_key[k] + a) & 0xff; ctx->S[i] = ctx->S[j]; ctx->S[j] = a; if((unsigned int)++k >= key_len) k = 0; } return 0; } static void arc4_crypt(void *ctx_arg, u8 *out, const u8 *in) { struct arc4_ctx *ctx = ctx_arg; u8 *const S = ctx->S; u8 x = ctx->x; u8 y = ctx->y; u8 a, b; a = S[x]; y = (y + a) & 0xff; b = S[y]; S[x] = b; S[y] = a; x = (x + 1) & 0xff; *out++ = *in ^ S[(a + b) & 0xff]; ctx->x = x; ctx->y = y; } static struct crypto_alg arc4_alg = { .cra_name = "arc4", .cra_flags = CRYPTO_ALG_TYPE_CIPHER, .cra_blocksize = ARC4_BLOCK_SIZE, .cra_ctxsize = sizeof(struct arc4_ctx), .cra_module = THIS_MODULE, .cra_list = LIST_HEAD_INIT(arc4_alg.cra_list), .cra_u = { .cipher = { .cia_min_keysize = ARC4_MIN_KEY_SIZE, .cia_max_keysize = ARC4_MAX_KEY_SIZE, .cia_setkey = arc4_set_key, .cia_encrypt = arc4_crypt, .cia_decrypt = arc4_crypt } } }; static int __init arc4_init(void) { return crypto_register_alg(&arc4_alg); } static void __exit arc4_exit(void) { crypto_unregister_alg(&arc4_alg); } module_init(arc4_init); module_exit(arc4_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("ARC4 Cipher Algorithm"); MODULE_AUTHOR("Jon Oberheide <jon@oberheide.org>");
gpl-2.0
david-a-wheeler/linux
drivers/net/wireless/broadcom/b43/tables_phy_ht.c
10238
32970
/* Broadcom B43 wireless driver IEEE 802.11n HT-PHY data tables Copyright (c) 2011 Rafał Miłecki <zajec5@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 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. If not, write to the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "b43.h" #include "tables_phy_ht.h" #include "phy_common.h" #include "phy_ht.h" static const u16 b43_httab_0x12[] = { 0x0000, 0x0008, 0x000a, 0x0010, 0x0012, 0x0019, 0x001a, 0x001c, 0x0080, 0x0088, 0x008a, 0x0090, 0x0092, 0x0099, 0x009a, 0x009c, 0x0100, 0x0108, 0x010a, 0x0110, 0x0112, 0x0119, 0x011a, 0x011c, 0x0180, 0x0188, 0x018a, 0x0190, 0x0192, 0x0199, 0x019a, 0x019c, 0x0000, 0x0098, 0x00a0, 0x00a8, 0x009a, 0x00a2, 0x00aa, 0x0120, 0x0128, 0x0128, 0x0130, 0x0138, 0x0138, 0x0140, 0x0122, 0x012a, 0x012a, 0x0132, 0x013a, 0x013a, 0x0142, 0x01a8, 0x01b0, 0x01b8, 0x01b0, 0x01b8, 0x01c0, 0x01c8, 0x01c0, 0x01c8, 0x01d0, 0x01d0, 0x01d8, 0x01aa, 0x01b2, 0x01ba, 0x01b2, 0x01ba, 0x01c2, 0x01ca, 0x01c2, 0x01ca, 0x01d2, 0x01d2, 0x01da, 0x0001, 0x0002, 0x0004, 0x0009, 0x000c, 0x0011, 0x0014, 0x0018, 0x0020, 0x0021, 0x0022, 0x0024, 0x0081, 0x0082, 0x0084, 0x0089, 0x008c, 0x0091, 0x0094, 0x0098, 0x00a0, 0x00a1, 0x00a2, 0x00a4, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, 0x0007, }; static const u16 b43_httab_0x27[] = { 0x0009, 0x000e, 0x0011, 0x0014, 0x0017, 0x001a, 0x001d, 0x0020, 0x0009, 0x000e, 0x0011, 0x0014, 0x0017, 0x001a, 0x001d, 0x0020, 0x0009, 0x000e, 0x0011, 0x0014, 0x0017, 0x001a, 0x001d, 0x0020, 0x0009, 0x000e, 0x0011, 0x0014, 0x0017, 0x001a, 0x001d, 0x0020, }; static const u16 b43_httab_0x26[] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; static const u32 b43_httab_0x25[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; static const u32 b43_httab_0x2f[] = { 0x00035700, 0x0002cc9a, 0x00026666, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x00035700, 0x0002cc9a, 0x00026666, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, 0x0001581f, }; static const u16 b43_httab_0x1a[] = { 0x0055, 0x0054, 0x0054, 0x0053, 0x0052, 0x0052, 0x0051, 0x0051, 0x0050, 0x004f, 0x004f, 0x004e, 0x004e, 0x004d, 0x004c, 0x004c, 0x004b, 0x004a, 0x0049, 0x0049, 0x0048, 0x0047, 0x0046, 0x0046, 0x0045, 0x0044, 0x0043, 0x0042, 0x0041, 0x0040, 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0033, 0x0032, 0x0031, 0x002f, 0x002e, 0x002c, 0x002b, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021, 0x001f, 0x001d, 0x001a, 0x0018, 0x0015, 0x0012, 0x000e, 0x000b, 0x0007, 0x0002, 0x00fd, }; static const u16 b43_httab_0x1b[] = { 0x0055, 0x0054, 0x0054, 0x0053, 0x0052, 0x0052, 0x0051, 0x0051, 0x0050, 0x004f, 0x004f, 0x004e, 0x004e, 0x004d, 0x004c, 0x004c, 0x004b, 0x004a, 0x0049, 0x0049, 0x0048, 0x0047, 0x0046, 0x0046, 0x0045, 0x0044, 0x0043, 0x0042, 0x0041, 0x0040, 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0033, 0x0032, 0x0031, 0x002f, 0x002e, 0x002c, 0x002b, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021, 0x001f, 0x001d, 0x001a, 0x0018, 0x0015, 0x0012, 0x000e, 0x000b, 0x0007, 0x0002, 0x00fd, }; static const u16 b43_httab_0x1c[] = { 0x0055, 0x0054, 0x0054, 0x0053, 0x0052, 0x0052, 0x0051, 0x0051, 0x0050, 0x004f, 0x004f, 0x004e, 0x004e, 0x004d, 0x004c, 0x004c, 0x004b, 0x004a, 0x0049, 0x0049, 0x0048, 0x0047, 0x0046, 0x0046, 0x0045, 0x0044, 0x0043, 0x0042, 0x0041, 0x0040, 0x0040, 0x003f, 0x003e, 0x003d, 0x003c, 0x003a, 0x0039, 0x0038, 0x0037, 0x0036, 0x0035, 0x0033, 0x0032, 0x0031, 0x002f, 0x002e, 0x002c, 0x002b, 0x0029, 0x0027, 0x0025, 0x0023, 0x0021, 0x001f, 0x001d, 0x001a, 0x0018, 0x0015, 0x0012, 0x000e, 0x000b, 0x0007, 0x0002, 0x00fd, }; static const u32 b43_httab_0x1a_0xc0[] = { 0x5bf70044, 0x5bf70042, 0x5bf70040, 0x5bf7003e, 0x5bf7003c, 0x5bf7003b, 0x5bf70039, 0x5bf70037, 0x5bf70036, 0x5bf70034, 0x5bf70033, 0x5bf70031, 0x5bf70030, 0x5ba70044, 0x5ba70042, 0x5ba70040, 0x5ba7003e, 0x5ba7003c, 0x5ba7003b, 0x5ba70039, 0x5ba70037, 0x5ba70036, 0x5ba70034, 0x5ba70033, 0x5b770044, 0x5b770042, 0x5b770040, 0x5b77003e, 0x5b77003c, 0x5b77003b, 0x5b770039, 0x5b770037, 0x5b770036, 0x5b770034, 0x5b770033, 0x5b770031, 0x5b770030, 0x5b77002f, 0x5b77002d, 0x5b77002c, 0x5b470044, 0x5b470042, 0x5b470040, 0x5b47003e, 0x5b47003c, 0x5b47003b, 0x5b470039, 0x5b470037, 0x5b470036, 0x5b470034, 0x5b470033, 0x5b470031, 0x5b470030, 0x5b47002f, 0x5b47002d, 0x5b47002c, 0x5b47002b, 0x5b47002a, 0x5b270044, 0x5b270042, 0x5b270040, 0x5b27003e, 0x5b27003c, 0x5b27003b, 0x5b270039, 0x5b270037, 0x5b270036, 0x5b270034, 0x5b270033, 0x5b270031, 0x5b270030, 0x5b27002f, 0x5b170044, 0x5b170042, 0x5b170040, 0x5b17003e, 0x5b17003c, 0x5b17003b, 0x5b170039, 0x5b170037, 0x5b170036, 0x5b170034, 0x5b170033, 0x5b170031, 0x5b170030, 0x5b17002f, 0x5b17002d, 0x5b17002c, 0x5b17002b, 0x5b17002a, 0x5b170028, 0x5b170027, 0x5b170026, 0x5b170025, 0x5b170024, 0x5b170023, 0x5b070044, 0x5b070042, 0x5b070040, 0x5b07003e, 0x5b07003c, 0x5b07003b, 0x5b070039, 0x5b070037, 0x5b070036, 0x5b070034, 0x5b070033, 0x5b070031, 0x5b070030, 0x5b07002f, 0x5b07002d, 0x5b07002c, 0x5b07002b, 0x5b07002a, 0x5b070028, 0x5b070027, 0x5b070026, 0x5b070025, 0x5b070024, 0x5b070023, 0x5b070022, 0x5b070021, 0x5b070020, 0x5b07001f, 0x5b07001e, 0x5b07001d, 0x5b07001d, 0x5b07001c, }; static const u32 b43_httab_0x1a_0x140[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; static const u32 b43_httab_0x1b_0x140[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; static const u32 b43_httab_0x1c_0x140[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, }; static const u16 b43_httab_0x1a_0x1c0[] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; static const u16 b43_httab_0x1b_0x1c0[] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; static const u16 b43_httab_0x1c_0x1c0[] = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; static const u16 b43_httab_0x1a_0x240[] = { 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, }; static const u16 b43_httab_0x1b_0x240[] = { 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, }; static const u16 b43_httab_0x1c_0x240[] = { 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x0036, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x002a, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x001e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x000e, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01fc, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01ee, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, 0x01d6, }; static const u32 b43_httab_0x1f[] = { 0x00000000, 0x00000000, 0x00016023, 0x00006028, 0x00034036, 0x0003402e, 0x0007203c, 0x0006e037, 0x00070030, 0x0009401f, 0x0009a00f, 0x000b600d, 0x000c8007, 0x000ce007, 0x00101fff, 0x00121ff9, 0x0012e004, 0x0014dffc, 0x0016dff6, 0x0018dfe9, 0x001b3fe5, 0x001c5fd0, 0x001ddfc2, 0x001f1fb6, 0x00207fa4, 0x00219f8f, 0x0022ff7d, 0x00247f6c, 0x0024df5b, 0x00267f4b, 0x0027df3b, 0x0029bf3b, 0x002b5f2f, 0x002d3f2e, 0x002f5f2a, 0x002fff15, 0x00315f0b, 0x0032defa, 0x0033beeb, 0x0034fed9, 0x00353ec5, 0x00361eb0, 0x00363e9b, 0x0036be87, 0x0036be70, 0x0038fe67, 0x0044beb2, 0x00513ef3, 0x00595f11, 0x00669f3d, 0x0078dfdf, 0x00a143aa, 0x01642fff, 0x0162afff, 0x01620fff, 0x0160cfff, 0x015f0fff, 0x015dafff, 0x015bcfff, 0x015bcfff, 0x015b4fff, 0x015acfff, 0x01590fff, 0x0156cfff, }; static const u32 b43_httab_0x21[] = { 0x00000000, 0x00000000, 0x00016023, 0x00006028, 0x00034036, 0x0003402e, 0x0007203c, 0x0006e037, 0x00070030, 0x0009401f, 0x0009a00f, 0x000b600d, 0x000c8007, 0x000ce007, 0x00101fff, 0x00121ff9, 0x0012e004, 0x0014dffc, 0x0016dff6, 0x0018dfe9, 0x001b3fe5, 0x001c5fd0, 0x001ddfc2, 0x001f1fb6, 0x00207fa4, 0x00219f8f, 0x0022ff7d, 0x00247f6c, 0x0024df5b, 0x00267f4b, 0x0027df3b, 0x0029bf3b, 0x002b5f2f, 0x002d3f2e, 0x002f5f2a, 0x002fff15, 0x00315f0b, 0x0032defa, 0x0033beeb, 0x0034fed9, 0x00353ec5, 0x00361eb0, 0x00363e9b, 0x0036be87, 0x0036be70, 0x0038fe67, 0x0044beb2, 0x00513ef3, 0x00595f11, 0x00669f3d, 0x0078dfdf, 0x00a143aa, 0x01642fff, 0x0162afff, 0x01620fff, 0x0160cfff, 0x015f0fff, 0x015dafff, 0x015bcfff, 0x015bcfff, 0x015b4fff, 0x015acfff, 0x01590fff, 0x0156cfff, }; static const u32 b43_httab_0x23[] = { 0x00000000, 0x00000000, 0x00016023, 0x00006028, 0x00034036, 0x0003402e, 0x0007203c, 0x0006e037, 0x00070030, 0x0009401f, 0x0009a00f, 0x000b600d, 0x000c8007, 0x000ce007, 0x00101fff, 0x00121ff9, 0x0012e004, 0x0014dffc, 0x0016dff6, 0x0018dfe9, 0x001b3fe5, 0x001c5fd0, 0x001ddfc2, 0x001f1fb6, 0x00207fa4, 0x00219f8f, 0x0022ff7d, 0x00247f6c, 0x0024df5b, 0x00267f4b, 0x0027df3b, 0x0029bf3b, 0x002b5f2f, 0x002d3f2e, 0x002f5f2a, 0x002fff15, 0x00315f0b, 0x0032defa, 0x0033beeb, 0x0034fed9, 0x00353ec5, 0x00361eb0, 0x00363e9b, 0x0036be87, 0x0036be70, 0x0038fe67, 0x0044beb2, 0x00513ef3, 0x00595f11, 0x00669f3d, 0x0078dfdf, 0x00a143aa, 0x01642fff, 0x0162afff, 0x01620fff, 0x0160cfff, 0x015f0fff, 0x015dafff, 0x015bcfff, 0x015bcfff, 0x015b4fff, 0x015acfff, 0x01590fff, 0x0156cfff, }; static const u32 b43_httab_0x20[] = { 0x0b5e002d, 0x0ae2002f, 0x0a3b0032, 0x09a70035, 0x09220038, 0x08ab003b, 0x081f003f, 0x07a20043, 0x07340047, 0x06d2004b, 0x067a004f, 0x06170054, 0x05bf0059, 0x0571005e, 0x051e0064, 0x04d3006a, 0x04910070, 0x044c0077, 0x040f007e, 0x03d90085, 0x03a1008d, 0x036f0095, 0x033d009e, 0x030b00a8, 0x02e000b2, 0x02b900bc, 0x029200c7, 0x026d00d3, 0x024900e0, 0x022900ed, 0x020a00fb, 0x01ec010a, 0x01d20119, 0x01b7012a, 0x019e013c, 0x0188014e, 0x01720162, 0x015d0177, 0x0149018e, 0x013701a5, 0x012601be, 0x011501d8, 0x010601f4, 0x00f70212, 0x00e90231, 0x00dc0253, 0x00d00276, 0x00c4029b, 0x00b902c3, 0x00af02ed, 0x00a50319, 0x009c0348, 0x0093037a, 0x008b03af, 0x008303e6, 0x007c0422, 0x00750460, 0x006e04a3, 0x006804e9, 0x00620533, 0x005d0582, 0x005805d6, 0x0053062e, 0x004e068c, }; static const u32 b43_httab_0x22[] = { 0x0b5e002d, 0x0ae2002f, 0x0a3b0032, 0x09a70035, 0x09220038, 0x08ab003b, 0x081f003f, 0x07a20043, 0x07340047, 0x06d2004b, 0x067a004f, 0x06170054, 0x05bf0059, 0x0571005e, 0x051e0064, 0x04d3006a, 0x04910070, 0x044c0077, 0x040f007e, 0x03d90085, 0x03a1008d, 0x036f0095, 0x033d009e, 0x030b00a8, 0x02e000b2, 0x02b900bc, 0x029200c7, 0x026d00d3, 0x024900e0, 0x022900ed, 0x020a00fb, 0x01ec010a, 0x01d20119, 0x01b7012a, 0x019e013c, 0x0188014e, 0x01720162, 0x015d0177, 0x0149018e, 0x013701a5, 0x012601be, 0x011501d8, 0x010601f4, 0x00f70212, 0x00e90231, 0x00dc0253, 0x00d00276, 0x00c4029b, 0x00b902c3, 0x00af02ed, 0x00a50319, 0x009c0348, 0x0093037a, 0x008b03af, 0x008303e6, 0x007c0422, 0x00750460, 0x006e04a3, 0x006804e9, 0x00620533, 0x005d0582, 0x005805d6, 0x0053062e, 0x004e068c, }; static const u32 b43_httab_0x24[] = { 0x0b5e002d, 0x0ae2002f, 0x0a3b0032, 0x09a70035, 0x09220038, 0x08ab003b, 0x081f003f, 0x07a20043, 0x07340047, 0x06d2004b, 0x067a004f, 0x06170054, 0x05bf0059, 0x0571005e, 0x051e0064, 0x04d3006a, 0x04910070, 0x044c0077, 0x040f007e, 0x03d90085, 0x03a1008d, 0x036f0095, 0x033d009e, 0x030b00a8, 0x02e000b2, 0x02b900bc, 0x029200c7, 0x026d00d3, 0x024900e0, 0x022900ed, 0x020a00fb, 0x01ec010a, 0x01d20119, 0x01b7012a, 0x019e013c, 0x0188014e, 0x01720162, 0x015d0177, 0x0149018e, 0x013701a5, 0x012601be, 0x011501d8, 0x010601f4, 0x00f70212, 0x00e90231, 0x00dc0253, 0x00d00276, 0x00c4029b, 0x00b902c3, 0x00af02ed, 0x00a50319, 0x009c0348, 0x0093037a, 0x008b03af, 0x008303e6, 0x007c0422, 0x00750460, 0x006e04a3, 0x006804e9, 0x00620533, 0x005d0582, 0x005805d6, 0x0053062e, 0x004e068c, }; /* Some late-init table */ const u32 b43_httab_0x1a_0xc0_late[] = { 0x10f90040, 0x10e10040, 0x10e1003c, 0x10c9003d, 0x10b9003c, 0x10a9003d, 0x10a1003c, 0x1099003b, 0x1091003b, 0x1089003a, 0x1081003a, 0x10790039, 0x10710039, 0x1069003a, 0x1061003b, 0x1059003d, 0x1051003f, 0x10490042, 0x1049003e, 0x1049003b, 0x1041003e, 0x1041003b, 0x1039003e, 0x1039003b, 0x10390038, 0x10390035, 0x1031003a, 0x10310036, 0x10310033, 0x1029003a, 0x10290037, 0x10290034, 0x10290031, 0x10210039, 0x10210036, 0x10210033, 0x10210030, 0x1019003c, 0x10190039, 0x10190036, 0x10190033, 0x10190030, 0x1019002d, 0x1019002b, 0x10190028, 0x1011003a, 0x10110036, 0x10110033, 0x10110030, 0x1011002e, 0x1011002b, 0x10110029, 0x10110027, 0x10110024, 0x10110022, 0x10110020, 0x1011001f, 0x1011001d, 0x1009003a, 0x10090037, 0x10090034, 0x10090031, 0x1009002e, 0x1009002c, 0x10090029, 0x10090027, 0x10090025, 0x10090023, 0x10090021, 0x1009001f, 0x1009001d, 0x1009001b, 0x1009001a, 0x10090018, 0x10090017, 0x10090016, 0x10090015, 0x10090013, 0x10090012, 0x10090011, 0x10090010, 0x1009000f, 0x1009000f, 0x1009000e, 0x1009000d, 0x1009000c, 0x1009000c, 0x1009000b, 0x1009000a, 0x1009000a, 0x10090009, 0x10090009, 0x10090008, 0x10090008, 0x10090007, 0x10090007, 0x10090007, 0x10090006, 0x10090006, 0x10090005, 0x10090005, 0x10090005, 0x10090005, 0x10090004, 0x10090004, 0x10090004, 0x10090004, 0x10090003, 0x10090003, 0x10090003, 0x10090003, 0x10090003, 0x10090003, 0x10090002, 0x10090002, 0x10090002, 0x10090002, 0x10090002, 0x10090002, 0x10090002, 0x10090002, 0x10090002, 0x10090001, 0x10090001, 0x10090001, 0x10090001, 0x10090001, 0x10090001, }; /************************************************** * R/W ops. **************************************************/ u32 b43_httab_read(struct b43_wldev *dev, u32 offset) { u32 type, value; type = offset & B43_HTTAB_TYPEMASK; offset &= ~B43_HTTAB_TYPEMASK; B43_WARN_ON(offset > 0xFFFF); switch (type) { case B43_HTTAB_8BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); value = b43_phy_read(dev, B43_PHY_HT_TABLE_DATALO) & 0xFF; break; case B43_HTTAB_16BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); value = b43_phy_read(dev, B43_PHY_HT_TABLE_DATALO); break; case B43_HTTAB_32BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); value = b43_phy_read(dev, B43_PHY_HT_TABLE_DATAHI); value <<= 16; value |= b43_phy_read(dev, B43_PHY_HT_TABLE_DATALO); break; default: B43_WARN_ON(1); value = 0; } return value; } void b43_httab_read_bulk(struct b43_wldev *dev, u32 offset, unsigned int nr_elements, void *_data) { u32 type; u8 *data = _data; unsigned int i; type = offset & B43_HTTAB_TYPEMASK; offset &= ~B43_HTTAB_TYPEMASK; B43_WARN_ON(offset > 0xFFFF); b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); for (i = 0; i < nr_elements; i++) { switch (type) { case B43_HTTAB_8BIT: *data = b43_phy_read(dev, B43_PHY_HT_TABLE_DATALO) & 0xFF; data++; break; case B43_HTTAB_16BIT: *((u16 *)data) = b43_phy_read(dev, B43_PHY_HT_TABLE_DATALO); data += 2; break; case B43_HTTAB_32BIT: *((u32 *)data) = b43_phy_read(dev, B43_PHY_HT_TABLE_DATAHI); *((u32 *)data) <<= 16; *((u32 *)data) |= b43_phy_read(dev, B43_PHY_HT_TABLE_DATALO); data += 4; break; default: B43_WARN_ON(1); } } } void b43_httab_write(struct b43_wldev *dev, u32 offset, u32 value) { u32 type; type = offset & B43_HTTAB_TYPEMASK; offset &= 0xFFFF; switch (type) { case B43_HTTAB_8BIT: B43_WARN_ON(value & ~0xFF); b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value); break; case B43_HTTAB_16BIT: B43_WARN_ON(value & ~0xFFFF); b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value); break; case B43_HTTAB_32BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); b43_phy_write(dev, B43_PHY_HT_TABLE_DATAHI, value >> 16); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value & 0xFFFF); break; default: B43_WARN_ON(1); } return; } void b43_httab_write_few(struct b43_wldev *dev, u32 offset, size_t num, ...) { va_list args; u32 type, value; unsigned int i; type = offset & B43_HTTAB_TYPEMASK; offset &= 0xFFFF; va_start(args, num); switch (type) { case B43_HTTAB_8BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); for (i = 0; i < num; i++) { value = va_arg(args, int); B43_WARN_ON(value & ~0xFF); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value); } break; case B43_HTTAB_16BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); for (i = 0; i < num; i++) { value = va_arg(args, int); B43_WARN_ON(value & ~0xFFFF); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value); } break; case B43_HTTAB_32BIT: b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); for (i = 0; i < num; i++) { value = va_arg(args, int); b43_phy_write(dev, B43_PHY_HT_TABLE_DATAHI, value >> 16); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value & 0xFFFF); } break; default: B43_WARN_ON(1); } va_end(args); return; } void b43_httab_write_bulk(struct b43_wldev *dev, u32 offset, unsigned int nr_elements, const void *_data) { u32 type, value; const u8 *data = _data; unsigned int i; type = offset & B43_HTTAB_TYPEMASK; offset &= ~B43_HTTAB_TYPEMASK; B43_WARN_ON(offset > 0xFFFF); b43_phy_write(dev, B43_PHY_HT_TABLE_ADDR, offset); for (i = 0; i < nr_elements; i++) { switch (type) { case B43_HTTAB_8BIT: value = *data; data++; B43_WARN_ON(value & ~0xFF); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value); break; case B43_HTTAB_16BIT: value = *((u16 *)data); data += 2; B43_WARN_ON(value & ~0xFFFF); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value); break; case B43_HTTAB_32BIT: value = *((u32 *)data); data += 4; b43_phy_write(dev, B43_PHY_HT_TABLE_DATAHI, value >> 16); b43_phy_write(dev, B43_PHY_HT_TABLE_DATALO, value & 0xFFFF); break; default: B43_WARN_ON(1); } } } /************************************************** * Tables ops. **************************************************/ #define httab_upload(dev, offset, data) do { \ b43_httab_write_bulk(dev, offset, ARRAY_SIZE(data), data); \ } while (0) void b43_phy_ht_tables_init(struct b43_wldev *dev) { BUILD_BUG_ON(ARRAY_SIZE(b43_httab_0x1a_0xc0_late) != B43_HTTAB_1A_C0_LATE_SIZE); httab_upload(dev, B43_HTTAB16(0x12, 0), b43_httab_0x12); httab_upload(dev, B43_HTTAB16(0x27, 0), b43_httab_0x27); httab_upload(dev, B43_HTTAB16(0x26, 0), b43_httab_0x26); httab_upload(dev, B43_HTTAB32(0x25, 0), b43_httab_0x25); httab_upload(dev, B43_HTTAB32(0x2f, 0), b43_httab_0x2f); httab_upload(dev, B43_HTTAB16(0x1a, 0), b43_httab_0x1a); httab_upload(dev, B43_HTTAB16(0x1b, 0), b43_httab_0x1b); httab_upload(dev, B43_HTTAB16(0x1c, 0), b43_httab_0x1c); httab_upload(dev, B43_HTTAB32(0x1a, 0x0c0), b43_httab_0x1a_0xc0); httab_upload(dev, B43_HTTAB32(0x1a, 0x140), b43_httab_0x1a_0x140); httab_upload(dev, B43_HTTAB32(0x1b, 0x140), b43_httab_0x1b_0x140); httab_upload(dev, B43_HTTAB32(0x1c, 0x140), b43_httab_0x1c_0x140); httab_upload(dev, B43_HTTAB16(0x1a, 0x1c0), b43_httab_0x1a_0x1c0); httab_upload(dev, B43_HTTAB16(0x1b, 0x1c0), b43_httab_0x1b_0x1c0); httab_upload(dev, B43_HTTAB16(0x1c, 0x1c0), b43_httab_0x1c_0x1c0); httab_upload(dev, B43_HTTAB16(0x1a, 0x240), b43_httab_0x1a_0x240); httab_upload(dev, B43_HTTAB16(0x1b, 0x240), b43_httab_0x1b_0x240); httab_upload(dev, B43_HTTAB16(0x1c, 0x240), b43_httab_0x1c_0x240); httab_upload(dev, B43_HTTAB32(0x1f, 0), b43_httab_0x1f); httab_upload(dev, B43_HTTAB32(0x21, 0), b43_httab_0x21); httab_upload(dev, B43_HTTAB32(0x23, 0), b43_httab_0x23); httab_upload(dev, B43_HTTAB32(0x20, 0), b43_httab_0x20); httab_upload(dev, B43_HTTAB32(0x22, 0), b43_httab_0x22); httab_upload(dev, B43_HTTAB32(0x24, 0), b43_httab_0x24); }
gpl-2.0
darkspr1te/kernel_samsung_msm8660_shv-e160L
fs/jfs/jfs_metapage.c
10238
20060
/* * Copyright (C) International Business Machines Corp., 2000-2005 * Portions Copyright (C) Christoph Hellwig, 2001-2002 * * 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/fs.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/bio.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/buffer_head.h> #include <linux/mempool.h> #include <linux/seq_file.h> #include "jfs_incore.h" #include "jfs_superblock.h" #include "jfs_filsys.h" #include "jfs_metapage.h" #include "jfs_txnmgr.h" #include "jfs_debug.h" #ifdef CONFIG_JFS_STATISTICS static struct { uint pagealloc; /* # of page allocations */ uint pagefree; /* # of page frees */ uint lockwait; /* # of sleeping lock_metapage() calls */ } mpStat; #endif #define metapage_locked(mp) test_bit(META_locked, &(mp)->flag) #define trylock_metapage(mp) test_and_set_bit_lock(META_locked, &(mp)->flag) static inline void unlock_metapage(struct metapage *mp) { clear_bit_unlock(META_locked, &mp->flag); wake_up(&mp->wait); } static inline void __lock_metapage(struct metapage *mp) { DECLARE_WAITQUEUE(wait, current); INCREMENT(mpStat.lockwait); add_wait_queue_exclusive(&mp->wait, &wait); do { set_current_state(TASK_UNINTERRUPTIBLE); if (metapage_locked(mp)) { unlock_page(mp->page); io_schedule(); lock_page(mp->page); } } while (trylock_metapage(mp)); __set_current_state(TASK_RUNNING); remove_wait_queue(&mp->wait, &wait); } /* * Must have mp->page locked */ static inline void lock_metapage(struct metapage *mp) { if (trylock_metapage(mp)) __lock_metapage(mp); } #define METAPOOL_MIN_PAGES 32 static struct kmem_cache *metapage_cache; static mempool_t *metapage_mempool; #define MPS_PER_PAGE (PAGE_CACHE_SIZE >> L2PSIZE) #if MPS_PER_PAGE > 1 struct meta_anchor { int mp_count; atomic_t io_count; struct metapage *mp[MPS_PER_PAGE]; }; #define mp_anchor(page) ((struct meta_anchor *)page_private(page)) static inline struct metapage *page_to_mp(struct page *page, int offset) { if (!PagePrivate(page)) return NULL; return mp_anchor(page)->mp[offset >> L2PSIZE]; } static inline int insert_metapage(struct page *page, struct metapage *mp) { struct meta_anchor *a; int index; int l2mp_blocks; /* log2 blocks per metapage */ if (PagePrivate(page)) a = mp_anchor(page); else { a = kzalloc(sizeof(struct meta_anchor), GFP_NOFS); if (!a) return -ENOMEM; set_page_private(page, (unsigned long)a); SetPagePrivate(page); kmap(page); } if (mp) { l2mp_blocks = L2PSIZE - page->mapping->host->i_blkbits; index = (mp->index >> l2mp_blocks) & (MPS_PER_PAGE - 1); a->mp_count++; a->mp[index] = mp; } return 0; } static inline void remove_metapage(struct page *page, struct metapage *mp) { struct meta_anchor *a = mp_anchor(page); int l2mp_blocks = L2PSIZE - page->mapping->host->i_blkbits; int index; index = (mp->index >> l2mp_blocks) & (MPS_PER_PAGE - 1); BUG_ON(a->mp[index] != mp); a->mp[index] = NULL; if (--a->mp_count == 0) { kfree(a); set_page_private(page, 0); ClearPagePrivate(page); kunmap(page); } } static inline void inc_io(struct page *page) { atomic_inc(&mp_anchor(page)->io_count); } static inline void dec_io(struct page *page, void (*handler) (struct page *)) { if (atomic_dec_and_test(&mp_anchor(page)->io_count)) handler(page); } #else static inline struct metapage *page_to_mp(struct page *page, int offset) { return PagePrivate(page) ? (struct metapage *)page_private(page) : NULL; } static inline int insert_metapage(struct page *page, struct metapage *mp) { if (mp) { set_page_private(page, (unsigned long)mp); SetPagePrivate(page); kmap(page); } return 0; } static inline void remove_metapage(struct page *page, struct metapage *mp) { set_page_private(page, 0); ClearPagePrivate(page); kunmap(page); } #define inc_io(page) do {} while(0) #define dec_io(page, handler) handler(page) #endif static void init_once(void *foo) { struct metapage *mp = (struct metapage *)foo; mp->lid = 0; mp->lsn = 0; mp->flag = 0; mp->data = NULL; mp->clsn = 0; mp->log = NULL; set_bit(META_free, &mp->flag); init_waitqueue_head(&mp->wait); } static inline struct metapage *alloc_metapage(gfp_t gfp_mask) { return mempool_alloc(metapage_mempool, gfp_mask); } static inline void free_metapage(struct metapage *mp) { mp->flag = 0; set_bit(META_free, &mp->flag); mempool_free(mp, metapage_mempool); } int __init metapage_init(void) { /* * Allocate the metapage structures */ metapage_cache = kmem_cache_create("jfs_mp", sizeof(struct metapage), 0, 0, init_once); if (metapage_cache == NULL) return -ENOMEM; metapage_mempool = mempool_create_slab_pool(METAPOOL_MIN_PAGES, metapage_cache); if (metapage_mempool == NULL) { kmem_cache_destroy(metapage_cache); return -ENOMEM; } return 0; } void metapage_exit(void) { mempool_destroy(metapage_mempool); kmem_cache_destroy(metapage_cache); } static inline void drop_metapage(struct page *page, struct metapage *mp) { if (mp->count || mp->nohomeok || test_bit(META_dirty, &mp->flag) || test_bit(META_io, &mp->flag)) return; remove_metapage(page, mp); INCREMENT(mpStat.pagefree); free_metapage(mp); } /* * Metapage address space operations */ static sector_t metapage_get_blocks(struct inode *inode, sector_t lblock, int *len) { int rc = 0; int xflag; s64 xaddr; sector_t file_blocks = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_blkbits; if (lblock >= file_blocks) return 0; if (lblock + *len > file_blocks) *len = file_blocks - lblock; if (inode->i_ino) { rc = xtLookup(inode, (s64)lblock, *len, &xflag, &xaddr, len, 0); if ((rc == 0) && *len) lblock = (sector_t)xaddr; else lblock = 0; } /* else no mapping */ return lblock; } static void last_read_complete(struct page *page) { if (!PageError(page)) SetPageUptodate(page); unlock_page(page); } static void metapage_read_end_io(struct bio *bio, int err) { struct page *page = bio->bi_private; if (!test_bit(BIO_UPTODATE, &bio->bi_flags)) { printk(KERN_ERR "metapage_read_end_io: I/O error\n"); SetPageError(page); } dec_io(page, last_read_complete); bio_put(bio); } static void remove_from_logsync(struct metapage *mp) { struct jfs_log *log = mp->log; unsigned long flags; /* * This can race. Recheck that log hasn't been set to null, and after * acquiring logsync lock, recheck lsn */ if (!log) return; LOGSYNC_LOCK(log, flags); if (mp->lsn) { mp->log = NULL; mp->lsn = 0; mp->clsn = 0; log->count--; list_del(&mp->synclist); } LOGSYNC_UNLOCK(log, flags); } static void last_write_complete(struct page *page) { struct metapage *mp; unsigned int offset; for (offset = 0; offset < PAGE_CACHE_SIZE; offset += PSIZE) { mp = page_to_mp(page, offset); if (mp && test_bit(META_io, &mp->flag)) { if (mp->lsn) remove_from_logsync(mp); clear_bit(META_io, &mp->flag); } /* * I'd like to call drop_metapage here, but I don't think it's * safe unless I have the page locked */ } end_page_writeback(page); } static void metapage_write_end_io(struct bio *bio, int err) { struct page *page = bio->bi_private; BUG_ON(!PagePrivate(page)); if (! test_bit(BIO_UPTODATE, &bio->bi_flags)) { printk(KERN_ERR "metapage_write_end_io: I/O error\n"); SetPageError(page); } dec_io(page, last_write_complete); bio_put(bio); } static int metapage_writepage(struct page *page, struct writeback_control *wbc) { struct bio *bio = NULL; int block_offset; /* block offset of mp within page */ struct inode *inode = page->mapping->host; int blocks_per_mp = JFS_SBI(inode->i_sb)->nbperpage; int len; int xlen; struct metapage *mp; int redirty = 0; sector_t lblock; int nr_underway = 0; sector_t pblock; sector_t next_block = 0; sector_t page_start; unsigned long bio_bytes = 0; unsigned long bio_offset = 0; int offset; int bad_blocks = 0; page_start = (sector_t)page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits); BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); set_page_writeback(page); for (offset = 0; offset < PAGE_CACHE_SIZE; offset += PSIZE) { mp = page_to_mp(page, offset); if (!mp || !test_bit(META_dirty, &mp->flag)) continue; if (mp->nohomeok && !test_bit(META_forcewrite, &mp->flag)) { redirty = 1; /* * Make sure this page isn't blocked indefinitely. * If the journal isn't undergoing I/O, push it */ if (mp->log && !(mp->log->cflag & logGC_PAGEOUT)) jfs_flush_journal(mp->log, 0); continue; } clear_bit(META_dirty, &mp->flag); set_bit(META_io, &mp->flag); block_offset = offset >> inode->i_blkbits; lblock = page_start + block_offset; if (bio) { if (xlen && lblock == next_block) { /* Contiguous, in memory & on disk */ len = min(xlen, blocks_per_mp); xlen -= len; bio_bytes += len << inode->i_blkbits; continue; } /* Not contiguous */ if (bio_add_page(bio, page, bio_bytes, bio_offset) < bio_bytes) goto add_failed; /* * Increment counter before submitting i/o to keep * count from hitting zero before we're through */ inc_io(page); if (!bio->bi_size) goto dump_bio; submit_bio(WRITE, bio); nr_underway++; bio = NULL; } else inc_io(page); xlen = (PAGE_CACHE_SIZE - offset) >> inode->i_blkbits; pblock = metapage_get_blocks(inode, lblock, &xlen); if (!pblock) { printk(KERN_ERR "JFS: metapage_get_blocks failed\n"); /* * We already called inc_io(), but can't cancel it * with dec_io() until we're done with the page */ bad_blocks++; continue; } len = min(xlen, (int)JFS_SBI(inode->i_sb)->nbperpage); bio = bio_alloc(GFP_NOFS, 1); bio->bi_bdev = inode->i_sb->s_bdev; bio->bi_sector = pblock << (inode->i_blkbits - 9); bio->bi_end_io = metapage_write_end_io; bio->bi_private = page; /* Don't call bio_add_page yet, we may add to this vec */ bio_offset = offset; bio_bytes = len << inode->i_blkbits; xlen -= len; next_block = lblock + len; } if (bio) { if (bio_add_page(bio, page, bio_bytes, bio_offset) < bio_bytes) goto add_failed; if (!bio->bi_size) goto dump_bio; submit_bio(WRITE, bio); nr_underway++; } if (redirty) redirty_page_for_writepage(wbc, page); unlock_page(page); if (bad_blocks) goto err_out; if (nr_underway == 0) end_page_writeback(page); return 0; add_failed: /* We should never reach here, since we're only adding one vec */ printk(KERN_ERR "JFS: bio_add_page failed unexpectedly\n"); goto skip; dump_bio: print_hex_dump(KERN_ERR, "JFS: dump of bio: ", DUMP_PREFIX_ADDRESS, 16, 4, bio, sizeof(*bio), 0); skip: bio_put(bio); unlock_page(page); dec_io(page, last_write_complete); err_out: while (bad_blocks--) dec_io(page, last_write_complete); return -EIO; } static int metapage_readpage(struct file *fp, struct page *page) { struct inode *inode = page->mapping->host; struct bio *bio = NULL; int block_offset; int blocks_per_page = PAGE_CACHE_SIZE >> inode->i_blkbits; sector_t page_start; /* address of page in fs blocks */ sector_t pblock; int xlen; unsigned int len; int offset; BUG_ON(!PageLocked(page)); page_start = (sector_t)page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits); block_offset = 0; while (block_offset < blocks_per_page) { xlen = blocks_per_page - block_offset; pblock = metapage_get_blocks(inode, page_start + block_offset, &xlen); if (pblock) { if (!PagePrivate(page)) insert_metapage(page, NULL); inc_io(page); if (bio) submit_bio(READ, bio); bio = bio_alloc(GFP_NOFS, 1); bio->bi_bdev = inode->i_sb->s_bdev; bio->bi_sector = pblock << (inode->i_blkbits - 9); bio->bi_end_io = metapage_read_end_io; bio->bi_private = page; len = xlen << inode->i_blkbits; offset = block_offset << inode->i_blkbits; if (bio_add_page(bio, page, len, offset) < len) goto add_failed; block_offset += xlen; } else block_offset++; } if (bio) submit_bio(READ, bio); else unlock_page(page); return 0; add_failed: printk(KERN_ERR "JFS: bio_add_page failed unexpectedly\n"); bio_put(bio); dec_io(page, last_read_complete); return -EIO; } static int metapage_releasepage(struct page *page, gfp_t gfp_mask) { struct metapage *mp; int ret = 1; int offset; for (offset = 0; offset < PAGE_CACHE_SIZE; offset += PSIZE) { mp = page_to_mp(page, offset); if (!mp) continue; jfs_info("metapage_releasepage: mp = 0x%p", mp); if (mp->count || mp->nohomeok || test_bit(META_dirty, &mp->flag)) { jfs_info("count = %ld, nohomeok = %d", mp->count, mp->nohomeok); ret = 0; continue; } if (mp->lsn) remove_from_logsync(mp); remove_metapage(page, mp); INCREMENT(mpStat.pagefree); free_metapage(mp); } return ret; } static void metapage_invalidatepage(struct page *page, unsigned long offset) { BUG_ON(offset); BUG_ON(PageWriteback(page)); metapage_releasepage(page, 0); } const struct address_space_operations jfs_metapage_aops = { .readpage = metapage_readpage, .writepage = metapage_writepage, .releasepage = metapage_releasepage, .invalidatepage = metapage_invalidatepage, .set_page_dirty = __set_page_dirty_nobuffers, }; struct metapage *__get_metapage(struct inode *inode, unsigned long lblock, unsigned int size, int absolute, unsigned long new) { int l2BlocksPerPage; int l2bsize; struct address_space *mapping; struct metapage *mp = NULL; struct page *page; unsigned long page_index; unsigned long page_offset; jfs_info("__get_metapage: ino = %ld, lblock = 0x%lx, abs=%d", inode->i_ino, lblock, absolute); l2bsize = inode->i_blkbits; l2BlocksPerPage = PAGE_CACHE_SHIFT - l2bsize; page_index = lblock >> l2BlocksPerPage; page_offset = (lblock - (page_index << l2BlocksPerPage)) << l2bsize; if ((page_offset + size) > PAGE_CACHE_SIZE) { jfs_err("MetaData crosses page boundary!!"); jfs_err("lblock = %lx, size = %d", lblock, size); dump_stack(); return NULL; } if (absolute) mapping = JFS_SBI(inode->i_sb)->direct_inode->i_mapping; else { /* * If an nfs client tries to read an inode that is larger * than any existing inodes, we may try to read past the * end of the inode map */ if ((lblock << inode->i_blkbits) >= inode->i_size) return NULL; mapping = inode->i_mapping; } if (new && (PSIZE == PAGE_CACHE_SIZE)) { page = grab_cache_page(mapping, page_index); if (!page) { jfs_err("grab_cache_page failed!"); return NULL; } SetPageUptodate(page); } else { page = read_mapping_page(mapping, page_index, NULL); if (IS_ERR(page) || !PageUptodate(page)) { jfs_err("read_mapping_page failed!"); return NULL; } lock_page(page); } mp = page_to_mp(page, page_offset); if (mp) { if (mp->logical_size != size) { jfs_error(inode->i_sb, "__get_metapage: mp->logical_size != size"); jfs_err("logical_size = %d, size = %d", mp->logical_size, size); dump_stack(); goto unlock; } mp->count++; lock_metapage(mp); if (test_bit(META_discard, &mp->flag)) { if (!new) { jfs_error(inode->i_sb, "__get_metapage: using a " "discarded metapage"); discard_metapage(mp); goto unlock; } clear_bit(META_discard, &mp->flag); } } else { INCREMENT(mpStat.pagealloc); mp = alloc_metapage(GFP_NOFS); mp->page = page; mp->flag = 0; mp->xflag = COMMIT_PAGE; mp->count = 1; mp->nohomeok = 0; mp->logical_size = size; mp->data = page_address(page) + page_offset; mp->index = lblock; if (unlikely(insert_metapage(page, mp))) { free_metapage(mp); goto unlock; } lock_metapage(mp); } if (new) { jfs_info("zeroing mp = 0x%p", mp); memset(mp->data, 0, PSIZE); } unlock_page(page); jfs_info("__get_metapage: returning = 0x%p data = 0x%p", mp, mp->data); return mp; unlock: unlock_page(page); return NULL; } void grab_metapage(struct metapage * mp) { jfs_info("grab_metapage: mp = 0x%p", mp); page_cache_get(mp->page); lock_page(mp->page); mp->count++; lock_metapage(mp); unlock_page(mp->page); } void force_metapage(struct metapage *mp) { struct page *page = mp->page; jfs_info("force_metapage: mp = 0x%p", mp); set_bit(META_forcewrite, &mp->flag); clear_bit(META_sync, &mp->flag); page_cache_get(page); lock_page(page); set_page_dirty(page); write_one_page(page, 1); clear_bit(META_forcewrite, &mp->flag); page_cache_release(page); } void hold_metapage(struct metapage *mp) { lock_page(mp->page); } void put_metapage(struct metapage *mp) { if (mp->count || mp->nohomeok) { /* Someone else will release this */ unlock_page(mp->page); return; } page_cache_get(mp->page); mp->count++; lock_metapage(mp); unlock_page(mp->page); release_metapage(mp); } void release_metapage(struct metapage * mp) { struct page *page = mp->page; jfs_info("release_metapage: mp = 0x%p, flag = 0x%lx", mp, mp->flag); BUG_ON(!page); lock_page(page); unlock_metapage(mp); assert(mp->count); if (--mp->count || mp->nohomeok) { unlock_page(page); page_cache_release(page); return; } if (test_bit(META_dirty, &mp->flag)) { set_page_dirty(page); if (test_bit(META_sync, &mp->flag)) { clear_bit(META_sync, &mp->flag); write_one_page(page, 1); lock_page(page); /* write_one_page unlocks the page */ } } else if (mp->lsn) /* discard_metapage doesn't remove it */ remove_from_logsync(mp); /* Try to keep metapages from using up too much memory */ drop_metapage(page, mp); unlock_page(page); page_cache_release(page); } void __invalidate_metapages(struct inode *ip, s64 addr, int len) { sector_t lblock; int l2BlocksPerPage = PAGE_CACHE_SHIFT - ip->i_blkbits; int BlocksPerPage = 1 << l2BlocksPerPage; /* All callers are interested in block device's mapping */ struct address_space *mapping = JFS_SBI(ip->i_sb)->direct_inode->i_mapping; struct metapage *mp; struct page *page; unsigned int offset; /* * Mark metapages to discard. They will eventually be * released, but should not be written. */ for (lblock = addr & ~(BlocksPerPage - 1); lblock < addr + len; lblock += BlocksPerPage) { page = find_lock_page(mapping, lblock >> l2BlocksPerPage); if (!page) continue; for (offset = 0; offset < PAGE_CACHE_SIZE; offset += PSIZE) { mp = page_to_mp(page, offset); if (!mp) continue; if (mp->index < addr) continue; if (mp->index >= addr + len) break; clear_bit(META_dirty, &mp->flag); set_bit(META_discard, &mp->flag); if (mp->lsn) remove_from_logsync(mp); } unlock_page(page); page_cache_release(page); } } #ifdef CONFIG_JFS_STATISTICS static int jfs_mpstat_proc_show(struct seq_file *m, void *v) { seq_printf(m, "JFS Metapage statistics\n" "=======================\n" "page allocations = %d\n" "page frees = %d\n" "lock waits = %d\n", mpStat.pagealloc, mpStat.pagefree, mpStat.lockwait); return 0; } static int jfs_mpstat_proc_open(struct inode *inode, struct file *file) { return single_open(file, jfs_mpstat_proc_show, NULL); } const struct file_operations jfs_mpstat_proc_fops = { .owner = THIS_MODULE, .open = jfs_mpstat_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif
gpl-2.0
hroark13/n861_two_n860
fs/jfs/jfs_xtree.c
11518
94348
/* * Copyright (C) International Business Machines Corp., 2000-2005 * * 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 */ /* * jfs_xtree.c: extent allocation descriptor B+-tree manager */ #include <linux/fs.h> #include <linux/module.h> #include <linux/quotaops.h> #include <linux/seq_file.h> #include "jfs_incore.h" #include "jfs_filsys.h" #include "jfs_metapage.h" #include "jfs_dmap.h" #include "jfs_dinode.h" #include "jfs_superblock.h" #include "jfs_debug.h" /* * xtree local flag */ #define XT_INSERT 0x00000001 /* * xtree key/entry comparison: extent offset * * return: * -1: k < start of extent * 0: start_of_extent <= k <= end_of_extent * 1: k > end_of_extent */ #define XT_CMP(CMP, K, X, OFFSET64)\ {\ OFFSET64 = offsetXAD(X);\ (CMP) = ((K) >= OFFSET64 + lengthXAD(X)) ? 1 :\ ((K) < OFFSET64) ? -1 : 0;\ } /* write a xad entry */ #define XT_PUTENTRY(XAD, FLAG, OFF, LEN, ADDR)\ {\ (XAD)->flag = (FLAG);\ XADoffset((XAD), (OFF));\ XADlength((XAD), (LEN));\ XADaddress((XAD), (ADDR));\ } #define XT_PAGE(IP, MP) BT_PAGE(IP, MP, xtpage_t, i_xtroot) /* get page buffer for specified block address */ /* ToDo: Replace this ugly macro with a function */ #define XT_GETPAGE(IP, BN, MP, SIZE, P, RC)\ {\ BT_GETPAGE(IP, BN, MP, xtpage_t, SIZE, P, RC, i_xtroot)\ if (!(RC))\ {\ if ((le16_to_cpu((P)->header.nextindex) < XTENTRYSTART) ||\ (le16_to_cpu((P)->header.nextindex) > le16_to_cpu((P)->header.maxentry)) ||\ (le16_to_cpu((P)->header.maxentry) > (((BN)==0)?XTROOTMAXSLOT:PSIZE>>L2XTSLOTSIZE)))\ {\ jfs_error((IP)->i_sb, "XT_GETPAGE: xtree page corrupt");\ BT_PUTPAGE(MP);\ MP = NULL;\ RC = -EIO;\ }\ }\ } /* for consistency */ #define XT_PUTPAGE(MP) BT_PUTPAGE(MP) #define XT_GETSEARCH(IP, LEAF, BN, MP, P, INDEX) \ BT_GETSEARCH(IP, LEAF, BN, MP, xtpage_t, P, INDEX, i_xtroot) /* xtree entry parameter descriptor */ struct xtsplit { struct metapage *mp; s16 index; u8 flag; s64 off; s64 addr; int len; struct pxdlist *pxdlist; }; /* * statistics */ #ifdef CONFIG_JFS_STATISTICS static struct { uint search; uint fastSearch; uint split; } xtStat; #endif /* * forward references */ static int xtSearch(struct inode *ip, s64 xoff, s64 *next, int *cmpp, struct btstack * btstack, int flag); static int xtSplitUp(tid_t tid, struct inode *ip, struct xtsplit * split, struct btstack * btstack); static int xtSplitPage(tid_t tid, struct inode *ip, struct xtsplit * split, struct metapage ** rmpp, s64 * rbnp); static int xtSplitRoot(tid_t tid, struct inode *ip, struct xtsplit * split, struct metapage ** rmpp); #ifdef _STILL_TO_PORT static int xtDeleteUp(tid_t tid, struct inode *ip, struct metapage * fmp, xtpage_t * fp, struct btstack * btstack); static int xtSearchNode(struct inode *ip, xad_t * xad, int *cmpp, struct btstack * btstack, int flag); static int xtRelink(tid_t tid, struct inode *ip, xtpage_t * fp); #endif /* _STILL_TO_PORT */ /* * xtLookup() * * function: map a single page into a physical extent; */ int xtLookup(struct inode *ip, s64 lstart, s64 llen, int *pflag, s64 * paddr, s32 * plen, int no_check) { int rc = 0; struct btstack btstack; int cmp; s64 bn; struct metapage *mp; xtpage_t *p; int index; xad_t *xad; s64 next, size, xoff, xend; int xlen; s64 xaddr; *paddr = 0; *plen = llen; if (!no_check) { /* is lookup offset beyond eof ? */ size = ((u64) ip->i_size + (JFS_SBI(ip->i_sb)->bsize - 1)) >> JFS_SBI(ip->i_sb)->l2bsize; if (lstart >= size) return 0; } /* * search for the xad entry covering the logical extent */ //search: if ((rc = xtSearch(ip, lstart, &next, &cmp, &btstack, 0))) { jfs_err("xtLookup: xtSearch returned %d", rc); return rc; } /* * compute the physical extent covering logical extent * * N.B. search may have failed (e.g., hole in sparse file), * and returned the index of the next entry. */ /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); /* is xad found covering start of logical extent ? * lstart is a page start address, * i.e., lstart cannot start in a hole; */ if (cmp) { if (next) *plen = min(next - lstart, llen); goto out; } /* * lxd covered by xad */ xad = &p->xad[index]; xoff = offsetXAD(xad); xlen = lengthXAD(xad); xend = xoff + xlen; xaddr = addressXAD(xad); /* initialize new pxd */ *pflag = xad->flag; *paddr = xaddr + (lstart - xoff); /* a page must be fully covered by an xad */ *plen = min(xend - lstart, llen); out: XT_PUTPAGE(mp); return rc; } /* * xtSearch() * * function: search for the xad entry covering specified offset. * * parameters: * ip - file object; * xoff - extent offset; * nextp - address of next extent (if any) for search miss * cmpp - comparison result: * btstack - traverse stack; * flag - search process flag (XT_INSERT); * * returns: * btstack contains (bn, index) of search path traversed to the entry. * *cmpp is set to result of comparison with the entry returned. * the page containing the entry is pinned at exit. */ static int xtSearch(struct inode *ip, s64 xoff, s64 *nextp, int *cmpp, struct btstack * btstack, int flag) { struct jfs_inode_info *jfs_ip = JFS_IP(ip); int rc = 0; int cmp = 1; /* init for empty page */ s64 bn; /* block number */ struct metapage *mp; /* page buffer */ xtpage_t *p; /* page */ xad_t *xad; int base, index, lim, btindex; struct btframe *btsp; int nsplit = 0; /* number of pages to split */ s64 t64; s64 next = 0; INCREMENT(xtStat.search); BT_CLR(btstack); btstack->nsplit = 0; /* * search down tree from root: * * between two consecutive entries of <Ki, Pi> and <Kj, Pj> of * internal page, child page Pi contains entry with k, Ki <= K < Kj. * * if entry with search key K is not found * internal page search find the entry with largest key Ki * less than K which point to the child page to search; * leaf page search find the entry with smallest key Kj * greater than K so that the returned index is the position of * the entry to be shifted right for insertion of new entry. * for empty tree, search key is greater than any key of the tree. * * by convention, root bn = 0. */ for (bn = 0;;) { /* get/pin the page to search */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* try sequential access heuristics with the previous * access entry in target leaf page: * once search narrowed down into the target leaf, * key must either match an entry in the leaf or * key entry does not exist in the tree; */ //fastSearch: if ((jfs_ip->btorder & BT_SEQUENTIAL) && (p->header.flag & BT_LEAF) && (index = jfs_ip->btindex) < le16_to_cpu(p->header.nextindex)) { xad = &p->xad[index]; t64 = offsetXAD(xad); if (xoff < t64 + lengthXAD(xad)) { if (xoff >= t64) { *cmpp = 0; goto out; } /* stop sequential access heuristics */ goto binarySearch; } else { /* (t64 + lengthXAD(xad)) <= xoff */ /* try next sequential entry */ index++; if (index < le16_to_cpu(p->header.nextindex)) { xad++; t64 = offsetXAD(xad); if (xoff < t64 + lengthXAD(xad)) { if (xoff >= t64) { *cmpp = 0; goto out; } /* miss: key falls between * previous and this entry */ *cmpp = 1; next = t64; goto out; } /* (xoff >= t64 + lengthXAD(xad)); * matching entry may be further out: * stop heuristic search */ /* stop sequential access heuristics */ goto binarySearch; } /* (index == p->header.nextindex); * miss: key entry does not exist in * the target leaf/tree */ *cmpp = 1; goto out; } /* * if hit, return index of the entry found, and * if miss, where new entry with search key is * to be inserted; */ out: /* compute number of pages to split */ if (flag & XT_INSERT) { if (p->header.nextindex == /* little-endian */ p->header.maxentry) nsplit++; else nsplit = 0; btstack->nsplit = nsplit; } /* save search result */ btsp = btstack->top; btsp->bn = bn; btsp->index = index; btsp->mp = mp; /* update sequential access heuristics */ jfs_ip->btindex = index; if (nextp) *nextp = next; INCREMENT(xtStat.fastSearch); return 0; } /* well, ... full search now */ binarySearch: lim = le16_to_cpu(p->header.nextindex) - XTENTRYSTART; /* * binary search with search key K on the current page */ for (base = XTENTRYSTART; lim; lim >>= 1) { index = base + (lim >> 1); XT_CMP(cmp, xoff, &p->xad[index], t64); if (cmp == 0) { /* * search hit */ /* search hit - leaf page: * return the entry found */ if (p->header.flag & BT_LEAF) { *cmpp = cmp; /* compute number of pages to split */ if (flag & XT_INSERT) { if (p->header.nextindex == p->header.maxentry) nsplit++; else nsplit = 0; btstack->nsplit = nsplit; } /* save search result */ btsp = btstack->top; btsp->bn = bn; btsp->index = index; btsp->mp = mp; /* init sequential access heuristics */ btindex = jfs_ip->btindex; if (index == btindex || index == btindex + 1) jfs_ip->btorder = BT_SEQUENTIAL; else jfs_ip->btorder = BT_RANDOM; jfs_ip->btindex = index; return 0; } /* search hit - internal page: * descend/search its child page */ if (index < le16_to_cpu(p->header.nextindex)-1) next = offsetXAD(&p->xad[index + 1]); goto next; } if (cmp > 0) { base = index + 1; --lim; } } /* * search miss * * base is the smallest index with key (Kj) greater than * search key (K) and may be zero or maxentry index. */ if (base < le16_to_cpu(p->header.nextindex)) next = offsetXAD(&p->xad[base]); /* * search miss - leaf page: * * return location of entry (base) where new entry with * search key K is to be inserted. */ if (p->header.flag & BT_LEAF) { *cmpp = cmp; /* compute number of pages to split */ if (flag & XT_INSERT) { if (p->header.nextindex == p->header.maxentry) nsplit++; else nsplit = 0; btstack->nsplit = nsplit; } /* save search result */ btsp = btstack->top; btsp->bn = bn; btsp->index = base; btsp->mp = mp; /* init sequential access heuristics */ btindex = jfs_ip->btindex; if (base == btindex || base == btindex + 1) jfs_ip->btorder = BT_SEQUENTIAL; else jfs_ip->btorder = BT_RANDOM; jfs_ip->btindex = base; if (nextp) *nextp = next; return 0; } /* * search miss - non-leaf page: * * if base is non-zero, decrement base by one to get the parent * entry of the child page to search. */ index = base ? base - 1 : base; /* * go down to child page */ next: /* update number of pages to split */ if (p->header.nextindex == p->header.maxentry) nsplit++; else nsplit = 0; /* push (bn, index) of the parent page/entry */ if (BT_STACK_FULL(btstack)) { jfs_error(ip->i_sb, "stack overrun in xtSearch!"); XT_PUTPAGE(mp); return -EIO; } BT_PUSH(btstack, bn, index); /* get the child page block number */ bn = addressXAD(&p->xad[index]); /* unpin the parent page */ XT_PUTPAGE(mp); } } /* * xtInsert() * * function: * * parameter: * tid - transaction id; * ip - file object; * xflag - extent flag (XAD_NOTRECORDED): * xoff - extent offset; * xlen - extent length; * xaddrp - extent address pointer (in/out): * if (*xaddrp) * caller allocated data extent at *xaddrp; * else * allocate data extent and return its xaddr; * flag - * * return: */ int xtInsert(tid_t tid, /* transaction id */ struct inode *ip, int xflag, s64 xoff, s32 xlen, s64 * xaddrp, int flag) { int rc = 0; s64 xaddr, hint; struct metapage *mp; /* meta-page buffer */ xtpage_t *p; /* base B+-tree index page */ s64 bn; int index, nextindex; struct btstack btstack; /* traverse stack */ struct xtsplit split; /* split information */ xad_t *xad; int cmp; s64 next; struct tlock *tlck; struct xtlock *xtlck; jfs_info("xtInsert: nxoff:0x%lx nxlen:0x%x", (ulong) xoff, xlen); /* * search for the entry location at which to insert: * * xtFastSearch() and xtSearch() both returns (leaf page * pinned, index at which to insert). * n.b. xtSearch() may return index of maxentry of * the full page. */ if ((rc = xtSearch(ip, xoff, &next, &cmp, &btstack, XT_INSERT))) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); /* This test must follow XT_GETSEARCH since mp must be valid if * we branch to out: */ if ((cmp == 0) || (next && (xlen > next - xoff))) { rc = -EEXIST; goto out; } /* * allocate data extent requested * * allocation hint: last xad */ if ((xaddr = *xaddrp) == 0) { if (index > XTENTRYSTART) { xad = &p->xad[index - 1]; hint = addressXAD(xad) + lengthXAD(xad) - 1; } else hint = 0; if ((rc = dquot_alloc_block(ip, xlen))) goto out; if ((rc = dbAlloc(ip, hint, (s64) xlen, &xaddr))) { dquot_free_block(ip, xlen); goto out; } } /* * insert entry for new extent */ xflag |= XAD_NEW; /* * if the leaf page is full, split the page and * propagate up the router entry for the new page from split * * The xtSplitUp() will insert the entry and unpin the leaf page. */ nextindex = le16_to_cpu(p->header.nextindex); if (nextindex == le16_to_cpu(p->header.maxentry)) { split.mp = mp; split.index = index; split.flag = xflag; split.off = xoff; split.len = xlen; split.addr = xaddr; split.pxdlist = NULL; if ((rc = xtSplitUp(tid, ip, &split, &btstack))) { /* undo data extent allocation */ if (*xaddrp == 0) { dbFree(ip, xaddr, (s64) xlen); dquot_free_block(ip, xlen); } return rc; } *xaddrp = xaddr; return 0; } /* * insert the new entry into the leaf page */ /* * acquire a transaction lock on the leaf page; * * action: xad insertion/extension; */ BT_MARK_DIRTY(mp, ip); /* if insert into middle, shift right remaining entries. */ if (index < nextindex) memmove(&p->xad[index + 1], &p->xad[index], (nextindex - index) * sizeof(xad_t)); /* insert the new entry: mark the entry NEW */ xad = &p->xad[index]; XT_PUTENTRY(xad, xflag, xoff, xlen, xaddr); /* advance next available entry index */ le16_add_cpu(&p->header.nextindex, 1); /* Don't log it if there are no links to the file */ if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index, (int)xtlck->lwm.offset) : index; xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; } *xaddrp = xaddr; out: /* unpin the leaf page */ XT_PUTPAGE(mp); return rc; } /* * xtSplitUp() * * function: * split full pages as propagating insertion up the tree * * parameter: * tid - transaction id; * ip - file object; * split - entry parameter descriptor; * btstack - traverse stack from xtSearch() * * return: */ static int xtSplitUp(tid_t tid, struct inode *ip, struct xtsplit * split, struct btstack * btstack) { int rc = 0; struct metapage *smp; xtpage_t *sp; /* split page */ struct metapage *rmp; s64 rbn; /* new right page block number */ struct metapage *rcmp; xtpage_t *rcp; /* right child page */ s64 rcbn; /* right child page block number */ int skip; /* index of entry of insertion */ int nextindex; /* next available entry index of p */ struct btframe *parent; /* parent page entry on traverse stack */ xad_t *xad; s64 xaddr; int xlen; int nsplit; /* number of pages split */ struct pxdlist pxdlist; pxd_t *pxd; struct tlock *tlck; struct xtlock *xtlck; smp = split->mp; sp = XT_PAGE(ip, smp); /* is inode xtree root extension/inline EA area free ? */ if ((sp->header.flag & BT_ROOT) && (!S_ISDIR(ip->i_mode)) && (le16_to_cpu(sp->header.maxentry) < XTROOTMAXSLOT) && (JFS_IP(ip)->mode2 & INLINEEA)) { sp->header.maxentry = cpu_to_le16(XTROOTMAXSLOT); JFS_IP(ip)->mode2 &= ~INLINEEA; BT_MARK_DIRTY(smp, ip); /* * acquire a transaction lock on the leaf page; * * action: xad insertion/extension; */ /* if insert into middle, shift right remaining entries. */ skip = split->index; nextindex = le16_to_cpu(sp->header.nextindex); if (skip < nextindex) memmove(&sp->xad[skip + 1], &sp->xad[skip], (nextindex - skip) * sizeof(xad_t)); /* insert the new entry: mark the entry NEW */ xad = &sp->xad[skip]; XT_PUTENTRY(xad, split->flag, split->off, split->len, split->addr); /* advance next available entry index */ le16_add_cpu(&sp->header.nextindex, 1); /* Don't log it if there are no links to the file */ if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, smp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = (xtlck->lwm.offset) ? min(skip, (int)xtlck->lwm.offset) : skip; xtlck->lwm.length = le16_to_cpu(sp->header.nextindex) - xtlck->lwm.offset; } return 0; } /* * allocate new index blocks to cover index page split(s) * * allocation hint: ? */ if (split->pxdlist == NULL) { nsplit = btstack->nsplit; split->pxdlist = &pxdlist; pxdlist.maxnpxd = pxdlist.npxd = 0; pxd = &pxdlist.pxd[0]; xlen = JFS_SBI(ip->i_sb)->nbperpage; for (; nsplit > 0; nsplit--, pxd++) { if ((rc = dbAlloc(ip, (s64) 0, (s64) xlen, &xaddr)) == 0) { PXDaddress(pxd, xaddr); PXDlength(pxd, xlen); pxdlist.maxnpxd++; continue; } /* undo allocation */ XT_PUTPAGE(smp); return rc; } } /* * Split leaf page <sp> into <sp> and a new right page <rp>. * * The split routines insert the new entry into the leaf page, * and acquire txLock as appropriate. * return <rp> pinned and its block number <rpbn>. */ rc = (sp->header.flag & BT_ROOT) ? xtSplitRoot(tid, ip, split, &rmp) : xtSplitPage(tid, ip, split, &rmp, &rbn); XT_PUTPAGE(smp); if (rc) return -EIO; /* * propagate up the router entry for the leaf page just split * * insert a router entry for the new page into the parent page, * propagate the insert/split up the tree by walking back the stack * of (bn of parent page, index of child page entry in parent page) * that were traversed during the search for the page that split. * * the propagation of insert/split up the tree stops if the root * splits or the page inserted into doesn't have to split to hold * the new entry. * * the parent entry for the split page remains the same, and * a new entry is inserted at its right with the first key and * block number of the new right page. * * There are a maximum of 3 pages pinned at any time: * right child, left parent and right parent (when the parent splits) * to keep the child page pinned while working on the parent. * make sure that all pins are released at exit. */ while ((parent = BT_POP(btstack)) != NULL) { /* parent page specified by stack frame <parent> */ /* keep current child pages <rcp> pinned */ rcmp = rmp; rcbn = rbn; rcp = XT_PAGE(ip, rcmp); /* * insert router entry in parent for new right child page <rp> */ /* get/pin the parent page <sp> */ XT_GETPAGE(ip, parent->bn, smp, PSIZE, sp, rc); if (rc) { XT_PUTPAGE(rcmp); return rc; } /* * The new key entry goes ONE AFTER the index of parent entry, * because the split was to the right. */ skip = parent->index + 1; /* * split or shift right remaining entries of the parent page */ nextindex = le16_to_cpu(sp->header.nextindex); /* * parent page is full - split the parent page */ if (nextindex == le16_to_cpu(sp->header.maxentry)) { /* init for parent page split */ split->mp = smp; split->index = skip; /* index at insert */ split->flag = XAD_NEW; split->off = offsetXAD(&rcp->xad[XTENTRYSTART]); split->len = JFS_SBI(ip->i_sb)->nbperpage; split->addr = rcbn; /* unpin previous right child page */ XT_PUTPAGE(rcmp); /* The split routines insert the new entry, * and acquire txLock as appropriate. * return <rp> pinned and its block number <rpbn>. */ rc = (sp->header.flag & BT_ROOT) ? xtSplitRoot(tid, ip, split, &rmp) : xtSplitPage(tid, ip, split, &rmp, &rbn); if (rc) { XT_PUTPAGE(smp); return rc; } XT_PUTPAGE(smp); /* keep new child page <rp> pinned */ } /* * parent page is not full - insert in parent page */ else { /* * insert router entry in parent for the right child * page from the first entry of the right child page: */ /* * acquire a transaction lock on the parent page; * * action: router xad insertion; */ BT_MARK_DIRTY(smp, ip); /* * if insert into middle, shift right remaining entries */ if (skip < nextindex) memmove(&sp->xad[skip + 1], &sp->xad[skip], (nextindex - skip) << L2XTSLOTSIZE); /* insert the router entry */ xad = &sp->xad[skip]; XT_PUTENTRY(xad, XAD_NEW, offsetXAD(&rcp->xad[XTENTRYSTART]), JFS_SBI(ip->i_sb)->nbperpage, rcbn); /* advance next available entry index. */ le16_add_cpu(&sp->header.nextindex, 1); /* Don't log it if there are no links to the file */ if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, smp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = (xtlck->lwm.offset) ? min(skip, (int)xtlck->lwm.offset) : skip; xtlck->lwm.length = le16_to_cpu(sp->header.nextindex) - xtlck->lwm.offset; } /* unpin parent page */ XT_PUTPAGE(smp); /* exit propagate up */ break; } } /* unpin current right page */ XT_PUTPAGE(rmp); return 0; } /* * xtSplitPage() * * function: * split a full non-root page into * original/split/left page and new right page * i.e., the original/split page remains as left page. * * parameter: * int tid, * struct inode *ip, * struct xtsplit *split, * struct metapage **rmpp, * u64 *rbnp, * * return: * Pointer to page in which to insert or NULL on error. */ static int xtSplitPage(tid_t tid, struct inode *ip, struct xtsplit * split, struct metapage ** rmpp, s64 * rbnp) { int rc = 0; struct metapage *smp; xtpage_t *sp; struct metapage *rmp; xtpage_t *rp; /* new right page allocated */ s64 rbn; /* new right page block number */ struct metapage *mp; xtpage_t *p; s64 nextbn; int skip, maxentry, middle, righthalf, n; xad_t *xad; struct pxdlist *pxdlist; pxd_t *pxd; struct tlock *tlck; struct xtlock *sxtlck = NULL, *rxtlck = NULL; int quota_allocation = 0; smp = split->mp; sp = XT_PAGE(ip, smp); INCREMENT(xtStat.split); pxdlist = split->pxdlist; pxd = &pxdlist->pxd[pxdlist->npxd]; pxdlist->npxd++; rbn = addressPXD(pxd); /* Allocate blocks to quota. */ rc = dquot_alloc_block(ip, lengthPXD(pxd)); if (rc) goto clean_up; quota_allocation += lengthPXD(pxd); /* * allocate the new right page for the split */ rmp = get_metapage(ip, rbn, PSIZE, 1); if (rmp == NULL) { rc = -EIO; goto clean_up; } jfs_info("xtSplitPage: ip:0x%p smp:0x%p rmp:0x%p", ip, smp, rmp); BT_MARK_DIRTY(rmp, ip); /* * action: new page; */ rp = (xtpage_t *) rmp->data; rp->header.self = *pxd; rp->header.flag = sp->header.flag & BT_TYPE; rp->header.maxentry = sp->header.maxentry; /* little-endian */ rp->header.nextindex = cpu_to_le16(XTENTRYSTART); BT_MARK_DIRTY(smp, ip); /* Don't log it if there are no links to the file */ if (!test_cflag(COMMIT_Nolink, ip)) { /* * acquire a transaction lock on the new right page; */ tlck = txLock(tid, ip, rmp, tlckXTREE | tlckNEW); rxtlck = (struct xtlock *) & tlck->lock; rxtlck->lwm.offset = XTENTRYSTART; /* * acquire a transaction lock on the split page */ tlck = txLock(tid, ip, smp, tlckXTREE | tlckGROW); sxtlck = (struct xtlock *) & tlck->lock; } /* * initialize/update sibling pointers of <sp> and <rp> */ nextbn = le64_to_cpu(sp->header.next); rp->header.next = cpu_to_le64(nextbn); rp->header.prev = cpu_to_le64(addressPXD(&sp->header.self)); sp->header.next = cpu_to_le64(rbn); skip = split->index; /* * sequential append at tail (after last entry of last page) * * if splitting the last page on a level because of appending * a entry to it (skip is maxentry), it's likely that the access is * sequential. adding an empty page on the side of the level is less * work and can push the fill factor much higher than normal. * if we're wrong it's no big deal - we will do the split the right * way next time. * (it may look like it's equally easy to do a similar hack for * reverse sorted data, that is, split the tree left, but it's not. * Be my guest.) */ if (nextbn == 0 && skip == le16_to_cpu(sp->header.maxentry)) { /* * acquire a transaction lock on the new/right page; * * action: xad insertion; */ /* insert entry at the first entry of the new right page */ xad = &rp->xad[XTENTRYSTART]; XT_PUTENTRY(xad, split->flag, split->off, split->len, split->addr); rp->header.nextindex = cpu_to_le16(XTENTRYSTART + 1); if (!test_cflag(COMMIT_Nolink, ip)) { /* rxtlck->lwm.offset = XTENTRYSTART; */ rxtlck->lwm.length = 1; } *rmpp = rmp; *rbnp = rbn; jfs_info("xtSplitPage: sp:0x%p rp:0x%p", sp, rp); return 0; } /* * non-sequential insert (at possibly middle page) */ /* * update previous pointer of old next/right page of <sp> */ if (nextbn != 0) { XT_GETPAGE(ip, nextbn, mp, PSIZE, p, rc); if (rc) { XT_PUTPAGE(rmp); goto clean_up; } BT_MARK_DIRTY(mp, ip); /* * acquire a transaction lock on the next page; * * action:sibling pointer update; */ if (!test_cflag(COMMIT_Nolink, ip)) tlck = txLock(tid, ip, mp, tlckXTREE | tlckRELINK); p->header.prev = cpu_to_le64(rbn); /* sibling page may have been updated previously, or * it may be updated later; */ XT_PUTPAGE(mp); } /* * split the data between the split and new/right pages */ maxentry = le16_to_cpu(sp->header.maxentry); middle = maxentry >> 1; righthalf = maxentry - middle; /* * skip index in old split/left page - insert into left page: */ if (skip <= middle) { /* move right half of split page to the new right page */ memmove(&rp->xad[XTENTRYSTART], &sp->xad[middle], righthalf << L2XTSLOTSIZE); /* shift right tail of left half to make room for new entry */ if (skip < middle) memmove(&sp->xad[skip + 1], &sp->xad[skip], (middle - skip) << L2XTSLOTSIZE); /* insert new entry */ xad = &sp->xad[skip]; XT_PUTENTRY(xad, split->flag, split->off, split->len, split->addr); /* update page header */ sp->header.nextindex = cpu_to_le16(middle + 1); if (!test_cflag(COMMIT_Nolink, ip)) { sxtlck->lwm.offset = (sxtlck->lwm.offset) ? min(skip, (int)sxtlck->lwm.offset) : skip; } rp->header.nextindex = cpu_to_le16(XTENTRYSTART + righthalf); } /* * skip index in new right page - insert into right page: */ else { /* move left head of right half to right page */ n = skip - middle; memmove(&rp->xad[XTENTRYSTART], &sp->xad[middle], n << L2XTSLOTSIZE); /* insert new entry */ n += XTENTRYSTART; xad = &rp->xad[n]; XT_PUTENTRY(xad, split->flag, split->off, split->len, split->addr); /* move right tail of right half to right page */ if (skip < maxentry) memmove(&rp->xad[n + 1], &sp->xad[skip], (maxentry - skip) << L2XTSLOTSIZE); /* update page header */ sp->header.nextindex = cpu_to_le16(middle); if (!test_cflag(COMMIT_Nolink, ip)) { sxtlck->lwm.offset = (sxtlck->lwm.offset) ? min(middle, (int)sxtlck->lwm.offset) : middle; } rp->header.nextindex = cpu_to_le16(XTENTRYSTART + righthalf + 1); } if (!test_cflag(COMMIT_Nolink, ip)) { sxtlck->lwm.length = le16_to_cpu(sp->header.nextindex) - sxtlck->lwm.offset; /* rxtlck->lwm.offset = XTENTRYSTART; */ rxtlck->lwm.length = le16_to_cpu(rp->header.nextindex) - XTENTRYSTART; } *rmpp = rmp; *rbnp = rbn; jfs_info("xtSplitPage: sp:0x%p rp:0x%p", sp, rp); return rc; clean_up: /* Rollback quota allocation. */ if (quota_allocation) dquot_free_block(ip, quota_allocation); return (rc); } /* * xtSplitRoot() * * function: * split the full root page into original/root/split page and new * right page * i.e., root remains fixed in tree anchor (inode) and the root is * copied to a single new right child page since root page << * non-root page, and the split root page contains a single entry * for the new right child page. * * parameter: * int tid, * struct inode *ip, * struct xtsplit *split, * struct metapage **rmpp) * * return: * Pointer to page in which to insert or NULL on error. */ static int xtSplitRoot(tid_t tid, struct inode *ip, struct xtsplit * split, struct metapage ** rmpp) { xtpage_t *sp; struct metapage *rmp; xtpage_t *rp; s64 rbn; int skip, nextindex; xad_t *xad; pxd_t *pxd; struct pxdlist *pxdlist; struct tlock *tlck; struct xtlock *xtlck; int rc; sp = &JFS_IP(ip)->i_xtroot; INCREMENT(xtStat.split); /* * allocate a single (right) child page */ pxdlist = split->pxdlist; pxd = &pxdlist->pxd[pxdlist->npxd]; pxdlist->npxd++; rbn = addressPXD(pxd); rmp = get_metapage(ip, rbn, PSIZE, 1); if (rmp == NULL) return -EIO; /* Allocate blocks to quota. */ rc = dquot_alloc_block(ip, lengthPXD(pxd)); if (rc) { release_metapage(rmp); return rc; } jfs_info("xtSplitRoot: ip:0x%p rmp:0x%p", ip, rmp); /* * acquire a transaction lock on the new right page; * * action: new page; */ BT_MARK_DIRTY(rmp, ip); rp = (xtpage_t *) rmp->data; rp->header.flag = (sp->header.flag & BT_LEAF) ? BT_LEAF : BT_INTERNAL; rp->header.self = *pxd; rp->header.nextindex = cpu_to_le16(XTENTRYSTART); rp->header.maxentry = cpu_to_le16(PSIZE >> L2XTSLOTSIZE); /* initialize sibling pointers */ rp->header.next = 0; rp->header.prev = 0; /* * copy the in-line root page into new right page extent */ nextindex = le16_to_cpu(sp->header.maxentry); memmove(&rp->xad[XTENTRYSTART], &sp->xad[XTENTRYSTART], (nextindex - XTENTRYSTART) << L2XTSLOTSIZE); /* * insert the new entry into the new right/child page * (skip index in the new right page will not change) */ skip = split->index; /* if insert into middle, shift right remaining entries */ if (skip != nextindex) memmove(&rp->xad[skip + 1], &rp->xad[skip], (nextindex - skip) * sizeof(xad_t)); xad = &rp->xad[skip]; XT_PUTENTRY(xad, split->flag, split->off, split->len, split->addr); /* update page header */ rp->header.nextindex = cpu_to_le16(nextindex + 1); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, rmp, tlckXTREE | tlckNEW); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = XTENTRYSTART; xtlck->lwm.length = le16_to_cpu(rp->header.nextindex) - XTENTRYSTART; } /* * reset the root * * init root with the single entry for the new right page * set the 1st entry offset to 0, which force the left-most key * at any level of the tree to be less than any search key. */ /* * acquire a transaction lock on the root page (in-memory inode); * * action: root split; */ BT_MARK_DIRTY(split->mp, ip); xad = &sp->xad[XTENTRYSTART]; XT_PUTENTRY(xad, XAD_NEW, 0, JFS_SBI(ip->i_sb)->nbperpage, rbn); /* update page header of root */ sp->header.flag &= ~BT_LEAF; sp->header.flag |= BT_INTERNAL; sp->header.nextindex = cpu_to_le16(XTENTRYSTART + 1); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, split->mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = XTENTRYSTART; xtlck->lwm.length = 1; } *rmpp = rmp; jfs_info("xtSplitRoot: sp:0x%p rp:0x%p", sp, rp); return 0; } /* * xtExtend() * * function: extend in-place; * * note: existing extent may or may not have been committed. * caller is responsible for pager buffer cache update, and * working block allocation map update; * update pmap: alloc whole extended extent; */ int xtExtend(tid_t tid, /* transaction id */ struct inode *ip, s64 xoff, /* delta extent offset */ s32 xlen, /* delta extent length */ int flag) { int rc = 0; int cmp; struct metapage *mp; /* meta-page buffer */ xtpage_t *p; /* base B+-tree index page */ s64 bn; int index, nextindex, len; struct btstack btstack; /* traverse stack */ struct xtsplit split; /* split information */ xad_t *xad; s64 xaddr; struct tlock *tlck; struct xtlock *xtlck = NULL; jfs_info("xtExtend: nxoff:0x%lx nxlen:0x%x", (ulong) xoff, xlen); /* there must exist extent to be extended */ if ((rc = xtSearch(ip, xoff - 1, NULL, &cmp, &btstack, XT_INSERT))) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); if (cmp != 0) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtExtend: xtSearch did not find extent"); return -EIO; } /* extension must be contiguous */ xad = &p->xad[index]; if ((offsetXAD(xad) + lengthXAD(xad)) != xoff) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtExtend: extension is not contiguous"); return -EIO; } /* * acquire a transaction lock on the leaf page; * * action: xad insertion/extension; */ BT_MARK_DIRTY(mp, ip); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } /* extend will overflow extent ? */ xlen = lengthXAD(xad) + xlen; if ((len = xlen - MAXXLEN) <= 0) goto extendOld; /* * extent overflow: insert entry for new extent */ //insertNew: xoff = offsetXAD(xad) + MAXXLEN; xaddr = addressXAD(xad) + MAXXLEN; nextindex = le16_to_cpu(p->header.nextindex); /* * if the leaf page is full, insert the new entry and * propagate up the router entry for the new page from split * * The xtSplitUp() will insert the entry and unpin the leaf page. */ if (nextindex == le16_to_cpu(p->header.maxentry)) { /* xtSpliUp() unpins leaf pages */ split.mp = mp; split.index = index + 1; split.flag = XAD_NEW; split.off = xoff; /* split offset */ split.len = len; split.addr = xaddr; split.pxdlist = NULL; if ((rc = xtSplitUp(tid, ip, &split, &btstack))) return rc; /* get back old page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* * if leaf root has been split, original root has been * copied to new child page, i.e., original entry now * resides on the new child page; */ if (p->header.flag & BT_INTERNAL) { ASSERT(p->header.nextindex == cpu_to_le16(XTENTRYSTART + 1)); xad = &p->xad[XTENTRYSTART]; bn = addressXAD(xad); XT_PUTPAGE(mp); /* get new child page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; BT_MARK_DIRTY(mp, ip); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE|tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } } } /* * insert the new entry into the leaf page */ else { /* insert the new entry: mark the entry NEW */ xad = &p->xad[index + 1]; XT_PUTENTRY(xad, XAD_NEW, xoff, len, xaddr); /* advance next available entry index */ le16_add_cpu(&p->header.nextindex, 1); } /* get back old entry */ xad = &p->xad[index]; xlen = MAXXLEN; /* * extend old extent */ extendOld: XADlength(xad, xlen); if (!(xad->flag & XAD_NEW)) xad->flag |= XAD_EXTENDED; if (!test_cflag(COMMIT_Nolink, ip)) { xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index, (int)xtlck->lwm.offset) : index; xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; } /* unpin the leaf page */ XT_PUTPAGE(mp); return rc; } #ifdef _NOTYET /* * xtTailgate() * * function: split existing 'tail' extent * (split offset >= start offset of tail extent), and * relocate and extend the split tail half; * * note: existing extent may or may not have been committed. * caller is responsible for pager buffer cache update, and * working block allocation map update; * update pmap: free old split tail extent, alloc new extent; */ int xtTailgate(tid_t tid, /* transaction id */ struct inode *ip, s64 xoff, /* split/new extent offset */ s32 xlen, /* new extent length */ s64 xaddr, /* new extent address */ int flag) { int rc = 0; int cmp; struct metapage *mp; /* meta-page buffer */ xtpage_t *p; /* base B+-tree index page */ s64 bn; int index, nextindex, llen, rlen; struct btstack btstack; /* traverse stack */ struct xtsplit split; /* split information */ xad_t *xad; struct tlock *tlck; struct xtlock *xtlck = 0; struct tlock *mtlck; struct maplock *pxdlock; /* printf("xtTailgate: nxoff:0x%lx nxlen:0x%x nxaddr:0x%lx\n", (ulong)xoff, xlen, (ulong)xaddr); */ /* there must exist extent to be tailgated */ if ((rc = xtSearch(ip, xoff, NULL, &cmp, &btstack, XT_INSERT))) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); if (cmp != 0) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtTailgate: couldn't find extent"); return -EIO; } /* entry found must be last entry */ nextindex = le16_to_cpu(p->header.nextindex); if (index != nextindex - 1) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtTailgate: the entry found is not the last entry"); return -EIO; } BT_MARK_DIRTY(mp, ip); /* * acquire tlock of the leaf page containing original entry */ if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } /* completely replace extent ? */ xad = &p->xad[index]; /* printf("xtTailgate: xoff:0x%lx xlen:0x%x xaddr:0x%lx\n", (ulong)offsetXAD(xad), lengthXAD(xad), (ulong)addressXAD(xad)); */ if ((llen = xoff - offsetXAD(xad)) == 0) goto updateOld; /* * partially replace extent: insert entry for new extent */ //insertNew: /* * if the leaf page is full, insert the new entry and * propagate up the router entry for the new page from split * * The xtSplitUp() will insert the entry and unpin the leaf page. */ if (nextindex == le16_to_cpu(p->header.maxentry)) { /* xtSpliUp() unpins leaf pages */ split.mp = mp; split.index = index + 1; split.flag = XAD_NEW; split.off = xoff; /* split offset */ split.len = xlen; split.addr = xaddr; split.pxdlist = NULL; if ((rc = xtSplitUp(tid, ip, &split, &btstack))) return rc; /* get back old page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* * if leaf root has been split, original root has been * copied to new child page, i.e., original entry now * resides on the new child page; */ if (p->header.flag & BT_INTERNAL) { ASSERT(p->header.nextindex == cpu_to_le16(XTENTRYSTART + 1)); xad = &p->xad[XTENTRYSTART]; bn = addressXAD(xad); XT_PUTPAGE(mp); /* get new child page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; BT_MARK_DIRTY(mp, ip); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE|tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } } } /* * insert the new entry into the leaf page */ else { /* insert the new entry: mark the entry NEW */ xad = &p->xad[index + 1]; XT_PUTENTRY(xad, XAD_NEW, xoff, xlen, xaddr); /* advance next available entry index */ le16_add_cpu(&p->header.nextindex, 1); } /* get back old XAD */ xad = &p->xad[index]; /* * truncate/relocate old extent at split offset */ updateOld: /* update dmap for old/committed/truncated extent */ rlen = lengthXAD(xad) - llen; if (!(xad->flag & XAD_NEW)) { /* free from PWMAP at commit */ if (!test_cflag(COMMIT_Nolink, ip)) { mtlck = txMaplock(tid, ip, tlckMAP); pxdlock = (struct maplock *) & mtlck->lock; pxdlock->flag = mlckFREEPXD; PXDaddress(&pxdlock->pxd, addressXAD(xad) + llen); PXDlength(&pxdlock->pxd, rlen); pxdlock->index = 1; } } else /* free from WMAP */ dbFree(ip, addressXAD(xad) + llen, (s64) rlen); if (llen) /* truncate */ XADlength(xad, llen); else /* replace */ XT_PUTENTRY(xad, XAD_NEW, xoff, xlen, xaddr); if (!test_cflag(COMMIT_Nolink, ip)) { xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index, (int)xtlck->lwm.offset) : index; xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; } /* unpin the leaf page */ XT_PUTPAGE(mp); return rc; } #endif /* _NOTYET */ /* * xtUpdate() * * function: update XAD; * * update extent for allocated_but_not_recorded or * compressed extent; * * parameter: * nxad - new XAD; * logical extent of the specified XAD must be completely * contained by an existing XAD; */ int xtUpdate(tid_t tid, struct inode *ip, xad_t * nxad) { /* new XAD */ int rc = 0; int cmp; struct metapage *mp; /* meta-page buffer */ xtpage_t *p; /* base B+-tree index page */ s64 bn; int index0, index, newindex, nextindex; struct btstack btstack; /* traverse stack */ struct xtsplit split; /* split information */ xad_t *xad, *lxad, *rxad; int xflag; s64 nxoff, xoff; int nxlen, xlen, lxlen, rxlen; s64 nxaddr, xaddr; struct tlock *tlck; struct xtlock *xtlck = NULL; int newpage = 0; /* there must exist extent to be tailgated */ nxoff = offsetXAD(nxad); nxlen = lengthXAD(nxad); nxaddr = addressXAD(nxad); if ((rc = xtSearch(ip, nxoff, NULL, &cmp, &btstack, XT_INSERT))) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index0); if (cmp != 0) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtUpdate: Could not find extent"); return -EIO; } BT_MARK_DIRTY(mp, ip); /* * acquire tlock of the leaf page containing original entry */ if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } xad = &p->xad[index0]; xflag = xad->flag; xoff = offsetXAD(xad); xlen = lengthXAD(xad); xaddr = addressXAD(xad); /* nXAD must be completely contained within XAD */ if ((xoff > nxoff) || (nxoff + nxlen > xoff + xlen)) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtUpdate: nXAD in not completely contained within XAD"); return -EIO; } index = index0; newindex = index + 1; nextindex = le16_to_cpu(p->header.nextindex); #ifdef _JFS_WIP_NOCOALESCE if (xoff < nxoff) goto updateRight; /* * replace XAD with nXAD */ replace: /* (nxoff == xoff) */ if (nxlen == xlen) { /* replace XAD with nXAD:recorded */ *xad = *nxad; xad->flag = xflag & ~XAD_NOTRECORDED; goto out; } else /* (nxlen < xlen) */ goto updateLeft; #endif /* _JFS_WIP_NOCOALESCE */ /* #ifdef _JFS_WIP_COALESCE */ if (xoff < nxoff) goto coalesceRight; /* * coalesce with left XAD */ //coalesceLeft: /* (xoff == nxoff) */ /* is XAD first entry of page ? */ if (index == XTENTRYSTART) goto replace; /* is nXAD logically and physically contiguous with lXAD ? */ lxad = &p->xad[index - 1]; lxlen = lengthXAD(lxad); if (!(lxad->flag & XAD_NOTRECORDED) && (nxoff == offsetXAD(lxad) + lxlen) && (nxaddr == addressXAD(lxad) + lxlen) && (lxlen + nxlen < MAXXLEN)) { /* extend right lXAD */ index0 = index - 1; XADlength(lxad, lxlen + nxlen); /* If we just merged two extents together, need to make sure the * right extent gets logged. If the left one is marked XAD_NEW, * then we know it will be logged. Otherwise, mark as * XAD_EXTENDED */ if (!(lxad->flag & XAD_NEW)) lxad->flag |= XAD_EXTENDED; if (xlen > nxlen) { /* truncate XAD */ XADoffset(xad, xoff + nxlen); XADlength(xad, xlen - nxlen); XADaddress(xad, xaddr + nxlen); goto out; } else { /* (xlen == nxlen) */ /* remove XAD */ if (index < nextindex - 1) memmove(&p->xad[index], &p->xad[index + 1], (nextindex - index - 1) << L2XTSLOTSIZE); p->header.nextindex = cpu_to_le16(le16_to_cpu(p->header.nextindex) - 1); index = index0; newindex = index + 1; nextindex = le16_to_cpu(p->header.nextindex); xoff = nxoff = offsetXAD(lxad); xlen = nxlen = lxlen + nxlen; xaddr = nxaddr = addressXAD(lxad); goto coalesceRight; } } /* * replace XAD with nXAD */ replace: /* (nxoff == xoff) */ if (nxlen == xlen) { /* replace XAD with nXAD:recorded */ *xad = *nxad; xad->flag = xflag & ~XAD_NOTRECORDED; goto coalesceRight; } else /* (nxlen < xlen) */ goto updateLeft; /* * coalesce with right XAD */ coalesceRight: /* (xoff <= nxoff) */ /* is XAD last entry of page ? */ if (newindex == nextindex) { if (xoff == nxoff) goto out; goto updateRight; } /* is nXAD logically and physically contiguous with rXAD ? */ rxad = &p->xad[index + 1]; rxlen = lengthXAD(rxad); if (!(rxad->flag & XAD_NOTRECORDED) && (nxoff + nxlen == offsetXAD(rxad)) && (nxaddr + nxlen == addressXAD(rxad)) && (rxlen + nxlen < MAXXLEN)) { /* extend left rXAD */ XADoffset(rxad, nxoff); XADlength(rxad, rxlen + nxlen); XADaddress(rxad, nxaddr); /* If we just merged two extents together, need to make sure * the left extent gets logged. If the right one is marked * XAD_NEW, then we know it will be logged. Otherwise, mark as * XAD_EXTENDED */ if (!(rxad->flag & XAD_NEW)) rxad->flag |= XAD_EXTENDED; if (xlen > nxlen) /* truncate XAD */ XADlength(xad, xlen - nxlen); else { /* (xlen == nxlen) */ /* remove XAD */ memmove(&p->xad[index], &p->xad[index + 1], (nextindex - index - 1) << L2XTSLOTSIZE); p->header.nextindex = cpu_to_le16(le16_to_cpu(p->header.nextindex) - 1); } goto out; } else if (xoff == nxoff) goto out; if (xoff >= nxoff) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtUpdate: xoff >= nxoff"); return -EIO; } /* #endif _JFS_WIP_COALESCE */ /* * split XAD into (lXAD, nXAD): * * |---nXAD---> * --|----------XAD----------|-- * |-lXAD-| */ updateRight: /* (xoff < nxoff) */ /* truncate old XAD as lXAD:not_recorded */ xad = &p->xad[index]; XADlength(xad, nxoff - xoff); /* insert nXAD:recorded */ if (nextindex == le16_to_cpu(p->header.maxentry)) { /* xtSpliUp() unpins leaf pages */ split.mp = mp; split.index = newindex; split.flag = xflag & ~XAD_NOTRECORDED; split.off = nxoff; split.len = nxlen; split.addr = nxaddr; split.pxdlist = NULL; if ((rc = xtSplitUp(tid, ip, &split, &btstack))) return rc; /* get back old page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* * if leaf root has been split, original root has been * copied to new child page, i.e., original entry now * resides on the new child page; */ if (p->header.flag & BT_INTERNAL) { ASSERT(p->header.nextindex == cpu_to_le16(XTENTRYSTART + 1)); xad = &p->xad[XTENTRYSTART]; bn = addressXAD(xad); XT_PUTPAGE(mp); /* get new child page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; BT_MARK_DIRTY(mp, ip); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE|tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } } else { /* is nXAD on new page ? */ if (newindex > (le16_to_cpu(p->header.maxentry) >> 1)) { newindex = newindex - le16_to_cpu(p->header.nextindex) + XTENTRYSTART; newpage = 1; } } } else { /* if insert into middle, shift right remaining entries */ if (newindex < nextindex) memmove(&p->xad[newindex + 1], &p->xad[newindex], (nextindex - newindex) << L2XTSLOTSIZE); /* insert the entry */ xad = &p->xad[newindex]; *xad = *nxad; xad->flag = xflag & ~XAD_NOTRECORDED; /* advance next available entry index. */ p->header.nextindex = cpu_to_le16(le16_to_cpu(p->header.nextindex) + 1); } /* * does nXAD force 3-way split ? * * |---nXAD--->| * --|----------XAD-------------|-- * |-lXAD-| |-rXAD -| */ if (nxoff + nxlen == xoff + xlen) goto out; /* reorient nXAD as XAD for further split XAD into (nXAD, rXAD) */ if (newpage) { /* close out old page */ if (!test_cflag(COMMIT_Nolink, ip)) { xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index0, (int)xtlck->lwm.offset) : index0; xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; } bn = le64_to_cpu(p->header.next); XT_PUTPAGE(mp); /* get new right page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; BT_MARK_DIRTY(mp, ip); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } index0 = index = newindex; } else index++; newindex = index + 1; nextindex = le16_to_cpu(p->header.nextindex); xlen = xlen - (nxoff - xoff); xoff = nxoff; xaddr = nxaddr; /* recompute split pages */ if (nextindex == le16_to_cpu(p->header.maxentry)) { XT_PUTPAGE(mp); if ((rc = xtSearch(ip, nxoff, NULL, &cmp, &btstack, XT_INSERT))) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index0); if (cmp != 0) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtUpdate: xtSearch failed"); return -EIO; } if (index0 != index) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtUpdate: unexpected value of index"); return -EIO; } } /* * split XAD into (nXAD, rXAD) * * ---nXAD---| * --|----------XAD----------|-- * |-rXAD-| */ updateLeft: /* (nxoff == xoff) && (nxlen < xlen) */ /* update old XAD with nXAD:recorded */ xad = &p->xad[index]; *xad = *nxad; xad->flag = xflag & ~XAD_NOTRECORDED; /* insert rXAD:not_recorded */ xoff = xoff + nxlen; xlen = xlen - nxlen; xaddr = xaddr + nxlen; if (nextindex == le16_to_cpu(p->header.maxentry)) { /* printf("xtUpdate.updateLeft.split p:0x%p\n", p); */ /* xtSpliUp() unpins leaf pages */ split.mp = mp; split.index = newindex; split.flag = xflag; split.off = xoff; split.len = xlen; split.addr = xaddr; split.pxdlist = NULL; if ((rc = xtSplitUp(tid, ip, &split, &btstack))) return rc; /* get back old page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* * if leaf root has been split, original root has been * copied to new child page, i.e., original entry now * resides on the new child page; */ if (p->header.flag & BT_INTERNAL) { ASSERT(p->header.nextindex == cpu_to_le16(XTENTRYSTART + 1)); xad = &p->xad[XTENTRYSTART]; bn = addressXAD(xad); XT_PUTPAGE(mp); /* get new child page */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; BT_MARK_DIRTY(mp, ip); if (!test_cflag(COMMIT_Nolink, ip)) { tlck = txLock(tid, ip, mp, tlckXTREE|tlckGROW); xtlck = (struct xtlock *) & tlck->lock; } } } else { /* if insert into middle, shift right remaining entries */ if (newindex < nextindex) memmove(&p->xad[newindex + 1], &p->xad[newindex], (nextindex - newindex) << L2XTSLOTSIZE); /* insert the entry */ xad = &p->xad[newindex]; XT_PUTENTRY(xad, xflag, xoff, xlen, xaddr); /* advance next available entry index. */ p->header.nextindex = cpu_to_le16(le16_to_cpu(p->header.nextindex) + 1); } out: if (!test_cflag(COMMIT_Nolink, ip)) { xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index0, (int)xtlck->lwm.offset) : index0; xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; } /* unpin the leaf page */ XT_PUTPAGE(mp); return rc; } /* * xtAppend() * * function: grow in append mode from contiguous region specified ; * * parameter: * tid - transaction id; * ip - file object; * xflag - extent flag: * xoff - extent offset; * maxblocks - max extent length; * xlen - extent length (in/out); * xaddrp - extent address pointer (in/out): * flag - * * return: */ int xtAppend(tid_t tid, /* transaction id */ struct inode *ip, int xflag, s64 xoff, s32 maxblocks, s32 * xlenp, /* (in/out) */ s64 * xaddrp, /* (in/out) */ int flag) { int rc = 0; struct metapage *mp; /* meta-page buffer */ xtpage_t *p; /* base B+-tree index page */ s64 bn, xaddr; int index, nextindex; struct btstack btstack; /* traverse stack */ struct xtsplit split; /* split information */ xad_t *xad; int cmp; struct tlock *tlck; struct xtlock *xtlck; int nsplit, nblocks, xlen; struct pxdlist pxdlist; pxd_t *pxd; s64 next; xaddr = *xaddrp; xlen = *xlenp; jfs_info("xtAppend: xoff:0x%lx maxblocks:%d xlen:%d xaddr:0x%lx", (ulong) xoff, maxblocks, xlen, (ulong) xaddr); /* * search for the entry location at which to insert: * * xtFastSearch() and xtSearch() both returns (leaf page * pinned, index at which to insert). * n.b. xtSearch() may return index of maxentry of * the full page. */ if ((rc = xtSearch(ip, xoff, &next, &cmp, &btstack, XT_INSERT))) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); if (cmp == 0) { rc = -EEXIST; goto out; } if (next) xlen = min(xlen, (int)(next - xoff)); //insert: /* * insert entry for new extent */ xflag |= XAD_NEW; /* * if the leaf page is full, split the page and * propagate up the router entry for the new page from split * * The xtSplitUp() will insert the entry and unpin the leaf page. */ nextindex = le16_to_cpu(p->header.nextindex); if (nextindex < le16_to_cpu(p->header.maxentry)) goto insertLeaf; /* * allocate new index blocks to cover index page split(s) */ nsplit = btstack.nsplit; split.pxdlist = &pxdlist; pxdlist.maxnpxd = pxdlist.npxd = 0; pxd = &pxdlist.pxd[0]; nblocks = JFS_SBI(ip->i_sb)->nbperpage; for (; nsplit > 0; nsplit--, pxd++, xaddr += nblocks, maxblocks -= nblocks) { if ((rc = dbAllocBottomUp(ip, xaddr, (s64) nblocks)) == 0) { PXDaddress(pxd, xaddr); PXDlength(pxd, nblocks); pxdlist.maxnpxd++; continue; } /* undo allocation */ goto out; } xlen = min(xlen, maxblocks); /* * allocate data extent requested */ if ((rc = dbAllocBottomUp(ip, xaddr, (s64) xlen))) goto out; split.mp = mp; split.index = index; split.flag = xflag; split.off = xoff; split.len = xlen; split.addr = xaddr; if ((rc = xtSplitUp(tid, ip, &split, &btstack))) { /* undo data extent allocation */ dbFree(ip, *xaddrp, (s64) * xlenp); return rc; } *xaddrp = xaddr; *xlenp = xlen; return 0; /* * insert the new entry into the leaf page */ insertLeaf: /* * allocate data extent requested */ if ((rc = dbAllocBottomUp(ip, xaddr, (s64) xlen))) goto out; BT_MARK_DIRTY(mp, ip); /* * acquire a transaction lock on the leaf page; * * action: xad insertion/extension; */ tlck = txLock(tid, ip, mp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; /* insert the new entry: mark the entry NEW */ xad = &p->xad[index]; XT_PUTENTRY(xad, xflag, xoff, xlen, xaddr); /* advance next available entry index */ le16_add_cpu(&p->header.nextindex, 1); xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index,(int) xtlck->lwm.offset) : index; xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; *xaddrp = xaddr; *xlenp = xlen; out: /* unpin the leaf page */ XT_PUTPAGE(mp); return rc; } #ifdef _STILL_TO_PORT /* - TBD for defragmentaion/reorganization - * * xtDelete() * * function: * delete the entry with the specified key. * * N.B.: whole extent of the entry is assumed to be deleted. * * parameter: * * return: * ENOENT: if the entry is not found. * * exception: */ int xtDelete(tid_t tid, struct inode *ip, s64 xoff, s32 xlen, int flag) { int rc = 0; struct btstack btstack; int cmp; s64 bn; struct metapage *mp; xtpage_t *p; int index, nextindex; struct tlock *tlck; struct xtlock *xtlck; /* * find the matching entry; xtSearch() pins the page */ if ((rc = xtSearch(ip, xoff, NULL, &cmp, &btstack, 0))) return rc; XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); if (cmp) { /* unpin the leaf page */ XT_PUTPAGE(mp); return -ENOENT; } /* * delete the entry from the leaf page */ nextindex = le16_to_cpu(p->header.nextindex); le16_add_cpu(&p->header.nextindex, -1); /* * if the leaf page bocome empty, free the page */ if (p->header.nextindex == cpu_to_le16(XTENTRYSTART)) return (xtDeleteUp(tid, ip, mp, p, &btstack)); BT_MARK_DIRTY(mp, ip); /* * acquire a transaction lock on the leaf page; * * action:xad deletion; */ tlck = txLock(tid, ip, mp, tlckXTREE); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index, xtlck->lwm.offset) : index; /* if delete from middle, shift left/compact the remaining entries */ if (index < nextindex - 1) memmove(&p->xad[index], &p->xad[index + 1], (nextindex - index - 1) * sizeof(xad_t)); XT_PUTPAGE(mp); return 0; } /* - TBD for defragmentaion/reorganization - * * xtDeleteUp() * * function: * free empty pages as propagating deletion up the tree * * parameter: * * return: */ static int xtDeleteUp(tid_t tid, struct inode *ip, struct metapage * fmp, xtpage_t * fp, struct btstack * btstack) { int rc = 0; struct metapage *mp; xtpage_t *p; int index, nextindex; s64 xaddr; int xlen; struct btframe *parent; struct tlock *tlck; struct xtlock *xtlck; /* * keep root leaf page which has become empty */ if (fp->header.flag & BT_ROOT) { /* keep the root page */ fp->header.flag &= ~BT_INTERNAL; fp->header.flag |= BT_LEAF; fp->header.nextindex = cpu_to_le16(XTENTRYSTART); /* XT_PUTPAGE(fmp); */ return 0; } /* * free non-root leaf page */ if ((rc = xtRelink(tid, ip, fp))) { XT_PUTPAGE(fmp); return rc; } xaddr = addressPXD(&fp->header.self); xlen = lengthPXD(&fp->header.self); /* free the page extent */ dbFree(ip, xaddr, (s64) xlen); /* free the buffer page */ discard_metapage(fmp); /* * propagate page deletion up the index tree * * If the delete from the parent page makes it empty, * continue all the way up the tree. * stop if the root page is reached (which is never deleted) or * if the entry deletion does not empty the page. */ while ((parent = BT_POP(btstack)) != NULL) { /* get/pin the parent page <sp> */ XT_GETPAGE(ip, parent->bn, mp, PSIZE, p, rc); if (rc) return rc; index = parent->index; /* delete the entry for the freed child page from parent. */ nextindex = le16_to_cpu(p->header.nextindex); /* * the parent has the single entry being deleted: * free the parent page which has become empty. */ if (nextindex == 1) { if (p->header.flag & BT_ROOT) { /* keep the root page */ p->header.flag &= ~BT_INTERNAL; p->header.flag |= BT_LEAF; p->header.nextindex = cpu_to_le16(XTENTRYSTART); /* XT_PUTPAGE(mp); */ break; } else { /* free the parent page */ if ((rc = xtRelink(tid, ip, p))) return rc; xaddr = addressPXD(&p->header.self); /* free the page extent */ dbFree(ip, xaddr, (s64) JFS_SBI(ip->i_sb)->nbperpage); /* unpin/free the buffer page */ discard_metapage(mp); /* propagate up */ continue; } } /* * the parent has other entries remaining: * delete the router entry from the parent page. */ else { BT_MARK_DIRTY(mp, ip); /* * acquire a transaction lock on the leaf page; * * action:xad deletion; */ tlck = txLock(tid, ip, mp, tlckXTREE); xtlck = (struct xtlock *) & tlck->lock; xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index, xtlck->lwm. offset) : index; /* if delete from middle, * shift left/compact the remaining entries in the page */ if (index < nextindex - 1) memmove(&p->xad[index], &p->xad[index + 1], (nextindex - index - 1) << L2XTSLOTSIZE); le16_add_cpu(&p->header.nextindex, -1); jfs_info("xtDeleteUp(entry): 0x%lx[%d]", (ulong) parent->bn, index); } /* unpin the parent page */ XT_PUTPAGE(mp); /* exit propagation up */ break; } return 0; } /* * NAME: xtRelocate() * * FUNCTION: relocate xtpage or data extent of regular file; * This function is mainly used by defragfs utility. * * NOTE: This routine does not have the logic to handle * uncommitted allocated extent. The caller should call * txCommit() to commit all the allocation before call * this routine. */ int xtRelocate(tid_t tid, struct inode * ip, xad_t * oxad, /* old XAD */ s64 nxaddr, /* new xaddr */ int xtype) { /* extent type: XTPAGE or DATAEXT */ int rc = 0; struct tblock *tblk; struct tlock *tlck; struct xtlock *xtlck; struct metapage *mp, *pmp, *lmp, *rmp; /* meta-page buffer */ xtpage_t *p, *pp, *rp, *lp; /* base B+-tree index page */ xad_t *xad; pxd_t *pxd; s64 xoff, xsize; int xlen; s64 oxaddr, sxaddr, dxaddr, nextbn, prevbn; cbuf_t *cp; s64 offset, nbytes, nbrd, pno; int nb, npages, nblks; s64 bn; int cmp; int index; struct pxd_lock *pxdlock; struct btstack btstack; /* traverse stack */ xtype = xtype & EXTENT_TYPE; xoff = offsetXAD(oxad); oxaddr = addressXAD(oxad); xlen = lengthXAD(oxad); /* validate extent offset */ offset = xoff << JFS_SBI(ip->i_sb)->l2bsize; if (offset >= ip->i_size) return -ESTALE; /* stale extent */ jfs_info("xtRelocate: xtype:%d xoff:0x%lx xlen:0x%x xaddr:0x%lx:0x%lx", xtype, (ulong) xoff, xlen, (ulong) oxaddr, (ulong) nxaddr); /* * 1. get and validate the parent xtpage/xad entry * covering the source extent to be relocated; */ if (xtype == DATAEXT) { /* search in leaf entry */ rc = xtSearch(ip, xoff, NULL, &cmp, &btstack, 0); if (rc) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, pmp, pp, index); if (cmp) { XT_PUTPAGE(pmp); return -ESTALE; } /* validate for exact match with a single entry */ xad = &pp->xad[index]; if (addressXAD(xad) != oxaddr || lengthXAD(xad) != xlen) { XT_PUTPAGE(pmp); return -ESTALE; } } else { /* (xtype == XTPAGE) */ /* search in internal entry */ rc = xtSearchNode(ip, oxad, &cmp, &btstack, 0); if (rc) return rc; /* retrieve search result */ XT_GETSEARCH(ip, btstack.top, bn, pmp, pp, index); if (cmp) { XT_PUTPAGE(pmp); return -ESTALE; } /* xtSearchNode() validated for exact match with a single entry */ xad = &pp->xad[index]; } jfs_info("xtRelocate: parent xad entry validated."); /* * 2. relocate the extent */ if (xtype == DATAEXT) { /* if the extent is allocated-but-not-recorded * there is no real data to be moved in this extent, */ if (xad->flag & XAD_NOTRECORDED) goto out; else /* release xtpage for cmRead()/xtLookup() */ XT_PUTPAGE(pmp); /* * cmRelocate() * * copy target data pages to be relocated; * * data extent must start at page boundary and * multiple of page size (except the last data extent); * read in each page of the source data extent into cbuf, * update the cbuf extent descriptor of the page to be * homeward bound to new dst data extent * copy the data from the old extent to new extent. * copy is essential for compressed files to avoid problems * that can arise if there was a change in compression * algorithms. * it is a good strategy because it may disrupt cache * policy to keep the pages in memory afterwards. */ offset = xoff << JFS_SBI(ip->i_sb)->l2bsize; assert((offset & CM_OFFSET) == 0); nbytes = xlen << JFS_SBI(ip->i_sb)->l2bsize; pno = offset >> CM_L2BSIZE; npages = (nbytes + (CM_BSIZE - 1)) >> CM_L2BSIZE; /* npages = ((offset + nbytes - 1) >> CM_L2BSIZE) - (offset >> CM_L2BSIZE) + 1; */ sxaddr = oxaddr; dxaddr = nxaddr; /* process the request one cache buffer at a time */ for (nbrd = 0; nbrd < nbytes; nbrd += nb, offset += nb, pno++, npages--) { /* compute page size */ nb = min(nbytes - nbrd, CM_BSIZE); /* get the cache buffer of the page */ if (rc = cmRead(ip, offset, npages, &cp)) break; assert(addressPXD(&cp->cm_pxd) == sxaddr); assert(!cp->cm_modified); /* bind buffer with the new extent address */ nblks = nb >> JFS_IP(ip->i_sb)->l2bsize; cmSetXD(ip, cp, pno, dxaddr, nblks); /* release the cbuf, mark it as modified */ cmPut(cp, true); dxaddr += nblks; sxaddr += nblks; } /* get back parent page */ if ((rc = xtSearch(ip, xoff, NULL, &cmp, &btstack, 0))) return rc; XT_GETSEARCH(ip, btstack.top, bn, pmp, pp, index); jfs_info("xtRelocate: target data extent relocated."); } else { /* (xtype == XTPAGE) */ /* * read in the target xtpage from the source extent; */ XT_GETPAGE(ip, oxaddr, mp, PSIZE, p, rc); if (rc) { XT_PUTPAGE(pmp); return rc; } /* * read in sibling pages if any to update sibling pointers; */ rmp = NULL; if (p->header.next) { nextbn = le64_to_cpu(p->header.next); XT_GETPAGE(ip, nextbn, rmp, PSIZE, rp, rc); if (rc) { XT_PUTPAGE(pmp); XT_PUTPAGE(mp); return (rc); } } lmp = NULL; if (p->header.prev) { prevbn = le64_to_cpu(p->header.prev); XT_GETPAGE(ip, prevbn, lmp, PSIZE, lp, rc); if (rc) { XT_PUTPAGE(pmp); XT_PUTPAGE(mp); if (rmp) XT_PUTPAGE(rmp); return (rc); } } /* at this point, all xtpages to be updated are in memory */ /* * update sibling pointers of sibling xtpages if any; */ if (lmp) { BT_MARK_DIRTY(lmp, ip); tlck = txLock(tid, ip, lmp, tlckXTREE | tlckRELINK); lp->header.next = cpu_to_le64(nxaddr); XT_PUTPAGE(lmp); } if (rmp) { BT_MARK_DIRTY(rmp, ip); tlck = txLock(tid, ip, rmp, tlckXTREE | tlckRELINK); rp->header.prev = cpu_to_le64(nxaddr); XT_PUTPAGE(rmp); } /* * update the target xtpage to be relocated * * update the self address of the target page * and write to destination extent; * redo image covers the whole xtpage since it is new page * to the destination extent; * update of bmap for the free of source extent * of the target xtpage itself: * update of bmap for the allocation of destination extent * of the target xtpage itself: * update of bmap for the extents covered by xad entries in * the target xtpage is not necessary since they are not * updated; * if not committed before this relocation, * target page may contain XAD_NEW entries which must * be scanned for bmap update (logredo() always * scan xtpage REDOPAGE image for bmap update); * if committed before this relocation (tlckRELOCATE), * scan may be skipped by commit() and logredo(); */ BT_MARK_DIRTY(mp, ip); /* tlckNEW init xtlck->lwm.offset = XTENTRYSTART; */ tlck = txLock(tid, ip, mp, tlckXTREE | tlckNEW); xtlck = (struct xtlock *) & tlck->lock; /* update the self address in the xtpage header */ pxd = &p->header.self; PXDaddress(pxd, nxaddr); /* linelock for the after image of the whole page */ xtlck->lwm.length = le16_to_cpu(p->header.nextindex) - xtlck->lwm.offset; /* update the buffer extent descriptor of target xtpage */ xsize = xlen << JFS_SBI(ip->i_sb)->l2bsize; bmSetXD(mp, nxaddr, xsize); /* unpin the target page to new homeward bound */ XT_PUTPAGE(mp); jfs_info("xtRelocate: target xtpage relocated."); } /* * 3. acquire maplock for the source extent to be freed; * * acquire a maplock saving the src relocated extent address; * to free of the extent at commit time; */ out: /* if DATAEXT relocation, write a LOG_UPDATEMAP record for * free PXD of the source data extent (logredo() will update * bmap for free of source data extent), and update bmap for * free of the source data extent; */ if (xtype == DATAEXT) tlck = txMaplock(tid, ip, tlckMAP); /* if XTPAGE relocation, write a LOG_NOREDOPAGE record * for the source xtpage (logredo() will init NoRedoPage * filter and will also update bmap for free of the source * xtpage), and update bmap for free of the source xtpage; * N.B. We use tlckMAP instead of tlkcXTREE because there * is no buffer associated with this lock since the buffer * has been redirected to the target location. */ else /* (xtype == XTPAGE) */ tlck = txMaplock(tid, ip, tlckMAP | tlckRELOCATE); pxdlock = (struct pxd_lock *) & tlck->lock; pxdlock->flag = mlckFREEPXD; PXDaddress(&pxdlock->pxd, oxaddr); PXDlength(&pxdlock->pxd, xlen); pxdlock->index = 1; /* * 4. update the parent xad entry for relocation; * * acquire tlck for the parent entry with XAD_NEW as entry * update which will write LOG_REDOPAGE and update bmap for * allocation of XAD_NEW destination extent; */ jfs_info("xtRelocate: update parent xad entry."); BT_MARK_DIRTY(pmp, ip); tlck = txLock(tid, ip, pmp, tlckXTREE | tlckGROW); xtlck = (struct xtlock *) & tlck->lock; /* update the XAD with the new destination extent; */ xad = &pp->xad[index]; xad->flag |= XAD_NEW; XADaddress(xad, nxaddr); xtlck->lwm.offset = min(index, xtlck->lwm.offset); xtlck->lwm.length = le16_to_cpu(pp->header.nextindex) - xtlck->lwm.offset; /* unpin the parent xtpage */ XT_PUTPAGE(pmp); return rc; } /* * xtSearchNode() * * function: search for the internal xad entry covering specified extent. * This function is mainly used by defragfs utility. * * parameters: * ip - file object; * xad - extent to find; * cmpp - comparison result: * btstack - traverse stack; * flag - search process flag; * * returns: * btstack contains (bn, index) of search path traversed to the entry. * *cmpp is set to result of comparison with the entry returned. * the page containing the entry is pinned at exit. */ static int xtSearchNode(struct inode *ip, xad_t * xad, /* required XAD entry */ int *cmpp, struct btstack * btstack, int flag) { int rc = 0; s64 xoff, xaddr; int xlen; int cmp = 1; /* init for empty page */ s64 bn; /* block number */ struct metapage *mp; /* meta-page buffer */ xtpage_t *p; /* page */ int base, index, lim; struct btframe *btsp; s64 t64; BT_CLR(btstack); xoff = offsetXAD(xad); xlen = lengthXAD(xad); xaddr = addressXAD(xad); /* * search down tree from root: * * between two consecutive entries of <Ki, Pi> and <Kj, Pj> of * internal page, child page Pi contains entry with k, Ki <= K < Kj. * * if entry with search key K is not found * internal page search find the entry with largest key Ki * less than K which point to the child page to search; * leaf page search find the entry with smallest key Kj * greater than K so that the returned index is the position of * the entry to be shifted right for insertion of new entry. * for empty tree, search key is greater than any key of the tree. * * by convention, root bn = 0. */ for (bn = 0;;) { /* get/pin the page to search */ XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; if (p->header.flag & BT_LEAF) { XT_PUTPAGE(mp); return -ESTALE; } lim = le16_to_cpu(p->header.nextindex) - XTENTRYSTART; /* * binary search with search key K on the current page */ for (base = XTENTRYSTART; lim; lim >>= 1) { index = base + (lim >> 1); XT_CMP(cmp, xoff, &p->xad[index], t64); if (cmp == 0) { /* * search hit * * verify for exact match; */ if (xaddr == addressXAD(&p->xad[index]) && xoff == offsetXAD(&p->xad[index])) { *cmpp = cmp; /* save search result */ btsp = btstack->top; btsp->bn = bn; btsp->index = index; btsp->mp = mp; return 0; } /* descend/search its child page */ goto next; } if (cmp > 0) { base = index + 1; --lim; } } /* * search miss - non-leaf page: * * base is the smallest index with key (Kj) greater than * search key (K) and may be zero or maxentry index. * if base is non-zero, decrement base by one to get the parent * entry of the child page to search. */ index = base ? base - 1 : base; /* * go down to child page */ next: /* get the child page block number */ bn = addressXAD(&p->xad[index]); /* unpin the parent page */ XT_PUTPAGE(mp); } } /* * xtRelink() * * function: * link around a freed page. * * Parameter: * int tid, * struct inode *ip, * xtpage_t *p) * * returns: */ static int xtRelink(tid_t tid, struct inode *ip, xtpage_t * p) { int rc = 0; struct metapage *mp; s64 nextbn, prevbn; struct tlock *tlck; nextbn = le64_to_cpu(p->header.next); prevbn = le64_to_cpu(p->header.prev); /* update prev pointer of the next page */ if (nextbn != 0) { XT_GETPAGE(ip, nextbn, mp, PSIZE, p, rc); if (rc) return rc; /* * acquire a transaction lock on the page; * * action: update prev pointer; */ BT_MARK_DIRTY(mp, ip); tlck = txLock(tid, ip, mp, tlckXTREE | tlckRELINK); /* the page may already have been tlock'd */ p->header.prev = cpu_to_le64(prevbn); XT_PUTPAGE(mp); } /* update next pointer of the previous page */ if (prevbn != 0) { XT_GETPAGE(ip, prevbn, mp, PSIZE, p, rc); if (rc) return rc; /* * acquire a transaction lock on the page; * * action: update next pointer; */ BT_MARK_DIRTY(mp, ip); tlck = txLock(tid, ip, mp, tlckXTREE | tlckRELINK); /* the page may already have been tlock'd */ p->header.next = le64_to_cpu(nextbn); XT_PUTPAGE(mp); } return 0; } #endif /* _STILL_TO_PORT */ /* * xtInitRoot() * * initialize file root (inline in inode) */ void xtInitRoot(tid_t tid, struct inode *ip) { xtpage_t *p; /* * acquire a transaction lock on the root * * action: */ txLock(tid, ip, (struct metapage *) &JFS_IP(ip)->bxflag, tlckXTREE | tlckNEW); p = &JFS_IP(ip)->i_xtroot; p->header.flag = DXD_INDEX | BT_ROOT | BT_LEAF; p->header.nextindex = cpu_to_le16(XTENTRYSTART); if (S_ISDIR(ip->i_mode)) p->header.maxentry = cpu_to_le16(XTROOTINITSLOT_DIR); else { p->header.maxentry = cpu_to_le16(XTROOTINITSLOT); ip->i_size = 0; } return; } /* * We can run into a deadlock truncating a file with a large number of * xtree pages (large fragmented file). A robust fix would entail a * reservation system where we would reserve a number of metadata pages * and tlocks which we would be guaranteed without a deadlock. Without * this, a partial fix is to limit number of metadata pages we will lock * in a single transaction. Currently we will truncate the file so that * no more than 50 leaf pages will be locked. The caller of xtTruncate * will be responsible for ensuring that the current transaction gets * committed, and that subsequent transactions are created to truncate * the file further if needed. */ #define MAX_TRUNCATE_LEAVES 50 /* * xtTruncate() * * function: * traverse for truncation logging backward bottom up; * terminate at the last extent entry at the current subtree * root page covering new down size. * truncation may occur within the last extent entry. * * parameter: * int tid, * struct inode *ip, * s64 newsize, * int type) {PWMAP, PMAP, WMAP; DELETE, TRUNCATE} * * return: * * note: * PWMAP: * 1. truncate (non-COMMIT_NOLINK file) * by jfs_truncate() or jfs_open(O_TRUNC): * xtree is updated; * 2. truncate index table of directory when last entry removed * map update via tlock at commit time; * PMAP: * Call xtTruncate_pmap instead * WMAP: * 1. remove (free zero link count) on last reference release * (pmap has been freed at commit zero link count); * 2. truncate (COMMIT_NOLINK file, i.e., tmp file): * xtree is updated; * map update directly at truncation time; * * if (DELETE) * no LOG_NOREDOPAGE is required (NOREDOFILE is sufficient); * else if (TRUNCATE) * must write LOG_NOREDOPAGE for deleted index page; * * pages may already have been tlocked by anonymous transactions * during file growth (i.e., write) before truncation; * * except last truncated entry, deleted entries remains as is * in the page (nextindex is updated) for other use * (e.g., log/update allocation map): this avoid copying the page * info but delay free of pages; * */ s64 xtTruncate(tid_t tid, struct inode *ip, s64 newsize, int flag) { int rc = 0; s64 teof; struct metapage *mp; xtpage_t *p; s64 bn; int index, nextindex; xad_t *xad; s64 xoff, xaddr; int xlen, len, freexlen; struct btstack btstack; struct btframe *parent; struct tblock *tblk = NULL; struct tlock *tlck = NULL; struct xtlock *xtlck = NULL; struct xdlistlock xadlock; /* maplock for COMMIT_WMAP */ struct pxd_lock *pxdlock; /* maplock for COMMIT_WMAP */ s64 nfreed; int freed, log; int locked_leaves = 0; /* save object truncation type */ if (tid) { tblk = tid_to_tblock(tid); tblk->xflag |= flag; } nfreed = 0; flag &= COMMIT_MAP; assert(flag != COMMIT_PMAP); if (flag == COMMIT_PWMAP) log = 1; else { log = 0; xadlock.flag = mlckFREEXADLIST; xadlock.index = 1; } /* * if the newsize is not an integral number of pages, * the file between newsize and next page boundary will * be cleared. * if truncating into a file hole, it will cause * a full block to be allocated for the logical block. */ /* * release page blocks of truncated region <teof, eof> * * free the data blocks from the leaf index blocks. * delete the parent index entries corresponding to * the freed child data/index blocks. * free the index blocks themselves which aren't needed * in new sized file. * * index blocks are updated only if the blocks are to be * retained in the new sized file. * if type is PMAP, the data and index pages are NOT * freed, and the data and index blocks are NOT freed * from working map. * (this will allow continued access of data/index of * temporary file (zerolink count file truncated to zero-length)). */ teof = (newsize + (JFS_SBI(ip->i_sb)->bsize - 1)) >> JFS_SBI(ip->i_sb)->l2bsize; /* clear stack */ BT_CLR(&btstack); /* * start with root * * root resides in the inode */ bn = 0; /* * first access of each page: */ getPage: XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* process entries backward from last index */ index = le16_to_cpu(p->header.nextindex) - 1; /* Since this is the rightmost page at this level, and we may have * already freed a page that was formerly to the right, let's make * sure that the next pointer is zero. */ if (p->header.next) { if (log) /* * Make sure this change to the header is logged. * If we really truncate this leaf, the flag * will be changed to tlckTRUNCATE */ tlck = txLock(tid, ip, mp, tlckXTREE|tlckGROW); BT_MARK_DIRTY(mp, ip); p->header.next = 0; } if (p->header.flag & BT_INTERNAL) goto getChild; /* * leaf page */ freed = 0; /* does region covered by leaf page precede Teof ? */ xad = &p->xad[index]; xoff = offsetXAD(xad); xlen = lengthXAD(xad); if (teof >= xoff + xlen) { XT_PUTPAGE(mp); goto getParent; } /* (re)acquire tlock of the leaf page */ if (log) { if (++locked_leaves > MAX_TRUNCATE_LEAVES) { /* * We need to limit the size of the transaction * to avoid exhausting pagecache & tlocks */ XT_PUTPAGE(mp); newsize = (xoff + xlen) << JFS_SBI(ip->i_sb)->l2bsize; goto getParent; } tlck = txLock(tid, ip, mp, tlckXTREE); tlck->type = tlckXTREE | tlckTRUNCATE; xtlck = (struct xtlock *) & tlck->lock; xtlck->hwm.offset = le16_to_cpu(p->header.nextindex) - 1; } BT_MARK_DIRTY(mp, ip); /* * scan backward leaf page entries */ for (; index >= XTENTRYSTART; index--) { xad = &p->xad[index]; xoff = offsetXAD(xad); xlen = lengthXAD(xad); xaddr = addressXAD(xad); /* * The "data" for a directory is indexed by the block * device's address space. This metadata must be invalidated * here */ if (S_ISDIR(ip->i_mode) && (teof == 0)) invalidate_xad_metapages(ip, *xad); /* * entry beyond eof: continue scan of current page * xad * ---|---=======-------> * eof */ if (teof < xoff) { nfreed += xlen; continue; } /* * (xoff <= teof): last entry to be deleted from page; * If other entries remain in page: keep and update the page. */ /* * eof == entry_start: delete the entry * xad * -------|=======-------> * eof * */ if (teof == xoff) { nfreed += xlen; if (index == XTENTRYSTART) break; nextindex = index; } /* * eof within the entry: truncate the entry. * xad * -------===|===-------> * eof */ else if (teof < xoff + xlen) { /* update truncated entry */ len = teof - xoff; freexlen = xlen - len; XADlength(xad, len); /* save pxd of truncated extent in tlck */ xaddr += len; if (log) { /* COMMIT_PWMAP */ xtlck->lwm.offset = (xtlck->lwm.offset) ? min(index, (int)xtlck->lwm.offset) : index; xtlck->lwm.length = index + 1 - xtlck->lwm.offset; xtlck->twm.offset = index; pxdlock = (struct pxd_lock *) & xtlck->pxdlock; pxdlock->flag = mlckFREEPXD; PXDaddress(&pxdlock->pxd, xaddr); PXDlength(&pxdlock->pxd, freexlen); } /* free truncated extent */ else { /* COMMIT_WMAP */ pxdlock = (struct pxd_lock *) & xadlock; pxdlock->flag = mlckFREEPXD; PXDaddress(&pxdlock->pxd, xaddr); PXDlength(&pxdlock->pxd, freexlen); txFreeMap(ip, pxdlock, NULL, COMMIT_WMAP); /* reset map lock */ xadlock.flag = mlckFREEXADLIST; } /* current entry is new last entry; */ nextindex = index + 1; nfreed += freexlen; } /* * eof beyond the entry: * xad * -------=======---|---> * eof */ else { /* (xoff + xlen < teof) */ nextindex = index + 1; } if (nextindex < le16_to_cpu(p->header.nextindex)) { if (!log) { /* COMMIT_WAMP */ xadlock.xdlist = &p->xad[nextindex]; xadlock.count = le16_to_cpu(p->header.nextindex) - nextindex; txFreeMap(ip, (struct maplock *) & xadlock, NULL, COMMIT_WMAP); } p->header.nextindex = cpu_to_le16(nextindex); } XT_PUTPAGE(mp); /* assert(freed == 0); */ goto getParent; } /* end scan of leaf page entries */ freed = 1; /* * leaf page become empty: free the page if type != PMAP */ if (log) { /* COMMIT_PWMAP */ /* txCommit() with tlckFREE: * free data extents covered by leaf [XTENTRYSTART:hwm); * invalidate leaf if COMMIT_PWMAP; * if (TRUNCATE), will write LOG_NOREDOPAGE; */ tlck->type = tlckXTREE | tlckFREE; } else { /* COMMIT_WAMP */ /* free data extents covered by leaf */ xadlock.xdlist = &p->xad[XTENTRYSTART]; xadlock.count = le16_to_cpu(p->header.nextindex) - XTENTRYSTART; txFreeMap(ip, (struct maplock *) & xadlock, NULL, COMMIT_WMAP); } if (p->header.flag & BT_ROOT) { p->header.flag &= ~BT_INTERNAL; p->header.flag |= BT_LEAF; p->header.nextindex = cpu_to_le16(XTENTRYSTART); XT_PUTPAGE(mp); /* debug */ goto out; } else { if (log) { /* COMMIT_PWMAP */ /* page will be invalidated at tx completion */ XT_PUTPAGE(mp); } else { /* COMMIT_WMAP */ if (mp->lid) lid_to_tlock(mp->lid)->flag |= tlckFREELOCK; /* invalidate empty leaf page */ discard_metapage(mp); } } /* * the leaf page become empty: delete the parent entry * for the leaf page if the parent page is to be kept * in the new sized file. */ /* * go back up to the parent page */ getParent: /* pop/restore parent entry for the current child page */ if ((parent = BT_POP(&btstack)) == NULL) /* current page must have been root */ goto out; /* get back the parent page */ bn = parent->bn; XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; index = parent->index; /* * child page was not empty: */ if (freed == 0) { /* has any entry deleted from parent ? */ if (index < le16_to_cpu(p->header.nextindex) - 1) { /* (re)acquire tlock on the parent page */ if (log) { /* COMMIT_PWMAP */ /* txCommit() with tlckTRUNCATE: * free child extents covered by parent [); */ tlck = txLock(tid, ip, mp, tlckXTREE); xtlck = (struct xtlock *) & tlck->lock; if (!(tlck->type & tlckTRUNCATE)) { xtlck->hwm.offset = le16_to_cpu(p->header. nextindex) - 1; tlck->type = tlckXTREE | tlckTRUNCATE; } } else { /* COMMIT_WMAP */ /* free child extents covered by parent */ xadlock.xdlist = &p->xad[index + 1]; xadlock.count = le16_to_cpu(p->header.nextindex) - index - 1; txFreeMap(ip, (struct maplock *) & xadlock, NULL, COMMIT_WMAP); } BT_MARK_DIRTY(mp, ip); p->header.nextindex = cpu_to_le16(index + 1); } XT_PUTPAGE(mp); goto getParent; } /* * child page was empty: */ nfreed += lengthXAD(&p->xad[index]); /* * During working map update, child page's tlock must be handled * before parent's. This is because the parent's tlock will cause * the child's disk space to be marked available in the wmap, so * it's important that the child page be released by that time. * * ToDo: tlocks should be on doubly-linked list, so we can * quickly remove it and add it to the end. */ /* * Move parent page's tlock to the end of the tid's tlock list */ if (log && mp->lid && (tblk->last != mp->lid) && lid_to_tlock(mp->lid)->tid) { lid_t lid = mp->lid; struct tlock *prev; tlck = lid_to_tlock(lid); if (tblk->next == lid) tblk->next = tlck->next; else { for (prev = lid_to_tlock(tblk->next); prev->next != lid; prev = lid_to_tlock(prev->next)) { assert(prev->next); } prev->next = tlck->next; } lid_to_tlock(tblk->last)->next = lid; tlck->next = 0; tblk->last = lid; } /* * parent page become empty: free the page */ if (index == XTENTRYSTART) { if (log) { /* COMMIT_PWMAP */ /* txCommit() with tlckFREE: * free child extents covered by parent; * invalidate parent if COMMIT_PWMAP; */ tlck = txLock(tid, ip, mp, tlckXTREE); xtlck = (struct xtlock *) & tlck->lock; xtlck->hwm.offset = le16_to_cpu(p->header.nextindex) - 1; tlck->type = tlckXTREE | tlckFREE; } else { /* COMMIT_WMAP */ /* free child extents covered by parent */ xadlock.xdlist = &p->xad[XTENTRYSTART]; xadlock.count = le16_to_cpu(p->header.nextindex) - XTENTRYSTART; txFreeMap(ip, (struct maplock *) & xadlock, NULL, COMMIT_WMAP); } BT_MARK_DIRTY(mp, ip); if (p->header.flag & BT_ROOT) { p->header.flag &= ~BT_INTERNAL; p->header.flag |= BT_LEAF; p->header.nextindex = cpu_to_le16(XTENTRYSTART); if (le16_to_cpu(p->header.maxentry) == XTROOTMAXSLOT) { /* * Shrink root down to allow inline * EA (otherwise fsck complains) */ p->header.maxentry = cpu_to_le16(XTROOTINITSLOT); JFS_IP(ip)->mode2 |= INLINEEA; } XT_PUTPAGE(mp); /* debug */ goto out; } else { if (log) { /* COMMIT_PWMAP */ /* page will be invalidated at tx completion */ XT_PUTPAGE(mp); } else { /* COMMIT_WMAP */ if (mp->lid) lid_to_tlock(mp->lid)->flag |= tlckFREELOCK; /* invalidate parent page */ discard_metapage(mp); } /* parent has become empty and freed: * go back up to its parent page */ /* freed = 1; */ goto getParent; } } /* * parent page still has entries for front region; */ else { /* try truncate region covered by preceding entry * (process backward) */ index--; /* go back down to the child page corresponding * to the entry */ goto getChild; } /* * internal page: go down to child page of current entry */ getChild: /* save current parent entry for the child page */ if (BT_STACK_FULL(&btstack)) { jfs_error(ip->i_sb, "stack overrun in xtTruncate!"); XT_PUTPAGE(mp); return -EIO; } BT_PUSH(&btstack, bn, index); /* get child page */ xad = &p->xad[index]; bn = addressXAD(xad); /* * first access of each internal entry: */ /* release parent page */ XT_PUTPAGE(mp); /* process the child page */ goto getPage; out: /* * update file resource stat */ /* set size */ if (S_ISDIR(ip->i_mode) && !newsize) ip->i_size = 1; /* fsck hates zero-length directories */ else ip->i_size = newsize; /* update quota allocation to reflect freed blocks */ dquot_free_block(ip, nfreed); /* * free tlock of invalidated pages */ if (flag == COMMIT_WMAP) txFreelock(ip); return newsize; } /* * xtTruncate_pmap() * * function: * Perform truncate to zero length for deleted file, leaving the * the xtree and working map untouched. This allows the file to * be accessed via open file handles, while the delete of the file * is committed to disk. * * parameter: * tid_t tid, * struct inode *ip, * s64 committed_size) * * return: new committed size * * note: * * To avoid deadlock by holding too many transaction locks, the * truncation may be broken up into multiple transactions. * The committed_size keeps track of part of the file has been * freed from the pmaps. */ s64 xtTruncate_pmap(tid_t tid, struct inode *ip, s64 committed_size) { s64 bn; struct btstack btstack; int cmp; int index; int locked_leaves = 0; struct metapage *mp; xtpage_t *p; struct btframe *parent; int rc; struct tblock *tblk; struct tlock *tlck = NULL; xad_t *xad; int xlen; s64 xoff; struct xtlock *xtlck = NULL; /* save object truncation type */ tblk = tid_to_tblock(tid); tblk->xflag |= COMMIT_PMAP; /* clear stack */ BT_CLR(&btstack); if (committed_size) { xoff = (committed_size >> JFS_SBI(ip->i_sb)->l2bsize) - 1; rc = xtSearch(ip, xoff, NULL, &cmp, &btstack, 0); if (rc) return rc; XT_GETSEARCH(ip, btstack.top, bn, mp, p, index); if (cmp != 0) { XT_PUTPAGE(mp); jfs_error(ip->i_sb, "xtTruncate_pmap: did not find extent"); return -EIO; } } else { /* * start with root * * root resides in the inode */ bn = 0; /* * first access of each page: */ getPage: XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; /* process entries backward from last index */ index = le16_to_cpu(p->header.nextindex) - 1; if (p->header.flag & BT_INTERNAL) goto getChild; } /* * leaf page */ if (++locked_leaves > MAX_TRUNCATE_LEAVES) { /* * We need to limit the size of the transaction * to avoid exhausting pagecache & tlocks */ xad = &p->xad[index]; xoff = offsetXAD(xad); xlen = lengthXAD(xad); XT_PUTPAGE(mp); return (xoff + xlen) << JFS_SBI(ip->i_sb)->l2bsize; } tlck = txLock(tid, ip, mp, tlckXTREE); tlck->type = tlckXTREE | tlckFREE; xtlck = (struct xtlock *) & tlck->lock; xtlck->hwm.offset = index; XT_PUTPAGE(mp); /* * go back up to the parent page */ getParent: /* pop/restore parent entry for the current child page */ if ((parent = BT_POP(&btstack)) == NULL) /* current page must have been root */ goto out; /* get back the parent page */ bn = parent->bn; XT_GETPAGE(ip, bn, mp, PSIZE, p, rc); if (rc) return rc; index = parent->index; /* * parent page become empty: free the page */ if (index == XTENTRYSTART) { /* txCommit() with tlckFREE: * free child extents covered by parent; * invalidate parent if COMMIT_PWMAP; */ tlck = txLock(tid, ip, mp, tlckXTREE); xtlck = (struct xtlock *) & tlck->lock; xtlck->hwm.offset = le16_to_cpu(p->header.nextindex) - 1; tlck->type = tlckXTREE | tlckFREE; XT_PUTPAGE(mp); if (p->header.flag & BT_ROOT) { goto out; } else { goto getParent; } } /* * parent page still has entries for front region; */ else index--; /* * internal page: go down to child page of current entry */ getChild: /* save current parent entry for the child page */ if (BT_STACK_FULL(&btstack)) { jfs_error(ip->i_sb, "stack overrun in xtTruncate_pmap!"); XT_PUTPAGE(mp); return -EIO; } BT_PUSH(&btstack, bn, index); /* get child page */ xad = &p->xad[index]; bn = addressXAD(xad); /* * first access of each internal entry: */ /* release parent page */ XT_PUTPAGE(mp); /* process the child page */ goto getPage; out: return 0; } #ifdef CONFIG_JFS_STATISTICS static int jfs_xtstat_proc_show(struct seq_file *m, void *v) { seq_printf(m, "JFS Xtree statistics\n" "====================\n" "searches = %d\n" "fast searches = %d\n" "splits = %d\n", xtStat.search, xtStat.fastSearch, xtStat.split); return 0; } static int jfs_xtstat_proc_open(struct inode *inode, struct file *file) { return single_open(file, jfs_xtstat_proc_show, NULL); } const struct file_operations jfs_xtstat_proc_fops = { .owner = THIS_MODULE, .open = jfs_xtstat_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif
gpl-2.0
alexax66/kernel_samsung_a3xelte
drivers/gpu/arm/mali400/mali/linux/mali_sync_user.c
255
2992
/* * Copyright (C) 2011-2012 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained from Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file mali_sync_user.c * */ #ifdef CONFIG_SYNC #include <linux/sched.h> #include <linux/fdtable.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/module.h> #include <linux/anon_inodes.h> #include <linux/version.h> #include <asm/uaccess.h> /* MALI_SEC */ #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0) #include "mali_osk.h" #include "mali_kernel_common.h" #include "mali_sync.h" static int mali_stream_close(struct inode * inode, struct file * file) { struct sync_timeline * tl; tl = (struct sync_timeline*)file->private_data; BUG_ON(!tl); sync_timeline_destroy(tl); return 0; } static struct file_operations stream_fops = { .owner = THIS_MODULE, .release = mali_stream_close, }; _mali_osk_errcode_t mali_stream_create(const char * name, int *out_fd) { struct sync_timeline * tl; BUG_ON(!out_fd); tl = mali_sync_timeline_alloc(name); if (!tl) { return _MALI_OSK_ERR_FAULT; } *out_fd = anon_inode_getfd(name, &stream_fops, tl, O_RDONLY | O_CLOEXEC); if (*out_fd < 0) { sync_timeline_destroy(tl); return _MALI_OSK_ERR_FAULT; } else { return _MALI_OSK_ERR_OK; } } mali_sync_pt *mali_stream_create_point(int tl_fd) { struct sync_timeline *tl; struct sync_pt * pt; struct file *tl_file; tl_file = fget(tl_fd); if (tl_file == NULL) return NULL; if (tl_file->f_op != &stream_fops) { pt = NULL; goto out; } tl = tl_file->private_data; pt = mali_sync_pt_alloc(tl); if (!pt) { pt = NULL; goto out; } out: fput(tl_file); return pt; } int mali_stream_create_fence(mali_sync_pt *pt) { struct sync_fence *fence; struct fdtable * fdt; struct files_struct * files; int fd = -1; fence = sync_fence_create("mali_fence", pt); if (!fence) { sync_pt_free(pt); fd = -EFAULT; goto out; } /* create a fd representing the fence */ fd = get_unused_fd(); if (fd < 0) { sync_fence_put(fence); goto out; } files = current->files; spin_lock(&files->file_lock); fdt = files_fdtable(files); #if LINUX_VERSION_CODE >= KERNEL_VERSION(3,4,0) __set_close_on_exec(fd, fdt); #else FD_SET(fd, fdt->close_on_exec); #endif spin_unlock(&files->file_lock); /* bind fence to the new fd */ sync_fence_install(fence, fd); out: return fd; } _mali_osk_errcode_t mali_fence_validate(int fd) { struct sync_fence * fence; fence = sync_fence_fdget(fd); if (NULL != fence) { sync_fence_put(fence); return _MALI_OSK_ERR_OK; } else { return _MALI_OSK_ERR_FAULT; } } #endif #endif /* CONFIG_SYNC */
gpl-2.0
t0mm13b/CAF-Zte-Blade-Android-MSM-2.6.35
mm/sparse.c
255
21017
/* * sparse memory mappings. */ #include <linux/mm.h> #include <linux/slab.h> #include <linux/mmzone.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/vmalloc.h> #include "internal.h" #include <asm/dma.h> #include <asm/pgalloc.h> #include <asm/pgtable.h> /* * Permanent SPARSEMEM data: * * 1) mem_section - memory sections, mem_map's for valid memory */ #ifdef CONFIG_SPARSEMEM_EXTREME struct mem_section *mem_section[NR_SECTION_ROOTS] ____cacheline_internodealigned_in_smp; #else struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT] ____cacheline_internodealigned_in_smp; #endif EXPORT_SYMBOL(mem_section); #ifdef NODE_NOT_IN_PAGE_FLAGS /* * If we did not store the node number in the page then we have to * do a lookup in the section_to_node_table in order to find which * node the page belongs to. */ #if MAX_NUMNODES <= 256 static u8 section_to_node_table[NR_MEM_SECTIONS] __cacheline_aligned; #else static u16 section_to_node_table[NR_MEM_SECTIONS] __cacheline_aligned; #endif int page_to_nid(struct page *page) { return section_to_node_table[page_to_section(page)]; } EXPORT_SYMBOL(page_to_nid); static void set_section_nid(unsigned long section_nr, int nid) { section_to_node_table[section_nr] = nid; } #else /* !NODE_NOT_IN_PAGE_FLAGS */ static inline void set_section_nid(unsigned long section_nr, int nid) { } #endif #ifdef CONFIG_SPARSEMEM_EXTREME static struct mem_section noinline __init_refok *sparse_index_alloc(int nid) { struct mem_section *section = NULL; unsigned long array_size = SECTIONS_PER_ROOT * sizeof(struct mem_section); if (slab_is_available()) { if (node_state(nid, N_HIGH_MEMORY)) section = kmalloc_node(array_size, GFP_KERNEL, nid); else section = kmalloc(array_size, GFP_KERNEL); } else section = alloc_bootmem_node(NODE_DATA(nid), array_size); if (section) memset(section, 0, array_size); return section; } static int __meminit sparse_index_init(unsigned long section_nr, int nid) { static DEFINE_SPINLOCK(index_init_lock); unsigned long root = SECTION_NR_TO_ROOT(section_nr); struct mem_section *section; int ret = 0; if (mem_section[root]) return -EEXIST; section = sparse_index_alloc(nid); if (!section) return -ENOMEM; /* * This lock keeps two different sections from * reallocating for the same index */ spin_lock(&index_init_lock); if (mem_section[root]) { ret = -EEXIST; goto out; } mem_section[root] = section; out: spin_unlock(&index_init_lock); return ret; } #else /* !SPARSEMEM_EXTREME */ static inline int sparse_index_init(unsigned long section_nr, int nid) { return 0; } #endif /* * Although written for the SPARSEMEM_EXTREME case, this happens * to also work for the flat array case because * NR_SECTION_ROOTS==NR_MEM_SECTIONS. */ int __section_nr(struct mem_section *ms) { unsigned long root_nr; struct mem_section *root; if (NR_SECTION_ROOTS == 0) return ms - __nr_to_section(0); for (root_nr = 0; root_nr < NR_SECTION_ROOTS; root_nr++) { root = __nr_to_section(root_nr * SECTIONS_PER_ROOT); if (!root) continue; if ((ms >= root) && (ms < (root + SECTIONS_PER_ROOT))) break; } return (root_nr * SECTIONS_PER_ROOT) + (ms - root); } /* * During early boot, before section_mem_map is used for an actual * mem_map, we use section_mem_map to store the section's NUMA * node. This keeps us from having to use another data structure. The * node information is cleared just before we store the real mem_map. */ static inline unsigned long sparse_encode_early_nid(int nid) { return (nid << SECTION_NID_SHIFT); } static inline int sparse_early_nid(struct mem_section *section) { return (section->section_mem_map >> SECTION_NID_SHIFT); } /* Validate the physical addressing limitations of the model */ void __meminit mminit_validate_memmodel_limits(unsigned long *start_pfn, unsigned long *end_pfn) { unsigned long max_sparsemem_pfn = 1UL << (MAX_PHYSMEM_BITS-PAGE_SHIFT); /* * Sanity checks - do not allow an architecture to pass * in larger pfns than the maximum scope of sparsemem: */ if (*start_pfn > max_sparsemem_pfn) { mminit_dprintk(MMINIT_WARNING, "pfnvalidation", "Start of range %lu -> %lu exceeds SPARSEMEM max %lu\n", *start_pfn, *end_pfn, max_sparsemem_pfn); WARN_ON_ONCE(1); *start_pfn = max_sparsemem_pfn; *end_pfn = max_sparsemem_pfn; } else if (*end_pfn > max_sparsemem_pfn) { mminit_dprintk(MMINIT_WARNING, "pfnvalidation", "End of range %lu -> %lu exceeds SPARSEMEM max %lu\n", *start_pfn, *end_pfn, max_sparsemem_pfn); WARN_ON_ONCE(1); *end_pfn = max_sparsemem_pfn; } } /* Record a memory area against a node. */ void __init memory_present(int nid, unsigned long start, unsigned long end) { unsigned long pfn; start &= PAGE_SECTION_MASK; mminit_validate_memmodel_limits(&start, &end); for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION) { unsigned long section = pfn_to_section_nr(pfn); struct mem_section *ms; sparse_index_init(section, nid); set_section_nid(section, nid); ms = __nr_to_section(section); if (!ms->section_mem_map) ms->section_mem_map = sparse_encode_early_nid(nid) | SECTION_MARKED_PRESENT; } } /* * Only used by the i386 NUMA architecures, but relatively * generic code. */ unsigned long __init node_memmap_size_bytes(int nid, unsigned long start_pfn, unsigned long end_pfn) { unsigned long pfn; unsigned long nr_pages = 0; mminit_validate_memmodel_limits(&start_pfn, &end_pfn); for (pfn = start_pfn; pfn < end_pfn; pfn += PAGES_PER_SECTION) { if (nid != early_pfn_to_nid(pfn)) continue; if (pfn_present(pfn)) nr_pages += PAGES_PER_SECTION; } return nr_pages * sizeof(struct page); } /* * Subtle, we encode the real pfn into the mem_map such that * the identity pfn - section_mem_map will return the actual * physical page frame number. */ static unsigned long sparse_encode_mem_map(struct page *mem_map, unsigned long pnum) { return (unsigned long)(mem_map - (section_nr_to_pfn(pnum))); } /* * Decode mem_map from the coded memmap */ struct page *sparse_decode_mem_map(unsigned long coded_mem_map, unsigned long pnum) { /* mask off the extra low bits of information */ coded_mem_map &= SECTION_MAP_MASK; return ((struct page *)coded_mem_map) + section_nr_to_pfn(pnum); } static int __meminit sparse_init_one_section(struct mem_section *ms, unsigned long pnum, struct page *mem_map, unsigned long *pageblock_bitmap) { if (!present_section(ms)) return -EINVAL; ms->section_mem_map &= ~SECTION_MAP_MASK; ms->section_mem_map |= sparse_encode_mem_map(mem_map, pnum) | SECTION_HAS_MEM_MAP; ms->pageblock_flags = pageblock_bitmap; return 1; } unsigned long usemap_size(void) { unsigned long size_bytes; size_bytes = roundup(SECTION_BLOCKFLAGS_BITS, 8) / 8; size_bytes = roundup(size_bytes, sizeof(unsigned long)); return size_bytes; } #ifdef CONFIG_MEMORY_HOTPLUG static unsigned long *__kmalloc_section_usemap(void) { return kmalloc(usemap_size(), GFP_KERNEL); } #endif /* CONFIG_MEMORY_HOTPLUG */ #ifdef CONFIG_MEMORY_HOTREMOVE static unsigned long * __init sparse_early_usemaps_alloc_pgdat_section(struct pglist_data *pgdat, unsigned long count) { unsigned long section_nr; /* * A page may contain usemaps for other sections preventing the * page being freed and making a section unremovable while * other sections referencing the usemap retmain active. Similarly, * a pgdat can prevent a section being removed. If section A * contains a pgdat and section B contains the usemap, both * sections become inter-dependent. This allocates usemaps * from the same section as the pgdat where possible to avoid * this problem. */ section_nr = pfn_to_section_nr(__pa(pgdat) >> PAGE_SHIFT); return alloc_bootmem_section(usemap_size() * count, section_nr); } static void __init check_usemap_section_nr(int nid, unsigned long *usemap) { unsigned long usemap_snr, pgdat_snr; static unsigned long old_usemap_snr = NR_MEM_SECTIONS; static unsigned long old_pgdat_snr = NR_MEM_SECTIONS; struct pglist_data *pgdat = NODE_DATA(nid); int usemap_nid; usemap_snr = pfn_to_section_nr(__pa(usemap) >> PAGE_SHIFT); pgdat_snr = pfn_to_section_nr(__pa(pgdat) >> PAGE_SHIFT); if (usemap_snr == pgdat_snr) return; if (old_usemap_snr == usemap_snr && old_pgdat_snr == pgdat_snr) /* skip redundant message */ return; old_usemap_snr = usemap_snr; old_pgdat_snr = pgdat_snr; usemap_nid = sparse_early_nid(__nr_to_section(usemap_snr)); if (usemap_nid != nid) { printk(KERN_INFO "node %d must be removed before remove section %ld\n", nid, usemap_snr); return; } /* * There is a circular dependency. * Some platforms allow un-removable section because they will just * gather other removable sections for dynamic partitioning. * Just notify un-removable section's number here. */ printk(KERN_INFO "Section %ld and %ld (node %d)", usemap_snr, pgdat_snr, nid); printk(KERN_CONT " have a circular dependency on usemap and pgdat allocations\n"); } #else static unsigned long * __init sparse_early_usemaps_alloc_pgdat_section(struct pglist_data *pgdat, unsigned long count) { return NULL; } static void __init check_usemap_section_nr(int nid, unsigned long *usemap) { } #endif /* CONFIG_MEMORY_HOTREMOVE */ static void __init sparse_early_usemaps_alloc_node(unsigned long**usemap_map, unsigned long pnum_begin, unsigned long pnum_end, unsigned long usemap_count, int nodeid) { void *usemap; unsigned long pnum; int size = usemap_size(); usemap = sparse_early_usemaps_alloc_pgdat_section(NODE_DATA(nodeid), usemap_count); if (usemap) { for (pnum = pnum_begin; pnum < pnum_end; pnum++) { if (!present_section_nr(pnum)) continue; usemap_map[pnum] = usemap; usemap += size; } return; } usemap = alloc_bootmem_node(NODE_DATA(nodeid), size * usemap_count); if (usemap) { for (pnum = pnum_begin; pnum < pnum_end; pnum++) { if (!present_section_nr(pnum)) continue; usemap_map[pnum] = usemap; usemap += size; check_usemap_section_nr(nodeid, usemap_map[pnum]); } return; } printk(KERN_WARNING "%s: allocation failed\n", __func__); } #ifndef CONFIG_SPARSEMEM_VMEMMAP struct page __init *sparse_mem_map_populate(unsigned long pnum, int nid) { struct page *map; unsigned long size; map = alloc_remap(nid, sizeof(struct page) * PAGES_PER_SECTION); if (map) return map; size = PAGE_ALIGN(sizeof(struct page) * PAGES_PER_SECTION); map = __alloc_bootmem_node_high(NODE_DATA(nid), size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS)); return map; } void __init sparse_mem_maps_populate_node(struct page **map_map, unsigned long pnum_begin, unsigned long pnum_end, unsigned long map_count, int nodeid) { void *map; unsigned long pnum; unsigned long size = sizeof(struct page) * PAGES_PER_SECTION; map = alloc_remap(nodeid, size * map_count); if (map) { for (pnum = pnum_begin; pnum < pnum_end; pnum++) { if (!present_section_nr(pnum)) continue; map_map[pnum] = map; map += size; } return; } size = PAGE_ALIGN(size); map = __alloc_bootmem_node_high(NODE_DATA(nodeid), size * map_count, PAGE_SIZE, __pa(MAX_DMA_ADDRESS)); if (map) { for (pnum = pnum_begin; pnum < pnum_end; pnum++) { if (!present_section_nr(pnum)) continue; map_map[pnum] = map; map += size; } return; } /* fallback */ for (pnum = pnum_begin; pnum < pnum_end; pnum++) { struct mem_section *ms; if (!present_section_nr(pnum)) continue; map_map[pnum] = sparse_mem_map_populate(pnum, nodeid); if (map_map[pnum]) continue; ms = __nr_to_section(pnum); printk(KERN_ERR "%s: sparsemem memory map backing failed " "some memory will not be available.\n", __func__); ms->section_mem_map = 0; } } #endif /* !CONFIG_SPARSEMEM_VMEMMAP */ #ifdef CONFIG_SPARSEMEM_ALLOC_MEM_MAP_TOGETHER static void __init sparse_early_mem_maps_alloc_node(struct page **map_map, unsigned long pnum_begin, unsigned long pnum_end, unsigned long map_count, int nodeid) { sparse_mem_maps_populate_node(map_map, pnum_begin, pnum_end, map_count, nodeid); } #else static struct page __init *sparse_early_mem_map_alloc(unsigned long pnum) { struct page *map; struct mem_section *ms = __nr_to_section(pnum); int nid = sparse_early_nid(ms); map = sparse_mem_map_populate(pnum, nid); if (map) return map; printk(KERN_ERR "%s: sparsemem memory map backing failed " "some memory will not be available.\n", __func__); ms->section_mem_map = 0; return NULL; } #endif void __attribute__((weak)) __meminit vmemmap_populate_print_last(void) { } /* * Allocate the accumulated non-linear sections, allocate a mem_map * for each and record the physical to section mapping. */ void __init sparse_init(void) { unsigned long pnum; struct page *map; unsigned long *usemap; unsigned long **usemap_map; int size; int nodeid_begin = 0; unsigned long pnum_begin = 0; unsigned long usemap_count; #ifdef CONFIG_SPARSEMEM_ALLOC_MEM_MAP_TOGETHER unsigned long map_count; int size2; struct page **map_map; #endif /* * map is using big page (aka 2M in x86 64 bit) * usemap is less one page (aka 24 bytes) * so alloc 2M (with 2M align) and 24 bytes in turn will * make next 2M slip to one more 2M later. * then in big system, the memory will have a lot of holes... * here try to allocate 2M pages continously. * * powerpc need to call sparse_init_one_section right after each * sparse_early_mem_map_alloc, so allocate usemap_map at first. */ size = sizeof(unsigned long *) * NR_MEM_SECTIONS; usemap_map = alloc_bootmem(size); if (!usemap_map) panic("can not allocate usemap_map\n"); for (pnum = 0; pnum < NR_MEM_SECTIONS; pnum++) { struct mem_section *ms; if (!present_section_nr(pnum)) continue; ms = __nr_to_section(pnum); nodeid_begin = sparse_early_nid(ms); pnum_begin = pnum; break; } usemap_count = 1; for (pnum = pnum_begin + 1; pnum < NR_MEM_SECTIONS; pnum++) { struct mem_section *ms; int nodeid; if (!present_section_nr(pnum)) continue; ms = __nr_to_section(pnum); nodeid = sparse_early_nid(ms); if (nodeid == nodeid_begin) { usemap_count++; continue; } /* ok, we need to take cake of from pnum_begin to pnum - 1*/ sparse_early_usemaps_alloc_node(usemap_map, pnum_begin, pnum, usemap_count, nodeid_begin); /* new start, update count etc*/ nodeid_begin = nodeid; pnum_begin = pnum; usemap_count = 1; } /* ok, last chunk */ sparse_early_usemaps_alloc_node(usemap_map, pnum_begin, NR_MEM_SECTIONS, usemap_count, nodeid_begin); #ifdef CONFIG_SPARSEMEM_ALLOC_MEM_MAP_TOGETHER size2 = sizeof(struct page *) * NR_MEM_SECTIONS; map_map = alloc_bootmem(size2); if (!map_map) panic("can not allocate map_map\n"); for (pnum = 0; pnum < NR_MEM_SECTIONS; pnum++) { struct mem_section *ms; if (!present_section_nr(pnum)) continue; ms = __nr_to_section(pnum); nodeid_begin = sparse_early_nid(ms); pnum_begin = pnum; break; } map_count = 1; for (pnum = pnum_begin + 1; pnum < NR_MEM_SECTIONS; pnum++) { struct mem_section *ms; int nodeid; if (!present_section_nr(pnum)) continue; ms = __nr_to_section(pnum); nodeid = sparse_early_nid(ms); if (nodeid == nodeid_begin) { map_count++; continue; } /* ok, we need to take cake of from pnum_begin to pnum - 1*/ sparse_early_mem_maps_alloc_node(map_map, pnum_begin, pnum, map_count, nodeid_begin); /* new start, update count etc*/ nodeid_begin = nodeid; pnum_begin = pnum; map_count = 1; } /* ok, last chunk */ sparse_early_mem_maps_alloc_node(map_map, pnum_begin, NR_MEM_SECTIONS, map_count, nodeid_begin); #endif for (pnum = 0; pnum < NR_MEM_SECTIONS; pnum++) { if (!present_section_nr(pnum)) continue; usemap = usemap_map[pnum]; if (!usemap) continue; #ifdef CONFIG_SPARSEMEM_ALLOC_MEM_MAP_TOGETHER map = map_map[pnum]; #else map = sparse_early_mem_map_alloc(pnum); #endif if (!map) continue; sparse_init_one_section(__nr_to_section(pnum), pnum, map, usemap); } vmemmap_populate_print_last(); #ifdef CONFIG_SPARSEMEM_ALLOC_MEM_MAP_TOGETHER free_bootmem(__pa(map_map), size2); #endif free_bootmem(__pa(usemap_map), size); } #ifdef CONFIG_MEMORY_HOTPLUG #ifdef CONFIG_SPARSEMEM_VMEMMAP static inline struct page *kmalloc_section_memmap(unsigned long pnum, int nid, unsigned long nr_pages) { /* This will make the necessary allocations eventually. */ return sparse_mem_map_populate(pnum, nid); } static void __kfree_section_memmap(struct page *memmap, unsigned long nr_pages) { return; /* XXX: Not implemented yet */ } static void free_map_bootmem(struct page *page, unsigned long nr_pages) { } #else static struct page *__kmalloc_section_memmap(unsigned long nr_pages) { struct page *page, *ret; unsigned long memmap_size = sizeof(struct page) * nr_pages; page = alloc_pages(GFP_KERNEL|__GFP_NOWARN, get_order(memmap_size)); if (page) goto got_map_page; ret = vmalloc(memmap_size); if (ret) goto got_map_ptr; return NULL; got_map_page: ret = (struct page *)pfn_to_kaddr(page_to_pfn(page)); got_map_ptr: memset(ret, 0, memmap_size); return ret; } static inline struct page *kmalloc_section_memmap(unsigned long pnum, int nid, unsigned long nr_pages) { return __kmalloc_section_memmap(nr_pages); } static void __kfree_section_memmap(struct page *memmap, unsigned long nr_pages) { if (is_vmalloc_addr(memmap)) vfree(memmap); else free_pages((unsigned long)memmap, get_order(sizeof(struct page) * nr_pages)); } static void free_map_bootmem(struct page *page, unsigned long nr_pages) { unsigned long maps_section_nr, removing_section_nr, i; int magic; for (i = 0; i < nr_pages; i++, page++) { magic = atomic_read(&page->_mapcount); BUG_ON(magic == NODE_INFO); maps_section_nr = pfn_to_section_nr(page_to_pfn(page)); removing_section_nr = page->private; /* * When this function is called, the removing section is * logical offlined state. This means all pages are isolated * from page allocator. If removing section's memmap is placed * on the same section, it must not be freed. * If it is freed, page allocator may allocate it which will * be removed physically soon. */ if (maps_section_nr != removing_section_nr) put_page_bootmem(page); } } #endif /* CONFIG_SPARSEMEM_VMEMMAP */ static void free_section_usemap(struct page *memmap, unsigned long *usemap) { struct page *usemap_page; unsigned long nr_pages; if (!usemap) return; usemap_page = virt_to_page(usemap); /* * Check to see if allocation came from hot-plug-add */ if (PageSlab(usemap_page)) { kfree(usemap); if (memmap) __kfree_section_memmap(memmap, PAGES_PER_SECTION); return; } /* * The usemap came from bootmem. This is packed with other usemaps * on the section which has pgdat at boot time. Just keep it as is now. */ if (memmap) { struct page *memmap_page; memmap_page = virt_to_page(memmap); nr_pages = PAGE_ALIGN(PAGES_PER_SECTION * sizeof(struct page)) >> PAGE_SHIFT; free_map_bootmem(memmap_page, nr_pages); } } /* * returns the number of sections whose mem_maps were properly * set. If this is <=0, then that means that the passed-in * map was not consumed and must be freed. */ int __meminit sparse_add_one_section(struct zone *zone, unsigned long start_pfn, int nr_pages) { unsigned long section_nr = pfn_to_section_nr(start_pfn); struct pglist_data *pgdat = zone->zone_pgdat; struct mem_section *ms; struct page *memmap; unsigned long *usemap; unsigned long flags; int ret; /* * no locking for this, because it does its own * plus, it does a kmalloc */ ret = sparse_index_init(section_nr, pgdat->node_id); if (ret < 0 && ret != -EEXIST) return ret; memmap = kmalloc_section_memmap(section_nr, pgdat->node_id, nr_pages); if (!memmap) return -ENOMEM; usemap = __kmalloc_section_usemap(); if (!usemap) { __kfree_section_memmap(memmap, nr_pages); return -ENOMEM; } pgdat_resize_lock(pgdat, &flags); ms = __pfn_to_section(start_pfn); if (ms->section_mem_map & SECTION_MARKED_PRESENT) { ret = -EEXIST; goto out; } ms->section_mem_map |= SECTION_MARKED_PRESENT; ret = sparse_init_one_section(ms, section_nr, memmap, usemap); out: pgdat_resize_unlock(pgdat, &flags); if (ret <= 0) { kfree(usemap); __kfree_section_memmap(memmap, nr_pages); } return ret; } void sparse_remove_one_section(struct zone *zone, struct mem_section *ms) { struct page *memmap = NULL; unsigned long *usemap = NULL; if (ms->section_mem_map) { usemap = ms->pageblock_flags; memmap = sparse_decode_mem_map(ms->section_mem_map, __section_nr(ms)); ms->section_mem_map = 0; ms->pageblock_flags = NULL; } free_section_usemap(memmap, usemap); } #endif
gpl-2.0
Brainiarc7/android_kernel_huawei_u8185
drivers/video/backlight/ltv350qv.c
255
8418
/* * Power control for Samsung LTV350QV Quarter VGA LCD Panel * * Copyright (C) 2006, 2007 Atmel Corporation * * 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/delay.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include "ltv350qv.h" #define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL) struct ltv350qv { struct spi_device *spi; u8 *buffer; int power; struct lcd_device *ld; }; /* * The power-on and power-off sequences are taken from the * LTV350QV-F04 data sheet from Samsung. The register definitions are * taken from the S6F2002 command list also from Samsung. Both * documents are distributed with the AVR32 Linux BSP CD from Atmel. * * There's still some voodoo going on here, but it's a lot better than * in the first incarnation of the driver where all we had was the raw * numbers from the initialization sequence. */ static int ltv350qv_write_reg(struct ltv350qv *lcd, u8 reg, u16 val) { struct spi_message msg; struct spi_transfer index_xfer = { .len = 3, .cs_change = 1, }; struct spi_transfer value_xfer = { .len = 3, }; spi_message_init(&msg); /* register index */ lcd->buffer[0] = LTV_OPC_INDEX; lcd->buffer[1] = 0x00; lcd->buffer[2] = reg & 0x7f; index_xfer.tx_buf = lcd->buffer; spi_message_add_tail(&index_xfer, &msg); /* register value */ lcd->buffer[4] = LTV_OPC_DATA; lcd->buffer[5] = val >> 8; lcd->buffer[6] = val; value_xfer.tx_buf = lcd->buffer + 4; spi_message_add_tail(&value_xfer, &msg); return spi_sync(lcd->spi, &msg); } /* The comments are taken straight from the data sheet */ static int ltv350qv_power_on(struct ltv350qv *lcd) { int ret; /* Power On Reset Display off State */ if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, 0x0000)) goto err; msleep(15); /* Power Setting Function 1 */ if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE)) goto err; if (ltv350qv_write_reg(lcd, LTV_PWRCTL2, LTV_VCOML_ENABLE)) goto err_power1; /* Power Setting Function 2 */ if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5))) goto err_power2; msleep(55); /* Instruction Setting */ ret = ltv350qv_write_reg(lcd, LTV_IFCTL, LTV_NMD | LTV_REV | LTV_NL(0x1d)); ret |= ltv350qv_write_reg(lcd, LTV_DATACTL, LTV_DS_SAME | LTV_CHS_480 | LTV_DF_RGB | LTV_RGB_BGR); ret |= ltv350qv_write_reg(lcd, LTV_ENTRY_MODE, LTV_VSPL_ACTIVE_LOW | LTV_HSPL_ACTIVE_LOW | LTV_DPL_SAMPLE_RISING | LTV_EPL_ACTIVE_LOW | LTV_SS_RIGHT_TO_LEFT); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL1, LTV_CLW(3)); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_FWI(3)); ret |= ltv350qv_write_reg(lcd, LTV_VBP, 0x000a); ret |= ltv350qv_write_reg(lcd, LTV_HBP, 0x0021); ret |= ltv350qv_write_reg(lcd, LTV_SOTCTL, LTV_SDT(3) | LTV_EQ(0)); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(0), 0x0103); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(1), 0x0301); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(2), 0x1f0f); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(3), 0x1f0f); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(4), 0x0707); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(5), 0x0307); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(6), 0x0707); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(7), 0x0000); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(8), 0x0004); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(9), 0x0000); if (ret) goto err_settings; /* Wait more than 2 frames */ msleep(20); /* Display On Sequence */ ret = ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_VCOMOUT_ENABLE | LTV_POWER_ON | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5)); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_DSC | LTV_FWI(3)); if (ret) goto err_disp_on; /* Display should now be ON. Phew. */ return 0; err_disp_on: /* * Try to recover. Error handling probably isn't very useful * at this point, just make a best effort to switch the panel * off. */ ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5)); ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_FWI(3)); err_settings: err_power2: err_power1: ltv350qv_write_reg(lcd, LTV_PWRCTL2, 0x0000); msleep(1); err: ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE); return -EIO; } static int ltv350qv_power_off(struct ltv350qv *lcd) { int ret; /* Display Off Sequence */ ret = ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5)); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_FWI(3)); /* Power down setting 1 */ ret |= ltv350qv_write_reg(lcd, LTV_PWRCTL2, 0x0000); /* Wait at least 1 ms */ msleep(1); /* Power down setting 2 */ ret |= ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE); /* * No point in trying to recover here. If we can't switch the * panel off, what are we supposed to do other than inform the * user about the failure? */ if (ret) return -EIO; /* Display power should now be OFF */ return 0; } static int ltv350qv_power(struct ltv350qv *lcd, int power) { int ret = 0; if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power)) ret = ltv350qv_power_on(lcd); else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power)) ret = ltv350qv_power_off(lcd); if (!ret) lcd->power = power; return ret; } static int ltv350qv_set_power(struct lcd_device *ld, int power) { struct ltv350qv *lcd = lcd_get_data(ld); return ltv350qv_power(lcd, power); } static int ltv350qv_get_power(struct lcd_device *ld) { struct ltv350qv *lcd = lcd_get_data(ld); return lcd->power; } static struct lcd_ops ltv_ops = { .get_power = ltv350qv_get_power, .set_power = ltv350qv_set_power, }; static int __devinit ltv350qv_probe(struct spi_device *spi) { struct ltv350qv *lcd; struct lcd_device *ld; int ret; lcd = kzalloc(sizeof(struct ltv350qv), GFP_KERNEL); if (!lcd) return -ENOMEM; lcd->spi = spi; lcd->power = FB_BLANK_POWERDOWN; lcd->buffer = kzalloc(8, GFP_KERNEL); if (!lcd->buffer) { ret = -ENOMEM; goto out_free_lcd; } ld = lcd_device_register("ltv350qv", &spi->dev, lcd, &ltv_ops); if (IS_ERR(ld)) { ret = PTR_ERR(ld); goto out_free_buffer; } lcd->ld = ld; ret = ltv350qv_power(lcd, FB_BLANK_UNBLANK); if (ret) goto out_unregister; dev_set_drvdata(&spi->dev, lcd); return 0; out_unregister: lcd_device_unregister(ld); out_free_buffer: kfree(lcd->buffer); out_free_lcd: kfree(lcd); return ret; } static int __devexit ltv350qv_remove(struct spi_device *spi) { struct ltv350qv *lcd = dev_get_drvdata(&spi->dev); ltv350qv_power(lcd, FB_BLANK_POWERDOWN); lcd_device_unregister(lcd->ld); kfree(lcd->buffer); kfree(lcd); return 0; } #ifdef CONFIG_PM static int ltv350qv_suspend(struct spi_device *spi, pm_message_t state) { struct ltv350qv *lcd = dev_get_drvdata(&spi->dev); return ltv350qv_power(lcd, FB_BLANK_POWERDOWN); } static int ltv350qv_resume(struct spi_device *spi) { struct ltv350qv *lcd = dev_get_drvdata(&spi->dev); return ltv350qv_power(lcd, FB_BLANK_UNBLANK); } #else #define ltv350qv_suspend NULL #define ltv350qv_resume NULL #endif /* Power down all displays on reboot, poweroff or halt */ static void ltv350qv_shutdown(struct spi_device *spi) { struct ltv350qv *lcd = dev_get_drvdata(&spi->dev); ltv350qv_power(lcd, FB_BLANK_POWERDOWN); } static struct spi_driver ltv350qv_driver = { .driver = { .name = "ltv350qv", .bus = &spi_bus_type, .owner = THIS_MODULE, }, .probe = ltv350qv_probe, .remove = __devexit_p(ltv350qv_remove), .shutdown = ltv350qv_shutdown, .suspend = ltv350qv_suspend, .resume = ltv350qv_resume, }; static int __init ltv350qv_init(void) { return spi_register_driver(&ltv350qv_driver); } static void __exit ltv350qv_exit(void) { spi_unregister_driver(&ltv350qv_driver); } module_init(ltv350qv_init); module_exit(ltv350qv_exit); MODULE_AUTHOR("Haavard Skinnemoen <hskinnemoen@atmel.com>"); MODULE_DESCRIPTION("Samsung LTV350QV LCD Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:ltv350qv");
gpl-2.0
singleman/linux
security/selinux/ss/ebitmap.c
767
10717
/* * Implementation of the extensible bitmap type. * * Author : Stephen Smalley, <sds@epoch.ncsc.mil> */ /* * Updated: Hewlett-Packard <paul@paul-moore.com> * * Added support to import/export the NetLabel category bitmap * * (c) Copyright Hewlett-Packard Development Company, L.P., 2006 */ /* * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com> * Applied standard bit operations to improve bitmap scanning. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/errno.h> #include <net/netlabel.h> #include "ebitmap.h" #include "policydb.h" #define BITS_PER_U64 (sizeof(u64) * 8) int ebitmap_cmp(struct ebitmap *e1, struct ebitmap *e2) { struct ebitmap_node *n1, *n2; if (e1->highbit != e2->highbit) return 0; n1 = e1->node; n2 = e2->node; while (n1 && n2 && (n1->startbit == n2->startbit) && !memcmp(n1->maps, n2->maps, EBITMAP_SIZE / 8)) { n1 = n1->next; n2 = n2->next; } if (n1 || n2) return 0; return 1; } int ebitmap_cpy(struct ebitmap *dst, struct ebitmap *src) { struct ebitmap_node *n, *new, *prev; ebitmap_init(dst); n = src->node; prev = NULL; while (n) { new = kzalloc(sizeof(*new), GFP_ATOMIC); if (!new) { ebitmap_destroy(dst); return -ENOMEM; } new->startbit = n->startbit; memcpy(new->maps, n->maps, EBITMAP_SIZE / 8); new->next = NULL; if (prev) prev->next = new; else dst->node = new; prev = new; n = n->next; } dst->highbit = src->highbit; return 0; } #ifdef CONFIG_NETLABEL /** * ebitmap_netlbl_export - Export an ebitmap into a NetLabel category bitmap * @ebmap: the ebitmap to export * @catmap: the NetLabel category bitmap * * Description: * Export a SELinux extensibile bitmap into a NetLabel category bitmap. * Returns zero on success, negative values on error. * */ int ebitmap_netlbl_export(struct ebitmap *ebmap, struct netlbl_lsm_catmap **catmap) { struct ebitmap_node *e_iter = ebmap->node; unsigned long e_map; u32 offset; unsigned int iter; int rc; if (e_iter == NULL) { *catmap = NULL; return 0; } if (*catmap != NULL) netlbl_catmap_free(*catmap); *catmap = NULL; while (e_iter) { offset = e_iter->startbit; for (iter = 0; iter < EBITMAP_UNIT_NUMS; iter++) { e_map = e_iter->maps[iter]; if (e_map != 0) { rc = netlbl_catmap_setlong(catmap, offset, e_map, GFP_ATOMIC); if (rc != 0) goto netlbl_export_failure; } offset += EBITMAP_UNIT_SIZE; } e_iter = e_iter->next; } return 0; netlbl_export_failure: netlbl_catmap_free(*catmap); return -ENOMEM; } /** * ebitmap_netlbl_import - Import a NetLabel category bitmap into an ebitmap * @ebmap: the ebitmap to import * @catmap: the NetLabel category bitmap * * Description: * Import a NetLabel category bitmap into a SELinux extensibile bitmap. * Returns zero on success, negative values on error. * */ int ebitmap_netlbl_import(struct ebitmap *ebmap, struct netlbl_lsm_catmap *catmap) { int rc; struct ebitmap_node *e_iter = NULL; struct ebitmap_node *e_prev = NULL; u32 offset = 0, idx; unsigned long bitmap; for (;;) { rc = netlbl_catmap_getlong(catmap, &offset, &bitmap); if (rc < 0) goto netlbl_import_failure; if (offset == (u32)-1) return 0; /* don't waste ebitmap space if the netlabel bitmap is empty */ if (bitmap == 0) { offset += EBITMAP_UNIT_SIZE; continue; } if (e_iter == NULL || offset >= e_iter->startbit + EBITMAP_SIZE) { e_prev = e_iter; e_iter = kzalloc(sizeof(*e_iter), GFP_ATOMIC); if (e_iter == NULL) goto netlbl_import_failure; e_iter->startbit = offset & ~(EBITMAP_SIZE - 1); if (e_prev == NULL) ebmap->node = e_iter; else e_prev->next = e_iter; ebmap->highbit = e_iter->startbit + EBITMAP_SIZE; } /* offset will always be aligned to an unsigned long */ idx = EBITMAP_NODE_INDEX(e_iter, offset); e_iter->maps[idx] = bitmap; /* next */ offset += EBITMAP_UNIT_SIZE; } /* NOTE: we should never reach this return */ return 0; netlbl_import_failure: ebitmap_destroy(ebmap); return -ENOMEM; } #endif /* CONFIG_NETLABEL */ /* * Check to see if all the bits set in e2 are also set in e1. Optionally, * if last_e2bit is non-zero, the highest set bit in e2 cannot exceed * last_e2bit. */ int ebitmap_contains(struct ebitmap *e1, struct ebitmap *e2, u32 last_e2bit) { struct ebitmap_node *n1, *n2; int i; if (e1->highbit < e2->highbit) return 0; n1 = e1->node; n2 = e2->node; while (n1 && n2 && (n1->startbit <= n2->startbit)) { if (n1->startbit < n2->startbit) { n1 = n1->next; continue; } for (i = EBITMAP_UNIT_NUMS - 1; (i >= 0) && !n2->maps[i]; ) i--; /* Skip trailing NULL map entries */ if (last_e2bit && (i >= 0)) { u32 lastsetbit = n2->startbit + i * EBITMAP_UNIT_SIZE + __fls(n2->maps[i]); if (lastsetbit > last_e2bit) return 0; } while (i >= 0) { if ((n1->maps[i] & n2->maps[i]) != n2->maps[i]) return 0; i--; } n1 = n1->next; n2 = n2->next; } if (n2) return 0; return 1; } int ebitmap_get_bit(struct ebitmap *e, unsigned long bit) { struct ebitmap_node *n; if (e->highbit < bit) return 0; n = e->node; while (n && (n->startbit <= bit)) { if ((n->startbit + EBITMAP_SIZE) > bit) return ebitmap_node_get_bit(n, bit); n = n->next; } return 0; } int ebitmap_set_bit(struct ebitmap *e, unsigned long bit, int value) { struct ebitmap_node *n, *prev, *new; prev = NULL; n = e->node; while (n && n->startbit <= bit) { if ((n->startbit + EBITMAP_SIZE) > bit) { if (value) { ebitmap_node_set_bit(n, bit); } else { unsigned int s; ebitmap_node_clr_bit(n, bit); s = find_first_bit(n->maps, EBITMAP_SIZE); if (s < EBITMAP_SIZE) return 0; /* drop this node from the bitmap */ if (!n->next) { /* * this was the highest map * within the bitmap */ if (prev) e->highbit = prev->startbit + EBITMAP_SIZE; else e->highbit = 0; } if (prev) prev->next = n->next; else e->node = n->next; kfree(n); } return 0; } prev = n; n = n->next; } if (!value) return 0; new = kzalloc(sizeof(*new), GFP_ATOMIC); if (!new) return -ENOMEM; new->startbit = bit - (bit % EBITMAP_SIZE); ebitmap_node_set_bit(new, bit); if (!n) /* this node will be the highest map within the bitmap */ e->highbit = new->startbit + EBITMAP_SIZE; if (prev) { new->next = prev->next; prev->next = new; } else { new->next = e->node; e->node = new; } return 0; } void ebitmap_destroy(struct ebitmap *e) { struct ebitmap_node *n, *temp; if (!e) return; n = e->node; while (n) { temp = n; n = n->next; kfree(temp); } e->highbit = 0; e->node = NULL; return; } int ebitmap_read(struct ebitmap *e, void *fp) { struct ebitmap_node *n = NULL; u32 mapunit, count, startbit, index; u64 map; __le32 buf[3]; int rc, i; ebitmap_init(e); rc = next_entry(buf, fp, sizeof buf); if (rc < 0) goto out; mapunit = le32_to_cpu(buf[0]); e->highbit = le32_to_cpu(buf[1]); count = le32_to_cpu(buf[2]); if (mapunit != BITS_PER_U64) { printk(KERN_ERR "SELinux: ebitmap: map size %u does not " "match my size %Zd (high bit was %d)\n", mapunit, BITS_PER_U64, e->highbit); goto bad; } /* round up e->highbit */ e->highbit += EBITMAP_SIZE - 1; e->highbit -= (e->highbit % EBITMAP_SIZE); if (!e->highbit) { e->node = NULL; goto ok; } for (i = 0; i < count; i++) { rc = next_entry(&startbit, fp, sizeof(u32)); if (rc < 0) { printk(KERN_ERR "SELinux: ebitmap: truncated map\n"); goto bad; } startbit = le32_to_cpu(startbit); if (startbit & (mapunit - 1)) { printk(KERN_ERR "SELinux: ebitmap start bit (%d) is " "not a multiple of the map unit size (%u)\n", startbit, mapunit); goto bad; } if (startbit > e->highbit - mapunit) { printk(KERN_ERR "SELinux: ebitmap start bit (%d) is " "beyond the end of the bitmap (%u)\n", startbit, (e->highbit - mapunit)); goto bad; } if (!n || startbit >= n->startbit + EBITMAP_SIZE) { struct ebitmap_node *tmp; tmp = kzalloc(sizeof(*tmp), GFP_KERNEL); if (!tmp) { printk(KERN_ERR "SELinux: ebitmap: out of memory\n"); rc = -ENOMEM; goto bad; } /* round down */ tmp->startbit = startbit - (startbit % EBITMAP_SIZE); if (n) n->next = tmp; else e->node = tmp; n = tmp; } else if (startbit <= n->startbit) { printk(KERN_ERR "SELinux: ebitmap: start bit %d" " comes after start bit %d\n", startbit, n->startbit); goto bad; } rc = next_entry(&map, fp, sizeof(u64)); if (rc < 0) { printk(KERN_ERR "SELinux: ebitmap: truncated map\n"); goto bad; } map = le64_to_cpu(map); index = (startbit - n->startbit) / EBITMAP_UNIT_SIZE; while (map) { n->maps[index++] = map & (-1UL); map = EBITMAP_SHIFT_UNIT_SIZE(map); } } ok: rc = 0; out: return rc; bad: if (!rc) rc = -EINVAL; ebitmap_destroy(e); goto out; } int ebitmap_write(struct ebitmap *e, void *fp) { struct ebitmap_node *n; u32 count; __le32 buf[3]; u64 map; int bit, last_bit, last_startbit, rc; buf[0] = cpu_to_le32(BITS_PER_U64); count = 0; last_bit = 0; last_startbit = -1; ebitmap_for_each_positive_bit(e, n, bit) { if (rounddown(bit, (int)BITS_PER_U64) > last_startbit) { count++; last_startbit = rounddown(bit, BITS_PER_U64); } last_bit = roundup(bit + 1, BITS_PER_U64); } buf[1] = cpu_to_le32(last_bit); buf[2] = cpu_to_le32(count); rc = put_entry(buf, sizeof(u32), 3, fp); if (rc) return rc; map = 0; last_startbit = INT_MIN; ebitmap_for_each_positive_bit(e, n, bit) { if (rounddown(bit, (int)BITS_PER_U64) > last_startbit) { __le64 buf64[1]; /* this is the very first bit */ if (!map) { last_startbit = rounddown(bit, BITS_PER_U64); map = (u64)1 << (bit - last_startbit); continue; } /* write the last node */ buf[0] = cpu_to_le32(last_startbit); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; buf64[0] = cpu_to_le64(map); rc = put_entry(buf64, sizeof(u64), 1, fp); if (rc) return rc; /* set up for the next node */ map = 0; last_startbit = rounddown(bit, BITS_PER_U64); } map |= (u64)1 << (bit - last_startbit); } /* write the last node */ if (map) { __le64 buf64[1]; /* write the last node */ buf[0] = cpu_to_le32(last_startbit); rc = put_entry(buf, sizeof(u32), 1, fp); if (rc) return rc; buf64[0] = cpu_to_le64(map); rc = put_entry(buf64, sizeof(u64), 1, fp); if (rc) return rc; } return 0; }
gpl-2.0
djvoleur/test_test
arch/sparc/kernel/smp_64.c
767
36596
/* smp.c: Sparc64 SMP support. * * Copyright (C) 1997, 2007, 2008 David S. Miller (davem@davemloft.net) */ #include <linux/export.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/pagemap.h> #include <linux/threads.h> #include <linux/smp.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/fs.h> #include <linux/seq_file.h> #include <linux/cache.h> #include <linux/jiffies.h> #include <linux/profile.h> #include <linux/bootmem.h> #include <linux/vmalloc.h> #include <linux/ftrace.h> #include <linux/cpu.h> #include <linux/slab.h> #include <asm/head.h> #include <asm/ptrace.h> #include <linux/atomic.h> #include <asm/tlbflush.h> #include <asm/mmu_context.h> #include <asm/cpudata.h> #include <asm/hvtramp.h> #include <asm/io.h> #include <asm/timer.h> #include <asm/irq.h> #include <asm/irq_regs.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/oplib.h> #include <asm/uaccess.h> #include <asm/starfire.h> #include <asm/tlb.h> #include <asm/sections.h> #include <asm/prom.h> #include <asm/mdesc.h> #include <asm/ldc.h> #include <asm/hypervisor.h> #include <asm/pcr.h> #include "cpumap.h" int sparc64_multi_core __read_mostly; DEFINE_PER_CPU(cpumask_t, cpu_sibling_map) = CPU_MASK_NONE; cpumask_t cpu_core_map[NR_CPUS] __read_mostly = { [0 ... NR_CPUS-1] = CPU_MASK_NONE }; EXPORT_PER_CPU_SYMBOL(cpu_sibling_map); EXPORT_SYMBOL(cpu_core_map); static cpumask_t smp_commenced_mask; void smp_info(struct seq_file *m) { int i; seq_printf(m, "State:\n"); for_each_online_cpu(i) seq_printf(m, "CPU%d:\t\tonline\n", i); } void smp_bogo(struct seq_file *m) { int i; for_each_online_cpu(i) seq_printf(m, "Cpu%dClkTck\t: %016lx\n", i, cpu_data(i).clock_tick); } extern void setup_sparc64_timer(void); static volatile unsigned long callin_flag = 0; void __cpuinit smp_callin(void) { int cpuid = hard_smp_processor_id(); __local_per_cpu_offset = __per_cpu_offset(cpuid); if (tlb_type == hypervisor) sun4v_ktsb_register(); __flush_tlb_all(); setup_sparc64_timer(); if (cheetah_pcache_forced_on) cheetah_enable_pcache(); callin_flag = 1; __asm__ __volatile__("membar #Sync\n\t" "flush %%g6" : : : "memory"); /* Clear this or we will die instantly when we * schedule back to this idler... */ current_thread_info()->new_child = 0; /* Attach to the address space of init_task. */ atomic_inc(&init_mm.mm_count); current->active_mm = &init_mm; /* inform the notifiers about the new cpu */ notify_cpu_starting(cpuid); while (!cpumask_test_cpu(cpuid, &smp_commenced_mask)) rmb(); set_cpu_online(cpuid, true); local_irq_enable(); /* idle thread is expected to have preempt disabled */ preempt_disable(); cpu_startup_entry(CPUHP_ONLINE); } void cpu_panic(void) { printk("CPU[%d]: Returns from cpu_idle!\n", smp_processor_id()); panic("SMP bolixed\n"); } /* This tick register synchronization scheme is taken entirely from * the ia64 port, see arch/ia64/kernel/smpboot.c for details and credit. * * The only change I've made is to rework it so that the master * initiates the synchonization instead of the slave. -DaveM */ #define MASTER 0 #define SLAVE (SMP_CACHE_BYTES/sizeof(unsigned long)) #define NUM_ROUNDS 64 /* magic value */ #define NUM_ITERS 5 /* likewise */ static DEFINE_RAW_SPINLOCK(itc_sync_lock); static unsigned long go[SLAVE + 1]; #define DEBUG_TICK_SYNC 0 static inline long get_delta (long *rt, long *master) { unsigned long best_t0 = 0, best_t1 = ~0UL, best_tm = 0; unsigned long tcenter, t0, t1, tm; unsigned long i; for (i = 0; i < NUM_ITERS; i++) { t0 = tick_ops->get_tick(); go[MASTER] = 1; membar_safe("#StoreLoad"); while (!(tm = go[SLAVE])) rmb(); go[SLAVE] = 0; wmb(); t1 = tick_ops->get_tick(); if (t1 - t0 < best_t1 - best_t0) best_t0 = t0, best_t1 = t1, best_tm = tm; } *rt = best_t1 - best_t0; *master = best_tm - best_t0; /* average best_t0 and best_t1 without overflow: */ tcenter = (best_t0/2 + best_t1/2); if (best_t0 % 2 + best_t1 % 2 == 2) tcenter++; return tcenter - best_tm; } void smp_synchronize_tick_client(void) { long i, delta, adj, adjust_latency = 0, done = 0; unsigned long flags, rt, master_time_stamp; #if DEBUG_TICK_SYNC struct { long rt; /* roundtrip time */ long master; /* master's timestamp */ long diff; /* difference between midpoint and master's timestamp */ long lat; /* estimate of itc adjustment latency */ } t[NUM_ROUNDS]; #endif go[MASTER] = 1; while (go[MASTER]) rmb(); local_irq_save(flags); { for (i = 0; i < NUM_ROUNDS; i++) { delta = get_delta(&rt, &master_time_stamp); if (delta == 0) done = 1; /* let's lock on to this... */ if (!done) { if (i > 0) { adjust_latency += -delta; adj = -delta + adjust_latency/4; } else adj = -delta; tick_ops->add_tick(adj); } #if DEBUG_TICK_SYNC t[i].rt = rt; t[i].master = master_time_stamp; t[i].diff = delta; t[i].lat = adjust_latency/4; #endif } } local_irq_restore(flags); #if DEBUG_TICK_SYNC for (i = 0; i < NUM_ROUNDS; i++) printk("rt=%5ld master=%5ld diff=%5ld adjlat=%5ld\n", t[i].rt, t[i].master, t[i].diff, t[i].lat); #endif printk(KERN_INFO "CPU %d: synchronized TICK with master CPU " "(last diff %ld cycles, maxerr %lu cycles)\n", smp_processor_id(), delta, rt); } static void smp_start_sync_tick_client(int cpu); static void smp_synchronize_one_tick(int cpu) { unsigned long flags, i; go[MASTER] = 0; smp_start_sync_tick_client(cpu); /* wait for client to be ready */ while (!go[MASTER]) rmb(); /* now let the client proceed into his loop */ go[MASTER] = 0; membar_safe("#StoreLoad"); raw_spin_lock_irqsave(&itc_sync_lock, flags); { for (i = 0; i < NUM_ROUNDS*NUM_ITERS; i++) { while (!go[MASTER]) rmb(); go[MASTER] = 0; wmb(); go[SLAVE] = tick_ops->get_tick(); membar_safe("#StoreLoad"); } } raw_spin_unlock_irqrestore(&itc_sync_lock, flags); } #if defined(CONFIG_SUN_LDOMS) && defined(CONFIG_HOTPLUG_CPU) /* XXX Put this in some common place. XXX */ static unsigned long kimage_addr_to_ra(void *p) { unsigned long val = (unsigned long) p; return kern_base + (val - KERNBASE); } static void __cpuinit ldom_startcpu_cpuid(unsigned int cpu, unsigned long thread_reg, void **descrp) { extern unsigned long sparc64_ttable_tl0; extern unsigned long kern_locked_tte_data; struct hvtramp_descr *hdesc; unsigned long trampoline_ra; struct trap_per_cpu *tb; u64 tte_vaddr, tte_data; unsigned long hv_err; int i; hdesc = kzalloc(sizeof(*hdesc) + (sizeof(struct hvtramp_mapping) * num_kernel_image_mappings - 1), GFP_KERNEL); if (!hdesc) { printk(KERN_ERR "ldom_startcpu_cpuid: Cannot allocate " "hvtramp_descr.\n"); return; } *descrp = hdesc; hdesc->cpu = cpu; hdesc->num_mappings = num_kernel_image_mappings; tb = &trap_block[cpu]; hdesc->fault_info_va = (unsigned long) &tb->fault_info; hdesc->fault_info_pa = kimage_addr_to_ra(&tb->fault_info); hdesc->thread_reg = thread_reg; tte_vaddr = (unsigned long) KERNBASE; tte_data = kern_locked_tte_data; for (i = 0; i < hdesc->num_mappings; i++) { hdesc->maps[i].vaddr = tte_vaddr; hdesc->maps[i].tte = tte_data; tte_vaddr += 0x400000; tte_data += 0x400000; } trampoline_ra = kimage_addr_to_ra(hv_cpu_startup); hv_err = sun4v_cpu_start(cpu, trampoline_ra, kimage_addr_to_ra(&sparc64_ttable_tl0), __pa(hdesc)); if (hv_err) printk(KERN_ERR "ldom_startcpu_cpuid: sun4v_cpu_start() " "gives error %lu\n", hv_err); } #endif extern unsigned long sparc64_cpu_startup; /* The OBP cpu startup callback truncates the 3rd arg cookie to * 32-bits (I think) so to be safe we have it read the pointer * contained here so we work on >4GB machines. -DaveM */ static struct thread_info *cpu_new_thread = NULL; static int __cpuinit smp_boot_one_cpu(unsigned int cpu, struct task_struct *idle) { unsigned long entry = (unsigned long)(&sparc64_cpu_startup); unsigned long cookie = (unsigned long)(&cpu_new_thread); void *descr = NULL; int timeout, ret; callin_flag = 0; cpu_new_thread = task_thread_info(idle); if (tlb_type == hypervisor) { #if defined(CONFIG_SUN_LDOMS) && defined(CONFIG_HOTPLUG_CPU) if (ldom_domaining_enabled) ldom_startcpu_cpuid(cpu, (unsigned long) cpu_new_thread, &descr); else #endif prom_startcpu_cpuid(cpu, entry, cookie); } else { struct device_node *dp = of_find_node_by_cpuid(cpu); prom_startcpu(dp->phandle, entry, cookie); } for (timeout = 0; timeout < 50000; timeout++) { if (callin_flag) break; udelay(100); } if (callin_flag) { ret = 0; } else { printk("Processor %d is stuck.\n", cpu); ret = -ENODEV; } cpu_new_thread = NULL; kfree(descr); return ret; } static void spitfire_xcall_helper(u64 data0, u64 data1, u64 data2, u64 pstate, unsigned long cpu) { u64 result, target; int stuck, tmp; if (this_is_starfire) { /* map to real upaid */ cpu = (((cpu & 0x3c) << 1) | ((cpu & 0x40) >> 4) | (cpu & 0x3)); } target = (cpu << 14) | 0x70; again: /* Ok, this is the real Spitfire Errata #54. * One must read back from a UDB internal register * after writes to the UDB interrupt dispatch, but * before the membar Sync for that write. * So we use the high UDB control register (ASI 0x7f, * ADDR 0x20) for the dummy read. -DaveM */ tmp = 0x40; __asm__ __volatile__( "wrpr %1, %2, %%pstate\n\t" "stxa %4, [%0] %3\n\t" "stxa %5, [%0+%8] %3\n\t" "add %0, %8, %0\n\t" "stxa %6, [%0+%8] %3\n\t" "membar #Sync\n\t" "stxa %%g0, [%7] %3\n\t" "membar #Sync\n\t" "mov 0x20, %%g1\n\t" "ldxa [%%g1] 0x7f, %%g0\n\t" "membar #Sync" : "=r" (tmp) : "r" (pstate), "i" (PSTATE_IE), "i" (ASI_INTR_W), "r" (data0), "r" (data1), "r" (data2), "r" (target), "r" (0x10), "0" (tmp) : "g1"); /* NOTE: PSTATE_IE is still clear. */ stuck = 100000; do { __asm__ __volatile__("ldxa [%%g0] %1, %0" : "=r" (result) : "i" (ASI_INTR_DISPATCH_STAT)); if (result == 0) { __asm__ __volatile__("wrpr %0, 0x0, %%pstate" : : "r" (pstate)); return; } stuck -= 1; if (stuck == 0) break; } while (result & 0x1); __asm__ __volatile__("wrpr %0, 0x0, %%pstate" : : "r" (pstate)); if (stuck == 0) { printk("CPU[%d]: mondo stuckage result[%016llx]\n", smp_processor_id(), result); } else { udelay(2); goto again; } } static void spitfire_xcall_deliver(struct trap_per_cpu *tb, int cnt) { u64 *mondo, data0, data1, data2; u16 *cpu_list; u64 pstate; int i; __asm__ __volatile__("rdpr %%pstate, %0" : "=r" (pstate)); cpu_list = __va(tb->cpu_list_pa); mondo = __va(tb->cpu_mondo_block_pa); data0 = mondo[0]; data1 = mondo[1]; data2 = mondo[2]; for (i = 0; i < cnt; i++) spitfire_xcall_helper(data0, data1, data2, pstate, cpu_list[i]); } /* Cheetah now allows to send the whole 64-bytes of data in the interrupt * packet, but we have no use for that. However we do take advantage of * the new pipelining feature (ie. dispatch to multiple cpus simultaneously). */ static void cheetah_xcall_deliver(struct trap_per_cpu *tb, int cnt) { int nack_busy_id, is_jbus, need_more; u64 *mondo, pstate, ver, busy_mask; u16 *cpu_list; cpu_list = __va(tb->cpu_list_pa); mondo = __va(tb->cpu_mondo_block_pa); /* Unfortunately, someone at Sun had the brilliant idea to make the * busy/nack fields hard-coded by ITID number for this Ultra-III * derivative processor. */ __asm__ ("rdpr %%ver, %0" : "=r" (ver)); is_jbus = ((ver >> 32) == __JALAPENO_ID || (ver >> 32) == __SERRANO_ID); __asm__ __volatile__("rdpr %%pstate, %0" : "=r" (pstate)); retry: need_more = 0; __asm__ __volatile__("wrpr %0, %1, %%pstate\n\t" : : "r" (pstate), "i" (PSTATE_IE)); /* Setup the dispatch data registers. */ __asm__ __volatile__("stxa %0, [%3] %6\n\t" "stxa %1, [%4] %6\n\t" "stxa %2, [%5] %6\n\t" "membar #Sync\n\t" : /* no outputs */ : "r" (mondo[0]), "r" (mondo[1]), "r" (mondo[2]), "r" (0x40), "r" (0x50), "r" (0x60), "i" (ASI_INTR_W)); nack_busy_id = 0; busy_mask = 0; { int i; for (i = 0; i < cnt; i++) { u64 target, nr; nr = cpu_list[i]; if (nr == 0xffff) continue; target = (nr << 14) | 0x70; if (is_jbus) { busy_mask |= (0x1UL << (nr * 2)); } else { target |= (nack_busy_id << 24); busy_mask |= (0x1UL << (nack_busy_id * 2)); } __asm__ __volatile__( "stxa %%g0, [%0] %1\n\t" "membar #Sync\n\t" : /* no outputs */ : "r" (target), "i" (ASI_INTR_W)); nack_busy_id++; if (nack_busy_id == 32) { need_more = 1; break; } } } /* Now, poll for completion. */ { u64 dispatch_stat, nack_mask; long stuck; stuck = 100000 * nack_busy_id; nack_mask = busy_mask << 1; do { __asm__ __volatile__("ldxa [%%g0] %1, %0" : "=r" (dispatch_stat) : "i" (ASI_INTR_DISPATCH_STAT)); if (!(dispatch_stat & (busy_mask | nack_mask))) { __asm__ __volatile__("wrpr %0, 0x0, %%pstate" : : "r" (pstate)); if (unlikely(need_more)) { int i, this_cnt = 0; for (i = 0; i < cnt; i++) { if (cpu_list[i] == 0xffff) continue; cpu_list[i] = 0xffff; this_cnt++; if (this_cnt == 32) break; } goto retry; } return; } if (!--stuck) break; } while (dispatch_stat & busy_mask); __asm__ __volatile__("wrpr %0, 0x0, %%pstate" : : "r" (pstate)); if (dispatch_stat & busy_mask) { /* Busy bits will not clear, continue instead * of freezing up on this cpu. */ printk("CPU[%d]: mondo stuckage result[%016llx]\n", smp_processor_id(), dispatch_stat); } else { int i, this_busy_nack = 0; /* Delay some random time with interrupts enabled * to prevent deadlock. */ udelay(2 * nack_busy_id); /* Clear out the mask bits for cpus which did not * NACK us. */ for (i = 0; i < cnt; i++) { u64 check_mask, nr; nr = cpu_list[i]; if (nr == 0xffff) continue; if (is_jbus) check_mask = (0x2UL << (2*nr)); else check_mask = (0x2UL << this_busy_nack); if ((dispatch_stat & check_mask) == 0) cpu_list[i] = 0xffff; this_busy_nack += 2; if (this_busy_nack == 64) break; } goto retry; } } } /* Multi-cpu list version. */ static void hypervisor_xcall_deliver(struct trap_per_cpu *tb, int cnt) { int retries, this_cpu, prev_sent, i, saw_cpu_error; unsigned long status; u16 *cpu_list; this_cpu = smp_processor_id(); cpu_list = __va(tb->cpu_list_pa); saw_cpu_error = 0; retries = 0; prev_sent = 0; do { int forward_progress, n_sent; status = sun4v_cpu_mondo_send(cnt, tb->cpu_list_pa, tb->cpu_mondo_block_pa); /* HV_EOK means all cpus received the xcall, we're done. */ if (likely(status == HV_EOK)) break; /* First, see if we made any forward progress. * * The hypervisor indicates successful sends by setting * cpu list entries to the value 0xffff. */ n_sent = 0; for (i = 0; i < cnt; i++) { if (likely(cpu_list[i] == 0xffff)) n_sent++; } forward_progress = 0; if (n_sent > prev_sent) forward_progress = 1; prev_sent = n_sent; /* If we get a HV_ECPUERROR, then one or more of the cpus * in the list are in error state. Use the cpu_state() * hypervisor call to find out which cpus are in error state. */ if (unlikely(status == HV_ECPUERROR)) { for (i = 0; i < cnt; i++) { long err; u16 cpu; cpu = cpu_list[i]; if (cpu == 0xffff) continue; err = sun4v_cpu_state(cpu); if (err == HV_CPU_STATE_ERROR) { saw_cpu_error = (cpu + 1); cpu_list[i] = 0xffff; } } } else if (unlikely(status != HV_EWOULDBLOCK)) goto fatal_mondo_error; /* Don't bother rewriting the CPU list, just leave the * 0xffff and non-0xffff entries in there and the * hypervisor will do the right thing. * * Only advance timeout state if we didn't make any * forward progress. */ if (unlikely(!forward_progress)) { if (unlikely(++retries > 10000)) goto fatal_mondo_timeout; /* Delay a little bit to let other cpus catch up * on their cpu mondo queue work. */ udelay(2 * cnt); } } while (1); if (unlikely(saw_cpu_error)) goto fatal_mondo_cpu_error; return; fatal_mondo_cpu_error: printk(KERN_CRIT "CPU[%d]: SUN4V mondo cpu error, some target cpus " "(including %d) were in error state\n", this_cpu, saw_cpu_error - 1); return; fatal_mondo_timeout: printk(KERN_CRIT "CPU[%d]: SUN4V mondo timeout, no forward " " progress after %d retries.\n", this_cpu, retries); goto dump_cpu_list_and_out; fatal_mondo_error: printk(KERN_CRIT "CPU[%d]: Unexpected SUN4V mondo error %lu\n", this_cpu, status); printk(KERN_CRIT "CPU[%d]: Args were cnt(%d) cpulist_pa(%lx) " "mondo_block_pa(%lx)\n", this_cpu, cnt, tb->cpu_list_pa, tb->cpu_mondo_block_pa); dump_cpu_list_and_out: printk(KERN_CRIT "CPU[%d]: CPU list [ ", this_cpu); for (i = 0; i < cnt; i++) printk("%u ", cpu_list[i]); printk("]\n"); } static void (*xcall_deliver_impl)(struct trap_per_cpu *, int); static void xcall_deliver(u64 data0, u64 data1, u64 data2, const cpumask_t *mask) { struct trap_per_cpu *tb; int this_cpu, i, cnt; unsigned long flags; u16 *cpu_list; u64 *mondo; /* We have to do this whole thing with interrupts fully disabled. * Otherwise if we send an xcall from interrupt context it will * corrupt both our mondo block and cpu list state. * * One consequence of this is that we cannot use timeout mechanisms * that depend upon interrupts being delivered locally. So, for * example, we cannot sample jiffies and expect it to advance. * * Fortunately, udelay() uses %stick/%tick so we can use that. */ local_irq_save(flags); this_cpu = smp_processor_id(); tb = &trap_block[this_cpu]; mondo = __va(tb->cpu_mondo_block_pa); mondo[0] = data0; mondo[1] = data1; mondo[2] = data2; wmb(); cpu_list = __va(tb->cpu_list_pa); /* Setup the initial cpu list. */ cnt = 0; for_each_cpu(i, mask) { if (i == this_cpu || !cpu_online(i)) continue; cpu_list[cnt++] = i; } if (cnt) xcall_deliver_impl(tb, cnt); local_irq_restore(flags); } /* Send cross call to all processors mentioned in MASK_P * except self. Really, there are only two cases currently, * "cpu_online_mask" and "mm_cpumask(mm)". */ static void smp_cross_call_masked(unsigned long *func, u32 ctx, u64 data1, u64 data2, const cpumask_t *mask) { u64 data0 = (((u64)ctx)<<32 | (((u64)func) & 0xffffffff)); xcall_deliver(data0, data1, data2, mask); } /* Send cross call to all processors except self. */ static void smp_cross_call(unsigned long *func, u32 ctx, u64 data1, u64 data2) { smp_cross_call_masked(func, ctx, data1, data2, cpu_online_mask); } extern unsigned long xcall_sync_tick; static void smp_start_sync_tick_client(int cpu) { xcall_deliver((u64) &xcall_sync_tick, 0, 0, cpumask_of(cpu)); } extern unsigned long xcall_call_function; void arch_send_call_function_ipi_mask(const struct cpumask *mask) { xcall_deliver((u64) &xcall_call_function, 0, 0, mask); } extern unsigned long xcall_call_function_single; void arch_send_call_function_single_ipi(int cpu) { xcall_deliver((u64) &xcall_call_function_single, 0, 0, cpumask_of(cpu)); } void __irq_entry smp_call_function_client(int irq, struct pt_regs *regs) { clear_softint(1 << irq); irq_enter(); generic_smp_call_function_interrupt(); irq_exit(); } void __irq_entry smp_call_function_single_client(int irq, struct pt_regs *regs) { clear_softint(1 << irq); irq_enter(); generic_smp_call_function_single_interrupt(); irq_exit(); } static void tsb_sync(void *info) { struct trap_per_cpu *tp = &trap_block[raw_smp_processor_id()]; struct mm_struct *mm = info; /* It is not valid to test "current->active_mm == mm" here. * * The value of "current" is not changed atomically with * switch_mm(). But that's OK, we just need to check the * current cpu's trap block PGD physical address. */ if (tp->pgd_paddr == __pa(mm->pgd)) tsb_context_switch(mm); } void smp_tsb_sync(struct mm_struct *mm) { smp_call_function_many(mm_cpumask(mm), tsb_sync, mm, 1); } extern unsigned long xcall_flush_tlb_mm; extern unsigned long xcall_flush_tlb_page; extern unsigned long xcall_flush_tlb_kernel_range; extern unsigned long xcall_fetch_glob_regs; extern unsigned long xcall_fetch_glob_pmu; extern unsigned long xcall_fetch_glob_pmu_n4; extern unsigned long xcall_receive_signal; extern unsigned long xcall_new_mmu_context_version; #ifdef CONFIG_KGDB extern unsigned long xcall_kgdb_capture; #endif #ifdef DCACHE_ALIASING_POSSIBLE extern unsigned long xcall_flush_dcache_page_cheetah; #endif extern unsigned long xcall_flush_dcache_page_spitfire; #ifdef CONFIG_DEBUG_DCFLUSH extern atomic_t dcpage_flushes; extern atomic_t dcpage_flushes_xcall; #endif static inline void __local_flush_dcache_page(struct page *page) { #ifdef DCACHE_ALIASING_POSSIBLE __flush_dcache_page(page_address(page), ((tlb_type == spitfire) && page_mapping(page) != NULL)); #else if (page_mapping(page) != NULL && tlb_type == spitfire) __flush_icache_page(__pa(page_address(page))); #endif } void smp_flush_dcache_page_impl(struct page *page, int cpu) { int this_cpu; if (tlb_type == hypervisor) return; #ifdef CONFIG_DEBUG_DCFLUSH atomic_inc(&dcpage_flushes); #endif this_cpu = get_cpu(); if (cpu == this_cpu) { __local_flush_dcache_page(page); } else if (cpu_online(cpu)) { void *pg_addr = page_address(page); u64 data0 = 0; if (tlb_type == spitfire) { data0 = ((u64)&xcall_flush_dcache_page_spitfire); if (page_mapping(page) != NULL) data0 |= ((u64)1 << 32); } else if (tlb_type == cheetah || tlb_type == cheetah_plus) { #ifdef DCACHE_ALIASING_POSSIBLE data0 = ((u64)&xcall_flush_dcache_page_cheetah); #endif } if (data0) { xcall_deliver(data0, __pa(pg_addr), (u64) pg_addr, cpumask_of(cpu)); #ifdef CONFIG_DEBUG_DCFLUSH atomic_inc(&dcpage_flushes_xcall); #endif } } put_cpu(); } void flush_dcache_page_all(struct mm_struct *mm, struct page *page) { void *pg_addr; u64 data0; if (tlb_type == hypervisor) return; preempt_disable(); #ifdef CONFIG_DEBUG_DCFLUSH atomic_inc(&dcpage_flushes); #endif data0 = 0; pg_addr = page_address(page); if (tlb_type == spitfire) { data0 = ((u64)&xcall_flush_dcache_page_spitfire); if (page_mapping(page) != NULL) data0 |= ((u64)1 << 32); } else if (tlb_type == cheetah || tlb_type == cheetah_plus) { #ifdef DCACHE_ALIASING_POSSIBLE data0 = ((u64)&xcall_flush_dcache_page_cheetah); #endif } if (data0) { xcall_deliver(data0, __pa(pg_addr), (u64) pg_addr, cpu_online_mask); #ifdef CONFIG_DEBUG_DCFLUSH atomic_inc(&dcpage_flushes_xcall); #endif } __local_flush_dcache_page(page); preempt_enable(); } void __irq_entry smp_new_mmu_context_version_client(int irq, struct pt_regs *regs) { struct mm_struct *mm; unsigned long flags; clear_softint(1 << irq); /* See if we need to allocate a new TLB context because * the version of the one we are using is now out of date. */ mm = current->active_mm; if (unlikely(!mm || (mm == &init_mm))) return; spin_lock_irqsave(&mm->context.lock, flags); if (unlikely(!CTX_VALID(mm->context))) get_new_mmu_context(mm); spin_unlock_irqrestore(&mm->context.lock, flags); load_secondary_context(mm); __flush_tlb_mm(CTX_HWBITS(mm->context), SECONDARY_CONTEXT); } void smp_new_mmu_context_version(void) { smp_cross_call(&xcall_new_mmu_context_version, 0, 0, 0); } #ifdef CONFIG_KGDB void kgdb_roundup_cpus(unsigned long flags) { smp_cross_call(&xcall_kgdb_capture, 0, 0, 0); } #endif void smp_fetch_global_regs(void) { smp_cross_call(&xcall_fetch_glob_regs, 0, 0, 0); } void smp_fetch_global_pmu(void) { if (tlb_type == hypervisor && sun4v_chip_type >= SUN4V_CHIP_NIAGARA4) smp_cross_call(&xcall_fetch_glob_pmu_n4, 0, 0, 0); else smp_cross_call(&xcall_fetch_glob_pmu, 0, 0, 0); } /* We know that the window frames of the user have been flushed * to the stack before we get here because all callers of us * are flush_tlb_*() routines, and these run after flush_cache_*() * which performs the flushw. * * The SMP TLB coherency scheme we use works as follows: * * 1) mm->cpu_vm_mask is a bit mask of which cpus an address * space has (potentially) executed on, this is the heuristic * we use to avoid doing cross calls. * * Also, for flushing from kswapd and also for clones, we * use cpu_vm_mask as the list of cpus to make run the TLB. * * 2) TLB context numbers are shared globally across all processors * in the system, this allows us to play several games to avoid * cross calls. * * One invariant is that when a cpu switches to a process, and * that processes tsk->active_mm->cpu_vm_mask does not have the * current cpu's bit set, that tlb context is flushed locally. * * If the address space is non-shared (ie. mm->count == 1) we avoid * cross calls when we want to flush the currently running process's * tlb state. This is done by clearing all cpu bits except the current * processor's in current->mm->cpu_vm_mask and performing the * flush locally only. This will force any subsequent cpus which run * this task to flush the context from the local tlb if the process * migrates to another cpu (again). * * 3) For shared address spaces (threads) and swapping we bite the * bullet for most cases and perform the cross call (but only to * the cpus listed in cpu_vm_mask). * * The performance gain from "optimizing" away the cross call for threads is * questionable (in theory the big win for threads is the massive sharing of * address space state across processors). */ /* This currently is only used by the hugetlb arch pre-fault * hook on UltraSPARC-III+ and later when changing the pagesize * bits of the context register for an address space. */ void smp_flush_tlb_mm(struct mm_struct *mm) { u32 ctx = CTX_HWBITS(mm->context); int cpu = get_cpu(); if (atomic_read(&mm->mm_users) == 1) { cpumask_copy(mm_cpumask(mm), cpumask_of(cpu)); goto local_flush_and_out; } smp_cross_call_masked(&xcall_flush_tlb_mm, ctx, 0, 0, mm_cpumask(mm)); local_flush_and_out: __flush_tlb_mm(ctx, SECONDARY_CONTEXT); put_cpu(); } struct tlb_pending_info { unsigned long ctx; unsigned long nr; unsigned long *vaddrs; }; static void tlb_pending_func(void *info) { struct tlb_pending_info *t = info; __flush_tlb_pending(t->ctx, t->nr, t->vaddrs); } void smp_flush_tlb_pending(struct mm_struct *mm, unsigned long nr, unsigned long *vaddrs) { u32 ctx = CTX_HWBITS(mm->context); struct tlb_pending_info info; int cpu = get_cpu(); info.ctx = ctx; info.nr = nr; info.vaddrs = vaddrs; if (mm == current->mm && atomic_read(&mm->mm_users) == 1) cpumask_copy(mm_cpumask(mm), cpumask_of(cpu)); else smp_call_function_many(mm_cpumask(mm), tlb_pending_func, &info, 1); __flush_tlb_pending(ctx, nr, vaddrs); put_cpu(); } void smp_flush_tlb_page(struct mm_struct *mm, unsigned long vaddr) { unsigned long context = CTX_HWBITS(mm->context); int cpu = get_cpu(); if (mm == current->mm && atomic_read(&mm->mm_users) == 1) cpumask_copy(mm_cpumask(mm), cpumask_of(cpu)); else smp_cross_call_masked(&xcall_flush_tlb_page, context, vaddr, 0, mm_cpumask(mm)); __flush_tlb_page(context, vaddr); put_cpu(); } void smp_flush_tlb_kernel_range(unsigned long start, unsigned long end) { start &= PAGE_MASK; end = PAGE_ALIGN(end); if (start != end) { smp_cross_call(&xcall_flush_tlb_kernel_range, 0, start, end); __flush_tlb_kernel_range(start, end); } } /* CPU capture. */ /* #define CAPTURE_DEBUG */ extern unsigned long xcall_capture; static atomic_t smp_capture_depth = ATOMIC_INIT(0); static atomic_t smp_capture_registry = ATOMIC_INIT(0); static unsigned long penguins_are_doing_time; void smp_capture(void) { int result = atomic_add_ret(1, &smp_capture_depth); if (result == 1) { int ncpus = num_online_cpus(); #ifdef CAPTURE_DEBUG printk("CPU[%d]: Sending penguins to jail...", smp_processor_id()); #endif penguins_are_doing_time = 1; atomic_inc(&smp_capture_registry); smp_cross_call(&xcall_capture, 0, 0, 0); while (atomic_read(&smp_capture_registry) != ncpus) rmb(); #ifdef CAPTURE_DEBUG printk("done\n"); #endif } } void smp_release(void) { if (atomic_dec_and_test(&smp_capture_depth)) { #ifdef CAPTURE_DEBUG printk("CPU[%d]: Giving pardon to " "imprisoned penguins\n", smp_processor_id()); #endif penguins_are_doing_time = 0; membar_safe("#StoreLoad"); atomic_dec(&smp_capture_registry); } } /* Imprisoned penguins run with %pil == PIL_NORMAL_MAX, but PSTATE_IE * set, so they can service tlb flush xcalls... */ extern void prom_world(int); void __irq_entry smp_penguin_jailcell(int irq, struct pt_regs *regs) { clear_softint(1 << irq); preempt_disable(); __asm__ __volatile__("flushw"); prom_world(1); atomic_inc(&smp_capture_registry); membar_safe("#StoreLoad"); while (penguins_are_doing_time) rmb(); atomic_dec(&smp_capture_registry); prom_world(0); preempt_enable(); } /* /proc/profile writes can call this, don't __init it please. */ int setup_profiling_timer(unsigned int multiplier) { return -EINVAL; } void __init smp_prepare_cpus(unsigned int max_cpus) { } void smp_prepare_boot_cpu(void) { } void __init smp_setup_processor_id(void) { if (tlb_type == spitfire) xcall_deliver_impl = spitfire_xcall_deliver; else if (tlb_type == cheetah || tlb_type == cheetah_plus) xcall_deliver_impl = cheetah_xcall_deliver; else xcall_deliver_impl = hypervisor_xcall_deliver; } void smp_fill_in_sib_core_maps(void) { unsigned int i; for_each_present_cpu(i) { unsigned int j; cpumask_clear(&cpu_core_map[i]); if (cpu_data(i).core_id == 0) { cpumask_set_cpu(i, &cpu_core_map[i]); continue; } for_each_present_cpu(j) { if (cpu_data(i).core_id == cpu_data(j).core_id) cpumask_set_cpu(j, &cpu_core_map[i]); } } for_each_present_cpu(i) { unsigned int j; cpumask_clear(&per_cpu(cpu_sibling_map, i)); if (cpu_data(i).proc_id == -1) { cpumask_set_cpu(i, &per_cpu(cpu_sibling_map, i)); continue; } for_each_present_cpu(j) { if (cpu_data(i).proc_id == cpu_data(j).proc_id) cpumask_set_cpu(j, &per_cpu(cpu_sibling_map, i)); } } } int __cpuinit __cpu_up(unsigned int cpu, struct task_struct *tidle) { int ret = smp_boot_one_cpu(cpu, tidle); if (!ret) { cpumask_set_cpu(cpu, &smp_commenced_mask); while (!cpu_online(cpu)) mb(); if (!cpu_online(cpu)) { ret = -ENODEV; } else { /* On SUN4V, writes to %tick and %stick are * not allowed. */ if (tlb_type != hypervisor) smp_synchronize_one_tick(cpu); } } return ret; } #ifdef CONFIG_HOTPLUG_CPU void cpu_play_dead(void) { int cpu = smp_processor_id(); unsigned long pstate; idle_task_exit(); if (tlb_type == hypervisor) { struct trap_per_cpu *tb = &trap_block[cpu]; sun4v_cpu_qconf(HV_CPU_QUEUE_CPU_MONDO, tb->cpu_mondo_pa, 0); sun4v_cpu_qconf(HV_CPU_QUEUE_DEVICE_MONDO, tb->dev_mondo_pa, 0); sun4v_cpu_qconf(HV_CPU_QUEUE_RES_ERROR, tb->resum_mondo_pa, 0); sun4v_cpu_qconf(HV_CPU_QUEUE_NONRES_ERROR, tb->nonresum_mondo_pa, 0); } cpumask_clear_cpu(cpu, &smp_commenced_mask); membar_safe("#Sync"); local_irq_disable(); __asm__ __volatile__( "rdpr %%pstate, %0\n\t" "wrpr %0, %1, %%pstate" : "=r" (pstate) : "i" (PSTATE_IE)); while (1) barrier(); } int __cpu_disable(void) { int cpu = smp_processor_id(); cpuinfo_sparc *c; int i; for_each_cpu(i, &cpu_core_map[cpu]) cpumask_clear_cpu(cpu, &cpu_core_map[i]); cpumask_clear(&cpu_core_map[cpu]); for_each_cpu(i, &per_cpu(cpu_sibling_map, cpu)) cpumask_clear_cpu(cpu, &per_cpu(cpu_sibling_map, i)); cpumask_clear(&per_cpu(cpu_sibling_map, cpu)); c = &cpu_data(cpu); c->core_id = 0; c->proc_id = -1; smp_wmb(); /* Make sure no interrupts point to this cpu. */ fixup_irqs(); local_irq_enable(); mdelay(1); local_irq_disable(); set_cpu_online(cpu, false); cpu_map_rebuild(); return 0; } void __cpu_die(unsigned int cpu) { int i; for (i = 0; i < 100; i++) { smp_rmb(); if (!cpumask_test_cpu(cpu, &smp_commenced_mask)) break; msleep(100); } if (cpumask_test_cpu(cpu, &smp_commenced_mask)) { printk(KERN_ERR "CPU %u didn't die...\n", cpu); } else { #if defined(CONFIG_SUN_LDOMS) unsigned long hv_err; int limit = 100; do { hv_err = sun4v_cpu_stop(cpu); if (hv_err == HV_EOK) { set_cpu_present(cpu, false); break; } } while (--limit > 0); if (limit <= 0) { printk(KERN_ERR "sun4v_cpu_stop() fails err=%lu\n", hv_err); } #endif } } #endif void __init smp_cpus_done(unsigned int max_cpus) { pcr_arch_init(); } void smp_send_reschedule(int cpu) { xcall_deliver((u64) &xcall_receive_signal, 0, 0, cpumask_of(cpu)); } void __irq_entry smp_receive_signal_client(int irq, struct pt_regs *regs) { clear_softint(1 << irq); scheduler_ipi(); } /* This is a nop because we capture all other cpus * anyways when making the PROM active. */ void smp_send_stop(void) { } /** * pcpu_alloc_bootmem - NUMA friendly alloc_bootmem wrapper for percpu * @cpu: cpu to allocate for * @size: size allocation in bytes * @align: alignment * * Allocate @size bytes aligned at @align for cpu @cpu. This wrapper * does the right thing for NUMA regardless of the current * configuration. * * RETURNS: * Pointer to the allocated area on success, NULL on failure. */ static void * __init pcpu_alloc_bootmem(unsigned int cpu, size_t size, size_t align) { const unsigned long goal = __pa(MAX_DMA_ADDRESS); #ifdef CONFIG_NEED_MULTIPLE_NODES int node = cpu_to_node(cpu); void *ptr; if (!node_online(node) || !NODE_DATA(node)) { ptr = __alloc_bootmem(size, align, goal); pr_info("cpu %d has no node %d or node-local memory\n", cpu, node); pr_debug("per cpu data for cpu%d %lu bytes at %016lx\n", cpu, size, __pa(ptr)); } else { ptr = __alloc_bootmem_node(NODE_DATA(node), size, align, goal); pr_debug("per cpu data for cpu%d %lu bytes on node%d at " "%016lx\n", cpu, size, node, __pa(ptr)); } return ptr; #else return __alloc_bootmem(size, align, goal); #endif } static void __init pcpu_free_bootmem(void *ptr, size_t size) { free_bootmem(__pa(ptr), size); } static int __init pcpu_cpu_distance(unsigned int from, unsigned int to) { if (cpu_to_node(from) == cpu_to_node(to)) return LOCAL_DISTANCE; else return REMOTE_DISTANCE; } static void __init pcpu_populate_pte(unsigned long addr) { pgd_t *pgd = pgd_offset_k(addr); pud_t *pud; pmd_t *pmd; pud = pud_offset(pgd, addr); if (pud_none(*pud)) { pmd_t *new; new = __alloc_bootmem(PAGE_SIZE, PAGE_SIZE, PAGE_SIZE); pud_populate(&init_mm, pud, new); } pmd = pmd_offset(pud, addr); if (!pmd_present(*pmd)) { pte_t *new; new = __alloc_bootmem(PAGE_SIZE, PAGE_SIZE, PAGE_SIZE); pmd_populate_kernel(&init_mm, pmd, new); } } void __init setup_per_cpu_areas(void) { unsigned long delta; unsigned int cpu; int rc = -EINVAL; if (pcpu_chosen_fc != PCPU_FC_PAGE) { rc = pcpu_embed_first_chunk(PERCPU_MODULE_RESERVE, PERCPU_DYNAMIC_RESERVE, 4 << 20, pcpu_cpu_distance, pcpu_alloc_bootmem, pcpu_free_bootmem); if (rc) pr_warning("PERCPU: %s allocator failed (%d), " "falling back to page size\n", pcpu_fc_names[pcpu_chosen_fc], rc); } if (rc < 0) rc = pcpu_page_first_chunk(PERCPU_MODULE_RESERVE, pcpu_alloc_bootmem, pcpu_free_bootmem, pcpu_populate_pte); if (rc < 0) panic("cannot initialize percpu area (err=%d)", rc); delta = (unsigned long)pcpu_base_addr - (unsigned long)__per_cpu_start; for_each_possible_cpu(cpu) __per_cpu_offset(cpu) = delta + pcpu_unit_offsets[cpu]; /* Setup %g5 for the boot cpu. */ __local_per_cpu_offset = __per_cpu_offset(smp_processor_id()); of_fill_in_cpu_data(); if (tlb_type == hypervisor) mdesc_fill_in_cpu_data(cpu_all_mask); }
gpl-2.0
kgilmer/bl-linux-omap
net/bridge/netfilter/ebt_mark.c
767
1927
/* * ebt_mark * * Authors: * Bart De Schuymer <bdschuym@pandora.be> * * July, 2002 * */ /* The mark target can be used in any chain, * I believe adding a mangle table just for marking is total overkill. * Marking a frame doesn't really change anything in the frame anyway. */ #include <linux/module.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_bridge/ebtables.h> #include <linux/netfilter_bridge/ebt_mark_t.h> static unsigned int ebt_mark_tg(struct sk_buff *skb, const struct xt_target_param *par) { const struct ebt_mark_t_info *info = par->targinfo; int action = info->target & -16; if (action == MARK_SET_VALUE) skb->mark = info->mark; else if (action == MARK_OR_VALUE) skb->mark |= info->mark; else if (action == MARK_AND_VALUE) skb->mark &= info->mark; else skb->mark ^= info->mark; return info->target | ~EBT_VERDICT_BITS; } static bool ebt_mark_tg_check(const struct xt_tgchk_param *par) { const struct ebt_mark_t_info *info = par->targinfo; int tmp; tmp = info->target | ~EBT_VERDICT_BITS; if (BASE_CHAIN && tmp == EBT_RETURN) return false; if (tmp < -NUM_STANDARD_TARGETS || tmp >= 0) return false; tmp = info->target & ~EBT_VERDICT_BITS; if (tmp != MARK_SET_VALUE && tmp != MARK_OR_VALUE && tmp != MARK_AND_VALUE && tmp != MARK_XOR_VALUE) return false; return true; } static struct xt_target ebt_mark_tg_reg __read_mostly = { .name = "mark", .revision = 0, .family = NFPROTO_BRIDGE, .target = ebt_mark_tg, .checkentry = ebt_mark_tg_check, .targetsize = XT_ALIGN(sizeof(struct ebt_mark_t_info)), .me = THIS_MODULE, }; static int __init ebt_mark_init(void) { return xt_register_target(&ebt_mark_tg_reg); } static void __exit ebt_mark_fini(void) { xt_unregister_target(&ebt_mark_tg_reg); } module_init(ebt_mark_init); module_exit(ebt_mark_fini); MODULE_DESCRIPTION("Ebtables: Packet mark modification"); MODULE_LICENSE("GPL");
gpl-2.0
01org/XenGT-Preview-kernel
drivers/acpi/button.c
1023
12274
/* * button.c - ACPI Button Driver * * Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com> * Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.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., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/input.h> #include <linux/slab.h> #include <linux/acpi.h> #include <acpi/button.h> #define PREFIX "ACPI: " #define ACPI_BUTTON_CLASS "button" #define ACPI_BUTTON_FILE_INFO "info" #define ACPI_BUTTON_FILE_STATE "state" #define ACPI_BUTTON_TYPE_UNKNOWN 0x00 #define ACPI_BUTTON_NOTIFY_STATUS 0x80 #define ACPI_BUTTON_SUBCLASS_POWER "power" #define ACPI_BUTTON_HID_POWER "PNP0C0C" #define ACPI_BUTTON_DEVICE_NAME_POWER "Power Button" #define ACPI_BUTTON_TYPE_POWER 0x01 #define ACPI_BUTTON_SUBCLASS_SLEEP "sleep" #define ACPI_BUTTON_HID_SLEEP "PNP0C0E" #define ACPI_BUTTON_DEVICE_NAME_SLEEP "Sleep Button" #define ACPI_BUTTON_TYPE_SLEEP 0x03 #define ACPI_BUTTON_SUBCLASS_LID "lid" #define ACPI_BUTTON_HID_LID "PNP0C0D" #define ACPI_BUTTON_DEVICE_NAME_LID "Lid Switch" #define ACPI_BUTTON_TYPE_LID 0x05 #define _COMPONENT ACPI_BUTTON_COMPONENT ACPI_MODULE_NAME("button"); MODULE_AUTHOR("Paul Diefenbaugh"); MODULE_DESCRIPTION("ACPI Button Driver"); MODULE_LICENSE("GPL"); static const struct acpi_device_id button_device_ids[] = { {ACPI_BUTTON_HID_LID, 0}, {ACPI_BUTTON_HID_SLEEP, 0}, {ACPI_BUTTON_HID_SLEEPF, 0}, {ACPI_BUTTON_HID_POWER, 0}, {ACPI_BUTTON_HID_POWERF, 0}, {"", 0}, }; MODULE_DEVICE_TABLE(acpi, button_device_ids); static int acpi_button_add(struct acpi_device *device); static int acpi_button_remove(struct acpi_device *device); static void acpi_button_notify(struct acpi_device *device, u32 event); #ifdef CONFIG_PM_SLEEP static int acpi_button_suspend(struct device *dev); static int acpi_button_resume(struct device *dev); #else #define acpi_button_suspend NULL #define acpi_button_resume NULL #endif static SIMPLE_DEV_PM_OPS(acpi_button_pm, acpi_button_suspend, acpi_button_resume); static struct acpi_driver acpi_button_driver = { .name = "button", .class = ACPI_BUTTON_CLASS, .ids = button_device_ids, .ops = { .add = acpi_button_add, .remove = acpi_button_remove, .notify = acpi_button_notify, }, .drv.pm = &acpi_button_pm, }; struct acpi_button { unsigned int type; struct input_dev *input; char phys[32]; /* for input device */ unsigned long pushed; bool suspended; }; static BLOCKING_NOTIFIER_HEAD(acpi_lid_notifier); static struct acpi_device *lid_device; /* -------------------------------------------------------------------------- FS Interface (/proc) -------------------------------------------------------------------------- */ static struct proc_dir_entry *acpi_button_dir; static struct proc_dir_entry *acpi_lid_dir; static int acpi_button_state_seq_show(struct seq_file *seq, void *offset) { struct acpi_device *device = seq->private; acpi_status status; unsigned long long state; status = acpi_evaluate_integer(device->handle, "_LID", NULL, &state); seq_printf(seq, "state: %s\n", ACPI_FAILURE(status) ? "unsupported" : (state ? "open" : "closed")); return 0; } static int acpi_button_state_open_fs(struct inode *inode, struct file *file) { return single_open(file, acpi_button_state_seq_show, PDE_DATA(inode)); } static const struct file_operations acpi_button_state_fops = { .owner = THIS_MODULE, .open = acpi_button_state_open_fs, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int acpi_button_add_fs(struct acpi_device *device) { struct acpi_button *button = acpi_driver_data(device); struct proc_dir_entry *entry = NULL; int ret = 0; /* procfs I/F for ACPI lid device only */ if (button->type != ACPI_BUTTON_TYPE_LID) return 0; if (acpi_button_dir || acpi_lid_dir) { printk(KERN_ERR PREFIX "More than one Lid device found!\n"); return -EEXIST; } /* create /proc/acpi/button */ acpi_button_dir = proc_mkdir(ACPI_BUTTON_CLASS, acpi_root_dir); if (!acpi_button_dir) return -ENODEV; /* create /proc/acpi/button/lid */ acpi_lid_dir = proc_mkdir(ACPI_BUTTON_SUBCLASS_LID, acpi_button_dir); if (!acpi_lid_dir) { ret = -ENODEV; goto remove_button_dir; } /* create /proc/acpi/button/lid/LID/ */ acpi_device_dir(device) = proc_mkdir(acpi_device_bid(device), acpi_lid_dir); if (!acpi_device_dir(device)) { ret = -ENODEV; goto remove_lid_dir; } /* create /proc/acpi/button/lid/LID/state */ entry = proc_create_data(ACPI_BUTTON_FILE_STATE, S_IRUGO, acpi_device_dir(device), &acpi_button_state_fops, device); if (!entry) { ret = -ENODEV; goto remove_dev_dir; } done: return ret; remove_dev_dir: remove_proc_entry(acpi_device_bid(device), acpi_lid_dir); acpi_device_dir(device) = NULL; remove_lid_dir: remove_proc_entry(ACPI_BUTTON_SUBCLASS_LID, acpi_button_dir); remove_button_dir: remove_proc_entry(ACPI_BUTTON_CLASS, acpi_root_dir); goto done; } static int acpi_button_remove_fs(struct acpi_device *device) { struct acpi_button *button = acpi_driver_data(device); if (button->type != ACPI_BUTTON_TYPE_LID) return 0; remove_proc_entry(ACPI_BUTTON_FILE_STATE, acpi_device_dir(device)); remove_proc_entry(acpi_device_bid(device), acpi_lid_dir); acpi_device_dir(device) = NULL; remove_proc_entry(ACPI_BUTTON_SUBCLASS_LID, acpi_button_dir); remove_proc_entry(ACPI_BUTTON_CLASS, acpi_root_dir); return 0; } /* -------------------------------------------------------------------------- Driver Interface -------------------------------------------------------------------------- */ int acpi_lid_notifier_register(struct notifier_block *nb) { return blocking_notifier_chain_register(&acpi_lid_notifier, nb); } EXPORT_SYMBOL(acpi_lid_notifier_register); int acpi_lid_notifier_unregister(struct notifier_block *nb) { return blocking_notifier_chain_unregister(&acpi_lid_notifier, nb); } EXPORT_SYMBOL(acpi_lid_notifier_unregister); int acpi_lid_open(void) { acpi_status status; unsigned long long state; if (!lid_device) return -ENODEV; status = acpi_evaluate_integer(lid_device->handle, "_LID", NULL, &state); if (ACPI_FAILURE(status)) return -ENODEV; return !!state; } EXPORT_SYMBOL(acpi_lid_open); static int acpi_lid_send_state(struct acpi_device *device) { struct acpi_button *button = acpi_driver_data(device); unsigned long long state; acpi_status status; int ret; status = acpi_evaluate_integer(device->handle, "_LID", NULL, &state); if (ACPI_FAILURE(status)) return -ENODEV; /* input layer checks if event is redundant */ input_report_switch(button->input, SW_LID, !state); input_sync(button->input); if (state) pm_wakeup_event(&device->dev, 0); ret = blocking_notifier_call_chain(&acpi_lid_notifier, state, device); if (ret == NOTIFY_DONE) ret = blocking_notifier_call_chain(&acpi_lid_notifier, state, device); if (ret == NOTIFY_DONE || ret == NOTIFY_OK) { /* * It is also regarded as success if the notifier_chain * returns NOTIFY_OK or NOTIFY_DONE. */ ret = 0; } return ret; } static void acpi_button_notify(struct acpi_device *device, u32 event) { struct acpi_button *button = acpi_driver_data(device); struct input_dev *input; switch (event) { case ACPI_FIXED_HARDWARE_EVENT: event = ACPI_BUTTON_NOTIFY_STATUS; /* fall through */ case ACPI_BUTTON_NOTIFY_STATUS: input = button->input; if (button->type == ACPI_BUTTON_TYPE_LID) { acpi_lid_send_state(device); } else { int keycode; pm_wakeup_event(&device->dev, 0); if (button->suspended) break; keycode = test_bit(KEY_SLEEP, input->keybit) ? KEY_SLEEP : KEY_POWER; input_report_key(input, keycode, 1); input_sync(input); input_report_key(input, keycode, 0); input_sync(input); acpi_bus_generate_netlink_event( device->pnp.device_class, dev_name(&device->dev), event, ++button->pushed); } break; default: ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Unsupported event [0x%x]\n", event)); break; } } #ifdef CONFIG_PM_SLEEP static int acpi_button_suspend(struct device *dev) { struct acpi_device *device = to_acpi_device(dev); struct acpi_button *button = acpi_driver_data(device); button->suspended = true; return 0; } static int acpi_button_resume(struct device *dev) { struct acpi_device *device = to_acpi_device(dev); struct acpi_button *button = acpi_driver_data(device); button->suspended = false; if (button->type == ACPI_BUTTON_TYPE_LID) return acpi_lid_send_state(device); return 0; } #endif static int acpi_button_add(struct acpi_device *device) { struct acpi_button *button; struct input_dev *input; const char *hid = acpi_device_hid(device); char *name, *class; int error; button = kzalloc(sizeof(struct acpi_button), GFP_KERNEL); if (!button) return -ENOMEM; device->driver_data = button; button->input = input = input_allocate_device(); if (!input) { error = -ENOMEM; goto err_free_button; } name = acpi_device_name(device); class = acpi_device_class(device); if (!strcmp(hid, ACPI_BUTTON_HID_POWER) || !strcmp(hid, ACPI_BUTTON_HID_POWERF)) { button->type = ACPI_BUTTON_TYPE_POWER; strcpy(name, ACPI_BUTTON_DEVICE_NAME_POWER); sprintf(class, "%s/%s", ACPI_BUTTON_CLASS, ACPI_BUTTON_SUBCLASS_POWER); } else if (!strcmp(hid, ACPI_BUTTON_HID_SLEEP) || !strcmp(hid, ACPI_BUTTON_HID_SLEEPF)) { button->type = ACPI_BUTTON_TYPE_SLEEP; strcpy(name, ACPI_BUTTON_DEVICE_NAME_SLEEP); sprintf(class, "%s/%s", ACPI_BUTTON_CLASS, ACPI_BUTTON_SUBCLASS_SLEEP); } else if (!strcmp(hid, ACPI_BUTTON_HID_LID)) { button->type = ACPI_BUTTON_TYPE_LID; strcpy(name, ACPI_BUTTON_DEVICE_NAME_LID); sprintf(class, "%s/%s", ACPI_BUTTON_CLASS, ACPI_BUTTON_SUBCLASS_LID); } else { printk(KERN_ERR PREFIX "Unsupported hid [%s]\n", hid); error = -ENODEV; goto err_free_input; } error = acpi_button_add_fs(device); if (error) goto err_free_input; snprintf(button->phys, sizeof(button->phys), "%s/button/input0", hid); input->name = name; input->phys = button->phys; input->id.bustype = BUS_HOST; input->id.product = button->type; input->dev.parent = &device->dev; switch (button->type) { case ACPI_BUTTON_TYPE_POWER: input_set_capability(input, EV_KEY, KEY_POWER); break; case ACPI_BUTTON_TYPE_SLEEP: input_set_capability(input, EV_KEY, KEY_SLEEP); break; case ACPI_BUTTON_TYPE_LID: input_set_capability(input, EV_SW, SW_LID); break; } error = input_register_device(input); if (error) goto err_remove_fs; if (button->type == ACPI_BUTTON_TYPE_LID) { acpi_lid_send_state(device); /* * This assumes there's only one lid device, or if there are * more we only care about the last one... */ lid_device = device; } printk(KERN_INFO PREFIX "%s [%s]\n", name, acpi_device_bid(device)); return 0; err_remove_fs: acpi_button_remove_fs(device); err_free_input: input_free_device(input); err_free_button: kfree(button); return error; } static int acpi_button_remove(struct acpi_device *device) { struct acpi_button *button = acpi_driver_data(device); acpi_button_remove_fs(device); input_unregister_device(button->input); kfree(button); return 0; } module_acpi_driver(acpi_button_driver);
gpl-2.0
aps243/kernel-imx
drivers/media/dvb-frontends/drxd_hard.c
2303
76892
/* * drxd_hard.c: DVB-T Demodulator Micronas DRX3975D-A2,DRX397xD-B1 * * Copyright (C) 2003-2007 Micronas * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 only, 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA * Or, point your browser to http://www.gnu.org/copyleft/gpl.html */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/firmware.h> #include <linux/i2c.h> #include <asm/div64.h> #include "dvb_frontend.h" #include "drxd.h" #include "drxd_firm.h" #define DRX_FW_FILENAME_A2 "drxd-a2-1.1.fw" #define DRX_FW_FILENAME_B1 "drxd-b1-1.1.fw" #define CHUNK_SIZE 48 #define DRX_I2C_RMW 0x10 #define DRX_I2C_BROADCAST 0x20 #define DRX_I2C_CLEARCRC 0x80 #define DRX_I2C_SINGLE_MASTER 0xC0 #define DRX_I2C_MODEFLAGS 0xC0 #define DRX_I2C_FLAGS 0xF0 #ifndef SIZEOF_ARRAY #define SIZEOF_ARRAY(array) (sizeof((array))/sizeof((array)[0])) #endif #define DEFAULT_LOCK_TIMEOUT 1100 #define DRX_CHANNEL_AUTO 0 #define DRX_CHANNEL_HIGH 1 #define DRX_CHANNEL_LOW 2 #define DRX_LOCK_MPEG 1 #define DRX_LOCK_FEC 2 #define DRX_LOCK_DEMOD 4 /****************************************************************************/ enum CSCDState { CSCD_INIT = 0, CSCD_SET, CSCD_SAVED }; enum CDrxdState { DRXD_UNINITIALIZED = 0, DRXD_STOPPED, DRXD_STARTED }; enum AGC_CTRL_MODE { AGC_CTRL_AUTO = 0, AGC_CTRL_USER, AGC_CTRL_OFF }; enum OperationMode { OM_Default, OM_DVBT_Diversity_Front, OM_DVBT_Diversity_End }; struct SCfgAgc { enum AGC_CTRL_MODE ctrlMode; u16 outputLevel; /* range [0, ... , 1023], 1/n of fullscale range */ u16 settleLevel; /* range [0, ... , 1023], 1/n of fullscale range */ u16 minOutputLevel; /* range [0, ... , 1023], 1/n of fullscale range */ u16 maxOutputLevel; /* range [0, ... , 1023], 1/n of fullscale range */ u16 speed; /* range [0, ... , 1023], 1/n of fullscale range */ u16 R1; u16 R2; u16 R3; }; struct SNoiseCal { int cpOpt; short cpNexpOfs; short tdCal2k; short tdCal8k; }; enum app_env { APPENV_STATIC = 0, APPENV_PORTABLE = 1, APPENV_MOBILE = 2 }; enum EIFFilter { IFFILTER_SAW = 0, IFFILTER_DISCRETE = 1 }; struct drxd_state { struct dvb_frontend frontend; struct dvb_frontend_ops ops; struct dtv_frontend_properties props; const struct firmware *fw; struct device *dev; struct i2c_adapter *i2c; void *priv; struct drxd_config config; int i2c_access; int init_done; struct mutex mutex; u8 chip_adr; u16 hi_cfg_timing_div; u16 hi_cfg_bridge_delay; u16 hi_cfg_wakeup_key; u16 hi_cfg_ctrl; u16 intermediate_freq; u16 osc_clock_freq; enum CSCDState cscd_state; enum CDrxdState drxd_state; u16 sys_clock_freq; s16 osc_clock_deviation; u16 expected_sys_clock_freq; u16 insert_rs_byte; u16 enable_parallel; int operation_mode; struct SCfgAgc if_agc_cfg; struct SCfgAgc rf_agc_cfg; struct SNoiseCal noise_cal; u32 fe_fs_add_incr; u32 org_fe_fs_add_incr; u16 current_fe_if_incr; u16 m_FeAgRegAgPwd; u16 m_FeAgRegAgAgcSio; u16 m_EcOcRegOcModeLop; u16 m_EcOcRegSncSncLvl; u8 *m_InitAtomicRead; u8 *m_HiI2cPatch; u8 *m_ResetCEFR; u8 *m_InitFE_1; u8 *m_InitFE_2; u8 *m_InitCP; u8 *m_InitCE; u8 *m_InitEQ; u8 *m_InitSC; u8 *m_InitEC; u8 *m_ResetECRAM; u8 *m_InitDiversityFront; u8 *m_InitDiversityEnd; u8 *m_DisableDiversity; u8 *m_StartDiversityFront; u8 *m_StartDiversityEnd; u8 *m_DiversityDelay8MHZ; u8 *m_DiversityDelay6MHZ; u8 *microcode; u32 microcode_length; int type_A; int PGA; int diversity; int tuner_mirrors; enum app_env app_env_default; enum app_env app_env_diversity; }; /****************************************************************************/ /* I2C **********************************************************************/ /****************************************************************************/ static int i2c_write(struct i2c_adapter *adap, u8 adr, u8 * data, int len) { struct i2c_msg msg = {.addr = adr, .flags = 0, .buf = data, .len = len }; if (i2c_transfer(adap, &msg, 1) != 1) return -1; return 0; } static int i2c_read(struct i2c_adapter *adap, u8 adr, u8 *msg, int len, u8 *answ, int alen) { struct i2c_msg msgs[2] = { { .addr = adr, .flags = 0, .buf = msg, .len = len }, { .addr = adr, .flags = I2C_M_RD, .buf = answ, .len = alen } }; if (i2c_transfer(adap, msgs, 2) != 2) return -1; return 0; } static inline u32 MulDiv32(u32 a, u32 b, u32 c) { u64 tmp64; tmp64 = (u64)a * (u64)b; do_div(tmp64, c); return (u32) tmp64; } static int Read16(struct drxd_state *state, u32 reg, u16 *data, u8 flags) { u8 adr = state->config.demod_address; u8 mm1[4] = { reg & 0xff, (reg >> 16) & 0xff, flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff }; u8 mm2[2]; if (i2c_read(state->i2c, adr, mm1, 4, mm2, 2) < 0) return -1; if (data) *data = mm2[0] | (mm2[1] << 8); return mm2[0] | (mm2[1] << 8); } static int Read32(struct drxd_state *state, u32 reg, u32 *data, u8 flags) { u8 adr = state->config.demod_address; u8 mm1[4] = { reg & 0xff, (reg >> 16) & 0xff, flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff }; u8 mm2[4]; if (i2c_read(state->i2c, adr, mm1, 4, mm2, 4) < 0) return -1; if (data) *data = mm2[0] | (mm2[1] << 8) | (mm2[2] << 16) | (mm2[3] << 24); return 0; } static int Write16(struct drxd_state *state, u32 reg, u16 data, u8 flags) { u8 adr = state->config.demod_address; u8 mm[6] = { reg & 0xff, (reg >> 16) & 0xff, flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff, data & 0xff, (data >> 8) & 0xff }; if (i2c_write(state->i2c, adr, mm, 6) < 0) return -1; return 0; } static int Write32(struct drxd_state *state, u32 reg, u32 data, u8 flags) { u8 adr = state->config.demod_address; u8 mm[8] = { reg & 0xff, (reg >> 16) & 0xff, flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff, data & 0xff, (data >> 8) & 0xff, (data >> 16) & 0xff, (data >> 24) & 0xff }; if (i2c_write(state->i2c, adr, mm, 8) < 0) return -1; return 0; } static int write_chunk(struct drxd_state *state, u32 reg, u8 *data, u32 len, u8 flags) { u8 adr = state->config.demod_address; u8 mm[CHUNK_SIZE + 4] = { reg & 0xff, (reg >> 16) & 0xff, flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff }; int i; for (i = 0; i < len; i++) mm[4 + i] = data[i]; if (i2c_write(state->i2c, adr, mm, 4 + len) < 0) { printk(KERN_ERR "error in write_chunk\n"); return -1; } return 0; } static int WriteBlock(struct drxd_state *state, u32 Address, u16 BlockSize, u8 *pBlock, u8 Flags) { while (BlockSize > 0) { u16 Chunk = BlockSize > CHUNK_SIZE ? CHUNK_SIZE : BlockSize; if (write_chunk(state, Address, pBlock, Chunk, Flags) < 0) return -1; pBlock += Chunk; Address += (Chunk >> 1); BlockSize -= Chunk; } return 0; } static int WriteTable(struct drxd_state *state, u8 * pTable) { int status = 0; if (pTable == NULL) return 0; while (!status) { u16 Length; u32 Address = pTable[0] | (pTable[1] << 8) | (pTable[2] << 16) | (pTable[3] << 24); if (Address == 0xFFFFFFFF) break; pTable += sizeof(u32); Length = pTable[0] | (pTable[1] << 8); pTable += sizeof(u16); if (!Length) break; status = WriteBlock(state, Address, Length * 2, pTable, 0); pTable += (Length * 2); } return status; } /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ static int ResetCEFR(struct drxd_state *state) { return WriteTable(state, state->m_ResetCEFR); } static int InitCP(struct drxd_state *state) { return WriteTable(state, state->m_InitCP); } static int InitCE(struct drxd_state *state) { int status; enum app_env AppEnv = state->app_env_default; do { status = WriteTable(state, state->m_InitCE); if (status < 0) break; if (state->operation_mode == OM_DVBT_Diversity_Front || state->operation_mode == OM_DVBT_Diversity_End) { AppEnv = state->app_env_diversity; } if (AppEnv == APPENV_STATIC) { status = Write16(state, CE_REG_TAPSET__A, 0x0000, 0); if (status < 0) break; } else if (AppEnv == APPENV_PORTABLE) { status = Write16(state, CE_REG_TAPSET__A, 0x0001, 0); if (status < 0) break; } else if (AppEnv == APPENV_MOBILE && state->type_A) { status = Write16(state, CE_REG_TAPSET__A, 0x0002, 0); if (status < 0) break; } else if (AppEnv == APPENV_MOBILE && !state->type_A) { status = Write16(state, CE_REG_TAPSET__A, 0x0006, 0); if (status < 0) break; } /* start ce */ status = Write16(state, B_CE_REG_COMM_EXEC__A, 0x0001, 0); if (status < 0) break; } while (0); return status; } static int StopOC(struct drxd_state *state) { int status = 0; u16 ocSyncLvl = 0; u16 ocModeLop = state->m_EcOcRegOcModeLop; u16 dtoIncLop = 0; u16 dtoIncHip = 0; do { /* Store output configuration */ status = Read16(state, EC_OC_REG_SNC_ISC_LVL__A, &ocSyncLvl, 0); if (status < 0) break; /* CHK_ERROR(Read16(EC_OC_REG_OC_MODE_LOP__A, &ocModeLop)); */ state->m_EcOcRegSncSncLvl = ocSyncLvl; /* m_EcOcRegOcModeLop = ocModeLop; */ /* Flush FIFO (byte-boundary) at fixed rate */ status = Read16(state, EC_OC_REG_RCN_MAP_LOP__A, &dtoIncLop, 0); if (status < 0) break; status = Read16(state, EC_OC_REG_RCN_MAP_HIP__A, &dtoIncHip, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_DTO_INC_LOP__A, dtoIncLop, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_DTO_INC_HIP__A, dtoIncHip, 0); if (status < 0) break; ocModeLop &= ~(EC_OC_REG_OC_MODE_LOP_DTO_CTR_SRC__M); ocModeLop |= EC_OC_REG_OC_MODE_LOP_DTO_CTR_SRC_STATIC; status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, ocModeLop, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_HOLD, 0); if (status < 0) break; msleep(1); /* Output pins to '0' */ status = Write16(state, EC_OC_REG_OCR_MPG_UOS__A, EC_OC_REG_OCR_MPG_UOS__M, 0); if (status < 0) break; /* Force the OC out of sync */ ocSyncLvl &= ~(EC_OC_REG_SNC_ISC_LVL_OSC__M); status = Write16(state, EC_OC_REG_SNC_ISC_LVL__A, ocSyncLvl, 0); if (status < 0) break; ocModeLop &= ~(EC_OC_REG_OC_MODE_LOP_PAR_ENA__M); ocModeLop |= EC_OC_REG_OC_MODE_LOP_PAR_ENA_ENABLE; ocModeLop |= 0x2; /* Magically-out-of-sync */ status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, ocModeLop, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_COMM_INT_STA__A, 0x0, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_ACTIVE, 0); if (status < 0) break; } while (0); return status; } static int StartOC(struct drxd_state *state) { int status = 0; do { /* Stop OC */ status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_HOLD, 0); if (status < 0) break; /* Restore output configuration */ status = Write16(state, EC_OC_REG_SNC_ISC_LVL__A, state->m_EcOcRegSncSncLvl, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, state->m_EcOcRegOcModeLop, 0); if (status < 0) break; /* Output pins active again */ status = Write16(state, EC_OC_REG_OCR_MPG_UOS__A, EC_OC_REG_OCR_MPG_UOS_INIT, 0); if (status < 0) break; /* Start OC */ status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_ACTIVE, 0); if (status < 0) break; } while (0); return status; } static int InitEQ(struct drxd_state *state) { return WriteTable(state, state->m_InitEQ); } static int InitEC(struct drxd_state *state) { return WriteTable(state, state->m_InitEC); } static int InitSC(struct drxd_state *state) { return WriteTable(state, state->m_InitSC); } static int InitAtomicRead(struct drxd_state *state) { return WriteTable(state, state->m_InitAtomicRead); } static int CorrectSysClockDeviation(struct drxd_state *state); static int DRX_GetLockStatus(struct drxd_state *state, u32 * pLockStatus) { u16 ScRaRamLock = 0; const u16 mpeg_lock_mask = (SC_RA_RAM_LOCK_MPEG__M | SC_RA_RAM_LOCK_FEC__M | SC_RA_RAM_LOCK_DEMOD__M); const u16 fec_lock_mask = (SC_RA_RAM_LOCK_FEC__M | SC_RA_RAM_LOCK_DEMOD__M); const u16 demod_lock_mask = SC_RA_RAM_LOCK_DEMOD__M; int status; *pLockStatus = 0; status = Read16(state, SC_RA_RAM_LOCK__A, &ScRaRamLock, 0x0000); if (status < 0) { printk(KERN_ERR "Can't read SC_RA_RAM_LOCK__A status = %08x\n", status); return status; } if (state->drxd_state != DRXD_STARTED) return 0; if ((ScRaRamLock & mpeg_lock_mask) == mpeg_lock_mask) { *pLockStatus |= DRX_LOCK_MPEG; CorrectSysClockDeviation(state); } if ((ScRaRamLock & fec_lock_mask) == fec_lock_mask) *pLockStatus |= DRX_LOCK_FEC; if ((ScRaRamLock & demod_lock_mask) == demod_lock_mask) *pLockStatus |= DRX_LOCK_DEMOD; return 0; } /****************************************************************************/ static int SetCfgIfAgc(struct drxd_state *state, struct SCfgAgc *cfg) { int status; if (cfg->outputLevel > DRXD_FE_CTRL_MAX) return -1; if (cfg->ctrlMode == AGC_CTRL_USER) { do { u16 FeAgRegPm1AgcWri; u16 FeAgRegAgModeLop; status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &FeAgRegAgModeLop, 0); if (status < 0) break; FeAgRegAgModeLop &= (~FE_AG_REG_AG_MODE_LOP_MODE_4__M); FeAgRegAgModeLop |= FE_AG_REG_AG_MODE_LOP_MODE_4_STATIC; status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, FeAgRegAgModeLop, 0); if (status < 0) break; FeAgRegPm1AgcWri = (u16) (cfg->outputLevel & FE_AG_REG_PM1_AGC_WRI__M); status = Write16(state, FE_AG_REG_PM1_AGC_WRI__A, FeAgRegPm1AgcWri, 0); if (status < 0) break; } while (0); } else if (cfg->ctrlMode == AGC_CTRL_AUTO) { if (((cfg->maxOutputLevel) < (cfg->minOutputLevel)) || ((cfg->maxOutputLevel) > DRXD_FE_CTRL_MAX) || ((cfg->speed) > DRXD_FE_CTRL_MAX) || ((cfg->settleLevel) > DRXD_FE_CTRL_MAX) ) return -1; do { u16 FeAgRegAgModeLop; u16 FeAgRegEgcSetLvl; u16 slope, offset; /* == Mode == */ status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &FeAgRegAgModeLop, 0); if (status < 0) break; FeAgRegAgModeLop &= (~FE_AG_REG_AG_MODE_LOP_MODE_4__M); FeAgRegAgModeLop |= FE_AG_REG_AG_MODE_LOP_MODE_4_DYNAMIC; status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, FeAgRegAgModeLop, 0); if (status < 0) break; /* == Settle level == */ FeAgRegEgcSetLvl = (u16) ((cfg->settleLevel >> 1) & FE_AG_REG_EGC_SET_LVL__M); status = Write16(state, FE_AG_REG_EGC_SET_LVL__A, FeAgRegEgcSetLvl, 0); if (status < 0) break; /* == Min/Max == */ slope = (u16) ((cfg->maxOutputLevel - cfg->minOutputLevel) / 2); offset = (u16) ((cfg->maxOutputLevel + cfg->minOutputLevel) / 2 - 511); status = Write16(state, FE_AG_REG_GC1_AGC_RIC__A, slope, 0); if (status < 0) break; status = Write16(state, FE_AG_REG_GC1_AGC_OFF__A, offset, 0); if (status < 0) break; /* == Speed == */ { const u16 maxRur = 8; const u16 slowIncrDecLUT[] = { 3, 4, 4, 5, 6 }; const u16 fastIncrDecLUT[] = { 14, 15, 15, 16, 17, 18, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 31 }; u16 fineSteps = (DRXD_FE_CTRL_MAX + 1) / (maxRur + 1); u16 fineSpeed = (u16) (cfg->speed - ((cfg->speed / fineSteps) * fineSteps)); u16 invRurCount = (u16) (cfg->speed / fineSteps); u16 rurCount; if (invRurCount > maxRur) { rurCount = 0; fineSpeed += fineSteps; } else { rurCount = maxRur - invRurCount; } /* fastInc = default * (2^(fineSpeed/fineSteps)) => range[default...2*default> slowInc = default * (2^(fineSpeed/fineSteps)) */ { u16 fastIncrDec = fastIncrDecLUT[fineSpeed / ((fineSteps / (14 + 1)) + 1)]; u16 slowIncrDec = slowIncrDecLUT[fineSpeed / (fineSteps / (3 + 1))]; status = Write16(state, FE_AG_REG_EGC_RUR_CNT__A, rurCount, 0); if (status < 0) break; status = Write16(state, FE_AG_REG_EGC_FAS_INC__A, fastIncrDec, 0); if (status < 0) break; status = Write16(state, FE_AG_REG_EGC_FAS_DEC__A, fastIncrDec, 0); if (status < 0) break; status = Write16(state, FE_AG_REG_EGC_SLO_INC__A, slowIncrDec, 0); if (status < 0) break; status = Write16(state, FE_AG_REG_EGC_SLO_DEC__A, slowIncrDec, 0); if (status < 0) break; } } } while (0); } else { /* No OFF mode for IF control */ return -1; } return status; } static int SetCfgRfAgc(struct drxd_state *state, struct SCfgAgc *cfg) { int status = 0; if (cfg->outputLevel > DRXD_FE_CTRL_MAX) return -1; if (cfg->ctrlMode == AGC_CTRL_USER) { do { u16 AgModeLop = 0; u16 level = (cfg->outputLevel); if (level == DRXD_FE_CTRL_MAX) level++; status = Write16(state, FE_AG_REG_PM2_AGC_WRI__A, level, 0x0000); if (status < 0) break; /*==== Mode ====*/ /* Powerdown PD2, WRI source */ state->m_FeAgRegAgPwd &= ~(FE_AG_REG_AG_PWD_PWD_PD2__M); state->m_FeAgRegAgPwd |= FE_AG_REG_AG_PWD_PWD_PD2_DISABLE; status = Write16(state, FE_AG_REG_AG_PWD__A, state->m_FeAgRegAgPwd, 0x0000); if (status < 0) break; status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000); if (status < 0) break; AgModeLop &= (~(FE_AG_REG_AG_MODE_LOP_MODE_5__M | FE_AG_REG_AG_MODE_LOP_MODE_E__M)); AgModeLop |= (FE_AG_REG_AG_MODE_LOP_MODE_5_STATIC | FE_AG_REG_AG_MODE_LOP_MODE_E_STATIC); status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000); if (status < 0) break; /* enable AGC2 pin */ { u16 FeAgRegAgAgcSio = 0; status = Read16(state, FE_AG_REG_AG_AGC_SIO__A, &FeAgRegAgAgcSio, 0x0000); if (status < 0) break; FeAgRegAgAgcSio &= ~(FE_AG_REG_AG_AGC_SIO_AGC_SIO_2__M); FeAgRegAgAgcSio |= FE_AG_REG_AG_AGC_SIO_AGC_SIO_2_OUTPUT; status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, FeAgRegAgAgcSio, 0x0000); if (status < 0) break; } } while (0); } else if (cfg->ctrlMode == AGC_CTRL_AUTO) { u16 AgModeLop = 0; do { u16 level; /* Automatic control */ /* Powerup PD2, AGC2 as output, TGC source */ (state->m_FeAgRegAgPwd) &= ~(FE_AG_REG_AG_PWD_PWD_PD2__M); (state->m_FeAgRegAgPwd) |= FE_AG_REG_AG_PWD_PWD_PD2_DISABLE; status = Write16(state, FE_AG_REG_AG_PWD__A, (state->m_FeAgRegAgPwd), 0x0000); if (status < 0) break; status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000); if (status < 0) break; AgModeLop &= (~(FE_AG_REG_AG_MODE_LOP_MODE_5__M | FE_AG_REG_AG_MODE_LOP_MODE_E__M)); AgModeLop |= (FE_AG_REG_AG_MODE_LOP_MODE_5_STATIC | FE_AG_REG_AG_MODE_LOP_MODE_E_DYNAMIC); status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000); if (status < 0) break; /* Settle level */ level = (((cfg->settleLevel) >> 4) & FE_AG_REG_TGC_SET_LVL__M); status = Write16(state, FE_AG_REG_TGC_SET_LVL__A, level, 0x0000); if (status < 0) break; /* Min/max: don't care */ /* Speed: TODO */ /* enable AGC2 pin */ { u16 FeAgRegAgAgcSio = 0; status = Read16(state, FE_AG_REG_AG_AGC_SIO__A, &FeAgRegAgAgcSio, 0x0000); if (status < 0) break; FeAgRegAgAgcSio &= ~(FE_AG_REG_AG_AGC_SIO_AGC_SIO_2__M); FeAgRegAgAgcSio |= FE_AG_REG_AG_AGC_SIO_AGC_SIO_2_OUTPUT; status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, FeAgRegAgAgcSio, 0x0000); if (status < 0) break; } } while (0); } else { u16 AgModeLop = 0; do { /* No RF AGC control */ /* Powerdown PD2, AGC2 as output, WRI source */ (state->m_FeAgRegAgPwd) &= ~(FE_AG_REG_AG_PWD_PWD_PD2__M); (state->m_FeAgRegAgPwd) |= FE_AG_REG_AG_PWD_PWD_PD2_ENABLE; status = Write16(state, FE_AG_REG_AG_PWD__A, (state->m_FeAgRegAgPwd), 0x0000); if (status < 0) break; status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000); if (status < 0) break; AgModeLop &= (~(FE_AG_REG_AG_MODE_LOP_MODE_5__M | FE_AG_REG_AG_MODE_LOP_MODE_E__M)); AgModeLop |= (FE_AG_REG_AG_MODE_LOP_MODE_5_STATIC | FE_AG_REG_AG_MODE_LOP_MODE_E_STATIC); status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000); if (status < 0) break; /* set FeAgRegAgAgcSio AGC2 (RF) as input */ { u16 FeAgRegAgAgcSio = 0; status = Read16(state, FE_AG_REG_AG_AGC_SIO__A, &FeAgRegAgAgcSio, 0x0000); if (status < 0) break; FeAgRegAgAgcSio &= ~(FE_AG_REG_AG_AGC_SIO_AGC_SIO_2__M); FeAgRegAgAgcSio |= FE_AG_REG_AG_AGC_SIO_AGC_SIO_2_INPUT; status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, FeAgRegAgAgcSio, 0x0000); if (status < 0) break; } } while (0); } return status; } static int ReadIFAgc(struct drxd_state *state, u32 * pValue) { int status = 0; *pValue = 0; if (state->if_agc_cfg.ctrlMode != AGC_CTRL_OFF) { u16 Value; status = Read16(state, FE_AG_REG_GC1_AGC_DAT__A, &Value, 0); Value &= FE_AG_REG_GC1_AGC_DAT__M; if (status >= 0) { /* 3.3V | R1 | Vin - R3 - * -- Vout | R2 | GND */ u32 R1 = state->if_agc_cfg.R1; u32 R2 = state->if_agc_cfg.R2; u32 R3 = state->if_agc_cfg.R3; u32 Vmax, Rpar, Vmin, Vout; if (R2 == 0 && (R1 == 0 || R3 == 0)) return 0; Vmax = (3300 * R2) / (R1 + R2); Rpar = (R2 * R3) / (R3 + R2); Vmin = (3300 * Rpar) / (R1 + Rpar); Vout = Vmin + ((Vmax - Vmin) * Value) / 1024; *pValue = Vout; } } return status; } static int load_firmware(struct drxd_state *state, const char *fw_name) { const struct firmware *fw; if (request_firmware(&fw, fw_name, state->dev) < 0) { printk(KERN_ERR "drxd: firmware load failure [%s]\n", fw_name); return -EIO; } state->microcode = kmemdup(fw->data, fw->size, GFP_KERNEL); if (state->microcode == NULL) { release_firmware(fw); printk(KERN_ERR "drxd: firmware load failure: no memory\n"); return -ENOMEM; } state->microcode_length = fw->size; release_firmware(fw); return 0; } static int DownloadMicrocode(struct drxd_state *state, const u8 *pMCImage, u32 Length) { u8 *pSrc; u32 Address; u16 nBlocks; u16 BlockSize; u32 offset = 0; int i, status = 0; pSrc = (u8 *) pMCImage; /* We're not using Flags */ /* Flags = (pSrc[0] << 8) | pSrc[1]; */ pSrc += sizeof(u16); offset += sizeof(u16); nBlocks = (pSrc[0] << 8) | pSrc[1]; pSrc += sizeof(u16); offset += sizeof(u16); for (i = 0; i < nBlocks; i++) { Address = (pSrc[0] << 24) | (pSrc[1] << 16) | (pSrc[2] << 8) | pSrc[3]; pSrc += sizeof(u32); offset += sizeof(u32); BlockSize = ((pSrc[0] << 8) | pSrc[1]) * sizeof(u16); pSrc += sizeof(u16); offset += sizeof(u16); /* We're not using Flags */ /* u16 Flags = (pSrc[0] << 8) | pSrc[1]; */ pSrc += sizeof(u16); offset += sizeof(u16); /* We're not using BlockCRC */ /* u16 BlockCRC = (pSrc[0] << 8) | pSrc[1]; */ pSrc += sizeof(u16); offset += sizeof(u16); status = WriteBlock(state, Address, BlockSize, pSrc, DRX_I2C_CLEARCRC); if (status < 0) break; pSrc += BlockSize; offset += BlockSize; } return status; } static int HI_Command(struct drxd_state *state, u16 cmd, u16 * pResult) { u32 nrRetries = 0; u16 waitCmd; int status; status = Write16(state, HI_RA_RAM_SRV_CMD__A, cmd, 0); if (status < 0) return status; do { nrRetries += 1; if (nrRetries > DRXD_MAX_RETRIES) { status = -1; break; } status = Read16(state, HI_RA_RAM_SRV_CMD__A, &waitCmd, 0); } while (waitCmd != 0); if (status >= 0) status = Read16(state, HI_RA_RAM_SRV_RES__A, pResult, 0); return status; } static int HI_CfgCommand(struct drxd_state *state) { int status = 0; mutex_lock(&state->mutex); Write16(state, HI_RA_RAM_SRV_CFG_KEY__A, HI_RA_RAM_SRV_RST_KEY_ACT, 0); Write16(state, HI_RA_RAM_SRV_CFG_DIV__A, state->hi_cfg_timing_div, 0); Write16(state, HI_RA_RAM_SRV_CFG_BDL__A, state->hi_cfg_bridge_delay, 0); Write16(state, HI_RA_RAM_SRV_CFG_WUP__A, state->hi_cfg_wakeup_key, 0); Write16(state, HI_RA_RAM_SRV_CFG_ACT__A, state->hi_cfg_ctrl, 0); Write16(state, HI_RA_RAM_SRV_CFG_KEY__A, HI_RA_RAM_SRV_RST_KEY_ACT, 0); if ((state->hi_cfg_ctrl & HI_RA_RAM_SRV_CFG_ACT_PWD_EXE) == HI_RA_RAM_SRV_CFG_ACT_PWD_EXE) status = Write16(state, HI_RA_RAM_SRV_CMD__A, HI_RA_RAM_SRV_CMD_CONFIG, 0); else status = HI_Command(state, HI_RA_RAM_SRV_CMD_CONFIG, 0); mutex_unlock(&state->mutex); return status; } static int InitHI(struct drxd_state *state) { state->hi_cfg_wakeup_key = (state->chip_adr); /* port/bridge/power down ctrl */ state->hi_cfg_ctrl = HI_RA_RAM_SRV_CFG_ACT_SLV0_ON; return HI_CfgCommand(state); } static int HI_ResetCommand(struct drxd_state *state) { int status; mutex_lock(&state->mutex); status = Write16(state, HI_RA_RAM_SRV_RST_KEY__A, HI_RA_RAM_SRV_RST_KEY_ACT, 0); if (status == 0) status = HI_Command(state, HI_RA_RAM_SRV_CMD_RESET, 0); mutex_unlock(&state->mutex); msleep(1); return status; } static int DRX_ConfigureI2CBridge(struct drxd_state *state, int bEnableBridge) { state->hi_cfg_ctrl &= (~HI_RA_RAM_SRV_CFG_ACT_BRD__M); if (bEnableBridge) state->hi_cfg_ctrl |= HI_RA_RAM_SRV_CFG_ACT_BRD_ON; else state->hi_cfg_ctrl |= HI_RA_RAM_SRV_CFG_ACT_BRD_OFF; return HI_CfgCommand(state); } #define HI_TR_WRITE 0x9 #define HI_TR_READ 0xA #define HI_TR_READ_WRITE 0xB #define HI_TR_BROADCAST 0x4 #if 0 static int AtomicReadBlock(struct drxd_state *state, u32 Addr, u16 DataSize, u8 *pData, u8 Flags) { int status; int i = 0; /* Parameter check */ if ((!pData) || ((DataSize & 1) != 0)) return -1; mutex_lock(&state->mutex); do { /* Instruct HI to read n bytes */ /* TODO use proper names forthese egisters */ status = Write16(state, HI_RA_RAM_SRV_CFG_KEY__A, (HI_TR_FUNC_ADDR & 0xFFFF), 0); if (status < 0) break; status = Write16(state, HI_RA_RAM_SRV_CFG_DIV__A, (u16) (Addr >> 16), 0); if (status < 0) break; status = Write16(state, HI_RA_RAM_SRV_CFG_BDL__A, (u16) (Addr & 0xFFFF), 0); if (status < 0) break; status = Write16(state, HI_RA_RAM_SRV_CFG_WUP__A, (u16) ((DataSize / 2) - 1), 0); if (status < 0) break; status = Write16(state, HI_RA_RAM_SRV_CFG_ACT__A, HI_TR_READ, 0); if (status < 0) break; status = HI_Command(state, HI_RA_RAM_SRV_CMD_EXECUTE, 0); if (status < 0) break; } while (0); if (status >= 0) { for (i = 0; i < (DataSize / 2); i += 1) { u16 word; status = Read16(state, (HI_RA_RAM_USR_BEGIN__A + i), &word, 0); if (status < 0) break; pData[2 * i] = (u8) (word & 0xFF); pData[(2 * i) + 1] = (u8) (word >> 8); } } mutex_unlock(&state->mutex); return status; } static int AtomicReadReg32(struct drxd_state *state, u32 Addr, u32 *pData, u8 Flags) { u8 buf[sizeof(u32)]; int status; if (!pData) return -1; status = AtomicReadBlock(state, Addr, sizeof(u32), buf, Flags); *pData = (((u32) buf[0]) << 0) + (((u32) buf[1]) << 8) + (((u32) buf[2]) << 16) + (((u32) buf[3]) << 24); return status; } #endif static int StopAllProcessors(struct drxd_state *state) { return Write16(state, HI_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, DRX_I2C_BROADCAST); } static int EnableAndResetMB(struct drxd_state *state) { if (state->type_A) { /* disable? monitor bus observe @ EC_OC */ Write16(state, EC_OC_REG_OC_MON_SIO__A, 0x0000, 0x0000); } /* do inverse broadcast, followed by explicit write to HI */ Write16(state, HI_COMM_MB__A, 0x0000, DRX_I2C_BROADCAST); Write16(state, HI_COMM_MB__A, 0x0000, 0x0000); return 0; } static int InitCC(struct drxd_state *state) { if (state->osc_clock_freq == 0 || state->osc_clock_freq > 20000 || (state->osc_clock_freq % 4000) != 0) { printk(KERN_ERR "invalid osc frequency %d\n", state->osc_clock_freq); return -1; } Write16(state, CC_REG_OSC_MODE__A, CC_REG_OSC_MODE_M20, 0); Write16(state, CC_REG_PLL_MODE__A, CC_REG_PLL_MODE_BYPASS_PLL | CC_REG_PLL_MODE_PUMP_CUR_12, 0); Write16(state, CC_REG_REF_DIVIDE__A, state->osc_clock_freq / 4000, 0); Write16(state, CC_REG_PWD_MODE__A, CC_REG_PWD_MODE_DOWN_PLL, 0); Write16(state, CC_REG_UPDATE__A, CC_REG_UPDATE_KEY, 0); return 0; } static int ResetECOD(struct drxd_state *state) { int status = 0; if (state->type_A) status = Write16(state, EC_OD_REG_SYNC__A, 0x0664, 0); else status = Write16(state, B_EC_OD_REG_SYNC__A, 0x0664, 0); if (!(status < 0)) status = WriteTable(state, state->m_ResetECRAM); if (!(status < 0)) status = Write16(state, EC_OD_REG_COMM_EXEC__A, 0x0001, 0); return status; } /* Configure PGA switch */ static int SetCfgPga(struct drxd_state *state, int pgaSwitch) { int status; u16 AgModeLop = 0; u16 AgModeHip = 0; do { if (pgaSwitch) { /* PGA on */ /* fine gain */ status = Read16(state, B_FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000); if (status < 0) break; AgModeLop &= (~(B_FE_AG_REG_AG_MODE_LOP_MODE_C__M)); AgModeLop |= B_FE_AG_REG_AG_MODE_LOP_MODE_C_DYNAMIC; status = Write16(state, B_FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000); if (status < 0) break; /* coarse gain */ status = Read16(state, B_FE_AG_REG_AG_MODE_HIP__A, &AgModeHip, 0x0000); if (status < 0) break; AgModeHip &= (~(B_FE_AG_REG_AG_MODE_HIP_MODE_J__M)); AgModeHip |= B_FE_AG_REG_AG_MODE_HIP_MODE_J_DYNAMIC; status = Write16(state, B_FE_AG_REG_AG_MODE_HIP__A, AgModeHip, 0x0000); if (status < 0) break; /* enable fine and coarse gain, enable AAF, no ext resistor */ status = Write16(state, B_FE_AG_REG_AG_PGA_MODE__A, B_FE_AG_REG_AG_PGA_MODE_PFY_PCY_AFY_REN, 0x0000); if (status < 0) break; } else { /* PGA off, bypass */ /* fine gain */ status = Read16(state, B_FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000); if (status < 0) break; AgModeLop &= (~(B_FE_AG_REG_AG_MODE_LOP_MODE_C__M)); AgModeLop |= B_FE_AG_REG_AG_MODE_LOP_MODE_C_STATIC; status = Write16(state, B_FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000); if (status < 0) break; /* coarse gain */ status = Read16(state, B_FE_AG_REG_AG_MODE_HIP__A, &AgModeHip, 0x0000); if (status < 0) break; AgModeHip &= (~(B_FE_AG_REG_AG_MODE_HIP_MODE_J__M)); AgModeHip |= B_FE_AG_REG_AG_MODE_HIP_MODE_J_STATIC; status = Write16(state, B_FE_AG_REG_AG_MODE_HIP__A, AgModeHip, 0x0000); if (status < 0) break; /* disable fine and coarse gain, enable AAF, no ext resistor */ status = Write16(state, B_FE_AG_REG_AG_PGA_MODE__A, B_FE_AG_REG_AG_PGA_MODE_PFN_PCN_AFY_REN, 0x0000); if (status < 0) break; } } while (0); return status; } static int InitFE(struct drxd_state *state) { int status; do { status = WriteTable(state, state->m_InitFE_1); if (status < 0) break; if (state->type_A) { status = Write16(state, FE_AG_REG_AG_PGA_MODE__A, FE_AG_REG_AG_PGA_MODE_PFN_PCN_AFY_REN, 0); } else { if (state->PGA) status = SetCfgPga(state, 0); else status = Write16(state, B_FE_AG_REG_AG_PGA_MODE__A, B_FE_AG_REG_AG_PGA_MODE_PFN_PCN_AFY_REN, 0); } if (status < 0) break; status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, state->m_FeAgRegAgAgcSio, 0x0000); if (status < 0) break; status = Write16(state, FE_AG_REG_AG_PWD__A, state->m_FeAgRegAgPwd, 0x0000); if (status < 0) break; status = WriteTable(state, state->m_InitFE_2); if (status < 0) break; } while (0); return status; } static int InitFT(struct drxd_state *state) { /* norm OFFSET, MB says =2 voor 8K en =3 voor 2K waarschijnlijk SC stuff */ return Write16(state, FT_REG_COMM_EXEC__A, 0x0001, 0x0000); } static int SC_WaitForReady(struct drxd_state *state) { u16 curCmd; int i; for (i = 0; i < DRXD_MAX_RETRIES; i += 1) { int status = Read16(state, SC_RA_RAM_CMD__A, &curCmd, 0); if (status == 0 || curCmd == 0) return status; } return -1; } static int SC_SendCommand(struct drxd_state *state, u16 cmd) { int status = 0; u16 errCode; Write16(state, SC_RA_RAM_CMD__A, cmd, 0); SC_WaitForReady(state); Read16(state, SC_RA_RAM_CMD_ADDR__A, &errCode, 0); if (errCode == 0xFFFF) { printk(KERN_ERR "Command Error\n"); status = -1; } return status; } static int SC_ProcStartCommand(struct drxd_state *state, u16 subCmd, u16 param0, u16 param1) { int status = 0; u16 scExec; mutex_lock(&state->mutex); do { Read16(state, SC_COMM_EXEC__A, &scExec, 0); if (scExec != 1) { status = -1; break; } SC_WaitForReady(state); Write16(state, SC_RA_RAM_CMD_ADDR__A, subCmd, 0); Write16(state, SC_RA_RAM_PARAM1__A, param1, 0); Write16(state, SC_RA_RAM_PARAM0__A, param0, 0); SC_SendCommand(state, SC_RA_RAM_CMD_PROC_START); } while (0); mutex_unlock(&state->mutex); return status; } static int SC_SetPrefParamCommand(struct drxd_state *state, u16 subCmd, u16 param0, u16 param1) { int status; mutex_lock(&state->mutex); do { status = SC_WaitForReady(state); if (status < 0) break; status = Write16(state, SC_RA_RAM_CMD_ADDR__A, subCmd, 0); if (status < 0) break; status = Write16(state, SC_RA_RAM_PARAM1__A, param1, 0); if (status < 0) break; status = Write16(state, SC_RA_RAM_PARAM0__A, param0, 0); if (status < 0) break; status = SC_SendCommand(state, SC_RA_RAM_CMD_SET_PREF_PARAM); if (status < 0) break; } while (0); mutex_unlock(&state->mutex); return status; } #if 0 static int SC_GetOpParamCommand(struct drxd_state *state, u16 * result) { int status = 0; mutex_lock(&state->mutex); do { status = SC_WaitForReady(state); if (status < 0) break; status = SC_SendCommand(state, SC_RA_RAM_CMD_GET_OP_PARAM); if (status < 0) break; status = Read16(state, SC_RA_RAM_PARAM0__A, result, 0); if (status < 0) break; } while (0); mutex_unlock(&state->mutex); return status; } #endif static int ConfigureMPEGOutput(struct drxd_state *state, int bEnableOutput) { int status; do { u16 EcOcRegIprInvMpg = 0; u16 EcOcRegOcModeLop = 0; u16 EcOcRegOcModeHip = 0; u16 EcOcRegOcMpgSio = 0; /*CHK_ERROR(Read16(state, EC_OC_REG_OC_MODE_LOP__A, &EcOcRegOcModeLop, 0)); */ if (state->operation_mode == OM_DVBT_Diversity_Front) { if (bEnableOutput) { EcOcRegOcModeHip |= B_EC_OC_REG_OC_MODE_HIP_MPG_BUS_SRC_MONITOR; } else EcOcRegOcMpgSio |= EC_OC_REG_OC_MPG_SIO__M; EcOcRegOcModeLop |= EC_OC_REG_OC_MODE_LOP_PAR_ENA_DISABLE; } else { EcOcRegOcModeLop = state->m_EcOcRegOcModeLop; if (bEnableOutput) EcOcRegOcMpgSio &= (~(EC_OC_REG_OC_MPG_SIO__M)); else EcOcRegOcMpgSio |= EC_OC_REG_OC_MPG_SIO__M; /* Don't Insert RS Byte */ if (state->insert_rs_byte) { EcOcRegOcModeLop &= (~(EC_OC_REG_OC_MODE_LOP_PAR_ENA__M)); EcOcRegOcModeHip &= (~EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL__M); EcOcRegOcModeHip |= EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL_ENABLE; } else { EcOcRegOcModeLop |= EC_OC_REG_OC_MODE_LOP_PAR_ENA_DISABLE; EcOcRegOcModeHip &= (~EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL__M); EcOcRegOcModeHip |= EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL_DISABLE; } /* Mode = Parallel */ if (state->enable_parallel) EcOcRegOcModeLop &= (~(EC_OC_REG_OC_MODE_LOP_MPG_TRM_MDE__M)); else EcOcRegOcModeLop |= EC_OC_REG_OC_MODE_LOP_MPG_TRM_MDE_SERIAL; } /* Invert Data */ /* EcOcRegIprInvMpg |= 0x00FF; */ EcOcRegIprInvMpg &= (~(0x00FF)); /* Invert Error ( we don't use the pin ) */ /* EcOcRegIprInvMpg |= 0x0100; */ EcOcRegIprInvMpg &= (~(0x0100)); /* Invert Start ( we don't use the pin ) */ /* EcOcRegIprInvMpg |= 0x0200; */ EcOcRegIprInvMpg &= (~(0x0200)); /* Invert Valid ( we don't use the pin ) */ /* EcOcRegIprInvMpg |= 0x0400; */ EcOcRegIprInvMpg &= (~(0x0400)); /* Invert Clock */ /* EcOcRegIprInvMpg |= 0x0800; */ EcOcRegIprInvMpg &= (~(0x0800)); /* EcOcRegOcModeLop =0x05; */ status = Write16(state, EC_OC_REG_IPR_INV_MPG__A, EcOcRegIprInvMpg, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, EcOcRegOcModeLop, 0); if (status < 0) break; status = Write16(state, EC_OC_REG_OC_MODE_HIP__A, EcOcRegOcModeHip, 0x0000); if (status < 0) break; status = Write16(state, EC_OC_REG_OC_MPG_SIO__A, EcOcRegOcMpgSio, 0); if (status < 0) break; } while (0); return status; } static int SetDeviceTypeId(struct drxd_state *state) { int status = 0; u16 deviceId = 0; do { status = Read16(state, CC_REG_JTAGID_L__A, &deviceId, 0); if (status < 0) break; /* TODO: why twice? */ status = Read16(state, CC_REG_JTAGID_L__A, &deviceId, 0); if (status < 0) break; printk(KERN_INFO "drxd: deviceId = %04x\n", deviceId); state->type_A = 0; state->PGA = 0; state->diversity = 0; if (deviceId == 0) { /* on A2 only 3975 available */ state->type_A = 1; printk(KERN_INFO "DRX3975D-A2\n"); } else { deviceId >>= 12; printk(KERN_INFO "DRX397%dD-B1\n", deviceId); switch (deviceId) { case 4: state->diversity = 1; case 3: case 7: state->PGA = 1; break; case 6: state->diversity = 1; case 5: case 8: break; default: status = -1; break; } } } while (0); if (status < 0) return status; /* Init Table selection */ state->m_InitAtomicRead = DRXD_InitAtomicRead; state->m_InitSC = DRXD_InitSC; state->m_ResetECRAM = DRXD_ResetECRAM; if (state->type_A) { state->m_ResetCEFR = DRXD_ResetCEFR; state->m_InitFE_1 = DRXD_InitFEA2_1; state->m_InitFE_2 = DRXD_InitFEA2_2; state->m_InitCP = DRXD_InitCPA2; state->m_InitCE = DRXD_InitCEA2; state->m_InitEQ = DRXD_InitEQA2; state->m_InitEC = DRXD_InitECA2; if (load_firmware(state, DRX_FW_FILENAME_A2)) return -EIO; } else { state->m_ResetCEFR = NULL; state->m_InitFE_1 = DRXD_InitFEB1_1; state->m_InitFE_2 = DRXD_InitFEB1_2; state->m_InitCP = DRXD_InitCPB1; state->m_InitCE = DRXD_InitCEB1; state->m_InitEQ = DRXD_InitEQB1; state->m_InitEC = DRXD_InitECB1; if (load_firmware(state, DRX_FW_FILENAME_B1)) return -EIO; } if (state->diversity) { state->m_InitDiversityFront = DRXD_InitDiversityFront; state->m_InitDiversityEnd = DRXD_InitDiversityEnd; state->m_DisableDiversity = DRXD_DisableDiversity; state->m_StartDiversityFront = DRXD_StartDiversityFront; state->m_StartDiversityEnd = DRXD_StartDiversityEnd; state->m_DiversityDelay8MHZ = DRXD_DiversityDelay8MHZ; state->m_DiversityDelay6MHZ = DRXD_DiversityDelay6MHZ; } else { state->m_InitDiversityFront = NULL; state->m_InitDiversityEnd = NULL; state->m_DisableDiversity = NULL; state->m_StartDiversityFront = NULL; state->m_StartDiversityEnd = NULL; state->m_DiversityDelay8MHZ = NULL; state->m_DiversityDelay6MHZ = NULL; } return status; } static int CorrectSysClockDeviation(struct drxd_state *state) { int status; s32 incr = 0; s32 nomincr = 0; u32 bandwidth = 0; u32 sysClockInHz = 0; u32 sysClockFreq = 0; /* in kHz */ s16 oscClockDeviation; s16 Diff; do { /* Retrieve bandwidth and incr, sanity check */ /* These accesses should be AtomicReadReg32, but that causes trouble (at least for diversity */ status = Read32(state, LC_RA_RAM_IFINCR_NOM_L__A, ((u32 *) &nomincr), 0); if (status < 0) break; status = Read32(state, FE_IF_REG_INCR0__A, (u32 *) &incr, 0); if (status < 0) break; if (state->type_A) { if ((nomincr - incr < -500) || (nomincr - incr > 500)) break; } else { if ((nomincr - incr < -2000) || (nomincr - incr > 2000)) break; } switch (state->props.bandwidth_hz) { case 8000000: bandwidth = DRXD_BANDWIDTH_8MHZ_IN_HZ; break; case 7000000: bandwidth = DRXD_BANDWIDTH_7MHZ_IN_HZ; break; case 6000000: bandwidth = DRXD_BANDWIDTH_6MHZ_IN_HZ; break; default: return -1; break; } /* Compute new sysclock value sysClockFreq = (((incr + 2^23)*bandwidth)/2^21)/1000 */ incr += (1 << 23); sysClockInHz = MulDiv32(incr, bandwidth, 1 << 21); sysClockFreq = (u32) (sysClockInHz / 1000); /* rounding */ if ((sysClockInHz % 1000) > 500) sysClockFreq++; /* Compute clock deviation in ppm */ oscClockDeviation = (u16) ((((s32) (sysClockFreq) - (s32) (state->expected_sys_clock_freq)) * 1000000L) / (s32) (state->expected_sys_clock_freq)); Diff = oscClockDeviation - state->osc_clock_deviation; /*printk(KERN_INFO "sysclockdiff=%d\n", Diff); */ if (Diff >= -200 && Diff <= 200) { state->sys_clock_freq = (u16) sysClockFreq; if (oscClockDeviation != state->osc_clock_deviation) { if (state->config.osc_deviation) { state->config.osc_deviation(state->priv, oscClockDeviation, 1); state->osc_clock_deviation = oscClockDeviation; } } /* switch OFF SRMM scan in SC */ status = Write16(state, SC_RA_RAM_SAMPLE_RATE_COUNT__A, DRXD_OSCDEV_DONT_SCAN, 0); if (status < 0) break; /* overrule FE_IF internal value for proper re-locking */ status = Write16(state, SC_RA_RAM_IF_SAVE__AX, state->current_fe_if_incr, 0); if (status < 0) break; state->cscd_state = CSCD_SAVED; } } while (0); return status; } static int DRX_Stop(struct drxd_state *state) { int status; if (state->drxd_state != DRXD_STARTED) return 0; do { if (state->cscd_state != CSCD_SAVED) { u32 lock; status = DRX_GetLockStatus(state, &lock); if (status < 0) break; } status = StopOC(state); if (status < 0) break; state->drxd_state = DRXD_STOPPED; status = ConfigureMPEGOutput(state, 0); if (status < 0) break; if (state->type_A) { /* Stop relevant processors off the device */ status = Write16(state, EC_OD_REG_COMM_EXEC__A, 0x0000, 0x0000); if (status < 0) break; status = Write16(state, SC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, LC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; } else { /* Stop all processors except HI & CC & FE */ status = Write16(state, B_SC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, B_LC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, B_FT_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, B_CP_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, B_CE_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, B_EQ_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, EC_OD_REG_COMM_EXEC__A, 0x0000, 0); if (status < 0) break; } } while (0); return status; } #if 0 /* Currently unused */ static int SetOperationMode(struct drxd_state *state, int oMode) { int status; do { if (state->drxd_state != DRXD_STOPPED) { status = -1; break; } if (oMode == state->operation_mode) { status = 0; break; } if (oMode != OM_Default && !state->diversity) { status = -1; break; } switch (oMode) { case OM_DVBT_Diversity_Front: status = WriteTable(state, state->m_InitDiversityFront); break; case OM_DVBT_Diversity_End: status = WriteTable(state, state->m_InitDiversityEnd); break; case OM_Default: /* We need to check how to get DRXD out of diversity */ default: status = WriteTable(state, state->m_DisableDiversity); break; } } while (0); if (!status) state->operation_mode = oMode; return status; } #endif static int StartDiversity(struct drxd_state *state) { int status = 0; u16 rcControl; do { if (state->operation_mode == OM_DVBT_Diversity_Front) { status = WriteTable(state, state->m_StartDiversityFront); if (status < 0) break; } else if (state->operation_mode == OM_DVBT_Diversity_End) { status = WriteTable(state, state->m_StartDiversityEnd); if (status < 0) break; if (state->props.bandwidth_hz == 8000000) { status = WriteTable(state, state->m_DiversityDelay8MHZ); if (status < 0) break; } else { status = WriteTable(state, state->m_DiversityDelay6MHZ); if (status < 0) break; } status = Read16(state, B_EQ_REG_RC_SEL_CAR__A, &rcControl, 0); if (status < 0) break; rcControl &= ~(B_EQ_REG_RC_SEL_CAR_FFTMODE__M); rcControl |= B_EQ_REG_RC_SEL_CAR_DIV_ON | /* combining enabled */ B_EQ_REG_RC_SEL_CAR_MEAS_A_CC | B_EQ_REG_RC_SEL_CAR_PASS_A_CC | B_EQ_REG_RC_SEL_CAR_LOCAL_A_CC; status = Write16(state, B_EQ_REG_RC_SEL_CAR__A, rcControl, 0); if (status < 0) break; } } while (0); return status; } static int SetFrequencyShift(struct drxd_state *state, u32 offsetFreq, int channelMirrored) { int negativeShift = (state->tuner_mirrors == channelMirrored); /* Handle all mirroring * * Note: ADC mirroring (aliasing) is implictly handled by limiting * feFsRegAddInc to 28 bits below * (if the result before masking is more than 28 bits, this means * that the ADC is mirroring. * The masking is in fact the aliasing of the ADC) * */ /* Compute register value, unsigned computation */ state->fe_fs_add_incr = MulDiv32(state->intermediate_freq + offsetFreq, 1 << 28, state->sys_clock_freq); /* Remove integer part */ state->fe_fs_add_incr &= 0x0FFFFFFFL; if (negativeShift) state->fe_fs_add_incr = ((1 << 28) - state->fe_fs_add_incr); /* Save the frequency shift without tunerOffset compensation for CtrlGetChannel. */ state->org_fe_fs_add_incr = MulDiv32(state->intermediate_freq, 1 << 28, state->sys_clock_freq); /* Remove integer part */ state->org_fe_fs_add_incr &= 0x0FFFFFFFL; if (negativeShift) state->org_fe_fs_add_incr = ((1L << 28) - state->org_fe_fs_add_incr); return Write32(state, FE_FS_REG_ADD_INC_LOP__A, state->fe_fs_add_incr, 0); } static int SetCfgNoiseCalibration(struct drxd_state *state, struct SNoiseCal *noiseCal) { u16 beOptEna; int status = 0; do { status = Read16(state, SC_RA_RAM_BE_OPT_ENA__A, &beOptEna, 0); if (status < 0) break; if (noiseCal->cpOpt) { beOptEna |= (1 << SC_RA_RAM_BE_OPT_ENA_CP_OPT); } else { beOptEna &= ~(1 << SC_RA_RAM_BE_OPT_ENA_CP_OPT); status = Write16(state, CP_REG_AC_NEXP_OFFS__A, noiseCal->cpNexpOfs, 0); if (status < 0) break; } status = Write16(state, SC_RA_RAM_BE_OPT_ENA__A, beOptEna, 0); if (status < 0) break; if (!state->type_A) { status = Write16(state, B_SC_RA_RAM_CO_TD_CAL_2K__A, noiseCal->tdCal2k, 0); if (status < 0) break; status = Write16(state, B_SC_RA_RAM_CO_TD_CAL_8K__A, noiseCal->tdCal8k, 0); if (status < 0) break; } } while (0); return status; } static int DRX_Start(struct drxd_state *state, s32 off) { struct dtv_frontend_properties *p = &state->props; int status; u16 transmissionParams = 0; u16 operationMode = 0; u16 qpskTdTpsPwr = 0; u16 qam16TdTpsPwr = 0; u16 qam64TdTpsPwr = 0; u32 feIfIncr = 0; u32 bandwidth = 0; int mirrorFreqSpect; u16 qpskSnCeGain = 0; u16 qam16SnCeGain = 0; u16 qam64SnCeGain = 0; u16 qpskIsGainMan = 0; u16 qam16IsGainMan = 0; u16 qam64IsGainMan = 0; u16 qpskIsGainExp = 0; u16 qam16IsGainExp = 0; u16 qam64IsGainExp = 0; u16 bandwidthParam = 0; if (off < 0) off = (off - 500) / 1000; else off = (off + 500) / 1000; do { if (state->drxd_state != DRXD_STOPPED) return -1; status = ResetECOD(state); if (status < 0) break; if (state->type_A) { status = InitSC(state); if (status < 0) break; } else { status = InitFT(state); if (status < 0) break; status = InitCP(state); if (status < 0) break; status = InitCE(state); if (status < 0) break; status = InitEQ(state); if (status < 0) break; status = InitSC(state); if (status < 0) break; } /* Restore current IF & RF AGC settings */ status = SetCfgIfAgc(state, &state->if_agc_cfg); if (status < 0) break; status = SetCfgRfAgc(state, &state->rf_agc_cfg); if (status < 0) break; mirrorFreqSpect = (state->props.inversion == INVERSION_ON); switch (p->transmission_mode) { default: /* Not set, detect it automatically */ operationMode |= SC_RA_RAM_OP_AUTO_MODE__M; /* fall through , try first guess DRX_FFTMODE_8K */ case TRANSMISSION_MODE_8K: transmissionParams |= SC_RA_RAM_OP_PARAM_MODE_8K; if (state->type_A) { status = Write16(state, EC_SB_REG_TR_MODE__A, EC_SB_REG_TR_MODE_8K, 0x0000); if (status < 0) break; qpskSnCeGain = 99; qam16SnCeGain = 83; qam64SnCeGain = 67; } break; case TRANSMISSION_MODE_2K: transmissionParams |= SC_RA_RAM_OP_PARAM_MODE_2K; if (state->type_A) { status = Write16(state, EC_SB_REG_TR_MODE__A, EC_SB_REG_TR_MODE_2K, 0x0000); if (status < 0) break; qpskSnCeGain = 97; qam16SnCeGain = 71; qam64SnCeGain = 65; } break; } switch (p->guard_interval) { case GUARD_INTERVAL_1_4: transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_4; break; case GUARD_INTERVAL_1_8: transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_8; break; case GUARD_INTERVAL_1_16: transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_16; break; case GUARD_INTERVAL_1_32: transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_32; break; default: /* Not set, detect it automatically */ operationMode |= SC_RA_RAM_OP_AUTO_GUARD__M; /* try first guess 1/4 */ transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_4; break; } switch (p->hierarchy) { case HIERARCHY_1: transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_A1; if (state->type_A) { status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0001, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_ALPHA__A, 0x0001, 0x0000); if (status < 0) break; qpskTdTpsPwr = EQ_TD_TPS_PWR_UNKNOWN; qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHA1; qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHA1; qpskIsGainMan = SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_MAN__PRE; qam16IsGainMan = SC_RA_RAM_EQ_IS_GAIN_16QAM_MAN__PRE; qam64IsGainMan = SC_RA_RAM_EQ_IS_GAIN_64QAM_MAN__PRE; qpskIsGainExp = SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_EXP__PRE; qam16IsGainExp = SC_RA_RAM_EQ_IS_GAIN_16QAM_EXP__PRE; qam64IsGainExp = SC_RA_RAM_EQ_IS_GAIN_64QAM_EXP__PRE; } break; case HIERARCHY_2: transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_A2; if (state->type_A) { status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0002, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_ALPHA__A, 0x0002, 0x0000); if (status < 0) break; qpskTdTpsPwr = EQ_TD_TPS_PWR_UNKNOWN; qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHA2; qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHA2; qpskIsGainMan = SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_MAN__PRE; qam16IsGainMan = SC_RA_RAM_EQ_IS_GAIN_16QAM_A2_MAN__PRE; qam64IsGainMan = SC_RA_RAM_EQ_IS_GAIN_64QAM_A2_MAN__PRE; qpskIsGainExp = SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_EXP__PRE; qam16IsGainExp = SC_RA_RAM_EQ_IS_GAIN_16QAM_A2_EXP__PRE; qam64IsGainExp = SC_RA_RAM_EQ_IS_GAIN_64QAM_A2_EXP__PRE; } break; case HIERARCHY_4: transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_A4; if (state->type_A) { status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0003, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_ALPHA__A, 0x0003, 0x0000); if (status < 0) break; qpskTdTpsPwr = EQ_TD_TPS_PWR_UNKNOWN; qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHA4; qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHA4; qpskIsGainMan = SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_MAN__PRE; qam16IsGainMan = SC_RA_RAM_EQ_IS_GAIN_16QAM_A4_MAN__PRE; qam64IsGainMan = SC_RA_RAM_EQ_IS_GAIN_64QAM_A4_MAN__PRE; qpskIsGainExp = SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_EXP__PRE; qam16IsGainExp = SC_RA_RAM_EQ_IS_GAIN_16QAM_A4_EXP__PRE; qam64IsGainExp = SC_RA_RAM_EQ_IS_GAIN_64QAM_A4_EXP__PRE; } break; case HIERARCHY_AUTO: default: /* Not set, detect it automatically, start with none */ operationMode |= SC_RA_RAM_OP_AUTO_HIER__M; transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_NO; if (state->type_A) { status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0000, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_ALPHA__A, 0x0000, 0x0000); if (status < 0) break; qpskTdTpsPwr = EQ_TD_TPS_PWR_QPSK; qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHAN; qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHAN; qpskIsGainMan = SC_RA_RAM_EQ_IS_GAIN_QPSK_MAN__PRE; qam16IsGainMan = SC_RA_RAM_EQ_IS_GAIN_16QAM_MAN__PRE; qam64IsGainMan = SC_RA_RAM_EQ_IS_GAIN_64QAM_MAN__PRE; qpskIsGainExp = SC_RA_RAM_EQ_IS_GAIN_QPSK_EXP__PRE; qam16IsGainExp = SC_RA_RAM_EQ_IS_GAIN_16QAM_EXP__PRE; qam64IsGainExp = SC_RA_RAM_EQ_IS_GAIN_64QAM_EXP__PRE; } break; } status = status; if (status < 0) break; switch (p->modulation) { default: operationMode |= SC_RA_RAM_OP_AUTO_CONST__M; /* fall through , try first guess DRX_CONSTELLATION_QAM64 */ case QAM_64: transmissionParams |= SC_RA_RAM_OP_PARAM_CONST_QAM64; if (state->type_A) { status = Write16(state, EQ_REG_OT_CONST__A, 0x0002, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_CONST__A, EC_SB_REG_CONST_64QAM, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_MSB__A, 0x0020, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_BIT2__A, 0x0008, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_LSB__A, 0x0002, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_TD_TPS_PWR_OFS__A, qam64TdTpsPwr, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_SN_CEGAIN__A, qam64SnCeGain, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_IS_GAIN_MAN__A, qam64IsGainMan, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_IS_GAIN_EXP__A, qam64IsGainExp, 0x0000); if (status < 0) break; } break; case QPSK: transmissionParams |= SC_RA_RAM_OP_PARAM_CONST_QPSK; if (state->type_A) { status = Write16(state, EQ_REG_OT_CONST__A, 0x0000, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_CONST__A, EC_SB_REG_CONST_QPSK, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_MSB__A, 0x0010, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_BIT2__A, 0x0000, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_LSB__A, 0x0000, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_TD_TPS_PWR_OFS__A, qpskTdTpsPwr, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_SN_CEGAIN__A, qpskSnCeGain, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_IS_GAIN_MAN__A, qpskIsGainMan, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_IS_GAIN_EXP__A, qpskIsGainExp, 0x0000); if (status < 0) break; } break; case QAM_16: transmissionParams |= SC_RA_RAM_OP_PARAM_CONST_QAM16; if (state->type_A) { status = Write16(state, EQ_REG_OT_CONST__A, 0x0001, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_CONST__A, EC_SB_REG_CONST_16QAM, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_MSB__A, 0x0010, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_BIT2__A, 0x0004, 0x0000); if (status < 0) break; status = Write16(state, EC_SB_REG_SCALE_LSB__A, 0x0000, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_TD_TPS_PWR_OFS__A, qam16TdTpsPwr, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_SN_CEGAIN__A, qam16SnCeGain, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_IS_GAIN_MAN__A, qam16IsGainMan, 0x0000); if (status < 0) break; status = Write16(state, EQ_REG_IS_GAIN_EXP__A, qam16IsGainExp, 0x0000); if (status < 0) break; } break; } status = status; if (status < 0) break; switch (DRX_CHANNEL_HIGH) { default: case DRX_CHANNEL_AUTO: case DRX_CHANNEL_LOW: transmissionParams |= SC_RA_RAM_OP_PARAM_PRIO_LO; status = Write16(state, EC_SB_REG_PRIOR__A, EC_SB_REG_PRIOR_LO, 0x0000); if (status < 0) break; break; case DRX_CHANNEL_HIGH: transmissionParams |= SC_RA_RAM_OP_PARAM_PRIO_HI; status = Write16(state, EC_SB_REG_PRIOR__A, EC_SB_REG_PRIOR_HI, 0x0000); if (status < 0) break; break; } switch (p->code_rate_HP) { case FEC_1_2: transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_1_2; if (state->type_A) { status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C1_2, 0x0000); if (status < 0) break; } break; default: operationMode |= SC_RA_RAM_OP_AUTO_RATE__M; case FEC_2_3: transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_2_3; if (state->type_A) { status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C2_3, 0x0000); if (status < 0) break; } break; case FEC_3_4: transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_3_4; if (state->type_A) { status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C3_4, 0x0000); if (status < 0) break; } break; case FEC_5_6: transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_5_6; if (state->type_A) { status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C5_6, 0x0000); if (status < 0) break; } break; case FEC_7_8: transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_7_8; if (state->type_A) { status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C7_8, 0x0000); if (status < 0) break; } break; } status = status; if (status < 0) break; /* First determine real bandwidth (Hz) */ /* Also set delay for impulse noise cruncher (only A2) */ /* Also set parameters for EC_OC fix, note EC_OC_REG_TMD_HIL_MAR is changed by SC for fix for some 8K,1/8 guard but is restored by InitEC and ResetEC functions */ switch (p->bandwidth_hz) { case 0: p->bandwidth_hz = 8000000; /* fall through */ case 8000000: /* (64/7)*(8/8)*1000000 */ bandwidth = DRXD_BANDWIDTH_8MHZ_IN_HZ; bandwidthParam = 0; status = Write16(state, FE_AG_REG_IND_DEL__A, 50, 0x0000); break; case 7000000: /* (64/7)*(7/8)*1000000 */ bandwidth = DRXD_BANDWIDTH_7MHZ_IN_HZ; bandwidthParam = 0x4807; /*binary:0100 1000 0000 0111 */ status = Write16(state, FE_AG_REG_IND_DEL__A, 59, 0x0000); break; case 6000000: /* (64/7)*(6/8)*1000000 */ bandwidth = DRXD_BANDWIDTH_6MHZ_IN_HZ; bandwidthParam = 0x0F07; /*binary: 0000 1111 0000 0111 */ status = Write16(state, FE_AG_REG_IND_DEL__A, 71, 0x0000); break; default: status = -EINVAL; } if (status < 0) break; status = Write16(state, SC_RA_RAM_BAND__A, bandwidthParam, 0x0000); if (status < 0) break; { u16 sc_config; status = Read16(state, SC_RA_RAM_CONFIG__A, &sc_config, 0); if (status < 0) break; /* enable SLAVE mode in 2k 1/32 to prevent timing change glitches */ if ((p->transmission_mode == TRANSMISSION_MODE_2K) && (p->guard_interval == GUARD_INTERVAL_1_32)) { /* enable slave */ sc_config |= SC_RA_RAM_CONFIG_SLAVE__M; } else { /* disable slave */ sc_config &= ~SC_RA_RAM_CONFIG_SLAVE__M; } status = Write16(state, SC_RA_RAM_CONFIG__A, sc_config, 0); if (status < 0) break; } status = SetCfgNoiseCalibration(state, &state->noise_cal); if (status < 0) break; if (state->cscd_state == CSCD_INIT) { /* switch on SRMM scan in SC */ status = Write16(state, SC_RA_RAM_SAMPLE_RATE_COUNT__A, DRXD_OSCDEV_DO_SCAN, 0x0000); if (status < 0) break; /* CHK_ERROR(Write16(SC_RA_RAM_SAMPLE_RATE_STEP__A, DRXD_OSCDEV_STEP, 0x0000));*/ state->cscd_state = CSCD_SET; } /* Now compute FE_IF_REG_INCR */ /*((( SysFreq/BandWidth)/2)/2) -1) * 2^23) => ((SysFreq / BandWidth) * (2^21) ) - (2^23) */ feIfIncr = MulDiv32(state->sys_clock_freq * 1000, (1ULL << 21), bandwidth) - (1 << 23); status = Write16(state, FE_IF_REG_INCR0__A, (u16) (feIfIncr & FE_IF_REG_INCR0__M), 0x0000); if (status < 0) break; status = Write16(state, FE_IF_REG_INCR1__A, (u16) ((feIfIncr >> FE_IF_REG_INCR0__W) & FE_IF_REG_INCR1__M), 0x0000); if (status < 0) break; /* Bandwidth setting done */ /* Mirror & frequency offset */ SetFrequencyShift(state, off, mirrorFreqSpect); /* Start SC, write channel settings to SC */ /* Enable SC after setting all other parameters */ status = Write16(state, SC_COMM_STATE__A, 0, 0x0000); if (status < 0) break; status = Write16(state, SC_COMM_EXEC__A, 1, 0x0000); if (status < 0) break; /* Write SC parameter registers, operation mode */ #if 1 operationMode = (SC_RA_RAM_OP_AUTO_MODE__M | SC_RA_RAM_OP_AUTO_GUARD__M | SC_RA_RAM_OP_AUTO_CONST__M | SC_RA_RAM_OP_AUTO_HIER__M | SC_RA_RAM_OP_AUTO_RATE__M); #endif status = SC_SetPrefParamCommand(state, 0x0000, transmissionParams, operationMode); if (status < 0) break; /* Start correct processes to get in lock */ status = SC_ProcStartCommand(state, SC_RA_RAM_PROC_LOCKTRACK, SC_RA_RAM_SW_EVENT_RUN_NMASK__M, SC_RA_RAM_LOCKTRACK_MIN); if (status < 0) break; status = StartOC(state); if (status < 0) break; if (state->operation_mode != OM_Default) { status = StartDiversity(state); if (status < 0) break; } state->drxd_state = DRXD_STARTED; } while (0); return status; } static int CDRXD(struct drxd_state *state, u32 IntermediateFrequency) { u32 ulRfAgcOutputLevel = 0xffffffff; u32 ulRfAgcSettleLevel = 528; /* Optimum value for MT2060 */ u32 ulRfAgcMinLevel = 0; /* Currently unused */ u32 ulRfAgcMaxLevel = DRXD_FE_CTRL_MAX; /* Currently unused */ u32 ulRfAgcSpeed = 0; /* Currently unused */ u32 ulRfAgcMode = 0; /*2; Off */ u32 ulRfAgcR1 = 820; u32 ulRfAgcR2 = 2200; u32 ulRfAgcR3 = 150; u32 ulIfAgcMode = 0; /* Auto */ u32 ulIfAgcOutputLevel = 0xffffffff; u32 ulIfAgcSettleLevel = 0xffffffff; u32 ulIfAgcMinLevel = 0xffffffff; u32 ulIfAgcMaxLevel = 0xffffffff; u32 ulIfAgcSpeed = 0xffffffff; u32 ulIfAgcR1 = 820; u32 ulIfAgcR2 = 2200; u32 ulIfAgcR3 = 150; u32 ulClock = state->config.clock; u32 ulSerialMode = 0; u32 ulEcOcRegOcModeLop = 4; /* Dynamic DTO source */ u32 ulHiI2cDelay = HI_I2C_DELAY; u32 ulHiI2cBridgeDelay = HI_I2C_BRIDGE_DELAY; u32 ulHiI2cPatch = 0; u32 ulEnvironment = APPENV_PORTABLE; u32 ulEnvironmentDiversity = APPENV_MOBILE; u32 ulIFFilter = IFFILTER_SAW; state->if_agc_cfg.ctrlMode = AGC_CTRL_AUTO; state->if_agc_cfg.outputLevel = 0; state->if_agc_cfg.settleLevel = 140; state->if_agc_cfg.minOutputLevel = 0; state->if_agc_cfg.maxOutputLevel = 1023; state->if_agc_cfg.speed = 904; if (ulIfAgcMode == 1 && ulIfAgcOutputLevel <= DRXD_FE_CTRL_MAX) { state->if_agc_cfg.ctrlMode = AGC_CTRL_USER; state->if_agc_cfg.outputLevel = (u16) (ulIfAgcOutputLevel); } if (ulIfAgcMode == 0 && ulIfAgcSettleLevel <= DRXD_FE_CTRL_MAX && ulIfAgcMinLevel <= DRXD_FE_CTRL_MAX && ulIfAgcMaxLevel <= DRXD_FE_CTRL_MAX && ulIfAgcSpeed <= DRXD_FE_CTRL_MAX) { state->if_agc_cfg.ctrlMode = AGC_CTRL_AUTO; state->if_agc_cfg.settleLevel = (u16) (ulIfAgcSettleLevel); state->if_agc_cfg.minOutputLevel = (u16) (ulIfAgcMinLevel); state->if_agc_cfg.maxOutputLevel = (u16) (ulIfAgcMaxLevel); state->if_agc_cfg.speed = (u16) (ulIfAgcSpeed); } state->if_agc_cfg.R1 = (u16) (ulIfAgcR1); state->if_agc_cfg.R2 = (u16) (ulIfAgcR2); state->if_agc_cfg.R3 = (u16) (ulIfAgcR3); state->rf_agc_cfg.R1 = (u16) (ulRfAgcR1); state->rf_agc_cfg.R2 = (u16) (ulRfAgcR2); state->rf_agc_cfg.R3 = (u16) (ulRfAgcR3); state->rf_agc_cfg.ctrlMode = AGC_CTRL_AUTO; /* rest of the RFAgcCfg structure currently unused */ if (ulRfAgcMode == 1 && ulRfAgcOutputLevel <= DRXD_FE_CTRL_MAX) { state->rf_agc_cfg.ctrlMode = AGC_CTRL_USER; state->rf_agc_cfg.outputLevel = (u16) (ulRfAgcOutputLevel); } if (ulRfAgcMode == 0 && ulRfAgcSettleLevel <= DRXD_FE_CTRL_MAX && ulRfAgcMinLevel <= DRXD_FE_CTRL_MAX && ulRfAgcMaxLevel <= DRXD_FE_CTRL_MAX && ulRfAgcSpeed <= DRXD_FE_CTRL_MAX) { state->rf_agc_cfg.ctrlMode = AGC_CTRL_AUTO; state->rf_agc_cfg.settleLevel = (u16) (ulRfAgcSettleLevel); state->rf_agc_cfg.minOutputLevel = (u16) (ulRfAgcMinLevel); state->rf_agc_cfg.maxOutputLevel = (u16) (ulRfAgcMaxLevel); state->rf_agc_cfg.speed = (u16) (ulRfAgcSpeed); } if (ulRfAgcMode == 2) state->rf_agc_cfg.ctrlMode = AGC_CTRL_OFF; if (ulEnvironment <= 2) state->app_env_default = (enum app_env) (ulEnvironment); if (ulEnvironmentDiversity <= 2) state->app_env_diversity = (enum app_env) (ulEnvironmentDiversity); if (ulIFFilter == IFFILTER_DISCRETE) { /* discrete filter */ state->noise_cal.cpOpt = 0; state->noise_cal.cpNexpOfs = 40; state->noise_cal.tdCal2k = -40; state->noise_cal.tdCal8k = -24; } else { /* SAW filter */ state->noise_cal.cpOpt = 1; state->noise_cal.cpNexpOfs = 0; state->noise_cal.tdCal2k = -21; state->noise_cal.tdCal8k = -24; } state->m_EcOcRegOcModeLop = (u16) (ulEcOcRegOcModeLop); state->chip_adr = (state->config.demod_address << 1) | 1; switch (ulHiI2cPatch) { case 1: state->m_HiI2cPatch = DRXD_HiI2cPatch_1; break; case 3: state->m_HiI2cPatch = DRXD_HiI2cPatch_3; break; default: state->m_HiI2cPatch = NULL; } /* modify tuner and clock attributes */ state->intermediate_freq = (u16) (IntermediateFrequency / 1000); /* expected system clock frequency in kHz */ state->expected_sys_clock_freq = 48000; /* real system clock frequency in kHz */ state->sys_clock_freq = 48000; state->osc_clock_freq = (u16) ulClock; state->osc_clock_deviation = 0; state->cscd_state = CSCD_INIT; state->drxd_state = DRXD_UNINITIALIZED; state->PGA = 0; state->type_A = 0; state->tuner_mirrors = 0; /* modify MPEG output attributes */ state->insert_rs_byte = state->config.insert_rs_byte; state->enable_parallel = (ulSerialMode != 1); /* Timing div, 250ns/Psys */ /* Timing div, = ( delay (nano seconds) * sysclk (kHz) )/ 1000 */ state->hi_cfg_timing_div = (u16) ((state->sys_clock_freq / 1000) * ulHiI2cDelay) / 1000; /* Bridge delay, uses oscilator clock */ /* Delay = ( delay (nano seconds) * oscclk (kHz) )/ 1000 */ state->hi_cfg_bridge_delay = (u16) ((state->osc_clock_freq / 1000) * ulHiI2cBridgeDelay) / 1000; state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_CONSUMER; /* state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_PRO; */ state->m_FeAgRegAgAgcSio = DRXD_DEF_AG_AGC_SIO; return 0; } static int DRXD_init(struct drxd_state *state, const u8 *fw, u32 fw_size) { int status = 0; u32 driverVersion; if (state->init_done) return 0; CDRXD(state, state->config.IF ? state->config.IF : 36000000); do { state->operation_mode = OM_Default; status = SetDeviceTypeId(state); if (status < 0) break; /* Apply I2c address patch to B1 */ if (!state->type_A && state->m_HiI2cPatch != NULL) status = WriteTable(state, state->m_HiI2cPatch); if (status < 0) break; if (state->type_A) { /* HI firmware patch for UIO readout, avoid clearing of result register */ status = Write16(state, 0x43012D, 0x047f, 0); if (status < 0) break; } status = HI_ResetCommand(state); if (status < 0) break; status = StopAllProcessors(state); if (status < 0) break; status = InitCC(state); if (status < 0) break; state->osc_clock_deviation = 0; if (state->config.osc_deviation) state->osc_clock_deviation = state->config.osc_deviation(state->priv, 0, 0); { /* Handle clock deviation */ s32 devB; s32 devA = (s32) (state->osc_clock_deviation) * (s32) (state->expected_sys_clock_freq); /* deviation in kHz */ s32 deviation = (devA / (1000000L)); /* rounding, signed */ if (devA > 0) devB = (2); else devB = (-2); if ((devB * (devA % 1000000L) > 1000000L)) { /* add +1 or -1 */ deviation += (devB / 2); } state->sys_clock_freq = (u16) ((state->expected_sys_clock_freq) + deviation); } status = InitHI(state); if (status < 0) break; status = InitAtomicRead(state); if (status < 0) break; status = EnableAndResetMB(state); if (status < 0) break; if (state->type_A) status = ResetCEFR(state); if (status < 0) break; if (fw) { status = DownloadMicrocode(state, fw, fw_size); if (status < 0) break; } else { status = DownloadMicrocode(state, state->microcode, state->microcode_length); if (status < 0) break; } if (state->PGA) { state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_PRO; SetCfgPga(state, 0); /* PGA = 0 dB */ } else { state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_CONSUMER; } state->m_FeAgRegAgAgcSio = DRXD_DEF_AG_AGC_SIO; status = InitFE(state); if (status < 0) break; status = InitFT(state); if (status < 0) break; status = InitCP(state); if (status < 0) break; status = InitCE(state); if (status < 0) break; status = InitEQ(state); if (status < 0) break; status = InitEC(state); if (status < 0) break; status = InitSC(state); if (status < 0) break; status = SetCfgIfAgc(state, &state->if_agc_cfg); if (status < 0) break; status = SetCfgRfAgc(state, &state->rf_agc_cfg); if (status < 0) break; state->cscd_state = CSCD_INIT; status = Write16(state, SC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; status = Write16(state, LC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0); if (status < 0) break; driverVersion = (((VERSION_MAJOR / 10) << 4) + (VERSION_MAJOR % 10)) << 24; driverVersion += (((VERSION_MINOR / 10) << 4) + (VERSION_MINOR % 10)) << 16; driverVersion += ((VERSION_PATCH / 1000) << 12) + ((VERSION_PATCH / 100) << 8) + ((VERSION_PATCH / 10) << 4) + (VERSION_PATCH % 10); status = Write32(state, SC_RA_RAM_DRIVER_VERSION__AX, driverVersion, 0); if (status < 0) break; status = StopOC(state); if (status < 0) break; state->drxd_state = DRXD_STOPPED; state->init_done = 1; status = 0; } while (0); return status; } static int DRXD_status(struct drxd_state *state, u32 *pLockStatus) { DRX_GetLockStatus(state, pLockStatus); /*if (*pLockStatus&DRX_LOCK_MPEG) */ if (*pLockStatus & DRX_LOCK_FEC) { ConfigureMPEGOutput(state, 1); /* Get status again, in case we have MPEG lock now */ /*DRX_GetLockStatus(state, pLockStatus); */ } return 0; } /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ static int drxd_read_signal_strength(struct dvb_frontend *fe, u16 * strength) { struct drxd_state *state = fe->demodulator_priv; u32 value; int res; res = ReadIFAgc(state, &value); if (res < 0) *strength = 0; else *strength = 0xffff - (value << 4); return 0; } static int drxd_read_status(struct dvb_frontend *fe, fe_status_t * status) { struct drxd_state *state = fe->demodulator_priv; u32 lock; DRXD_status(state, &lock); *status = 0; /* No MPEG lock in V255 firmware, bug ? */ #if 1 if (lock & DRX_LOCK_MPEG) *status |= FE_HAS_LOCK; #else if (lock & DRX_LOCK_FEC) *status |= FE_HAS_LOCK; #endif if (lock & DRX_LOCK_FEC) *status |= FE_HAS_VITERBI | FE_HAS_SYNC; if (lock & DRX_LOCK_DEMOD) *status |= FE_HAS_CARRIER | FE_HAS_SIGNAL; return 0; } static int drxd_init(struct dvb_frontend *fe) { struct drxd_state *state = fe->demodulator_priv; int err = 0; /* if (request_firmware(&state->fw, "drxd.fw", state->dev)<0) */ return DRXD_init(state, 0, 0); err = DRXD_init(state, state->fw->data, state->fw->size); release_firmware(state->fw); return err; } int drxd_config_i2c(struct dvb_frontend *fe, int onoff) { struct drxd_state *state = fe->demodulator_priv; if (state->config.disable_i2c_gate_ctrl == 1) return 0; return DRX_ConfigureI2CBridge(state, onoff); } EXPORT_SYMBOL(drxd_config_i2c); static int drxd_get_tune_settings(struct dvb_frontend *fe, struct dvb_frontend_tune_settings *sets) { sets->min_delay_ms = 10000; sets->max_drift = 0; sets->step_size = 0; return 0; } static int drxd_read_ber(struct dvb_frontend *fe, u32 * ber) { *ber = 0; return 0; } static int drxd_read_snr(struct dvb_frontend *fe, u16 * snr) { *snr = 0; return 0; } static int drxd_read_ucblocks(struct dvb_frontend *fe, u32 * ucblocks) { *ucblocks = 0; return 0; } static int drxd_sleep(struct dvb_frontend *fe) { struct drxd_state *state = fe->demodulator_priv; ConfigureMPEGOutput(state, 0); return 0; } static int drxd_i2c_gate_ctrl(struct dvb_frontend *fe, int enable) { return drxd_config_i2c(fe, enable); } static int drxd_set_frontend(struct dvb_frontend *fe) { struct dtv_frontend_properties *p = &fe->dtv_property_cache; struct drxd_state *state = fe->demodulator_priv; s32 off = 0; state->props = *p; DRX_Stop(state); if (fe->ops.tuner_ops.set_params) { fe->ops.tuner_ops.set_params(fe); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } msleep(200); return DRX_Start(state, off); } static void drxd_release(struct dvb_frontend *fe) { struct drxd_state *state = fe->demodulator_priv; kfree(state); } static struct dvb_frontend_ops drxd_ops = { .delsys = { SYS_DVBT}, .info = { .name = "Micronas DRXD DVB-T", .frequency_min = 47125000, .frequency_max = 855250000, .frequency_stepsize = 166667, .frequency_tolerance = 0, .caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO | FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_HIERARCHY_AUTO | FE_CAN_RECOVER | FE_CAN_MUTE_TS}, .release = drxd_release, .init = drxd_init, .sleep = drxd_sleep, .i2c_gate_ctrl = drxd_i2c_gate_ctrl, .set_frontend = drxd_set_frontend, .get_tune_settings = drxd_get_tune_settings, .read_status = drxd_read_status, .read_ber = drxd_read_ber, .read_signal_strength = drxd_read_signal_strength, .read_snr = drxd_read_snr, .read_ucblocks = drxd_read_ucblocks, }; struct dvb_frontend *drxd_attach(const struct drxd_config *config, void *priv, struct i2c_adapter *i2c, struct device *dev) { struct drxd_state *state = NULL; state = kmalloc(sizeof(struct drxd_state), GFP_KERNEL); if (!state) return NULL; memset(state, 0, sizeof(*state)); state->ops = drxd_ops; state->dev = dev; state->config = *config; state->i2c = i2c; state->priv = priv; mutex_init(&state->mutex); if (Read16(state, 0, 0, 0) < 0) goto error; state->frontend.ops = drxd_ops; state->frontend.demodulator_priv = state; ConfigureMPEGOutput(state, 0); /* add few initialization to allow gate control */ CDRXD(state, state->config.IF ? state->config.IF : 36000000); InitHI(state); return &state->frontend; error: printk(KERN_ERR "drxd: not found\n"); kfree(state); return NULL; } EXPORT_SYMBOL(drxd_attach); MODULE_DESCRIPTION("DRXD driver"); MODULE_AUTHOR("Micronas"); MODULE_LICENSE("GPL");
gpl-2.0
civato/A500ICS_StormFlex
drivers/net/wireless/hostap/hostap_ap.c
2815
86834
/* * Intersil Prism2 driver with Host AP (software access point) support * Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen * <j@w1.fi> * Copyright (c) 2002-2005, Jouni Malinen <j@w1.fi> * * This file is to be included into hostap.c when S/W AP functionality is * compiled. * * AP: FIX: * - if unicast Class 2 (assoc,reassoc,disassoc) frame received from * unauthenticated STA, send deauth. frame (8802.11: 5.5) * - if unicast Class 3 (data with to/from DS,deauth,pspoll) frame received * from authenticated, but unassoc STA, send disassoc frame (8802.11: 5.5) * - if unicast Class 3 received from unauthenticated STA, send deauth. frame * (8802.11: 5.5) */ #include <linux/proc_fs.h> #include <linux/delay.h> #include <linux/random.h> #include <linux/if_arp.h> #include <linux/slab.h> #include "hostap_wlan.h" #include "hostap.h" #include "hostap_ap.h" static int other_ap_policy[MAX_PARM_DEVICES] = { AP_OTHER_AP_SKIP_ALL, DEF_INTS }; module_param_array(other_ap_policy, int, NULL, 0444); MODULE_PARM_DESC(other_ap_policy, "Other AP beacon monitoring policy (0-3)"); static int ap_max_inactivity[MAX_PARM_DEVICES] = { AP_MAX_INACTIVITY_SEC, DEF_INTS }; module_param_array(ap_max_inactivity, int, NULL, 0444); MODULE_PARM_DESC(ap_max_inactivity, "AP timeout (in seconds) for station " "inactivity"); static int ap_bridge_packets[MAX_PARM_DEVICES] = { 1, DEF_INTS }; module_param_array(ap_bridge_packets, int, NULL, 0444); MODULE_PARM_DESC(ap_bridge_packets, "Bridge packets directly between " "stations"); static int autom_ap_wds[MAX_PARM_DEVICES] = { 0, DEF_INTS }; module_param_array(autom_ap_wds, int, NULL, 0444); MODULE_PARM_DESC(autom_ap_wds, "Add WDS connections to other APs " "automatically"); static struct sta_info* ap_get_sta(struct ap_data *ap, u8 *sta); static void hostap_event_expired_sta(struct net_device *dev, struct sta_info *sta); static void handle_add_proc_queue(struct work_struct *work); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT static void handle_wds_oper_queue(struct work_struct *work); static void prism2_send_mgmt(struct net_device *dev, u16 type_subtype, char *body, int body_len, u8 *addr, u16 tx_cb_idx); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ #ifndef PRISM2_NO_PROCFS_DEBUG static int ap_debug_proc_read(char *page, char **start, off_t off, int count, int *eof, void *data) { char *p = page; struct ap_data *ap = (struct ap_data *) data; if (off != 0) { *eof = 1; return 0; } p += sprintf(p, "BridgedUnicastFrames=%u\n", ap->bridged_unicast); p += sprintf(p, "BridgedMulticastFrames=%u\n", ap->bridged_multicast); p += sprintf(p, "max_inactivity=%u\n", ap->max_inactivity / HZ); p += sprintf(p, "bridge_packets=%u\n", ap->bridge_packets); p += sprintf(p, "nullfunc_ack=%u\n", ap->nullfunc_ack); p += sprintf(p, "autom_ap_wds=%u\n", ap->autom_ap_wds); p += sprintf(p, "auth_algs=%u\n", ap->local->auth_algs); p += sprintf(p, "tx_drop_nonassoc=%u\n", ap->tx_drop_nonassoc); return (p - page); } #endif /* PRISM2_NO_PROCFS_DEBUG */ static void ap_sta_hash_add(struct ap_data *ap, struct sta_info *sta) { sta->hnext = ap->sta_hash[STA_HASH(sta->addr)]; ap->sta_hash[STA_HASH(sta->addr)] = sta; } static void ap_sta_hash_del(struct ap_data *ap, struct sta_info *sta) { struct sta_info *s; s = ap->sta_hash[STA_HASH(sta->addr)]; if (s == NULL) return; if (memcmp(s->addr, sta->addr, ETH_ALEN) == 0) { ap->sta_hash[STA_HASH(sta->addr)] = s->hnext; return; } while (s->hnext != NULL && memcmp(s->hnext->addr, sta->addr, ETH_ALEN) != 0) s = s->hnext; if (s->hnext != NULL) s->hnext = s->hnext->hnext; else printk("AP: could not remove STA %pM from hash table\n", sta->addr); } static void ap_free_sta(struct ap_data *ap, struct sta_info *sta) { if (sta->ap && sta->local) hostap_event_expired_sta(sta->local->dev, sta); if (ap->proc != NULL) { char name[20]; sprintf(name, "%pM", sta->addr); remove_proc_entry(name, ap->proc); } if (sta->crypt) { sta->crypt->ops->deinit(sta->crypt->priv); kfree(sta->crypt); sta->crypt = NULL; } skb_queue_purge(&sta->tx_buf); ap->num_sta--; #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT if (sta->aid > 0) ap->sta_aid[sta->aid - 1] = NULL; if (!sta->ap && sta->u.sta.challenge) kfree(sta->u.sta.challenge); del_timer(&sta->timer); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ kfree(sta); } static void hostap_set_tim(local_info_t *local, int aid, int set) { if (local->func->set_tim) local->func->set_tim(local->dev, aid, set); } static void hostap_event_new_sta(struct net_device *dev, struct sta_info *sta) { union iwreq_data wrqu; memset(&wrqu, 0, sizeof(wrqu)); memcpy(wrqu.addr.sa_data, sta->addr, ETH_ALEN); wrqu.addr.sa_family = ARPHRD_ETHER; wireless_send_event(dev, IWEVREGISTERED, &wrqu, NULL); } static void hostap_event_expired_sta(struct net_device *dev, struct sta_info *sta) { union iwreq_data wrqu; memset(&wrqu, 0, sizeof(wrqu)); memcpy(wrqu.addr.sa_data, sta->addr, ETH_ALEN); wrqu.addr.sa_family = ARPHRD_ETHER; wireless_send_event(dev, IWEVEXPIRED, &wrqu, NULL); } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT static void ap_handle_timer(unsigned long data) { struct sta_info *sta = (struct sta_info *) data; local_info_t *local; struct ap_data *ap; unsigned long next_time = 0; int was_assoc; if (sta == NULL || sta->local == NULL || sta->local->ap == NULL) { PDEBUG(DEBUG_AP, "ap_handle_timer() called with NULL data\n"); return; } local = sta->local; ap = local->ap; was_assoc = sta->flags & WLAN_STA_ASSOC; if (atomic_read(&sta->users) != 0) next_time = jiffies + HZ; else if ((sta->flags & WLAN_STA_PERM) && !(sta->flags & WLAN_STA_AUTH)) next_time = jiffies + ap->max_inactivity; if (time_before(jiffies, sta->last_rx + ap->max_inactivity)) { /* station activity detected; reset timeout state */ sta->timeout_next = STA_NULLFUNC; next_time = sta->last_rx + ap->max_inactivity; } else if (sta->timeout_next == STA_DISASSOC && !(sta->flags & WLAN_STA_PENDING_POLL)) { /* STA ACKed data nullfunc frame poll */ sta->timeout_next = STA_NULLFUNC; next_time = jiffies + ap->max_inactivity; } if (next_time) { sta->timer.expires = next_time; add_timer(&sta->timer); return; } if (sta->ap) sta->timeout_next = STA_DEAUTH; if (sta->timeout_next == STA_DEAUTH && !(sta->flags & WLAN_STA_PERM)) { spin_lock(&ap->sta_table_lock); ap_sta_hash_del(ap, sta); list_del(&sta->list); spin_unlock(&ap->sta_table_lock); sta->flags &= ~(WLAN_STA_AUTH | WLAN_STA_ASSOC); } else if (sta->timeout_next == STA_DISASSOC) sta->flags &= ~WLAN_STA_ASSOC; if (was_assoc && !(sta->flags & WLAN_STA_ASSOC) && !sta->ap) hostap_event_expired_sta(local->dev, sta); if (sta->timeout_next == STA_DEAUTH && sta->aid > 0 && !skb_queue_empty(&sta->tx_buf)) { hostap_set_tim(local, sta->aid, 0); sta->flags &= ~WLAN_STA_TIM; } if (sta->ap) { if (ap->autom_ap_wds) { PDEBUG(DEBUG_AP, "%s: removing automatic WDS " "connection to AP %pM\n", local->dev->name, sta->addr); hostap_wds_link_oper(local, sta->addr, WDS_DEL); } } else if (sta->timeout_next == STA_NULLFUNC) { /* send data frame to poll STA and check whether this frame * is ACKed */ /* FIX: IEEE80211_STYPE_NULLFUNC would be more appropriate, but * it is apparently not retried so TX Exc events are not * received for it */ sta->flags |= WLAN_STA_PENDING_POLL; prism2_send_mgmt(local->dev, IEEE80211_FTYPE_DATA | IEEE80211_STYPE_DATA, NULL, 0, sta->addr, ap->tx_callback_poll); } else { int deauth = sta->timeout_next == STA_DEAUTH; __le16 resp; PDEBUG(DEBUG_AP, "%s: sending %s info to STA %pM" "(last=%lu, jiffies=%lu)\n", local->dev->name, deauth ? "deauthentication" : "disassociation", sta->addr, sta->last_rx, jiffies); resp = cpu_to_le16(deauth ? WLAN_REASON_PREV_AUTH_NOT_VALID : WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY); prism2_send_mgmt(local->dev, IEEE80211_FTYPE_MGMT | (deauth ? IEEE80211_STYPE_DEAUTH : IEEE80211_STYPE_DISASSOC), (char *) &resp, 2, sta->addr, 0); } if (sta->timeout_next == STA_DEAUTH) { if (sta->flags & WLAN_STA_PERM) { PDEBUG(DEBUG_AP, "%s: STA %pM" " would have been removed, " "but it has 'perm' flag\n", local->dev->name, sta->addr); } else ap_free_sta(ap, sta); return; } if (sta->timeout_next == STA_NULLFUNC) { sta->timeout_next = STA_DISASSOC; sta->timer.expires = jiffies + AP_DISASSOC_DELAY; } else { sta->timeout_next = STA_DEAUTH; sta->timer.expires = jiffies + AP_DEAUTH_DELAY; } add_timer(&sta->timer); } void hostap_deauth_all_stas(struct net_device *dev, struct ap_data *ap, int resend) { u8 addr[ETH_ALEN]; __le16 resp; int i; PDEBUG(DEBUG_AP, "%s: Deauthenticate all stations\n", dev->name); memset(addr, 0xff, ETH_ALEN); resp = cpu_to_le16(WLAN_REASON_PREV_AUTH_NOT_VALID); /* deauth message sent; try to resend it few times; the message is * broadcast, so it may be delayed until next DTIM; there is not much * else we can do at this point since the driver is going to be shut * down */ for (i = 0; i < 5; i++) { prism2_send_mgmt(dev, IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_DEAUTH, (char *) &resp, 2, addr, 0); if (!resend || ap->num_sta <= 0) return; mdelay(50); } } static int ap_control_proc_read(char *page, char **start, off_t off, int count, int *eof, void *data) { char *p = page; struct ap_data *ap = (struct ap_data *) data; char *policy_txt; struct mac_entry *entry; if (off != 0) { *eof = 1; return 0; } switch (ap->mac_restrictions.policy) { case MAC_POLICY_OPEN: policy_txt = "open"; break; case MAC_POLICY_ALLOW: policy_txt = "allow"; break; case MAC_POLICY_DENY: policy_txt = "deny"; break; default: policy_txt = "unknown"; break; } p += sprintf(p, "MAC policy: %s\n", policy_txt); p += sprintf(p, "MAC entries: %u\n", ap->mac_restrictions.entries); p += sprintf(p, "MAC list:\n"); spin_lock_bh(&ap->mac_restrictions.lock); list_for_each_entry(entry, &ap->mac_restrictions.mac_list, list) { if (p - page > PAGE_SIZE - 80) { p += sprintf(p, "All entries did not fit one page.\n"); break; } p += sprintf(p, "%pM\n", entry->addr); } spin_unlock_bh(&ap->mac_restrictions.lock); return (p - page); } int ap_control_add_mac(struct mac_restrictions *mac_restrictions, u8 *mac) { struct mac_entry *entry; entry = kmalloc(sizeof(struct mac_entry), GFP_KERNEL); if (entry == NULL) return -1; memcpy(entry->addr, mac, ETH_ALEN); spin_lock_bh(&mac_restrictions->lock); list_add_tail(&entry->list, &mac_restrictions->mac_list); mac_restrictions->entries++; spin_unlock_bh(&mac_restrictions->lock); return 0; } int ap_control_del_mac(struct mac_restrictions *mac_restrictions, u8 *mac) { struct list_head *ptr; struct mac_entry *entry; spin_lock_bh(&mac_restrictions->lock); for (ptr = mac_restrictions->mac_list.next; ptr != &mac_restrictions->mac_list; ptr = ptr->next) { entry = list_entry(ptr, struct mac_entry, list); if (memcmp(entry->addr, mac, ETH_ALEN) == 0) { list_del(ptr); kfree(entry); mac_restrictions->entries--; spin_unlock_bh(&mac_restrictions->lock); return 0; } } spin_unlock_bh(&mac_restrictions->lock); return -1; } static int ap_control_mac_deny(struct mac_restrictions *mac_restrictions, u8 *mac) { struct mac_entry *entry; int found = 0; if (mac_restrictions->policy == MAC_POLICY_OPEN) return 0; spin_lock_bh(&mac_restrictions->lock); list_for_each_entry(entry, &mac_restrictions->mac_list, list) { if (memcmp(entry->addr, mac, ETH_ALEN) == 0) { found = 1; break; } } spin_unlock_bh(&mac_restrictions->lock); if (mac_restrictions->policy == MAC_POLICY_ALLOW) return !found; else return found; } void ap_control_flush_macs(struct mac_restrictions *mac_restrictions) { struct list_head *ptr, *n; struct mac_entry *entry; if (mac_restrictions->entries == 0) return; spin_lock_bh(&mac_restrictions->lock); for (ptr = mac_restrictions->mac_list.next, n = ptr->next; ptr != &mac_restrictions->mac_list; ptr = n, n = ptr->next) { entry = list_entry(ptr, struct mac_entry, list); list_del(ptr); kfree(entry); } mac_restrictions->entries = 0; spin_unlock_bh(&mac_restrictions->lock); } int ap_control_kick_mac(struct ap_data *ap, struct net_device *dev, u8 *mac) { struct sta_info *sta; __le16 resp; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, mac); if (sta) { ap_sta_hash_del(ap, sta); list_del(&sta->list); } spin_unlock_bh(&ap->sta_table_lock); if (!sta) return -EINVAL; resp = cpu_to_le16(WLAN_REASON_PREV_AUTH_NOT_VALID); prism2_send_mgmt(dev, IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_DEAUTH, (char *) &resp, 2, sta->addr, 0); if ((sta->flags & WLAN_STA_ASSOC) && !sta->ap) hostap_event_expired_sta(dev, sta); ap_free_sta(ap, sta); return 0; } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ void ap_control_kickall(struct ap_data *ap) { struct list_head *ptr, *n; struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); for (ptr = ap->sta_list.next, n = ptr->next; ptr != &ap->sta_list; ptr = n, n = ptr->next) { sta = list_entry(ptr, struct sta_info, list); ap_sta_hash_del(ap, sta); list_del(&sta->list); if ((sta->flags & WLAN_STA_ASSOC) && !sta->ap && sta->local) hostap_event_expired_sta(sta->local->dev, sta); ap_free_sta(ap, sta); } spin_unlock_bh(&ap->sta_table_lock); } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT #define PROC_LIMIT (PAGE_SIZE - 80) static int prism2_ap_proc_read(char *page, char **start, off_t off, int count, int *eof, void *data) { char *p = page; struct ap_data *ap = (struct ap_data *) data; struct sta_info *sta; int i; if (off > PROC_LIMIT) { *eof = 1; return 0; } p += sprintf(p, "# BSSID CHAN SIGNAL NOISE RATE SSID FLAGS\n"); spin_lock_bh(&ap->sta_table_lock); list_for_each_entry(sta, &ap->sta_list, list) { if (!sta->ap) continue; p += sprintf(p, "%pM %d %d %d %d '", sta->addr, sta->u.ap.channel, sta->last_rx_signal, sta->last_rx_silence, sta->last_rx_rate); for (i = 0; i < sta->u.ap.ssid_len; i++) p += sprintf(p, ((sta->u.ap.ssid[i] >= 32 && sta->u.ap.ssid[i] < 127) ? "%c" : "<%02x>"), sta->u.ap.ssid[i]); p += sprintf(p, "'"); if (sta->capability & WLAN_CAPABILITY_ESS) p += sprintf(p, " [ESS]"); if (sta->capability & WLAN_CAPABILITY_IBSS) p += sprintf(p, " [IBSS]"); if (sta->capability & WLAN_CAPABILITY_PRIVACY) p += sprintf(p, " [WEP]"); p += sprintf(p, "\n"); if ((p - page) > PROC_LIMIT) { printk(KERN_DEBUG "hostap: ap proc did not fit\n"); break; } } spin_unlock_bh(&ap->sta_table_lock); if ((p - page) <= off) { *eof = 1; return 0; } *start = page + off; return (p - page - off); } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ void hostap_check_sta_fw_version(struct ap_data *ap, int sta_fw_ver) { if (!ap) return; if (sta_fw_ver == PRISM2_FW_VER(0,8,0)) { PDEBUG(DEBUG_AP, "Using data::nullfunc ACK workaround - " "firmware upgrade recommended\n"); ap->nullfunc_ack = 1; } else ap->nullfunc_ack = 0; if (sta_fw_ver == PRISM2_FW_VER(1,4,2)) { printk(KERN_WARNING "%s: Warning: secondary station firmware " "version 1.4.2 does not seem to work in Host AP mode\n", ap->local->dev->name); } } /* Called only as a tasklet (software IRQ) */ static void hostap_ap_tx_cb(struct sk_buff *skb, int ok, void *data) { struct ap_data *ap = data; struct ieee80211_hdr *hdr; if (!ap->local->hostapd || !ap->local->apdev) { dev_kfree_skb(skb); return; } /* Pass the TX callback frame to the hostapd; use 802.11 header version * 1 to indicate failure (no ACK) and 2 success (frame ACKed) */ hdr = (struct ieee80211_hdr *) skb->data; hdr->frame_control &= cpu_to_le16(~IEEE80211_FCTL_VERS); hdr->frame_control |= cpu_to_le16(ok ? BIT(1) : BIT(0)); skb->dev = ap->local->apdev; skb_pull(skb, hostap_80211_get_hdrlen(hdr->frame_control)); skb->pkt_type = PACKET_OTHERHOST; skb->protocol = cpu_to_be16(ETH_P_802_2); memset(skb->cb, 0, sizeof(skb->cb)); netif_rx(skb); } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT /* Called only as a tasklet (software IRQ) */ static void hostap_ap_tx_cb_auth(struct sk_buff *skb, int ok, void *data) { struct ap_data *ap = data; struct net_device *dev = ap->local->dev; struct ieee80211_hdr *hdr; u16 auth_alg, auth_transaction, status; __le16 *pos; struct sta_info *sta = NULL; char *txt = NULL; if (ap->local->hostapd) { dev_kfree_skb(skb); return; } hdr = (struct ieee80211_hdr *) skb->data; if (!ieee80211_is_auth(hdr->frame_control) || skb->len < IEEE80211_MGMT_HDR_LEN + 6) { printk(KERN_DEBUG "%s: hostap_ap_tx_cb_auth received invalid " "frame\n", dev->name); dev_kfree_skb(skb); return; } pos = (__le16 *) (skb->data + IEEE80211_MGMT_HDR_LEN); auth_alg = le16_to_cpu(*pos++); auth_transaction = le16_to_cpu(*pos++); status = le16_to_cpu(*pos++); if (!ok) { txt = "frame was not ACKed"; goto done; } spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, hdr->addr1); if (sta) atomic_inc(&sta->users); spin_unlock(&ap->sta_table_lock); if (!sta) { txt = "STA not found"; goto done; } if (status == WLAN_STATUS_SUCCESS && ((auth_alg == WLAN_AUTH_OPEN && auth_transaction == 2) || (auth_alg == WLAN_AUTH_SHARED_KEY && auth_transaction == 4))) { txt = "STA authenticated"; sta->flags |= WLAN_STA_AUTH; sta->last_auth = jiffies; } else if (status != WLAN_STATUS_SUCCESS) txt = "authentication failed"; done: if (sta) atomic_dec(&sta->users); if (txt) { PDEBUG(DEBUG_AP, "%s: %pM auth_cb - alg=%d " "trans#=%d status=%d - %s\n", dev->name, hdr->addr1, auth_alg, auth_transaction, status, txt); } dev_kfree_skb(skb); } /* Called only as a tasklet (software IRQ) */ static void hostap_ap_tx_cb_assoc(struct sk_buff *skb, int ok, void *data) { struct ap_data *ap = data; struct net_device *dev = ap->local->dev; struct ieee80211_hdr *hdr; u16 status; __le16 *pos; struct sta_info *sta = NULL; char *txt = NULL; if (ap->local->hostapd) { dev_kfree_skb(skb); return; } hdr = (struct ieee80211_hdr *) skb->data; if ((!ieee80211_is_assoc_resp(hdr->frame_control) && !ieee80211_is_reassoc_resp(hdr->frame_control)) || skb->len < IEEE80211_MGMT_HDR_LEN + 4) { printk(KERN_DEBUG "%s: hostap_ap_tx_cb_assoc received invalid " "frame\n", dev->name); dev_kfree_skb(skb); return; } if (!ok) { txt = "frame was not ACKed"; goto done; } spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, hdr->addr1); if (sta) atomic_inc(&sta->users); spin_unlock(&ap->sta_table_lock); if (!sta) { txt = "STA not found"; goto done; } pos = (__le16 *) (skb->data + IEEE80211_MGMT_HDR_LEN); pos++; status = le16_to_cpu(*pos++); if (status == WLAN_STATUS_SUCCESS) { if (!(sta->flags & WLAN_STA_ASSOC)) hostap_event_new_sta(dev, sta); txt = "STA associated"; sta->flags |= WLAN_STA_ASSOC; sta->last_assoc = jiffies; } else txt = "association failed"; done: if (sta) atomic_dec(&sta->users); if (txt) { PDEBUG(DEBUG_AP, "%s: %pM assoc_cb - %s\n", dev->name, hdr->addr1, txt); } dev_kfree_skb(skb); } /* Called only as a tasklet (software IRQ); TX callback for poll frames used * in verifying whether the STA is still present. */ static void hostap_ap_tx_cb_poll(struct sk_buff *skb, int ok, void *data) { struct ap_data *ap = data; struct ieee80211_hdr *hdr; struct sta_info *sta; if (skb->len < 24) goto fail; hdr = (struct ieee80211_hdr *) skb->data; if (ok) { spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, hdr->addr1); if (sta) sta->flags &= ~WLAN_STA_PENDING_POLL; spin_unlock(&ap->sta_table_lock); } else { PDEBUG(DEBUG_AP, "%s: STA %pM did not ACK activity poll frame\n", ap->local->dev->name, hdr->addr1); } fail: dev_kfree_skb(skb); } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ void hostap_init_data(local_info_t *local) { struct ap_data *ap = local->ap; if (ap == NULL) { printk(KERN_WARNING "hostap_init_data: ap == NULL\n"); return; } memset(ap, 0, sizeof(struct ap_data)); ap->local = local; ap->ap_policy = GET_INT_PARM(other_ap_policy, local->card_idx); ap->bridge_packets = GET_INT_PARM(ap_bridge_packets, local->card_idx); ap->max_inactivity = GET_INT_PARM(ap_max_inactivity, local->card_idx) * HZ; ap->autom_ap_wds = GET_INT_PARM(autom_ap_wds, local->card_idx); spin_lock_init(&ap->sta_table_lock); INIT_LIST_HEAD(&ap->sta_list); /* Initialize task queue structure for AP management */ INIT_WORK(&local->ap->add_sta_proc_queue, handle_add_proc_queue); ap->tx_callback_idx = hostap_tx_callback_register(local, hostap_ap_tx_cb, ap); if (ap->tx_callback_idx == 0) printk(KERN_WARNING "%s: failed to register TX callback for " "AP\n", local->dev->name); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT INIT_WORK(&local->ap->wds_oper_queue, handle_wds_oper_queue); ap->tx_callback_auth = hostap_tx_callback_register(local, hostap_ap_tx_cb_auth, ap); ap->tx_callback_assoc = hostap_tx_callback_register(local, hostap_ap_tx_cb_assoc, ap); ap->tx_callback_poll = hostap_tx_callback_register(local, hostap_ap_tx_cb_poll, ap); if (ap->tx_callback_auth == 0 || ap->tx_callback_assoc == 0 || ap->tx_callback_poll == 0) printk(KERN_WARNING "%s: failed to register TX callback for " "AP\n", local->dev->name); spin_lock_init(&ap->mac_restrictions.lock); INIT_LIST_HEAD(&ap->mac_restrictions.mac_list); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ ap->initialized = 1; } void hostap_init_ap_proc(local_info_t *local) { struct ap_data *ap = local->ap; ap->proc = local->proc; if (ap->proc == NULL) return; #ifndef PRISM2_NO_PROCFS_DEBUG create_proc_read_entry("ap_debug", 0, ap->proc, ap_debug_proc_read, ap); #endif /* PRISM2_NO_PROCFS_DEBUG */ #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT create_proc_read_entry("ap_control", 0, ap->proc, ap_control_proc_read, ap); create_proc_read_entry("ap", 0, ap->proc, prism2_ap_proc_read, ap); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ } void hostap_free_data(struct ap_data *ap) { struct sta_info *n, *sta; if (ap == NULL || !ap->initialized) { printk(KERN_DEBUG "hostap_free_data: ap has not yet been " "initialized - skip resource freeing\n"); return; } flush_work_sync(&ap->add_sta_proc_queue); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT flush_work_sync(&ap->wds_oper_queue); if (ap->crypt) ap->crypt->deinit(ap->crypt_priv); ap->crypt = ap->crypt_priv = NULL; #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ list_for_each_entry_safe(sta, n, &ap->sta_list, list) { ap_sta_hash_del(ap, sta); list_del(&sta->list); if ((sta->flags & WLAN_STA_ASSOC) && !sta->ap && sta->local) hostap_event_expired_sta(sta->local->dev, sta); ap_free_sta(ap, sta); } #ifndef PRISM2_NO_PROCFS_DEBUG if (ap->proc != NULL) { remove_proc_entry("ap_debug", ap->proc); } #endif /* PRISM2_NO_PROCFS_DEBUG */ #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT if (ap->proc != NULL) { remove_proc_entry("ap", ap->proc); remove_proc_entry("ap_control", ap->proc); } ap_control_flush_macs(&ap->mac_restrictions); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ ap->initialized = 0; } /* caller should have mutex for AP STA list handling */ static struct sta_info* ap_get_sta(struct ap_data *ap, u8 *sta) { struct sta_info *s; s = ap->sta_hash[STA_HASH(sta)]; while (s != NULL && memcmp(s->addr, sta, ETH_ALEN) != 0) s = s->hnext; return s; } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT /* Called from timer handler and from scheduled AP queue handlers */ static void prism2_send_mgmt(struct net_device *dev, u16 type_subtype, char *body, int body_len, u8 *addr, u16 tx_cb_idx) { struct hostap_interface *iface; local_info_t *local; struct ieee80211_hdr *hdr; u16 fc; struct sk_buff *skb; struct hostap_skb_tx_data *meta; int hdrlen; iface = netdev_priv(dev); local = iface->local; dev = local->dev; /* always use master radio device */ iface = netdev_priv(dev); if (!(dev->flags & IFF_UP)) { PDEBUG(DEBUG_AP, "%s: prism2_send_mgmt - device is not UP - " "cannot send frame\n", dev->name); return; } skb = dev_alloc_skb(sizeof(*hdr) + body_len); if (skb == NULL) { PDEBUG(DEBUG_AP, "%s: prism2_send_mgmt failed to allocate " "skb\n", dev->name); return; } fc = type_subtype; hdrlen = hostap_80211_get_hdrlen(cpu_to_le16(type_subtype)); hdr = (struct ieee80211_hdr *) skb_put(skb, hdrlen); if (body) memcpy(skb_put(skb, body_len), body, body_len); memset(hdr, 0, hdrlen); /* FIX: ctrl::ack sending used special HFA384X_TX_CTRL_802_11 * tx_control instead of using local->tx_control */ memcpy(hdr->addr1, addr, ETH_ALEN); /* DA / RA */ if (ieee80211_is_data(hdr->frame_control)) { fc |= IEEE80211_FCTL_FROMDS; memcpy(hdr->addr2, dev->dev_addr, ETH_ALEN); /* BSSID */ memcpy(hdr->addr3, dev->dev_addr, ETH_ALEN); /* SA */ } else if (ieee80211_is_ctl(hdr->frame_control)) { /* control:ACK does not have addr2 or addr3 */ memset(hdr->addr2, 0, ETH_ALEN); memset(hdr->addr3, 0, ETH_ALEN); } else { memcpy(hdr->addr2, dev->dev_addr, ETH_ALEN); /* SA */ memcpy(hdr->addr3, dev->dev_addr, ETH_ALEN); /* BSSID */ } hdr->frame_control = cpu_to_le16(fc); meta = (struct hostap_skb_tx_data *) skb->cb; memset(meta, 0, sizeof(*meta)); meta->magic = HOSTAP_SKB_TX_DATA_MAGIC; meta->iface = iface; meta->tx_cb_idx = tx_cb_idx; skb->dev = dev; skb_reset_mac_header(skb); skb_reset_network_header(skb); dev_queue_xmit(skb); } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ static int prism2_sta_proc_read(char *page, char **start, off_t off, int count, int *eof, void *data) { char *p = page; struct sta_info *sta = (struct sta_info *) data; int i; /* FIX: possible race condition.. the STA data could have just expired, * but proc entry was still here so that the read could have started; * some locking should be done here.. */ if (off != 0) { *eof = 1; return 0; } p += sprintf(p, "%s=%pM\nusers=%d\naid=%d\n" "flags=0x%04x%s%s%s%s%s%s%s\n" "capability=0x%02x\nlisten_interval=%d\nsupported_rates=", sta->ap ? "AP" : "STA", sta->addr, atomic_read(&sta->users), sta->aid, sta->flags, sta->flags & WLAN_STA_AUTH ? " AUTH" : "", sta->flags & WLAN_STA_ASSOC ? " ASSOC" : "", sta->flags & WLAN_STA_PS ? " PS" : "", sta->flags & WLAN_STA_TIM ? " TIM" : "", sta->flags & WLAN_STA_PERM ? " PERM" : "", sta->flags & WLAN_STA_AUTHORIZED ? " AUTHORIZED" : "", sta->flags & WLAN_STA_PENDING_POLL ? " POLL" : "", sta->capability, sta->listen_interval); /* supported_rates: 500 kbit/s units with msb ignored */ for (i = 0; i < sizeof(sta->supported_rates); i++) if (sta->supported_rates[i] != 0) p += sprintf(p, "%d%sMbps ", (sta->supported_rates[i] & 0x7f) / 2, sta->supported_rates[i] & 1 ? ".5" : ""); p += sprintf(p, "\njiffies=%lu\nlast_auth=%lu\nlast_assoc=%lu\n" "last_rx=%lu\nlast_tx=%lu\nrx_packets=%lu\n" "tx_packets=%lu\n" "rx_bytes=%lu\ntx_bytes=%lu\nbuffer_count=%d\n" "last_rx: silence=%d dBm signal=%d dBm rate=%d%s Mbps\n" "tx_rate=%d\ntx[1M]=%d\ntx[2M]=%d\ntx[5.5M]=%d\n" "tx[11M]=%d\n" "rx[1M]=%d\nrx[2M]=%d\nrx[5.5M]=%d\nrx[11M]=%d\n", jiffies, sta->last_auth, sta->last_assoc, sta->last_rx, sta->last_tx, sta->rx_packets, sta->tx_packets, sta->rx_bytes, sta->tx_bytes, skb_queue_len(&sta->tx_buf), sta->last_rx_silence, sta->last_rx_signal, sta->last_rx_rate / 10, sta->last_rx_rate % 10 ? ".5" : "", sta->tx_rate, sta->tx_count[0], sta->tx_count[1], sta->tx_count[2], sta->tx_count[3], sta->rx_count[0], sta->rx_count[1], sta->rx_count[2], sta->rx_count[3]); if (sta->crypt && sta->crypt->ops && sta->crypt->ops->print_stats) p = sta->crypt->ops->print_stats(p, sta->crypt->priv); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT if (sta->ap) { if (sta->u.ap.channel >= 0) p += sprintf(p, "channel=%d\n", sta->u.ap.channel); p += sprintf(p, "ssid="); for (i = 0; i < sta->u.ap.ssid_len; i++) p += sprintf(p, ((sta->u.ap.ssid[i] >= 32 && sta->u.ap.ssid[i] < 127) ? "%c" : "<%02x>"), sta->u.ap.ssid[i]); p += sprintf(p, "\n"); } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ return (p - page); } static void handle_add_proc_queue(struct work_struct *work) { struct ap_data *ap = container_of(work, struct ap_data, add_sta_proc_queue); struct sta_info *sta; char name[20]; struct add_sta_proc_data *entry, *prev; entry = ap->add_sta_proc_entries; ap->add_sta_proc_entries = NULL; while (entry) { spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, entry->addr); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&ap->sta_table_lock); if (sta) { sprintf(name, "%pM", sta->addr); sta->proc = create_proc_read_entry( name, 0, ap->proc, prism2_sta_proc_read, sta); atomic_dec(&sta->users); } prev = entry; entry = entry->next; kfree(prev); } } static struct sta_info * ap_add_sta(struct ap_data *ap, u8 *addr) { struct sta_info *sta; sta = kzalloc(sizeof(struct sta_info), GFP_ATOMIC); if (sta == NULL) { PDEBUG(DEBUG_AP, "AP: kmalloc failed\n"); return NULL; } /* initialize STA info data */ sta->local = ap->local; skb_queue_head_init(&sta->tx_buf); memcpy(sta->addr, addr, ETH_ALEN); atomic_inc(&sta->users); spin_lock_bh(&ap->sta_table_lock); list_add(&sta->list, &ap->sta_list); ap->num_sta++; ap_sta_hash_add(ap, sta); spin_unlock_bh(&ap->sta_table_lock); if (ap->proc) { struct add_sta_proc_data *entry; /* schedule a non-interrupt context process to add a procfs * entry for the STA since procfs code use GFP_KERNEL */ entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (entry) { memcpy(entry->addr, sta->addr, ETH_ALEN); entry->next = ap->add_sta_proc_entries; ap->add_sta_proc_entries = entry; schedule_work(&ap->add_sta_proc_queue); } else printk(KERN_DEBUG "Failed to add STA proc data\n"); } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT init_timer(&sta->timer); sta->timer.expires = jiffies + ap->max_inactivity; sta->timer.data = (unsigned long) sta; sta->timer.function = ap_handle_timer; if (!ap->local->hostapd) add_timer(&sta->timer); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ return sta; } static int ap_tx_rate_ok(int rateidx, struct sta_info *sta, local_info_t *local) { if (rateidx > sta->tx_max_rate || !(sta->tx_supp_rates & (1 << rateidx))) return 0; if (local->tx_rate_control != 0 && !(local->tx_rate_control & (1 << rateidx))) return 0; return 1; } static void prism2_check_tx_rates(struct sta_info *sta) { int i; sta->tx_supp_rates = 0; for (i = 0; i < sizeof(sta->supported_rates); i++) { if ((sta->supported_rates[i] & 0x7f) == 2) sta->tx_supp_rates |= WLAN_RATE_1M; if ((sta->supported_rates[i] & 0x7f) == 4) sta->tx_supp_rates |= WLAN_RATE_2M; if ((sta->supported_rates[i] & 0x7f) == 11) sta->tx_supp_rates |= WLAN_RATE_5M5; if ((sta->supported_rates[i] & 0x7f) == 22) sta->tx_supp_rates |= WLAN_RATE_11M; } sta->tx_max_rate = sta->tx_rate = sta->tx_rate_idx = 0; if (sta->tx_supp_rates & WLAN_RATE_1M) { sta->tx_max_rate = 0; if (ap_tx_rate_ok(0, sta, sta->local)) { sta->tx_rate = 10; sta->tx_rate_idx = 0; } } if (sta->tx_supp_rates & WLAN_RATE_2M) { sta->tx_max_rate = 1; if (ap_tx_rate_ok(1, sta, sta->local)) { sta->tx_rate = 20; sta->tx_rate_idx = 1; } } if (sta->tx_supp_rates & WLAN_RATE_5M5) { sta->tx_max_rate = 2; if (ap_tx_rate_ok(2, sta, sta->local)) { sta->tx_rate = 55; sta->tx_rate_idx = 2; } } if (sta->tx_supp_rates & WLAN_RATE_11M) { sta->tx_max_rate = 3; if (ap_tx_rate_ok(3, sta, sta->local)) { sta->tx_rate = 110; sta->tx_rate_idx = 3; } } } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT static void ap_crypt_init(struct ap_data *ap) { ap->crypt = lib80211_get_crypto_ops("WEP"); if (ap->crypt) { if (ap->crypt->init) { ap->crypt_priv = ap->crypt->init(0); if (ap->crypt_priv == NULL) ap->crypt = NULL; else { u8 key[WEP_KEY_LEN]; get_random_bytes(key, WEP_KEY_LEN); ap->crypt->set_key(key, WEP_KEY_LEN, NULL, ap->crypt_priv); } } } if (ap->crypt == NULL) { printk(KERN_WARNING "AP could not initialize WEP: load module " "lib80211_crypt_wep.ko\n"); } } /* Generate challenge data for shared key authentication. IEEE 802.11 specifies * that WEP algorithm is used for generating challenge. This should be unique, * but otherwise there is not really need for randomness etc. Initialize WEP * with pseudo random key and then use increasing IV to get unique challenge * streams. * * Called only as a scheduled task for pending AP frames. */ static char * ap_auth_make_challenge(struct ap_data *ap) { char *tmpbuf; struct sk_buff *skb; if (ap->crypt == NULL) { ap_crypt_init(ap); if (ap->crypt == NULL) return NULL; } tmpbuf = kmalloc(WLAN_AUTH_CHALLENGE_LEN, GFP_ATOMIC); if (tmpbuf == NULL) { PDEBUG(DEBUG_AP, "AP: kmalloc failed for challenge\n"); return NULL; } skb = dev_alloc_skb(WLAN_AUTH_CHALLENGE_LEN + ap->crypt->extra_mpdu_prefix_len + ap->crypt->extra_mpdu_postfix_len); if (skb == NULL) { kfree(tmpbuf); return NULL; } skb_reserve(skb, ap->crypt->extra_mpdu_prefix_len); memset(skb_put(skb, WLAN_AUTH_CHALLENGE_LEN), 0, WLAN_AUTH_CHALLENGE_LEN); if (ap->crypt->encrypt_mpdu(skb, 0, ap->crypt_priv)) { dev_kfree_skb(skb); kfree(tmpbuf); return NULL; } skb_copy_from_linear_data_offset(skb, ap->crypt->extra_mpdu_prefix_len, tmpbuf, WLAN_AUTH_CHALLENGE_LEN); dev_kfree_skb(skb); return tmpbuf; } /* Called only as a scheduled task for pending AP frames. */ static void handle_authen(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct net_device *dev = local->dev; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; size_t hdrlen; struct ap_data *ap = local->ap; char body[8 + WLAN_AUTH_CHALLENGE_LEN], *challenge = NULL; int len, olen; u16 auth_alg, auth_transaction, status_code; __le16 *pos; u16 resp = WLAN_STATUS_SUCCESS; struct sta_info *sta = NULL; struct lib80211_crypt_data *crypt; char *txt = ""; len = skb->len - IEEE80211_MGMT_HDR_LEN; hdrlen = hostap_80211_get_hdrlen(hdr->frame_control); if (len < 6) { PDEBUG(DEBUG_AP, "%s: handle_authen - too short payload " "(len=%d) from %pM\n", dev->name, len, hdr->addr2); return; } spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&local->ap->sta_table_lock); if (sta && sta->crypt) crypt = sta->crypt; else { int idx = 0; if (skb->len >= hdrlen + 3) idx = skb->data[hdrlen + 3] >> 6; crypt = local->crypt_info.crypt[idx]; } pos = (__le16 *) (skb->data + IEEE80211_MGMT_HDR_LEN); auth_alg = __le16_to_cpu(*pos); pos++; auth_transaction = __le16_to_cpu(*pos); pos++; status_code = __le16_to_cpu(*pos); pos++; if (memcmp(dev->dev_addr, hdr->addr2, ETH_ALEN) == 0 || ap_control_mac_deny(&ap->mac_restrictions, hdr->addr2)) { txt = "authentication denied"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (((local->auth_algs & PRISM2_AUTH_OPEN) && auth_alg == WLAN_AUTH_OPEN) || ((local->auth_algs & PRISM2_AUTH_SHARED_KEY) && crypt && auth_alg == WLAN_AUTH_SHARED_KEY)) { } else { txt = "unsupported algorithm"; resp = WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG; goto fail; } if (len >= 8) { u8 *u = (u8 *) pos; if (*u == WLAN_EID_CHALLENGE) { if (*(u + 1) != WLAN_AUTH_CHALLENGE_LEN) { txt = "invalid challenge len"; resp = WLAN_STATUS_CHALLENGE_FAIL; goto fail; } if (len - 8 < WLAN_AUTH_CHALLENGE_LEN) { txt = "challenge underflow"; resp = WLAN_STATUS_CHALLENGE_FAIL; goto fail; } challenge = (char *) (u + 2); } } if (sta && sta->ap) { if (time_after(jiffies, sta->u.ap.last_beacon + (10 * sta->listen_interval * HZ) / 1024)) { PDEBUG(DEBUG_AP, "%s: no beacons received for a while," " assuming AP %pM is now STA\n", dev->name, sta->addr); sta->ap = 0; sta->flags = 0; sta->u.sta.challenge = NULL; } else { txt = "AP trying to authenticate?"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } } if ((auth_alg == WLAN_AUTH_OPEN && auth_transaction == 1) || (auth_alg == WLAN_AUTH_SHARED_KEY && (auth_transaction == 1 || (auth_transaction == 3 && sta != NULL && sta->u.sta.challenge != NULL)))) { } else { txt = "unknown authentication transaction number"; resp = WLAN_STATUS_UNKNOWN_AUTH_TRANSACTION; goto fail; } if (sta == NULL) { txt = "new STA"; if (local->ap->num_sta >= MAX_STA_COUNT) { /* FIX: might try to remove some old STAs first? */ txt = "no more room for new STAs"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } sta = ap_add_sta(local->ap, hdr->addr2); if (sta == NULL) { txt = "ap_add_sta failed"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } } switch (auth_alg) { case WLAN_AUTH_OPEN: txt = "authOK"; /* IEEE 802.11 standard is not completely clear about * whether STA is considered authenticated after * authentication OK frame has been send or after it * has been ACKed. In order to reduce interoperability * issues, mark the STA authenticated before ACK. */ sta->flags |= WLAN_STA_AUTH; break; case WLAN_AUTH_SHARED_KEY: if (auth_transaction == 1) { if (sta->u.sta.challenge == NULL) { sta->u.sta.challenge = ap_auth_make_challenge(local->ap); if (sta->u.sta.challenge == NULL) { resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } } } else { if (sta->u.sta.challenge == NULL || challenge == NULL || memcmp(sta->u.sta.challenge, challenge, WLAN_AUTH_CHALLENGE_LEN) != 0 || !ieee80211_has_protected(hdr->frame_control)) { txt = "challenge response incorrect"; resp = WLAN_STATUS_CHALLENGE_FAIL; goto fail; } txt = "challenge OK - authOK"; /* IEEE 802.11 standard is not completely clear about * whether STA is considered authenticated after * authentication OK frame has been send or after it * has been ACKed. In order to reduce interoperability * issues, mark the STA authenticated before ACK. */ sta->flags |= WLAN_STA_AUTH; kfree(sta->u.sta.challenge); sta->u.sta.challenge = NULL; } break; } fail: pos = (__le16 *) body; *pos = cpu_to_le16(auth_alg); pos++; *pos = cpu_to_le16(auth_transaction + 1); pos++; *pos = cpu_to_le16(resp); /* status_code */ pos++; olen = 6; if (resp == WLAN_STATUS_SUCCESS && sta != NULL && sta->u.sta.challenge != NULL && auth_alg == WLAN_AUTH_SHARED_KEY && auth_transaction == 1) { u8 *tmp = (u8 *) pos; *tmp++ = WLAN_EID_CHALLENGE; *tmp++ = WLAN_AUTH_CHALLENGE_LEN; pos++; memcpy(pos, sta->u.sta.challenge, WLAN_AUTH_CHALLENGE_LEN); olen += 2 + WLAN_AUTH_CHALLENGE_LEN; } prism2_send_mgmt(dev, IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_AUTH, body, olen, hdr->addr2, ap->tx_callback_auth); if (sta) { sta->last_rx = jiffies; atomic_dec(&sta->users); } if (resp) { PDEBUG(DEBUG_AP, "%s: %pM auth (alg=%d " "trans#=%d stat=%d len=%d fc=%04x) ==> %d (%s)\n", dev->name, hdr->addr2, auth_alg, auth_transaction, status_code, len, le16_to_cpu(hdr->frame_control), resp, txt); } } /* Called only as a scheduled task for pending AP frames. */ static void handle_assoc(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats, int reassoc) { struct net_device *dev = local->dev; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; char body[12], *p, *lpos; int len, left; __le16 *pos; u16 resp = WLAN_STATUS_SUCCESS; struct sta_info *sta = NULL; int send_deauth = 0; char *txt = ""; u8 prev_ap[ETH_ALEN]; left = len = skb->len - IEEE80211_MGMT_HDR_LEN; if (len < (reassoc ? 10 : 4)) { PDEBUG(DEBUG_AP, "%s: handle_assoc - too short payload " "(len=%d, reassoc=%d) from %pM\n", dev->name, len, reassoc, hdr->addr2); return; } spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta == NULL || (sta->flags & WLAN_STA_AUTH) == 0) { spin_unlock_bh(&local->ap->sta_table_lock); txt = "trying to associate before authentication"; send_deauth = 1; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; sta = NULL; /* do not decrement sta->users */ goto fail; } atomic_inc(&sta->users); spin_unlock_bh(&local->ap->sta_table_lock); pos = (__le16 *) (skb->data + IEEE80211_MGMT_HDR_LEN); sta->capability = __le16_to_cpu(*pos); pos++; left -= 2; sta->listen_interval = __le16_to_cpu(*pos); pos++; left -= 2; if (reassoc) { memcpy(prev_ap, pos, ETH_ALEN); pos++; pos++; pos++; left -= 6; } else memset(prev_ap, 0, ETH_ALEN); if (left >= 2) { unsigned int ileft; unsigned char *u = (unsigned char *) pos; if (*u == WLAN_EID_SSID) { u++; left--; ileft = *u; u++; left--; if (ileft > left || ileft > MAX_SSID_LEN) { txt = "SSID overflow"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } if (ileft != strlen(local->essid) || memcmp(local->essid, u, ileft) != 0) { txt = "not our SSID"; resp = WLAN_STATUS_ASSOC_DENIED_UNSPEC; goto fail; } u += ileft; left -= ileft; } if (left >= 2 && *u == WLAN_EID_SUPP_RATES) { u++; left--; ileft = *u; u++; left--; if (ileft > left || ileft == 0 || ileft > WLAN_SUPP_RATES_MAX) { txt = "SUPP_RATES len error"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } memset(sta->supported_rates, 0, sizeof(sta->supported_rates)); memcpy(sta->supported_rates, u, ileft); prism2_check_tx_rates(sta); u += ileft; left -= ileft; } if (left > 0) { PDEBUG(DEBUG_AP, "%s: assoc from %pM" " with extra data (%d bytes) [", dev->name, hdr->addr2, left); while (left > 0) { PDEBUG2(DEBUG_AP, "<%02x>", *u); u++; left--; } PDEBUG2(DEBUG_AP, "]\n"); } } else { txt = "frame underflow"; resp = WLAN_STATUS_UNSPECIFIED_FAILURE; goto fail; } /* get a unique AID */ if (sta->aid > 0) txt = "OK, old AID"; else { spin_lock_bh(&local->ap->sta_table_lock); for (sta->aid = 1; sta->aid <= MAX_AID_TABLE_SIZE; sta->aid++) if (local->ap->sta_aid[sta->aid - 1] == NULL) break; if (sta->aid > MAX_AID_TABLE_SIZE) { sta->aid = 0; spin_unlock_bh(&local->ap->sta_table_lock); resp = WLAN_STATUS_AP_UNABLE_TO_HANDLE_NEW_STA; txt = "no room for more AIDs"; } else { local->ap->sta_aid[sta->aid - 1] = sta; spin_unlock_bh(&local->ap->sta_table_lock); txt = "OK, new AID"; } } fail: pos = (__le16 *) body; if (send_deauth) { *pos = cpu_to_le16(WLAN_REASON_STA_REQ_ASSOC_WITHOUT_AUTH); pos++; } else { /* FIX: CF-Pollable and CF-PollReq should be set to match the * values in beacons/probe responses */ /* FIX: how about privacy and WEP? */ /* capability */ *pos = cpu_to_le16(WLAN_CAPABILITY_ESS); pos++; /* status_code */ *pos = cpu_to_le16(resp); pos++; *pos = cpu_to_le16((sta && sta->aid > 0 ? sta->aid : 0) | BIT(14) | BIT(15)); /* AID */ pos++; /* Supported rates (Information element) */ p = (char *) pos; *p++ = WLAN_EID_SUPP_RATES; lpos = p; *p++ = 0; /* len */ if (local->tx_rate_control & WLAN_RATE_1M) { *p++ = local->basic_rates & WLAN_RATE_1M ? 0x82 : 0x02; (*lpos)++; } if (local->tx_rate_control & WLAN_RATE_2M) { *p++ = local->basic_rates & WLAN_RATE_2M ? 0x84 : 0x04; (*lpos)++; } if (local->tx_rate_control & WLAN_RATE_5M5) { *p++ = local->basic_rates & WLAN_RATE_5M5 ? 0x8b : 0x0b; (*lpos)++; } if (local->tx_rate_control & WLAN_RATE_11M) { *p++ = local->basic_rates & WLAN_RATE_11M ? 0x96 : 0x16; (*lpos)++; } pos = (__le16 *) p; } prism2_send_mgmt(dev, IEEE80211_FTYPE_MGMT | (send_deauth ? IEEE80211_STYPE_DEAUTH : (reassoc ? IEEE80211_STYPE_REASSOC_RESP : IEEE80211_STYPE_ASSOC_RESP)), body, (u8 *) pos - (u8 *) body, hdr->addr2, send_deauth ? 0 : local->ap->tx_callback_assoc); if (sta) { if (resp == WLAN_STATUS_SUCCESS) { sta->last_rx = jiffies; /* STA will be marked associated from TX callback, if * AssocResp is ACKed */ } atomic_dec(&sta->users); } #if 0 PDEBUG(DEBUG_AP, "%s: %pM %sassoc (len=%d " "prev_ap=%pM) => %d(%d) (%s)\n", dev->name, hdr->addr2, reassoc ? "re" : "", len, prev_ap, resp, send_deauth, txt); #endif } /* Called only as a scheduled task for pending AP frames. */ static void handle_deauth(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct net_device *dev = local->dev; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; char *body = (char *) (skb->data + IEEE80211_MGMT_HDR_LEN); int len; u16 reason_code; __le16 *pos; struct sta_info *sta = NULL; len = skb->len - IEEE80211_MGMT_HDR_LEN; if (len < 2) { printk("handle_deauth - too short payload (len=%d)\n", len); return; } pos = (__le16 *) body; reason_code = le16_to_cpu(*pos); PDEBUG(DEBUG_AP, "%s: deauthentication: %pM len=%d, " "reason_code=%d\n", dev->name, hdr->addr2, len, reason_code); spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta != NULL) { if ((sta->flags & WLAN_STA_ASSOC) && !sta->ap) hostap_event_expired_sta(local->dev, sta); sta->flags &= ~(WLAN_STA_AUTH | WLAN_STA_ASSOC); } spin_unlock_bh(&local->ap->sta_table_lock); if (sta == NULL) { printk("%s: deauthentication from %pM, " "reason_code=%d, but STA not authenticated\n", dev->name, hdr->addr2, reason_code); } } /* Called only as a scheduled task for pending AP frames. */ static void handle_disassoc(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct net_device *dev = local->dev; struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; char *body = skb->data + IEEE80211_MGMT_HDR_LEN; int len; u16 reason_code; __le16 *pos; struct sta_info *sta = NULL; len = skb->len - IEEE80211_MGMT_HDR_LEN; if (len < 2) { printk("handle_disassoc - too short payload (len=%d)\n", len); return; } pos = (__le16 *) body; reason_code = le16_to_cpu(*pos); PDEBUG(DEBUG_AP, "%s: disassociation: %pM len=%d, " "reason_code=%d\n", dev->name, hdr->addr2, len, reason_code); spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta != NULL) { if ((sta->flags & WLAN_STA_ASSOC) && !sta->ap) hostap_event_expired_sta(local->dev, sta); sta->flags &= ~WLAN_STA_ASSOC; } spin_unlock_bh(&local->ap->sta_table_lock); if (sta == NULL) { printk("%s: disassociation from %pM, " "reason_code=%d, but STA not authenticated\n", dev->name, hdr->addr2, reason_code); } } /* Called only as a scheduled task for pending AP frames. */ static void ap_handle_data_nullfunc(local_info_t *local, struct ieee80211_hdr *hdr) { struct net_device *dev = local->dev; /* some STA f/w's seem to require control::ACK frame for * data::nullfunc, but at least Prism2 station f/w version 0.8.0 does * not send this.. * send control::ACK for the data::nullfunc */ printk(KERN_DEBUG "Sending control::ACK for data::nullfunc\n"); prism2_send_mgmt(dev, IEEE80211_FTYPE_CTL | IEEE80211_STYPE_ACK, NULL, 0, hdr->addr2, 0); } /* Called only as a scheduled task for pending AP frames. */ static void ap_handle_dropped_data(local_info_t *local, struct ieee80211_hdr *hdr) { struct net_device *dev = local->dev; struct sta_info *sta; __le16 reason; spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&local->ap->sta_table_lock); if (sta != NULL && (sta->flags & WLAN_STA_ASSOC)) { PDEBUG(DEBUG_AP, "ap_handle_dropped_data: STA is now okay?\n"); atomic_dec(&sta->users); return; } reason = cpu_to_le16(WLAN_REASON_CLASS3_FRAME_FROM_NONASSOC_STA); prism2_send_mgmt(dev, IEEE80211_FTYPE_MGMT | ((sta == NULL || !(sta->flags & WLAN_STA_ASSOC)) ? IEEE80211_STYPE_DEAUTH : IEEE80211_STYPE_DISASSOC), (char *) &reason, sizeof(reason), hdr->addr2, 0); if (sta) atomic_dec(&sta->users); } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ /* Called only as a scheduled task for pending AP frames. */ static void pspoll_send_buffered(local_info_t *local, struct sta_info *sta, struct sk_buff *skb) { struct hostap_skb_tx_data *meta; if (!(sta->flags & WLAN_STA_PS)) { /* Station has moved to non-PS mode, so send all buffered * frames using normal device queue. */ dev_queue_xmit(skb); return; } /* add a flag for hostap_handle_sta_tx() to know that this skb should * be passed through even though STA is using PS */ meta = (struct hostap_skb_tx_data *) skb->cb; meta->flags |= HOSTAP_TX_FLAGS_BUFFERED_FRAME; if (!skb_queue_empty(&sta->tx_buf)) { /* indicate to STA that more frames follow */ meta->flags |= HOSTAP_TX_FLAGS_ADD_MOREDATA; } dev_queue_xmit(skb); } /* Called only as a scheduled task for pending AP frames. */ static void handle_pspoll(local_info_t *local, struct ieee80211_hdr *hdr, struct hostap_80211_rx_status *rx_stats) { struct net_device *dev = local->dev; struct sta_info *sta; u16 aid; struct sk_buff *skb; PDEBUG(DEBUG_PS2, "handle_pspoll: BSSID=%pM, TA=%pM PWRMGT=%d\n", hdr->addr1, hdr->addr2, !!ieee80211_has_pm(hdr->frame_control)); if (memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN)) { PDEBUG(DEBUG_AP, "handle_pspoll - addr1(BSSID)=%pM not own MAC\n", hdr->addr1); return; } aid = le16_to_cpu(hdr->duration_id); if ((aid & (BIT(15) | BIT(14))) != (BIT(15) | BIT(14))) { PDEBUG(DEBUG_PS, " PSPOLL and AID[15:14] not set\n"); return; } aid &= ~(BIT(15) | BIT(14)); if (aid == 0 || aid > MAX_AID_TABLE_SIZE) { PDEBUG(DEBUG_PS, " invalid aid=%d\n", aid); return; } PDEBUG(DEBUG_PS2, " aid=%d\n", aid); spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&local->ap->sta_table_lock); if (sta == NULL) { PDEBUG(DEBUG_PS, " STA not found\n"); return; } if (sta->aid != aid) { PDEBUG(DEBUG_PS, " received aid=%i does not match with " "assoc.aid=%d\n", aid, sta->aid); return; } /* FIX: todo: * - add timeout for buffering (clear aid in TIM vector if buffer timed * out (expiry time must be longer than ListenInterval for * the corresponding STA; "8802-11: 11.2.1.9 AP aging function" * - what to do, if buffered, pspolled, and sent frame is not ACKed by * sta; store buffer for later use and leave TIM aid bit set? use * TX event to check whether frame was ACKed? */ while ((skb = skb_dequeue(&sta->tx_buf)) != NULL) { /* send buffered frame .. */ PDEBUG(DEBUG_PS2, "Sending buffered frame to STA after PS POLL" " (buffer_count=%d)\n", skb_queue_len(&sta->tx_buf)); pspoll_send_buffered(local, sta, skb); if (sta->flags & WLAN_STA_PS) { /* send only one buffered packet per PS Poll */ /* FIX: should ignore further PS Polls until the * buffered packet that was just sent is acknowledged * (Tx or TxExc event) */ break; } } if (skb_queue_empty(&sta->tx_buf)) { /* try to clear aid from TIM */ if (!(sta->flags & WLAN_STA_TIM)) PDEBUG(DEBUG_PS2, "Re-unsetting TIM for aid %d\n", aid); hostap_set_tim(local, aid, 0); sta->flags &= ~WLAN_STA_TIM; } atomic_dec(&sta->users); } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT static void handle_wds_oper_queue(struct work_struct *work) { struct ap_data *ap = container_of(work, struct ap_data, wds_oper_queue); local_info_t *local = ap->local; struct wds_oper_data *entry, *prev; spin_lock_bh(&local->lock); entry = local->ap->wds_oper_entries; local->ap->wds_oper_entries = NULL; spin_unlock_bh(&local->lock); while (entry) { PDEBUG(DEBUG_AP, "%s: %s automatic WDS connection " "to AP %pM\n", local->dev->name, entry->type == WDS_ADD ? "adding" : "removing", entry->addr); if (entry->type == WDS_ADD) prism2_wds_add(local, entry->addr, 0); else if (entry->type == WDS_DEL) prism2_wds_del(local, entry->addr, 0, 1); prev = entry; entry = entry->next; kfree(prev); } } /* Called only as a scheduled task for pending AP frames. */ static void handle_beacon(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; char *body = skb->data + IEEE80211_MGMT_HDR_LEN; int len, left; u16 beacon_int, capability; __le16 *pos; char *ssid = NULL; unsigned char *supp_rates = NULL; int ssid_len = 0, supp_rates_len = 0; struct sta_info *sta = NULL; int new_sta = 0, channel = -1; len = skb->len - IEEE80211_MGMT_HDR_LEN; if (len < 8 + 2 + 2) { printk(KERN_DEBUG "handle_beacon - too short payload " "(len=%d)\n", len); return; } pos = (__le16 *) body; left = len; /* Timestamp (8 octets) */ pos += 4; left -= 8; /* Beacon interval (2 octets) */ beacon_int = le16_to_cpu(*pos); pos++; left -= 2; /* Capability information (2 octets) */ capability = le16_to_cpu(*pos); pos++; left -= 2; if (local->ap->ap_policy != AP_OTHER_AP_EVEN_IBSS && capability & WLAN_CAPABILITY_IBSS) return; if (left >= 2) { unsigned int ileft; unsigned char *u = (unsigned char *) pos; if (*u == WLAN_EID_SSID) { u++; left--; ileft = *u; u++; left--; if (ileft > left || ileft > MAX_SSID_LEN) { PDEBUG(DEBUG_AP, "SSID: overflow\n"); return; } if (local->ap->ap_policy == AP_OTHER_AP_SAME_SSID && (ileft != strlen(local->essid) || memcmp(local->essid, u, ileft) != 0)) { /* not our SSID */ return; } ssid = u; ssid_len = ileft; u += ileft; left -= ileft; } if (*u == WLAN_EID_SUPP_RATES) { u++; left--; ileft = *u; u++; left--; if (ileft > left || ileft == 0 || ileft > 8) { PDEBUG(DEBUG_AP, " - SUPP_RATES len error\n"); return; } supp_rates = u; supp_rates_len = ileft; u += ileft; left -= ileft; } if (*u == WLAN_EID_DS_PARAMS) { u++; left--; ileft = *u; u++; left--; if (ileft > left || ileft != 1) { PDEBUG(DEBUG_AP, " - DS_PARAMS len error\n"); return; } channel = *u; u += ileft; left -= ileft; } } spin_lock_bh(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta != NULL) atomic_inc(&sta->users); spin_unlock_bh(&local->ap->sta_table_lock); if (sta == NULL) { /* add new AP */ new_sta = 1; sta = ap_add_sta(local->ap, hdr->addr2); if (sta == NULL) { printk(KERN_INFO "prism2: kmalloc failed for AP " "data structure\n"); return; } hostap_event_new_sta(local->dev, sta); /* mark APs authentication and associated for pseudo ad-hoc * style communication */ sta->flags = WLAN_STA_AUTH | WLAN_STA_ASSOC; if (local->ap->autom_ap_wds) { hostap_wds_link_oper(local, sta->addr, WDS_ADD); } } sta->ap = 1; if (ssid) { sta->u.ap.ssid_len = ssid_len; memcpy(sta->u.ap.ssid, ssid, ssid_len); sta->u.ap.ssid[ssid_len] = '\0'; } else { sta->u.ap.ssid_len = 0; sta->u.ap.ssid[0] = '\0'; } sta->u.ap.channel = channel; sta->rx_packets++; sta->rx_bytes += len; sta->u.ap.last_beacon = sta->last_rx = jiffies; sta->capability = capability; sta->listen_interval = beacon_int; atomic_dec(&sta->users); if (new_sta) { memset(sta->supported_rates, 0, sizeof(sta->supported_rates)); memcpy(sta->supported_rates, supp_rates, supp_rates_len); prism2_check_tx_rates(sta); } } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ /* Called only as a tasklet. */ static void handle_ap_item(local_info_t *local, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT struct net_device *dev = local->dev; #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ u16 fc, type, stype; struct ieee80211_hdr *hdr; /* FIX: should give skb->len to handler functions and check that the * buffer is long enough */ hdr = (struct ieee80211_hdr *) skb->data; fc = le16_to_cpu(hdr->frame_control); type = fc & IEEE80211_FCTL_FTYPE; stype = fc & IEEE80211_FCTL_STYPE; #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT if (!local->hostapd && type == IEEE80211_FTYPE_DATA) { PDEBUG(DEBUG_AP, "handle_ap_item - data frame\n"); if (!(fc & IEEE80211_FCTL_TODS) || (fc & IEEE80211_FCTL_FROMDS)) { if (stype == IEEE80211_STYPE_NULLFUNC) { /* no ToDS nullfunc seems to be used to check * AP association; so send reject message to * speed up re-association */ ap_handle_dropped_data(local, hdr); goto done; } PDEBUG(DEBUG_AP, " not ToDS frame (fc=0x%04x)\n", fc); goto done; } if (memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN)) { PDEBUG(DEBUG_AP, "handle_ap_item - addr1(BSSID)=%pM" " not own MAC\n", hdr->addr1); goto done; } if (local->ap->nullfunc_ack && stype == IEEE80211_STYPE_NULLFUNC) ap_handle_data_nullfunc(local, hdr); else ap_handle_dropped_data(local, hdr); goto done; } if (type == IEEE80211_FTYPE_MGMT && stype == IEEE80211_STYPE_BEACON) { handle_beacon(local, skb, rx_stats); goto done; } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ if (type == IEEE80211_FTYPE_CTL && stype == IEEE80211_STYPE_PSPOLL) { handle_pspoll(local, hdr, rx_stats); goto done; } if (local->hostapd) { PDEBUG(DEBUG_AP, "Unknown frame in AP queue: type=0x%02x " "subtype=0x%02x\n", type, stype); goto done; } #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT if (type != IEEE80211_FTYPE_MGMT) { PDEBUG(DEBUG_AP, "handle_ap_item - not a management frame?\n"); goto done; } if (memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN)) { PDEBUG(DEBUG_AP, "handle_ap_item - addr1(DA)=%pM" " not own MAC\n", hdr->addr1); goto done; } if (memcmp(hdr->addr3, dev->dev_addr, ETH_ALEN)) { PDEBUG(DEBUG_AP, "handle_ap_item - addr3(BSSID)=%pM" " not own MAC\n", hdr->addr3); goto done; } switch (stype) { case IEEE80211_STYPE_ASSOC_REQ: handle_assoc(local, skb, rx_stats, 0); break; case IEEE80211_STYPE_ASSOC_RESP: PDEBUG(DEBUG_AP, "==> ASSOC RESP (ignored)\n"); break; case IEEE80211_STYPE_REASSOC_REQ: handle_assoc(local, skb, rx_stats, 1); break; case IEEE80211_STYPE_REASSOC_RESP: PDEBUG(DEBUG_AP, "==> REASSOC RESP (ignored)\n"); break; case IEEE80211_STYPE_ATIM: PDEBUG(DEBUG_AP, "==> ATIM (ignored)\n"); break; case IEEE80211_STYPE_DISASSOC: handle_disassoc(local, skb, rx_stats); break; case IEEE80211_STYPE_AUTH: handle_authen(local, skb, rx_stats); break; case IEEE80211_STYPE_DEAUTH: handle_deauth(local, skb, rx_stats); break; default: PDEBUG(DEBUG_AP, "Unknown mgmt frame subtype 0x%02x\n", stype >> 4); break; } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ done: dev_kfree_skb(skb); } /* Called only as a tasklet (software IRQ) */ void hostap_rx(struct net_device *dev, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats) { struct hostap_interface *iface; local_info_t *local; struct ieee80211_hdr *hdr; iface = netdev_priv(dev); local = iface->local; if (skb->len < 16) goto drop; dev->stats.rx_packets++; hdr = (struct ieee80211_hdr *) skb->data; if (local->ap->ap_policy == AP_OTHER_AP_SKIP_ALL && ieee80211_is_beacon(hdr->frame_control)) goto drop; skb->protocol = cpu_to_be16(ETH_P_HOSTAP); handle_ap_item(local, skb, rx_stats); return; drop: dev_kfree_skb(skb); } /* Called only as a tasklet (software IRQ) */ static void schedule_packet_send(local_info_t *local, struct sta_info *sta) { struct sk_buff *skb; struct ieee80211_hdr *hdr; struct hostap_80211_rx_status rx_stats; if (skb_queue_empty(&sta->tx_buf)) return; skb = dev_alloc_skb(16); if (skb == NULL) { printk(KERN_DEBUG "%s: schedule_packet_send: skb alloc " "failed\n", local->dev->name); return; } hdr = (struct ieee80211_hdr *) skb_put(skb, 16); /* Generate a fake pspoll frame to start packet delivery */ hdr->frame_control = cpu_to_le16( IEEE80211_FTYPE_CTL | IEEE80211_STYPE_PSPOLL); memcpy(hdr->addr1, local->dev->dev_addr, ETH_ALEN); memcpy(hdr->addr2, sta->addr, ETH_ALEN); hdr->duration_id = cpu_to_le16(sta->aid | BIT(15) | BIT(14)); PDEBUG(DEBUG_PS2, "%s: Scheduling buffered packet delivery for STA %pM\n", local->dev->name, sta->addr); skb->dev = local->dev; memset(&rx_stats, 0, sizeof(rx_stats)); hostap_rx(local->dev, skb, &rx_stats); } int prism2_ap_get_sta_qual(local_info_t *local, struct sockaddr addr[], struct iw_quality qual[], int buf_size, int aplist) { struct ap_data *ap = local->ap; struct list_head *ptr; int count = 0; spin_lock_bh(&ap->sta_table_lock); for (ptr = ap->sta_list.next; ptr != NULL && ptr != &ap->sta_list; ptr = ptr->next) { struct sta_info *sta = (struct sta_info *) ptr; if (aplist && !sta->ap) continue; addr[count].sa_family = ARPHRD_ETHER; memcpy(addr[count].sa_data, sta->addr, ETH_ALEN); if (sta->last_rx_silence == 0) qual[count].qual = sta->last_rx_signal < 27 ? 0 : (sta->last_rx_signal - 27) * 92 / 127; else qual[count].qual = sta->last_rx_signal - sta->last_rx_silence - 35; qual[count].level = HFA384X_LEVEL_TO_dBm(sta->last_rx_signal); qual[count].noise = HFA384X_LEVEL_TO_dBm(sta->last_rx_silence); qual[count].updated = sta->last_rx_updated; sta->last_rx_updated = IW_QUAL_DBM; count++; if (count >= buf_size) break; } spin_unlock_bh(&ap->sta_table_lock); return count; } /* Translate our list of Access Points & Stations to a card independent * format that the Wireless Tools will understand - Jean II */ int prism2_ap_translate_scan(struct net_device *dev, struct iw_request_info *info, char *buffer) { struct hostap_interface *iface; local_info_t *local; struct ap_data *ap; struct list_head *ptr; struct iw_event iwe; char *current_ev = buffer; char *end_buf = buffer + IW_SCAN_MAX_DATA; #if !defined(PRISM2_NO_KERNEL_IEEE80211_MGMT) char buf[64]; #endif iface = netdev_priv(dev); local = iface->local; ap = local->ap; spin_lock_bh(&ap->sta_table_lock); for (ptr = ap->sta_list.next; ptr != NULL && ptr != &ap->sta_list; ptr = ptr->next) { struct sta_info *sta = (struct sta_info *) ptr; /* First entry *MUST* be the AP MAC address */ memset(&iwe, 0, sizeof(iwe)); iwe.cmd = SIOCGIWAP; iwe.u.ap_addr.sa_family = ARPHRD_ETHER; memcpy(iwe.u.ap_addr.sa_data, sta->addr, ETH_ALEN); iwe.len = IW_EV_ADDR_LEN; current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_ADDR_LEN); /* Use the mode to indicate if it's a station or * an Access Point */ memset(&iwe, 0, sizeof(iwe)); iwe.cmd = SIOCGIWMODE; if (sta->ap) iwe.u.mode = IW_MODE_MASTER; else iwe.u.mode = IW_MODE_INFRA; iwe.len = IW_EV_UINT_LEN; current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_UINT_LEN); /* Some quality */ memset(&iwe, 0, sizeof(iwe)); iwe.cmd = IWEVQUAL; if (sta->last_rx_silence == 0) iwe.u.qual.qual = sta->last_rx_signal < 27 ? 0 : (sta->last_rx_signal - 27) * 92 / 127; else iwe.u.qual.qual = sta->last_rx_signal - sta->last_rx_silence - 35; iwe.u.qual.level = HFA384X_LEVEL_TO_dBm(sta->last_rx_signal); iwe.u.qual.noise = HFA384X_LEVEL_TO_dBm(sta->last_rx_silence); iwe.u.qual.updated = sta->last_rx_updated; iwe.len = IW_EV_QUAL_LEN; current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe, IW_EV_QUAL_LEN); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT if (sta->ap) { memset(&iwe, 0, sizeof(iwe)); iwe.cmd = SIOCGIWESSID; iwe.u.data.length = sta->u.ap.ssid_len; iwe.u.data.flags = 1; current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, sta->u.ap.ssid); memset(&iwe, 0, sizeof(iwe)); iwe.cmd = SIOCGIWENCODE; if (sta->capability & WLAN_CAPABILITY_PRIVACY) iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY; else iwe.u.data.flags = IW_ENCODE_DISABLED; current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, sta->u.ap.ssid); if (sta->u.ap.channel > 0 && sta->u.ap.channel <= FREQ_COUNT) { memset(&iwe, 0, sizeof(iwe)); iwe.cmd = SIOCGIWFREQ; iwe.u.freq.m = freq_list[sta->u.ap.channel - 1] * 100000; iwe.u.freq.e = 1; current_ev = iwe_stream_add_event( info, current_ev, end_buf, &iwe, IW_EV_FREQ_LEN); } memset(&iwe, 0, sizeof(iwe)); iwe.cmd = IWEVCUSTOM; sprintf(buf, "beacon_interval=%d", sta->listen_interval); iwe.u.data.length = strlen(buf); current_ev = iwe_stream_add_point(info, current_ev, end_buf, &iwe, buf); } #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ sta->last_rx_updated = IW_QUAL_DBM; /* To be continued, we should make good use of IWEVCUSTOM */ } spin_unlock_bh(&ap->sta_table_lock); return current_ev - buffer; } static int prism2_hostapd_add_sta(struct ap_data *ap, struct prism2_hostapd_param *param) { struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, param->sta_addr); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&ap->sta_table_lock); if (sta == NULL) { sta = ap_add_sta(ap, param->sta_addr); if (sta == NULL) return -1; } if (!(sta->flags & WLAN_STA_ASSOC) && !sta->ap && sta->local) hostap_event_new_sta(sta->local->dev, sta); sta->flags |= WLAN_STA_AUTH | WLAN_STA_ASSOC; sta->last_rx = jiffies; sta->aid = param->u.add_sta.aid; sta->capability = param->u.add_sta.capability; sta->tx_supp_rates = param->u.add_sta.tx_supp_rates; if (sta->tx_supp_rates & WLAN_RATE_1M) sta->supported_rates[0] = 2; if (sta->tx_supp_rates & WLAN_RATE_2M) sta->supported_rates[1] = 4; if (sta->tx_supp_rates & WLAN_RATE_5M5) sta->supported_rates[2] = 11; if (sta->tx_supp_rates & WLAN_RATE_11M) sta->supported_rates[3] = 22; prism2_check_tx_rates(sta); atomic_dec(&sta->users); return 0; } static int prism2_hostapd_remove_sta(struct ap_data *ap, struct prism2_hostapd_param *param) { struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, param->sta_addr); if (sta) { ap_sta_hash_del(ap, sta); list_del(&sta->list); } spin_unlock_bh(&ap->sta_table_lock); if (!sta) return -ENOENT; if ((sta->flags & WLAN_STA_ASSOC) && !sta->ap && sta->local) hostap_event_expired_sta(sta->local->dev, sta); ap_free_sta(ap, sta); return 0; } static int prism2_hostapd_get_info_sta(struct ap_data *ap, struct prism2_hostapd_param *param) { struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, param->sta_addr); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&ap->sta_table_lock); if (!sta) return -ENOENT; param->u.get_info_sta.inactive_sec = (jiffies - sta->last_rx) / HZ; atomic_dec(&sta->users); return 1; } static int prism2_hostapd_set_flags_sta(struct ap_data *ap, struct prism2_hostapd_param *param) { struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, param->sta_addr); if (sta) { sta->flags |= param->u.set_flags_sta.flags_or; sta->flags &= param->u.set_flags_sta.flags_and; } spin_unlock_bh(&ap->sta_table_lock); if (!sta) return -ENOENT; return 0; } static int prism2_hostapd_sta_clear_stats(struct ap_data *ap, struct prism2_hostapd_param *param) { struct sta_info *sta; int rate; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, param->sta_addr); if (sta) { sta->rx_packets = sta->tx_packets = 0; sta->rx_bytes = sta->tx_bytes = 0; for (rate = 0; rate < WLAN_RATE_COUNT; rate++) { sta->tx_count[rate] = 0; sta->rx_count[rate] = 0; } } spin_unlock_bh(&ap->sta_table_lock); if (!sta) return -ENOENT; return 0; } int prism2_hostapd(struct ap_data *ap, struct prism2_hostapd_param *param) { switch (param->cmd) { case PRISM2_HOSTAPD_FLUSH: ap_control_kickall(ap); return 0; case PRISM2_HOSTAPD_ADD_STA: return prism2_hostapd_add_sta(ap, param); case PRISM2_HOSTAPD_REMOVE_STA: return prism2_hostapd_remove_sta(ap, param); case PRISM2_HOSTAPD_GET_INFO_STA: return prism2_hostapd_get_info_sta(ap, param); case PRISM2_HOSTAPD_SET_FLAGS_STA: return prism2_hostapd_set_flags_sta(ap, param); case PRISM2_HOSTAPD_STA_CLEAR_STATS: return prism2_hostapd_sta_clear_stats(ap, param); default: printk(KERN_WARNING "prism2_hostapd: unknown cmd=%d\n", param->cmd); return -EOPNOTSUPP; } } /* Update station info for host-based TX rate control and return current * TX rate */ static int ap_update_sta_tx_rate(struct sta_info *sta, struct net_device *dev) { int ret = sta->tx_rate; struct hostap_interface *iface; local_info_t *local; iface = netdev_priv(dev); local = iface->local; sta->tx_count[sta->tx_rate_idx]++; sta->tx_since_last_failure++; sta->tx_consecutive_exc = 0; if (sta->tx_since_last_failure >= WLAN_RATE_UPDATE_COUNT && sta->tx_rate_idx < sta->tx_max_rate) { /* use next higher rate */ int old_rate, new_rate; old_rate = new_rate = sta->tx_rate_idx; while (new_rate < sta->tx_max_rate) { new_rate++; if (ap_tx_rate_ok(new_rate, sta, local)) { sta->tx_rate_idx = new_rate; break; } } if (old_rate != sta->tx_rate_idx) { switch (sta->tx_rate_idx) { case 0: sta->tx_rate = 10; break; case 1: sta->tx_rate = 20; break; case 2: sta->tx_rate = 55; break; case 3: sta->tx_rate = 110; break; default: sta->tx_rate = 0; break; } PDEBUG(DEBUG_AP, "%s: STA %pM TX rate raised to %d\n", dev->name, sta->addr, sta->tx_rate); } sta->tx_since_last_failure = 0; } return ret; } /* Called only from software IRQ. Called for each TX frame prior possible * encryption and transmit. */ ap_tx_ret hostap_handle_sta_tx(local_info_t *local, struct hostap_tx_data *tx) { struct sta_info *sta = NULL; struct sk_buff *skb = tx->skb; int set_tim, ret; struct ieee80211_hdr *hdr; struct hostap_skb_tx_data *meta; meta = (struct hostap_skb_tx_data *) skb->cb; ret = AP_TX_CONTINUE; if (local->ap == NULL || skb->len < 10 || meta->iface->type == HOSTAP_INTERFACE_STA) goto out; hdr = (struct ieee80211_hdr *) skb->data; if (hdr->addr1[0] & 0x01) { /* broadcast/multicast frame - no AP related processing */ if (local->ap->num_sta <= 0) ret = AP_TX_DROP; goto out; } /* unicast packet - check whether destination STA is associated */ spin_lock(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr1); if (sta) atomic_inc(&sta->users); spin_unlock(&local->ap->sta_table_lock); if (local->iw_mode == IW_MODE_MASTER && sta == NULL && !(meta->flags & HOSTAP_TX_FLAGS_WDS) && meta->iface->type != HOSTAP_INTERFACE_MASTER && meta->iface->type != HOSTAP_INTERFACE_AP) { #if 0 /* This can happen, e.g., when wlan0 is added to a bridge and * bridging code does not know which port is the correct target * for a unicast frame. In this case, the packet is send to all * ports of the bridge. Since this is a valid scenario, do not * print out any errors here. */ if (net_ratelimit()) { printk(KERN_DEBUG "AP: drop packet to non-associated " "STA %pM\n", hdr->addr1); } #endif local->ap->tx_drop_nonassoc++; ret = AP_TX_DROP; goto out; } if (sta == NULL) goto out; if (!(sta->flags & WLAN_STA_AUTHORIZED)) ret = AP_TX_CONTINUE_NOT_AUTHORIZED; /* Set tx_rate if using host-based TX rate control */ if (!local->fw_tx_rate_control) local->ap->last_tx_rate = meta->rate = ap_update_sta_tx_rate(sta, local->dev); if (local->iw_mode != IW_MODE_MASTER) goto out; if (!(sta->flags & WLAN_STA_PS)) goto out; if (meta->flags & HOSTAP_TX_FLAGS_ADD_MOREDATA) { /* indicate to STA that more frames follow */ hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_MOREDATA); } if (meta->flags & HOSTAP_TX_FLAGS_BUFFERED_FRAME) { /* packet was already buffered and now send due to * PS poll, so do not rebuffer it */ goto out; } if (skb_queue_len(&sta->tx_buf) >= STA_MAX_TX_BUFFER) { PDEBUG(DEBUG_PS, "%s: No more space in STA (%pM)'s" "PS mode buffer\n", local->dev->name, sta->addr); /* Make sure that TIM is set for the station (it might not be * after AP wlan hw reset). */ /* FIX: should fix hw reset to restore bits based on STA * buffer state.. */ hostap_set_tim(local, sta->aid, 1); sta->flags |= WLAN_STA_TIM; ret = AP_TX_DROP; goto out; } /* STA in PS mode, buffer frame for later delivery */ set_tim = skb_queue_empty(&sta->tx_buf); skb_queue_tail(&sta->tx_buf, skb); /* FIX: could save RX time to skb and expire buffered frames after * some time if STA does not poll for them */ if (set_tim) { if (sta->flags & WLAN_STA_TIM) PDEBUG(DEBUG_PS2, "Re-setting TIM for aid %d\n", sta->aid); hostap_set_tim(local, sta->aid, 1); sta->flags |= WLAN_STA_TIM; } ret = AP_TX_BUFFERED; out: if (sta != NULL) { if (ret == AP_TX_CONTINUE || ret == AP_TX_CONTINUE_NOT_AUTHORIZED) { sta->tx_packets++; sta->tx_bytes += skb->len; sta->last_tx = jiffies; } if ((ret == AP_TX_CONTINUE || ret == AP_TX_CONTINUE_NOT_AUTHORIZED) && sta->crypt && tx->host_encrypt) { tx->crypt = sta->crypt; tx->sta_ptr = sta; /* hostap_handle_sta_release() will * be called to release sta info * later */ } else atomic_dec(&sta->users); } return ret; } void hostap_handle_sta_release(void *ptr) { struct sta_info *sta = ptr; atomic_dec(&sta->users); } /* Called only as a tasklet (software IRQ) */ void hostap_handle_sta_tx_exc(local_info_t *local, struct sk_buff *skb) { struct sta_info *sta; struct ieee80211_hdr *hdr; struct hostap_skb_tx_data *meta; hdr = (struct ieee80211_hdr *) skb->data; meta = (struct hostap_skb_tx_data *) skb->cb; spin_lock(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr1); if (!sta) { spin_unlock(&local->ap->sta_table_lock); PDEBUG(DEBUG_AP, "%s: Could not find STA %pM" " for this TX error (@%lu)\n", local->dev->name, hdr->addr1, jiffies); return; } sta->tx_since_last_failure = 0; sta->tx_consecutive_exc++; if (sta->tx_consecutive_exc >= WLAN_RATE_DECREASE_THRESHOLD && sta->tx_rate_idx > 0 && meta->rate <= sta->tx_rate) { /* use next lower rate */ int old, rate; old = rate = sta->tx_rate_idx; while (rate > 0) { rate--; if (ap_tx_rate_ok(rate, sta, local)) { sta->tx_rate_idx = rate; break; } } if (old != sta->tx_rate_idx) { switch (sta->tx_rate_idx) { case 0: sta->tx_rate = 10; break; case 1: sta->tx_rate = 20; break; case 2: sta->tx_rate = 55; break; case 3: sta->tx_rate = 110; break; default: sta->tx_rate = 0; break; } PDEBUG(DEBUG_AP, "%s: STA %pM TX rate lowered to %d\n", local->dev->name, sta->addr, sta->tx_rate); } sta->tx_consecutive_exc = 0; } spin_unlock(&local->ap->sta_table_lock); } static void hostap_update_sta_ps2(local_info_t *local, struct sta_info *sta, int pwrmgt, int type, int stype) { if (pwrmgt && !(sta->flags & WLAN_STA_PS)) { sta->flags |= WLAN_STA_PS; PDEBUG(DEBUG_PS2, "STA %pM changed to use PS " "mode (type=0x%02X, stype=0x%02X)\n", sta->addr, type >> 2, stype >> 4); } else if (!pwrmgt && (sta->flags & WLAN_STA_PS)) { sta->flags &= ~WLAN_STA_PS; PDEBUG(DEBUG_PS2, "STA %pM changed to not use " "PS mode (type=0x%02X, stype=0x%02X)\n", sta->addr, type >> 2, stype >> 4); if (type != IEEE80211_FTYPE_CTL || stype != IEEE80211_STYPE_PSPOLL) schedule_packet_send(local, sta); } } /* Called only as a tasklet (software IRQ). Called for each RX frame to update * STA power saving state. pwrmgt is a flag from 802.11 frame_control field. */ int hostap_update_sta_ps(local_info_t *local, struct ieee80211_hdr *hdr) { struct sta_info *sta; u16 fc; spin_lock(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta) atomic_inc(&sta->users); spin_unlock(&local->ap->sta_table_lock); if (!sta) return -1; fc = le16_to_cpu(hdr->frame_control); hostap_update_sta_ps2(local, sta, fc & IEEE80211_FCTL_PM, fc & IEEE80211_FCTL_FTYPE, fc & IEEE80211_FCTL_STYPE); atomic_dec(&sta->users); return 0; } /* Called only as a tasklet (software IRQ). Called for each RX frame after * getting RX header and payload from hardware. */ ap_rx_ret hostap_handle_sta_rx(local_info_t *local, struct net_device *dev, struct sk_buff *skb, struct hostap_80211_rx_status *rx_stats, int wds) { int ret; struct sta_info *sta; u16 fc, type, stype; struct ieee80211_hdr *hdr; if (local->ap == NULL) return AP_RX_CONTINUE; hdr = (struct ieee80211_hdr *) skb->data; fc = le16_to_cpu(hdr->frame_control); type = fc & IEEE80211_FCTL_FTYPE; stype = fc & IEEE80211_FCTL_STYPE; spin_lock(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta) atomic_inc(&sta->users); spin_unlock(&local->ap->sta_table_lock); if (sta && !(sta->flags & WLAN_STA_AUTHORIZED)) ret = AP_RX_CONTINUE_NOT_AUTHORIZED; else ret = AP_RX_CONTINUE; if (fc & IEEE80211_FCTL_TODS) { if (!wds && (sta == NULL || !(sta->flags & WLAN_STA_ASSOC))) { if (local->hostapd) { prism2_rx_80211(local->apdev, skb, rx_stats, PRISM2_RX_NON_ASSOC); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT } else { printk(KERN_DEBUG "%s: dropped received packet" " from non-associated STA %pM" " (type=0x%02x, subtype=0x%02x)\n", dev->name, hdr->addr2, type >> 2, stype >> 4); hostap_rx(dev, skb, rx_stats); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ } ret = AP_RX_EXIT; goto out; } } else if (fc & IEEE80211_FCTL_FROMDS) { if (!wds) { /* FromDS frame - not for us; probably * broadcast/multicast in another BSS - drop */ if (memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN) == 0) { printk(KERN_DEBUG "Odd.. FromDS packet " "received with own BSSID\n"); hostap_dump_rx_80211(dev->name, skb, rx_stats); } ret = AP_RX_DROP; goto out; } } else if (stype == IEEE80211_STYPE_NULLFUNC && sta == NULL && memcmp(hdr->addr1, dev->dev_addr, ETH_ALEN) == 0) { if (local->hostapd) { prism2_rx_80211(local->apdev, skb, rx_stats, PRISM2_RX_NON_ASSOC); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT } else { /* At least Lucent f/w seems to send data::nullfunc * frames with no ToDS flag when the current AP returns * after being unavailable for some time. Speed up * re-association by informing the station about it not * being associated. */ printk(KERN_DEBUG "%s: rejected received nullfunc frame" " without ToDS from not associated STA %pM\n", dev->name, hdr->addr2); hostap_rx(dev, skb, rx_stats); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ } ret = AP_RX_EXIT; goto out; } else if (stype == IEEE80211_STYPE_NULLFUNC) { /* At least Lucent cards seem to send periodic nullfunc * frames with ToDS. Let these through to update SQ * stats and PS state. Nullfunc frames do not contain * any data and they will be dropped below. */ } else { /* If BSSID (Addr3) is foreign, this frame is a normal * broadcast frame from an IBSS network. Drop it silently. * If BSSID is own, report the dropping of this frame. */ if (memcmp(hdr->addr3, dev->dev_addr, ETH_ALEN) == 0) { printk(KERN_DEBUG "%s: dropped received packet from %pM" " with no ToDS flag " "(type=0x%02x, subtype=0x%02x)\n", dev->name, hdr->addr2, type >> 2, stype >> 4); hostap_dump_rx_80211(dev->name, skb, rx_stats); } ret = AP_RX_DROP; goto out; } if (sta) { hostap_update_sta_ps2(local, sta, fc & IEEE80211_FCTL_PM, type, stype); sta->rx_packets++; sta->rx_bytes += skb->len; sta->last_rx = jiffies; } if (local->ap->nullfunc_ack && stype == IEEE80211_STYPE_NULLFUNC && fc & IEEE80211_FCTL_TODS) { if (local->hostapd) { prism2_rx_80211(local->apdev, skb, rx_stats, PRISM2_RX_NULLFUNC_ACK); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT } else { /* some STA f/w's seem to require control::ACK frame * for data::nullfunc, but Prism2 f/w 0.8.0 (at least * from Compaq) does not send this.. Try to generate * ACK for these frames from the host driver to make * power saving work with, e.g., Lucent WaveLAN f/w */ hostap_rx(dev, skb, rx_stats); #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */ } ret = AP_RX_EXIT; goto out; } out: if (sta) atomic_dec(&sta->users); return ret; } /* Called only as a tasklet (software IRQ) */ int hostap_handle_sta_crypto(local_info_t *local, struct ieee80211_hdr *hdr, struct lib80211_crypt_data **crypt, void **sta_ptr) { struct sta_info *sta; spin_lock(&local->ap->sta_table_lock); sta = ap_get_sta(local->ap, hdr->addr2); if (sta) atomic_inc(&sta->users); spin_unlock(&local->ap->sta_table_lock); if (!sta) return -1; if (sta->crypt) { *crypt = sta->crypt; *sta_ptr = sta; /* hostap_handle_sta_release() will be called to release STA * info */ } else atomic_dec(&sta->users); return 0; } /* Called only as a tasklet (software IRQ) */ int hostap_is_sta_assoc(struct ap_data *ap, u8 *sta_addr) { struct sta_info *sta; int ret = 0; spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, sta_addr); if (sta != NULL && (sta->flags & WLAN_STA_ASSOC) && !sta->ap) ret = 1; spin_unlock(&ap->sta_table_lock); return ret; } /* Called only as a tasklet (software IRQ) */ int hostap_is_sta_authorized(struct ap_data *ap, u8 *sta_addr) { struct sta_info *sta; int ret = 0; spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, sta_addr); if (sta != NULL && (sta->flags & WLAN_STA_ASSOC) && !sta->ap && ((sta->flags & WLAN_STA_AUTHORIZED) || ap->local->ieee_802_1x == 0)) ret = 1; spin_unlock(&ap->sta_table_lock); return ret; } /* Called only as a tasklet (software IRQ) */ int hostap_add_sta(struct ap_data *ap, u8 *sta_addr) { struct sta_info *sta; int ret = 1; if (!ap) return -1; spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, sta_addr); if (sta) ret = 0; spin_unlock(&ap->sta_table_lock); if (ret == 1) { sta = ap_add_sta(ap, sta_addr); if (!sta) return -1; sta->flags = WLAN_STA_AUTH | WLAN_STA_ASSOC; sta->ap = 1; memset(sta->supported_rates, 0, sizeof(sta->supported_rates)); /* No way of knowing which rates are supported since we did not * get supported rates element from beacon/assoc req. Assume * that remote end supports all 802.11b rates. */ sta->supported_rates[0] = 0x82; sta->supported_rates[1] = 0x84; sta->supported_rates[2] = 0x0b; sta->supported_rates[3] = 0x16; sta->tx_supp_rates = WLAN_RATE_1M | WLAN_RATE_2M | WLAN_RATE_5M5 | WLAN_RATE_11M; sta->tx_rate = 110; sta->tx_max_rate = sta->tx_rate_idx = 3; } return ret; } /* Called only as a tasklet (software IRQ) */ int hostap_update_rx_stats(struct ap_data *ap, struct ieee80211_hdr *hdr, struct hostap_80211_rx_status *rx_stats) { struct sta_info *sta; if (!ap) return -1; spin_lock(&ap->sta_table_lock); sta = ap_get_sta(ap, hdr->addr2); if (sta) { sta->last_rx_silence = rx_stats->noise; sta->last_rx_signal = rx_stats->signal; sta->last_rx_rate = rx_stats->rate; sta->last_rx_updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM; if (rx_stats->rate == 10) sta->rx_count[0]++; else if (rx_stats->rate == 20) sta->rx_count[1]++; else if (rx_stats->rate == 55) sta->rx_count[2]++; else if (rx_stats->rate == 110) sta->rx_count[3]++; } spin_unlock(&ap->sta_table_lock); return sta ? 0 : -1; } void hostap_update_rates(local_info_t *local) { struct sta_info *sta; struct ap_data *ap = local->ap; if (!ap) return; spin_lock_bh(&ap->sta_table_lock); list_for_each_entry(sta, &ap->sta_list, list) { prism2_check_tx_rates(sta); } spin_unlock_bh(&ap->sta_table_lock); } void * ap_crypt_get_ptrs(struct ap_data *ap, u8 *addr, int permanent, struct lib80211_crypt_data ***crypt) { struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); sta = ap_get_sta(ap, addr); if (sta) atomic_inc(&sta->users); spin_unlock_bh(&ap->sta_table_lock); if (!sta && permanent) sta = ap_add_sta(ap, addr); if (!sta) return NULL; if (permanent) sta->flags |= WLAN_STA_PERM; *crypt = &sta->crypt; return sta; } void hostap_add_wds_links(local_info_t *local) { struct ap_data *ap = local->ap; struct sta_info *sta; spin_lock_bh(&ap->sta_table_lock); list_for_each_entry(sta, &ap->sta_list, list) { if (sta->ap) hostap_wds_link_oper(local, sta->addr, WDS_ADD); } spin_unlock_bh(&ap->sta_table_lock); schedule_work(&local->ap->wds_oper_queue); } void hostap_wds_link_oper(local_info_t *local, u8 *addr, wds_oper_type type) { struct wds_oper_data *entry; entry = kmalloc(sizeof(*entry), GFP_ATOMIC); if (!entry) return; memcpy(entry->addr, addr, ETH_ALEN); entry->type = type; spin_lock_bh(&local->lock); entry->next = local->ap->wds_oper_entries; local->ap->wds_oper_entries = entry; spin_unlock_bh(&local->lock); schedule_work(&local->ap->wds_oper_queue); } EXPORT_SYMBOL(hostap_init_data); EXPORT_SYMBOL(hostap_init_ap_proc); EXPORT_SYMBOL(hostap_free_data); EXPORT_SYMBOL(hostap_check_sta_fw_version); EXPORT_SYMBOL(hostap_handle_sta_tx_exc); #ifndef PRISM2_NO_KERNEL_IEEE80211_MGMT #endif /* PRISM2_NO_KERNEL_IEEE80211_MGMT */
gpl-2.0
jderrick/linux-blkdev
drivers/video/fbdev/via/hw.c
4607
60031
/* * Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved. * Copyright 2001-2008 S3 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; * either version 2, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTIES OR REPRESENTATIONS; 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/via-core.h> #include <asm/olpc.h> #include "global.h" #include "via_clock.h" static struct pll_limit cle266_pll_limits[] = { {19, 19, 4, 0}, {26, 102, 5, 0}, {53, 112, 6, 0}, {41, 100, 7, 0}, {83, 108, 8, 0}, {87, 118, 9, 0}, {95, 115, 12, 0}, {108, 108, 13, 0}, {83, 83, 17, 0}, {67, 98, 20, 0}, {121, 121, 24, 0}, {99, 99, 29, 0}, {33, 33, 3, 1}, {15, 23, 4, 1}, {37, 121, 5, 1}, {82, 82, 6, 1}, {31, 84, 7, 1}, {83, 83, 8, 1}, {76, 127, 9, 1}, {33, 121, 4, 2}, {91, 118, 5, 2}, {83, 109, 6, 2}, {90, 90, 7, 2}, {93, 93, 2, 3}, {53, 53, 3, 3}, {73, 117, 4, 3}, {101, 127, 5, 3}, {99, 99, 7, 3} }; static struct pll_limit k800_pll_limits[] = { {22, 22, 2, 0}, {28, 28, 3, 0}, {81, 112, 3, 1}, {86, 166, 4, 1}, {109, 153, 5, 1}, {66, 116, 3, 2}, {93, 137, 4, 2}, {117, 208, 5, 2}, {30, 30, 2, 3}, {69, 125, 3, 3}, {89, 161, 4, 3}, {121, 208, 5, 3}, {66, 66, 2, 4}, {85, 85, 3, 4}, {141, 161, 4, 4}, {177, 177, 5, 4} }; static struct pll_limit cx700_pll_limits[] = { {98, 98, 3, 1}, {86, 86, 4, 1}, {109, 208, 5, 1}, {68, 68, 2, 2}, {95, 116, 3, 2}, {93, 166, 4, 2}, {110, 206, 5, 2}, {174, 174, 7, 2}, {82, 109, 3, 3}, {117, 161, 4, 3}, {112, 208, 5, 3}, {141, 202, 5, 4} }; static struct pll_limit vx855_pll_limits[] = { {86, 86, 4, 1}, {108, 208, 5, 1}, {110, 208, 5, 2}, {83, 112, 3, 3}, {103, 161, 4, 3}, {112, 209, 5, 3}, {142, 161, 4, 4}, {141, 176, 5, 4} }; /* according to VIA Technologies these values are based on experiment */ static struct io_reg scaling_parameters[] = { {VIACR, CR7A, 0xFF, 0x01}, /* LCD Scaling Parameter 1 */ {VIACR, CR7B, 0xFF, 0x02}, /* LCD Scaling Parameter 2 */ {VIACR, CR7C, 0xFF, 0x03}, /* LCD Scaling Parameter 3 */ {VIACR, CR7D, 0xFF, 0x04}, /* LCD Scaling Parameter 4 */ {VIACR, CR7E, 0xFF, 0x07}, /* LCD Scaling Parameter 5 */ {VIACR, CR7F, 0xFF, 0x0A}, /* LCD Scaling Parameter 6 */ {VIACR, CR80, 0xFF, 0x0D}, /* LCD Scaling Parameter 7 */ {VIACR, CR81, 0xFF, 0x13}, /* LCD Scaling Parameter 8 */ {VIACR, CR82, 0xFF, 0x16}, /* LCD Scaling Parameter 9 */ {VIACR, CR83, 0xFF, 0x19}, /* LCD Scaling Parameter 10 */ {VIACR, CR84, 0xFF, 0x1C}, /* LCD Scaling Parameter 11 */ {VIACR, CR85, 0xFF, 0x1D}, /* LCD Scaling Parameter 12 */ {VIACR, CR86, 0xFF, 0x1E}, /* LCD Scaling Parameter 13 */ {VIACR, CR87, 0xFF, 0x1F}, /* LCD Scaling Parameter 14 */ }; static struct io_reg common_vga[] = { {VIACR, CR07, 0x10, 0x10}, /* [0] vertical total (bit 8) [1] vertical display end (bit 8) [2] vertical retrace start (bit 8) [3] start vertical blanking (bit 8) [4] line compare (bit 8) [5] vertical total (bit 9) [6] vertical display end (bit 9) [7] vertical retrace start (bit 9) */ {VIACR, CR08, 0xFF, 0x00}, /* [0-4] preset row scan [5-6] byte panning */ {VIACR, CR09, 0xDF, 0x40}, /* [0-4] max scan line [5] start vertical blanking (bit 9) [6] line compare (bit 9) [7] scan doubling */ {VIACR, CR0A, 0xFF, 0x1E}, /* [0-4] cursor start [5] cursor disable */ {VIACR, CR0B, 0xFF, 0x00}, /* [0-4] cursor end [5-6] cursor skew */ {VIACR, CR0E, 0xFF, 0x00}, /* [0-7] cursor location (high) */ {VIACR, CR0F, 0xFF, 0x00}, /* [0-7] cursor location (low) */ {VIACR, CR11, 0xF0, 0x80}, /* [0-3] vertical retrace end [6] memory refresh bandwidth [7] CRTC register protect enable */ {VIACR, CR14, 0xFF, 0x00}, /* [0-4] underline location [5] divide memory address clock by 4 [6] double word addressing */ {VIACR, CR17, 0xFF, 0x63}, /* [0-1] mapping of display address 13-14 [2] divide scan line clock by 2 [3] divide memory address clock by 2 [5] address wrap [6] byte mode select [7] sync enable */ {VIACR, CR18, 0xFF, 0xFF}, /* [0-7] line compare */ }; static struct fifo_depth_select display_fifo_depth_reg = { /* IGA1 FIFO Depth_Select */ {IGA1_FIFO_DEPTH_SELECT_REG_NUM, {{SR17, 0, 7} } }, /* IGA2 FIFO Depth_Select */ {IGA2_FIFO_DEPTH_SELECT_REG_NUM, {{CR68, 4, 7}, {CR94, 7, 7}, {CR95, 7, 7} } } }; static struct fifo_threshold_select fifo_threshold_select_reg = { /* IGA1 FIFO Threshold Select */ {IGA1_FIFO_THRESHOLD_REG_NUM, {{SR16, 0, 5}, {SR16, 7, 7} } }, /* IGA2 FIFO Threshold Select */ {IGA2_FIFO_THRESHOLD_REG_NUM, {{CR68, 0, 3}, {CR95, 4, 6} } } }; static struct fifo_high_threshold_select fifo_high_threshold_select_reg = { /* IGA1 FIFO High Threshold Select */ {IGA1_FIFO_HIGH_THRESHOLD_REG_NUM, {{SR18, 0, 5}, {SR18, 7, 7} } }, /* IGA2 FIFO High Threshold Select */ {IGA2_FIFO_HIGH_THRESHOLD_REG_NUM, {{CR92, 0, 3}, {CR95, 0, 2} } } }; static struct display_queue_expire_num display_queue_expire_num_reg = { /* IGA1 Display Queue Expire Num */ {IGA1_DISPLAY_QUEUE_EXPIRE_NUM_REG_NUM, {{SR22, 0, 4} } }, /* IGA2 Display Queue Expire Num */ {IGA2_DISPLAY_QUEUE_EXPIRE_NUM_REG_NUM, {{CR94, 0, 6} } } }; /* Definition Fetch Count Registers*/ static struct fetch_count fetch_count_reg = { /* IGA1 Fetch Count Register */ {IGA1_FETCH_COUNT_REG_NUM, {{SR1C, 0, 7}, {SR1D, 0, 1} } }, /* IGA2 Fetch Count Register */ {IGA2_FETCH_COUNT_REG_NUM, {{CR65, 0, 7}, {CR67, 2, 3} } } }; static struct rgbLUT palLUT_table[] = { /* {R,G,B} */ /* Index 0x00~0x03 */ {0x00, 0x00, 0x00}, {0x00, 0x00, 0x2A}, {0x00, 0x2A, 0x00}, {0x00, 0x2A, 0x2A}, /* Index 0x04~0x07 */ {0x2A, 0x00, 0x00}, {0x2A, 0x00, 0x2A}, {0x2A, 0x15, 0x00}, {0x2A, 0x2A, 0x2A}, /* Index 0x08~0x0B */ {0x15, 0x15, 0x15}, {0x15, 0x15, 0x3F}, {0x15, 0x3F, 0x15}, {0x15, 0x3F, 0x3F}, /* Index 0x0C~0x0F */ {0x3F, 0x15, 0x15}, {0x3F, 0x15, 0x3F}, {0x3F, 0x3F, 0x15}, {0x3F, 0x3F, 0x3F}, /* Index 0x10~0x13 */ {0x00, 0x00, 0x00}, {0x05, 0x05, 0x05}, {0x08, 0x08, 0x08}, {0x0B, 0x0B, 0x0B}, /* Index 0x14~0x17 */ {0x0E, 0x0E, 0x0E}, {0x11, 0x11, 0x11}, {0x14, 0x14, 0x14}, {0x18, 0x18, 0x18}, /* Index 0x18~0x1B */ {0x1C, 0x1C, 0x1C}, {0x20, 0x20, 0x20}, {0x24, 0x24, 0x24}, {0x28, 0x28, 0x28}, /* Index 0x1C~0x1F */ {0x2D, 0x2D, 0x2D}, {0x32, 0x32, 0x32}, {0x38, 0x38, 0x38}, {0x3F, 0x3F, 0x3F}, /* Index 0x20~0x23 */ {0x00, 0x00, 0x3F}, {0x10, 0x00, 0x3F}, {0x1F, 0x00, 0x3F}, {0x2F, 0x00, 0x3F}, /* Index 0x24~0x27 */ {0x3F, 0x00, 0x3F}, {0x3F, 0x00, 0x2F}, {0x3F, 0x00, 0x1F}, {0x3F, 0x00, 0x10}, /* Index 0x28~0x2B */ {0x3F, 0x00, 0x00}, {0x3F, 0x10, 0x00}, {0x3F, 0x1F, 0x00}, {0x3F, 0x2F, 0x00}, /* Index 0x2C~0x2F */ {0x3F, 0x3F, 0x00}, {0x2F, 0x3F, 0x00}, {0x1F, 0x3F, 0x00}, {0x10, 0x3F, 0x00}, /* Index 0x30~0x33 */ {0x00, 0x3F, 0x00}, {0x00, 0x3F, 0x10}, {0x00, 0x3F, 0x1F}, {0x00, 0x3F, 0x2F}, /* Index 0x34~0x37 */ {0x00, 0x3F, 0x3F}, {0x00, 0x2F, 0x3F}, {0x00, 0x1F, 0x3F}, {0x00, 0x10, 0x3F}, /* Index 0x38~0x3B */ {0x1F, 0x1F, 0x3F}, {0x27, 0x1F, 0x3F}, {0x2F, 0x1F, 0x3F}, {0x37, 0x1F, 0x3F}, /* Index 0x3C~0x3F */ {0x3F, 0x1F, 0x3F}, {0x3F, 0x1F, 0x37}, {0x3F, 0x1F, 0x2F}, {0x3F, 0x1F, 0x27}, /* Index 0x40~0x43 */ {0x3F, 0x1F, 0x1F}, {0x3F, 0x27, 0x1F}, {0x3F, 0x2F, 0x1F}, {0x3F, 0x3F, 0x1F}, /* Index 0x44~0x47 */ {0x3F, 0x3F, 0x1F}, {0x37, 0x3F, 0x1F}, {0x2F, 0x3F, 0x1F}, {0x27, 0x3F, 0x1F}, /* Index 0x48~0x4B */ {0x1F, 0x3F, 0x1F}, {0x1F, 0x3F, 0x27}, {0x1F, 0x3F, 0x2F}, {0x1F, 0x3F, 0x37}, /* Index 0x4C~0x4F */ {0x1F, 0x3F, 0x3F}, {0x1F, 0x37, 0x3F}, {0x1F, 0x2F, 0x3F}, {0x1F, 0x27, 0x3F}, /* Index 0x50~0x53 */ {0x2D, 0x2D, 0x3F}, {0x31, 0x2D, 0x3F}, {0x36, 0x2D, 0x3F}, {0x3A, 0x2D, 0x3F}, /* Index 0x54~0x57 */ {0x3F, 0x2D, 0x3F}, {0x3F, 0x2D, 0x3A}, {0x3F, 0x2D, 0x36}, {0x3F, 0x2D, 0x31}, /* Index 0x58~0x5B */ {0x3F, 0x2D, 0x2D}, {0x3F, 0x31, 0x2D}, {0x3F, 0x36, 0x2D}, {0x3F, 0x3A, 0x2D}, /* Index 0x5C~0x5F */ {0x3F, 0x3F, 0x2D}, {0x3A, 0x3F, 0x2D}, {0x36, 0x3F, 0x2D}, {0x31, 0x3F, 0x2D}, /* Index 0x60~0x63 */ {0x2D, 0x3F, 0x2D}, {0x2D, 0x3F, 0x31}, {0x2D, 0x3F, 0x36}, {0x2D, 0x3F, 0x3A}, /* Index 0x64~0x67 */ {0x2D, 0x3F, 0x3F}, {0x2D, 0x3A, 0x3F}, {0x2D, 0x36, 0x3F}, {0x2D, 0x31, 0x3F}, /* Index 0x68~0x6B */ {0x00, 0x00, 0x1C}, {0x07, 0x00, 0x1C}, {0x0E, 0x00, 0x1C}, {0x15, 0x00, 0x1C}, /* Index 0x6C~0x6F */ {0x1C, 0x00, 0x1C}, {0x1C, 0x00, 0x15}, {0x1C, 0x00, 0x0E}, {0x1C, 0x00, 0x07}, /* Index 0x70~0x73 */ {0x1C, 0x00, 0x00}, {0x1C, 0x07, 0x00}, {0x1C, 0x0E, 0x00}, {0x1C, 0x15, 0x00}, /* Index 0x74~0x77 */ {0x1C, 0x1C, 0x00}, {0x15, 0x1C, 0x00}, {0x0E, 0x1C, 0x00}, {0x07, 0x1C, 0x00}, /* Index 0x78~0x7B */ {0x00, 0x1C, 0x00}, {0x00, 0x1C, 0x07}, {0x00, 0x1C, 0x0E}, {0x00, 0x1C, 0x15}, /* Index 0x7C~0x7F */ {0x00, 0x1C, 0x1C}, {0x00, 0x15, 0x1C}, {0x00, 0x0E, 0x1C}, {0x00, 0x07, 0x1C}, /* Index 0x80~0x83 */ {0x0E, 0x0E, 0x1C}, {0x11, 0x0E, 0x1C}, {0x15, 0x0E, 0x1C}, {0x18, 0x0E, 0x1C}, /* Index 0x84~0x87 */ {0x1C, 0x0E, 0x1C}, {0x1C, 0x0E, 0x18}, {0x1C, 0x0E, 0x15}, {0x1C, 0x0E, 0x11}, /* Index 0x88~0x8B */ {0x1C, 0x0E, 0x0E}, {0x1C, 0x11, 0x0E}, {0x1C, 0x15, 0x0E}, {0x1C, 0x18, 0x0E}, /* Index 0x8C~0x8F */ {0x1C, 0x1C, 0x0E}, {0x18, 0x1C, 0x0E}, {0x15, 0x1C, 0x0E}, {0x11, 0x1C, 0x0E}, /* Index 0x90~0x93 */ {0x0E, 0x1C, 0x0E}, {0x0E, 0x1C, 0x11}, {0x0E, 0x1C, 0x15}, {0x0E, 0x1C, 0x18}, /* Index 0x94~0x97 */ {0x0E, 0x1C, 0x1C}, {0x0E, 0x18, 0x1C}, {0x0E, 0x15, 0x1C}, {0x0E, 0x11, 0x1C}, /* Index 0x98~0x9B */ {0x14, 0x14, 0x1C}, {0x16, 0x14, 0x1C}, {0x18, 0x14, 0x1C}, {0x1A, 0x14, 0x1C}, /* Index 0x9C~0x9F */ {0x1C, 0x14, 0x1C}, {0x1C, 0x14, 0x1A}, {0x1C, 0x14, 0x18}, {0x1C, 0x14, 0x16}, /* Index 0xA0~0xA3 */ {0x1C, 0x14, 0x14}, {0x1C, 0x16, 0x14}, {0x1C, 0x18, 0x14}, {0x1C, 0x1A, 0x14}, /* Index 0xA4~0xA7 */ {0x1C, 0x1C, 0x14}, {0x1A, 0x1C, 0x14}, {0x18, 0x1C, 0x14}, {0x16, 0x1C, 0x14}, /* Index 0xA8~0xAB */ {0x14, 0x1C, 0x14}, {0x14, 0x1C, 0x16}, {0x14, 0x1C, 0x18}, {0x14, 0x1C, 0x1A}, /* Index 0xAC~0xAF */ {0x14, 0x1C, 0x1C}, {0x14, 0x1A, 0x1C}, {0x14, 0x18, 0x1C}, {0x14, 0x16, 0x1C}, /* Index 0xB0~0xB3 */ {0x00, 0x00, 0x10}, {0x04, 0x00, 0x10}, {0x08, 0x00, 0x10}, {0x0C, 0x00, 0x10}, /* Index 0xB4~0xB7 */ {0x10, 0x00, 0x10}, {0x10, 0x00, 0x0C}, {0x10, 0x00, 0x08}, {0x10, 0x00, 0x04}, /* Index 0xB8~0xBB */ {0x10, 0x00, 0x00}, {0x10, 0x04, 0x00}, {0x10, 0x08, 0x00}, {0x10, 0x0C, 0x00}, /* Index 0xBC~0xBF */ {0x10, 0x10, 0x00}, {0x0C, 0x10, 0x00}, {0x08, 0x10, 0x00}, {0x04, 0x10, 0x00}, /* Index 0xC0~0xC3 */ {0x00, 0x10, 0x00}, {0x00, 0x10, 0x04}, {0x00, 0x10, 0x08}, {0x00, 0x10, 0x0C}, /* Index 0xC4~0xC7 */ {0x00, 0x10, 0x10}, {0x00, 0x0C, 0x10}, {0x00, 0x08, 0x10}, {0x00, 0x04, 0x10}, /* Index 0xC8~0xCB */ {0x08, 0x08, 0x10}, {0x0A, 0x08, 0x10}, {0x0C, 0x08, 0x10}, {0x0E, 0x08, 0x10}, /* Index 0xCC~0xCF */ {0x10, 0x08, 0x10}, {0x10, 0x08, 0x0E}, {0x10, 0x08, 0x0C}, {0x10, 0x08, 0x0A}, /* Index 0xD0~0xD3 */ {0x10, 0x08, 0x08}, {0x10, 0x0A, 0x08}, {0x10, 0x0C, 0x08}, {0x10, 0x0E, 0x08}, /* Index 0xD4~0xD7 */ {0x10, 0x10, 0x08}, {0x0E, 0x10, 0x08}, {0x0C, 0x10, 0x08}, {0x0A, 0x10, 0x08}, /* Index 0xD8~0xDB */ {0x08, 0x10, 0x08}, {0x08, 0x10, 0x0A}, {0x08, 0x10, 0x0C}, {0x08, 0x10, 0x0E}, /* Index 0xDC~0xDF */ {0x08, 0x10, 0x10}, {0x08, 0x0E, 0x10}, {0x08, 0x0C, 0x10}, {0x08, 0x0A, 0x10}, /* Index 0xE0~0xE3 */ {0x0B, 0x0B, 0x10}, {0x0C, 0x0B, 0x10}, {0x0D, 0x0B, 0x10}, {0x0F, 0x0B, 0x10}, /* Index 0xE4~0xE7 */ {0x10, 0x0B, 0x10}, {0x10, 0x0B, 0x0F}, {0x10, 0x0B, 0x0D}, {0x10, 0x0B, 0x0C}, /* Index 0xE8~0xEB */ {0x10, 0x0B, 0x0B}, {0x10, 0x0C, 0x0B}, {0x10, 0x0D, 0x0B}, {0x10, 0x0F, 0x0B}, /* Index 0xEC~0xEF */ {0x10, 0x10, 0x0B}, {0x0F, 0x10, 0x0B}, {0x0D, 0x10, 0x0B}, {0x0C, 0x10, 0x0B}, /* Index 0xF0~0xF3 */ {0x0B, 0x10, 0x0B}, {0x0B, 0x10, 0x0C}, {0x0B, 0x10, 0x0D}, {0x0B, 0x10, 0x0F}, /* Index 0xF4~0xF7 */ {0x0B, 0x10, 0x10}, {0x0B, 0x0F, 0x10}, {0x0B, 0x0D, 0x10}, {0x0B, 0x0C, 0x10}, /* Index 0xF8~0xFB */ {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, /* Index 0xFC~0xFF */ {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00} }; static struct via_device_mapping device_mapping[] = { {VIA_LDVP0, "LDVP0"}, {VIA_LDVP1, "LDVP1"}, {VIA_DVP0, "DVP0"}, {VIA_CRT, "CRT"}, {VIA_DVP1, "DVP1"}, {VIA_LVDS1, "LVDS1"}, {VIA_LVDS2, "LVDS2"} }; /* structure with function pointers to support clock control */ static struct via_clock clock; static void load_fix_bit_crtc_reg(void); static void init_gfx_chip_info(int chip_type); static void init_tmds_chip_info(void); static void init_lvds_chip_info(void); static void device_screen_off(void); static void device_screen_on(void); static void set_display_channel(void); static void device_off(void); static void device_on(void); static void enable_second_display_channel(void); static void disable_second_display_channel(void); void viafb_lock_crt(void) { viafb_write_reg_mask(CR11, VIACR, BIT7, BIT7); } void viafb_unlock_crt(void) { viafb_write_reg_mask(CR11, VIACR, 0, BIT7); viafb_write_reg_mask(CR47, VIACR, 0, BIT0); } static void write_dac_reg(u8 index, u8 r, u8 g, u8 b) { outb(index, LUT_INDEX_WRITE); outb(r, LUT_DATA); outb(g, LUT_DATA); outb(b, LUT_DATA); } static u32 get_dvi_devices(int output_interface) { switch (output_interface) { case INTERFACE_DVP0: return VIA_DVP0 | VIA_LDVP0; case INTERFACE_DVP1: if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) return VIA_LDVP1; else return VIA_DVP1; case INTERFACE_DFP_HIGH: if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) return 0; else return VIA_LVDS2 | VIA_DVP0; case INTERFACE_DFP_LOW: if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) return 0; else return VIA_DVP1 | VIA_LVDS1; case INTERFACE_TMDS: return VIA_LVDS1; } return 0; } static u32 get_lcd_devices(int output_interface) { switch (output_interface) { case INTERFACE_DVP0: return VIA_DVP0; case INTERFACE_DVP1: return VIA_DVP1; case INTERFACE_DFP_HIGH: return VIA_LVDS2 | VIA_DVP0; case INTERFACE_DFP_LOW: return VIA_LVDS1 | VIA_DVP1; case INTERFACE_DFP: return VIA_LVDS1 | VIA_LVDS2; case INTERFACE_LVDS0: case INTERFACE_LVDS0LVDS1: return VIA_LVDS1; case INTERFACE_LVDS1: return VIA_LVDS2; } return 0; } /*Set IGA path for each device*/ void viafb_set_iga_path(void) { int crt_iga_path = 0; if (viafb_SAMM_ON == 1) { if (viafb_CRT_ON) { if (viafb_primary_dev == CRT_Device) crt_iga_path = IGA1; else crt_iga_path = IGA2; } if (viafb_DVI_ON) { if (viafb_primary_dev == DVI_Device) viaparinfo->tmds_setting_info->iga_path = IGA1; else viaparinfo->tmds_setting_info->iga_path = IGA2; } if (viafb_LCD_ON) { if (viafb_primary_dev == LCD_Device) { if (viafb_dual_fb && (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)) { viaparinfo-> lvds_setting_info->iga_path = IGA2; crt_iga_path = IGA1; viaparinfo-> tmds_setting_info->iga_path = IGA1; } else viaparinfo-> lvds_setting_info->iga_path = IGA1; } else { viaparinfo->lvds_setting_info->iga_path = IGA2; } } if (viafb_LCD2_ON) { if (LCD2_Device == viafb_primary_dev) viaparinfo->lvds_setting_info2->iga_path = IGA1; else viaparinfo->lvds_setting_info2->iga_path = IGA2; } } else { viafb_SAMM_ON = 0; if (viafb_CRT_ON && viafb_LCD_ON) { crt_iga_path = IGA1; viaparinfo->lvds_setting_info->iga_path = IGA2; } else if (viafb_CRT_ON && viafb_DVI_ON) { crt_iga_path = IGA1; viaparinfo->tmds_setting_info->iga_path = IGA2; } else if (viafb_LCD_ON && viafb_DVI_ON) { viaparinfo->tmds_setting_info->iga_path = IGA1; viaparinfo->lvds_setting_info->iga_path = IGA2; } else if (viafb_LCD_ON && viafb_LCD2_ON) { viaparinfo->lvds_setting_info->iga_path = IGA2; viaparinfo->lvds_setting_info2->iga_path = IGA2; } else if (viafb_CRT_ON) { crt_iga_path = IGA1; } else if (viafb_LCD_ON) { viaparinfo->lvds_setting_info->iga_path = IGA2; } else if (viafb_DVI_ON) { viaparinfo->tmds_setting_info->iga_path = IGA1; } } viaparinfo->shared->iga1_devices = 0; viaparinfo->shared->iga2_devices = 0; if (viafb_CRT_ON) { if (crt_iga_path == IGA1) viaparinfo->shared->iga1_devices |= VIA_CRT; else viaparinfo->shared->iga2_devices |= VIA_CRT; } if (viafb_DVI_ON) { if (viaparinfo->tmds_setting_info->iga_path == IGA1) viaparinfo->shared->iga1_devices |= get_dvi_devices( viaparinfo->chip_info-> tmds_chip_info.output_interface); else viaparinfo->shared->iga2_devices |= get_dvi_devices( viaparinfo->chip_info-> tmds_chip_info.output_interface); } if (viafb_LCD_ON) { if (viaparinfo->lvds_setting_info->iga_path == IGA1) viaparinfo->shared->iga1_devices |= get_lcd_devices( viaparinfo->chip_info-> lvds_chip_info.output_interface); else viaparinfo->shared->iga2_devices |= get_lcd_devices( viaparinfo->chip_info-> lvds_chip_info.output_interface); } if (viafb_LCD2_ON) { if (viaparinfo->lvds_setting_info2->iga_path == IGA1) viaparinfo->shared->iga1_devices |= get_lcd_devices( viaparinfo->chip_info-> lvds_chip_info2.output_interface); else viaparinfo->shared->iga2_devices |= get_lcd_devices( viaparinfo->chip_info-> lvds_chip_info2.output_interface); } /* looks like the OLPC has its display wired to DVP1 and LVDS2 */ if (machine_is_olpc()) viaparinfo->shared->iga2_devices = VIA_DVP1 | VIA_LVDS2; } static void set_color_register(u8 index, u8 red, u8 green, u8 blue) { outb(0xFF, 0x3C6); /* bit mask of palette */ outb(index, 0x3C8); outb(red, 0x3C9); outb(green, 0x3C9); outb(blue, 0x3C9); } void viafb_set_primary_color_register(u8 index, u8 red, u8 green, u8 blue) { viafb_write_reg_mask(0x1A, VIASR, 0x00, 0x01); set_color_register(index, red, green, blue); } void viafb_set_secondary_color_register(u8 index, u8 red, u8 green, u8 blue) { viafb_write_reg_mask(0x1A, VIASR, 0x01, 0x01); set_color_register(index, red, green, blue); } static void set_source_common(u8 index, u8 offset, u8 iga) { u8 value, mask = 1 << offset; switch (iga) { case IGA1: value = 0x00; break; case IGA2: value = mask; break; default: printk(KERN_WARNING "viafb: Unsupported source: %d\n", iga); return; } via_write_reg_mask(VIACR, index, value, mask); } static void set_crt_source(u8 iga) { u8 value; switch (iga) { case IGA1: value = 0x00; break; case IGA2: value = 0x40; break; default: printk(KERN_WARNING "viafb: Unsupported source: %d\n", iga); return; } via_write_reg_mask(VIASR, 0x16, value, 0x40); } static inline void set_ldvp0_source(u8 iga) { set_source_common(0x6C, 7, iga); } static inline void set_ldvp1_source(u8 iga) { set_source_common(0x93, 7, iga); } static inline void set_dvp0_source(u8 iga) { set_source_common(0x96, 4, iga); } static inline void set_dvp1_source(u8 iga) { set_source_common(0x9B, 4, iga); } static inline void set_lvds1_source(u8 iga) { set_source_common(0x99, 4, iga); } static inline void set_lvds2_source(u8 iga) { set_source_common(0x97, 4, iga); } void via_set_source(u32 devices, u8 iga) { if (devices & VIA_LDVP0) set_ldvp0_source(iga); if (devices & VIA_LDVP1) set_ldvp1_source(iga); if (devices & VIA_DVP0) set_dvp0_source(iga); if (devices & VIA_CRT) set_crt_source(iga); if (devices & VIA_DVP1) set_dvp1_source(iga); if (devices & VIA_LVDS1) set_lvds1_source(iga); if (devices & VIA_LVDS2) set_lvds2_source(iga); } static void set_crt_state(u8 state) { u8 value; switch (state) { case VIA_STATE_ON: value = 0x00; break; case VIA_STATE_STANDBY: value = 0x10; break; case VIA_STATE_SUSPEND: value = 0x20; break; case VIA_STATE_OFF: value = 0x30; break; default: return; } via_write_reg_mask(VIACR, 0x36, value, 0x30); } static void set_dvp0_state(u8 state) { u8 value; switch (state) { case VIA_STATE_ON: value = 0xC0; break; case VIA_STATE_OFF: value = 0x00; break; default: return; } via_write_reg_mask(VIASR, 0x1E, value, 0xC0); } static void set_dvp1_state(u8 state) { u8 value; switch (state) { case VIA_STATE_ON: value = 0x30; break; case VIA_STATE_OFF: value = 0x00; break; default: return; } via_write_reg_mask(VIASR, 0x1E, value, 0x30); } static void set_lvds1_state(u8 state) { u8 value; switch (state) { case VIA_STATE_ON: value = 0x03; break; case VIA_STATE_OFF: value = 0x00; break; default: return; } via_write_reg_mask(VIASR, 0x2A, value, 0x03); } static void set_lvds2_state(u8 state) { u8 value; switch (state) { case VIA_STATE_ON: value = 0x0C; break; case VIA_STATE_OFF: value = 0x00; break; default: return; } via_write_reg_mask(VIASR, 0x2A, value, 0x0C); } void via_set_state(u32 devices, u8 state) { /* TODO: Can we enable/disable these devices? How? if (devices & VIA_LDVP0) if (devices & VIA_LDVP1) */ if (devices & VIA_DVP0) set_dvp0_state(state); if (devices & VIA_CRT) set_crt_state(state); if (devices & VIA_DVP1) set_dvp1_state(state); if (devices & VIA_LVDS1) set_lvds1_state(state); if (devices & VIA_LVDS2) set_lvds2_state(state); } void via_set_sync_polarity(u32 devices, u8 polarity) { if (polarity & ~(VIA_HSYNC_NEGATIVE | VIA_VSYNC_NEGATIVE)) { printk(KERN_WARNING "viafb: Unsupported polarity: %d\n", polarity); return; } if (devices & VIA_CRT) via_write_misc_reg_mask(polarity << 6, 0xC0); if (devices & VIA_DVP1) via_write_reg_mask(VIACR, 0x9B, polarity << 5, 0x60); if (devices & VIA_LVDS1) via_write_reg_mask(VIACR, 0x99, polarity << 5, 0x60); if (devices & VIA_LVDS2) via_write_reg_mask(VIACR, 0x97, polarity << 5, 0x60); } u32 via_parse_odev(char *input, char **end) { char *ptr = input; u32 odev = 0; bool next = true; int i, len; while (next) { next = false; for (i = 0; i < ARRAY_SIZE(device_mapping); i++) { len = strlen(device_mapping[i].name); if (!strncmp(ptr, device_mapping[i].name, len)) { odev |= device_mapping[i].device; ptr += len; if (*ptr == ',') { ptr++; next = true; } } } } *end = ptr; return odev; } void via_odev_to_seq(struct seq_file *m, u32 odev) { int i, count = 0; for (i = 0; i < ARRAY_SIZE(device_mapping); i++) { if (odev & device_mapping[i].device) { if (count > 0) seq_putc(m, ','); seq_puts(m, device_mapping[i].name); count++; } } seq_putc(m, '\n'); } static void load_fix_bit_crtc_reg(void) { viafb_unlock_crt(); /* always set to 1 */ viafb_write_reg_mask(CR03, VIACR, 0x80, BIT7); /* line compare should set all bits = 1 (extend modes) */ viafb_write_reg_mask(CR35, VIACR, 0x10, BIT4); /* line compare should set all bits = 1 (extend modes) */ viafb_write_reg_mask(CR33, VIACR, 0x06, BIT0 + BIT1 + BIT2); /*viafb_write_reg_mask(CR32, VIACR, 0x01, BIT0); */ viafb_lock_crt(); /* If K8M800, enable Prefetch Mode. */ if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) || (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890)) viafb_write_reg_mask(CR33, VIACR, 0x08, BIT3); if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) && (viaparinfo->chip_info->gfx_chip_revision == CLE266_REVISION_AX)) viafb_write_reg_mask(SR1A, VIASR, 0x02, BIT1); } void viafb_load_reg(int timing_value, int viafb_load_reg_num, struct io_register *reg, int io_type) { int reg_mask; int bit_num = 0; int data; int i, j; int shift_next_reg; int start_index, end_index, cr_index; u16 get_bit; for (i = 0; i < viafb_load_reg_num; i++) { reg_mask = 0; data = 0; start_index = reg[i].start_bit; end_index = reg[i].end_bit; cr_index = reg[i].io_addr; shift_next_reg = bit_num; for (j = start_index; j <= end_index; j++) { /*if (bit_num==8) timing_value = timing_value >>8; */ reg_mask = reg_mask | (BIT0 << j); get_bit = (timing_value & (BIT0 << bit_num)); data = data | ((get_bit >> shift_next_reg) << start_index); bit_num++; } if (io_type == VIACR) viafb_write_reg_mask(cr_index, VIACR, data, reg_mask); else viafb_write_reg_mask(cr_index, VIASR, data, reg_mask); } } /* Write Registers */ void viafb_write_regx(struct io_reg RegTable[], int ItemNum) { int i; /*DEBUG_MSG(KERN_INFO "Table Size : %x!!\n",ItemNum ); */ for (i = 0; i < ItemNum; i++) via_write_reg_mask(RegTable[i].port, RegTable[i].index, RegTable[i].value, RegTable[i].mask); } void viafb_load_fetch_count_reg(int h_addr, int bpp_byte, int set_iga) { int reg_value; int viafb_load_reg_num; struct io_register *reg = NULL; switch (set_iga) { case IGA1: reg_value = IGA1_FETCH_COUNT_FORMULA(h_addr, bpp_byte); viafb_load_reg_num = fetch_count_reg. iga1_fetch_count_reg.reg_num; reg = fetch_count_reg.iga1_fetch_count_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR); break; case IGA2: reg_value = IGA2_FETCH_COUNT_FORMULA(h_addr, bpp_byte); viafb_load_reg_num = fetch_count_reg. iga2_fetch_count_reg.reg_num; reg = fetch_count_reg.iga2_fetch_count_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR); break; } } void viafb_load_FIFO_reg(int set_iga, int hor_active, int ver_active) { int reg_value; int viafb_load_reg_num; struct io_register *reg = NULL; int iga1_fifo_max_depth = 0, iga1_fifo_threshold = 0, iga1_fifo_high_threshold = 0, iga1_display_queue_expire_num = 0; int iga2_fifo_max_depth = 0, iga2_fifo_threshold = 0, iga2_fifo_high_threshold = 0, iga2_display_queue_expire_num = 0; if (set_iga == IGA1) { if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) { iga1_fifo_max_depth = K800_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = K800_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = K800_IGA1_FIFO_HIGH_THRESHOLD; /* If resolution > 1280x1024, expire length = 64, else expire length = 128 */ if ((hor_active > 1280) && (ver_active > 1024)) iga1_display_queue_expire_num = 16; else iga1_display_queue_expire_num = K800_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_PM800) { iga1_fifo_max_depth = P880_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = P880_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = P880_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = P880_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; /* If resolution > 1280x1024, expire length = 64, else expire length = 128 */ if ((hor_active > 1280) && (ver_active > 1024)) iga1_display_queue_expire_num = 16; else iga1_display_queue_expire_num = P880_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CN700) { iga1_fifo_max_depth = CN700_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = CN700_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = CN700_IGA1_FIFO_HIGH_THRESHOLD; /* If resolution > 1280x1024, expire length = 64, else expire length = 128 */ if ((hor_active > 1280) && (ver_active > 1024)) iga1_display_queue_expire_num = 16; else iga1_display_queue_expire_num = CN700_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) { iga1_fifo_max_depth = CX700_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = CX700_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = CX700_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = CX700_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890) { iga1_fifo_max_depth = K8M890_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = K8M890_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = K8M890_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = K8M890_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M890) { iga1_fifo_max_depth = P4M890_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = P4M890_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = P4M890_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = P4M890_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M900) { iga1_fifo_max_depth = P4M900_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = P4M900_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = P4M900_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = P4M900_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX800) { iga1_fifo_max_depth = VX800_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = VX800_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = VX800_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = VX800_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX855) { iga1_fifo_max_depth = VX855_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = VX855_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = VX855_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = VX855_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX900) { iga1_fifo_max_depth = VX900_IGA1_FIFO_MAX_DEPTH; iga1_fifo_threshold = VX900_IGA1_FIFO_THRESHOLD; iga1_fifo_high_threshold = VX900_IGA1_FIFO_HIGH_THRESHOLD; iga1_display_queue_expire_num = VX900_IGA1_DISPLAY_QUEUE_EXPIRE_NUM; } /* Set Display FIFO Depath Select */ reg_value = IGA1_FIFO_DEPTH_SELECT_FORMULA(iga1_fifo_max_depth); viafb_load_reg_num = display_fifo_depth_reg.iga1_fifo_depth_select_reg.reg_num; reg = display_fifo_depth_reg.iga1_fifo_depth_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR); /* Set Display FIFO Threshold Select */ reg_value = IGA1_FIFO_THRESHOLD_FORMULA(iga1_fifo_threshold); viafb_load_reg_num = fifo_threshold_select_reg. iga1_fifo_threshold_select_reg.reg_num; reg = fifo_threshold_select_reg. iga1_fifo_threshold_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR); /* Set FIFO High Threshold Select */ reg_value = IGA1_FIFO_HIGH_THRESHOLD_FORMULA(iga1_fifo_high_threshold); viafb_load_reg_num = fifo_high_threshold_select_reg. iga1_fifo_high_threshold_select_reg.reg_num; reg = fifo_high_threshold_select_reg. iga1_fifo_high_threshold_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR); /* Set Display Queue Expire Num */ reg_value = IGA1_DISPLAY_QUEUE_EXPIRE_NUM_FORMULA (iga1_display_queue_expire_num); viafb_load_reg_num = display_queue_expire_num_reg. iga1_display_queue_expire_num_reg.reg_num; reg = display_queue_expire_num_reg. iga1_display_queue_expire_num_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR); } else { if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) { iga2_fifo_max_depth = K800_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = K800_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = K800_IGA2_FIFO_HIGH_THRESHOLD; /* If resolution > 1280x1024, expire length = 64, else expire length = 128 */ if ((hor_active > 1280) && (ver_active > 1024)) iga2_display_queue_expire_num = 16; else iga2_display_queue_expire_num = K800_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_PM800) { iga2_fifo_max_depth = P880_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = P880_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = P880_IGA2_FIFO_HIGH_THRESHOLD; /* If resolution > 1280x1024, expire length = 64, else expire length = 128 */ if ((hor_active > 1280) && (ver_active > 1024)) iga2_display_queue_expire_num = 16; else iga2_display_queue_expire_num = P880_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CN700) { iga2_fifo_max_depth = CN700_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = CN700_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = CN700_IGA2_FIFO_HIGH_THRESHOLD; /* If resolution > 1280x1024, expire length = 64, else expire length = 128 */ if ((hor_active > 1280) && (ver_active > 1024)) iga2_display_queue_expire_num = 16; else iga2_display_queue_expire_num = CN700_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) { iga2_fifo_max_depth = CX700_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = CX700_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = CX700_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = CX700_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890) { iga2_fifo_max_depth = K8M890_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = K8M890_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = K8M890_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = K8M890_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M890) { iga2_fifo_max_depth = P4M890_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = P4M890_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = P4M890_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = P4M890_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M900) { iga2_fifo_max_depth = P4M900_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = P4M900_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = P4M900_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = P4M900_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX800) { iga2_fifo_max_depth = VX800_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = VX800_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = VX800_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = VX800_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX855) { iga2_fifo_max_depth = VX855_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = VX855_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = VX855_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = VX855_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX900) { iga2_fifo_max_depth = VX900_IGA2_FIFO_MAX_DEPTH; iga2_fifo_threshold = VX900_IGA2_FIFO_THRESHOLD; iga2_fifo_high_threshold = VX900_IGA2_FIFO_HIGH_THRESHOLD; iga2_display_queue_expire_num = VX900_IGA2_DISPLAY_QUEUE_EXPIRE_NUM; } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) { /* Set Display FIFO Depath Select */ reg_value = IGA2_FIFO_DEPTH_SELECT_FORMULA(iga2_fifo_max_depth) - 1; /* Patch LCD in IGA2 case */ viafb_load_reg_num = display_fifo_depth_reg. iga2_fifo_depth_select_reg.reg_num; reg = display_fifo_depth_reg. iga2_fifo_depth_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR); } else { /* Set Display FIFO Depath Select */ reg_value = IGA2_FIFO_DEPTH_SELECT_FORMULA(iga2_fifo_max_depth); viafb_load_reg_num = display_fifo_depth_reg. iga2_fifo_depth_select_reg.reg_num; reg = display_fifo_depth_reg. iga2_fifo_depth_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR); } /* Set Display FIFO Threshold Select */ reg_value = IGA2_FIFO_THRESHOLD_FORMULA(iga2_fifo_threshold); viafb_load_reg_num = fifo_threshold_select_reg. iga2_fifo_threshold_select_reg.reg_num; reg = fifo_threshold_select_reg. iga2_fifo_threshold_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR); /* Set FIFO High Threshold Select */ reg_value = IGA2_FIFO_HIGH_THRESHOLD_FORMULA(iga2_fifo_high_threshold); viafb_load_reg_num = fifo_high_threshold_select_reg. iga2_fifo_high_threshold_select_reg.reg_num; reg = fifo_high_threshold_select_reg. iga2_fifo_high_threshold_select_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR); /* Set Display Queue Expire Num */ reg_value = IGA2_DISPLAY_QUEUE_EXPIRE_NUM_FORMULA (iga2_display_queue_expire_num); viafb_load_reg_num = display_queue_expire_num_reg. iga2_display_queue_expire_num_reg.reg_num; reg = display_queue_expire_num_reg. iga2_display_queue_expire_num_reg.reg; viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR); } } static struct via_pll_config get_pll_config(struct pll_limit *limits, int size, int clk) { struct via_pll_config cur, up, down, best = {0, 1, 0}; const u32 f0 = 14318180; /* X1 frequency */ int i, f; for (i = 0; i < size; i++) { cur.rshift = limits[i].rshift; cur.divisor = limits[i].divisor; cur.multiplier = clk / ((f0 / cur.divisor)>>cur.rshift); f = abs(get_pll_output_frequency(f0, cur) - clk); up = down = cur; up.multiplier++; down.multiplier--; if (abs(get_pll_output_frequency(f0, up) - clk) < f) cur = up; else if (abs(get_pll_output_frequency(f0, down) - clk) < f) cur = down; if (cur.multiplier < limits[i].multiplier_min) cur.multiplier = limits[i].multiplier_min; else if (cur.multiplier > limits[i].multiplier_max) cur.multiplier = limits[i].multiplier_max; f = abs(get_pll_output_frequency(f0, cur) - clk); if (f < abs(get_pll_output_frequency(f0, best) - clk)) best = cur; } return best; } static struct via_pll_config get_best_pll_config(int clk) { struct via_pll_config config; switch (viaparinfo->chip_info->gfx_chip_name) { case UNICHROME_CLE266: case UNICHROME_K400: config = get_pll_config(cle266_pll_limits, ARRAY_SIZE(cle266_pll_limits), clk); break; case UNICHROME_K800: case UNICHROME_PM800: case UNICHROME_CN700: config = get_pll_config(k800_pll_limits, ARRAY_SIZE(k800_pll_limits), clk); break; case UNICHROME_CX700: case UNICHROME_CN750: case UNICHROME_K8M890: case UNICHROME_P4M890: case UNICHROME_P4M900: case UNICHROME_VX800: config = get_pll_config(cx700_pll_limits, ARRAY_SIZE(cx700_pll_limits), clk); break; case UNICHROME_VX855: case UNICHROME_VX900: config = get_pll_config(vx855_pll_limits, ARRAY_SIZE(vx855_pll_limits), clk); break; } return config; } /* Set VCLK*/ void viafb_set_vclock(u32 clk, int set_iga) { struct via_pll_config config = get_best_pll_config(clk); if (set_iga == IGA1) clock.set_primary_pll(config); if (set_iga == IGA2) clock.set_secondary_pll(config); /* Fire! */ via_write_misc_reg_mask(0x0C, 0x0C); /* select external clock */ } struct via_display_timing var_to_timing(const struct fb_var_screeninfo *var, u16 cxres, u16 cyres) { struct via_display_timing timing; u16 dx = (var->xres - cxres) / 2, dy = (var->yres - cyres) / 2; timing.hor_addr = cxres; timing.hor_sync_start = timing.hor_addr + var->right_margin + dx; timing.hor_sync_end = timing.hor_sync_start + var->hsync_len; timing.hor_total = timing.hor_sync_end + var->left_margin + dx; timing.hor_blank_start = timing.hor_addr + dx; timing.hor_blank_end = timing.hor_total - dx; timing.ver_addr = cyres; timing.ver_sync_start = timing.ver_addr + var->lower_margin + dy; timing.ver_sync_end = timing.ver_sync_start + var->vsync_len; timing.ver_total = timing.ver_sync_end + var->upper_margin + dy; timing.ver_blank_start = timing.ver_addr + dy; timing.ver_blank_end = timing.ver_total - dy; return timing; } void viafb_fill_crtc_timing(const struct fb_var_screeninfo *var, u16 cxres, u16 cyres, int iga) { struct via_display_timing crt_reg = var_to_timing(var, cxres ? cxres : var->xres, cyres ? cyres : var->yres); if (iga == IGA1) via_set_primary_timing(&crt_reg); else if (iga == IGA2) via_set_secondary_timing(&crt_reg); viafb_load_fetch_count_reg(var->xres, var->bits_per_pixel / 8, iga); if (viaparinfo->chip_info->gfx_chip_name != UNICHROME_CLE266 && viaparinfo->chip_info->gfx_chip_name != UNICHROME_K400) viafb_load_FIFO_reg(iga, var->xres, var->yres); viafb_set_vclock(PICOS2KHZ(var->pixclock) * 1000, iga); } void viafb_init_chip_info(int chip_type) { via_clock_init(&clock, chip_type); init_gfx_chip_info(chip_type); init_tmds_chip_info(); init_lvds_chip_info(); /*Set IGA path for each device */ viafb_set_iga_path(); viaparinfo->lvds_setting_info->display_method = viafb_lcd_dsp_method; viaparinfo->lvds_setting_info->lcd_mode = viafb_lcd_mode; viaparinfo->lvds_setting_info2->display_method = viaparinfo->lvds_setting_info->display_method; viaparinfo->lvds_setting_info2->lcd_mode = viaparinfo->lvds_setting_info->lcd_mode; } void viafb_update_device_setting(int hres, int vres, int bpp, int flag) { if (flag == 0) { viaparinfo->tmds_setting_info->h_active = hres; viaparinfo->tmds_setting_info->v_active = vres; } else { if (viaparinfo->tmds_setting_info->iga_path == IGA2) { viaparinfo->tmds_setting_info->h_active = hres; viaparinfo->tmds_setting_info->v_active = vres; } } } static void init_gfx_chip_info(int chip_type) { u8 tmp; viaparinfo->chip_info->gfx_chip_name = chip_type; /* Check revision of CLE266 Chip */ if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) { /* CR4F only define in CLE266.CX chip */ tmp = viafb_read_reg(VIACR, CR4F); viafb_write_reg(CR4F, VIACR, 0x55); if (viafb_read_reg(VIACR, CR4F) != 0x55) viaparinfo->chip_info->gfx_chip_revision = CLE266_REVISION_AX; else viaparinfo->chip_info->gfx_chip_revision = CLE266_REVISION_CX; /* restore orignal CR4F value */ viafb_write_reg(CR4F, VIACR, tmp); } if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) { tmp = viafb_read_reg(VIASR, SR43); DEBUG_MSG(KERN_INFO "SR43:%X\n", tmp); if (tmp & 0x02) { viaparinfo->chip_info->gfx_chip_revision = CX700_REVISION_700M2; } else if (tmp & 0x40) { viaparinfo->chip_info->gfx_chip_revision = CX700_REVISION_700M; } else { viaparinfo->chip_info->gfx_chip_revision = CX700_REVISION_700; } } /* Determine which 2D engine we have */ switch (viaparinfo->chip_info->gfx_chip_name) { case UNICHROME_VX800: case UNICHROME_VX855: case UNICHROME_VX900: viaparinfo->chip_info->twod_engine = VIA_2D_ENG_M1; break; case UNICHROME_K8M890: case UNICHROME_P4M900: viaparinfo->chip_info->twod_engine = VIA_2D_ENG_H5; break; default: viaparinfo->chip_info->twod_engine = VIA_2D_ENG_H2; break; } } static void init_tmds_chip_info(void) { viafb_tmds_trasmitter_identify(); if (INTERFACE_NONE == viaparinfo->chip_info->tmds_chip_info. output_interface) { switch (viaparinfo->chip_info->gfx_chip_name) { case UNICHROME_CX700: { /* we should check support by hardware layout.*/ if ((viafb_display_hardware_layout == HW_LAYOUT_DVI_ONLY) || (viafb_display_hardware_layout == HW_LAYOUT_LCD_DVI)) { viaparinfo->chip_info->tmds_chip_info. output_interface = INTERFACE_TMDS; } else { viaparinfo->chip_info->tmds_chip_info. output_interface = INTERFACE_NONE; } break; } case UNICHROME_K8M890: case UNICHROME_P4M900: case UNICHROME_P4M890: /* TMDS on PCIE, we set DFPLOW as default. */ viaparinfo->chip_info->tmds_chip_info.output_interface = INTERFACE_DFP_LOW; break; default: { /* set DVP1 default for DVI */ viaparinfo->chip_info->tmds_chip_info .output_interface = INTERFACE_DVP1; } } } DEBUG_MSG(KERN_INFO "TMDS Chip = %d\n", viaparinfo->chip_info->tmds_chip_info.tmds_chip_name); viafb_init_dvi_size(&viaparinfo->shared->chip_info.tmds_chip_info, &viaparinfo->shared->tmds_setting_info); } static void init_lvds_chip_info(void) { viafb_lvds_trasmitter_identify(); viafb_init_lcd_size(); viafb_init_lvds_output_interface(&viaparinfo->chip_info->lvds_chip_info, viaparinfo->lvds_setting_info); if (viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name) { viafb_init_lvds_output_interface(&viaparinfo->chip_info-> lvds_chip_info2, viaparinfo->lvds_setting_info2); } /*If CX700,two singel LCD, we need to reassign LCD interface to different LVDS port */ if ((UNICHROME_CX700 == viaparinfo->chip_info->gfx_chip_name) && (HW_LAYOUT_LCD1_LCD2 == viafb_display_hardware_layout)) { if ((INTEGRATED_LVDS == viaparinfo->chip_info->lvds_chip_info. lvds_chip_name) && (INTEGRATED_LVDS == viaparinfo->chip_info-> lvds_chip_info2.lvds_chip_name)) { viaparinfo->chip_info->lvds_chip_info.output_interface = INTERFACE_LVDS0; viaparinfo->chip_info->lvds_chip_info2. output_interface = INTERFACE_LVDS1; } } DEBUG_MSG(KERN_INFO "LVDS Chip = %d\n", viaparinfo->chip_info->lvds_chip_info.lvds_chip_name); DEBUG_MSG(KERN_INFO "LVDS1 output_interface = %d\n", viaparinfo->chip_info->lvds_chip_info.output_interface); DEBUG_MSG(KERN_INFO "LVDS2 output_interface = %d\n", viaparinfo->chip_info->lvds_chip_info.output_interface); } void viafb_init_dac(int set_iga) { int i; u8 tmp; if (set_iga == IGA1) { /* access Primary Display's LUT */ viafb_write_reg_mask(SR1A, VIASR, 0x00, BIT0); /* turn off LCK */ viafb_write_reg_mask(SR1B, VIASR, 0x00, BIT7 + BIT6); for (i = 0; i < 256; i++) { write_dac_reg(i, palLUT_table[i].red, palLUT_table[i].green, palLUT_table[i].blue); } /* turn on LCK */ viafb_write_reg_mask(SR1B, VIASR, 0xC0, BIT7 + BIT6); } else { tmp = viafb_read_reg(VIACR, CR6A); /* access Secondary Display's LUT */ viafb_write_reg_mask(CR6A, VIACR, 0x40, BIT6); viafb_write_reg_mask(SR1A, VIASR, 0x01, BIT0); for (i = 0; i < 256; i++) { write_dac_reg(i, palLUT_table[i].red, palLUT_table[i].green, palLUT_table[i].blue); } /* set IGA1 DAC for default */ viafb_write_reg_mask(SR1A, VIASR, 0x00, BIT0); viafb_write_reg(CR6A, VIACR, tmp); } } static void device_screen_off(void) { /* turn off CRT screen (IGA1) */ viafb_write_reg_mask(SR01, VIASR, 0x20, BIT5); } static void device_screen_on(void) { /* turn on CRT screen (IGA1) */ viafb_write_reg_mask(SR01, VIASR, 0x00, BIT5); } static void set_display_channel(void) { /*If viafb_LCD2_ON, on cx700, internal lvds's information is keeped on lvds_setting_info2 */ if (viafb_LCD2_ON && viaparinfo->lvds_setting_info2->device_lcd_dualedge) { /* For dual channel LCD: */ /* Set to Dual LVDS channel. */ viafb_write_reg_mask(CRD2, VIACR, 0x20, BIT4 + BIT5); } else if (viafb_LCD_ON && viafb_DVI_ON) { /* For LCD+DFP: */ /* Set to LVDS1 + TMDS channel. */ viafb_write_reg_mask(CRD2, VIACR, 0x10, BIT4 + BIT5); } else if (viafb_DVI_ON) { /* Set to single TMDS channel. */ viafb_write_reg_mask(CRD2, VIACR, 0x30, BIT4 + BIT5); } else if (viafb_LCD_ON) { if (viaparinfo->lvds_setting_info->device_lcd_dualedge) { /* For dual channel LCD: */ /* Set to Dual LVDS channel. */ viafb_write_reg_mask(CRD2, VIACR, 0x20, BIT4 + BIT5); } else { /* Set to LVDS0 + LVDS1 channel. */ viafb_write_reg_mask(CRD2, VIACR, 0x00, BIT4 + BIT5); } } } static u8 get_sync(struct fb_var_screeninfo *var) { u8 polarity = 0; if (!(var->sync & FB_SYNC_HOR_HIGH_ACT)) polarity |= VIA_HSYNC_NEGATIVE; if (!(var->sync & FB_SYNC_VERT_HIGH_ACT)) polarity |= VIA_VSYNC_NEGATIVE; return polarity; } static void hw_init(void) { int i; inb(VIAStatus); outb(0x00, VIAAR); /* Write Common Setting for Video Mode */ viafb_write_regx(common_vga, ARRAY_SIZE(common_vga)); switch (viaparinfo->chip_info->gfx_chip_name) { case UNICHROME_CLE266: viafb_write_regx(CLE266_ModeXregs, NUM_TOTAL_CLE266_ModeXregs); break; case UNICHROME_K400: viafb_write_regx(KM400_ModeXregs, NUM_TOTAL_KM400_ModeXregs); break; case UNICHROME_K800: case UNICHROME_PM800: viafb_write_regx(CN400_ModeXregs, NUM_TOTAL_CN400_ModeXregs); break; case UNICHROME_CN700: case UNICHROME_K8M890: case UNICHROME_P4M890: case UNICHROME_P4M900: viafb_write_regx(CN700_ModeXregs, NUM_TOTAL_CN700_ModeXregs); break; case UNICHROME_CX700: case UNICHROME_VX800: viafb_write_regx(CX700_ModeXregs, NUM_TOTAL_CX700_ModeXregs); break; case UNICHROME_VX855: case UNICHROME_VX900: viafb_write_regx(VX855_ModeXregs, NUM_TOTAL_VX855_ModeXregs); break; } /* magic required on VX900 for correct modesetting on IGA1 */ via_write_reg_mask(VIACR, 0x45, 0x00, 0x01); /* probably this should go to the scaling code one day */ via_write_reg_mask(VIACR, 0xFD, 0, 0x80); /* VX900 hw scale on IGA2 */ viafb_write_regx(scaling_parameters, ARRAY_SIZE(scaling_parameters)); /* Fill VPIT Parameters */ /* Write Misc Register */ outb(VPIT.Misc, VIA_MISC_REG_WRITE); /* Write Sequencer */ for (i = 1; i <= StdSR; i++) via_write_reg(VIASR, i, VPIT.SR[i - 1]); viafb_write_reg_mask(0x15, VIASR, 0xA2, 0xA2); /* Write Graphic Controller */ for (i = 0; i < StdGR; i++) via_write_reg(VIAGR, i, VPIT.GR[i]); /* Write Attribute Controller */ for (i = 0; i < StdAR; i++) { inb(VIAStatus); outb(i, VIAAR); outb(VPIT.AR[i], VIAAR); } inb(VIAStatus); outb(0x20, VIAAR); load_fix_bit_crtc_reg(); } int viafb_setmode(void) { int j, cxres = 0, cyres = 0; int port; u32 devices = viaparinfo->shared->iga1_devices | viaparinfo->shared->iga2_devices; u8 value, index, mask; struct fb_var_screeninfo var2; device_screen_off(); device_off(); via_set_state(devices, VIA_STATE_OFF); hw_init(); /* Update Patch Register */ if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266 || viaparinfo->chip_info->gfx_chip_name == UNICHROME_K400) && viafbinfo->var.xres == 1024 && viafbinfo->var.yres == 768) { for (j = 0; j < res_patch_table[0].table_length; j++) { index = res_patch_table[0].io_reg_table[j].index; port = res_patch_table[0].io_reg_table[j].port; value = res_patch_table[0].io_reg_table[j].value; mask = res_patch_table[0].io_reg_table[j].mask; viafb_write_reg_mask(index, port, value, mask); } } via_set_primary_pitch(viafbinfo->fix.line_length); via_set_secondary_pitch(viafb_dual_fb ? viafbinfo1->fix.line_length : viafbinfo->fix.line_length); via_set_primary_color_depth(viaparinfo->depth); via_set_secondary_color_depth(viafb_dual_fb ? viaparinfo1->depth : viaparinfo->depth); via_set_source(viaparinfo->shared->iga1_devices, IGA1); via_set_source(viaparinfo->shared->iga2_devices, IGA2); if (viaparinfo->shared->iga2_devices) enable_second_display_channel(); else disable_second_display_channel(); /* Update Refresh Rate Setting */ /* Clear On Screen */ if (viafb_dual_fb) { var2 = viafbinfo1->var; } else if (viafb_SAMM_ON) { viafb_fill_var_timing_info(&var2, viafb_get_best_mode( viafb_second_xres, viafb_second_yres, viafb_refresh1)); cxres = viafbinfo->var.xres; cyres = viafbinfo->var.yres; var2.bits_per_pixel = viafbinfo->var.bits_per_pixel; } /* CRT set mode */ if (viafb_CRT_ON) { if (viaparinfo->shared->iga2_devices & VIA_CRT && viafb_SAMM_ON) viafb_fill_crtc_timing(&var2, cxres, cyres, IGA2); else viafb_fill_crtc_timing(&viafbinfo->var, 0, 0, (viaparinfo->shared->iga1_devices & VIA_CRT) ? IGA1 : IGA2); /* Patch if set_hres is not 8 alignment (1366) to viafb_setmode to 8 alignment (1368),there is several pixels (2 pixels) on right side of screen. */ if (viafbinfo->var.xres % 8) { viafb_unlock_crt(); viafb_write_reg(CR02, VIACR, viafb_read_reg(VIACR, CR02) - 1); viafb_lock_crt(); } } if (viafb_DVI_ON) { if (viaparinfo->shared->tmds_setting_info.iga_path == IGA2 && viafb_SAMM_ON) viafb_dvi_set_mode(&var2, cxres, cyres, IGA2); else viafb_dvi_set_mode(&viafbinfo->var, 0, 0, viaparinfo->tmds_setting_info->iga_path); } if (viafb_LCD_ON) { if (viafb_SAMM_ON && (viaparinfo->lvds_setting_info->iga_path == IGA2)) { viafb_lcd_set_mode(&var2, cxres, cyres, viaparinfo->lvds_setting_info, &viaparinfo->chip_info->lvds_chip_info); } else { /* IGA1 doesn't have LCD scaling, so set it center. */ if (viaparinfo->lvds_setting_info->iga_path == IGA1) { viaparinfo->lvds_setting_info->display_method = LCD_CENTERING; } viafb_lcd_set_mode(&viafbinfo->var, 0, 0, viaparinfo->lvds_setting_info, &viaparinfo->chip_info->lvds_chip_info); } } if (viafb_LCD2_ON) { if (viafb_SAMM_ON && (viaparinfo->lvds_setting_info2->iga_path == IGA2)) { viafb_lcd_set_mode(&var2, cxres, cyres, viaparinfo->lvds_setting_info2, &viaparinfo->chip_info->lvds_chip_info2); } else { /* IGA1 doesn't have LCD scaling, so set it center. */ if (viaparinfo->lvds_setting_info2->iga_path == IGA1) { viaparinfo->lvds_setting_info2->display_method = LCD_CENTERING; } viafb_lcd_set_mode(&viafbinfo->var, 0, 0, viaparinfo->lvds_setting_info2, &viaparinfo->chip_info->lvds_chip_info2); } } if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) && (viafb_LCD_ON || viafb_DVI_ON)) set_display_channel(); /* If set mode normally, save resolution information for hot-plug . */ if (!viafb_hotplug) { viafb_hotplug_Xres = viafbinfo->var.xres; viafb_hotplug_Yres = viafbinfo->var.yres; viafb_hotplug_bpp = viafbinfo->var.bits_per_pixel; viafb_hotplug_refresh = viafb_refresh; if (viafb_DVI_ON) viafb_DeviceStatus = DVI_Device; else viafb_DeviceStatus = CRT_Device; } device_on(); if (!viafb_SAMM_ON) via_set_sync_polarity(devices, get_sync(&viafbinfo->var)); else { via_set_sync_polarity(viaparinfo->shared->iga1_devices, get_sync(&viafbinfo->var)); via_set_sync_polarity(viaparinfo->shared->iga2_devices, get_sync(&var2)); } clock.set_engine_pll_state(VIA_STATE_ON); clock.set_primary_clock_source(VIA_CLKSRC_X1, true); clock.set_secondary_clock_source(VIA_CLKSRC_X1, true); #ifdef CONFIG_FB_VIA_X_COMPATIBILITY clock.set_primary_pll_state(VIA_STATE_ON); clock.set_primary_clock_state(VIA_STATE_ON); clock.set_secondary_pll_state(VIA_STATE_ON); clock.set_secondary_clock_state(VIA_STATE_ON); #else if (viaparinfo->shared->iga1_devices) { clock.set_primary_pll_state(VIA_STATE_ON); clock.set_primary_clock_state(VIA_STATE_ON); } else { clock.set_primary_pll_state(VIA_STATE_OFF); clock.set_primary_clock_state(VIA_STATE_OFF); } if (viaparinfo->shared->iga2_devices) { clock.set_secondary_pll_state(VIA_STATE_ON); clock.set_secondary_clock_state(VIA_STATE_ON); } else { clock.set_secondary_pll_state(VIA_STATE_OFF); clock.set_secondary_clock_state(VIA_STATE_OFF); } #endif /*CONFIG_FB_VIA_X_COMPATIBILITY*/ via_set_state(devices, VIA_STATE_ON); device_screen_on(); return 1; } int viafb_get_refresh(int hres, int vres, u32 long_refresh) { const struct fb_videomode *best; best = viafb_get_best_mode(hres, vres, long_refresh); if (!best) return 60; if (abs(best->refresh - long_refresh) > 3) { if (hres == 1200 && vres == 900) return 49; /* OLPC DCON only supports 50 Hz */ else return 60; } return best->refresh; } static void device_off(void) { viafb_dvi_disable(); viafb_lcd_disable(); } static void device_on(void) { if (viafb_DVI_ON == 1) viafb_dvi_enable(); if (viafb_LCD_ON == 1) viafb_lcd_enable(); } static void enable_second_display_channel(void) { /* to enable second display channel. */ viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT6); viafb_write_reg_mask(CR6A, VIACR, BIT7, BIT7); viafb_write_reg_mask(CR6A, VIACR, BIT6, BIT6); } static void disable_second_display_channel(void) { /* to disable second display channel. */ viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT6); viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT7); viafb_write_reg_mask(CR6A, VIACR, BIT6, BIT6); } void viafb_set_dpa_gfx(int output_interface, struct GFX_DPA_SETTING\ *p_gfx_dpa_setting) { switch (output_interface) { case INTERFACE_DVP0: { /* DVP0 Clock Polarity and Adjust: */ viafb_write_reg_mask(CR96, VIACR, p_gfx_dpa_setting->DVP0, 0x0F); /* DVP0 Clock and Data Pads Driving: */ viafb_write_reg_mask(SR1E, VIASR, p_gfx_dpa_setting->DVP0ClockDri_S, BIT2); viafb_write_reg_mask(SR2A, VIASR, p_gfx_dpa_setting->DVP0ClockDri_S1, BIT4); viafb_write_reg_mask(SR1B, VIASR, p_gfx_dpa_setting->DVP0DataDri_S, BIT1); viafb_write_reg_mask(SR2A, VIASR, p_gfx_dpa_setting->DVP0DataDri_S1, BIT5); break; } case INTERFACE_DVP1: { /* DVP1 Clock Polarity and Adjust: */ viafb_write_reg_mask(CR9B, VIACR, p_gfx_dpa_setting->DVP1, 0x0F); /* DVP1 Clock and Data Pads Driving: */ viafb_write_reg_mask(SR65, VIASR, p_gfx_dpa_setting->DVP1Driving, 0x0F); break; } case INTERFACE_DFP_HIGH: { viafb_write_reg_mask(CR97, VIACR, p_gfx_dpa_setting->DFPHigh, 0x0F); break; } case INTERFACE_DFP_LOW: { viafb_write_reg_mask(CR99, VIACR, p_gfx_dpa_setting->DFPLow, 0x0F); break; } case INTERFACE_DFP: { viafb_write_reg_mask(CR97, VIACR, p_gfx_dpa_setting->DFPHigh, 0x0F); viafb_write_reg_mask(CR99, VIACR, p_gfx_dpa_setting->DFPLow, 0x0F); break; } } } void viafb_fill_var_timing_info(struct fb_var_screeninfo *var, const struct fb_videomode *mode) { var->pixclock = mode->pixclock; var->xres = mode->xres; var->yres = mode->yres; var->left_margin = mode->left_margin; var->right_margin = mode->right_margin; var->hsync_len = mode->hsync_len; var->upper_margin = mode->upper_margin; var->lower_margin = mode->lower_margin; var->vsync_len = mode->vsync_len; var->sync = mode->sync; }
gpl-2.0
cristianomatos/android_kernel_google_msm
drivers/media/video/tvaudio.c
4863
63582
/* * Driver for simple i2c audio chips. * * Copyright (c) 2000 Gerd Knorr * based on code by: * Eric Sandeen (eric_sandeen@bigfoot.com) * Steve VanDeBogart (vandebo@uclink.berkeley.edu) * Greg Alexander (galexand@acm.org) * * Copyright(c) 2005-2008 Mauro Carvalho Chehab * - Some cleanups, code fixes, etc * - Convert it to V4L2 API * * This code is placed under the terms of the GNU General Public License * * OPTIONS: * debug - set to 1 if you'd like to see debug messages * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <media/tvaudio.h> #include <media/v4l2-device.h> #include <media/v4l2-chip-ident.h> #include <media/i2c-addr.h> /* ---------------------------------------------------------------------- */ /* insmod args */ static int debug; /* insmod parameter */ module_param(debug, int, 0644); MODULE_DESCRIPTION("device driver for various i2c TV sound decoder / audiomux chips"); MODULE_AUTHOR("Eric Sandeen, Steve VanDeBogart, Greg Alexander, Gerd Knorr"); MODULE_LICENSE("GPL"); #define UNSET (-1U) /* ---------------------------------------------------------------------- */ /* our structs */ #define MAXREGS 256 struct CHIPSTATE; typedef int (*getvalue)(int); typedef int (*checkit)(struct CHIPSTATE*); typedef int (*initialize)(struct CHIPSTATE*); typedef int (*getmode)(struct CHIPSTATE*); typedef void (*setmode)(struct CHIPSTATE*, int mode); /* i2c command */ typedef struct AUDIOCMD { int count; /* # of bytes to send */ unsigned char bytes[MAXREGS+1]; /* addr, data, data, ... */ } audiocmd; /* chip description */ struct CHIPDESC { char *name; /* chip name */ int addr_lo, addr_hi; /* i2c address range */ int registers; /* # of registers */ int *insmodopt; checkit checkit; initialize initialize; int flags; #define CHIP_HAS_VOLUME 1 #define CHIP_HAS_BASSTREBLE 2 #define CHIP_HAS_INPUTSEL 4 #define CHIP_NEED_CHECKMODE 8 /* various i2c command sequences */ audiocmd init; /* which register has which value */ int leftreg,rightreg,treblereg,bassreg; /* initialize with (defaults to 65535/65535/32768/32768 */ int leftinit,rightinit,trebleinit,bassinit; /* functions to convert the values (v4l -> chip) */ getvalue volfunc,treblefunc,bassfunc; /* get/set mode */ getmode getmode; setmode setmode; /* input switch register + values for v4l inputs */ int inputreg; int inputmap[4]; int inputmute; int inputmask; }; /* current state of the chip */ struct CHIPSTATE { struct v4l2_subdev sd; /* chip-specific description - should point to an entry at CHIPDESC table */ struct CHIPDESC *desc; /* shadow register set */ audiocmd shadow; /* current settings */ __u16 left,right,treble,bass,muted,mode; int prevmode; int radio; int input; /* thread */ struct task_struct *thread; struct timer_list wt; int watch_stereo; int audmode; }; static inline struct CHIPSTATE *to_state(struct v4l2_subdev *sd) { return container_of(sd, struct CHIPSTATE, sd); } /* ---------------------------------------------------------------------- */ /* i2c I/O functions */ static int chip_write(struct CHIPSTATE *chip, int subaddr, int val) { struct v4l2_subdev *sd = &chip->sd; struct i2c_client *c = v4l2_get_subdevdata(sd); unsigned char buffer[2]; if (subaddr < 0) { v4l2_dbg(1, debug, sd, "chip_write: 0x%x\n", val); chip->shadow.bytes[1] = val; buffer[0] = val; if (1 != i2c_master_send(c, buffer, 1)) { v4l2_warn(sd, "I/O error (write 0x%x)\n", val); return -1; } } else { if (subaddr + 1 >= ARRAY_SIZE(chip->shadow.bytes)) { v4l2_info(sd, "Tried to access a non-existent register: %d\n", subaddr); return -EINVAL; } v4l2_dbg(1, debug, sd, "chip_write: reg%d=0x%x\n", subaddr, val); chip->shadow.bytes[subaddr+1] = val; buffer[0] = subaddr; buffer[1] = val; if (2 != i2c_master_send(c, buffer, 2)) { v4l2_warn(sd, "I/O error (write reg%d=0x%x)\n", subaddr, val); return -1; } } return 0; } static int chip_write_masked(struct CHIPSTATE *chip, int subaddr, int val, int mask) { struct v4l2_subdev *sd = &chip->sd; if (mask != 0) { if (subaddr < 0) { val = (chip->shadow.bytes[1] & ~mask) | (val & mask); } else { if (subaddr + 1 >= ARRAY_SIZE(chip->shadow.bytes)) { v4l2_info(sd, "Tried to access a non-existent register: %d\n", subaddr); return -EINVAL; } val = (chip->shadow.bytes[subaddr+1] & ~mask) | (val & mask); } } return chip_write(chip, subaddr, val); } static int chip_read(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; struct i2c_client *c = v4l2_get_subdevdata(sd); unsigned char buffer; if (1 != i2c_master_recv(c, &buffer, 1)) { v4l2_warn(sd, "I/O error (read)\n"); return -1; } v4l2_dbg(1, debug, sd, "chip_read: 0x%x\n", buffer); return buffer; } static int chip_read2(struct CHIPSTATE *chip, int subaddr) { struct v4l2_subdev *sd = &chip->sd; struct i2c_client *c = v4l2_get_subdevdata(sd); unsigned char write[1]; unsigned char read[1]; struct i2c_msg msgs[2] = { { c->addr, 0, 1, write }, { c->addr, I2C_M_RD, 1, read } }; write[0] = subaddr; if (2 != i2c_transfer(c->adapter, msgs, 2)) { v4l2_warn(sd, "I/O error (read2)\n"); return -1; } v4l2_dbg(1, debug, sd, "chip_read2: reg%d=0x%x\n", subaddr, read[0]); return read[0]; } static int chip_cmd(struct CHIPSTATE *chip, char *name, audiocmd *cmd) { struct v4l2_subdev *sd = &chip->sd; struct i2c_client *c = v4l2_get_subdevdata(sd); int i; if (0 == cmd->count) return 0; if (cmd->count + cmd->bytes[0] - 1 >= ARRAY_SIZE(chip->shadow.bytes)) { v4l2_info(sd, "Tried to access a non-existent register range: %d to %d\n", cmd->bytes[0] + 1, cmd->bytes[0] + cmd->count - 1); return -EINVAL; } /* FIXME: it seems that the shadow bytes are wrong bellow !*/ /* update our shadow register set; print bytes if (debug > 0) */ v4l2_dbg(1, debug, sd, "chip_cmd(%s): reg=%d, data:", name, cmd->bytes[0]); for (i = 1; i < cmd->count; i++) { if (debug) printk(KERN_CONT " 0x%x", cmd->bytes[i]); chip->shadow.bytes[i+cmd->bytes[0]] = cmd->bytes[i]; } if (debug) printk(KERN_CONT "\n"); /* send data to the chip */ if (cmd->count != i2c_master_send(c, cmd->bytes, cmd->count)) { v4l2_warn(sd, "I/O error (%s)\n", name); return -1; } return 0; } /* ---------------------------------------------------------------------- */ /* kernel thread for doing i2c stuff asyncronly * right now it is used only to check the audio mode (mono/stereo/whatever) * some time after switching to another TV channel, then turn on stereo * if available, ... */ static void chip_thread_wake(unsigned long data) { struct CHIPSTATE *chip = (struct CHIPSTATE*)data; wake_up_process(chip->thread); } static int chip_thread(void *data) { struct CHIPSTATE *chip = data; struct CHIPDESC *desc = chip->desc; struct v4l2_subdev *sd = &chip->sd; int mode; v4l2_dbg(1, debug, sd, "thread started\n"); set_freezable(); for (;;) { set_current_state(TASK_INTERRUPTIBLE); if (!kthread_should_stop()) schedule(); set_current_state(TASK_RUNNING); try_to_freeze(); if (kthread_should_stop()) break; v4l2_dbg(1, debug, sd, "thread wakeup\n"); /* don't do anything for radio or if mode != auto */ if (chip->radio || chip->mode != 0) continue; /* have a look what's going on */ mode = desc->getmode(chip); if (mode == chip->prevmode) continue; /* chip detected a new audio mode - set it */ v4l2_dbg(1, debug, sd, "thread checkmode\n"); chip->prevmode = mode; if (mode & V4L2_TUNER_MODE_STEREO) desc->setmode(chip, V4L2_TUNER_MODE_STEREO); if (mode & V4L2_TUNER_MODE_LANG1_LANG2) desc->setmode(chip, V4L2_TUNER_MODE_STEREO); else if (mode & V4L2_TUNER_MODE_LANG1) desc->setmode(chip, V4L2_TUNER_MODE_LANG1); else if (mode & V4L2_TUNER_MODE_LANG2) desc->setmode(chip, V4L2_TUNER_MODE_LANG2); else desc->setmode(chip, V4L2_TUNER_MODE_MONO); /* schedule next check */ mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000)); } v4l2_dbg(1, debug, sd, "thread exiting\n"); return 0; } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for tda9840 */ #define TDA9840_SW 0x00 #define TDA9840_LVADJ 0x02 #define TDA9840_STADJ 0x03 #define TDA9840_TEST 0x04 #define TDA9840_MONO 0x10 #define TDA9840_STEREO 0x2a #define TDA9840_DUALA 0x12 #define TDA9840_DUALB 0x1e #define TDA9840_DUALAB 0x1a #define TDA9840_DUALBA 0x16 #define TDA9840_EXTERNAL 0x7a #define TDA9840_DS_DUAL 0x20 /* Dual sound identified */ #define TDA9840_ST_STEREO 0x40 /* Stereo sound identified */ #define TDA9840_PONRES 0x80 /* Power-on reset detected if = 1 */ #define TDA9840_TEST_INT1SN 0x1 /* Integration time 0.5s when set */ #define TDA9840_TEST_INTFU 0x02 /* Disables integrator function */ static int tda9840_getmode(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; int val, mode; val = chip_read(chip); mode = V4L2_TUNER_MODE_MONO; if (val & TDA9840_DS_DUAL) mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2; if (val & TDA9840_ST_STEREO) mode |= V4L2_TUNER_MODE_STEREO; v4l2_dbg(1, debug, sd, "tda9840_getmode(): raw chip read: %d, return: %d\n", val, mode); return mode; } static void tda9840_setmode(struct CHIPSTATE *chip, int mode) { int update = 1; int t = chip->shadow.bytes[TDA9840_SW + 1] & ~0x7e; switch (mode) { case V4L2_TUNER_MODE_MONO: t |= TDA9840_MONO; break; case V4L2_TUNER_MODE_STEREO: t |= TDA9840_STEREO; break; case V4L2_TUNER_MODE_LANG1: t |= TDA9840_DUALA; break; case V4L2_TUNER_MODE_LANG2: t |= TDA9840_DUALB; break; default: update = 0; } if (update) chip_write(chip, TDA9840_SW, t); } static int tda9840_checkit(struct CHIPSTATE *chip) { int rc; rc = chip_read(chip); /* lower 5 bits should be 0 */ return ((rc & 0x1f) == 0) ? 1 : 0; } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for tda985x */ /* subaddresses for TDA9855 */ #define TDA9855_VR 0x00 /* Volume, right */ #define TDA9855_VL 0x01 /* Volume, left */ #define TDA9855_BA 0x02 /* Bass */ #define TDA9855_TR 0x03 /* Treble */ #define TDA9855_SW 0x04 /* Subwoofer - not connected on DTV2000 */ /* subaddresses for TDA9850 */ #define TDA9850_C4 0x04 /* Control 1 for TDA9850 */ /* subaddesses for both chips */ #define TDA985x_C5 0x05 /* Control 2 for TDA9850, Control 1 for TDA9855 */ #define TDA985x_C6 0x06 /* Control 3 for TDA9850, Control 2 for TDA9855 */ #define TDA985x_C7 0x07 /* Control 4 for TDA9850, Control 3 for TDA9855 */ #define TDA985x_A1 0x08 /* Alignment 1 for both chips */ #define TDA985x_A2 0x09 /* Alignment 2 for both chips */ #define TDA985x_A3 0x0a /* Alignment 3 for both chips */ /* Masks for bits in TDA9855 subaddresses */ /* 0x00 - VR in TDA9855 */ /* 0x01 - VL in TDA9855 */ /* lower 7 bits control gain from -71dB (0x28) to 16dB (0x7f) * in 1dB steps - mute is 0x27 */ /* 0x02 - BA in TDA9855 */ /* lower 5 bits control bass gain from -12dB (0x06) to 16.5dB (0x19) * in .5dB steps - 0 is 0x0E */ /* 0x03 - TR in TDA9855 */ /* 4 bits << 1 control treble gain from -12dB (0x3) to 12dB (0xb) * in 3dB steps - 0 is 0x7 */ /* Masks for bits in both chips' subaddresses */ /* 0x04 - SW in TDA9855, C4/Control 1 in TDA9850 */ /* Unique to TDA9855: */ /* 4 bits << 2 control subwoofer/surround gain from -14db (0x1) to 14db (0xf) * in 3dB steps - mute is 0x0 */ /* Unique to TDA9850: */ /* lower 4 bits control stereo noise threshold, over which stereo turns off * set to values of 0x00 through 0x0f for Ster1 through Ster16 */ /* 0x05 - C5 - Control 1 in TDA9855 , Control 2 in TDA9850*/ /* Unique to TDA9855: */ #define TDA9855_MUTE 1<<7 /* GMU, Mute at outputs */ #define TDA9855_AVL 1<<6 /* AVL, Automatic Volume Level */ #define TDA9855_LOUD 1<<5 /* Loudness, 1==off */ #define TDA9855_SUR 1<<3 /* Surround / Subwoofer 1==.5(L-R) 0==.5(L+R) */ /* Bits 0 to 3 select various combinations * of line in and line out, only the * interesting ones are defined */ #define TDA9855_EXT 1<<2 /* Selects inputs LIR and LIL. Pins 41 & 12 */ #define TDA9855_INT 0 /* Selects inputs LOR and LOL. (internal) */ /* Unique to TDA9850: */ /* lower 4 bits contol SAP noise threshold, over which SAP turns off * set to values of 0x00 through 0x0f for SAP1 through SAP16 */ /* 0x06 - C6 - Control 2 in TDA9855, Control 3 in TDA9850 */ /* Common to TDA9855 and TDA9850: */ #define TDA985x_SAP 3<<6 /* Selects SAP output, mute if not received */ #define TDA985x_STEREO 1<<6 /* Selects Stereo ouput, mono if not received */ #define TDA985x_MONO 0 /* Forces Mono output */ #define TDA985x_LMU 1<<3 /* Mute (LOR/LOL for 9855, OUTL/OUTR for 9850) */ /* Unique to TDA9855: */ #define TDA9855_TZCM 1<<5 /* If set, don't mute till zero crossing */ #define TDA9855_VZCM 1<<4 /* If set, don't change volume till zero crossing*/ #define TDA9855_LINEAR 0 /* Linear Stereo */ #define TDA9855_PSEUDO 1 /* Pseudo Stereo */ #define TDA9855_SPAT_30 2 /* Spatial Stereo, 30% anti-phase crosstalk */ #define TDA9855_SPAT_50 3 /* Spatial Stereo, 52% anti-phase crosstalk */ #define TDA9855_E_MONO 7 /* Forced mono - mono select elseware, so useless*/ /* 0x07 - C7 - Control 3 in TDA9855, Control 4 in TDA9850 */ /* Common to both TDA9855 and TDA9850: */ /* lower 4 bits control input gain from -3.5dB (0x0) to 4dB (0xF) * in .5dB steps - 0dB is 0x7 */ /* 0x08, 0x09 - A1 and A2 (read/write) */ /* Common to both TDA9855 and TDA9850: */ /* lower 5 bites are wideband and spectral expander alignment * from 0x00 to 0x1f - nominal at 0x0f and 0x10 (read/write) */ #define TDA985x_STP 1<<5 /* Stereo Pilot/detect (read-only) */ #define TDA985x_SAPP 1<<6 /* SAP Pilot/detect (read-only) */ #define TDA985x_STS 1<<7 /* Stereo trigger 1= <35mV 0= <30mV (write-only)*/ /* 0x0a - A3 */ /* Common to both TDA9855 and TDA9850: */ /* lower 3 bits control timing current for alignment: -30% (0x0), -20% (0x1), * -10% (0x2), nominal (0x3), +10% (0x6), +20% (0x5), +30% (0x4) */ #define TDA985x_ADJ 1<<7 /* Stereo adjust on/off (wideband and spectral */ static int tda9855_volume(int val) { return val/0x2e8+0x27; } static int tda9855_bass(int val) { return val/0xccc+0x06; } static int tda9855_treble(int val) { return (val/0x1c71+0x3)<<1; } static int tda985x_getmode(struct CHIPSTATE *chip) { int mode; mode = ((TDA985x_STP | TDA985x_SAPP) & chip_read(chip)) >> 4; /* Add mono mode regardless of SAP and stereo */ /* Allows forced mono */ return mode | V4L2_TUNER_MODE_MONO; } static void tda985x_setmode(struct CHIPSTATE *chip, int mode) { int update = 1; int c6 = chip->shadow.bytes[TDA985x_C6+1] & 0x3f; switch (mode) { case V4L2_TUNER_MODE_MONO: c6 |= TDA985x_MONO; break; case V4L2_TUNER_MODE_STEREO: c6 |= TDA985x_STEREO; break; case V4L2_TUNER_MODE_LANG1: c6 |= TDA985x_SAP; break; default: update = 0; } if (update) chip_write(chip,TDA985x_C6,c6); } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for tda9873h */ /* Subaddresses for TDA9873H */ #define TDA9873_SW 0x00 /* Switching */ #define TDA9873_AD 0x01 /* Adjust */ #define TDA9873_PT 0x02 /* Port */ /* Subaddress 0x00: Switching Data * B7..B0: * * B1, B0: Input source selection * 0, 0 internal * 1, 0 external stereo * 0, 1 external mono */ #define TDA9873_INP_MASK 3 #define TDA9873_INTERNAL 0 #define TDA9873_EXT_STEREO 2 #define TDA9873_EXT_MONO 1 /* B3, B2: output signal select * B4 : transmission mode * 0, 0, 1 Mono * 1, 0, 0 Stereo * 1, 1, 1 Stereo (reversed channel) * 0, 0, 0 Dual AB * 0, 0, 1 Dual AA * 0, 1, 0 Dual BB * 0, 1, 1 Dual BA */ #define TDA9873_TR_MASK (7 << 2) #define TDA9873_TR_MONO 4 #define TDA9873_TR_STEREO 1 << 4 #define TDA9873_TR_REVERSE (1 << 3) & (1 << 2) #define TDA9873_TR_DUALA 1 << 2 #define TDA9873_TR_DUALB 1 << 3 /* output level controls * B5: output level switch (0 = reduced gain, 1 = normal gain) * B6: mute (1 = muted) * B7: auto-mute (1 = auto-mute enabled) */ #define TDA9873_GAIN_NORMAL 1 << 5 #define TDA9873_MUTE 1 << 6 #define TDA9873_AUTOMUTE 1 << 7 /* Subaddress 0x01: Adjust/standard */ /* Lower 4 bits (C3..C0) control stereo adjustment on R channel (-0.6 - +0.7 dB) * Recommended value is +0 dB */ #define TDA9873_STEREO_ADJ 0x06 /* 0dB gain */ /* Bits C6..C4 control FM stantard * C6, C5, C4 * 0, 0, 0 B/G (PAL FM) * 0, 0, 1 M * 0, 1, 0 D/K(1) * 0, 1, 1 D/K(2) * 1, 0, 0 D/K(3) * 1, 0, 1 I */ #define TDA9873_BG 0 #define TDA9873_M 1 #define TDA9873_DK1 2 #define TDA9873_DK2 3 #define TDA9873_DK3 4 #define TDA9873_I 5 /* C7 controls identification response time (1=fast/0=normal) */ #define TDA9873_IDR_NORM 0 #define TDA9873_IDR_FAST 1 << 7 /* Subaddress 0x02: Port data */ /* E1, E0 free programmable ports P1/P2 0, 0 both ports low 0, 1 P1 high 1, 0 P2 high 1, 1 both ports high */ #define TDA9873_PORTS 3 /* E2: test port */ #define TDA9873_TST_PORT 1 << 2 /* E5..E3 control mono output channel (together with transmission mode bit B4) * * E5 E4 E3 B4 OUTM * 0 0 0 0 mono * 0 0 1 0 DUAL B * 0 1 0 1 mono (from stereo decoder) */ #define TDA9873_MOUT_MONO 0 #define TDA9873_MOUT_FMONO 0 #define TDA9873_MOUT_DUALA 0 #define TDA9873_MOUT_DUALB 1 << 3 #define TDA9873_MOUT_ST 1 << 4 #define TDA9873_MOUT_EXTM (1 << 4 ) & (1 << 3) #define TDA9873_MOUT_EXTL 1 << 5 #define TDA9873_MOUT_EXTR (1 << 5 ) & (1 << 3) #define TDA9873_MOUT_EXTLR (1 << 5 ) & (1 << 4) #define TDA9873_MOUT_MUTE (1 << 5 ) & (1 << 4) & (1 << 3) /* Status bits: (chip read) */ #define TDA9873_PONR 0 /* Power-on reset detected if = 1 */ #define TDA9873_STEREO 2 /* Stereo sound is identified */ #define TDA9873_DUAL 4 /* Dual sound is identified */ static int tda9873_getmode(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; int val,mode; val = chip_read(chip); mode = V4L2_TUNER_MODE_MONO; if (val & TDA9873_STEREO) mode |= V4L2_TUNER_MODE_STEREO; if (val & TDA9873_DUAL) mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2; v4l2_dbg(1, debug, sd, "tda9873_getmode(): raw chip read: %d, return: %d\n", val, mode); return mode; } static void tda9873_setmode(struct CHIPSTATE *chip, int mode) { struct v4l2_subdev *sd = &chip->sd; int sw_data = chip->shadow.bytes[TDA9873_SW+1] & ~ TDA9873_TR_MASK; /* int adj_data = chip->shadow.bytes[TDA9873_AD+1] ; */ if ((sw_data & TDA9873_INP_MASK) != TDA9873_INTERNAL) { v4l2_dbg(1, debug, sd, "tda9873_setmode(): external input\n"); return; } v4l2_dbg(1, debug, sd, "tda9873_setmode(): chip->shadow.bytes[%d] = %d\n", TDA9873_SW+1, chip->shadow.bytes[TDA9873_SW+1]); v4l2_dbg(1, debug, sd, "tda9873_setmode(): sw_data = %d\n", sw_data); switch (mode) { case V4L2_TUNER_MODE_MONO: sw_data |= TDA9873_TR_MONO; break; case V4L2_TUNER_MODE_STEREO: sw_data |= TDA9873_TR_STEREO; break; case V4L2_TUNER_MODE_LANG1: sw_data |= TDA9873_TR_DUALA; break; case V4L2_TUNER_MODE_LANG2: sw_data |= TDA9873_TR_DUALB; break; default: chip->mode = 0; return; } chip_write(chip, TDA9873_SW, sw_data); v4l2_dbg(1, debug, sd, "tda9873_setmode(): req. mode %d; chip_write: %d\n", mode, sw_data); } static int tda9873_checkit(struct CHIPSTATE *chip) { int rc; if (-1 == (rc = chip_read2(chip,254))) return 0; return (rc & ~0x1f) == 0x80; } /* ---------------------------------------------------------------------- */ /* audio chip description - defines+functions for tda9874h and tda9874a */ /* Dariusz Kowalewski <darekk@automex.pl> */ /* Subaddresses for TDA9874H and TDA9874A (slave rx) */ #define TDA9874A_AGCGR 0x00 /* AGC gain */ #define TDA9874A_GCONR 0x01 /* general config */ #define TDA9874A_MSR 0x02 /* monitor select */ #define TDA9874A_C1FRA 0x03 /* carrier 1 freq. */ #define TDA9874A_C1FRB 0x04 /* carrier 1 freq. */ #define TDA9874A_C1FRC 0x05 /* carrier 1 freq. */ #define TDA9874A_C2FRA 0x06 /* carrier 2 freq. */ #define TDA9874A_C2FRB 0x07 /* carrier 2 freq. */ #define TDA9874A_C2FRC 0x08 /* carrier 2 freq. */ #define TDA9874A_DCR 0x09 /* demodulator config */ #define TDA9874A_FMER 0x0a /* FM de-emphasis */ #define TDA9874A_FMMR 0x0b /* FM dematrix */ #define TDA9874A_C1OLAR 0x0c /* ch.1 output level adj. */ #define TDA9874A_C2OLAR 0x0d /* ch.2 output level adj. */ #define TDA9874A_NCONR 0x0e /* NICAM config */ #define TDA9874A_NOLAR 0x0f /* NICAM output level adj. */ #define TDA9874A_NLELR 0x10 /* NICAM lower error limit */ #define TDA9874A_NUELR 0x11 /* NICAM upper error limit */ #define TDA9874A_AMCONR 0x12 /* audio mute control */ #define TDA9874A_SDACOSR 0x13 /* stereo DAC output select */ #define TDA9874A_AOSR 0x14 /* analog output select */ #define TDA9874A_DAICONR 0x15 /* digital audio interface config */ #define TDA9874A_I2SOSR 0x16 /* I2S-bus output select */ #define TDA9874A_I2SOLAR 0x17 /* I2S-bus output level adj. */ #define TDA9874A_MDACOSR 0x18 /* mono DAC output select (tda9874a) */ #define TDA9874A_ESP 0xFF /* easy standard progr. (tda9874a) */ /* Subaddresses for TDA9874H and TDA9874A (slave tx) */ #define TDA9874A_DSR 0x00 /* device status */ #define TDA9874A_NSR 0x01 /* NICAM status */ #define TDA9874A_NECR 0x02 /* NICAM error count */ #define TDA9874A_DR1 0x03 /* add. data LSB */ #define TDA9874A_DR2 0x04 /* add. data MSB */ #define TDA9874A_LLRA 0x05 /* monitor level read-out LSB */ #define TDA9874A_LLRB 0x06 /* monitor level read-out MSB */ #define TDA9874A_SIFLR 0x07 /* SIF level */ #define TDA9874A_TR2 252 /* test reg. 2 */ #define TDA9874A_TR1 253 /* test reg. 1 */ #define TDA9874A_DIC 254 /* device id. code */ #define TDA9874A_SIC 255 /* software id. code */ static int tda9874a_mode = 1; /* 0: A2, 1: NICAM */ static int tda9874a_GCONR = 0xc0; /* default config. input pin: SIFSEL=0 */ static int tda9874a_NCONR = 0x01; /* default NICAM config.: AMSEL=0,AMUTE=1 */ static int tda9874a_ESP = 0x07; /* default standard: NICAM D/K */ static int tda9874a_dic = -1; /* device id. code */ /* insmod options for tda9874a */ static unsigned int tda9874a_SIF = UNSET; static unsigned int tda9874a_AMSEL = UNSET; static unsigned int tda9874a_STD = UNSET; module_param(tda9874a_SIF, int, 0444); module_param(tda9874a_AMSEL, int, 0444); module_param(tda9874a_STD, int, 0444); /* * initialization table for tda9874 decoder: * - carrier 1 freq. registers (3 bytes) * - carrier 2 freq. registers (3 bytes) * - demudulator config register * - FM de-emphasis register (slow identification mode) * Note: frequency registers must be written in single i2c transfer. */ static struct tda9874a_MODES { char *name; audiocmd cmd; } tda9874a_modelist[9] = { { "A2, B/G", /* default */ { 9, { TDA9874A_C1FRA, 0x72,0x95,0x55, 0x77,0xA0,0x00, 0x00,0x00 }} }, { "A2, M (Korea)", { 9, { TDA9874A_C1FRA, 0x5D,0xC0,0x00, 0x62,0x6A,0xAA, 0x20,0x22 }} }, { "A2, D/K (1)", { 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x82,0x60,0x00, 0x00,0x00 }} }, { "A2, D/K (2)", { 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x8C,0x75,0x55, 0x00,0x00 }} }, { "A2, D/K (3)", { 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x77,0xA0,0x00, 0x00,0x00 }} }, { "NICAM, I", { 9, { TDA9874A_C1FRA, 0x7D,0x00,0x00, 0x88,0x8A,0xAA, 0x08,0x33 }} }, { "NICAM, B/G", { 9, { TDA9874A_C1FRA, 0x72,0x95,0x55, 0x79,0xEA,0xAA, 0x08,0x33 }} }, { "NICAM, D/K", { 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x79,0xEA,0xAA, 0x08,0x33 }} }, { "NICAM, L", { 9, { TDA9874A_C1FRA, 0x87,0x6A,0xAA, 0x79,0xEA,0xAA, 0x09,0x33 }} } }; static int tda9874a_setup(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; chip_write(chip, TDA9874A_AGCGR, 0x00); /* 0 dB */ chip_write(chip, TDA9874A_GCONR, tda9874a_GCONR); chip_write(chip, TDA9874A_MSR, (tda9874a_mode) ? 0x03:0x02); if(tda9874a_dic == 0x11) { chip_write(chip, TDA9874A_FMMR, 0x80); } else { /* dic == 0x07 */ chip_cmd(chip,"tda9874_modelist",&tda9874a_modelist[tda9874a_STD].cmd); chip_write(chip, TDA9874A_FMMR, 0x00); } chip_write(chip, TDA9874A_C1OLAR, 0x00); /* 0 dB */ chip_write(chip, TDA9874A_C2OLAR, 0x00); /* 0 dB */ chip_write(chip, TDA9874A_NCONR, tda9874a_NCONR); chip_write(chip, TDA9874A_NOLAR, 0x00); /* 0 dB */ /* Note: If signal quality is poor you may want to change NICAM */ /* error limit registers (NLELR and NUELR) to some greater values. */ /* Then the sound would remain stereo, but won't be so clear. */ chip_write(chip, TDA9874A_NLELR, 0x14); /* default */ chip_write(chip, TDA9874A_NUELR, 0x50); /* default */ if(tda9874a_dic == 0x11) { chip_write(chip, TDA9874A_AMCONR, 0xf9); chip_write(chip, TDA9874A_SDACOSR, (tda9874a_mode) ? 0x81:0x80); chip_write(chip, TDA9874A_AOSR, 0x80); chip_write(chip, TDA9874A_MDACOSR, (tda9874a_mode) ? 0x82:0x80); chip_write(chip, TDA9874A_ESP, tda9874a_ESP); } else { /* dic == 0x07 */ chip_write(chip, TDA9874A_AMCONR, 0xfb); chip_write(chip, TDA9874A_SDACOSR, (tda9874a_mode) ? 0x81:0x80); chip_write(chip, TDA9874A_AOSR, 0x00); /* or 0x10 */ } v4l2_dbg(1, debug, sd, "tda9874a_setup(): %s [0x%02X].\n", tda9874a_modelist[tda9874a_STD].name,tda9874a_STD); return 1; } static int tda9874a_getmode(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; int dsr,nsr,mode; int necr; /* just for debugging */ mode = V4L2_TUNER_MODE_MONO; if(-1 == (dsr = chip_read2(chip,TDA9874A_DSR))) return mode; if(-1 == (nsr = chip_read2(chip,TDA9874A_NSR))) return mode; if(-1 == (necr = chip_read2(chip,TDA9874A_NECR))) return mode; /* need to store dsr/nsr somewhere */ chip->shadow.bytes[MAXREGS-2] = dsr; chip->shadow.bytes[MAXREGS-1] = nsr; if(tda9874a_mode) { /* Note: DSR.RSSF and DSR.AMSTAT bits are also checked. * If NICAM auto-muting is enabled, DSR.AMSTAT=1 indicates * that sound has (temporarily) switched from NICAM to * mono FM (or AM) on 1st sound carrier due to high NICAM bit * error count. So in fact there is no stereo in this case :-( * But changing the mode to V4L2_TUNER_MODE_MONO would switch * external 4052 multiplexer in audio_hook(). */ if(nsr & 0x02) /* NSR.S/MB=1 */ mode |= V4L2_TUNER_MODE_STEREO; if(nsr & 0x01) /* NSR.D/SB=1 */ mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2; } else { if(dsr & 0x02) /* DSR.IDSTE=1 */ mode |= V4L2_TUNER_MODE_STEREO; if(dsr & 0x04) /* DSR.IDDUA=1 */ mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2; } v4l2_dbg(1, debug, sd, "tda9874a_getmode(): DSR=0x%X, NSR=0x%X, NECR=0x%X, return: %d.\n", dsr, nsr, necr, mode); return mode; } static void tda9874a_setmode(struct CHIPSTATE *chip, int mode) { struct v4l2_subdev *sd = &chip->sd; /* Disable/enable NICAM auto-muting (based on DSR.RSSF status bit). */ /* If auto-muting is disabled, we can hear a signal of degrading quality. */ if (tda9874a_mode) { if(chip->shadow.bytes[MAXREGS-2] & 0x20) /* DSR.RSSF=1 */ tda9874a_NCONR &= 0xfe; /* enable */ else tda9874a_NCONR |= 0x01; /* disable */ chip_write(chip, TDA9874A_NCONR, tda9874a_NCONR); } /* Note: TDA9874A supports automatic FM dematrixing (FMMR register) * and has auto-select function for audio output (AOSR register). * Old TDA9874H doesn't support these features. * TDA9874A also has additional mono output pin (OUTM), which * on same (all?) tv-cards is not used, anyway (as well as MONOIN). */ if(tda9874a_dic == 0x11) { int aosr = 0x80; int mdacosr = (tda9874a_mode) ? 0x82:0x80; switch(mode) { case V4L2_TUNER_MODE_MONO: case V4L2_TUNER_MODE_STEREO: break; case V4L2_TUNER_MODE_LANG1: aosr = 0x80; /* auto-select, dual A/A */ mdacosr = (tda9874a_mode) ? 0x82:0x80; break; case V4L2_TUNER_MODE_LANG2: aosr = 0xa0; /* auto-select, dual B/B */ mdacosr = (tda9874a_mode) ? 0x83:0x81; break; default: chip->mode = 0; return; } chip_write(chip, TDA9874A_AOSR, aosr); chip_write(chip, TDA9874A_MDACOSR, mdacosr); v4l2_dbg(1, debug, sd, "tda9874a_setmode(): req. mode %d; AOSR=0x%X, MDACOSR=0x%X.\n", mode, aosr, mdacosr); } else { /* dic == 0x07 */ int fmmr,aosr; switch(mode) { case V4L2_TUNER_MODE_MONO: fmmr = 0x00; /* mono */ aosr = 0x10; /* A/A */ break; case V4L2_TUNER_MODE_STEREO: if(tda9874a_mode) { fmmr = 0x00; aosr = 0x00; /* handled by NICAM auto-mute */ } else { fmmr = (tda9874a_ESP == 1) ? 0x05 : 0x04; /* stereo */ aosr = 0x00; } break; case V4L2_TUNER_MODE_LANG1: fmmr = 0x02; /* dual */ aosr = 0x10; /* dual A/A */ break; case V4L2_TUNER_MODE_LANG2: fmmr = 0x02; /* dual */ aosr = 0x20; /* dual B/B */ break; default: chip->mode = 0; return; } chip_write(chip, TDA9874A_FMMR, fmmr); chip_write(chip, TDA9874A_AOSR, aosr); v4l2_dbg(1, debug, sd, "tda9874a_setmode(): req. mode %d; FMMR=0x%X, AOSR=0x%X.\n", mode, fmmr, aosr); } } static int tda9874a_checkit(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; int dic,sic; /* device id. and software id. codes */ if(-1 == (dic = chip_read2(chip,TDA9874A_DIC))) return 0; if(-1 == (sic = chip_read2(chip,TDA9874A_SIC))) return 0; v4l2_dbg(1, debug, sd, "tda9874a_checkit(): DIC=0x%X, SIC=0x%X.\n", dic, sic); if((dic == 0x11)||(dic == 0x07)) { v4l2_info(sd, "found tda9874%s.\n", (dic == 0x11) ? "a" : "h"); tda9874a_dic = dic; /* remember device id. */ return 1; } return 0; /* not found */ } static int tda9874a_initialize(struct CHIPSTATE *chip) { if (tda9874a_SIF > 2) tda9874a_SIF = 1; if (tda9874a_STD >= ARRAY_SIZE(tda9874a_modelist)) tda9874a_STD = 0; if(tda9874a_AMSEL > 1) tda9874a_AMSEL = 0; if(tda9874a_SIF == 1) tda9874a_GCONR = 0xc0; /* sound IF input 1 */ else tda9874a_GCONR = 0xc1; /* sound IF input 2 */ tda9874a_ESP = tda9874a_STD; tda9874a_mode = (tda9874a_STD < 5) ? 0 : 1; if(tda9874a_AMSEL == 0) tda9874a_NCONR = 0x01; /* auto-mute: analog mono input */ else tda9874a_NCONR = 0x05; /* auto-mute: 1st carrier FM or AM */ tda9874a_setup(chip); return 0; } /* ---------------------------------------------------------------------- */ /* audio chip description - defines+functions for tda9875 */ /* The TDA9875 is made by Philips Semiconductor * http://www.semiconductors.philips.com * TDA9875: I2C-bus controlled DSP audio processor, FM demodulator * */ /* subaddresses for TDA9875 */ #define TDA9875_MUT 0x12 /*General mute (value --> 0b11001100*/ #define TDA9875_CFG 0x01 /* Config register (value --> 0b00000000 */ #define TDA9875_DACOS 0x13 /*DAC i/o select (ADC) 0b0000100*/ #define TDA9875_LOSR 0x16 /*Line output select regirter 0b0100 0001*/ #define TDA9875_CH1V 0x0c /*Channel 1 volume (mute)*/ #define TDA9875_CH2V 0x0d /*Channel 2 volume (mute)*/ #define TDA9875_SC1 0x14 /*SCART 1 in (mono)*/ #define TDA9875_SC2 0x15 /*SCART 2 in (mono)*/ #define TDA9875_ADCIS 0x17 /*ADC input select (mono) 0b0110 000*/ #define TDA9875_AER 0x19 /*Audio effect (AVL+Pseudo) 0b0000 0110*/ #define TDA9875_MCS 0x18 /*Main channel select (DAC) 0b0000100*/ #define TDA9875_MVL 0x1a /* Main volume gauche */ #define TDA9875_MVR 0x1b /* Main volume droite */ #define TDA9875_MBA 0x1d /* Main Basse */ #define TDA9875_MTR 0x1e /* Main treble */ #define TDA9875_ACS 0x1f /* Auxiliary channel select (FM) 0b0000000*/ #define TDA9875_AVL 0x20 /* Auxiliary volume gauche */ #define TDA9875_AVR 0x21 /* Auxiliary volume droite */ #define TDA9875_ABA 0x22 /* Auxiliary Basse */ #define TDA9875_ATR 0x23 /* Auxiliary treble */ #define TDA9875_MSR 0x02 /* Monitor select register */ #define TDA9875_C1MSB 0x03 /* Carrier 1 (FM) frequency register MSB */ #define TDA9875_C1MIB 0x04 /* Carrier 1 (FM) frequency register (16-8]b */ #define TDA9875_C1LSB 0x05 /* Carrier 1 (FM) frequency register LSB */ #define TDA9875_C2MSB 0x06 /* Carrier 2 (nicam) frequency register MSB */ #define TDA9875_C2MIB 0x07 /* Carrier 2 (nicam) frequency register (16-8]b */ #define TDA9875_C2LSB 0x08 /* Carrier 2 (nicam) frequency register LSB */ #define TDA9875_DCR 0x09 /* Demodulateur configuration regirter*/ #define TDA9875_DEEM 0x0a /* FM de-emphasis regirter*/ #define TDA9875_FMAT 0x0b /* FM Matrix regirter*/ /* values */ #define TDA9875_MUTE_ON 0xff /* general mute */ #define TDA9875_MUTE_OFF 0xcc /* general no mute */ static int tda9875_initialize(struct CHIPSTATE *chip) { chip_write(chip, TDA9875_CFG, 0xd0); /*reg de config 0 (reset)*/ chip_write(chip, TDA9875_MSR, 0x03); /* Monitor 0b00000XXX*/ chip_write(chip, TDA9875_C1MSB, 0x00); /*Car1(FM) MSB XMHz*/ chip_write(chip, TDA9875_C1MIB, 0x00); /*Car1(FM) MIB XMHz*/ chip_write(chip, TDA9875_C1LSB, 0x00); /*Car1(FM) LSB XMHz*/ chip_write(chip, TDA9875_C2MSB, 0x00); /*Car2(NICAM) MSB XMHz*/ chip_write(chip, TDA9875_C2MIB, 0x00); /*Car2(NICAM) MIB XMHz*/ chip_write(chip, TDA9875_C2LSB, 0x00); /*Car2(NICAM) LSB XMHz*/ chip_write(chip, TDA9875_DCR, 0x00); /*Demod config 0x00*/ chip_write(chip, TDA9875_DEEM, 0x44); /*DE-Emph 0b0100 0100*/ chip_write(chip, TDA9875_FMAT, 0x00); /*FM Matrix reg 0x00*/ chip_write(chip, TDA9875_SC1, 0x00); /* SCART 1 (SC1)*/ chip_write(chip, TDA9875_SC2, 0x01); /* SCART 2 (sc2)*/ chip_write(chip, TDA9875_CH1V, 0x10); /* Channel volume 1 mute*/ chip_write(chip, TDA9875_CH2V, 0x10); /* Channel volume 2 mute */ chip_write(chip, TDA9875_DACOS, 0x02); /* sig DAC i/o(in:nicam)*/ chip_write(chip, TDA9875_ADCIS, 0x6f); /* sig ADC input(in:mono)*/ chip_write(chip, TDA9875_LOSR, 0x00); /* line out (in:mono)*/ chip_write(chip, TDA9875_AER, 0x00); /*06 Effect (AVL+PSEUDO) */ chip_write(chip, TDA9875_MCS, 0x44); /* Main ch select (DAC) */ chip_write(chip, TDA9875_MVL, 0x03); /* Vol Main left 10dB */ chip_write(chip, TDA9875_MVR, 0x03); /* Vol Main right 10dB*/ chip_write(chip, TDA9875_MBA, 0x00); /* Main Bass Main 0dB*/ chip_write(chip, TDA9875_MTR, 0x00); /* Main Treble Main 0dB*/ chip_write(chip, TDA9875_ACS, 0x44); /* Aux chan select (dac)*/ chip_write(chip, TDA9875_AVL, 0x00); /* Vol Aux left 0dB*/ chip_write(chip, TDA9875_AVR, 0x00); /* Vol Aux right 0dB*/ chip_write(chip, TDA9875_ABA, 0x00); /* Aux Bass Main 0dB*/ chip_write(chip, TDA9875_ATR, 0x00); /* Aux Aigus Main 0dB*/ chip_write(chip, TDA9875_MUT, 0xcc); /* General mute */ return 0; } static int tda9875_volume(int val) { return (unsigned char)(val / 602 - 84); } static int tda9875_bass(int val) { return (unsigned char)(max(-12, val / 2115 - 15)); } static int tda9875_treble(int val) { return (unsigned char)(val / 2622 - 12); } /* ----------------------------------------------------------------------- */ /* *********************** * * i2c interface functions * * *********************** */ static int tda9875_checkit(struct CHIPSTATE *chip) { struct v4l2_subdev *sd = &chip->sd; int dic, rev; dic = chip_read2(chip, 254); rev = chip_read2(chip, 255); if (dic == 0 || dic == 2) { /* tda9875 and tda9875A */ v4l2_info(sd, "found tda9875%s rev. %d.\n", dic == 0 ? "" : "A", rev); return 1; } return 0; } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for tea6420 */ #define TEA6300_VL 0x00 /* volume left */ #define TEA6300_VR 0x01 /* volume right */ #define TEA6300_BA 0x02 /* bass */ #define TEA6300_TR 0x03 /* treble */ #define TEA6300_FA 0x04 /* fader control */ #define TEA6300_S 0x05 /* switch register */ /* values for those registers: */ #define TEA6300_S_SA 0x01 /* stereo A input */ #define TEA6300_S_SB 0x02 /* stereo B */ #define TEA6300_S_SC 0x04 /* stereo C */ #define TEA6300_S_GMU 0x80 /* general mute */ #define TEA6320_V 0x00 /* volume (0-5)/loudness off (6)/zero crossing mute(7) */ #define TEA6320_FFR 0x01 /* fader front right (0-5) */ #define TEA6320_FFL 0x02 /* fader front left (0-5) */ #define TEA6320_FRR 0x03 /* fader rear right (0-5) */ #define TEA6320_FRL 0x04 /* fader rear left (0-5) */ #define TEA6320_BA 0x05 /* bass (0-4) */ #define TEA6320_TR 0x06 /* treble (0-4) */ #define TEA6320_S 0x07 /* switch register */ /* values for those registers: */ #define TEA6320_S_SA 0x07 /* stereo A input */ #define TEA6320_S_SB 0x06 /* stereo B */ #define TEA6320_S_SC 0x05 /* stereo C */ #define TEA6320_S_SD 0x04 /* stereo D */ #define TEA6320_S_GMU 0x80 /* general mute */ #define TEA6420_S_SA 0x00 /* stereo A input */ #define TEA6420_S_SB 0x01 /* stereo B */ #define TEA6420_S_SC 0x02 /* stereo C */ #define TEA6420_S_SD 0x03 /* stereo D */ #define TEA6420_S_SE 0x04 /* stereo E */ #define TEA6420_S_GMU 0x05 /* general mute */ static int tea6300_shift10(int val) { return val >> 10; } static int tea6300_shift12(int val) { return val >> 12; } /* Assumes 16bit input (values 0x3f to 0x0c are unique, values less than */ /* 0x0c mirror those immediately higher) */ static int tea6320_volume(int val) { return (val / (65535/(63-12)) + 12) & 0x3f; } static int tea6320_shift11(int val) { return val >> 11; } static int tea6320_initialize(struct CHIPSTATE * chip) { chip_write(chip, TEA6320_FFR, 0x3f); chip_write(chip, TEA6320_FFL, 0x3f); chip_write(chip, TEA6320_FRR, 0x3f); chip_write(chip, TEA6320_FRL, 0x3f); return 0; } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for tda8425 */ #define TDA8425_VL 0x00 /* volume left */ #define TDA8425_VR 0x01 /* volume right */ #define TDA8425_BA 0x02 /* bass */ #define TDA8425_TR 0x03 /* treble */ #define TDA8425_S1 0x08 /* switch functions */ /* values for those registers: */ #define TDA8425_S1_OFF 0xEE /* audio off (mute on) */ #define TDA8425_S1_CH1 0xCE /* audio channel 1 (mute off) - "linear stereo" mode */ #define TDA8425_S1_CH2 0xCF /* audio channel 2 (mute off) - "linear stereo" mode */ #define TDA8425_S1_MU 0x20 /* mute bit */ #define TDA8425_S1_STEREO 0x18 /* stereo bits */ #define TDA8425_S1_STEREO_SPATIAL 0x18 /* spatial stereo */ #define TDA8425_S1_STEREO_LINEAR 0x08 /* linear stereo */ #define TDA8425_S1_STEREO_PSEUDO 0x10 /* pseudo stereo */ #define TDA8425_S1_STEREO_MONO 0x00 /* forced mono */ #define TDA8425_S1_ML 0x06 /* language selector */ #define TDA8425_S1_ML_SOUND_A 0x02 /* sound a */ #define TDA8425_S1_ML_SOUND_B 0x04 /* sound b */ #define TDA8425_S1_ML_STEREO 0x06 /* stereo */ #define TDA8425_S1_IS 0x01 /* channel selector */ static int tda8425_shift10(int val) { return (val >> 10) | 0xc0; } static int tda8425_shift12(int val) { return (val >> 12) | 0xf0; } static void tda8425_setmode(struct CHIPSTATE *chip, int mode) { int s1 = chip->shadow.bytes[TDA8425_S1+1] & 0xe1; if (mode & V4L2_TUNER_MODE_LANG1) { s1 |= TDA8425_S1_ML_SOUND_A; s1 |= TDA8425_S1_STEREO_PSEUDO; } else if (mode & V4L2_TUNER_MODE_LANG2) { s1 |= TDA8425_S1_ML_SOUND_B; s1 |= TDA8425_S1_STEREO_PSEUDO; } else { s1 |= TDA8425_S1_ML_STEREO; if (mode & V4L2_TUNER_MODE_MONO) s1 |= TDA8425_S1_STEREO_MONO; if (mode & V4L2_TUNER_MODE_STEREO) s1 |= TDA8425_S1_STEREO_SPATIAL; } chip_write(chip,TDA8425_S1,s1); } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for pic16c54 (PV951) */ /* the registers of 16C54, I2C sub address. */ #define PIC16C54_REG_KEY_CODE 0x01 /* Not use. */ #define PIC16C54_REG_MISC 0x02 /* bit definition of the RESET register, I2C data. */ #define PIC16C54_MISC_RESET_REMOTE_CTL 0x01 /* bit 0, Reset to receive the key */ /* code of remote controller */ #define PIC16C54_MISC_MTS_MAIN 0x02 /* bit 1 */ #define PIC16C54_MISC_MTS_SAP 0x04 /* bit 2 */ #define PIC16C54_MISC_MTS_BOTH 0x08 /* bit 3 */ #define PIC16C54_MISC_SND_MUTE 0x10 /* bit 4, Mute Audio(Line-in and Tuner) */ #define PIC16C54_MISC_SND_NOTMUTE 0x20 /* bit 5 */ #define PIC16C54_MISC_SWITCH_TUNER 0x40 /* bit 6 , Switch to Line-in */ #define PIC16C54_MISC_SWITCH_LINE 0x80 /* bit 7 , Switch to Tuner */ /* ---------------------------------------------------------------------- */ /* audio chip descriptions - defines+functions for TA8874Z */ /* write 1st byte */ #define TA8874Z_LED_STE 0x80 #define TA8874Z_LED_BIL 0x40 #define TA8874Z_LED_EXT 0x20 #define TA8874Z_MONO_SET 0x10 #define TA8874Z_MUTE 0x08 #define TA8874Z_F_MONO 0x04 #define TA8874Z_MODE_SUB 0x02 #define TA8874Z_MODE_MAIN 0x01 /* write 2nd byte */ /*#define TA8874Z_TI 0x80 */ /* test mode */ #define TA8874Z_SEPARATION 0x3f #define TA8874Z_SEPARATION_DEFAULT 0x10 /* read */ #define TA8874Z_B1 0x80 #define TA8874Z_B0 0x40 #define TA8874Z_CHAG_FLAG 0x20 /* * B1 B0 * mono L H * stereo L L * BIL H L */ static int ta8874z_getmode(struct CHIPSTATE *chip) { int val, mode; val = chip_read(chip); mode = V4L2_TUNER_MODE_MONO; if (val & TA8874Z_B1){ mode |= V4L2_TUNER_MODE_LANG1 | V4L2_TUNER_MODE_LANG2; }else if (!(val & TA8874Z_B0)){ mode |= V4L2_TUNER_MODE_STEREO; } /* v4l_dbg(1, debug, chip->c, "ta8874z_getmode(): raw chip read: 0x%02x, return: 0x%02x\n", val, mode); */ return mode; } static audiocmd ta8874z_stereo = { 2, {0, TA8874Z_SEPARATION_DEFAULT}}; static audiocmd ta8874z_mono = {2, { TA8874Z_MONO_SET, TA8874Z_SEPARATION_DEFAULT}}; static audiocmd ta8874z_main = {2, { 0, TA8874Z_SEPARATION_DEFAULT}}; static audiocmd ta8874z_sub = {2, { TA8874Z_MODE_SUB, TA8874Z_SEPARATION_DEFAULT}}; static void ta8874z_setmode(struct CHIPSTATE *chip, int mode) { struct v4l2_subdev *sd = &chip->sd; int update = 1; audiocmd *t = NULL; v4l2_dbg(1, debug, sd, "ta8874z_setmode(): mode: 0x%02x\n", mode); switch(mode){ case V4L2_TUNER_MODE_MONO: t = &ta8874z_mono; break; case V4L2_TUNER_MODE_STEREO: t = &ta8874z_stereo; break; case V4L2_TUNER_MODE_LANG1: t = &ta8874z_main; break; case V4L2_TUNER_MODE_LANG2: t = &ta8874z_sub; break; default: update = 0; } if(update) chip_cmd(chip, "TA8874Z", t); } static int ta8874z_checkit(struct CHIPSTATE *chip) { int rc; rc = chip_read(chip); return ((rc & 0x1f) == 0x1f) ? 1 : 0; } /* ---------------------------------------------------------------------- */ /* audio chip descriptions - struct CHIPDESC */ /* insmod options to enable/disable individual audio chips */ static int tda8425 = 1; static int tda9840 = 1; static int tda9850 = 1; static int tda9855 = 1; static int tda9873 = 1; static int tda9874a = 1; static int tda9875 = 1; static int tea6300; /* default 0 - address clash with msp34xx */ static int tea6320; /* default 0 - address clash with msp34xx */ static int tea6420 = 1; static int pic16c54 = 1; static int ta8874z; /* default 0 - address clash with tda9840 */ module_param(tda8425, int, 0444); module_param(tda9840, int, 0444); module_param(tda9850, int, 0444); module_param(tda9855, int, 0444); module_param(tda9873, int, 0444); module_param(tda9874a, int, 0444); module_param(tda9875, int, 0444); module_param(tea6300, int, 0444); module_param(tea6320, int, 0444); module_param(tea6420, int, 0444); module_param(pic16c54, int, 0444); module_param(ta8874z, int, 0444); static struct CHIPDESC chiplist[] = { { .name = "tda9840", .insmodopt = &tda9840, .addr_lo = I2C_ADDR_TDA9840 >> 1, .addr_hi = I2C_ADDR_TDA9840 >> 1, .registers = 5, .flags = CHIP_NEED_CHECKMODE, /* callbacks */ .checkit = tda9840_checkit, .getmode = tda9840_getmode, .setmode = tda9840_setmode, .init = { 2, { TDA9840_TEST, TDA9840_TEST_INT1SN /* ,TDA9840_SW, TDA9840_MONO */} } }, { .name = "tda9873h", .insmodopt = &tda9873, .addr_lo = I2C_ADDR_TDA985x_L >> 1, .addr_hi = I2C_ADDR_TDA985x_H >> 1, .registers = 3, .flags = CHIP_HAS_INPUTSEL | CHIP_NEED_CHECKMODE, /* callbacks */ .checkit = tda9873_checkit, .getmode = tda9873_getmode, .setmode = tda9873_setmode, .init = { 4, { TDA9873_SW, 0xa4, 0x06, 0x03 } }, .inputreg = TDA9873_SW, .inputmute = TDA9873_MUTE | TDA9873_AUTOMUTE, .inputmap = {0xa0, 0xa2, 0xa0, 0xa0}, .inputmask = TDA9873_INP_MASK|TDA9873_MUTE|TDA9873_AUTOMUTE, }, { .name = "tda9874h/a", .insmodopt = &tda9874a, .addr_lo = I2C_ADDR_TDA9874 >> 1, .addr_hi = I2C_ADDR_TDA9874 >> 1, .flags = CHIP_NEED_CHECKMODE, /* callbacks */ .initialize = tda9874a_initialize, .checkit = tda9874a_checkit, .getmode = tda9874a_getmode, .setmode = tda9874a_setmode, }, { .name = "tda9875", .insmodopt = &tda9875, .addr_lo = I2C_ADDR_TDA9875 >> 1, .addr_hi = I2C_ADDR_TDA9875 >> 1, .flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE, /* callbacks */ .initialize = tda9875_initialize, .checkit = tda9875_checkit, .volfunc = tda9875_volume, .bassfunc = tda9875_bass, .treblefunc = tda9875_treble, .leftreg = TDA9875_MVL, .rightreg = TDA9875_MVR, .bassreg = TDA9875_MBA, .treblereg = TDA9875_MTR, .leftinit = 58880, .rightinit = 58880, }, { .name = "tda9850", .insmodopt = &tda9850, .addr_lo = I2C_ADDR_TDA985x_L >> 1, .addr_hi = I2C_ADDR_TDA985x_H >> 1, .registers = 11, .getmode = tda985x_getmode, .setmode = tda985x_setmode, .init = { 8, { TDA9850_C4, 0x08, 0x08, TDA985x_STEREO, 0x07, 0x10, 0x10, 0x03 } } }, { .name = "tda9855", .insmodopt = &tda9855, .addr_lo = I2C_ADDR_TDA985x_L >> 1, .addr_hi = I2C_ADDR_TDA985x_H >> 1, .registers = 11, .flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE, .leftreg = TDA9855_VL, .rightreg = TDA9855_VR, .bassreg = TDA9855_BA, .treblereg = TDA9855_TR, /* callbacks */ .volfunc = tda9855_volume, .bassfunc = tda9855_bass, .treblefunc = tda9855_treble, .getmode = tda985x_getmode, .setmode = tda985x_setmode, .init = { 12, { 0, 0x6f, 0x6f, 0x0e, 0x07<<1, 0x8<<2, TDA9855_MUTE | TDA9855_AVL | TDA9855_LOUD | TDA9855_INT, TDA985x_STEREO | TDA9855_LINEAR | TDA9855_TZCM | TDA9855_VZCM, 0x07, 0x10, 0x10, 0x03 }} }, { .name = "tea6300", .insmodopt = &tea6300, .addr_lo = I2C_ADDR_TEA6300 >> 1, .addr_hi = I2C_ADDR_TEA6300 >> 1, .registers = 6, .flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL, .leftreg = TEA6300_VR, .rightreg = TEA6300_VL, .bassreg = TEA6300_BA, .treblereg = TEA6300_TR, /* callbacks */ .volfunc = tea6300_shift10, .bassfunc = tea6300_shift12, .treblefunc = tea6300_shift12, .inputreg = TEA6300_S, .inputmap = { TEA6300_S_SA, TEA6300_S_SB, TEA6300_S_SC }, .inputmute = TEA6300_S_GMU, }, { .name = "tea6320", .insmodopt = &tea6320, .addr_lo = I2C_ADDR_TEA6300 >> 1, .addr_hi = I2C_ADDR_TEA6300 >> 1, .registers = 8, .flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL, .leftreg = TEA6320_V, .rightreg = TEA6320_V, .bassreg = TEA6320_BA, .treblereg = TEA6320_TR, /* callbacks */ .initialize = tea6320_initialize, .volfunc = tea6320_volume, .bassfunc = tea6320_shift11, .treblefunc = tea6320_shift11, .inputreg = TEA6320_S, .inputmap = { TEA6320_S_SA, TEA6420_S_SB, TEA6300_S_SC, TEA6320_S_SD }, .inputmute = TEA6300_S_GMU, }, { .name = "tea6420", .insmodopt = &tea6420, .addr_lo = I2C_ADDR_TEA6420 >> 1, .addr_hi = I2C_ADDR_TEA6420 >> 1, .registers = 1, .flags = CHIP_HAS_INPUTSEL, .inputreg = -1, .inputmap = { TEA6420_S_SA, TEA6420_S_SB, TEA6420_S_SC }, .inputmute = TEA6300_S_GMU, }, { .name = "tda8425", .insmodopt = &tda8425, .addr_lo = I2C_ADDR_TDA8425 >> 1, .addr_hi = I2C_ADDR_TDA8425 >> 1, .registers = 9, .flags = CHIP_HAS_VOLUME | CHIP_HAS_BASSTREBLE | CHIP_HAS_INPUTSEL, .leftreg = TDA8425_VL, .rightreg = TDA8425_VR, .bassreg = TDA8425_BA, .treblereg = TDA8425_TR, /* callbacks */ .volfunc = tda8425_shift10, .bassfunc = tda8425_shift12, .treblefunc = tda8425_shift12, .setmode = tda8425_setmode, .inputreg = TDA8425_S1, .inputmap = { TDA8425_S1_CH1, TDA8425_S1_CH1, TDA8425_S1_CH1 }, .inputmute = TDA8425_S1_OFF, }, { .name = "pic16c54 (PV951)", .insmodopt = &pic16c54, .addr_lo = I2C_ADDR_PIC16C54 >> 1, .addr_hi = I2C_ADDR_PIC16C54>> 1, .registers = 2, .flags = CHIP_HAS_INPUTSEL, .inputreg = PIC16C54_REG_MISC, .inputmap = {PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_TUNER, PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_LINE, PIC16C54_MISC_SND_NOTMUTE|PIC16C54_MISC_SWITCH_LINE, PIC16C54_MISC_SND_MUTE}, .inputmute = PIC16C54_MISC_SND_MUTE, }, { .name = "ta8874z", .checkit = ta8874z_checkit, .insmodopt = &ta8874z, .addr_lo = I2C_ADDR_TDA9840 >> 1, .addr_hi = I2C_ADDR_TDA9840 >> 1, .registers = 2, .flags = CHIP_NEED_CHECKMODE, /* callbacks */ .getmode = ta8874z_getmode, .setmode = ta8874z_setmode, .init = {2, { TA8874Z_MONO_SET, TA8874Z_SEPARATION_DEFAULT}}, }, { .name = NULL } /* EOF */ }; /* ---------------------------------------------------------------------- */ static int tvaudio_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; switch (ctrl->id) { case V4L2_CID_AUDIO_MUTE: if (!(desc->flags & CHIP_HAS_INPUTSEL)) break; ctrl->value=chip->muted; return 0; case V4L2_CID_AUDIO_VOLUME: if (!(desc->flags & CHIP_HAS_VOLUME)) break; ctrl->value = max(chip->left,chip->right); return 0; case V4L2_CID_AUDIO_BALANCE: { int volume; if (!(desc->flags & CHIP_HAS_VOLUME)) break; volume = max(chip->left,chip->right); if (volume) ctrl->value=(32768*min(chip->left,chip->right))/volume; else ctrl->value=32768; return 0; } case V4L2_CID_AUDIO_BASS: if (!(desc->flags & CHIP_HAS_BASSTREBLE)) break; ctrl->value = chip->bass; return 0; case V4L2_CID_AUDIO_TREBLE: if (!(desc->flags & CHIP_HAS_BASSTREBLE)) break; ctrl->value = chip->treble; return 0; } return -EINVAL; } static int tvaudio_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; switch (ctrl->id) { case V4L2_CID_AUDIO_MUTE: if (!(desc->flags & CHIP_HAS_INPUTSEL)) break; if (ctrl->value < 0 || ctrl->value >= 2) return -ERANGE; chip->muted = ctrl->value; if (chip->muted) chip_write_masked(chip,desc->inputreg,desc->inputmute,desc->inputmask); else chip_write_masked(chip,desc->inputreg, desc->inputmap[chip->input],desc->inputmask); return 0; case V4L2_CID_AUDIO_VOLUME: { int volume,balance; if (!(desc->flags & CHIP_HAS_VOLUME)) break; volume = max(chip->left,chip->right); if (volume) balance=(32768*min(chip->left,chip->right))/volume; else balance=32768; volume=ctrl->value; chip->left = (min(65536 - balance,32768) * volume) / 32768; chip->right = (min(balance,volume *(__u16)32768)) / 32768; chip_write(chip,desc->leftreg,desc->volfunc(chip->left)); chip_write(chip,desc->rightreg,desc->volfunc(chip->right)); return 0; } case V4L2_CID_AUDIO_BALANCE: { int volume, balance; if (!(desc->flags & CHIP_HAS_VOLUME)) break; volume = max(chip->left, chip->right); balance = ctrl->value; chip->left = (min(65536 - balance, 32768) * volume) / 32768; chip->right = (min(balance, volume * (__u16)32768)) / 32768; chip_write(chip, desc->leftreg, desc->volfunc(chip->left)); chip_write(chip, desc->rightreg, desc->volfunc(chip->right)); return 0; } case V4L2_CID_AUDIO_BASS: if (!(desc->flags & CHIP_HAS_BASSTREBLE)) break; chip->bass = ctrl->value; chip_write(chip,desc->bassreg,desc->bassfunc(chip->bass)); return 0; case V4L2_CID_AUDIO_TREBLE: if (!(desc->flags & CHIP_HAS_BASSTREBLE)) break; chip->treble = ctrl->value; chip_write(chip,desc->treblereg,desc->treblefunc(chip->treble)); return 0; } return -EINVAL; } /* ---------------------------------------------------------------------- */ /* video4linux interface */ static int tvaudio_s_radio(struct v4l2_subdev *sd) { struct CHIPSTATE *chip = to_state(sd); chip->radio = 1; chip->watch_stereo = 0; /* del_timer(&chip->wt); */ return 0; } static int tvaudio_queryctrl(struct v4l2_subdev *sd, struct v4l2_queryctrl *qc) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; switch (qc->id) { case V4L2_CID_AUDIO_MUTE: if (desc->flags & CHIP_HAS_INPUTSEL) return v4l2_ctrl_query_fill(qc, 0, 1, 1, 0); break; case V4L2_CID_AUDIO_VOLUME: if (desc->flags & CHIP_HAS_VOLUME) return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 58880); break; case V4L2_CID_AUDIO_BALANCE: if (desc->flags & CHIP_HAS_VOLUME) return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768); break; case V4L2_CID_AUDIO_BASS: case V4L2_CID_AUDIO_TREBLE: if (desc->flags & CHIP_HAS_BASSTREBLE) return v4l2_ctrl_query_fill(qc, 0, 65535, 65535 / 100, 32768); break; default: break; } return -EINVAL; } static int tvaudio_s_routing(struct v4l2_subdev *sd, u32 input, u32 output, u32 config) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; if (!(desc->flags & CHIP_HAS_INPUTSEL)) return 0; if (input >= 4) return -EINVAL; /* There are four inputs: tuner, radio, extern and intern. */ chip->input = input; if (chip->muted) return 0; chip_write_masked(chip, desc->inputreg, desc->inputmap[chip->input], desc->inputmask); return 0; } static int tvaudio_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; int mode = 0; if (!desc->setmode) return 0; if (chip->radio) return 0; switch (vt->audmode) { case V4L2_TUNER_MODE_MONO: case V4L2_TUNER_MODE_STEREO: case V4L2_TUNER_MODE_LANG1: case V4L2_TUNER_MODE_LANG2: mode = vt->audmode; break; case V4L2_TUNER_MODE_LANG1_LANG2: mode = V4L2_TUNER_MODE_STEREO; break; default: return -EINVAL; } chip->audmode = vt->audmode; if (mode) { chip->watch_stereo = 0; /* del_timer(&chip->wt); */ chip->mode = mode; desc->setmode(chip, mode); } return 0; } static int tvaudio_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *vt) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; int mode = V4L2_TUNER_MODE_MONO; if (!desc->getmode) return 0; if (chip->radio) return 0; vt->audmode = chip->audmode; vt->rxsubchans = 0; vt->capability = V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2; mode = desc->getmode(chip); if (mode & V4L2_TUNER_MODE_MONO) vt->rxsubchans |= V4L2_TUNER_SUB_MONO; if (mode & V4L2_TUNER_MODE_STEREO) vt->rxsubchans |= V4L2_TUNER_SUB_STEREO; /* Note: for SAP it should be mono/lang2 or stereo/lang2. When this module is converted fully to v4l2, then this should change for those chips that can detect SAP. */ if (mode & V4L2_TUNER_MODE_LANG1) vt->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; return 0; } static int tvaudio_s_std(struct v4l2_subdev *sd, v4l2_std_id std) { struct CHIPSTATE *chip = to_state(sd); chip->radio = 0; return 0; } static int tvaudio_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *freq) { struct CHIPSTATE *chip = to_state(sd); struct CHIPDESC *desc = chip->desc; chip->mode = 0; /* automatic */ /* For chips that provide getmode and setmode, and doesn't automatically follows the stereo carrier, a kthread is created to set the audio standard. In this case, when then the video channel is changed, tvaudio starts on MONO mode. After waiting for 2 seconds, the kernel thread is called, to follow whatever audio standard is pointed by the audio carrier. */ if (chip->thread) { desc->setmode(chip, V4L2_TUNER_MODE_MONO); if (chip->prevmode != V4L2_TUNER_MODE_MONO) chip->prevmode = -1; /* reset previous mode */ mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000)); } return 0; } static int tvaudio_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip) { struct i2c_client *client = v4l2_get_subdevdata(sd); return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TVAUDIO, 0); } /* ----------------------------------------------------------------------- */ static const struct v4l2_subdev_core_ops tvaudio_core_ops = { .g_chip_ident = tvaudio_g_chip_ident, .queryctrl = tvaudio_queryctrl, .g_ctrl = tvaudio_g_ctrl, .s_ctrl = tvaudio_s_ctrl, .s_std = tvaudio_s_std, }; static const struct v4l2_subdev_tuner_ops tvaudio_tuner_ops = { .s_radio = tvaudio_s_radio, .s_frequency = tvaudio_s_frequency, .s_tuner = tvaudio_s_tuner, .g_tuner = tvaudio_g_tuner, }; static const struct v4l2_subdev_audio_ops tvaudio_audio_ops = { .s_routing = tvaudio_s_routing, }; static const struct v4l2_subdev_ops tvaudio_ops = { .core = &tvaudio_core_ops, .tuner = &tvaudio_tuner_ops, .audio = &tvaudio_audio_ops, }; /* ----------------------------------------------------------------------- */ /* i2c registration */ static int tvaudio_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct CHIPSTATE *chip; struct CHIPDESC *desc; struct v4l2_subdev *sd; if (debug) { printk(KERN_INFO "tvaudio: TV audio decoder + audio/video mux driver\n"); printk(KERN_INFO "tvaudio: known chips: "); for (desc = chiplist; desc->name != NULL; desc++) printk("%s%s", (desc == chiplist) ? "" : ", ", desc->name); printk("\n"); } chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; sd = &chip->sd; v4l2_i2c_subdev_init(sd, client, &tvaudio_ops); /* find description for the chip */ v4l2_dbg(1, debug, sd, "chip found @ 0x%x\n", client->addr<<1); for (desc = chiplist; desc->name != NULL; desc++) { if (0 == *(desc->insmodopt)) continue; if (client->addr < desc->addr_lo || client->addr > desc->addr_hi) continue; if (desc->checkit && !desc->checkit(chip)) continue; break; } if (desc->name == NULL) { v4l2_dbg(1, debug, sd, "no matching chip description found\n"); kfree(chip); return -EIO; } v4l2_info(sd, "%s found @ 0x%x (%s)\n", desc->name, client->addr<<1, client->adapter->name); if (desc->flags) { v4l2_dbg(1, debug, sd, "matches:%s%s%s.\n", (desc->flags & CHIP_HAS_VOLUME) ? " volume" : "", (desc->flags & CHIP_HAS_BASSTREBLE) ? " bass/treble" : "", (desc->flags & CHIP_HAS_INPUTSEL) ? " audiomux" : ""); } /* fill required data structures */ if (!id) strlcpy(client->name, desc->name, I2C_NAME_SIZE); chip->desc = desc; chip->shadow.count = desc->registers+1; chip->prevmode = -1; chip->audmode = V4L2_TUNER_MODE_LANG1; /* initialization */ if (desc->initialize != NULL) desc->initialize(chip); else chip_cmd(chip, "init", &desc->init); if (desc->flags & CHIP_HAS_VOLUME) { if (!desc->volfunc) { /* This shouldn't be happen. Warn user, but keep working without volume controls */ v4l2_info(sd, "volume callback undefined!\n"); desc->flags &= ~CHIP_HAS_VOLUME; } else { chip->left = desc->leftinit ? desc->leftinit : 65535; chip->right = desc->rightinit ? desc->rightinit : 65535; chip_write(chip, desc->leftreg, desc->volfunc(chip->left)); chip_write(chip, desc->rightreg, desc->volfunc(chip->right)); } } if (desc->flags & CHIP_HAS_BASSTREBLE) { if (!desc->bassfunc || !desc->treblefunc) { /* This shouldn't be happen. Warn user, but keep working without bass/treble controls */ v4l2_info(sd, "bass/treble callbacks undefined!\n"); desc->flags &= ~CHIP_HAS_BASSTREBLE; } else { chip->treble = desc->trebleinit ? desc->trebleinit : 32768; chip->bass = desc->bassinit ? desc->bassinit : 32768; chip_write(chip, desc->bassreg, desc->bassfunc(chip->bass)); chip_write(chip, desc->treblereg, desc->treblefunc(chip->treble)); } } chip->thread = NULL; init_timer(&chip->wt); if (desc->flags & CHIP_NEED_CHECKMODE) { if (!desc->getmode || !desc->setmode) { /* This shouldn't be happen. Warn user, but keep working without kthread */ v4l2_info(sd, "set/get mode callbacks undefined!\n"); return 0; } /* start async thread */ chip->wt.function = chip_thread_wake; chip->wt.data = (unsigned long)chip; chip->thread = kthread_run(chip_thread, chip, client->name); if (IS_ERR(chip->thread)) { v4l2_warn(sd, "failed to create kthread\n"); chip->thread = NULL; } } return 0; } static int tvaudio_remove(struct i2c_client *client) { struct v4l2_subdev *sd = i2c_get_clientdata(client); struct CHIPSTATE *chip = to_state(sd); del_timer_sync(&chip->wt); if (chip->thread) { /* shutdown async thread */ kthread_stop(chip->thread); chip->thread = NULL; } v4l2_device_unregister_subdev(sd); kfree(chip); return 0; } /* This driver supports many devices and the idea is to let the driver detect which device is present. So rather than listing all supported devices here, we pretend to support a single, fake device type. */ static const struct i2c_device_id tvaudio_id[] = { { "tvaudio", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, tvaudio_id); static struct i2c_driver tvaudio_driver = { .driver = { .owner = THIS_MODULE, .name = "tvaudio", }, .probe = tvaudio_probe, .remove = tvaudio_remove, .id_table = tvaudio_id, }; module_i2c_driver(tvaudio_driver);
gpl-2.0
Swapnil133609/Zeus_bacon
drivers/media/video/mt9m001.c
4863
19752
/* * Driver for MT9M001 CMOS Image Sensor from Micron * * Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de> * * 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/videodev2.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/log2.h> #include <linux/module.h> #include <media/soc_camera.h> #include <media/soc_mediabus.h> #include <media/v4l2-subdev.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-ctrls.h> /* * mt9m001 i2c address 0x5d * The platform has to define ctruct i2c_board_info objects and link to them * from struct soc_camera_link */ /* mt9m001 selected register addresses */ #define MT9M001_CHIP_VERSION 0x00 #define MT9M001_ROW_START 0x01 #define MT9M001_COLUMN_START 0x02 #define MT9M001_WINDOW_HEIGHT 0x03 #define MT9M001_WINDOW_WIDTH 0x04 #define MT9M001_HORIZONTAL_BLANKING 0x05 #define MT9M001_VERTICAL_BLANKING 0x06 #define MT9M001_OUTPUT_CONTROL 0x07 #define MT9M001_SHUTTER_WIDTH 0x09 #define MT9M001_FRAME_RESTART 0x0b #define MT9M001_SHUTTER_DELAY 0x0c #define MT9M001_RESET 0x0d #define MT9M001_READ_OPTIONS1 0x1e #define MT9M001_READ_OPTIONS2 0x20 #define MT9M001_GLOBAL_GAIN 0x35 #define MT9M001_CHIP_ENABLE 0xF1 #define MT9M001_MAX_WIDTH 1280 #define MT9M001_MAX_HEIGHT 1024 #define MT9M001_MIN_WIDTH 48 #define MT9M001_MIN_HEIGHT 32 #define MT9M001_COLUMN_SKIP 20 #define MT9M001_ROW_SKIP 12 /* MT9M001 has only one fixed colorspace per pixelcode */ struct mt9m001_datafmt { enum v4l2_mbus_pixelcode code; enum v4l2_colorspace colorspace; }; /* Find a data format by a pixel code in an array */ static const struct mt9m001_datafmt *mt9m001_find_datafmt( enum v4l2_mbus_pixelcode code, const struct mt9m001_datafmt *fmt, int n) { int i; for (i = 0; i < n; i++) if (fmt[i].code == code) return fmt + i; return NULL; } static const struct mt9m001_datafmt mt9m001_colour_fmts[] = { /* * Order important: first natively supported, * second supported with a GPIO extender */ {V4L2_MBUS_FMT_SBGGR10_1X10, V4L2_COLORSPACE_SRGB}, {V4L2_MBUS_FMT_SBGGR8_1X8, V4L2_COLORSPACE_SRGB}, }; static const struct mt9m001_datafmt mt9m001_monochrome_fmts[] = { /* Order important - see above */ {V4L2_MBUS_FMT_Y10_1X10, V4L2_COLORSPACE_JPEG}, {V4L2_MBUS_FMT_Y8_1X8, V4L2_COLORSPACE_JPEG}, }; struct mt9m001 { struct v4l2_subdev subdev; struct v4l2_ctrl_handler hdl; struct { /* exposure/auto-exposure cluster */ struct v4l2_ctrl *autoexposure; struct v4l2_ctrl *exposure; }; struct v4l2_rect rect; /* Sensor window */ const struct mt9m001_datafmt *fmt; const struct mt9m001_datafmt *fmts; int num_fmts; int model; /* V4L2_IDENT_MT9M001* codes from v4l2-chip-ident.h */ unsigned int total_h; unsigned short y_skip_top; /* Lines to skip at the top */ }; static struct mt9m001 *to_mt9m001(const struct i2c_client *client) { return container_of(i2c_get_clientdata(client), struct mt9m001, subdev); } static int reg_read(struct i2c_client *client, const u8 reg) { return i2c_smbus_read_word_swapped(client, reg); } static int reg_write(struct i2c_client *client, const u8 reg, const u16 data) { return i2c_smbus_write_word_swapped(client, reg, data); } static int reg_set(struct i2c_client *client, const u8 reg, const u16 data) { int ret; ret = reg_read(client, reg); if (ret < 0) return ret; return reg_write(client, reg, ret | data); } static int reg_clear(struct i2c_client *client, const u8 reg, const u16 data) { int ret; ret = reg_read(client, reg); if (ret < 0) return ret; return reg_write(client, reg, ret & ~data); } static int mt9m001_init(struct i2c_client *client) { int ret; dev_dbg(&client->dev, "%s\n", __func__); /* * We don't know, whether platform provides reset, issue a soft reset * too. This returns all registers to their default values. */ ret = reg_write(client, MT9M001_RESET, 1); if (!ret) ret = reg_write(client, MT9M001_RESET, 0); /* Disable chip, synchronous option update */ if (!ret) ret = reg_write(client, MT9M001_OUTPUT_CONTROL, 0); return ret; } static int mt9m001_s_stream(struct v4l2_subdev *sd, int enable) { struct i2c_client *client = v4l2_get_subdevdata(sd); /* Switch to master "normal" mode or stop sensor readout */ if (reg_write(client, MT9M001_OUTPUT_CONTROL, enable ? 2 : 0) < 0) return -EIO; return 0; } static int mt9m001_s_crop(struct v4l2_subdev *sd, struct v4l2_crop *a) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); struct v4l2_rect rect = a->c; int ret; const u16 hblank = 9, vblank = 25; if (mt9m001->fmts == mt9m001_colour_fmts) /* * Bayer format - even number of rows for simplicity, * but let the user play with the top row. */ rect.height = ALIGN(rect.height, 2); /* Datasheet requirement: see register description */ rect.width = ALIGN(rect.width, 2); rect.left = ALIGN(rect.left, 2); soc_camera_limit_side(&rect.left, &rect.width, MT9M001_COLUMN_SKIP, MT9M001_MIN_WIDTH, MT9M001_MAX_WIDTH); soc_camera_limit_side(&rect.top, &rect.height, MT9M001_ROW_SKIP, MT9M001_MIN_HEIGHT, MT9M001_MAX_HEIGHT); mt9m001->total_h = rect.height + mt9m001->y_skip_top + vblank; /* Blanking and start values - default... */ ret = reg_write(client, MT9M001_HORIZONTAL_BLANKING, hblank); if (!ret) ret = reg_write(client, MT9M001_VERTICAL_BLANKING, vblank); /* * The caller provides a supported format, as verified per * call to .try_mbus_fmt() */ if (!ret) ret = reg_write(client, MT9M001_COLUMN_START, rect.left); if (!ret) ret = reg_write(client, MT9M001_ROW_START, rect.top); if (!ret) ret = reg_write(client, MT9M001_WINDOW_WIDTH, rect.width - 1); if (!ret) ret = reg_write(client, MT9M001_WINDOW_HEIGHT, rect.height + mt9m001->y_skip_top - 1); if (!ret && v4l2_ctrl_g_ctrl(mt9m001->autoexposure) == V4L2_EXPOSURE_AUTO) ret = reg_write(client, MT9M001_SHUTTER_WIDTH, mt9m001->total_h); if (!ret) mt9m001->rect = rect; return ret; } static int mt9m001_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); a->c = mt9m001->rect; a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; return 0; } static int mt9m001_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a) { a->bounds.left = MT9M001_COLUMN_SKIP; a->bounds.top = MT9M001_ROW_SKIP; a->bounds.width = MT9M001_MAX_WIDTH; a->bounds.height = MT9M001_MAX_HEIGHT; a->defrect = a->bounds; a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; a->pixelaspect.numerator = 1; a->pixelaspect.denominator = 1; return 0; } static int mt9m001_g_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); mf->width = mt9m001->rect.width; mf->height = mt9m001->rect.height; mf->code = mt9m001->fmt->code; mf->colorspace = mt9m001->fmt->colorspace; mf->field = V4L2_FIELD_NONE; return 0; } static int mt9m001_s_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); struct v4l2_crop a = { .c = { .left = mt9m001->rect.left, .top = mt9m001->rect.top, .width = mf->width, .height = mf->height, }, }; int ret; /* No support for scaling so far, just crop. TODO: use skipping */ ret = mt9m001_s_crop(sd, &a); if (!ret) { mf->width = mt9m001->rect.width; mf->height = mt9m001->rect.height; mt9m001->fmt = mt9m001_find_datafmt(mf->code, mt9m001->fmts, mt9m001->num_fmts); mf->colorspace = mt9m001->fmt->colorspace; } return ret; } static int mt9m001_try_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); const struct mt9m001_datafmt *fmt; v4l_bound_align_image(&mf->width, MT9M001_MIN_WIDTH, MT9M001_MAX_WIDTH, 1, &mf->height, MT9M001_MIN_HEIGHT + mt9m001->y_skip_top, MT9M001_MAX_HEIGHT + mt9m001->y_skip_top, 0, 0); if (mt9m001->fmts == mt9m001_colour_fmts) mf->height = ALIGN(mf->height - 1, 2); fmt = mt9m001_find_datafmt(mf->code, mt9m001->fmts, mt9m001->num_fmts); if (!fmt) { fmt = mt9m001->fmt; mf->code = fmt->code; } mf->colorspace = fmt->colorspace; return 0; } static int mt9m001_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *id) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); if (id->match.type != V4L2_CHIP_MATCH_I2C_ADDR) return -EINVAL; if (id->match.addr != client->addr) return -ENODEV; id->ident = mt9m001->model; id->revision = 0; return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int mt9m001_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); if (reg->match.type != V4L2_CHIP_MATCH_I2C_ADDR || reg->reg > 0xff) return -EINVAL; if (reg->match.addr != client->addr) return -ENODEV; reg->size = 2; reg->val = reg_read(client, reg->reg); if (reg->val > 0xffff) return -EIO; return 0; } static int mt9m001_s_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); if (reg->match.type != V4L2_CHIP_MATCH_I2C_ADDR || reg->reg > 0xff) return -EINVAL; if (reg->match.addr != client->addr) return -ENODEV; if (reg_write(client, reg->reg, reg->val) < 0) return -EIO; return 0; } #endif static int mt9m001_g_volatile_ctrl(struct v4l2_ctrl *ctrl) { struct mt9m001 *mt9m001 = container_of(ctrl->handler, struct mt9m001, hdl); s32 min, max; switch (ctrl->id) { case V4L2_CID_EXPOSURE_AUTO: min = mt9m001->exposure->minimum; max = mt9m001->exposure->maximum; mt9m001->exposure->val = (524 + (mt9m001->total_h - 1) * (max - min)) / 1048 + min; break; } return 0; } static int mt9m001_s_ctrl(struct v4l2_ctrl *ctrl) { struct mt9m001 *mt9m001 = container_of(ctrl->handler, struct mt9m001, hdl); struct v4l2_subdev *sd = &mt9m001->subdev; struct i2c_client *client = v4l2_get_subdevdata(sd); struct v4l2_ctrl *exp = mt9m001->exposure; int data; switch (ctrl->id) { case V4L2_CID_VFLIP: if (ctrl->val) data = reg_set(client, MT9M001_READ_OPTIONS2, 0x8000); else data = reg_clear(client, MT9M001_READ_OPTIONS2, 0x8000); if (data < 0) return -EIO; return 0; case V4L2_CID_GAIN: /* See Datasheet Table 7, Gain settings. */ if (ctrl->val <= ctrl->default_value) { /* Pack it into 0..1 step 0.125, register values 0..8 */ unsigned long range = ctrl->default_value - ctrl->minimum; data = ((ctrl->val - ctrl->minimum) * 8 + range / 2) / range; dev_dbg(&client->dev, "Setting gain %d\n", data); data = reg_write(client, MT9M001_GLOBAL_GAIN, data); if (data < 0) return -EIO; } else { /* Pack it into 1.125..15 variable step, register values 9..67 */ /* We assume qctrl->maximum - qctrl->default_value - 1 > 0 */ unsigned long range = ctrl->maximum - ctrl->default_value - 1; unsigned long gain = ((ctrl->val - ctrl->default_value - 1) * 111 + range / 2) / range + 9; if (gain <= 32) data = gain; else if (gain <= 64) data = ((gain - 32) * 16 + 16) / 32 + 80; else data = ((gain - 64) * 7 + 28) / 56 + 96; dev_dbg(&client->dev, "Setting gain from %d to %d\n", reg_read(client, MT9M001_GLOBAL_GAIN), data); data = reg_write(client, MT9M001_GLOBAL_GAIN, data); if (data < 0) return -EIO; } return 0; case V4L2_CID_EXPOSURE_AUTO: if (ctrl->val == V4L2_EXPOSURE_MANUAL) { unsigned long range = exp->maximum - exp->minimum; unsigned long shutter = ((exp->val - exp->minimum) * 1048 + range / 2) / range + 1; dev_dbg(&client->dev, "Setting shutter width from %d to %lu\n", reg_read(client, MT9M001_SHUTTER_WIDTH), shutter); if (reg_write(client, MT9M001_SHUTTER_WIDTH, shutter) < 0) return -EIO; } else { const u16 vblank = 25; mt9m001->total_h = mt9m001->rect.height + mt9m001->y_skip_top + vblank; if (reg_write(client, MT9M001_SHUTTER_WIDTH, mt9m001->total_h) < 0) return -EIO; } return 0; } return -EINVAL; } /* * Interface active, can use i2c. If it fails, it can indeed mean, that * this wasn't our capture interface, so, we wait for the right one */ static int mt9m001_video_probe(struct soc_camera_link *icl, struct i2c_client *client) { struct mt9m001 *mt9m001 = to_mt9m001(client); s32 data; unsigned long flags; int ret; /* Enable the chip */ data = reg_write(client, MT9M001_CHIP_ENABLE, 1); dev_dbg(&client->dev, "write: %d\n", data); /* Read out the chip version register */ data = reg_read(client, MT9M001_CHIP_VERSION); /* must be 0x8411 or 0x8421 for colour sensor and 8431 for bw */ switch (data) { case 0x8411: case 0x8421: mt9m001->model = V4L2_IDENT_MT9M001C12ST; mt9m001->fmts = mt9m001_colour_fmts; break; case 0x8431: mt9m001->model = V4L2_IDENT_MT9M001C12STM; mt9m001->fmts = mt9m001_monochrome_fmts; break; default: dev_err(&client->dev, "No MT9M001 chip detected, register read %x\n", data); return -ENODEV; } mt9m001->num_fmts = 0; /* * This is a 10bit sensor, so by default we only allow 10bit. * The platform may support different bus widths due to * different routing of the data lines. */ if (icl->query_bus_param) flags = icl->query_bus_param(icl); else flags = SOCAM_DATAWIDTH_10; if (flags & SOCAM_DATAWIDTH_10) mt9m001->num_fmts++; else mt9m001->fmts++; if (flags & SOCAM_DATAWIDTH_8) mt9m001->num_fmts++; mt9m001->fmt = &mt9m001->fmts[0]; dev_info(&client->dev, "Detected a MT9M001 chip ID %x (%s)\n", data, data == 0x8431 ? "C12STM" : "C12ST"); ret = mt9m001_init(client); if (ret < 0) dev_err(&client->dev, "Failed to initialise the camera\n"); /* mt9m001_init() has reset the chip, returning registers to defaults */ return v4l2_ctrl_handler_setup(&mt9m001->hdl); } static void mt9m001_video_remove(struct soc_camera_link *icl) { if (icl->free_bus) icl->free_bus(icl); } static int mt9m001_g_skip_top_lines(struct v4l2_subdev *sd, u32 *lines) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); *lines = mt9m001->y_skip_top; return 0; } static const struct v4l2_ctrl_ops mt9m001_ctrl_ops = { .g_volatile_ctrl = mt9m001_g_volatile_ctrl, .s_ctrl = mt9m001_s_ctrl, }; static struct v4l2_subdev_core_ops mt9m001_subdev_core_ops = { .g_chip_ident = mt9m001_g_chip_ident, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = mt9m001_g_register, .s_register = mt9m001_s_register, #endif }; static int mt9m001_enum_fmt(struct v4l2_subdev *sd, unsigned int index, enum v4l2_mbus_pixelcode *code) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct mt9m001 *mt9m001 = to_mt9m001(client); if (index >= mt9m001->num_fmts) return -EINVAL; *code = mt9m001->fmts[index].code; return 0; } static int mt9m001_g_mbus_config(struct v4l2_subdev *sd, struct v4l2_mbus_config *cfg) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct soc_camera_link *icl = soc_camera_i2c_to_link(client); /* MT9M001 has all capture_format parameters fixed */ cfg->flags = V4L2_MBUS_PCLK_SAMPLE_FALLING | V4L2_MBUS_HSYNC_ACTIVE_HIGH | V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_DATA_ACTIVE_HIGH | V4L2_MBUS_MASTER; cfg->type = V4L2_MBUS_PARALLEL; cfg->flags = soc_camera_apply_board_flags(icl, cfg); return 0; } static int mt9m001_s_mbus_config(struct v4l2_subdev *sd, const struct v4l2_mbus_config *cfg) { const struct i2c_client *client = v4l2_get_subdevdata(sd); struct soc_camera_link *icl = soc_camera_i2c_to_link(client); struct mt9m001 *mt9m001 = to_mt9m001(client); unsigned int bps = soc_mbus_get_fmtdesc(mt9m001->fmt->code)->bits_per_sample; if (icl->set_bus_param) return icl->set_bus_param(icl, 1 << (bps - 1)); /* * Without board specific bus width settings we only support the * sensors native bus width */ return bps == 10 ? 0 : -EINVAL; } static struct v4l2_subdev_video_ops mt9m001_subdev_video_ops = { .s_stream = mt9m001_s_stream, .s_mbus_fmt = mt9m001_s_fmt, .g_mbus_fmt = mt9m001_g_fmt, .try_mbus_fmt = mt9m001_try_fmt, .s_crop = mt9m001_s_crop, .g_crop = mt9m001_g_crop, .cropcap = mt9m001_cropcap, .enum_mbus_fmt = mt9m001_enum_fmt, .g_mbus_config = mt9m001_g_mbus_config, .s_mbus_config = mt9m001_s_mbus_config, }; static struct v4l2_subdev_sensor_ops mt9m001_subdev_sensor_ops = { .g_skip_top_lines = mt9m001_g_skip_top_lines, }; static struct v4l2_subdev_ops mt9m001_subdev_ops = { .core = &mt9m001_subdev_core_ops, .video = &mt9m001_subdev_video_ops, .sensor = &mt9m001_subdev_sensor_ops, }; static int mt9m001_probe(struct i2c_client *client, const struct i2c_device_id *did) { struct mt9m001 *mt9m001; struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); struct soc_camera_link *icl = soc_camera_i2c_to_link(client); int ret; if (!icl) { dev_err(&client->dev, "MT9M001 driver needs platform data\n"); return -EINVAL; } if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) { dev_warn(&adapter->dev, "I2C-Adapter doesn't support I2C_FUNC_SMBUS_WORD\n"); return -EIO; } mt9m001 = kzalloc(sizeof(struct mt9m001), GFP_KERNEL); if (!mt9m001) return -ENOMEM; v4l2_i2c_subdev_init(&mt9m001->subdev, client, &mt9m001_subdev_ops); v4l2_ctrl_handler_init(&mt9m001->hdl, 4); v4l2_ctrl_new_std(&mt9m001->hdl, &mt9m001_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&mt9m001->hdl, &mt9m001_ctrl_ops, V4L2_CID_GAIN, 0, 127, 1, 64); mt9m001->exposure = v4l2_ctrl_new_std(&mt9m001->hdl, &mt9m001_ctrl_ops, V4L2_CID_EXPOSURE, 1, 255, 1, 255); /* * Simulated autoexposure. If enabled, we calculate shutter width * ourselves in the driver based on vertical blanking and frame width */ mt9m001->autoexposure = v4l2_ctrl_new_std_menu(&mt9m001->hdl, &mt9m001_ctrl_ops, V4L2_CID_EXPOSURE_AUTO, 1, 0, V4L2_EXPOSURE_AUTO); mt9m001->subdev.ctrl_handler = &mt9m001->hdl; if (mt9m001->hdl.error) { int err = mt9m001->hdl.error; kfree(mt9m001); return err; } v4l2_ctrl_auto_cluster(2, &mt9m001->autoexposure, V4L2_EXPOSURE_MANUAL, true); /* Second stage probe - when a capture adapter is there */ mt9m001->y_skip_top = 0; mt9m001->rect.left = MT9M001_COLUMN_SKIP; mt9m001->rect.top = MT9M001_ROW_SKIP; mt9m001->rect.width = MT9M001_MAX_WIDTH; mt9m001->rect.height = MT9M001_MAX_HEIGHT; ret = mt9m001_video_probe(icl, client); if (ret) { v4l2_ctrl_handler_free(&mt9m001->hdl); kfree(mt9m001); } return ret; } static int mt9m001_remove(struct i2c_client *client) { struct mt9m001 *mt9m001 = to_mt9m001(client); struct soc_camera_link *icl = soc_camera_i2c_to_link(client); v4l2_device_unregister_subdev(&mt9m001->subdev); v4l2_ctrl_handler_free(&mt9m001->hdl); mt9m001_video_remove(icl); kfree(mt9m001); return 0; } static const struct i2c_device_id mt9m001_id[] = { { "mt9m001", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, mt9m001_id); static struct i2c_driver mt9m001_i2c_driver = { .driver = { .name = "mt9m001", }, .probe = mt9m001_probe, .remove = mt9m001_remove, .id_table = mt9m001_id, }; module_i2c_driver(mt9m001_i2c_driver); MODULE_DESCRIPTION("Micron MT9M001 Camera driver"); MODULE_AUTHOR("Guennadi Liakhovetski <kernel@pengutronix.de>"); MODULE_LICENSE("GPL");
gpl-2.0
gmm001/android_kernel_zte_nx503a-1
arch/arm/mach-pxa/palmtc.c
4863
13747
/* * linux/arch/arm/mach-pxa/palmtc.c * * Support for the Palm Tungsten|C * * Author: Marek Vasut <marek.vasut@gmail.com> * * Based on work of: * Petr Blaha <p3t3@centrum.cz> * Chetan S. Kumar <shivakumar.chetan@gmail.com> * * 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/platform_device.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/input.h> #include <linux/pwm_backlight.h> #include <linux/gpio.h> #include <linux/input/matrix_keypad.h> #include <linux/ucb1400.h> #include <linux/power_supply.h> #include <linux/gpio_keys.h> #include <linux/mtd/physmap.h> #include <linux/usb/gpio_vbus.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/pxa25x.h> #include <mach/audio.h> #include <mach/palmtc.h> #include <mach/mmc.h> #include <mach/pxafb.h> #include <mach/irda.h> #include <mach/udc.h> #include "generic.h" #include "devices.h" /****************************************************************************** * Pin configuration ******************************************************************************/ static unsigned long palmtc_pin_config[] __initdata = { /* MMC */ GPIO6_MMC_CLK, GPIO8_MMC_CS0, GPIO12_GPIO, /* detect */ GPIO32_GPIO, /* power */ GPIO54_GPIO, /* r/o switch */ /* PCMCIA */ GPIO52_nPCE_1, GPIO53_nPCE_2, GPIO50_nPIOR, GPIO51_nPIOW, GPIO49_nPWE, GPIO48_nPOE, GPIO52_nPCE_1, GPIO53_nPCE_2, GPIO57_nIOIS16, GPIO56_nPWAIT, /* AC97 */ GPIO28_AC97_BITCLK, GPIO29_AC97_SDATA_IN_0, GPIO30_AC97_SDATA_OUT, GPIO31_AC97_SYNC, /* IrDA */ GPIO45_GPIO, /* ir disable */ GPIO46_FICP_RXD, GPIO47_FICP_TXD, /* PWM */ GPIO17_PWM1_OUT, /* USB */ GPIO4_GPIO, /* detect */ GPIO36_GPIO, /* pullup */ /* LCD */ GPIOxx_LCD_TFT_16BPP, /* MATRIX KEYPAD */ GPIO0_GPIO | WAKEUP_ON_EDGE_BOTH, /* in 0 */ GPIO9_GPIO | WAKEUP_ON_EDGE_BOTH, /* in 1 */ GPIO10_GPIO | WAKEUP_ON_EDGE_BOTH, /* in 2 */ GPIO11_GPIO | WAKEUP_ON_EDGE_BOTH, /* in 3 */ GPIO18_GPIO | MFP_LPM_DRIVE_LOW, /* out 0 */ GPIO19_GPIO | MFP_LPM_DRIVE_LOW, /* out 1 */ GPIO20_GPIO | MFP_LPM_DRIVE_LOW, /* out 2 */ GPIO21_GPIO | MFP_LPM_DRIVE_LOW, /* out 3 */ GPIO22_GPIO | MFP_LPM_DRIVE_LOW, /* out 4 */ GPIO23_GPIO | MFP_LPM_DRIVE_LOW, /* out 5 */ GPIO24_GPIO | MFP_LPM_DRIVE_LOW, /* out 6 */ GPIO25_GPIO | MFP_LPM_DRIVE_LOW, /* out 7 */ GPIO26_GPIO | MFP_LPM_DRIVE_LOW, /* out 8 */ GPIO27_GPIO | MFP_LPM_DRIVE_LOW, /* out 9 */ GPIO79_GPIO | MFP_LPM_DRIVE_LOW, /* out 10 */ GPIO80_GPIO | MFP_LPM_DRIVE_LOW, /* out 11 */ /* PXA GPIO KEYS */ GPIO7_GPIO | WAKEUP_ON_EDGE_BOTH, /* hotsync button on cradle */ /* MISC */ GPIO1_RST, /* reset */ GPIO2_GPIO, /* earphone detect */ GPIO16_GPIO, /* backlight switch */ }; /****************************************************************************** * SD/MMC card controller ******************************************************************************/ #if defined(CONFIG_MMC_PXA) || defined(CONFIG_MMC_PXA_MODULE) static struct pxamci_platform_data palmtc_mci_platform_data = { .ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34, .gpio_power = GPIO_NR_PALMTC_SD_POWER, .gpio_card_ro = GPIO_NR_PALMTC_SD_READONLY, .gpio_card_detect = GPIO_NR_PALMTC_SD_DETECT_N, .detect_delay_ms = 200, }; static void __init palmtc_mmc_init(void) { pxa_set_mci_info(&palmtc_mci_platform_data); } #else static inline void palmtc_mmc_init(void) {} #endif /****************************************************************************** * GPIO keys ******************************************************************************/ #if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE) static struct gpio_keys_button palmtc_pxa_buttons[] = { {KEY_F8, GPIO_NR_PALMTC_HOTSYNC_BUTTON, 1, "HotSync Button", EV_KEY, 1}, }; static struct gpio_keys_platform_data palmtc_pxa_keys_data = { .buttons = palmtc_pxa_buttons, .nbuttons = ARRAY_SIZE(palmtc_pxa_buttons), }; static struct platform_device palmtc_pxa_keys = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &palmtc_pxa_keys_data, }, }; static void __init palmtc_keys_init(void) { platform_device_register(&palmtc_pxa_keys); } #else static inline void palmtc_keys_init(void) {} #endif /****************************************************************************** * Backlight ******************************************************************************/ #if defined(CONFIG_BACKLIGHT_PWM) || defined(CONFIG_BACKLIGHT_PWM_MODULE) static int palmtc_backlight_init(struct device *dev) { int ret; ret = gpio_request(GPIO_NR_PALMTC_BL_POWER, "BL POWER"); if (ret) goto err; ret = gpio_direction_output(GPIO_NR_PALMTC_BL_POWER, 1); if (ret) goto err2; return 0; err2: gpio_free(GPIO_NR_PALMTC_BL_POWER); err: return ret; } static int palmtc_backlight_notify(struct device *dev, int brightness) { /* backlight is on when GPIO16 AF0 is high */ gpio_set_value(GPIO_NR_PALMTC_BL_POWER, brightness); return brightness; } static void palmtc_backlight_exit(struct device *dev) { gpio_free(GPIO_NR_PALMTC_BL_POWER); } static struct platform_pwm_backlight_data palmtc_backlight_data = { .pwm_id = 1, .max_brightness = PALMTC_MAX_INTENSITY, .dft_brightness = PALMTC_MAX_INTENSITY, .pwm_period_ns = PALMTC_PERIOD_NS, .init = palmtc_backlight_init, .notify = palmtc_backlight_notify, .exit = palmtc_backlight_exit, }; static struct platform_device palmtc_backlight = { .name = "pwm-backlight", .dev = { .parent = &pxa25x_device_pwm1.dev, .platform_data = &palmtc_backlight_data, }, }; static void __init palmtc_pwm_init(void) { platform_device_register(&palmtc_backlight); } #else static inline void palmtc_pwm_init(void) {} #endif /****************************************************************************** * IrDA ******************************************************************************/ #if defined(CONFIG_IRDA) || defined(CONFIG_IRDA_MODULE) static struct pxaficp_platform_data palmtc_ficp_platform_data = { .gpio_pwdown = GPIO_NR_PALMTC_IR_DISABLE, .transceiver_cap = IR_SIRMODE | IR_OFF, }; static void __init palmtc_irda_init(void) { pxa_set_ficp_info(&palmtc_ficp_platform_data); } #else static inline void palmtc_irda_init(void) {} #endif /****************************************************************************** * Keyboard ******************************************************************************/ #if defined(CONFIG_KEYBOARD_MATRIX) || defined(CONFIG_KEYBOARD_MATRIX_MODULE) static const uint32_t palmtc_matrix_keys[] = { KEY(0, 0, KEY_F1), KEY(0, 1, KEY_X), KEY(0, 2, KEY_POWER), KEY(0, 3, KEY_TAB), KEY(0, 4, KEY_A), KEY(0, 5, KEY_Q), KEY(0, 6, KEY_LEFTSHIFT), KEY(0, 7, KEY_Z), KEY(0, 8, KEY_S), KEY(0, 9, KEY_W), KEY(0, 10, KEY_E), KEY(0, 11, KEY_UP), KEY(1, 0, KEY_F2), KEY(1, 1, KEY_DOWN), KEY(1, 3, KEY_D), KEY(1, 4, KEY_C), KEY(1, 5, KEY_F), KEY(1, 6, KEY_R), KEY(1, 7, KEY_SPACE), KEY(1, 8, KEY_V), KEY(1, 9, KEY_G), KEY(1, 10, KEY_T), KEY(1, 11, KEY_LEFT), KEY(2, 0, KEY_F3), KEY(2, 1, KEY_LEFTCTRL), KEY(2, 3, KEY_H), KEY(2, 4, KEY_Y), KEY(2, 5, KEY_N), KEY(2, 6, KEY_J), KEY(2, 7, KEY_U), KEY(2, 8, KEY_M), KEY(2, 9, KEY_K), KEY(2, 10, KEY_I), KEY(2, 11, KEY_RIGHT), KEY(3, 0, KEY_F4), KEY(3, 1, KEY_ENTER), KEY(3, 3, KEY_DOT), KEY(3, 4, KEY_L), KEY(3, 5, KEY_O), KEY(3, 6, KEY_LEFTALT), KEY(3, 7, KEY_ENTER), KEY(3, 8, KEY_BACKSPACE), KEY(3, 9, KEY_P), KEY(3, 10, KEY_B), KEY(3, 11, KEY_FN), }; const struct matrix_keymap_data palmtc_keymap_data = { .keymap = palmtc_matrix_keys, .keymap_size = ARRAY_SIZE(palmtc_matrix_keys), }; static const unsigned int palmtc_keypad_row_gpios[] = { 0, 9, 10, 11 }; static const unsigned int palmtc_keypad_col_gpios[] = { 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 79, 80 }; static struct matrix_keypad_platform_data palmtc_keypad_platform_data = { .keymap_data = &palmtc_keymap_data, .row_gpios = palmtc_keypad_row_gpios, .num_row_gpios = ARRAY_SIZE(palmtc_keypad_row_gpios), .col_gpios = palmtc_keypad_col_gpios, .num_col_gpios = ARRAY_SIZE(palmtc_keypad_col_gpios), .active_low = 1, .debounce_ms = 20, .col_scan_delay_us = 5, }; static struct platform_device palmtc_keyboard = { .name = "matrix-keypad", .id = -1, .dev = { .platform_data = &palmtc_keypad_platform_data, }, }; static void __init palmtc_mkp_init(void) { platform_device_register(&palmtc_keyboard); } #else static inline void palmtc_mkp_init(void) {} #endif /****************************************************************************** * UDC ******************************************************************************/ #if defined(CONFIG_USB_PXA25X)||defined(CONFIG_USB_PXA25X_MODULE) static struct gpio_vbus_mach_info palmtc_udc_info = { .gpio_vbus = GPIO_NR_PALMTC_USB_DETECT_N, .gpio_vbus_inverted = 1, .gpio_pullup = GPIO_NR_PALMTC_USB_POWER, }; static struct platform_device palmtc_gpio_vbus = { .name = "gpio-vbus", .id = -1, .dev = { .platform_data = &palmtc_udc_info, }, }; static void __init palmtc_udc_init(void) { platform_device_register(&palmtc_gpio_vbus); }; #else static inline void palmtc_udc_init(void) {} #endif /****************************************************************************** * Touchscreen / Battery / GPIO-extender ******************************************************************************/ #if defined(CONFIG_TOUCHSCREEN_UCB1400) || \ defined(CONFIG_TOUCHSCREEN_UCB1400_MODULE) static struct platform_device palmtc_ucb1400_device = { .name = "ucb1400_core", .id = -1, }; static void __init palmtc_ts_init(void) { pxa_set_ac97_info(NULL); platform_device_register(&palmtc_ucb1400_device); } #else static inline void palmtc_ts_init(void) {} #endif /****************************************************************************** * LEDs ******************************************************************************/ #if defined(CONFIG_LEDS_GPIO) || defined(CONFIG_LEDS_GPIO_MODULE) struct gpio_led palmtc_gpio_leds[] = { { .name = "palmtc:green:user", .default_trigger = "none", .gpio = GPIO_NR_PALMTC_LED_POWER, .active_low = 1, }, { .name = "palmtc:vibra:vibra", .default_trigger = "none", .gpio = GPIO_NR_PALMTC_VIBRA_POWER, .active_low = 1, } }; static struct gpio_led_platform_data palmtc_gpio_led_info = { .leds = palmtc_gpio_leds, .num_leds = ARRAY_SIZE(palmtc_gpio_leds), }; static struct platform_device palmtc_leds = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &palmtc_gpio_led_info, } }; static void __init palmtc_leds_init(void) { platform_device_register(&palmtc_leds); } #else static inline void palmtc_leds_init(void) {} #endif /****************************************************************************** * NOR Flash ******************************************************************************/ #if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE) static struct resource palmtc_flash_resource = { .start = PXA_CS0_PHYS, .end = PXA_CS0_PHYS + SZ_16M - 1, .flags = IORESOURCE_MEM, }; static struct mtd_partition palmtc_flash_parts[] = { { .name = "U-Boot Bootloader", .offset = 0x0, .size = 0x40000, }, { .name = "Linux Kernel", .offset = 0x40000, .size = 0x2c0000, }, { .name = "Filesystem", .offset = 0x300000, .size = 0xcc0000, }, { .name = "U-Boot Environment", .offset = 0xfc0000, .size = MTDPART_SIZ_FULL, }, }; static struct physmap_flash_data palmtc_flash_data = { .width = 4, .parts = palmtc_flash_parts, .nr_parts = ARRAY_SIZE(palmtc_flash_parts), }; static struct platform_device palmtc_flash = { .name = "physmap-flash", .id = -1, .resource = &palmtc_flash_resource, .num_resources = 1, .dev = { .platform_data = &palmtc_flash_data, }, }; static void __init palmtc_nor_init(void) { platform_device_register(&palmtc_flash); } #else static inline void palmtc_nor_init(void) {} #endif /****************************************************************************** * Framebuffer ******************************************************************************/ #if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE) static struct pxafb_mode_info palmtc_lcd_modes[] = { { .pixclock = 115384, .xres = 320, .yres = 320, .bpp = 16, .left_margin = 27, .right_margin = 7, .upper_margin = 7, .lower_margin = 8, .hsync_len = 6, .vsync_len = 1, }, }; static struct pxafb_mach_info palmtc_lcd_screen = { .modes = palmtc_lcd_modes, .num_modes = ARRAY_SIZE(palmtc_lcd_modes), .lcd_conn = LCD_COLOR_TFT_16BPP | LCD_PCLK_EDGE_FALL, }; static void __init palmtc_lcd_init(void) { pxa_set_fb_info(NULL, &palmtc_lcd_screen); } #else static inline void palmtc_lcd_init(void) {} #endif /****************************************************************************** * Machine init ******************************************************************************/ static void __init palmtc_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(palmtc_pin_config)); pxa_set_ffuart_info(NULL); pxa_set_btuart_info(NULL); pxa_set_stuart_info(NULL); pxa_set_hwuart_info(NULL); palmtc_mmc_init(); palmtc_keys_init(); palmtc_pwm_init(); palmtc_irda_init(); palmtc_mkp_init(); palmtc_udc_init(); palmtc_ts_init(); palmtc_nor_init(); palmtc_lcd_init(); palmtc_leds_init(); }; MACHINE_START(PALMTC, "Palm Tungsten|C") .atag_offset = 0x100, .map_io = pxa25x_map_io, .nr_irqs = PXA_NR_IRQS, .init_irq = pxa25x_init_irq, .handle_irq = pxa25x_handle_irq, .timer = &pxa_timer, .init_machine = palmtc_init, .restart = pxa_restart, MACHINE_END
gpl-2.0
HackerOO7/android_kernel_huawei_u8951
arch/arm/mach-pxa/saar.c
4863
13270
/* * linux/arch/arm/mach-pxa/saar.c * * Support for the Marvell PXA930 Handheld Platform (aka SAAR) * * Copyright (C) 2007-2008 Marvell International Ltd. * * 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 * publishhed by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/i2c.h> #include <linux/i2c/pxa-i2c.h> #include <linux/smc91x.h> #include <linux/mfd/da903x.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <linux/mtd/onenand.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/flash.h> #include <mach/pxa930.h> #include <mach/pxafb.h> #include "devices.h" #include "generic.h" #define GPIO_LCD_RESET (16) /* SAAR MFP configurations */ static mfp_cfg_t saar_mfp_cfg[] __initdata = { /* LCD */ GPIO23_LCD_DD0, GPIO24_LCD_DD1, GPIO25_LCD_DD2, GPIO26_LCD_DD3, GPIO27_LCD_DD4, GPIO28_LCD_DD5, GPIO29_LCD_DD6, GPIO44_LCD_DD7, GPIO21_LCD_CS, GPIO22_LCD_VSYNC, GPIO17_LCD_FCLK_RD, GPIO18_LCD_LCLK_A0, GPIO19_LCD_PCLK_WR, GPIO16_GPIO, /* LCD reset */ /* Ethernet */ DF_nCS1_nCS3, GPIO97_GPIO, /* DFI */ DF_INT_RnB_ND_INT_RnB, DF_nRE_nOE_ND_nRE, DF_nWE_ND_nWE, DF_CLE_nOE_ND_CLE, DF_nADV1_ALE_ND_ALE, DF_nADV2_ALE_nCS3, DF_nCS0_ND_nCS0, DF_IO0_ND_IO0, DF_IO1_ND_IO1, DF_IO2_ND_IO2, DF_IO3_ND_IO3, DF_IO4_ND_IO4, DF_IO5_ND_IO5, DF_IO6_ND_IO6, DF_IO7_ND_IO7, DF_IO8_ND_IO8, DF_IO9_ND_IO9, DF_IO10_ND_IO10, DF_IO11_ND_IO11, DF_IO12_ND_IO12, DF_IO13_ND_IO13, DF_IO14_ND_IO14, DF_IO15_ND_IO15, }; #define SAAR_ETH_PHYS (0x14000000) static struct resource smc91x_resources[] = { [0] = { .start = (SAAR_ETH_PHYS + 0x300), .end = (SAAR_ETH_PHYS + 0xfffff), .flags = IORESOURCE_MEM, }, [1] = { .start = PXA_GPIO_TO_IRQ(mfp_to_gpio(MFP_PIN_GPIO97)), .end = PXA_GPIO_TO_IRQ(mfp_to_gpio(MFP_PIN_GPIO97)), .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE, } }; static struct smc91x_platdata saar_smc91x_info = { .flags = SMC91X_USE_16BIT | SMC91X_NOWAIT | SMC91X_USE_DMA, }; static struct platform_device smc91x_device = { .name = "smc91x", .id = 0, .num_resources = ARRAY_SIZE(smc91x_resources), .resource = smc91x_resources, .dev = { .platform_data = &saar_smc91x_info, }, }; #if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE) static uint16_t lcd_power_on[] = { /* single frame */ SMART_CMD_NOOP, SMART_CMD(0x00), SMART_DELAY(0), SMART_CMD_NOOP, SMART_CMD(0x00), SMART_DELAY(0), SMART_CMD_NOOP, SMART_CMD(0x00), SMART_DELAY(0), SMART_CMD_NOOP, SMART_CMD(0x00), SMART_DELAY(10), /* calibration control */ SMART_CMD(0x00), SMART_CMD(0xA4), SMART_DAT(0x80), SMART_DAT(0x01), SMART_DELAY(150), /*Power-On Init sequence*/ SMART_CMD(0x00), /* output ctrl */ SMART_CMD(0x01), SMART_DAT(0x01), SMART_DAT(0x00), SMART_CMD(0x00), /* wave ctrl */ SMART_CMD(0x02), SMART_DAT(0x07), SMART_DAT(0x00), SMART_CMD(0x00), SMART_CMD(0x03), /* entry mode */ SMART_DAT(0xD0), SMART_DAT(0x30), SMART_CMD(0x00), SMART_CMD(0x08), /* display ctrl 2 */ SMART_DAT(0x08), SMART_DAT(0x08), SMART_CMD(0x00), SMART_CMD(0x09), /* display ctrl 3 */ SMART_DAT(0x04), SMART_DAT(0x2F), SMART_CMD(0x00), SMART_CMD(0x0A), /* display ctrl 4 */ SMART_DAT(0x00), SMART_DAT(0x08), SMART_CMD(0x00), SMART_CMD(0x0D), /* Frame Marker position */ SMART_DAT(0x00), SMART_DAT(0x08), SMART_CMD(0x00), SMART_CMD(0x60), /* Driver output control */ SMART_DAT(0x27), SMART_DAT(0x00), SMART_CMD(0x00), SMART_CMD(0x61), /* Base image display control */ SMART_DAT(0x00), SMART_DAT(0x01), SMART_CMD(0x00), SMART_CMD(0x30), /* Y settings 30h-3Dh */ SMART_DAT(0x07), SMART_DAT(0x07), SMART_CMD(0x00), SMART_CMD(0x31), SMART_DAT(0x00), SMART_DAT(0x07), SMART_CMD(0x00), SMART_CMD(0x32), /* Timing(3), ASW HOLD=0.5CLK */ SMART_DAT(0x04), SMART_DAT(0x00), SMART_CMD(0x00), SMART_CMD(0x33), /* Timing(4), CKV ST=0CLK, CKV ED=1CLK */ SMART_DAT(0x03), SMART_DAT(0x03), SMART_CMD(0x00), SMART_CMD(0x34), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), SMART_CMD(0x35), SMART_DAT(0x02), SMART_DAT(0x05), SMART_CMD(0x00), SMART_CMD(0x36), SMART_DAT(0x1F), SMART_DAT(0x1F), SMART_CMD(0x00), SMART_CMD(0x37), SMART_DAT(0x07), SMART_DAT(0x07), SMART_CMD(0x00), SMART_CMD(0x38), SMART_DAT(0x00), SMART_DAT(0x07), SMART_CMD(0x00), SMART_CMD(0x39), SMART_DAT(0x04), SMART_DAT(0x00), SMART_CMD(0x00), SMART_CMD(0x3A), SMART_DAT(0x03), SMART_DAT(0x03), SMART_CMD(0x00), SMART_CMD(0x3B), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), SMART_CMD(0x3C), SMART_DAT(0x02), SMART_DAT(0x05), SMART_CMD(0x00), SMART_CMD(0x3D), SMART_DAT(0x1F), SMART_DAT(0x1F), SMART_CMD(0x00), /* Display control 1 */ SMART_CMD(0x07), SMART_DAT(0x00), SMART_DAT(0x01), SMART_CMD(0x00), /* Power control 5 */ SMART_CMD(0x17), SMART_DAT(0x00), SMART_DAT(0x01), SMART_CMD(0x00), /* Power control 1 */ SMART_CMD(0x10), SMART_DAT(0x10), SMART_DAT(0xB0), SMART_CMD(0x00), /* Power control 2 */ SMART_CMD(0x11), SMART_DAT(0x01), SMART_DAT(0x30), SMART_CMD(0x00), /* Power control 3 */ SMART_CMD(0x12), SMART_DAT(0x01), SMART_DAT(0x9E), SMART_CMD(0x00), /* Power control 4 */ SMART_CMD(0x13), SMART_DAT(0x17), SMART_DAT(0x00), SMART_CMD(0x00), /* Power control 3 */ SMART_CMD(0x12), SMART_DAT(0x01), SMART_DAT(0xBE), SMART_DELAY(100), /* display mode : 240*320 */ SMART_CMD(0x00), /* RAM address set(H) 0*/ SMART_CMD(0x20), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* RAM address set(V) 4*/ SMART_CMD(0x21), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* Start of Window RAM address set(H) 8*/ SMART_CMD(0x50), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* End of Window RAM address set(H) 12*/ SMART_CMD(0x51), SMART_DAT(0x00), SMART_DAT(0xEF), SMART_CMD(0x00), /* Start of Window RAM address set(V) 16*/ SMART_CMD(0x52), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* End of Window RAM address set(V) 20*/ SMART_CMD(0x53), SMART_DAT(0x01), SMART_DAT(0x3F), SMART_CMD(0x00), /* Panel interface control 1 */ SMART_CMD(0x90), SMART_DAT(0x00), SMART_DAT(0x1A), SMART_CMD(0x00), /* Panel interface control 2 */ SMART_CMD(0x92), SMART_DAT(0x04), SMART_DAT(0x00), SMART_CMD(0x00), /* Panel interface control 3 */ SMART_CMD(0x93), SMART_DAT(0x00), SMART_DAT(0x05), SMART_DELAY(20), }; static uint16_t lcd_panel_on[] = { SMART_CMD(0x00), SMART_CMD(0x07), SMART_DAT(0x00), SMART_DAT(0x21), SMART_DELAY(1), SMART_CMD(0x00), SMART_CMD(0x07), SMART_DAT(0x00), SMART_DAT(0x61), SMART_DELAY(100), SMART_CMD(0x00), SMART_CMD(0x07), SMART_DAT(0x01), SMART_DAT(0x73), SMART_DELAY(1), }; static uint16_t lcd_panel_off[] = { SMART_CMD(0x00), SMART_CMD(0x07), SMART_DAT(0x00), SMART_DAT(0x72), SMART_DELAY(40), SMART_CMD(0x00), SMART_CMD(0x07), SMART_DAT(0x00), SMART_DAT(0x01), SMART_DELAY(1), SMART_CMD(0x00), SMART_CMD(0x07), SMART_DAT(0x00), SMART_DAT(0x00), SMART_DELAY(1), }; static uint16_t lcd_power_off[] = { SMART_CMD(0x00), SMART_CMD(0x10), SMART_DAT(0x00), SMART_DAT(0x80), SMART_CMD(0x00), SMART_CMD(0x11), SMART_DAT(0x01), SMART_DAT(0x60), SMART_CMD(0x00), SMART_CMD(0x12), SMART_DAT(0x01), SMART_DAT(0xAE), SMART_DELAY(40), SMART_CMD(0x00), SMART_CMD(0x10), SMART_DAT(0x00), SMART_DAT(0x00), }; static uint16_t update_framedata[] = { /* set display ram: 240*320 */ SMART_CMD(0x00), /* RAM address set(H) 0*/ SMART_CMD(0x20), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* RAM address set(V) 4*/ SMART_CMD(0x21), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* Start of Window RAM address set(H) 8 */ SMART_CMD(0x50), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* End of Window RAM address set(H) 12 */ SMART_CMD(0x51), SMART_DAT(0x00), SMART_DAT(0xEF), SMART_CMD(0x00), /* Start of Window RAM address set(V) 16 */ SMART_CMD(0x52), SMART_DAT(0x00), SMART_DAT(0x00), SMART_CMD(0x00), /* End of Window RAM address set(V) 20 */ SMART_CMD(0x53), SMART_DAT(0x01), SMART_DAT(0x3F), /* wait for vsync cmd before transferring frame data */ SMART_CMD_WAIT_FOR_VSYNC, /* write ram */ SMART_CMD(0x00), SMART_CMD(0x22), /* write frame data */ SMART_CMD_WRITE_FRAME, }; static void ltm022a97a_lcd_power(int on, struct fb_var_screeninfo *var) { static int pin_requested = 0; struct fb_info *info = container_of(var, struct fb_info, var); int err; if (!pin_requested) { err = gpio_request(GPIO_LCD_RESET, "lcd reset"); if (err) { pr_err("failed to request gpio for LCD reset\n"); return; } gpio_direction_output(GPIO_LCD_RESET, 0); pin_requested = 1; } if (on) { gpio_set_value(GPIO_LCD_RESET, 0); msleep(100); gpio_set_value(GPIO_LCD_RESET, 1); msleep(10); pxafb_smart_queue(info, ARRAY_AND_SIZE(lcd_power_on)); pxafb_smart_queue(info, ARRAY_AND_SIZE(lcd_panel_on)); } else { pxafb_smart_queue(info, ARRAY_AND_SIZE(lcd_panel_off)); pxafb_smart_queue(info, ARRAY_AND_SIZE(lcd_power_off)); } err = pxafb_smart_flush(info); if (err) pr_err("%s: timed out\n", __func__); } static void ltm022a97a_update(struct fb_info *info) { pxafb_smart_queue(info, ARRAY_AND_SIZE(update_framedata)); pxafb_smart_flush(info); } static struct pxafb_mode_info toshiba_ltm022a97a_modes[] = { [0] = { .xres = 240, .yres = 320, .bpp = 16, .a0csrd_set_hld = 30, .a0cswr_set_hld = 30, .wr_pulse_width = 30, .rd_pulse_width = 30, .op_hold_time = 30, .cmd_inh_time = 60, /* L_LCLK_A0 and L_LCLK_RD active low */ .sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, }, }; static struct pxafb_mach_info saar_lcd_info = { .modes = toshiba_ltm022a97a_modes, .num_modes = 1, .lcd_conn = LCD_SMART_PANEL_8BPP | LCD_PCLK_EDGE_FALL, .pxafb_lcd_power = ltm022a97a_lcd_power, .smart_update = ltm022a97a_update, }; static void __init saar_init_lcd(void) { pxa_set_fb_info(NULL, &saar_lcd_info); } #else static inline void saar_init_lcd(void) {} #endif #if defined(CONFIG_I2C_PXA) || defined(CONFIG_I2C_PXA_MODULE) static struct da9034_backlight_pdata saar_da9034_backlight = { .output_current = 4, /* 4mA */ }; static struct da903x_subdev_info saar_da9034_subdevs[] = { [0] = { .name = "da903x-backlight", .id = DA9034_ID_WLED, .platform_data = &saar_da9034_backlight, }, }; static struct da903x_platform_data saar_da9034_info = { .num_subdevs = ARRAY_SIZE(saar_da9034_subdevs), .subdevs = saar_da9034_subdevs, }; static struct i2c_board_info saar_i2c_info[] = { [0] = { .type = "da9034", .addr = 0x34, .platform_data = &saar_da9034_info, .irq = PXA_GPIO_TO_IRQ(mfp_to_gpio(MFP_PIN_GPIO83)), }, }; static void __init saar_init_i2c(void) { pxa_set_i2c_info(NULL); i2c_register_board_info(0, ARRAY_AND_SIZE(saar_i2c_info)); } #else static inline void saar_init_i2c(void) {} #endif #if defined(CONFIG_MTD_ONENAND) || defined(CONFIG_MTD_ONENAND_MODULE) static struct mtd_partition saar_onenand_partitions[] = { { .name = "bootloader", .offset = 0, .size = SZ_1M, .mask_flags = MTD_WRITEABLE, }, { .name = "reserved", .offset = MTDPART_OFS_APPEND, .size = SZ_128K, .mask_flags = MTD_WRITEABLE, }, { .name = "reserved", .offset = MTDPART_OFS_APPEND, .size = SZ_8M, .mask_flags = MTD_WRITEABLE, }, { .name = "kernel", .offset = MTDPART_OFS_APPEND, .size = (SZ_2M + SZ_1M), .mask_flags = 0, }, { .name = "filesystem", .offset = MTDPART_OFS_APPEND, .size = SZ_32M + SZ_16M, .mask_flags = 0, } }; static struct onenand_platform_data saar_onenand_info = { .parts = saar_onenand_partitions, .nr_parts = ARRAY_SIZE(saar_onenand_partitions), }; #define SMC_CS0_PHYS_BASE (0x10000000) static struct resource saar_resource_onenand[] = { [0] = { .start = SMC_CS0_PHYS_BASE, .end = SMC_CS0_PHYS_BASE + SZ_1M, .flags = IORESOURCE_MEM, }, }; static struct platform_device saar_device_onenand = { .name = "onenand-flash", .id = -1, .dev = { .platform_data = &saar_onenand_info, }, .resource = saar_resource_onenand, .num_resources = ARRAY_SIZE(saar_resource_onenand), }; static void __init saar_init_onenand(void) { platform_device_register(&saar_device_onenand); } #else static void __init saar_init_onenand(void) {} #endif static void __init saar_init(void) { /* initialize MFP configurations */ pxa3xx_mfp_config(ARRAY_AND_SIZE(saar_mfp_cfg)); pxa_set_ffuart_info(NULL); pxa_set_btuart_info(NULL); pxa_set_stuart_info(NULL); platform_device_register(&smc91x_device); saar_init_onenand(); saar_init_i2c(); saar_init_lcd(); } MACHINE_START(SAAR, "PXA930 Handheld Platform (aka SAAR)") /* Maintainer: Eric Miao <eric.miao@marvell.com> */ .atag_offset = 0x100, .map_io = pxa3xx_map_io, .nr_irqs = PXA_NR_IRQS, .init_irq = pxa3xx_init_irq, .handle_irq = pxa3xx_handle_irq, .timer = &pxa_timer, .init_machine = saar_init, .restart = pxa_restart, MACHINE_END
gpl-2.0
drowningchild/dc-geebus
drivers/net/hamradio/baycom_epp.c
5119
34930
/*****************************************************************************/ /* * baycom_epp.c -- baycom epp radio modem driver. * * Copyright (C) 1998-2000 * Thomas Sailer (sailer@ife.ee.ethz.ch) * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * Please note that the GPL allows you to use the driver, NOT the radio. * In order to use the radio, you need a license from the communications * authority of your country. * * * History: * 0.1 xx.xx.1998 Initial version by Matthias Welwarsky (dg2fef) * 0.2 21.04.1998 Massive rework by Thomas Sailer * Integrated FPGA EPP modem configuration routines * 0.3 11.05.1998 Took FPGA config out and moved it into a separate program * 0.4 26.07.1999 Adapted to new lowlevel parport driver interface * 0.5 03.08.1999 adapt to Linus' new __setup/__initcall * removed some pre-2.2 kernel compatibility cruft * 0.6 10.08.1999 Check if parport can do SPP and is safe to access during interrupt contexts * 0.7 12.02.2000 adapted to softnet driver interface * */ /*****************************************************************************/ #include <linux/crc-ccitt.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/workqueue.h> #include <linux/fs.h> #include <linux/parport.h> #include <linux/if_arp.h> #include <linux/hdlcdrv.h> #include <linux/baycom.h> #include <linux/jiffies.h> #include <linux/random.h> #include <net/ax25.h> #include <asm/uaccess.h> /* --------------------------------------------------------------------- */ #define BAYCOM_DEBUG #define BAYCOM_MAGIC 19730510 /* --------------------------------------------------------------------- */ static const char paranoia_str[] = KERN_ERR "baycom_epp: bad magic number for hdlcdrv_state struct in routine %s\n"; static const char bc_drvname[] = "baycom_epp"; static const char bc_drvinfo[] = KERN_INFO "baycom_epp: (C) 1998-2000 Thomas Sailer, HB9JNX/AE4WA\n" "baycom_epp: version 0.7\n"; /* --------------------------------------------------------------------- */ #define NR_PORTS 4 static struct net_device *baycom_device[NR_PORTS]; /* --------------------------------------------------------------------- */ /* EPP status register */ #define EPP_DCDBIT 0x80 #define EPP_PTTBIT 0x08 #define EPP_NREF 0x01 #define EPP_NRAEF 0x02 #define EPP_NRHF 0x04 #define EPP_NTHF 0x20 #define EPP_NTAEF 0x10 #define EPP_NTEF EPP_PTTBIT /* EPP control register */ #define EPP_TX_FIFO_ENABLE 0x10 #define EPP_RX_FIFO_ENABLE 0x08 #define EPP_MODEM_ENABLE 0x20 #define EPP_LEDS 0xC0 #define EPP_IRQ_ENABLE 0x10 /* LPT registers */ #define LPTREG_ECONTROL 0x402 #define LPTREG_CONFIGB 0x401 #define LPTREG_CONFIGA 0x400 #define LPTREG_EPPDATA 0x004 #define LPTREG_EPPADDR 0x003 #define LPTREG_CONTROL 0x002 #define LPTREG_STATUS 0x001 #define LPTREG_DATA 0x000 /* LPT control register */ #define LPTCTRL_PROGRAM 0x04 /* 0 to reprogram */ #define LPTCTRL_WRITE 0x01 #define LPTCTRL_ADDRSTB 0x08 #define LPTCTRL_DATASTB 0x02 #define LPTCTRL_INTEN 0x10 /* LPT status register */ #define LPTSTAT_SHIFT_NINTR 6 #define LPTSTAT_WAIT 0x80 #define LPTSTAT_NINTR (1<<LPTSTAT_SHIFT_NINTR) #define LPTSTAT_PE 0x20 #define LPTSTAT_DONE 0x10 #define LPTSTAT_NERROR 0x08 #define LPTSTAT_EPPTIMEOUT 0x01 /* LPT data register */ #define LPTDATA_SHIFT_TDI 0 #define LPTDATA_SHIFT_TMS 2 #define LPTDATA_TDI (1<<LPTDATA_SHIFT_TDI) #define LPTDATA_TCK 0x02 #define LPTDATA_TMS (1<<LPTDATA_SHIFT_TMS) #define LPTDATA_INITBIAS 0x80 /* EPP modem config/status bits */ #define EPP_DCDBIT 0x80 #define EPP_PTTBIT 0x08 #define EPP_RXEBIT 0x01 #define EPP_RXAEBIT 0x02 #define EPP_RXHFULL 0x04 #define EPP_NTHF 0x20 #define EPP_NTAEF 0x10 #define EPP_NTEF EPP_PTTBIT #define EPP_TX_FIFO_ENABLE 0x10 #define EPP_RX_FIFO_ENABLE 0x08 #define EPP_MODEM_ENABLE 0x20 #define EPP_LEDS 0xC0 #define EPP_IRQ_ENABLE 0x10 /* Xilinx 4k JTAG instructions */ #define XC4K_IRLENGTH 3 #define XC4K_EXTEST 0 #define XC4K_PRELOAD 1 #define XC4K_CONFIGURE 5 #define XC4K_BYPASS 7 #define EPP_CONVENTIONAL 0 #define EPP_FPGA 1 #define EPP_FPGAEXTSTATUS 2 #define TXBUFFER_SIZE ((HDLCDRV_MAXFLEN*6/5)+8) /* ---------------------------------------------------------------------- */ /* * Information that need to be kept for each board. */ struct baycom_state { int magic; struct pardevice *pdev; struct net_device *dev; unsigned int work_running; struct delayed_work run_work; unsigned int modem; unsigned int bitrate; unsigned char stat; struct { unsigned int intclk; unsigned int fclk; unsigned int bps; unsigned int extmodem; unsigned int loopback; } cfg; struct hdlcdrv_channel_params ch_params; struct { unsigned int bitbuf, bitstream, numbits, state; unsigned char *bufptr; int bufcnt; unsigned char buf[TXBUFFER_SIZE]; } hdlcrx; struct { int calibrate; int slotcnt; int flags; enum { tx_idle = 0, tx_keyup, tx_data, tx_tail } state; unsigned char *bufptr; int bufcnt; unsigned char buf[TXBUFFER_SIZE]; } hdlctx; unsigned int ptt_keyed; struct sk_buff *skb; /* next transmit packet */ #ifdef BAYCOM_DEBUG struct debug_vals { unsigned long last_jiffies; unsigned cur_intcnt; unsigned last_intcnt; int cur_pllcorr; int last_pllcorr; unsigned int mod_cycles; unsigned int demod_cycles; } debug_vals; #endif /* BAYCOM_DEBUG */ }; /* --------------------------------------------------------------------- */ #define KISS_VERBOSE /* --------------------------------------------------------------------- */ #define PARAM_TXDELAY 1 #define PARAM_PERSIST 2 #define PARAM_SLOTTIME 3 #define PARAM_TXTAIL 4 #define PARAM_FULLDUP 5 #define PARAM_HARDWARE 6 #define PARAM_RETURN 255 /* --------------------------------------------------------------------- */ /* * the CRC routines are stolen from WAMPES * by Dieter Deyke */ /*---------------------------------------------------------------------------*/ #if 0 static inline void append_crc_ccitt(unsigned char *buffer, int len) { unsigned int crc = 0xffff; for (;len>0;len--) crc = (crc >> 8) ^ crc_ccitt_table[(crc ^ *buffer++) & 0xff]; crc ^= 0xffff; *buffer++ = crc; *buffer++ = crc >> 8; } #endif /*---------------------------------------------------------------------------*/ static inline int check_crc_ccitt(const unsigned char *buf, int cnt) { return (crc_ccitt(0xffff, buf, cnt) & 0xffff) == 0xf0b8; } /*---------------------------------------------------------------------------*/ static inline int calc_crc_ccitt(const unsigned char *buf, int cnt) { return (crc_ccitt(0xffff, buf, cnt) ^ 0xffff) & 0xffff; } /* ---------------------------------------------------------------------- */ #define tenms_to_flags(bc,tenms) ((tenms * bc->bitrate) / 800) /* --------------------------------------------------------------------- */ static inline void baycom_int_freq(struct baycom_state *bc) { #ifdef BAYCOM_DEBUG unsigned long cur_jiffies = jiffies; /* * measure the interrupt frequency */ bc->debug_vals.cur_intcnt++; if (time_after_eq(cur_jiffies, bc->debug_vals.last_jiffies + HZ)) { bc->debug_vals.last_jiffies = cur_jiffies; bc->debug_vals.last_intcnt = bc->debug_vals.cur_intcnt; bc->debug_vals.cur_intcnt = 0; bc->debug_vals.last_pllcorr = bc->debug_vals.cur_pllcorr; bc->debug_vals.cur_pllcorr = 0; } #endif /* BAYCOM_DEBUG */ } /* ---------------------------------------------------------------------- */ /* * eppconfig_path should be setable via /proc/sys. */ static char eppconfig_path[256] = "/usr/sbin/eppfpga"; static char *envp[] = { "HOME=/", "TERM=linux", "PATH=/usr/bin:/bin", NULL }; /* eppconfig: called during ifconfig up to configure the modem */ static int eppconfig(struct baycom_state *bc) { char modearg[256]; char portarg[16]; char *argv[] = { eppconfig_path, "-s", "-p", portarg, "-m", modearg, NULL }; /* set up arguments */ sprintf(modearg, "%sclk,%smodem,fclk=%d,bps=%d,divider=%d%s,extstat", bc->cfg.intclk ? "int" : "ext", bc->cfg.extmodem ? "ext" : "int", bc->cfg.fclk, bc->cfg.bps, (bc->cfg.fclk + 8 * bc->cfg.bps) / (16 * bc->cfg.bps), bc->cfg.loopback ? ",loopback" : ""); sprintf(portarg, "%ld", bc->pdev->port->base); printk(KERN_DEBUG "%s: %s -s -p %s -m %s\n", bc_drvname, eppconfig_path, portarg, modearg); return call_usermodehelper(eppconfig_path, argv, envp, UMH_WAIT_PROC); } /* ---------------------------------------------------------------------- */ static inline void do_kiss_params(struct baycom_state *bc, unsigned char *data, unsigned long len) { #ifdef KISS_VERBOSE #define PKP(a,b) printk(KERN_INFO "baycomm_epp: channel params: " a "\n", b) #else /* KISS_VERBOSE */ #define PKP(a,b) #endif /* KISS_VERBOSE */ if (len < 2) return; switch(data[0]) { case PARAM_TXDELAY: bc->ch_params.tx_delay = data[1]; PKP("TX delay = %ums", 10 * bc->ch_params.tx_delay); break; case PARAM_PERSIST: bc->ch_params.ppersist = data[1]; PKP("p persistence = %u", bc->ch_params.ppersist); break; case PARAM_SLOTTIME: bc->ch_params.slottime = data[1]; PKP("slot time = %ums", bc->ch_params.slottime); break; case PARAM_TXTAIL: bc->ch_params.tx_tail = data[1]; PKP("TX tail = %ums", bc->ch_params.tx_tail); break; case PARAM_FULLDUP: bc->ch_params.fulldup = !!data[1]; PKP("%s duplex", bc->ch_params.fulldup ? "full" : "half"); break; default: break; } #undef PKP } /* --------------------------------------------------------------------- */ static void encode_hdlc(struct baycom_state *bc) { struct sk_buff *skb; unsigned char *wp, *bp; int pkt_len; unsigned bitstream, notbitstream, bitbuf, numbit, crc; unsigned char crcarr[2]; int j; if (bc->hdlctx.bufcnt > 0) return; skb = bc->skb; if (!skb) return; bc->skb = NULL; pkt_len = skb->len-1; /* strip KISS byte */ wp = bc->hdlctx.buf; bp = skb->data+1; crc = calc_crc_ccitt(bp, pkt_len); crcarr[0] = crc; crcarr[1] = crc >> 8; *wp++ = 0x7e; bitstream = bitbuf = numbit = 0; while (pkt_len > -2) { bitstream >>= 8; bitstream |= ((unsigned int)*bp) << 8; bitbuf |= ((unsigned int)*bp) << numbit; notbitstream = ~bitstream; bp++; pkt_len--; if (!pkt_len) bp = crcarr; for (j = 0; j < 8; j++) if (unlikely(!(notbitstream & (0x1f0 << j)))) { bitstream &= ~(0x100 << j); bitbuf = (bitbuf & (((2 << j) << numbit) - 1)) | ((bitbuf & ~(((2 << j) << numbit) - 1)) << 1); numbit++; notbitstream = ~bitstream; } numbit += 8; while (numbit >= 8) { *wp++ = bitbuf; bitbuf >>= 8; numbit -= 8; } } bitbuf |= 0x7e7e << numbit; numbit += 16; while (numbit >= 8) { *wp++ = bitbuf; bitbuf >>= 8; numbit -= 8; } bc->hdlctx.bufptr = bc->hdlctx.buf; bc->hdlctx.bufcnt = wp - bc->hdlctx.buf; dev_kfree_skb(skb); bc->dev->stats.tx_packets++; } /* ---------------------------------------------------------------------- */ static int transmit(struct baycom_state *bc, int cnt, unsigned char stat) { struct parport *pp = bc->pdev->port; unsigned char tmp[128]; int i, j; if (bc->hdlctx.state == tx_tail && !(stat & EPP_PTTBIT)) bc->hdlctx.state = tx_idle; if (bc->hdlctx.state == tx_idle && bc->hdlctx.calibrate <= 0) { if (bc->hdlctx.bufcnt <= 0) encode_hdlc(bc); if (bc->hdlctx.bufcnt <= 0) return 0; if (!bc->ch_params.fulldup) { if (!(stat & EPP_DCDBIT)) { bc->hdlctx.slotcnt = bc->ch_params.slottime; return 0; } if ((--bc->hdlctx.slotcnt) > 0) return 0; bc->hdlctx.slotcnt = bc->ch_params.slottime; if ((random32() % 256) > bc->ch_params.ppersist) return 0; } } if (bc->hdlctx.state == tx_idle && bc->hdlctx.bufcnt > 0) { bc->hdlctx.state = tx_keyup; bc->hdlctx.flags = tenms_to_flags(bc, bc->ch_params.tx_delay); bc->ptt_keyed++; } while (cnt > 0) { switch (bc->hdlctx.state) { case tx_keyup: i = min_t(int, cnt, bc->hdlctx.flags); cnt -= i; bc->hdlctx.flags -= i; if (bc->hdlctx.flags <= 0) bc->hdlctx.state = tx_data; memset(tmp, 0x7e, sizeof(tmp)); while (i > 0) { j = (i > sizeof(tmp)) ? sizeof(tmp) : i; if (j != pp->ops->epp_write_data(pp, tmp, j, 0)) return -1; i -= j; } break; case tx_data: if (bc->hdlctx.bufcnt <= 0) { encode_hdlc(bc); if (bc->hdlctx.bufcnt <= 0) { bc->hdlctx.state = tx_tail; bc->hdlctx.flags = tenms_to_flags(bc, bc->ch_params.tx_tail); break; } } i = min_t(int, cnt, bc->hdlctx.bufcnt); bc->hdlctx.bufcnt -= i; cnt -= i; if (i != pp->ops->epp_write_data(pp, bc->hdlctx.bufptr, i, 0)) return -1; bc->hdlctx.bufptr += i; break; case tx_tail: encode_hdlc(bc); if (bc->hdlctx.bufcnt > 0) { bc->hdlctx.state = tx_data; break; } i = min_t(int, cnt, bc->hdlctx.flags); if (i) { cnt -= i; bc->hdlctx.flags -= i; memset(tmp, 0x7e, sizeof(tmp)); while (i > 0) { j = (i > sizeof(tmp)) ? sizeof(tmp) : i; if (j != pp->ops->epp_write_data(pp, tmp, j, 0)) return -1; i -= j; } break; } default: /* fall through */ if (bc->hdlctx.calibrate <= 0) return 0; i = min_t(int, cnt, bc->hdlctx.calibrate); cnt -= i; bc->hdlctx.calibrate -= i; memset(tmp, 0, sizeof(tmp)); while (i > 0) { j = (i > sizeof(tmp)) ? sizeof(tmp) : i; if (j != pp->ops->epp_write_data(pp, tmp, j, 0)) return -1; i -= j; } break; } } return 0; } /* ---------------------------------------------------------------------- */ static void do_rxpacket(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); struct sk_buff *skb; unsigned char *cp; unsigned pktlen; if (bc->hdlcrx.bufcnt < 4) return; if (!check_crc_ccitt(bc->hdlcrx.buf, bc->hdlcrx.bufcnt)) return; pktlen = bc->hdlcrx.bufcnt-2+1; /* KISS kludge */ if (!(skb = dev_alloc_skb(pktlen))) { printk("%s: memory squeeze, dropping packet\n", dev->name); dev->stats.rx_dropped++; return; } cp = skb_put(skb, pktlen); *cp++ = 0; /* KISS kludge */ memcpy(cp, bc->hdlcrx.buf, pktlen - 1); skb->protocol = ax25_type_trans(skb, dev); netif_rx(skb); dev->stats.rx_packets++; } static int receive(struct net_device *dev, int cnt) { struct baycom_state *bc = netdev_priv(dev); struct parport *pp = bc->pdev->port; unsigned int bitbuf, notbitstream, bitstream, numbits, state; unsigned char tmp[128]; unsigned char *cp; int cnt2, ret = 0; int j; numbits = bc->hdlcrx.numbits; state = bc->hdlcrx.state; bitstream = bc->hdlcrx.bitstream; bitbuf = bc->hdlcrx.bitbuf; while (cnt > 0) { cnt2 = (cnt > sizeof(tmp)) ? sizeof(tmp) : cnt; cnt -= cnt2; if (cnt2 != pp->ops->epp_read_data(pp, tmp, cnt2, 0)) { ret = -1; break; } cp = tmp; for (; cnt2 > 0; cnt2--, cp++) { bitstream >>= 8; bitstream |= (*cp) << 8; bitbuf >>= 8; bitbuf |= (*cp) << 8; numbits += 8; notbitstream = ~bitstream; for (j = 0; j < 8; j++) { /* flag or abort */ if (unlikely(!(notbitstream & (0x0fc << j)))) { /* abort received */ if (!(notbitstream & (0x1fc << j))) state = 0; /* flag received */ else if ((bitstream & (0x1fe << j)) == (0x0fc << j)) { if (state) do_rxpacket(dev); bc->hdlcrx.bufcnt = 0; bc->hdlcrx.bufptr = bc->hdlcrx.buf; state = 1; numbits = 7-j; } } /* stuffed bit */ else if (unlikely((bitstream & (0x1f8 << j)) == (0xf8 << j))) { numbits--; bitbuf = (bitbuf & ((~0xff) << j)) | ((bitbuf & ~((~0xff) << j)) << 1); } } while (state && numbits >= 8) { if (bc->hdlcrx.bufcnt >= TXBUFFER_SIZE) { state = 0; } else { *(bc->hdlcrx.bufptr)++ = bitbuf >> (16-numbits); bc->hdlcrx.bufcnt++; numbits -= 8; } } } } bc->hdlcrx.numbits = numbits; bc->hdlcrx.state = state; bc->hdlcrx.bitstream = bitstream; bc->hdlcrx.bitbuf = bitbuf; return ret; } /* --------------------------------------------------------------------- */ #ifdef __i386__ #include <asm/msr.h> #define GETTICK(x) \ ({ \ if (cpu_has_tsc) \ rdtscl(x); \ }) #else /* __i386__ */ #define GETTICK(x) #endif /* __i386__ */ static void epp_bh(struct work_struct *work) { struct net_device *dev; struct baycom_state *bc; struct parport *pp; unsigned char stat; unsigned char tmp[2]; unsigned int time1 = 0, time2 = 0, time3 = 0; int cnt, cnt2; bc = container_of(work, struct baycom_state, run_work.work); dev = bc->dev; if (!bc->work_running) return; baycom_int_freq(bc); pp = bc->pdev->port; /* update status */ if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; bc->stat = stat; bc->debug_vals.last_pllcorr = stat; GETTICK(time1); if (bc->modem == EPP_FPGAEXTSTATUS) { /* get input count */ tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE|1; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; if (pp->ops->epp_read_addr(pp, tmp, 2, 0) != 2) goto epptimeout; cnt = tmp[0] | (tmp[1] << 8); cnt &= 0x7fff; /* get output count */ tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE|2; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; if (pp->ops->epp_read_addr(pp, tmp, 2, 0) != 2) goto epptimeout; cnt2 = tmp[0] | (tmp[1] << 8); cnt2 = 16384 - (cnt2 & 0x7fff); /* return to normal */ tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; if (transmit(bc, cnt2, stat)) goto epptimeout; GETTICK(time2); if (receive(dev, cnt)) goto epptimeout; if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; bc->stat = stat; } else { /* try to tx */ switch (stat & (EPP_NTAEF|EPP_NTHF)) { case EPP_NTHF: cnt = 2048 - 256; break; case EPP_NTAEF: cnt = 2048 - 1793; break; case 0: cnt = 0; break; default: cnt = 2048 - 1025; break; } if (transmit(bc, cnt, stat)) goto epptimeout; GETTICK(time2); /* do receiver */ while ((stat & (EPP_NRAEF|EPP_NRHF)) != EPP_NRHF) { switch (stat & (EPP_NRAEF|EPP_NRHF)) { case EPP_NRAEF: cnt = 1025; break; case 0: cnt = 1793; break; default: cnt = 256; break; } if (receive(dev, cnt)) goto epptimeout; if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; } cnt = 0; if (bc->bitrate < 50000) cnt = 256; else if (bc->bitrate < 100000) cnt = 128; while (cnt > 0 && stat & EPP_NREF) { if (receive(dev, 1)) goto epptimeout; cnt--; if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; } } GETTICK(time3); #ifdef BAYCOM_DEBUG bc->debug_vals.mod_cycles = time2 - time1; bc->debug_vals.demod_cycles = time3 - time2; #endif /* BAYCOM_DEBUG */ schedule_delayed_work(&bc->run_work, 1); if (!bc->skb) netif_wake_queue(dev); return; epptimeout: printk(KERN_ERR "%s: EPP timeout!\n", bc_drvname); } /* ---------------------------------------------------------------------- */ /* * ===================== network driver interface ========================= */ static int baycom_send_packet(struct sk_buff *skb, struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); if (skb->data[0] != 0) { do_kiss_params(bc, skb->data, skb->len); dev_kfree_skb(skb); return NETDEV_TX_OK; } if (bc->skb) return NETDEV_TX_LOCKED; /* strip KISS byte */ if (skb->len >= HDLCDRV_MAXFLEN+1 || skb->len < 3) { dev_kfree_skb(skb); return NETDEV_TX_OK; } netif_stop_queue(dev); bc->skb = skb; return NETDEV_TX_OK; } /* --------------------------------------------------------------------- */ static int baycom_set_mac_address(struct net_device *dev, void *addr) { struct sockaddr *sa = (struct sockaddr *)addr; /* addr is an AX.25 shifted ASCII mac address */ memcpy(dev->dev_addr, sa->sa_data, dev->addr_len); return 0; } /* --------------------------------------------------------------------- */ static void epp_wakeup(void *handle) { struct net_device *dev = (struct net_device *)handle; struct baycom_state *bc = netdev_priv(dev); printk(KERN_DEBUG "baycom_epp: %s: why am I being woken up?\n", dev->name); if (!parport_claim(bc->pdev)) printk(KERN_DEBUG "baycom_epp: %s: I'm broken.\n", dev->name); } /* --------------------------------------------------------------------- */ /* * Open/initialize the board. This is called (in the current kernel) * sometime after booting when the 'ifconfig' program is run. * * This routine should set everything up anew at each open, even * registers that "should" only need to be set once at boot, so that * there is non-reboot way to recover if something goes wrong. */ static int epp_open(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); struct parport *pp = parport_find_base(dev->base_addr); unsigned int i, j; unsigned char tmp[128]; unsigned char stat; unsigned long tstart; if (!pp) { printk(KERN_ERR "%s: parport at 0x%lx unknown\n", bc_drvname, dev->base_addr); return -ENXIO; } #if 0 if (pp->irq < 0) { printk(KERN_ERR "%s: parport at 0x%lx has no irq\n", bc_drvname, pp->base); parport_put_port(pp); return -ENXIO; } #endif if ((~pp->modes) & (PARPORT_MODE_TRISTATE | PARPORT_MODE_PCSPP | PARPORT_MODE_SAFEININT)) { printk(KERN_ERR "%s: parport at 0x%lx cannot be used\n", bc_drvname, pp->base); parport_put_port(pp); return -EIO; } memset(&bc->modem, 0, sizeof(bc->modem)); bc->pdev = parport_register_device(pp, dev->name, NULL, epp_wakeup, NULL, PARPORT_DEV_EXCL, dev); parport_put_port(pp); if (!bc->pdev) { printk(KERN_ERR "%s: cannot register parport at 0x%lx\n", bc_drvname, pp->base); return -ENXIO; } if (parport_claim(bc->pdev)) { printk(KERN_ERR "%s: parport at 0x%lx busy\n", bc_drvname, pp->base); parport_unregister_device(bc->pdev); return -EBUSY; } dev->irq = /*pp->irq*/ 0; INIT_DELAYED_WORK(&bc->run_work, epp_bh); bc->work_running = 1; bc->modem = EPP_CONVENTIONAL; if (eppconfig(bc)) printk(KERN_INFO "%s: no FPGA detected, assuming conventional EPP modem\n", bc_drvname); else bc->modem = /*EPP_FPGA*/ EPP_FPGAEXTSTATUS; parport_write_control(pp, LPTCTRL_PROGRAM); /* prepare EPP mode; we aren't using interrupts */ /* reset the modem */ tmp[0] = 0; tmp[1] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE; if (pp->ops->epp_write_addr(pp, tmp, 2, 0) != 2) goto epptimeout; /* autoprobe baud rate */ tstart = jiffies; i = 0; while (time_before(jiffies, tstart + HZ/3)) { if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; if ((stat & (EPP_NRAEF|EPP_NRHF)) == EPP_NRHF) { schedule(); continue; } if (pp->ops->epp_read_data(pp, tmp, 128, 0) != 128) goto epptimeout; if (pp->ops->epp_read_data(pp, tmp, 128, 0) != 128) goto epptimeout; i += 256; } for (j = 0; j < 256; j++) { if (pp->ops->epp_read_addr(pp, &stat, 1, 0) != 1) goto epptimeout; if (!(stat & EPP_NREF)) break; if (pp->ops->epp_read_data(pp, tmp, 1, 0) != 1) goto epptimeout; i++; } tstart = jiffies - tstart; bc->bitrate = i * (8 * HZ) / tstart; j = 1; i = bc->bitrate >> 3; while (j < 7 && i > 150) { j++; i >>= 1; } printk(KERN_INFO "%s: autoprobed bitrate: %d int divider: %d int rate: %d\n", bc_drvname, bc->bitrate, j, bc->bitrate >> (j+2)); tmp[0] = EPP_TX_FIFO_ENABLE|EPP_RX_FIFO_ENABLE|EPP_MODEM_ENABLE/*|j*/; if (pp->ops->epp_write_addr(pp, tmp, 1, 0) != 1) goto epptimeout; /* * initialise hdlc variables */ bc->hdlcrx.state = 0; bc->hdlcrx.numbits = 0; bc->hdlctx.state = tx_idle; bc->hdlctx.bufcnt = 0; bc->hdlctx.slotcnt = bc->ch_params.slottime; bc->hdlctx.calibrate = 0; /* start the bottom half stuff */ schedule_delayed_work(&bc->run_work, 1); netif_start_queue(dev); return 0; epptimeout: printk(KERN_ERR "%s: epp timeout during bitrate probe\n", bc_drvname); parport_write_control(pp, 0); /* reset the adapter */ parport_release(bc->pdev); parport_unregister_device(bc->pdev); return -EIO; } /* --------------------------------------------------------------------- */ static int epp_close(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); struct parport *pp = bc->pdev->port; unsigned char tmp[1]; bc->work_running = 0; cancel_delayed_work_sync(&bc->run_work); bc->stat = EPP_DCDBIT; tmp[0] = 0; pp->ops->epp_write_addr(pp, tmp, 1, 0); parport_write_control(pp, 0); /* reset the adapter */ parport_release(bc->pdev); parport_unregister_device(bc->pdev); if (bc->skb) dev_kfree_skb(bc->skb); bc->skb = NULL; printk(KERN_INFO "%s: close epp at iobase 0x%lx irq %u\n", bc_drvname, dev->base_addr, dev->irq); return 0; } /* --------------------------------------------------------------------- */ static int baycom_setmode(struct baycom_state *bc, const char *modestr) { const char *cp; if (strstr(modestr,"intclk")) bc->cfg.intclk = 1; if (strstr(modestr,"extclk")) bc->cfg.intclk = 0; if (strstr(modestr,"intmodem")) bc->cfg.extmodem = 0; if (strstr(modestr,"extmodem")) bc->cfg.extmodem = 1; if (strstr(modestr,"noloopback")) bc->cfg.loopback = 0; if (strstr(modestr,"loopback")) bc->cfg.loopback = 1; if ((cp = strstr(modestr,"fclk="))) { bc->cfg.fclk = simple_strtoul(cp+5, NULL, 0); if (bc->cfg.fclk < 1000000) bc->cfg.fclk = 1000000; if (bc->cfg.fclk > 25000000) bc->cfg.fclk = 25000000; } if ((cp = strstr(modestr,"bps="))) { bc->cfg.bps = simple_strtoul(cp+4, NULL, 0); if (bc->cfg.bps < 1000) bc->cfg.bps = 1000; if (bc->cfg.bps > 1500000) bc->cfg.bps = 1500000; } return 0; } /* --------------------------------------------------------------------- */ static int baycom_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct baycom_state *bc = netdev_priv(dev); struct hdlcdrv_ioctl hi; if (cmd != SIOCDEVPRIVATE) return -ENOIOCTLCMD; if (copy_from_user(&hi, ifr->ifr_data, sizeof(hi))) return -EFAULT; switch (hi.cmd) { default: return -ENOIOCTLCMD; case HDLCDRVCTL_GETCHANNELPAR: hi.data.cp.tx_delay = bc->ch_params.tx_delay; hi.data.cp.tx_tail = bc->ch_params.tx_tail; hi.data.cp.slottime = bc->ch_params.slottime; hi.data.cp.ppersist = bc->ch_params.ppersist; hi.data.cp.fulldup = bc->ch_params.fulldup; break; case HDLCDRVCTL_SETCHANNELPAR: if (!capable(CAP_NET_ADMIN)) return -EACCES; bc->ch_params.tx_delay = hi.data.cp.tx_delay; bc->ch_params.tx_tail = hi.data.cp.tx_tail; bc->ch_params.slottime = hi.data.cp.slottime; bc->ch_params.ppersist = hi.data.cp.ppersist; bc->ch_params.fulldup = hi.data.cp.fulldup; bc->hdlctx.slotcnt = 1; return 0; case HDLCDRVCTL_GETMODEMPAR: hi.data.mp.iobase = dev->base_addr; hi.data.mp.irq = dev->irq; hi.data.mp.dma = dev->dma; hi.data.mp.dma2 = 0; hi.data.mp.seriobase = 0; hi.data.mp.pariobase = 0; hi.data.mp.midiiobase = 0; break; case HDLCDRVCTL_SETMODEMPAR: if ((!capable(CAP_SYS_RAWIO)) || netif_running(dev)) return -EACCES; dev->base_addr = hi.data.mp.iobase; dev->irq = /*hi.data.mp.irq*/0; dev->dma = /*hi.data.mp.dma*/0; return 0; case HDLCDRVCTL_GETSTAT: hi.data.cs.ptt = !!(bc->stat & EPP_PTTBIT); hi.data.cs.dcd = !(bc->stat & EPP_DCDBIT); hi.data.cs.ptt_keyed = bc->ptt_keyed; hi.data.cs.tx_packets = dev->stats.tx_packets; hi.data.cs.tx_errors = dev->stats.tx_errors; hi.data.cs.rx_packets = dev->stats.rx_packets; hi.data.cs.rx_errors = dev->stats.rx_errors; break; case HDLCDRVCTL_OLDGETSTAT: hi.data.ocs.ptt = !!(bc->stat & EPP_PTTBIT); hi.data.ocs.dcd = !(bc->stat & EPP_DCDBIT); hi.data.ocs.ptt_keyed = bc->ptt_keyed; break; case HDLCDRVCTL_CALIBRATE: if (!capable(CAP_SYS_RAWIO)) return -EACCES; bc->hdlctx.calibrate = hi.data.calibrate * bc->bitrate / 8; return 0; case HDLCDRVCTL_DRIVERNAME: strncpy(hi.data.drivername, "baycom_epp", sizeof(hi.data.drivername)); break; case HDLCDRVCTL_GETMODE: sprintf(hi.data.modename, "%sclk,%smodem,fclk=%d,bps=%d%s", bc->cfg.intclk ? "int" : "ext", bc->cfg.extmodem ? "ext" : "int", bc->cfg.fclk, bc->cfg.bps, bc->cfg.loopback ? ",loopback" : ""); break; case HDLCDRVCTL_SETMODE: if (!capable(CAP_NET_ADMIN) || netif_running(dev)) return -EACCES; hi.data.modename[sizeof(hi.data.modename)-1] = '\0'; return baycom_setmode(bc, hi.data.modename); case HDLCDRVCTL_MODELIST: strncpy(hi.data.modename, "intclk,extclk,intmodem,extmodem,divider=x", sizeof(hi.data.modename)); break; case HDLCDRVCTL_MODEMPARMASK: return HDLCDRV_PARMASK_IOBASE; } if (copy_to_user(ifr->ifr_data, &hi, sizeof(hi))) return -EFAULT; return 0; } /* --------------------------------------------------------------------- */ static const struct net_device_ops baycom_netdev_ops = { .ndo_open = epp_open, .ndo_stop = epp_close, .ndo_do_ioctl = baycom_ioctl, .ndo_start_xmit = baycom_send_packet, .ndo_set_mac_address = baycom_set_mac_address, }; /* * Check for a network adaptor of this type, and return '0' if one exists. * If dev->base_addr == 0, probe all likely locations. * If dev->base_addr == 1, always return failure. * If dev->base_addr == 2, allocate space for the device and return success * (detachable devices only). */ static void baycom_probe(struct net_device *dev) { const struct hdlcdrv_channel_params dflt_ch_params = { 20, 2, 10, 40, 0 }; struct baycom_state *bc; /* * not a real probe! only initialize data structures */ bc = netdev_priv(dev); /* * initialize the baycom_state struct */ bc->ch_params = dflt_ch_params; bc->ptt_keyed = 0; /* * initialize the device struct */ /* Fill in the fields of the device structure */ bc->skb = NULL; dev->netdev_ops = &baycom_netdev_ops; dev->header_ops = &ax25_header_ops; dev->type = ARPHRD_AX25; /* AF_AX25 device */ dev->hard_header_len = AX25_MAX_HEADER_LEN + AX25_BPQ_HEADER_LEN; dev->mtu = AX25_DEF_PACLEN; /* eth_mtu is the default */ dev->addr_len = AX25_ADDR_LEN; /* sizeof an ax.25 address */ memcpy(dev->broadcast, &ax25_bcast, AX25_ADDR_LEN); memcpy(dev->dev_addr, &null_ax25_address, AX25_ADDR_LEN); dev->tx_queue_len = 16; /* New style flags */ dev->flags = 0; } /* --------------------------------------------------------------------- */ /* * command line settable parameters */ static char *mode[NR_PORTS] = { "", }; static int iobase[NR_PORTS] = { 0x378, }; module_param_array(mode, charp, NULL, 0); MODULE_PARM_DESC(mode, "baycom operating mode"); module_param_array(iobase, int, NULL, 0); MODULE_PARM_DESC(iobase, "baycom io base address"); MODULE_AUTHOR("Thomas M. Sailer, sailer@ife.ee.ethz.ch, hb9jnx@hb9w.che.eu"); MODULE_DESCRIPTION("Baycom epp amateur radio modem driver"); MODULE_LICENSE("GPL"); /* --------------------------------------------------------------------- */ static void __init baycom_epp_dev_setup(struct net_device *dev) { struct baycom_state *bc = netdev_priv(dev); /* * initialize part of the baycom_state struct */ bc->dev = dev; bc->magic = BAYCOM_MAGIC; bc->cfg.fclk = 19666600; bc->cfg.bps = 9600; /* * initialize part of the device struct */ baycom_probe(dev); } static int __init init_baycomepp(void) { int i, found = 0; char set_hw = 1; printk(bc_drvinfo); /* * register net devices */ for (i = 0; i < NR_PORTS; i++) { struct net_device *dev; dev = alloc_netdev(sizeof(struct baycom_state), "bce%d", baycom_epp_dev_setup); if (!dev) { printk(KERN_WARNING "bce%d : out of memory\n", i); return found ? 0 : -ENOMEM; } sprintf(dev->name, "bce%d", i); dev->base_addr = iobase[i]; if (!mode[i]) set_hw = 0; if (!set_hw) iobase[i] = 0; if (register_netdev(dev)) { printk(KERN_WARNING "%s: cannot register net device %s\n", bc_drvname, dev->name); free_netdev(dev); break; } if (set_hw && baycom_setmode(netdev_priv(dev), mode[i])) set_hw = 0; baycom_device[i] = dev; found++; } return found ? 0 : -ENXIO; } static void __exit cleanup_baycomepp(void) { int i; for(i = 0; i < NR_PORTS; i++) { struct net_device *dev = baycom_device[i]; if (dev) { struct baycom_state *bc = netdev_priv(dev); if (bc->magic == BAYCOM_MAGIC) { unregister_netdev(dev); free_netdev(dev); } else printk(paranoia_str, "cleanup_module"); } } } module_init(init_baycomepp); module_exit(cleanup_baycomepp); /* --------------------------------------------------------------------- */ #ifndef MODULE /* * format: baycom_epp=io,mode * mode: fpga config options */ static int __init baycom_epp_setup(char *str) { static unsigned __initdata nr_dev = 0; int ints[2]; if (nr_dev >= NR_PORTS) return 0; str = get_options(str, 2, ints); if (ints[0] < 1) return 0; mode[nr_dev] = str; iobase[nr_dev] = ints[1]; nr_dev++; return 1; } __setup("baycom_epp=", baycom_epp_setup); #endif /* MODULE */ /* --------------------------------------------------------------------- */
gpl-2.0
anders3408/kernel_oppo_find5-old
drivers/hid/hid-sunplus.c
7423
2099
/* * HID driver for some sunplus "special" devices * * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz> * Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc * Copyright (c) 2006-2007 Jiri Kosina * Copyright (c) 2007 Paul Walmsley * Copyright (c) 2008 Jiri Slaby */ /* * 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 <linux/device.h> #include <linux/hid.h> #include <linux/module.h> #include "hid-ids.h" static __u8 *sp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { if (*rsize >= 107 && rdesc[104] == 0x26 && rdesc[105] == 0x80 && rdesc[106] == 0x03) { hid_info(hdev, "fixing up Sunplus Wireless Desktop report descriptor\n"); rdesc[105] = rdesc[110] = 0x03; rdesc[106] = rdesc[111] = 0x21; } return rdesc; } #define sp_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \ EV_KEY, (c)) static int sp_input_mapping(struct hid_device *hdev, struct hid_input *hi, struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max) { if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER) return 0; switch (usage->hid & HID_USAGE) { case 0x2003: sp_map_key_clear(KEY_ZOOMIN); break; case 0x2103: sp_map_key_clear(KEY_ZOOMOUT); break; default: return 0; } return 1; } static const struct hid_device_id sp_devices[] = { { HID_USB_DEVICE(USB_VENDOR_ID_SUNPLUS, USB_DEVICE_ID_SUNPLUS_WDESKTOP) }, { } }; MODULE_DEVICE_TABLE(hid, sp_devices); static struct hid_driver sp_driver = { .name = "sunplus", .id_table = sp_devices, .report_fixup = sp_report_fixup, .input_mapping = sp_input_mapping, }; static int __init sp_init(void) { return hid_register_driver(&sp_driver); } static void __exit sp_exit(void) { hid_unregister_driver(&sp_driver); } module_init(sp_init); module_exit(sp_exit); MODULE_LICENSE("GPL");
gpl-2.0
tjbrandt/Project-Fjord
arch/arm/mach-pxa/generic.c
7679
2347
/* * linux/arch/arm/mach-pxa/generic.c * * Author: Nicolas Pitre * Created: Jun 15, 2001 * Copyright: MontaVista Software Inc. * * Code common to all PXA machines. * * 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. * * Since this file should be linked before any other machine specific file, * the __initcall() here will be executed first. This serves as default * initialization stuff for PXA machines which can be overridden later if * need be. */ #include <linux/gpio.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <mach/hardware.h> #include <asm/mach/map.h> #include <asm/mach-types.h> #include <mach/reset.h> #include <mach/smemc.h> #include <mach/pxa3xx-regs.h> #include "generic.h" void clear_reset_status(unsigned int mask) { if (cpu_is_pxa2xx()) pxa2xx_clear_reset_status(mask); else { /* RESET_STATUS_* has a 1:1 mapping with ARSR */ ARSR = mask; } } unsigned long get_clock_tick_rate(void) { unsigned long clock_tick_rate; if (cpu_is_pxa25x()) clock_tick_rate = 3686400; else if (machine_is_mainstone()) clock_tick_rate = 3249600; else clock_tick_rate = 3250000; return clock_tick_rate; } EXPORT_SYMBOL(get_clock_tick_rate); /* * Get the clock frequency as reflected by CCCR and the turbo flag. * We assume these values have been applied via a fcs. * If info is not 0 we also display the current settings. */ unsigned int get_clk_frequency_khz(int info) { if (cpu_is_pxa25x()) return pxa25x_get_clk_frequency_khz(info); else if (cpu_is_pxa27x()) return pxa27x_get_clk_frequency_khz(info); return 0; } EXPORT_SYMBOL(get_clk_frequency_khz); /* * Intel PXA2xx internal register mapping. * * Note: virtual 0xfffe0000-0xffffffff is reserved for the vector table * and cache flush area. */ static struct map_desc common_io_desc[] __initdata = { { /* Devs */ .virtual = 0xf2000000, .pfn = __phys_to_pfn(0x40000000), .length = 0x02000000, .type = MT_DEVICE }, { /* UNCACHED_PHYS_0 */ .virtual = 0xff000000, .pfn = __phys_to_pfn(0x00000000), .length = 0x00100000, .type = MT_DEVICE } }; void __init pxa_map_io(void) { iotable_init(ARRAY_AND_SIZE(common_io_desc)); }
gpl-2.0
kozmikkick/tripndroid-endeavoru-3.0
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
williamfdevine/PrettyLinux
drivers/target/target_core_alua.c
1
65286
/******************************************************************************* * Filename: target_core_alua.c * * This file contains SPC-3 compliant asymmetric logical unit assigntment (ALUA) * * (c) Copyright 2009-2013 Datera, Inc. * * Nicholas A. Bellinger <nab@kernel.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 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/slab.h> #include <linux/spinlock.h> #include <linux/configfs.h> #include <linux/export.h> #include <linux/file.h> #include <scsi/scsi_proto.h> #include <asm/unaligned.h> #include <target/target_core_base.h> #include <target/target_core_backend.h> #include <target/target_core_fabric.h> #include "target_core_internal.h" #include "target_core_alua.h" #include "target_core_ua.h" static sense_reason_t core_alua_check_transition(int state, int valid, int *primary); static int core_alua_set_tg_pt_secondary_state( struct se_lun *lun, int explicit, int offline); static char *core_alua_dump_state(int state); static void __target_attach_tg_pt_gp(struct se_lun *lun, struct t10_alua_tg_pt_gp *tg_pt_gp); static u16 alua_lu_gps_counter; static u32 alua_lu_gps_count; static DEFINE_SPINLOCK(lu_gps_lock); static LIST_HEAD(lu_gps_list); struct t10_alua_lu_gp *default_lu_gp; /* * REPORT REFERRALS * * See sbc3r35 section 5.23 */ sense_reason_t target_emulate_report_referrals(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; struct t10_alua_lba_map *map; struct t10_alua_lba_map_member *map_mem; unsigned char *buf; u32 rd_len = 0, off; if (cmd->data_length < 4) { pr_warn("REPORT REFERRALS allocation length %u too" " small\n", cmd->data_length); return TCM_INVALID_CDB_FIELD; } buf = transport_kmap_data_sg(cmd); if (!buf) { return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } off = 4; spin_lock(&dev->t10_alua.lba_map_lock); if (list_empty(&dev->t10_alua.lba_map_list)) { spin_unlock(&dev->t10_alua.lba_map_lock); transport_kunmap_data_sg(cmd); return TCM_UNSUPPORTED_SCSI_OPCODE; } list_for_each_entry(map, &dev->t10_alua.lba_map_list, lba_map_list) { int desc_num = off + 3; int pg_num; off += 4; if (cmd->data_length > off) { put_unaligned_be64(map->lba_map_first_lba, &buf[off]); } off += 8; if (cmd->data_length > off) { put_unaligned_be64(map->lba_map_last_lba, &buf[off]); } off += 8; rd_len += 20; pg_num = 0; list_for_each_entry(map_mem, &map->lba_map_mem_list, lba_map_mem_list) { int alua_state = map_mem->lba_map_mem_alua_state; int alua_pg_id = map_mem->lba_map_mem_alua_pg_id; if (cmd->data_length > off) { buf[off] = alua_state & 0x0f; } off += 2; if (cmd->data_length > off) { buf[off] = (alua_pg_id >> 8) & 0xff; } off++; if (cmd->data_length > off) { buf[off] = (alua_pg_id & 0xff); } off++; rd_len += 4; pg_num++; } if (cmd->data_length > desc_num) { buf[desc_num] = pg_num; } } spin_unlock(&dev->t10_alua.lba_map_lock); /* * Set the RETURN DATA LENGTH set in the header of the DataIN Payload */ put_unaligned_be16(rd_len, &buf[2]); transport_kunmap_data_sg(cmd); target_complete_cmd(cmd, GOOD); return 0; } /* * REPORT_TARGET_PORT_GROUPS * * See spc4r17 section 6.27 */ sense_reason_t target_emulate_report_target_port_groups(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; struct t10_alua_tg_pt_gp *tg_pt_gp; struct se_lun *lun; unsigned char *buf; u32 rd_len = 0, off; int ext_hdr = (cmd->t_task_cdb[1] & 0x20); /* * Skip over RESERVED area to first Target port group descriptor * depending on the PARAMETER DATA FORMAT type.. */ if (ext_hdr != 0) { off = 8; } else { off = 4; } if (cmd->data_length < off) { pr_warn("REPORT TARGET PORT GROUPS allocation length %u too" " small for %s header\n", cmd->data_length, (ext_hdr) ? "extended" : "normal"); return TCM_INVALID_CDB_FIELD; } buf = transport_kmap_data_sg(cmd); if (!buf) { return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } spin_lock(&dev->t10_alua.tg_pt_gps_lock); list_for_each_entry(tg_pt_gp, &dev->t10_alua.tg_pt_gps_list, tg_pt_gp_list) { /* * Check if the Target port group and Target port descriptor list * based on tg_pt_gp_members count will fit into the response payload. * Otherwise, bump rd_len to let the initiator know we have exceeded * the allocation length and the response is truncated. */ if ((off + 8 + (tg_pt_gp->tg_pt_gp_members * 4)) > cmd->data_length) { rd_len += 8 + (tg_pt_gp->tg_pt_gp_members * 4); continue; } /* * PREF: Preferred target port bit, determine if this * bit should be set for port group. */ if (tg_pt_gp->tg_pt_gp_pref) { buf[off] = 0x80; } /* * Set the ASYMMETRIC ACCESS State */ buf[off++] |= (atomic_read( &tg_pt_gp->tg_pt_gp_alua_access_state) & 0xff); /* * Set supported ASYMMETRIC ACCESS State bits */ buf[off++] |= tg_pt_gp->tg_pt_gp_alua_supported_states; /* * TARGET PORT GROUP */ buf[off++] = ((tg_pt_gp->tg_pt_gp_id >> 8) & 0xff); buf[off++] = (tg_pt_gp->tg_pt_gp_id & 0xff); off++; /* Skip over Reserved */ /* * STATUS CODE */ buf[off++] = (tg_pt_gp->tg_pt_gp_alua_access_status & 0xff); /* * Vendor Specific field */ buf[off++] = 0x00; /* * TARGET PORT COUNT */ buf[off++] = (tg_pt_gp->tg_pt_gp_members & 0xff); rd_len += 8; spin_lock(&tg_pt_gp->tg_pt_gp_lock); list_for_each_entry(lun, &tg_pt_gp->tg_pt_gp_lun_list, lun_tg_pt_gp_link) { /* * Start Target Port descriptor format * * See spc4r17 section 6.2.7 Table 247 */ off += 2; /* Skip over Obsolete */ /* * Set RELATIVE TARGET PORT IDENTIFIER */ buf[off++] = ((lun->lun_rtpi >> 8) & 0xff); buf[off++] = (lun->lun_rtpi & 0xff); rd_len += 4; } spin_unlock(&tg_pt_gp->tg_pt_gp_lock); } spin_unlock(&dev->t10_alua.tg_pt_gps_lock); /* * Set the RETURN DATA LENGTH set in the header of the DataIN Payload */ put_unaligned_be32(rd_len, &buf[0]); /* * Fill in the Extended header parameter data format if requested */ if (ext_hdr != 0) { buf[4] = 0x10; /* * Set the implicit transition time (in seconds) for the application * client to use as a base for it's transition timeout value. * * Use the current tg_pt_gp_mem -> tg_pt_gp membership from the LUN * this CDB was received upon to determine this value individually * for ALUA target port group. */ spin_lock(&cmd->se_lun->lun_tg_pt_gp_lock); tg_pt_gp = cmd->se_lun->lun_tg_pt_gp; if (tg_pt_gp) { buf[5] = tg_pt_gp->tg_pt_gp_implicit_trans_secs; } spin_unlock(&cmd->se_lun->lun_tg_pt_gp_lock); } transport_kunmap_data_sg(cmd); target_complete_cmd(cmd, GOOD); return 0; } /* * SET_TARGET_PORT_GROUPS for explicit ALUA operation. * * See spc4r17 section 6.35 */ sense_reason_t target_emulate_set_target_port_groups(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; struct se_lun *l_lun = cmd->se_lun; struct se_node_acl *nacl = cmd->se_sess->se_node_acl; struct t10_alua_tg_pt_gp *tg_pt_gp = NULL, *l_tg_pt_gp; unsigned char *buf; unsigned char *ptr; sense_reason_t rc = TCM_NO_SENSE; u32 len = 4; /* Skip over RESERVED area in header */ int alua_access_state, primary = 0, valid_states; u16 tg_pt_id, rtpi; if (cmd->data_length < 4) { pr_warn("SET TARGET PORT GROUPS parameter list length %u too" " small\n", cmd->data_length); return TCM_INVALID_PARAMETER_LIST; } buf = transport_kmap_data_sg(cmd); if (!buf) { return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } /* * Determine if explicit ALUA via SET_TARGET_PORT_GROUPS is allowed * for the local tg_pt_gp. */ spin_lock(&l_lun->lun_tg_pt_gp_lock); l_tg_pt_gp = l_lun->lun_tg_pt_gp; if (!l_tg_pt_gp) { spin_unlock(&l_lun->lun_tg_pt_gp_lock); pr_err("Unable to access l_lun->tg_pt_gp\n"); rc = TCM_UNSUPPORTED_SCSI_OPCODE; goto out; } if (!(l_tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_EXPLICIT_ALUA)) { spin_unlock(&l_lun->lun_tg_pt_gp_lock); pr_debug("Unable to process SET_TARGET_PORT_GROUPS" " while TPGS_EXPLICIT_ALUA is disabled\n"); rc = TCM_UNSUPPORTED_SCSI_OPCODE; goto out; } valid_states = l_tg_pt_gp->tg_pt_gp_alua_supported_states; spin_unlock(&l_lun->lun_tg_pt_gp_lock); ptr = &buf[4]; /* Skip over RESERVED area in header */ while (len < cmd->data_length) { bool found = false; alua_access_state = (ptr[0] & 0x0f); /* * Check the received ALUA access state, and determine if * the state is a primary or secondary target port asymmetric * access state. */ rc = core_alua_check_transition(alua_access_state, valid_states, &primary); if (rc) { /* * If the SET TARGET PORT GROUPS attempts to establish * an invalid combination of target port asymmetric * access states or attempts to establish an * unsupported target port asymmetric access state, * then the command shall be terminated with CHECK * CONDITION status, with the sense key set to ILLEGAL * REQUEST, and the additional sense code set to INVALID * FIELD IN PARAMETER LIST. */ goto out; } /* * If the ASYMMETRIC ACCESS STATE field (see table 267) * specifies a primary target port asymmetric access state, * then the TARGET PORT GROUP OR TARGET PORT field specifies * a primary target port group for which the primary target * port asymmetric access state shall be changed. If the * ASYMMETRIC ACCESS STATE field specifies a secondary target * port asymmetric access state, then the TARGET PORT GROUP OR * TARGET PORT field specifies the relative target port * identifier (see 3.1.120) of the target port for which the * secondary target port asymmetric access state shall be * changed. */ if (primary) { tg_pt_id = get_unaligned_be16(ptr + 2); /* * Locate the matching target port group ID from * the global tg_pt_gp list */ spin_lock(&dev->t10_alua.tg_pt_gps_lock); list_for_each_entry(tg_pt_gp, &dev->t10_alua.tg_pt_gps_list, tg_pt_gp_list) { if (!tg_pt_gp->tg_pt_gp_valid_id) { continue; } if (tg_pt_id != tg_pt_gp->tg_pt_gp_id) { continue; } atomic_inc_mb(&tg_pt_gp->tg_pt_gp_ref_cnt); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); if (!core_alua_do_port_transition(tg_pt_gp, dev, l_lun, nacl, alua_access_state, 1)) { found = true; } spin_lock(&dev->t10_alua.tg_pt_gps_lock); atomic_dec_mb(&tg_pt_gp->tg_pt_gp_ref_cnt); break; } spin_unlock(&dev->t10_alua.tg_pt_gps_lock); } else { struct se_lun *lun; /* * Extract the RELATIVE TARGET PORT IDENTIFIER to identify * the Target Port in question for the the incoming * SET_TARGET_PORT_GROUPS op. */ rtpi = get_unaligned_be16(ptr + 2); /* * Locate the matching relative target port identifier * for the struct se_device storage object. */ spin_lock(&dev->se_port_lock); list_for_each_entry(lun, &dev->dev_sep_list, lun_dev_link) { if (lun->lun_rtpi != rtpi) { continue; } // XXX: racy unlock spin_unlock(&dev->se_port_lock); if (!core_alua_set_tg_pt_secondary_state( lun, 1, 1)) { found = true; } spin_lock(&dev->se_port_lock); break; } spin_unlock(&dev->se_port_lock); } if (!found) { rc = TCM_INVALID_PARAMETER_LIST; goto out; } ptr += 4; len += 4; } out: transport_kunmap_data_sg(cmd); if (!rc) { target_complete_cmd(cmd, GOOD); } return rc; } static inline void set_ascq(struct se_cmd *cmd, u8 alua_ascq) { /* * Set SCSI additional sense code (ASC) to 'LUN Not Accessible'; * The ALUA additional sense code qualifier (ASCQ) is determined * by the ALUA primary or secondary access state.. */ pr_debug("[%s]: ALUA TG Port not available, " "SenseKey: NOT_READY, ASC/ASCQ: " "0x04/0x%02x\n", cmd->se_tfo->get_fabric_name(), alua_ascq); cmd->scsi_asc = 0x04; cmd->scsi_ascq = alua_ascq; } static inline void core_alua_state_nonoptimized( struct se_cmd *cmd, unsigned char *cdb, int nonop_delay_msecs) { /* * Set SCF_ALUA_NON_OPTIMIZED here, this value will be checked * later to determine if processing of this cmd needs to be * temporarily delayed for the Active/NonOptimized primary access state. */ cmd->se_cmd_flags |= SCF_ALUA_NON_OPTIMIZED; cmd->alua_nonop_delay = nonop_delay_msecs; } static inline int core_alua_state_lba_dependent( struct se_cmd *cmd, struct t10_alua_tg_pt_gp *tg_pt_gp) { struct se_device *dev = cmd->se_dev; u64 segment_size, segment_mult, sectors, lba; /* Only need to check for cdb actually containing LBAs */ if (!(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB)) { return 0; } spin_lock(&dev->t10_alua.lba_map_lock); segment_size = dev->t10_alua.lba_map_segment_size; segment_mult = dev->t10_alua.lba_map_segment_multiplier; sectors = cmd->data_length / dev->dev_attrib.block_size; lba = cmd->t_task_lba; while (lba < cmd->t_task_lba + sectors) { struct t10_alua_lba_map *cur_map = NULL, *map; struct t10_alua_lba_map_member *map_mem; list_for_each_entry(map, &dev->t10_alua.lba_map_list, lba_map_list) { u64 start_lba, last_lba; u64 first_lba = map->lba_map_first_lba; if (segment_mult) { u64 tmp = lba; start_lba = do_div(tmp, segment_size * segment_mult); last_lba = first_lba + segment_size - 1; if (start_lba >= first_lba && start_lba <= last_lba) { lba += segment_size; cur_map = map; break; } } else { last_lba = map->lba_map_last_lba; if (lba >= first_lba && lba <= last_lba) { lba = last_lba + 1; cur_map = map; break; } } } if (!cur_map) { spin_unlock(&dev->t10_alua.lba_map_lock); set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_UNAVAILABLE); return 1; } list_for_each_entry(map_mem, &cur_map->lba_map_mem_list, lba_map_mem_list) { if (map_mem->lba_map_mem_alua_pg_id != tg_pt_gp->tg_pt_gp_id) { continue; } switch (map_mem->lba_map_mem_alua_state) { case ALUA_ACCESS_STATE_STANDBY: spin_unlock(&dev->t10_alua.lba_map_lock); set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_STANDBY); return 1; case ALUA_ACCESS_STATE_UNAVAILABLE: spin_unlock(&dev->t10_alua.lba_map_lock); set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_UNAVAILABLE); return 1; default: break; } } } spin_unlock(&dev->t10_alua.lba_map_lock); return 0; } static inline int core_alua_state_standby( struct se_cmd *cmd, unsigned char *cdb) { /* * Allowed CDBs for ALUA_ACCESS_STATE_STANDBY as defined by * spc4r17 section 5.9.2.4.4 */ switch (cdb[0]) { case INQUIRY: case LOG_SELECT: case LOG_SENSE: case MODE_SELECT: case MODE_SENSE: case REPORT_LUNS: case RECEIVE_DIAGNOSTIC: case SEND_DIAGNOSTIC: case READ_CAPACITY: return 0; case SERVICE_ACTION_IN_16: switch (cdb[1] & 0x1f) { case SAI_READ_CAPACITY_16: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_STANDBY); return 1; } case MAINTENANCE_IN: switch (cdb[1] & 0x1f) { case MI_REPORT_TARGET_PGS: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_STANDBY); return 1; } case MAINTENANCE_OUT: switch (cdb[1]) { case MO_SET_TARGET_PGS: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_STANDBY); return 1; } case REQUEST_SENSE: case PERSISTENT_RESERVE_IN: case PERSISTENT_RESERVE_OUT: case READ_BUFFER: case WRITE_BUFFER: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_STANDBY); return 1; } return 0; } static inline int core_alua_state_unavailable( struct se_cmd *cmd, unsigned char *cdb) { /* * Allowed CDBs for ALUA_ACCESS_STATE_UNAVAILABLE as defined by * spc4r17 section 5.9.2.4.5 */ switch (cdb[0]) { case INQUIRY: case REPORT_LUNS: return 0; case MAINTENANCE_IN: switch (cdb[1] & 0x1f) { case MI_REPORT_TARGET_PGS: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_UNAVAILABLE); return 1; } case MAINTENANCE_OUT: switch (cdb[1]) { case MO_SET_TARGET_PGS: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_UNAVAILABLE); return 1; } case REQUEST_SENSE: case READ_BUFFER: case WRITE_BUFFER: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_TG_PT_UNAVAILABLE); return 1; } return 0; } static inline int core_alua_state_transition( struct se_cmd *cmd, unsigned char *cdb) { /* * Allowed CDBs for ALUA_ACCESS_STATE_TRANSITION as defined by * spc4r17 section 5.9.2.5 */ switch (cdb[0]) { case INQUIRY: case REPORT_LUNS: return 0; case MAINTENANCE_IN: switch (cdb[1] & 0x1f) { case MI_REPORT_TARGET_PGS: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_STATE_TRANSITION); return 1; } case REQUEST_SENSE: case READ_BUFFER: case WRITE_BUFFER: return 0; default: set_ascq(cmd, ASCQ_04H_ALUA_STATE_TRANSITION); return 1; } return 0; } /* * return 1: Is used to signal LUN not accessible, and check condition/not ready * return 0: Used to signal success * return -1: Used to signal failure, and invalid cdb field */ sense_reason_t target_alua_state_check(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; unsigned char *cdb = cmd->t_task_cdb; struct se_lun *lun = cmd->se_lun; struct t10_alua_tg_pt_gp *tg_pt_gp; int out_alua_state, nonop_delay_msecs; if (dev->se_hba->hba_flags & HBA_FLAGS_INTERNAL_USE) { return 0; } if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH) { return 0; } /* * First, check for a struct se_port specific secondary ALUA target port * access state: OFFLINE */ if (atomic_read(&lun->lun_tg_pt_secondary_offline)) { pr_debug("ALUA: Got secondary offline status for local" " target port\n"); set_ascq(cmd, ASCQ_04H_ALUA_OFFLINE); return TCM_CHECK_CONDITION_NOT_READY; } if (!lun->lun_tg_pt_gp) { return 0; } spin_lock(&lun->lun_tg_pt_gp_lock); tg_pt_gp = lun->lun_tg_pt_gp; out_alua_state = atomic_read(&tg_pt_gp->tg_pt_gp_alua_access_state); nonop_delay_msecs = tg_pt_gp->tg_pt_gp_nonop_delay_msecs; // XXX: keeps using tg_pt_gp witout reference after unlock spin_unlock(&lun->lun_tg_pt_gp_lock); /* * Process ALUA_ACCESS_STATE_ACTIVE_OPTIMIZED in a separate conditional * statement so the compiler knows explicitly to check this case first. * For the Optimized ALUA access state case, we want to process the * incoming fabric cmd ASAP.. */ if (out_alua_state == ALUA_ACCESS_STATE_ACTIVE_OPTIMIZED) { return 0; } switch (out_alua_state) { case ALUA_ACCESS_STATE_ACTIVE_NON_OPTIMIZED: core_alua_state_nonoptimized(cmd, cdb, nonop_delay_msecs); break; case ALUA_ACCESS_STATE_STANDBY: if (core_alua_state_standby(cmd, cdb)) { return TCM_CHECK_CONDITION_NOT_READY; } break; case ALUA_ACCESS_STATE_UNAVAILABLE: if (core_alua_state_unavailable(cmd, cdb)) { return TCM_CHECK_CONDITION_NOT_READY; } break; case ALUA_ACCESS_STATE_TRANSITION: if (core_alua_state_transition(cmd, cdb)) { return TCM_CHECK_CONDITION_NOT_READY; } break; case ALUA_ACCESS_STATE_LBA_DEPENDENT: if (core_alua_state_lba_dependent(cmd, tg_pt_gp)) { return TCM_CHECK_CONDITION_NOT_READY; } break; /* * OFFLINE is a secondary ALUA target port group access state, that is * handled above with struct se_lun->lun_tg_pt_secondary_offline=1 */ case ALUA_ACCESS_STATE_OFFLINE: default: pr_err("Unknown ALUA access state: 0x%02x\n", out_alua_state); return TCM_INVALID_CDB_FIELD; } return 0; } /* * Check implicit and explicit ALUA state change request. */ static sense_reason_t core_alua_check_transition(int state, int valid, int *primary) { /* * OPTIMIZED, NON-OPTIMIZED, STANDBY and UNAVAILABLE are * defined as primary target port asymmetric access states. */ switch (state) { case ALUA_ACCESS_STATE_ACTIVE_OPTIMIZED: if (!(valid & ALUA_AO_SUP)) { goto not_supported; } *primary = 1; break; case ALUA_ACCESS_STATE_ACTIVE_NON_OPTIMIZED: if (!(valid & ALUA_AN_SUP)) { goto not_supported; } *primary = 1; break; case ALUA_ACCESS_STATE_STANDBY: if (!(valid & ALUA_S_SUP)) { goto not_supported; } *primary = 1; break; case ALUA_ACCESS_STATE_UNAVAILABLE: if (!(valid & ALUA_U_SUP)) { goto not_supported; } *primary = 1; break; case ALUA_ACCESS_STATE_LBA_DEPENDENT: if (!(valid & ALUA_LBD_SUP)) { goto not_supported; } *primary = 1; break; case ALUA_ACCESS_STATE_OFFLINE: /* * OFFLINE state is defined as a secondary target port * asymmetric access state. */ if (!(valid & ALUA_O_SUP)) { goto not_supported; } *primary = 0; break; case ALUA_ACCESS_STATE_TRANSITION: /* * Transitioning is set internally, and * cannot be selected manually. */ goto not_supported; default: pr_err("Unknown ALUA access state: 0x%02x\n", state); return TCM_INVALID_PARAMETER_LIST; } return 0; not_supported: pr_err("ALUA access state %s not supported", core_alua_dump_state(state)); return TCM_INVALID_PARAMETER_LIST; } static char *core_alua_dump_state(int state) { switch (state) { case ALUA_ACCESS_STATE_ACTIVE_OPTIMIZED: return "Active/Optimized"; case ALUA_ACCESS_STATE_ACTIVE_NON_OPTIMIZED: return "Active/NonOptimized"; case ALUA_ACCESS_STATE_LBA_DEPENDENT: return "LBA Dependent"; case ALUA_ACCESS_STATE_STANDBY: return "Standby"; case ALUA_ACCESS_STATE_UNAVAILABLE: return "Unavailable"; case ALUA_ACCESS_STATE_OFFLINE: return "Offline"; case ALUA_ACCESS_STATE_TRANSITION: return "Transitioning"; default: return "Unknown"; } return NULL; } char *core_alua_dump_status(int status) { switch (status) { case ALUA_STATUS_NONE: return "None"; case ALUA_STATUS_ALTERED_BY_EXPLICIT_STPG: return "Altered by Explicit STPG"; case ALUA_STATUS_ALTERED_BY_IMPLICIT_ALUA: return "Altered by Implicit ALUA"; default: return "Unknown"; } return NULL; } /* * Used by fabric modules to determine when we need to delay processing * for the Active/NonOptimized paths.. */ int core_alua_check_nonop_delay( struct se_cmd *cmd) { if (!(cmd->se_cmd_flags & SCF_ALUA_NON_OPTIMIZED)) { return 0; } if (in_interrupt()) { return 0; } /* * The ALUA Active/NonOptimized access state delay can be disabled * in via configfs with a value of zero */ if (!cmd->alua_nonop_delay) { return 0; } /* * struct se_cmd->alua_nonop_delay gets set by a target port group * defined interval in core_alua_state_nonoptimized() */ msleep_interruptible(cmd->alua_nonop_delay); return 0; } EXPORT_SYMBOL(core_alua_check_nonop_delay); static int core_alua_write_tpg_metadata( const char *path, unsigned char *md_buf, u32 md_buf_len) { struct file *file = filp_open(path, O_RDWR | O_CREAT | O_TRUNC, 0600); int ret; if (IS_ERR(file)) { pr_err("filp_open(%s) for ALUA metadata failed\n", path); return -ENODEV; } ret = kernel_write(file, md_buf, md_buf_len, 0); if (ret < 0) { pr_err("Error writing ALUA metadata file: %s\n", path); } fput(file); return (ret < 0) ? -EIO : 0; } /* * Called with tg_pt_gp->tg_pt_gp_md_mutex held */ static int core_alua_update_tpg_primary_metadata( struct t10_alua_tg_pt_gp *tg_pt_gp) { unsigned char *md_buf; struct t10_wwn *wwn = &tg_pt_gp->tg_pt_gp_dev->t10_wwn; char path[ALUA_METADATA_PATH_LEN]; int len, rc; md_buf = kzalloc(ALUA_MD_BUF_LEN, GFP_KERNEL); if (!md_buf) { pr_err("Unable to allocate buf for ALUA metadata\n"); return -ENOMEM; } memset(path, 0, ALUA_METADATA_PATH_LEN); len = snprintf(md_buf, ALUA_MD_BUF_LEN, "tg_pt_gp_id=%hu\n" "alua_access_state=0x%02x\n" "alua_access_status=0x%02x\n", tg_pt_gp->tg_pt_gp_id, tg_pt_gp->tg_pt_gp_alua_pending_state, tg_pt_gp->tg_pt_gp_alua_access_status); snprintf(path, ALUA_METADATA_PATH_LEN, "%s/alua/tpgs_%s/%s", db_root, &wwn->unit_serial[0], config_item_name(&tg_pt_gp->tg_pt_gp_group.cg_item)); rc = core_alua_write_tpg_metadata(path, md_buf, len); kfree(md_buf); return rc; } static void core_alua_queue_state_change_ua(struct t10_alua_tg_pt_gp *tg_pt_gp) { struct se_dev_entry *se_deve; struct se_lun *lun; struct se_lun_acl *lacl; spin_lock(&tg_pt_gp->tg_pt_gp_lock); list_for_each_entry(lun, &tg_pt_gp->tg_pt_gp_lun_list, lun_tg_pt_gp_link) { /* * After an implicit target port asymmetric access state * change, a device server shall establish a unit attention * condition for the initiator port associated with every I_T * nexus with the additional sense code set to ASYMMETRIC * ACCESS STATE CHANGED. * * After an explicit target port asymmetric access state * change, a device server shall establish a unit attention * condition with the additional sense code set to ASYMMETRIC * ACCESS STATE CHANGED for the initiator port associated with * every I_T nexus other than the I_T nexus on which the SET * TARGET PORT GROUPS command */ if (!percpu_ref_tryget_live(&lun->lun_ref)) { continue; } spin_unlock(&tg_pt_gp->tg_pt_gp_lock); spin_lock(&lun->lun_deve_lock); list_for_each_entry(se_deve, &lun->lun_deve_list, lun_link) { lacl = rcu_dereference_check(se_deve->se_lun_acl, lockdep_is_held(&lun->lun_deve_lock)); /* * spc4r37 p.242: * After an explicit target port asymmetric access * state change, a device server shall establish a * unit attention condition with the additional sense * code set to ASYMMETRIC ACCESS STATE CHANGED for * the initiator port associated with every I_T nexus * other than the I_T nexus on which the SET TARGET * PORT GROUPS command was received. */ if ((tg_pt_gp->tg_pt_gp_alua_access_status == ALUA_STATUS_ALTERED_BY_EXPLICIT_STPG) && (tg_pt_gp->tg_pt_gp_alua_lun != NULL) && (tg_pt_gp->tg_pt_gp_alua_lun == lun)) { continue; } /* * se_deve->se_lun_acl pointer may be NULL for a * entry created without explicit Node+MappedLUN ACLs */ if (lacl && (tg_pt_gp->tg_pt_gp_alua_nacl != NULL) && (tg_pt_gp->tg_pt_gp_alua_nacl == lacl->se_lun_nacl)) { continue; } core_scsi3_ua_allocate(se_deve, 0x2A, ASCQ_2AH_ASYMMETRIC_ACCESS_STATE_CHANGED); } spin_unlock(&lun->lun_deve_lock); spin_lock(&tg_pt_gp->tg_pt_gp_lock); percpu_ref_put(&lun->lun_ref); } spin_unlock(&tg_pt_gp->tg_pt_gp_lock); } static void core_alua_do_transition_tg_pt_work(struct work_struct *work) { struct t10_alua_tg_pt_gp *tg_pt_gp = container_of(work, struct t10_alua_tg_pt_gp, tg_pt_gp_transition_work.work); struct se_device *dev = tg_pt_gp->tg_pt_gp_dev; bool explicit = (tg_pt_gp->tg_pt_gp_alua_access_status == ALUA_STATUS_ALTERED_BY_EXPLICIT_STPG); /* * Update the ALUA metadata buf that has been allocated in * core_alua_do_port_transition(), this metadata will be written * to struct file. * * Note that there is the case where we do not want to update the * metadata when the saved metadata is being parsed in userspace * when setting the existing port access state and access status. * * Also note that the failure to write out the ALUA metadata to * struct file does NOT affect the actual ALUA transition. */ if (tg_pt_gp->tg_pt_gp_write_metadata) { mutex_lock(&tg_pt_gp->tg_pt_gp_md_mutex); core_alua_update_tpg_primary_metadata(tg_pt_gp); mutex_unlock(&tg_pt_gp->tg_pt_gp_md_mutex); } /* * Set the current primary ALUA access state to the requested new state */ atomic_set(&tg_pt_gp->tg_pt_gp_alua_access_state, tg_pt_gp->tg_pt_gp_alua_pending_state); pr_debug("Successful %s ALUA transition TG PT Group: %s ID: %hu" " from primary access state %s to %s\n", (explicit) ? "explicit" : "implicit", config_item_name(&tg_pt_gp->tg_pt_gp_group.cg_item), tg_pt_gp->tg_pt_gp_id, core_alua_dump_state(tg_pt_gp->tg_pt_gp_alua_previous_state), core_alua_dump_state(tg_pt_gp->tg_pt_gp_alua_pending_state)); core_alua_queue_state_change_ua(tg_pt_gp); spin_lock(&dev->t10_alua.tg_pt_gps_lock); atomic_dec(&tg_pt_gp->tg_pt_gp_ref_cnt); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); if (tg_pt_gp->tg_pt_gp_transition_complete) { complete(tg_pt_gp->tg_pt_gp_transition_complete); } } static int core_alua_do_transition_tg_pt( struct t10_alua_tg_pt_gp *tg_pt_gp, int new_state, int explicit) { struct se_device *dev = tg_pt_gp->tg_pt_gp_dev; DECLARE_COMPLETION_ONSTACK(wait); /* Nothing to be done here */ if (atomic_read(&tg_pt_gp->tg_pt_gp_alua_access_state) == new_state) { return 0; } if (new_state == ALUA_ACCESS_STATE_TRANSITION) { return -EAGAIN; } /* * Flush any pending transitions */ if (!explicit && tg_pt_gp->tg_pt_gp_implicit_trans_secs && atomic_read(&tg_pt_gp->tg_pt_gp_alua_access_state) == ALUA_ACCESS_STATE_TRANSITION) { /* Just in case */ tg_pt_gp->tg_pt_gp_alua_pending_state = new_state; tg_pt_gp->tg_pt_gp_transition_complete = &wait; flush_delayed_work(&tg_pt_gp->tg_pt_gp_transition_work); wait_for_completion(&wait); tg_pt_gp->tg_pt_gp_transition_complete = NULL; return 0; } /* * Save the old primary ALUA access state, and set the current state * to ALUA_ACCESS_STATE_TRANSITION. */ tg_pt_gp->tg_pt_gp_alua_previous_state = atomic_read(&tg_pt_gp->tg_pt_gp_alua_access_state); tg_pt_gp->tg_pt_gp_alua_pending_state = new_state; atomic_set(&tg_pt_gp->tg_pt_gp_alua_access_state, ALUA_ACCESS_STATE_TRANSITION); tg_pt_gp->tg_pt_gp_alua_access_status = (explicit) ? ALUA_STATUS_ALTERED_BY_EXPLICIT_STPG : ALUA_STATUS_ALTERED_BY_IMPLICIT_ALUA; core_alua_queue_state_change_ua(tg_pt_gp); /* * Check for the optional ALUA primary state transition delay */ if (tg_pt_gp->tg_pt_gp_trans_delay_msecs != 0) { msleep_interruptible(tg_pt_gp->tg_pt_gp_trans_delay_msecs); } /* * Take a reference for workqueue item */ spin_lock(&dev->t10_alua.tg_pt_gps_lock); atomic_inc(&tg_pt_gp->tg_pt_gp_ref_cnt); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); if (!explicit && tg_pt_gp->tg_pt_gp_implicit_trans_secs) { unsigned long transition_tmo; transition_tmo = tg_pt_gp->tg_pt_gp_implicit_trans_secs * HZ; queue_delayed_work(tg_pt_gp->tg_pt_gp_dev->tmr_wq, &tg_pt_gp->tg_pt_gp_transition_work, transition_tmo); } else { tg_pt_gp->tg_pt_gp_transition_complete = &wait; queue_delayed_work(tg_pt_gp->tg_pt_gp_dev->tmr_wq, &tg_pt_gp->tg_pt_gp_transition_work, 0); wait_for_completion(&wait); tg_pt_gp->tg_pt_gp_transition_complete = NULL; } return 0; } int core_alua_do_port_transition( struct t10_alua_tg_pt_gp *l_tg_pt_gp, struct se_device *l_dev, struct se_lun *l_lun, struct se_node_acl *l_nacl, int new_state, int explicit) { struct se_device *dev; struct t10_alua_lu_gp *lu_gp; struct t10_alua_lu_gp_member *lu_gp_mem, *local_lu_gp_mem; struct t10_alua_tg_pt_gp *tg_pt_gp; int primary, valid_states, rc = 0; valid_states = l_tg_pt_gp->tg_pt_gp_alua_supported_states; if (core_alua_check_transition(new_state, valid_states, &primary) != 0) { return -EINVAL; } local_lu_gp_mem = l_dev->dev_alua_lu_gp_mem; spin_lock(&local_lu_gp_mem->lu_gp_mem_lock); lu_gp = local_lu_gp_mem->lu_gp; atomic_inc(&lu_gp->lu_gp_ref_cnt); spin_unlock(&local_lu_gp_mem->lu_gp_mem_lock); /* * For storage objects that are members of the 'default_lu_gp', * we only do transition on the passed *l_tp_pt_gp, and not * on all of the matching target port groups IDs in default_lu_gp. */ if (!lu_gp->lu_gp_id) { /* * core_alua_do_transition_tg_pt() will always return * success. */ l_tg_pt_gp->tg_pt_gp_alua_lun = l_lun; l_tg_pt_gp->tg_pt_gp_alua_nacl = l_nacl; rc = core_alua_do_transition_tg_pt(l_tg_pt_gp, new_state, explicit); atomic_dec_mb(&lu_gp->lu_gp_ref_cnt); return rc; } /* * For all other LU groups aside from 'default_lu_gp', walk all of * the associated storage objects looking for a matching target port * group ID from the local target port group. */ spin_lock(&lu_gp->lu_gp_lock); list_for_each_entry(lu_gp_mem, &lu_gp->lu_gp_mem_list, lu_gp_mem_list) { dev = lu_gp_mem->lu_gp_mem_dev; atomic_inc_mb(&lu_gp_mem->lu_gp_mem_ref_cnt); spin_unlock(&lu_gp->lu_gp_lock); spin_lock(&dev->t10_alua.tg_pt_gps_lock); list_for_each_entry(tg_pt_gp, &dev->t10_alua.tg_pt_gps_list, tg_pt_gp_list) { if (!tg_pt_gp->tg_pt_gp_valid_id) { continue; } /* * If the target behavior port asymmetric access state * is changed for any target port group accessible via * a logical unit within a LU group, the target port * behavior group asymmetric access states for the same * target port group accessible via other logical units * in that LU group will also change. */ if (l_tg_pt_gp->tg_pt_gp_id != tg_pt_gp->tg_pt_gp_id) { continue; } if (l_tg_pt_gp == tg_pt_gp) { tg_pt_gp->tg_pt_gp_alua_lun = l_lun; tg_pt_gp->tg_pt_gp_alua_nacl = l_nacl; } else { tg_pt_gp->tg_pt_gp_alua_lun = NULL; tg_pt_gp->tg_pt_gp_alua_nacl = NULL; } atomic_inc_mb(&tg_pt_gp->tg_pt_gp_ref_cnt); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); /* * core_alua_do_transition_tg_pt() will always return * success. */ rc = core_alua_do_transition_tg_pt(tg_pt_gp, new_state, explicit); spin_lock(&dev->t10_alua.tg_pt_gps_lock); atomic_dec_mb(&tg_pt_gp->tg_pt_gp_ref_cnt); if (rc) { break; } } spin_unlock(&dev->t10_alua.tg_pt_gps_lock); spin_lock(&lu_gp->lu_gp_lock); atomic_dec_mb(&lu_gp_mem->lu_gp_mem_ref_cnt); } spin_unlock(&lu_gp->lu_gp_lock); if (!rc) { pr_debug("Successfully processed LU Group: %s all ALUA TG PT" " Group IDs: %hu %s transition to primary state: %s\n", config_item_name(&lu_gp->lu_gp_group.cg_item), l_tg_pt_gp->tg_pt_gp_id, (explicit) ? "explicit" : "implicit", core_alua_dump_state(new_state)); } atomic_dec_mb(&lu_gp->lu_gp_ref_cnt); return rc; } static int core_alua_update_tpg_secondary_metadata(struct se_lun *lun) { struct se_portal_group *se_tpg = lun->lun_tpg; unsigned char *md_buf; char path[ALUA_METADATA_PATH_LEN], wwn[ALUA_SECONDARY_METADATA_WWN_LEN]; int len, rc; mutex_lock(&lun->lun_tg_pt_md_mutex); md_buf = kzalloc(ALUA_MD_BUF_LEN, GFP_KERNEL); if (!md_buf) { pr_err("Unable to allocate buf for ALUA metadata\n"); rc = -ENOMEM; goto out_unlock; } memset(path, 0, ALUA_METADATA_PATH_LEN); memset(wwn, 0, ALUA_SECONDARY_METADATA_WWN_LEN); len = snprintf(wwn, ALUA_SECONDARY_METADATA_WWN_LEN, "%s", se_tpg->se_tpg_tfo->tpg_get_wwn(se_tpg)); if (se_tpg->se_tpg_tfo->tpg_get_tag != NULL) snprintf(wwn + len, ALUA_SECONDARY_METADATA_WWN_LEN - len, "+%hu", se_tpg->se_tpg_tfo->tpg_get_tag(se_tpg)); len = snprintf(md_buf, ALUA_MD_BUF_LEN, "alua_tg_pt_offline=%d\n" "alua_tg_pt_status=0x%02x\n", atomic_read(&lun->lun_tg_pt_secondary_offline), lun->lun_tg_pt_secondary_stat); snprintf(path, ALUA_METADATA_PATH_LEN, "%s/alua/%s/%s/lun_%llu", db_root, se_tpg->se_tpg_tfo->get_fabric_name(), wwn, lun->unpacked_lun); rc = core_alua_write_tpg_metadata(path, md_buf, len); kfree(md_buf); out_unlock: mutex_unlock(&lun->lun_tg_pt_md_mutex); return rc; } static int core_alua_set_tg_pt_secondary_state( struct se_lun *lun, int explicit, int offline) { struct t10_alua_tg_pt_gp *tg_pt_gp; int trans_delay_msecs; spin_lock(&lun->lun_tg_pt_gp_lock); tg_pt_gp = lun->lun_tg_pt_gp; if (!tg_pt_gp) { spin_unlock(&lun->lun_tg_pt_gp_lock); pr_err("Unable to complete secondary state" " transition\n"); return -EINVAL; } trans_delay_msecs = tg_pt_gp->tg_pt_gp_trans_delay_msecs; /* * Set the secondary ALUA target port access state to OFFLINE * or release the previously secondary state for struct se_lun */ if (offline) { atomic_set(&lun->lun_tg_pt_secondary_offline, 1); } else { atomic_set(&lun->lun_tg_pt_secondary_offline, 0); } lun->lun_tg_pt_secondary_stat = (explicit) ? ALUA_STATUS_ALTERED_BY_EXPLICIT_STPG : ALUA_STATUS_ALTERED_BY_IMPLICIT_ALUA; pr_debug("Successful %s ALUA transition TG PT Group: %s ID: %hu" " to secondary access state: %s\n", (explicit) ? "explicit" : "implicit", config_item_name(&tg_pt_gp->tg_pt_gp_group.cg_item), tg_pt_gp->tg_pt_gp_id, (offline) ? "OFFLINE" : "ONLINE"); spin_unlock(&lun->lun_tg_pt_gp_lock); /* * Do the optional transition delay after we set the secondary * ALUA access state. */ if (trans_delay_msecs != 0) { msleep_interruptible(trans_delay_msecs); } /* * See if we need to update the ALUA fabric port metadata for * secondary state and status */ if (lun->lun_tg_pt_secondary_write_md) { core_alua_update_tpg_secondary_metadata(lun); } return 0; } struct t10_alua_lba_map * core_alua_allocate_lba_map(struct list_head *list, u64 first_lba, u64 last_lba) { struct t10_alua_lba_map *lba_map; lba_map = kmem_cache_zalloc(t10_alua_lba_map_cache, GFP_KERNEL); if (!lba_map) { pr_err("Unable to allocate struct t10_alua_lba_map\n"); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&lba_map->lba_map_mem_list); lba_map->lba_map_first_lba = first_lba; lba_map->lba_map_last_lba = last_lba; list_add_tail(&lba_map->lba_map_list, list); return lba_map; } int core_alua_allocate_lba_map_mem(struct t10_alua_lba_map *lba_map, int pg_id, int state) { struct t10_alua_lba_map_member *lba_map_mem; list_for_each_entry(lba_map_mem, &lba_map->lba_map_mem_list, lba_map_mem_list) { if (lba_map_mem->lba_map_mem_alua_pg_id == pg_id) { pr_err("Duplicate pg_id %d in lba_map\n", pg_id); return -EINVAL; } } lba_map_mem = kmem_cache_zalloc(t10_alua_lba_map_mem_cache, GFP_KERNEL); if (!lba_map_mem) { pr_err("Unable to allocate struct t10_alua_lba_map_mem\n"); return -ENOMEM; } lba_map_mem->lba_map_mem_alua_state = state; lba_map_mem->lba_map_mem_alua_pg_id = pg_id; list_add_tail(&lba_map_mem->lba_map_mem_list, &lba_map->lba_map_mem_list); return 0; } void core_alua_free_lba_map(struct list_head *lba_list) { struct t10_alua_lba_map *lba_map, *lba_map_tmp; struct t10_alua_lba_map_member *lba_map_mem, *lba_map_mem_tmp; list_for_each_entry_safe(lba_map, lba_map_tmp, lba_list, lba_map_list) { list_for_each_entry_safe(lba_map_mem, lba_map_mem_tmp, &lba_map->lba_map_mem_list, lba_map_mem_list) { list_del(&lba_map_mem->lba_map_mem_list); kmem_cache_free(t10_alua_lba_map_mem_cache, lba_map_mem); } list_del(&lba_map->lba_map_list); kmem_cache_free(t10_alua_lba_map_cache, lba_map); } } void core_alua_set_lba_map(struct se_device *dev, struct list_head *lba_map_list, int segment_size, int segment_mult) { struct list_head old_lba_map_list; struct t10_alua_tg_pt_gp *tg_pt_gp; int activate = 0, supported; INIT_LIST_HEAD(&old_lba_map_list); spin_lock(&dev->t10_alua.lba_map_lock); dev->t10_alua.lba_map_segment_size = segment_size; dev->t10_alua.lba_map_segment_multiplier = segment_mult; list_splice_init(&dev->t10_alua.lba_map_list, &old_lba_map_list); if (lba_map_list) { list_splice_init(lba_map_list, &dev->t10_alua.lba_map_list); activate = 1; } spin_unlock(&dev->t10_alua.lba_map_lock); spin_lock(&dev->t10_alua.tg_pt_gps_lock); list_for_each_entry(tg_pt_gp, &dev->t10_alua.tg_pt_gps_list, tg_pt_gp_list) { if (!tg_pt_gp->tg_pt_gp_valid_id) { continue; } supported = tg_pt_gp->tg_pt_gp_alua_supported_states; if (activate) { supported |= ALUA_LBD_SUP; } else { supported &= ~ALUA_LBD_SUP; } tg_pt_gp->tg_pt_gp_alua_supported_states = supported; } spin_unlock(&dev->t10_alua.tg_pt_gps_lock); core_alua_free_lba_map(&old_lba_map_list); } struct t10_alua_lu_gp * core_alua_allocate_lu_gp(const char *name, int def_group) { struct t10_alua_lu_gp *lu_gp; lu_gp = kmem_cache_zalloc(t10_alua_lu_gp_cache, GFP_KERNEL); if (!lu_gp) { pr_err("Unable to allocate struct t10_alua_lu_gp\n"); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&lu_gp->lu_gp_node); INIT_LIST_HEAD(&lu_gp->lu_gp_mem_list); spin_lock_init(&lu_gp->lu_gp_lock); atomic_set(&lu_gp->lu_gp_ref_cnt, 0); if (def_group) { lu_gp->lu_gp_id = alua_lu_gps_counter++; lu_gp->lu_gp_valid_id = 1; alua_lu_gps_count++; } return lu_gp; } int core_alua_set_lu_gp_id(struct t10_alua_lu_gp *lu_gp, u16 lu_gp_id) { struct t10_alua_lu_gp *lu_gp_tmp; u16 lu_gp_id_tmp; /* * The lu_gp->lu_gp_id may only be set once.. */ if (lu_gp->lu_gp_valid_id) { pr_warn("ALUA LU Group already has a valid ID," " ignoring request\n"); return -EINVAL; } spin_lock(&lu_gps_lock); if (alua_lu_gps_count == 0x0000ffff) { pr_err("Maximum ALUA alua_lu_gps_count:" " 0x0000ffff reached\n"); spin_unlock(&lu_gps_lock); kmem_cache_free(t10_alua_lu_gp_cache, lu_gp); return -ENOSPC; } again: lu_gp_id_tmp = (lu_gp_id != 0) ? lu_gp_id : alua_lu_gps_counter++; list_for_each_entry(lu_gp_tmp, &lu_gps_list, lu_gp_node) { if (lu_gp_tmp->lu_gp_id == lu_gp_id_tmp) { if (!lu_gp_id) { goto again; } pr_warn("ALUA Logical Unit Group ID: %hu" " already exists, ignoring request\n", lu_gp_id); spin_unlock(&lu_gps_lock); return -EINVAL; } } lu_gp->lu_gp_id = lu_gp_id_tmp; lu_gp->lu_gp_valid_id = 1; list_add_tail(&lu_gp->lu_gp_node, &lu_gps_list); alua_lu_gps_count++; spin_unlock(&lu_gps_lock); return 0; } static struct t10_alua_lu_gp_member * core_alua_allocate_lu_gp_mem(struct se_device *dev) { struct t10_alua_lu_gp_member *lu_gp_mem; lu_gp_mem = kmem_cache_zalloc(t10_alua_lu_gp_mem_cache, GFP_KERNEL); if (!lu_gp_mem) { pr_err("Unable to allocate struct t10_alua_lu_gp_member\n"); return ERR_PTR(-ENOMEM); } INIT_LIST_HEAD(&lu_gp_mem->lu_gp_mem_list); spin_lock_init(&lu_gp_mem->lu_gp_mem_lock); atomic_set(&lu_gp_mem->lu_gp_mem_ref_cnt, 0); lu_gp_mem->lu_gp_mem_dev = dev; dev->dev_alua_lu_gp_mem = lu_gp_mem; return lu_gp_mem; } void core_alua_free_lu_gp(struct t10_alua_lu_gp *lu_gp) { struct t10_alua_lu_gp_member *lu_gp_mem, *lu_gp_mem_tmp; /* * Once we have reached this point, config_item_put() has * already been called from target_core_alua_drop_lu_gp(). * * Here, we remove the *lu_gp from the global list so that * no associations can be made while we are releasing * struct t10_alua_lu_gp. */ spin_lock(&lu_gps_lock); list_del(&lu_gp->lu_gp_node); alua_lu_gps_count--; spin_unlock(&lu_gps_lock); /* * Allow struct t10_alua_lu_gp * referenced by core_alua_get_lu_gp_by_name() * in target_core_configfs.c:target_core_store_alua_lu_gp() to be * released with core_alua_put_lu_gp_from_name() */ while (atomic_read(&lu_gp->lu_gp_ref_cnt)) { cpu_relax(); } /* * Release reference to struct t10_alua_lu_gp * from all associated * struct se_device. */ spin_lock(&lu_gp->lu_gp_lock); list_for_each_entry_safe(lu_gp_mem, lu_gp_mem_tmp, &lu_gp->lu_gp_mem_list, lu_gp_mem_list) { if (lu_gp_mem->lu_gp_assoc) { list_del(&lu_gp_mem->lu_gp_mem_list); lu_gp->lu_gp_members--; lu_gp_mem->lu_gp_assoc = 0; } spin_unlock(&lu_gp->lu_gp_lock); /* * * lu_gp_mem is associated with a single * struct se_device->dev_alua_lu_gp_mem, and is released when * struct se_device is released via core_alua_free_lu_gp_mem(). * * If the passed lu_gp does NOT match the default_lu_gp, assume * we want to re-associate a given lu_gp_mem with default_lu_gp. */ spin_lock(&lu_gp_mem->lu_gp_mem_lock); if (lu_gp != default_lu_gp) __core_alua_attach_lu_gp_mem(lu_gp_mem, default_lu_gp); else { lu_gp_mem->lu_gp = NULL; } spin_unlock(&lu_gp_mem->lu_gp_mem_lock); spin_lock(&lu_gp->lu_gp_lock); } spin_unlock(&lu_gp->lu_gp_lock); kmem_cache_free(t10_alua_lu_gp_cache, lu_gp); } void core_alua_free_lu_gp_mem(struct se_device *dev) { struct t10_alua_lu_gp *lu_gp; struct t10_alua_lu_gp_member *lu_gp_mem; lu_gp_mem = dev->dev_alua_lu_gp_mem; if (!lu_gp_mem) { return; } while (atomic_read(&lu_gp_mem->lu_gp_mem_ref_cnt)) { cpu_relax(); } spin_lock(&lu_gp_mem->lu_gp_mem_lock); lu_gp = lu_gp_mem->lu_gp; if (lu_gp) { spin_lock(&lu_gp->lu_gp_lock); if (lu_gp_mem->lu_gp_assoc) { list_del(&lu_gp_mem->lu_gp_mem_list); lu_gp->lu_gp_members--; lu_gp_mem->lu_gp_assoc = 0; } spin_unlock(&lu_gp->lu_gp_lock); lu_gp_mem->lu_gp = NULL; } spin_unlock(&lu_gp_mem->lu_gp_mem_lock); kmem_cache_free(t10_alua_lu_gp_mem_cache, lu_gp_mem); } struct t10_alua_lu_gp *core_alua_get_lu_gp_by_name(const char *name) { struct t10_alua_lu_gp *lu_gp; struct config_item *ci; spin_lock(&lu_gps_lock); list_for_each_entry(lu_gp, &lu_gps_list, lu_gp_node) { if (!lu_gp->lu_gp_valid_id) { continue; } ci = &lu_gp->lu_gp_group.cg_item; if (!strcmp(config_item_name(ci), name)) { atomic_inc(&lu_gp->lu_gp_ref_cnt); spin_unlock(&lu_gps_lock); return lu_gp; } } spin_unlock(&lu_gps_lock); return NULL; } void core_alua_put_lu_gp_from_name(struct t10_alua_lu_gp *lu_gp) { spin_lock(&lu_gps_lock); atomic_dec(&lu_gp->lu_gp_ref_cnt); spin_unlock(&lu_gps_lock); } /* * Called with struct t10_alua_lu_gp_member->lu_gp_mem_lock */ void __core_alua_attach_lu_gp_mem( struct t10_alua_lu_gp_member *lu_gp_mem, struct t10_alua_lu_gp *lu_gp) { spin_lock(&lu_gp->lu_gp_lock); lu_gp_mem->lu_gp = lu_gp; lu_gp_mem->lu_gp_assoc = 1; list_add_tail(&lu_gp_mem->lu_gp_mem_list, &lu_gp->lu_gp_mem_list); lu_gp->lu_gp_members++; spin_unlock(&lu_gp->lu_gp_lock); } /* * Called with struct t10_alua_lu_gp_member->lu_gp_mem_lock */ void __core_alua_drop_lu_gp_mem( struct t10_alua_lu_gp_member *lu_gp_mem, struct t10_alua_lu_gp *lu_gp) { spin_lock(&lu_gp->lu_gp_lock); list_del(&lu_gp_mem->lu_gp_mem_list); lu_gp_mem->lu_gp = NULL; lu_gp_mem->lu_gp_assoc = 0; lu_gp->lu_gp_members--; spin_unlock(&lu_gp->lu_gp_lock); } struct t10_alua_tg_pt_gp *core_alua_allocate_tg_pt_gp(struct se_device *dev, const char *name, int def_group) { struct t10_alua_tg_pt_gp *tg_pt_gp; tg_pt_gp = kmem_cache_zalloc(t10_alua_tg_pt_gp_cache, GFP_KERNEL); if (!tg_pt_gp) { pr_err("Unable to allocate struct t10_alua_tg_pt_gp\n"); return NULL; } INIT_LIST_HEAD(&tg_pt_gp->tg_pt_gp_list); INIT_LIST_HEAD(&tg_pt_gp->tg_pt_gp_lun_list); mutex_init(&tg_pt_gp->tg_pt_gp_md_mutex); spin_lock_init(&tg_pt_gp->tg_pt_gp_lock); atomic_set(&tg_pt_gp->tg_pt_gp_ref_cnt, 0); INIT_DELAYED_WORK(&tg_pt_gp->tg_pt_gp_transition_work, core_alua_do_transition_tg_pt_work); tg_pt_gp->tg_pt_gp_dev = dev; atomic_set(&tg_pt_gp->tg_pt_gp_alua_access_state, ALUA_ACCESS_STATE_ACTIVE_OPTIMIZED); /* * Enable both explicit and implicit ALUA support by default */ tg_pt_gp->tg_pt_gp_alua_access_type = TPGS_EXPLICIT_ALUA | TPGS_IMPLICIT_ALUA; /* * Set the default Active/NonOptimized Delay in milliseconds */ tg_pt_gp->tg_pt_gp_nonop_delay_msecs = ALUA_DEFAULT_NONOP_DELAY_MSECS; tg_pt_gp->tg_pt_gp_trans_delay_msecs = ALUA_DEFAULT_TRANS_DELAY_MSECS; tg_pt_gp->tg_pt_gp_implicit_trans_secs = ALUA_DEFAULT_IMPLICIT_TRANS_SECS; /* * Enable all supported states */ tg_pt_gp->tg_pt_gp_alua_supported_states = ALUA_T_SUP | ALUA_O_SUP | ALUA_U_SUP | ALUA_S_SUP | ALUA_AN_SUP | ALUA_AO_SUP; if (def_group) { spin_lock(&dev->t10_alua.tg_pt_gps_lock); tg_pt_gp->tg_pt_gp_id = dev->t10_alua.alua_tg_pt_gps_counter++; tg_pt_gp->tg_pt_gp_valid_id = 1; dev->t10_alua.alua_tg_pt_gps_count++; list_add_tail(&tg_pt_gp->tg_pt_gp_list, &dev->t10_alua.tg_pt_gps_list); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); } return tg_pt_gp; } int core_alua_set_tg_pt_gp_id( struct t10_alua_tg_pt_gp *tg_pt_gp, u16 tg_pt_gp_id) { struct se_device *dev = tg_pt_gp->tg_pt_gp_dev; struct t10_alua_tg_pt_gp *tg_pt_gp_tmp; u16 tg_pt_gp_id_tmp; /* * The tg_pt_gp->tg_pt_gp_id may only be set once.. */ if (tg_pt_gp->tg_pt_gp_valid_id) { pr_warn("ALUA TG PT Group already has a valid ID," " ignoring request\n"); return -EINVAL; } spin_lock(&dev->t10_alua.tg_pt_gps_lock); if (dev->t10_alua.alua_tg_pt_gps_count == 0x0000ffff) { pr_err("Maximum ALUA alua_tg_pt_gps_count:" " 0x0000ffff reached\n"); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); kmem_cache_free(t10_alua_tg_pt_gp_cache, tg_pt_gp); return -ENOSPC; } again: tg_pt_gp_id_tmp = (tg_pt_gp_id != 0) ? tg_pt_gp_id : dev->t10_alua.alua_tg_pt_gps_counter++; list_for_each_entry(tg_pt_gp_tmp, &dev->t10_alua.tg_pt_gps_list, tg_pt_gp_list) { if (tg_pt_gp_tmp->tg_pt_gp_id == tg_pt_gp_id_tmp) { if (!tg_pt_gp_id) { goto again; } pr_err("ALUA Target Port Group ID: %hu already" " exists, ignoring request\n", tg_pt_gp_id); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); return -EINVAL; } } tg_pt_gp->tg_pt_gp_id = tg_pt_gp_id_tmp; tg_pt_gp->tg_pt_gp_valid_id = 1; list_add_tail(&tg_pt_gp->tg_pt_gp_list, &dev->t10_alua.tg_pt_gps_list); dev->t10_alua.alua_tg_pt_gps_count++; spin_unlock(&dev->t10_alua.tg_pt_gps_lock); return 0; } void core_alua_free_tg_pt_gp( struct t10_alua_tg_pt_gp *tg_pt_gp) { struct se_device *dev = tg_pt_gp->tg_pt_gp_dev; struct se_lun *lun, *next; /* * Once we have reached this point, config_item_put() has already * been called from target_core_alua_drop_tg_pt_gp(). * * Here we remove *tg_pt_gp from the global list so that * no associations *OR* explicit ALUA via SET_TARGET_PORT_GROUPS * can be made while we are releasing struct t10_alua_tg_pt_gp. */ spin_lock(&dev->t10_alua.tg_pt_gps_lock); list_del(&tg_pt_gp->tg_pt_gp_list); dev->t10_alua.alua_tg_pt_gps_counter--; spin_unlock(&dev->t10_alua.tg_pt_gps_lock); flush_delayed_work(&tg_pt_gp->tg_pt_gp_transition_work); /* * Allow a struct t10_alua_tg_pt_gp_member * referenced by * core_alua_get_tg_pt_gp_by_name() in * target_core_configfs.c:target_core_store_alua_tg_pt_gp() * to be released with core_alua_put_tg_pt_gp_from_name(). */ while (atomic_read(&tg_pt_gp->tg_pt_gp_ref_cnt)) { cpu_relax(); } /* * Release reference to struct t10_alua_tg_pt_gp from all associated * struct se_port. */ spin_lock(&tg_pt_gp->tg_pt_gp_lock); list_for_each_entry_safe(lun, next, &tg_pt_gp->tg_pt_gp_lun_list, lun_tg_pt_gp_link) { list_del_init(&lun->lun_tg_pt_gp_link); tg_pt_gp->tg_pt_gp_members--; spin_unlock(&tg_pt_gp->tg_pt_gp_lock); /* * If the passed tg_pt_gp does NOT match the default_tg_pt_gp, * assume we want to re-associate a given tg_pt_gp_mem with * default_tg_pt_gp. */ spin_lock(&lun->lun_tg_pt_gp_lock); if (tg_pt_gp != dev->t10_alua.default_tg_pt_gp) { __target_attach_tg_pt_gp(lun, dev->t10_alua.default_tg_pt_gp); } else { lun->lun_tg_pt_gp = NULL; } spin_unlock(&lun->lun_tg_pt_gp_lock); spin_lock(&tg_pt_gp->tg_pt_gp_lock); } spin_unlock(&tg_pt_gp->tg_pt_gp_lock); kmem_cache_free(t10_alua_tg_pt_gp_cache, tg_pt_gp); } static struct t10_alua_tg_pt_gp *core_alua_get_tg_pt_gp_by_name( struct se_device *dev, const char *name) { struct t10_alua_tg_pt_gp *tg_pt_gp; struct config_item *ci; spin_lock(&dev->t10_alua.tg_pt_gps_lock); list_for_each_entry(tg_pt_gp, &dev->t10_alua.tg_pt_gps_list, tg_pt_gp_list) { if (!tg_pt_gp->tg_pt_gp_valid_id) { continue; } ci = &tg_pt_gp->tg_pt_gp_group.cg_item; if (!strcmp(config_item_name(ci), name)) { atomic_inc(&tg_pt_gp->tg_pt_gp_ref_cnt); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); return tg_pt_gp; } } spin_unlock(&dev->t10_alua.tg_pt_gps_lock); return NULL; } static void core_alua_put_tg_pt_gp_from_name( struct t10_alua_tg_pt_gp *tg_pt_gp) { struct se_device *dev = tg_pt_gp->tg_pt_gp_dev; spin_lock(&dev->t10_alua.tg_pt_gps_lock); atomic_dec(&tg_pt_gp->tg_pt_gp_ref_cnt); spin_unlock(&dev->t10_alua.tg_pt_gps_lock); } static void __target_attach_tg_pt_gp(struct se_lun *lun, struct t10_alua_tg_pt_gp *tg_pt_gp) { struct se_dev_entry *se_deve; assert_spin_locked(&lun->lun_tg_pt_gp_lock); spin_lock(&tg_pt_gp->tg_pt_gp_lock); lun->lun_tg_pt_gp = tg_pt_gp; list_add_tail(&lun->lun_tg_pt_gp_link, &tg_pt_gp->tg_pt_gp_lun_list); tg_pt_gp->tg_pt_gp_members++; spin_lock(&lun->lun_deve_lock); list_for_each_entry(se_deve, &lun->lun_deve_list, lun_link) core_scsi3_ua_allocate(se_deve, 0x3f, ASCQ_3FH_INQUIRY_DATA_HAS_CHANGED); spin_unlock(&lun->lun_deve_lock); spin_unlock(&tg_pt_gp->tg_pt_gp_lock); } void target_attach_tg_pt_gp(struct se_lun *lun, struct t10_alua_tg_pt_gp *tg_pt_gp) { spin_lock(&lun->lun_tg_pt_gp_lock); __target_attach_tg_pt_gp(lun, tg_pt_gp); spin_unlock(&lun->lun_tg_pt_gp_lock); } static void __target_detach_tg_pt_gp(struct se_lun *lun, struct t10_alua_tg_pt_gp *tg_pt_gp) { assert_spin_locked(&lun->lun_tg_pt_gp_lock); spin_lock(&tg_pt_gp->tg_pt_gp_lock); list_del_init(&lun->lun_tg_pt_gp_link); tg_pt_gp->tg_pt_gp_members--; spin_unlock(&tg_pt_gp->tg_pt_gp_lock); lun->lun_tg_pt_gp = NULL; } void target_detach_tg_pt_gp(struct se_lun *lun) { struct t10_alua_tg_pt_gp *tg_pt_gp; spin_lock(&lun->lun_tg_pt_gp_lock); tg_pt_gp = lun->lun_tg_pt_gp; if (tg_pt_gp) { __target_detach_tg_pt_gp(lun, tg_pt_gp); } spin_unlock(&lun->lun_tg_pt_gp_lock); } ssize_t core_alua_show_tg_pt_gp_info(struct se_lun *lun, char *page) { struct config_item *tg_pt_ci; struct t10_alua_tg_pt_gp *tg_pt_gp; ssize_t len = 0; spin_lock(&lun->lun_tg_pt_gp_lock); tg_pt_gp = lun->lun_tg_pt_gp; if (tg_pt_gp) { tg_pt_ci = &tg_pt_gp->tg_pt_gp_group.cg_item; len += sprintf(page, "TG Port Alias: %s\nTG Port Group ID:" " %hu\nTG Port Primary Access State: %s\nTG Port " "Primary Access Status: %s\nTG Port Secondary Access" " State: %s\nTG Port Secondary Access Status: %s\n", config_item_name(tg_pt_ci), tg_pt_gp->tg_pt_gp_id, core_alua_dump_state(atomic_read( &tg_pt_gp->tg_pt_gp_alua_access_state)), core_alua_dump_status( tg_pt_gp->tg_pt_gp_alua_access_status), atomic_read(&lun->lun_tg_pt_secondary_offline) ? "Offline" : "None", core_alua_dump_status(lun->lun_tg_pt_secondary_stat)); } spin_unlock(&lun->lun_tg_pt_gp_lock); return len; } ssize_t core_alua_store_tg_pt_gp_info( struct se_lun *lun, const char *page, size_t count) { struct se_portal_group *tpg = lun->lun_tpg; /* * rcu_dereference_raw protected by se_lun->lun_group symlink * reference to se_device->dev_group. */ struct se_device *dev = rcu_dereference_raw(lun->lun_se_dev); struct t10_alua_tg_pt_gp *tg_pt_gp = NULL, *tg_pt_gp_new = NULL; unsigned char buf[TG_PT_GROUP_NAME_BUF]; int move = 0; if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH || (dev->se_hba->hba_flags & HBA_FLAGS_INTERNAL_USE)) { return -ENODEV; } if (count > TG_PT_GROUP_NAME_BUF) { pr_err("ALUA Target Port Group alias too large!\n"); return -EINVAL; } memset(buf, 0, TG_PT_GROUP_NAME_BUF); memcpy(buf, page, count); /* * Any ALUA target port group alias besides "NULL" means we will be * making a new group association. */ if (strcmp(strstrip(buf), "NULL")) { /* * core_alua_get_tg_pt_gp_by_name() will increment reference to * struct t10_alua_tg_pt_gp. This reference is released with * core_alua_put_tg_pt_gp_from_name() below. */ tg_pt_gp_new = core_alua_get_tg_pt_gp_by_name(dev, strstrip(buf)); if (!tg_pt_gp_new) { return -ENODEV; } } spin_lock(&lun->lun_tg_pt_gp_lock); tg_pt_gp = lun->lun_tg_pt_gp; if (tg_pt_gp) { /* * Clearing an existing tg_pt_gp association, and replacing * with the default_tg_pt_gp. */ if (!tg_pt_gp_new) { pr_debug("Target_Core_ConfigFS: Moving" " %s/tpgt_%hu/%s from ALUA Target Port Group:" " alua/%s, ID: %hu back to" " default_tg_pt_gp\n", tpg->se_tpg_tfo->tpg_get_wwn(tpg), tpg->se_tpg_tfo->tpg_get_tag(tpg), config_item_name(&lun->lun_group.cg_item), config_item_name( &tg_pt_gp->tg_pt_gp_group.cg_item), tg_pt_gp->tg_pt_gp_id); __target_detach_tg_pt_gp(lun, tg_pt_gp); __target_attach_tg_pt_gp(lun, dev->t10_alua.default_tg_pt_gp); spin_unlock(&lun->lun_tg_pt_gp_lock); return count; } __target_detach_tg_pt_gp(lun, tg_pt_gp); move = 1; } __target_attach_tg_pt_gp(lun, tg_pt_gp_new); spin_unlock(&lun->lun_tg_pt_gp_lock); pr_debug("Target_Core_ConfigFS: %s %s/tpgt_%hu/%s to ALUA" " Target Port Group: alua/%s, ID: %hu\n", (move) ? "Moving" : "Adding", tpg->se_tpg_tfo->tpg_get_wwn(tpg), tpg->se_tpg_tfo->tpg_get_tag(tpg), config_item_name(&lun->lun_group.cg_item), config_item_name(&tg_pt_gp_new->tg_pt_gp_group.cg_item), tg_pt_gp_new->tg_pt_gp_id); core_alua_put_tg_pt_gp_from_name(tg_pt_gp_new); return count; } ssize_t core_alua_show_access_type( struct t10_alua_tg_pt_gp *tg_pt_gp, char *page) { if ((tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_EXPLICIT_ALUA) && (tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_IMPLICIT_ALUA)) { return sprintf(page, "Implicit and Explicit\n"); } else if (tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_IMPLICIT_ALUA) { return sprintf(page, "Implicit\n"); } else if (tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_EXPLICIT_ALUA) { return sprintf(page, "Explicit\n"); } else { return sprintf(page, "None\n"); } } ssize_t core_alua_store_access_type( struct t10_alua_tg_pt_gp *tg_pt_gp, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract alua_access_type\n"); return ret; } if ((tmp != 0) && (tmp != 1) && (tmp != 2) && (tmp != 3)) { pr_err("Illegal value for alua_access_type:" " %lu\n", tmp); return -EINVAL; } if (tmp == 3) tg_pt_gp->tg_pt_gp_alua_access_type = TPGS_IMPLICIT_ALUA | TPGS_EXPLICIT_ALUA; else if (tmp == 2) { tg_pt_gp->tg_pt_gp_alua_access_type = TPGS_EXPLICIT_ALUA; } else if (tmp == 1) { tg_pt_gp->tg_pt_gp_alua_access_type = TPGS_IMPLICIT_ALUA; } else { tg_pt_gp->tg_pt_gp_alua_access_type = 0; } return count; } ssize_t core_alua_show_nonop_delay_msecs( struct t10_alua_tg_pt_gp *tg_pt_gp, char *page) { return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_nonop_delay_msecs); } ssize_t core_alua_store_nonop_delay_msecs( struct t10_alua_tg_pt_gp *tg_pt_gp, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract nonop_delay_msecs\n"); return ret; } if (tmp > ALUA_MAX_NONOP_DELAY_MSECS) { pr_err("Passed nonop_delay_msecs: %lu, exceeds" " ALUA_MAX_NONOP_DELAY_MSECS: %d\n", tmp, ALUA_MAX_NONOP_DELAY_MSECS); return -EINVAL; } tg_pt_gp->tg_pt_gp_nonop_delay_msecs = (int)tmp; return count; } ssize_t core_alua_show_trans_delay_msecs( struct t10_alua_tg_pt_gp *tg_pt_gp, char *page) { return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_trans_delay_msecs); } ssize_t core_alua_store_trans_delay_msecs( struct t10_alua_tg_pt_gp *tg_pt_gp, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract trans_delay_msecs\n"); return ret; } if (tmp > ALUA_MAX_TRANS_DELAY_MSECS) { pr_err("Passed trans_delay_msecs: %lu, exceeds" " ALUA_MAX_TRANS_DELAY_MSECS: %d\n", tmp, ALUA_MAX_TRANS_DELAY_MSECS); return -EINVAL; } tg_pt_gp->tg_pt_gp_trans_delay_msecs = (int)tmp; return count; } ssize_t core_alua_show_implicit_trans_secs( struct t10_alua_tg_pt_gp *tg_pt_gp, char *page) { return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_implicit_trans_secs); } ssize_t core_alua_store_implicit_trans_secs( struct t10_alua_tg_pt_gp *tg_pt_gp, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract implicit_trans_secs\n"); return ret; } if (tmp > ALUA_MAX_IMPLICIT_TRANS_SECS) { pr_err("Passed implicit_trans_secs: %lu, exceeds" " ALUA_MAX_IMPLICIT_TRANS_SECS: %d\n", tmp, ALUA_MAX_IMPLICIT_TRANS_SECS); return -EINVAL; } tg_pt_gp->tg_pt_gp_implicit_trans_secs = (int)tmp; return count; } ssize_t core_alua_show_preferred_bit( struct t10_alua_tg_pt_gp *tg_pt_gp, char *page) { return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_pref); } ssize_t core_alua_store_preferred_bit( struct t10_alua_tg_pt_gp *tg_pt_gp, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract preferred ALUA value\n"); return ret; } if ((tmp != 0) && (tmp != 1)) { pr_err("Illegal value for preferred ALUA: %lu\n", tmp); return -EINVAL; } tg_pt_gp->tg_pt_gp_pref = (int)tmp; return count; } ssize_t core_alua_show_offline_bit(struct se_lun *lun, char *page) { return sprintf(page, "%d\n", atomic_read(&lun->lun_tg_pt_secondary_offline)); } ssize_t core_alua_store_offline_bit( struct se_lun *lun, const char *page, size_t count) { /* * rcu_dereference_raw protected by se_lun->lun_group symlink * reference to se_device->dev_group. */ struct se_device *dev = rcu_dereference_raw(lun->lun_se_dev); unsigned long tmp; int ret; if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH || (dev->se_hba->hba_flags & HBA_FLAGS_INTERNAL_USE)) { return -ENODEV; } ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract alua_tg_pt_offline value\n"); return ret; } if ((tmp != 0) && (tmp != 1)) { pr_err("Illegal value for alua_tg_pt_offline: %lu\n", tmp); return -EINVAL; } ret = core_alua_set_tg_pt_secondary_state(lun, 0, (int)tmp); if (ret < 0) { return -EINVAL; } return count; } ssize_t core_alua_show_secondary_status( struct se_lun *lun, char *page) { return sprintf(page, "%d\n", lun->lun_tg_pt_secondary_stat); } ssize_t core_alua_store_secondary_status( struct se_lun *lun, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract alua_tg_pt_status\n"); return ret; } if ((tmp != ALUA_STATUS_NONE) && (tmp != ALUA_STATUS_ALTERED_BY_EXPLICIT_STPG) && (tmp != ALUA_STATUS_ALTERED_BY_IMPLICIT_ALUA)) { pr_err("Illegal value for alua_tg_pt_status: %lu\n", tmp); return -EINVAL; } lun->lun_tg_pt_secondary_stat = (int)tmp; return count; } ssize_t core_alua_show_secondary_write_metadata( struct se_lun *lun, char *page) { return sprintf(page, "%d\n", lun->lun_tg_pt_secondary_write_md); } ssize_t core_alua_store_secondary_write_metadata( struct se_lun *lun, const char *page, size_t count) { unsigned long tmp; int ret; ret = kstrtoul(page, 0, &tmp); if (ret < 0) { pr_err("Unable to extract alua_tg_pt_write_md\n"); return ret; } if ((tmp != 0) && (tmp != 1)) { pr_err("Illegal value for alua_tg_pt_write_md:" " %lu\n", tmp); return -EINVAL; } lun->lun_tg_pt_secondary_write_md = (int)tmp; return count; } int core_setup_alua(struct se_device *dev) { if (!(dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH) && !(dev->se_hba->hba_flags & HBA_FLAGS_INTERNAL_USE)) { struct t10_alua_lu_gp_member *lu_gp_mem; /* * Associate this struct se_device with the default ALUA * LUN Group. */ lu_gp_mem = core_alua_allocate_lu_gp_mem(dev); if (IS_ERR(lu_gp_mem)) { return PTR_ERR(lu_gp_mem); } spin_lock(&lu_gp_mem->lu_gp_mem_lock); __core_alua_attach_lu_gp_mem(lu_gp_mem, default_lu_gp); spin_unlock(&lu_gp_mem->lu_gp_mem_lock); pr_debug("%s: Adding to default ALUA LU Group:" " core/alua/lu_gps/default_lu_gp\n", dev->transport->name); } return 0; }
gpl-3.0
p01arst0rm/decorum-linux
_resources/kernels/xnu-x86/bsd/net/nwk_wq.c
1
4318
/* * Copyright (c) 2016 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #include <stddef.h> #include <kern/debug.h> #include <kern/locks.h> #include <kern/thread.h> #include <kern/thread_call.h> #include <net/nwk_wq.h> #include <sys/proc_internal.h> #include <sys/systm.h> #include <sys/mcache.h> MALLOC_DEFINE(M_NWKWQ, "nwkwq", "Network work-queue"); static TAILQ_HEAD(, nwk_wq_entry) nwk_wq_head; decl_lck_mtx_data(static, nwk_wq_lock); /* Lock group and attributes */ static lck_grp_attr_t *nwk_wq_lock_grp_attributes = NULL; static lck_grp_t *nwk_wq_lock_group = NULL; /* Lock and lock attributes */ static lck_attr_t *nwk_wq_lock_attributes = NULL; decl_lck_mtx_data(static, nwk_wq_lock); /* Wait channel for Network work queue */ static void *nwk_wq_waitch = NULL; static void nwk_wq_thread_func(void *, wait_result_t); static int nwk_wq_thread_cont(int err); static void nwk_wq_thread_func(void *v, wait_result_t w); void nwk_wq_init (void) { thread_t nwk_wq_thread = THREAD_NULL; TAILQ_INIT(&nwk_wq_head); nwk_wq_lock_grp_attributes = lck_grp_attr_alloc_init(); nwk_wq_lock_group = lck_grp_alloc_init("Network work queue lock", nwk_wq_lock_grp_attributes); nwk_wq_lock_attributes = lck_attr_alloc_init(); lck_mtx_init(&nwk_wq_lock, nwk_wq_lock_group, nwk_wq_lock_attributes); if (kernel_thread_start(nwk_wq_thread_func, NULL, &nwk_wq_thread) != KERN_SUCCESS) { panic_plain("%s: couldn't create network work queue thread", __func__); /* NOTREACHED */ } thread_deallocate(nwk_wq_thread); } static int nwk_wq_thread_cont(int err) { TAILQ_HEAD(, nwk_wq_entry) temp_nwk_wq_head; struct nwk_wq_entry *nwk_item; struct nwk_wq_entry *nwk_item_next; #pragma unused(err) for (;;) { nwk_item = NULL; nwk_item_next = NULL; TAILQ_INIT(&temp_nwk_wq_head); LCK_MTX_ASSERT(&nwk_wq_lock, LCK_MTX_ASSERT_OWNED); while (TAILQ_FIRST(&nwk_wq_head) == NULL) { (void) msleep0(&nwk_wq_waitch, &nwk_wq_lock, (PZERO - 1), "nwk_wq_thread_cont", 0, nwk_wq_thread_cont); /* NOTREACHED */ } TAILQ_SWAP(&temp_nwk_wq_head, &nwk_wq_head, nwk_wq_entry, nwk_wq_link); VERIFY(TAILQ_EMPTY(&nwk_wq_head)); lck_mtx_unlock(&nwk_wq_lock); VERIFY(TAILQ_FIRST(&temp_nwk_wq_head) != NULL); TAILQ_FOREACH_SAFE(nwk_item, &temp_nwk_wq_head, nwk_wq_link, nwk_item_next) { nwk_item->func(nwk_item->arg); if (nwk_item->is_arg_managed == FALSE) FREE(nwk_item->arg, M_NWKWQ); FREE(nwk_item, M_NWKWQ); } lck_mtx_lock(&nwk_wq_lock); } } static void nwk_wq_thread_func(void *v, wait_result_t w) { #pragma unused(v, w) lck_mtx_lock(&nwk_wq_lock); (void) msleep0(&nwk_wq_waitch, &nwk_wq_lock, (PZERO - 1), "nwk_wq_thread_func", 0, nwk_wq_thread_cont); /* * msleep0() shouldn't have returned as PCATCH was not set; * therefore assert in this case. */ lck_mtx_unlock(&nwk_wq_lock); VERIFY(0); } void nwk_wq_enqueue(struct nwk_wq_entry *nwk_item) { lck_mtx_lock(&nwk_wq_lock); TAILQ_INSERT_TAIL(&nwk_wq_head, nwk_item, nwk_wq_link); lck_mtx_unlock(&nwk_wq_lock); wakeup((caddr_t)&nwk_wq_waitch); }
gpl-3.0
acetcom/cellwire
lib/nas/eps/ies.c
1
123007
/* * The MIT License * * Copyright (C) 2019,2020 by Sukchan Lee <acetcom@gmail.com> * * This file is part of Open5GS. * * 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. * * 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 THE AUTHORS OR COPYRIGHT HOLDERS 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. */ /******************************************************************************* * This file had been created by nas-message.py script v0.1.0 * Please do not modify this file but regenerate it via script. * Created on: 2020-08-16 17:47:29.412678 by acetcom * from 24301-g40.docx ******************************************************************************/ #include "ogs-nas-eps.h" int ogs_nas_eps_encode_optional_type(ogs_pkbuf_t *pkbuf, uint8_t type) { uint16_t size = sizeof(uint8_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &type, size); return size; } /* 9.9.2.0 Additional information * O TLV 3-n */ int ogs_nas_eps_decode_additional_information(ogs_nas_additional_information_t *additional_information, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_additional_information_t *source = (ogs_nas_additional_information_t *)pkbuf->data; additional_information->length = source->length; size = additional_information->length + sizeof(additional_information->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(additional_information, pkbuf->data - size, size); ogs_trace(" ADDITIONAL_INFORMATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_additional_information(ogs_pkbuf_t *pkbuf, ogs_nas_additional_information_t *additional_information) { uint16_t size = additional_information->length + sizeof(additional_information->length); ogs_nas_additional_information_t target; memcpy(&target, additional_information, sizeof(ogs_nas_additional_information_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" ADDITIONAL_INFORMATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.0A Device properties * O TV 1 */ int ogs_nas_eps_decode_device_properties(ogs_nas_device_properties_t *device_properties, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_device_properties_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(device_properties, pkbuf->data - size, size); ogs_trace(" DEVICE_PROPERTIES - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_device_properties(ogs_pkbuf_t *pkbuf, ogs_nas_device_properties_t *device_properties) { uint16_t size = sizeof(ogs_nas_device_properties_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, device_properties, size); ogs_trace(" DEVICE_PROPERTIES - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.1 EPS bearer context status * O TLV 4 */ int ogs_nas_eps_decode_eps_bearer_context_status(ogs_nas_eps_bearer_context_status_t *eps_bearer_context_status, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_eps_bearer_context_status_t *source = (ogs_nas_eps_bearer_context_status_t *)pkbuf->data; eps_bearer_context_status->length = source->length; size = eps_bearer_context_status->length + sizeof(eps_bearer_context_status->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_bearer_context_status, pkbuf->data - size, size); ogs_trace(" EPS_BEARER_CONTEXT_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_bearer_context_status(ogs_pkbuf_t *pkbuf, ogs_nas_eps_bearer_context_status_t *eps_bearer_context_status) { uint16_t size = eps_bearer_context_status->length + sizeof(eps_bearer_context_status->length); ogs_nas_eps_bearer_context_status_t target; memcpy(&target, eps_bearer_context_status, sizeof(ogs_nas_eps_bearer_context_status_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_BEARER_CONTEXT_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.10 Supported Codec List * O TLV 5-n */ int ogs_nas_eps_decode_supported_codec_list(ogs_nas_supported_codec_list_t *supported_codec_list, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_supported_codec_list_t *source = (ogs_nas_supported_codec_list_t *)pkbuf->data; supported_codec_list->length = source->length; size = supported_codec_list->length + sizeof(supported_codec_list->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(supported_codec_list, pkbuf->data - size, size); ogs_trace(" SUPPORTED_CODEC_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_supported_codec_list(ogs_pkbuf_t *pkbuf, ogs_nas_supported_codec_list_t *supported_codec_list) { uint16_t size = supported_codec_list->length + sizeof(supported_codec_list->length); ogs_nas_supported_codec_list_t target; memcpy(&target, supported_codec_list, sizeof(ogs_nas_supported_codec_list_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" SUPPORTED_CODEC_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.2 Location area identification * O TV 6 */ int ogs_nas_eps_decode_location_area_identification(ogs_nas_location_area_identification_t *location_area_identification, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_location_area_identification_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(location_area_identification, pkbuf->data - size, size); location_area_identification->lac = be16toh(location_area_identification->lac); ogs_trace(" LOCATION_AREA_IDENTIFICATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_location_area_identification(ogs_pkbuf_t *pkbuf, ogs_nas_location_area_identification_t *location_area_identification) { uint16_t size = sizeof(ogs_nas_location_area_identification_t); ogs_nas_location_area_identification_t target; memcpy(&target, location_area_identification, size); target.lac = htobe16(location_area_identification->lac); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" LOCATION_AREA_IDENTIFICATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.3 Mobile identity * O TLV 7-10 */ int ogs_nas_eps_decode_mobile_identity(ogs_nas_mobile_identity_t *mobile_identity, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_mobile_identity_t *source = (ogs_nas_mobile_identity_t *)pkbuf->data; mobile_identity->length = source->length; size = mobile_identity->length + sizeof(mobile_identity->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(mobile_identity, pkbuf->data - size, size); if (mobile_identity->tmsi.type == OGS_NAS_MOBILE_IDENTITY_TMSI) { mobile_identity->tmsi.tmsi = be32toh(mobile_identity->tmsi.tmsi); } ogs_trace(" MOBILE_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_mobile_identity(ogs_pkbuf_t *pkbuf, ogs_nas_mobile_identity_t *mobile_identity) { uint16_t size = mobile_identity->length + sizeof(mobile_identity->length); ogs_nas_mobile_identity_t target; memcpy(&target, mobile_identity, sizeof(ogs_nas_mobile_identity_t)); if (mobile_identity->tmsi.type == OGS_NAS_MOBILE_IDENTITY_TMSI) { target.tmsi.tmsi = htobe32(mobile_identity->tmsi.tmsi); target.tmsi.spare = 0xf; } ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" MOBILE_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.4 Mobile station classmark 2 * O TLV 5 */ int ogs_nas_eps_decode_mobile_station_classmark_2(ogs_nas_mobile_station_classmark_2_t *mobile_station_classmark_2, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_mobile_station_classmark_2_t *source = (ogs_nas_mobile_station_classmark_2_t *)pkbuf->data; mobile_station_classmark_2->length = source->length; size = mobile_station_classmark_2->length + sizeof(mobile_station_classmark_2->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(mobile_station_classmark_2, pkbuf->data - size, size); ogs_trace(" MOBILE_STATION_CLASSMARK_2 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_mobile_station_classmark_2(ogs_pkbuf_t *pkbuf, ogs_nas_mobile_station_classmark_2_t *mobile_station_classmark_2) { uint16_t size = mobile_station_classmark_2->length + sizeof(mobile_station_classmark_2->length); ogs_nas_mobile_station_classmark_2_t target; memcpy(&target, mobile_station_classmark_2, sizeof(ogs_nas_mobile_station_classmark_2_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" MOBILE_STATION_CLASSMARK_2 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.5 Mobile station classmark 3 * O TLV 2-34 */ int ogs_nas_eps_decode_mobile_station_classmark_3(ogs_nas_mobile_station_classmark_3_t *mobile_station_classmark_3, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_mobile_station_classmark_3_t *source = (ogs_nas_mobile_station_classmark_3_t *)pkbuf->data; mobile_station_classmark_3->length = source->length; size = mobile_station_classmark_3->length + sizeof(mobile_station_classmark_3->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(mobile_station_classmark_3, pkbuf->data - size, size); ogs_trace(" MOBILE_STATION_CLASSMARK_3 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_mobile_station_classmark_3(ogs_pkbuf_t *pkbuf, ogs_nas_mobile_station_classmark_3_t *mobile_station_classmark_3) { uint16_t size = mobile_station_classmark_3->length + sizeof(mobile_station_classmark_3->length); ogs_nas_mobile_station_classmark_3_t target; memcpy(&target, mobile_station_classmark_3, sizeof(ogs_nas_mobile_station_classmark_3_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" MOBILE_STATION_CLASSMARK_3 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.2.8 PLMN list * O TLV 5-47 */ int ogs_nas_eps_decode_plmn_list(ogs_nas_plmn_list_t *plmn_list, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_plmn_list_t *source = (ogs_nas_plmn_list_t *)pkbuf->data; plmn_list->length = source->length; size = plmn_list->length + sizeof(plmn_list->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(plmn_list, pkbuf->data - size, size); ogs_trace(" PLMN_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_plmn_list(ogs_pkbuf_t *pkbuf, ogs_nas_plmn_list_t *plmn_list) { uint16_t size = plmn_list->length + sizeof(plmn_list->length); ogs_nas_plmn_list_t target; memcpy(&target, plmn_list, sizeof(ogs_nas_plmn_list_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" PLMN_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.0A Additional update result * O TV 1 */ int ogs_nas_eps_decode_additional_update_result(ogs_nas_additional_update_result_t *additional_update_result, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_additional_update_result_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(additional_update_result, pkbuf->data - size, size); ogs_trace(" ADDITIONAL_UPDATE_RESULT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_additional_update_result(ogs_pkbuf_t *pkbuf, ogs_nas_additional_update_result_t *additional_update_result) { uint16_t size = sizeof(ogs_nas_additional_update_result_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, additional_update_result, size); ogs_trace(" ADDITIONAL_UPDATE_RESULT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.0B Additional update type * O TV 1 */ int ogs_nas_eps_decode_additional_update_type(ogs_nas_additional_update_type_t *additional_update_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_additional_update_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(additional_update_type, pkbuf->data - size, size); ogs_trace(" ADDITIONAL_UPDATE_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_additional_update_type(ogs_pkbuf_t *pkbuf, ogs_nas_additional_update_type_t *additional_update_type) { uint16_t size = sizeof(ogs_nas_additional_update_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, additional_update_type, size); ogs_trace(" ADDITIONAL_UPDATE_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.1 Authentication failure parameter * O TLV 16 */ int ogs_nas_eps_decode_authentication_failure_parameter(ogs_nas_authentication_failure_parameter_t *authentication_failure_parameter, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_authentication_failure_parameter_t *source = (ogs_nas_authentication_failure_parameter_t *)pkbuf->data; authentication_failure_parameter->length = source->length; size = authentication_failure_parameter->length + sizeof(authentication_failure_parameter->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(authentication_failure_parameter, pkbuf->data - size, size); ogs_trace(" AUTHENTICATION_FAILURE_PARAMETER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_authentication_failure_parameter(ogs_pkbuf_t *pkbuf, ogs_nas_authentication_failure_parameter_t *authentication_failure_parameter) { uint16_t size = authentication_failure_parameter->length + sizeof(authentication_failure_parameter->length); ogs_nas_authentication_failure_parameter_t target; memcpy(&target, authentication_failure_parameter, sizeof(ogs_nas_authentication_failure_parameter_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" AUTHENTICATION_FAILURE_PARAMETER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.10 EPS attach result * M V 1/2 */ int ogs_nas_eps_decode_eps_attach_result(ogs_nas_eps_attach_result_t *eps_attach_result, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_eps_attach_result_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_attach_result, pkbuf->data - size, size); ogs_trace(" EPS_ATTACH_RESULT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_attach_result(ogs_pkbuf_t *pkbuf, ogs_nas_eps_attach_result_t *eps_attach_result) { uint16_t size = sizeof(ogs_nas_eps_attach_result_t); ogs_nas_eps_attach_result_t target; memcpy(&target, eps_attach_result, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_ATTACH_RESULT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.11 EPS attach type * M V 1/2 */ int ogs_nas_eps_decode_eps_attach_type(ogs_nas_eps_attach_type_t *eps_attach_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_eps_attach_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_attach_type, pkbuf->data - size, size); ogs_trace(" EPS_ATTACH_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_attach_type(ogs_pkbuf_t *pkbuf, ogs_nas_eps_attach_type_t *eps_attach_type) { uint16_t size = sizeof(ogs_nas_eps_attach_type_t); ogs_nas_eps_attach_type_t target; memcpy(&target, eps_attach_type, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_ATTACH_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.12 EPS mobile identity * M LV 5-12 */ int ogs_nas_eps_decode_eps_mobile_identity(ogs_nas_eps_mobile_identity_t *eps_mobile_identity, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_eps_mobile_identity_t *source = (ogs_nas_eps_mobile_identity_t *)pkbuf->data; eps_mobile_identity->length = source->length; size = eps_mobile_identity->length + sizeof(eps_mobile_identity->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_mobile_identity, pkbuf->data - size, size); if (eps_mobile_identity->guti.type == OGS_NAS_EPS_MOBILE_IDENTITY_GUTI) { eps_mobile_identity->guti.mme_gid = be16toh(eps_mobile_identity->guti.mme_gid); eps_mobile_identity->guti.m_tmsi = be32toh(eps_mobile_identity->guti.m_tmsi); } ogs_trace(" EPS_MOBILE_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_mobile_identity(ogs_pkbuf_t *pkbuf, ogs_nas_eps_mobile_identity_t *eps_mobile_identity) { uint16_t size = eps_mobile_identity->length + sizeof(eps_mobile_identity->length); ogs_nas_eps_mobile_identity_t target; memcpy(&target, eps_mobile_identity, sizeof(ogs_nas_eps_mobile_identity_t)); if (target.guti.type == OGS_NAS_EPS_MOBILE_IDENTITY_GUTI) { target.guti.spare = 0xf; target.guti.mme_gid = htobe16(eps_mobile_identity->guti.mme_gid); target.guti.m_tmsi = htobe32(eps_mobile_identity->guti.m_tmsi); } ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_MOBILE_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.12A EPS network feature support * O TLV 3-4 */ int ogs_nas_eps_decode_eps_network_feature_support(ogs_nas_eps_network_feature_support_t *eps_network_feature_support, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_eps_network_feature_support_t *source = (ogs_nas_eps_network_feature_support_t *)pkbuf->data; eps_network_feature_support->length = source->length; size = eps_network_feature_support->length + sizeof(eps_network_feature_support->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_network_feature_support, pkbuf->data - size, size); ogs_trace(" EPS_NETWORK_FEATURE_SUPPORT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_network_feature_support(ogs_pkbuf_t *pkbuf, ogs_nas_eps_network_feature_support_t *eps_network_feature_support) { uint16_t size = eps_network_feature_support->length + sizeof(eps_network_feature_support->length); ogs_nas_eps_network_feature_support_t target; memcpy(&target, eps_network_feature_support, sizeof(ogs_nas_eps_network_feature_support_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_NETWORK_FEATURE_SUPPORT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.13 EPS update result * M V 1/2 */ int ogs_nas_eps_decode_eps_update_result(ogs_nas_eps_update_result_t *eps_update_result, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_eps_update_result_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_update_result, pkbuf->data - size, size); ogs_trace(" EPS_UPDATE_RESULT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_update_result(ogs_pkbuf_t *pkbuf, ogs_nas_eps_update_result_t *eps_update_result) { uint16_t size = sizeof(ogs_nas_eps_update_result_t); ogs_nas_eps_update_result_t target; memcpy(&target, eps_update_result, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_UPDATE_RESULT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.14 EPS update type * M V 1/2 */ int ogs_nas_eps_decode_eps_update_type(ogs_nas_eps_update_type_t *eps_update_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_eps_update_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_update_type, pkbuf->data - size, size); ogs_trace(" EPS_UPDATE_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_update_type(ogs_pkbuf_t *pkbuf, ogs_nas_eps_update_type_t *eps_update_type) { uint16_t size = sizeof(ogs_nas_eps_update_type_t); ogs_nas_eps_update_type_t target; memcpy(&target, eps_update_type, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_UPDATE_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.15 ESM message container * M LV-E 5-n */ int ogs_nas_eps_decode_esm_message_container(ogs_nas_esm_message_container_t *esm_message_container, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_esm_message_container_t *source = (ogs_nas_esm_message_container_t *)pkbuf->data; esm_message_container->length = be16toh(source->length); size = esm_message_container->length + sizeof(esm_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); esm_message_container->buffer = pkbuf->data - size + sizeof(esm_message_container->length); ogs_trace(" ESM_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, (void*)esm_message_container->buffer, esm_message_container->length); return size; } int ogs_nas_eps_encode_esm_message_container(ogs_pkbuf_t *pkbuf, ogs_nas_esm_message_container_t *esm_message_container) { uint16_t size = 0; uint16_t target; ogs_assert(esm_message_container); ogs_assert(esm_message_container->buffer); size = sizeof(esm_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); target = htobe16(esm_message_container->length); memcpy(pkbuf->data - size, &target, size); size = esm_message_container->length; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, esm_message_container->buffer, size); ogs_trace(" ESM_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return esm_message_container->length + sizeof(esm_message_container->length); } /* 9.9.3.16 GPRS timer * M V 1 */ int ogs_nas_eps_decode_gprs_timer(ogs_nas_gprs_timer_t *gprs_timer, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_gprs_timer_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(gprs_timer, pkbuf->data - size, size); ogs_trace(" GPRS_TIMER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_gprs_timer(ogs_pkbuf_t *pkbuf, ogs_nas_gprs_timer_t *gprs_timer) { uint16_t size = sizeof(ogs_nas_gprs_timer_t); ogs_nas_gprs_timer_t target; memcpy(&target, gprs_timer, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" GPRS_TIMER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.16A GPRS timer 2 * O TLV 3 */ int ogs_nas_eps_decode_gprs_timer_2(ogs_nas_gprs_timer_2_t *gprs_timer_2, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_gprs_timer_2_t *source = (ogs_nas_gprs_timer_2_t *)pkbuf->data; gprs_timer_2->length = source->length; size = gprs_timer_2->length + sizeof(gprs_timer_2->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(gprs_timer_2, pkbuf->data - size, size); ogs_trace(" GPRS_TIMER_2 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_gprs_timer_2(ogs_pkbuf_t *pkbuf, ogs_nas_gprs_timer_2_t *gprs_timer_2) { uint16_t size = gprs_timer_2->length + sizeof(gprs_timer_2->length); ogs_nas_gprs_timer_2_t target; memcpy(&target, gprs_timer_2, sizeof(ogs_nas_gprs_timer_2_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" GPRS_TIMER_2 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.16B GPRS timer 3 * O TLV 3 */ int ogs_nas_eps_decode_gprs_timer_3(ogs_nas_gprs_timer_3_t *gprs_timer_3, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_gprs_timer_3_t *source = (ogs_nas_gprs_timer_3_t *)pkbuf->data; gprs_timer_3->length = source->length; size = gprs_timer_3->length + sizeof(gprs_timer_3->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(gprs_timer_3, pkbuf->data - size, size); ogs_trace(" GPRS_TIMER_3 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_gprs_timer_3(ogs_pkbuf_t *pkbuf, ogs_nas_gprs_timer_3_t *gprs_timer_3) { uint16_t size = gprs_timer_3->length + sizeof(gprs_timer_3->length); ogs_nas_gprs_timer_3_t target; memcpy(&target, gprs_timer_3, sizeof(ogs_nas_gprs_timer_3_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" GPRS_TIMER_3 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.17 Identity type 2 * M V 1/2 */ int ogs_nas_eps_decode_identity_type_2(ogs_nas_identity_type_2_t *identity_type_2, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_identity_type_2_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(identity_type_2, pkbuf->data - size, size); ogs_trace(" IDENTITY_TYPE_2 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_identity_type_2(ogs_pkbuf_t *pkbuf, ogs_nas_identity_type_2_t *identity_type_2) { uint16_t size = sizeof(ogs_nas_identity_type_2_t); ogs_nas_identity_type_2_t target; memcpy(&target, identity_type_2, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" IDENTITY_TYPE_2 - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.18 IMEISV request * O TV 1 */ int ogs_nas_eps_decode_imeisv_request(ogs_nas_imeisv_request_t *imeisv_request, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_imeisv_request_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(imeisv_request, pkbuf->data - size, size); ogs_trace(" IMEISV_REQUEST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_imeisv_request(ogs_pkbuf_t *pkbuf, ogs_nas_imeisv_request_t *imeisv_request) { uint16_t size = sizeof(ogs_nas_imeisv_request_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, imeisv_request, size); ogs_trace(" IMEISV_REQUEST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.19 KSI and sequence number * M V 1 */ int ogs_nas_eps_decode_ksi_and_sequence_number(ogs_nas_ksi_and_sequence_number_t *ksi_and_sequence_number, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ksi_and_sequence_number_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ksi_and_sequence_number, pkbuf->data - size, size); ogs_trace(" KSI_AND_SEQUENCE_NUMBER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ksi_and_sequence_number(ogs_pkbuf_t *pkbuf, ogs_nas_ksi_and_sequence_number_t *ksi_and_sequence_number) { uint16_t size = sizeof(ogs_nas_ksi_and_sequence_number_t); ogs_nas_ksi_and_sequence_number_t target; memcpy(&target, ksi_and_sequence_number, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" KSI_AND_SEQUENCE_NUMBER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.2 Authentication parameter AUTN * M LV 17 */ int ogs_nas_eps_decode_authentication_parameter_autn(ogs_nas_authentication_parameter_autn_t *authentication_parameter_autn, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_authentication_parameter_autn_t *source = (ogs_nas_authentication_parameter_autn_t *)pkbuf->data; authentication_parameter_autn->length = source->length; size = authentication_parameter_autn->length + sizeof(authentication_parameter_autn->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(authentication_parameter_autn, pkbuf->data - size, size); ogs_trace(" AUTHENTICATION_PARAMETER_AUTN - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_authentication_parameter_autn(ogs_pkbuf_t *pkbuf, ogs_nas_authentication_parameter_autn_t *authentication_parameter_autn) { uint16_t size = authentication_parameter_autn->length + sizeof(authentication_parameter_autn->length); ogs_nas_authentication_parameter_autn_t target; memcpy(&target, authentication_parameter_autn, sizeof(ogs_nas_authentication_parameter_autn_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" AUTHENTICATION_PARAMETER_AUTN - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.20 MS network capability * O TLV 4-10 */ int ogs_nas_eps_decode_ms_network_capability(ogs_nas_ms_network_capability_t *ms_network_capability, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ms_network_capability_t *source = (ogs_nas_ms_network_capability_t *)pkbuf->data; ms_network_capability->length = source->length; size = ms_network_capability->length + sizeof(ms_network_capability->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ms_network_capability, pkbuf->data - size, size); ogs_trace(" MS_NETWORK_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ms_network_capability(ogs_pkbuf_t *pkbuf, ogs_nas_ms_network_capability_t *ms_network_capability) { uint16_t size = ms_network_capability->length + sizeof(ms_network_capability->length); ogs_nas_ms_network_capability_t target; memcpy(&target, ms_network_capability, sizeof(ogs_nas_ms_network_capability_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" MS_NETWORK_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.20A MS network feature support * O TV 1 */ int ogs_nas_eps_decode_ms_network_feature_support(ogs_nas_ms_network_feature_support_t *ms_network_feature_support, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ms_network_feature_support_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ms_network_feature_support, pkbuf->data - size, size); ogs_trace(" MS_NETWORK_FEATURE_SUPPORT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ms_network_feature_support(ogs_pkbuf_t *pkbuf, ogs_nas_ms_network_feature_support_t *ms_network_feature_support) { uint16_t size = sizeof(ogs_nas_ms_network_feature_support_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, ms_network_feature_support, size); ogs_trace(" MS_NETWORK_FEATURE_SUPPORT - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.21 key set identifier * O TV 1 */ int ogs_nas_eps_decode_key_set_identifier(ogs_nas_key_set_identifier_t *key_set_identifier, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_key_set_identifier_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(key_set_identifier, pkbuf->data - size, size); ogs_trace(" KEY_SET_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_key_set_identifier(ogs_pkbuf_t *pkbuf, ogs_nas_key_set_identifier_t *key_set_identifier) { uint16_t size = sizeof(ogs_nas_key_set_identifier_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, key_set_identifier, size); ogs_trace(" KEY_SET_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.22 EPS message container * M LV 3-252 */ int ogs_nas_eps_decode_eps_message_container(ogs_nas_eps_message_container_t *eps_message_container, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_eps_message_container_t *source = (ogs_nas_eps_message_container_t *)pkbuf->data; eps_message_container->length = source->length; size = eps_message_container->length + sizeof(eps_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_message_container, pkbuf->data - size, size); ogs_trace(" EPS_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_message_container(ogs_pkbuf_t *pkbuf, ogs_nas_eps_message_container_t *eps_message_container) { uint16_t size = eps_message_container->length + sizeof(eps_message_container->length); ogs_nas_eps_message_container_t target; memcpy(&target, eps_message_container, sizeof(ogs_nas_eps_message_container_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.23 security algorithms * M V 1 */ int ogs_nas_eps_decode_security_algorithms(ogs_nas_security_algorithms_t *security_algorithms, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_security_algorithms_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(security_algorithms, pkbuf->data - size, size); ogs_trace(" SECURITY_ALGORITHMS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_security_algorithms(ogs_pkbuf_t *pkbuf, ogs_nas_security_algorithms_t *security_algorithms) { uint16_t size = sizeof(ogs_nas_security_algorithms_t); ogs_nas_security_algorithms_t target; memcpy(&target, security_algorithms, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" SECURITY_ALGORITHMS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.24 Network name * O TLV 3-n */ int ogs_nas_eps_decode_network_name(ogs_nas_network_name_t *network_name, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_network_name_t *source = (ogs_nas_network_name_t *)pkbuf->data; network_name->length = source->length; size = network_name->length + sizeof(network_name->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(network_name, pkbuf->data - size, size); ogs_trace(" NETWORK_NAME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_network_name(ogs_pkbuf_t *pkbuf, ogs_nas_network_name_t *network_name) { uint16_t size = network_name->length + sizeof(network_name->length); ogs_nas_network_name_t target; memcpy(&target, network_name, sizeof(ogs_nas_network_name_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" NETWORK_NAME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.24A Network resource identifier container * O TLV 4 */ int ogs_nas_eps_decode_network_resource_identifier_container(ogs_nas_network_resource_identifier_container_t *network_resource_identifier_container, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_network_resource_identifier_container_t *source = (ogs_nas_network_resource_identifier_container_t *)pkbuf->data; network_resource_identifier_container->length = source->length; size = network_resource_identifier_container->length + sizeof(network_resource_identifier_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(network_resource_identifier_container, pkbuf->data - size, size); ogs_trace(" NETWORK_RESOURCE_IDENTIFIER_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_network_resource_identifier_container(ogs_pkbuf_t *pkbuf, ogs_nas_network_resource_identifier_container_t *network_resource_identifier_container) { uint16_t size = network_resource_identifier_container->length + sizeof(network_resource_identifier_container->length); ogs_nas_network_resource_identifier_container_t target; memcpy(&target, network_resource_identifier_container, sizeof(ogs_nas_network_resource_identifier_container_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" NETWORK_RESOURCE_IDENTIFIER_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.25 Nonce * O TV 5 */ int ogs_nas_eps_decode_nonce(ogs_nas_nonce_t *nonce, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_nonce_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(nonce, pkbuf->data - size, size); *nonce = be32toh(*nonce); ogs_trace(" NONCE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_nonce(ogs_pkbuf_t *pkbuf, ogs_nas_nonce_t *nonce) { uint16_t size = sizeof(ogs_nas_nonce_t); ogs_nas_nonce_t target; memcpy(&target, nonce, size); target = htobe32(*nonce); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" NONCE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.25A Paging identity * M V 1 */ int ogs_nas_eps_decode_paging_identity(ogs_nas_paging_identity_t *paging_identity, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_paging_identity_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(paging_identity, pkbuf->data - size, size); ogs_trace(" PAGING_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_paging_identity(ogs_pkbuf_t *pkbuf, ogs_nas_paging_identity_t *paging_identity) { uint16_t size = sizeof(ogs_nas_paging_identity_t); ogs_nas_paging_identity_t target; memcpy(&target, paging_identity, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" PAGING_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.26 P-TMSI signature * O TV 4 */ int ogs_nas_eps_decode_p_tmsi_signature(ogs_nas_p_tmsi_signature_t *p_tmsi_signature, ogs_pkbuf_t *pkbuf) { uint16_t size = 3; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(p_tmsi_signature, pkbuf->data - size, size); *p_tmsi_signature = htobe32(*p_tmsi_signature); ogs_trace(" P_TMSI_SIGNATURE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_p_tmsi_signature(ogs_pkbuf_t *pkbuf, ogs_nas_p_tmsi_signature_t *p_tmsi_signature) { uint16_t size = 3; ogs_nas_p_tmsi_signature_t target; memcpy(&target, p_tmsi_signature, size); *p_tmsi_signature = be32toh(*p_tmsi_signature); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" P_TMSI_SIGNATURE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.26A Extended EMM cause * O TV 1 */ int ogs_nas_eps_decode_extended_emm_cause(ogs_nas_extended_emm_cause_t *extended_emm_cause, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_extended_emm_cause_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(extended_emm_cause, pkbuf->data - size, size); ogs_trace(" EXTENDED_EMM_CAUSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_extended_emm_cause(ogs_pkbuf_t *pkbuf, ogs_nas_extended_emm_cause_t *extended_emm_cause) { uint16_t size = sizeof(ogs_nas_extended_emm_cause_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, extended_emm_cause, size); ogs_trace(" EXTENDED_EMM_CAUSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.27 Service type * M V 1/2 */ int ogs_nas_eps_decode_service_type(ogs_nas_service_type_t *service_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_service_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(service_type, pkbuf->data - size, size); ogs_trace(" SERVICE_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_service_type(ogs_pkbuf_t *pkbuf, ogs_nas_service_type_t *service_type) { uint16_t size = sizeof(ogs_nas_service_type_t); ogs_nas_service_type_t target; memcpy(&target, service_type, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" SERVICE_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.28 Short MAC * M V 2 */ int ogs_nas_eps_decode_short_mac(ogs_nas_short_mac_t *short_mac, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_short_mac_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(short_mac, pkbuf->data - size, size); *short_mac = be16toh(*short_mac); ogs_trace(" SHORT_MAC - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_short_mac(ogs_pkbuf_t *pkbuf, ogs_nas_short_mac_t *short_mac) { uint16_t size = sizeof(ogs_nas_short_mac_t); ogs_nas_short_mac_t target; memcpy(&target, short_mac, size); target = htobe16(*short_mac); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" SHORT_MAC - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.29 Time zone * O TV 2 */ int ogs_nas_eps_decode_time_zone(ogs_nas_time_zone_t *time_zone, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_time_zone_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(time_zone, pkbuf->data - size, size); ogs_trace(" TIME_ZONE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_time_zone(ogs_pkbuf_t *pkbuf, ogs_nas_time_zone_t *time_zone) { uint16_t size = sizeof(ogs_nas_time_zone_t); ogs_nas_time_zone_t target; memcpy(&target, time_zone, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TIME_ZONE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.3 Authentication parameter RAND * M V 16 */ int ogs_nas_eps_decode_authentication_parameter_rand(ogs_nas_authentication_parameter_rand_t *authentication_parameter_rand, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_authentication_parameter_rand_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(authentication_parameter_rand, pkbuf->data - size, size); ogs_trace(" AUTHENTICATION_PARAMETER_RAND - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_authentication_parameter_rand(ogs_pkbuf_t *pkbuf, ogs_nas_authentication_parameter_rand_t *authentication_parameter_rand) { uint16_t size = sizeof(ogs_nas_authentication_parameter_rand_t); ogs_nas_authentication_parameter_rand_t target; memcpy(&target, authentication_parameter_rand, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" AUTHENTICATION_PARAMETER_RAND - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.30 Time zone and time * O TV 8 */ int ogs_nas_eps_decode_time_zone_and_time(ogs_nas_time_zone_and_time_t *time_zone_and_time, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_time_zone_and_time_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(time_zone_and_time, pkbuf->data - size, size); ogs_trace(" TIME_ZONE_AND_TIME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_time_zone_and_time(ogs_pkbuf_t *pkbuf, ogs_nas_time_zone_and_time_t *time_zone_and_time) { uint16_t size = sizeof(ogs_nas_time_zone_and_time_t); ogs_nas_time_zone_and_time_t target; memcpy(&target, time_zone_and_time, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TIME_ZONE_AND_TIME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.31 TMSI status * O TV 1 */ int ogs_nas_eps_decode_tmsi_status(ogs_nas_tmsi_status_t *tmsi_status, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_tmsi_status_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(tmsi_status, pkbuf->data - size, size); ogs_trace(" TMSI_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_tmsi_status(ogs_pkbuf_t *pkbuf, ogs_nas_tmsi_status_t *tmsi_status) { uint16_t size = sizeof(ogs_nas_tmsi_status_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, tmsi_status, size); ogs_trace(" TMSI_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.32 Tracking area identity * O TV 6 */ int ogs_nas_eps_decode_tracking_area_identity(ogs_nas_tracking_area_identity_t *tracking_area_identity, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_tracking_area_identity_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(tracking_area_identity, pkbuf->data - size, size); tracking_area_identity->tac = be16toh(tracking_area_identity->tac); ogs_trace(" TRACKING_AREA_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_tracking_area_identity(ogs_pkbuf_t *pkbuf, ogs_nas_tracking_area_identity_t *tracking_area_identity) { uint16_t size = sizeof(ogs_nas_tracking_area_identity_t); ogs_nas_tracking_area_identity_t target; memcpy(&target, tracking_area_identity, size); target.tac = htobe16(tracking_area_identity->tac); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TRACKING_AREA_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.33 Tracking area identity list * M LV 7-97 */ int ogs_nas_eps_decode_tracking_area_identity_list(ogs_nas_tracking_area_identity_list_t *tracking_area_identity_list, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_tracking_area_identity_list_t *source = (ogs_nas_tracking_area_identity_list_t *)pkbuf->data; tracking_area_identity_list->length = source->length; size = tracking_area_identity_list->length + sizeof(tracking_area_identity_list->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(tracking_area_identity_list, pkbuf->data - size, size); ogs_trace(" TRACKING_AREA_IDENTITY_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_tracking_area_identity_list(ogs_pkbuf_t *pkbuf, ogs_nas_tracking_area_identity_list_t *tracking_area_identity_list) { uint16_t size = tracking_area_identity_list->length + sizeof(tracking_area_identity_list->length); ogs_nas_tracking_area_identity_list_t target; memcpy(&target, tracking_area_identity_list, sizeof(ogs_nas_tracking_area_identity_list_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TRACKING_AREA_IDENTITY_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.34 UE network capability * M LV 3-14 */ int ogs_nas_eps_decode_ue_network_capability(ogs_nas_ue_network_capability_t *ue_network_capability, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ue_network_capability_t *source = (ogs_nas_ue_network_capability_t *)pkbuf->data; ue_network_capability->length = source->length; size = ue_network_capability->length + sizeof(ue_network_capability->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_network_capability, pkbuf->data - size, size); ogs_trace(" UE_NETWORK_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_network_capability(ogs_pkbuf_t *pkbuf, ogs_nas_ue_network_capability_t *ue_network_capability) { uint16_t size = ue_network_capability->length + sizeof(ue_network_capability->length); ogs_nas_ue_network_capability_t target; memcpy(&target, ue_network_capability, sizeof(ogs_nas_ue_network_capability_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" UE_NETWORK_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.35 UE radio capability information update needed * O TV 1 */ int ogs_nas_eps_decode_ue_radio_capability_information_update_needed(ogs_nas_ue_radio_capability_information_update_needed_t *ue_radio_capability_information_update_needed, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ue_radio_capability_information_update_needed_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_radio_capability_information_update_needed, pkbuf->data - size, size); ogs_trace(" UE_RADIO_CAPABILITY_INFORMATION_UPDATE_NEEDED - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_radio_capability_information_update_needed(ogs_pkbuf_t *pkbuf, ogs_nas_ue_radio_capability_information_update_needed_t *ue_radio_capability_information_update_needed) { uint16_t size = sizeof(ogs_nas_ue_radio_capability_information_update_needed_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, ue_radio_capability_information_update_needed, size); ogs_trace(" UE_RADIO_CAPABILITY_INFORMATION_UPDATE_NEEDED - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.36 UE security capability * M LV 3-6 */ int ogs_nas_eps_decode_ue_security_capability(ogs_nas_ue_security_capability_t *ue_security_capability, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ue_security_capability_t *source = (ogs_nas_ue_security_capability_t *)pkbuf->data; ue_security_capability->length = source->length; size = ue_security_capability->length + sizeof(ue_security_capability->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_security_capability, pkbuf->data - size, size); ogs_trace(" UE_SECURITY_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_security_capability(ogs_pkbuf_t *pkbuf, ogs_nas_ue_security_capability_t *ue_security_capability) { uint16_t size = ue_security_capability->length + sizeof(ue_security_capability->length); ogs_nas_ue_security_capability_t target; memcpy(&target, ue_security_capability, sizeof(ogs_nas_ue_security_capability_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" UE_SECURITY_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.37 Emergency number list * O TLV 5-50 */ int ogs_nas_eps_decode_emergency_number_list(ogs_nas_emergency_number_list_t *emergency_number_list, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_emergency_number_list_t *source = (ogs_nas_emergency_number_list_t *)pkbuf->data; emergency_number_list->length = source->length; size = emergency_number_list->length + sizeof(emergency_number_list->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(emergency_number_list, pkbuf->data - size, size); ogs_trace(" EMERGENCY_NUMBER_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_emergency_number_list(ogs_pkbuf_t *pkbuf, ogs_nas_emergency_number_list_t *emergency_number_list) { uint16_t size = emergency_number_list->length + sizeof(emergency_number_list->length); ogs_nas_emergency_number_list_t target; memcpy(&target, emergency_number_list, sizeof(ogs_nas_emergency_number_list_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EMERGENCY_NUMBER_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.37A Extended emergency number list * O TLV-E 7-65538 */ int ogs_nas_eps_decode_extended_emergency_number_list(ogs_nas_extended_emergency_number_list_t *extended_emergency_number_list, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_extended_emergency_number_list_t *source = (ogs_nas_extended_emergency_number_list_t *)pkbuf->data; extended_emergency_number_list->length = be16toh(source->length); size = extended_emergency_number_list->length + sizeof(extended_emergency_number_list->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); extended_emergency_number_list->buffer = pkbuf->data - size + sizeof(extended_emergency_number_list->length); ogs_trace(" EXTENDED_EMERGENCY_NUMBER_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, (void*)extended_emergency_number_list->buffer, extended_emergency_number_list->length); return size; } int ogs_nas_eps_encode_extended_emergency_number_list(ogs_pkbuf_t *pkbuf, ogs_nas_extended_emergency_number_list_t *extended_emergency_number_list) { uint16_t size = 0; uint16_t target; ogs_assert(extended_emergency_number_list); ogs_assert(extended_emergency_number_list->buffer); size = sizeof(extended_emergency_number_list->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); target = htobe16(extended_emergency_number_list->length); memcpy(pkbuf->data - size, &target, size); size = extended_emergency_number_list->length; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, extended_emergency_number_list->buffer, size); ogs_trace(" EXTENDED_EMERGENCY_NUMBER_LIST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return extended_emergency_number_list->length + sizeof(extended_emergency_number_list->length); } /* 9.9.3.38 CLI * O TLV 3-14 */ int ogs_nas_eps_decode_cli(ogs_nas_cli_t *cli, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_cli_t *source = (ogs_nas_cli_t *)pkbuf->data; cli->length = source->length; size = cli->length + sizeof(cli->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(cli, pkbuf->data - size, size); ogs_trace(" CLI - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_cli(ogs_pkbuf_t *pkbuf, ogs_nas_cli_t *cli) { uint16_t size = cli->length + sizeof(cli->length); ogs_nas_cli_t target; memcpy(&target, cli, sizeof(ogs_nas_cli_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" CLI - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.39 SS Code * O TV 2 */ int ogs_nas_eps_decode_ss_code(ogs_nas_ss_code_t *ss_code, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ss_code_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ss_code, pkbuf->data - size, size); ogs_trace(" SS_CODE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ss_code(ogs_pkbuf_t *pkbuf, ogs_nas_ss_code_t *ss_code) { uint16_t size = sizeof(ogs_nas_ss_code_t); ogs_nas_ss_code_t target; memcpy(&target, ss_code, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" SS_CODE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.4 Authentication response parameter * M LV 5-17 */ int ogs_nas_eps_decode_authentication_response_parameter(ogs_nas_authentication_response_parameter_t *authentication_response_parameter, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_authentication_response_parameter_t *source = (ogs_nas_authentication_response_parameter_t *)pkbuf->data; authentication_response_parameter->length = source->length; size = authentication_response_parameter->length + sizeof(authentication_response_parameter->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(authentication_response_parameter, pkbuf->data - size, size); ogs_trace(" AUTHENTICATION_RESPONSE_PARAMETER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_authentication_response_parameter(ogs_pkbuf_t *pkbuf, ogs_nas_authentication_response_parameter_t *authentication_response_parameter) { uint16_t size = authentication_response_parameter->length + sizeof(authentication_response_parameter->length); ogs_nas_authentication_response_parameter_t target; memcpy(&target, authentication_response_parameter, sizeof(ogs_nas_authentication_response_parameter_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" AUTHENTICATION_RESPONSE_PARAMETER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.40 LCS indicator * O TV 2 */ int ogs_nas_eps_decode_lcs_indicator(ogs_nas_lcs_indicator_t *lcs_indicator, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_lcs_indicator_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(lcs_indicator, pkbuf->data - size, size); ogs_trace(" LCS_INDICATOR - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_lcs_indicator(ogs_pkbuf_t *pkbuf, ogs_nas_lcs_indicator_t *lcs_indicator) { uint16_t size = sizeof(ogs_nas_lcs_indicator_t); ogs_nas_lcs_indicator_t target; memcpy(&target, lcs_indicator, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" LCS_INDICATOR - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.41 LCS client identity * O TLV 3-257 */ int ogs_nas_eps_decode_lcs_client_identity(ogs_nas_lcs_client_identity_t *lcs_client_identity, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_lcs_client_identity_t *source = (ogs_nas_lcs_client_identity_t *)pkbuf->data; lcs_client_identity->length = source->length; size = lcs_client_identity->length + sizeof(lcs_client_identity->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(lcs_client_identity, pkbuf->data - size, size); ogs_trace(" LCS_CLIENT_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_lcs_client_identity(ogs_pkbuf_t *pkbuf, ogs_nas_lcs_client_identity_t *lcs_client_identity) { uint16_t size = lcs_client_identity->length + sizeof(lcs_client_identity->length); ogs_nas_lcs_client_identity_t target; memcpy(&target, lcs_client_identity, sizeof(ogs_nas_lcs_client_identity_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" LCS_CLIENT_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.42 Generic message container type * M V 1 */ int ogs_nas_eps_decode_generic_message_container_type(ogs_nas_generic_message_container_type_t *generic_message_container_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_generic_message_container_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(generic_message_container_type, pkbuf->data - size, size); ogs_trace(" GENERIC_MESSAGE_CONTAINER_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_generic_message_container_type(ogs_pkbuf_t *pkbuf, ogs_nas_generic_message_container_type_t *generic_message_container_type) { uint16_t size = sizeof(ogs_nas_generic_message_container_type_t); ogs_nas_generic_message_container_type_t target; memcpy(&target, generic_message_container_type, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" GENERIC_MESSAGE_CONTAINER_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.43 Generic message container * M LV-E 3-n */ int ogs_nas_eps_decode_generic_message_container(ogs_nas_generic_message_container_t *generic_message_container, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_generic_message_container_t *source = (ogs_nas_generic_message_container_t *)pkbuf->data; generic_message_container->length = be16toh(source->length); size = generic_message_container->length + sizeof(generic_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); generic_message_container->buffer = pkbuf->data - size + sizeof(generic_message_container->length); ogs_trace(" GENERIC_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, (void*)generic_message_container->buffer, generic_message_container->length); return size; } int ogs_nas_eps_encode_generic_message_container(ogs_pkbuf_t *pkbuf, ogs_nas_generic_message_container_t *generic_message_container) { uint16_t size = 0; uint16_t target; ogs_assert(generic_message_container); ogs_assert(generic_message_container->buffer); size = sizeof(generic_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); target = htobe16(generic_message_container->length); memcpy(pkbuf->data - size, &target, size); size = generic_message_container->length; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, generic_message_container->buffer, size); ogs_trace(" GENERIC_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return generic_message_container->length + sizeof(generic_message_container->length); } /* 9.9.3.44 Voice domain preference and UE usage setting * O TLV 3 */ int ogs_nas_eps_decode_voice_domain_preference_and_ue_usage_setting(ogs_nas_voice_domain_preference_and_ue_usage_setting_t *voice_domain_preference_and_ue_usage_setting, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_voice_domain_preference_and_ue_usage_setting_t *source = (ogs_nas_voice_domain_preference_and_ue_usage_setting_t *)pkbuf->data; voice_domain_preference_and_ue_usage_setting->length = source->length; size = voice_domain_preference_and_ue_usage_setting->length + sizeof(voice_domain_preference_and_ue_usage_setting->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(voice_domain_preference_and_ue_usage_setting, pkbuf->data - size, size); ogs_trace(" VOICE_DOMAIN_PREFERENCE_AND_UE_USAGE_SETTING - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_voice_domain_preference_and_ue_usage_setting(ogs_pkbuf_t *pkbuf, ogs_nas_voice_domain_preference_and_ue_usage_setting_t *voice_domain_preference_and_ue_usage_setting) { uint16_t size = voice_domain_preference_and_ue_usage_setting->length + sizeof(voice_domain_preference_and_ue_usage_setting->length); ogs_nas_voice_domain_preference_and_ue_usage_setting_t target; memcpy(&target, voice_domain_preference_and_ue_usage_setting, sizeof(ogs_nas_voice_domain_preference_and_ue_usage_setting_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" VOICE_DOMAIN_PREFERENCE_AND_UE_USAGE_SETTING - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.45 GUTI type * O TV 1 */ int ogs_nas_eps_decode_guti_type(ogs_nas_guti_type_t *guti_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_guti_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(guti_type, pkbuf->data - size, size); ogs_trace(" GUTI_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_guti_type(ogs_pkbuf_t *pkbuf, ogs_nas_guti_type_t *guti_type) { uint16_t size = sizeof(ogs_nas_guti_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, guti_type, size); ogs_trace(" GUTI_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.46 Extended DRX parameters * O TLV 3 */ int ogs_nas_eps_decode_extended_drx_parameters(ogs_nas_extended_drx_parameters_t *extended_drx_parameters, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_extended_drx_parameters_t *source = (ogs_nas_extended_drx_parameters_t *)pkbuf->data; extended_drx_parameters->length = source->length; size = extended_drx_parameters->length + sizeof(extended_drx_parameters->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(extended_drx_parameters, pkbuf->data - size, size); ogs_trace(" EXTENDED_DRX_PARAMETERS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_extended_drx_parameters(ogs_pkbuf_t *pkbuf, ogs_nas_extended_drx_parameters_t *extended_drx_parameters) { uint16_t size = extended_drx_parameters->length + sizeof(extended_drx_parameters->length); ogs_nas_extended_drx_parameters_t target; memcpy(&target, extended_drx_parameters, sizeof(ogs_nas_extended_drx_parameters_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EXTENDED_DRX_PARAMETERS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.48 DCN-ID * O TLV 4 */ int ogs_nas_eps_decode_dcn_id(ogs_nas_dcn_id_t *dcn_id, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_dcn_id_t *source = (ogs_nas_dcn_id_t *)pkbuf->data; dcn_id->length = source->length; size = dcn_id->length + sizeof(dcn_id->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(dcn_id, pkbuf->data - size, size); ogs_trace(" DCN_ID - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_dcn_id(ogs_pkbuf_t *pkbuf, ogs_nas_dcn_id_t *dcn_id) { uint16_t size = dcn_id->length + sizeof(dcn_id->length); ogs_nas_dcn_id_t target; memcpy(&target, dcn_id, sizeof(ogs_nas_dcn_id_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" DCN_ID - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.49 Non-3GPP NW provided policies * O TV 1 */ int ogs_nas_eps_decode_non__nw_provided_policies(ogs_nas_non__nw_provided_policies_t *non__nw_provided_policies, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_non__nw_provided_policies_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(non__nw_provided_policies, pkbuf->data - size, size); ogs_trace(" NON__NW_PROVIDED_POLICIES - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_non__nw_provided_policies(ogs_pkbuf_t *pkbuf, ogs_nas_non__nw_provided_policies_t *non__nw_provided_policies) { uint16_t size = sizeof(ogs_nas_non__nw_provided_policies_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, non__nw_provided_policies, size); ogs_trace(" NON__NW_PROVIDED_POLICIES - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.4B SMS services status * O TV 1 */ int ogs_nas_eps_decode_sms_services_status(ogs_nas_sms_services_status_t *sms_services_status, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_sms_services_status_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(sms_services_status, pkbuf->data - size, size); ogs_trace(" SMS_SERVICES_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_sms_services_status(ogs_pkbuf_t *pkbuf, ogs_nas_sms_services_status_t *sms_services_status) { uint16_t size = sizeof(ogs_nas_sms_services_status_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, sms_services_status, size); ogs_trace(" SMS_SERVICES_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.4a Ciphering key sequence number * O TV 1 */ int ogs_nas_eps_decode_ciphering_key_sequence_number(ogs_nas_ciphering_key_sequence_number_t *ciphering_key_sequence_number, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ciphering_key_sequence_number_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ciphering_key_sequence_number, pkbuf->data - size, size); ogs_trace(" CIPHERING_KEY_SEQUENCE_NUMBER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ciphering_key_sequence_number(ogs_pkbuf_t *pkbuf, ogs_nas_ciphering_key_sequence_number_t *ciphering_key_sequence_number) { uint16_t size = sizeof(ogs_nas_ciphering_key_sequence_number_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, ciphering_key_sequence_number, size); ogs_trace(" CIPHERING_KEY_SEQUENCE_NUMBER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.5 CSFB response * O TV 1 */ int ogs_nas_eps_decode_csfb_response(ogs_nas_csfb_response_t *csfb_response, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_csfb_response_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(csfb_response, pkbuf->data - size, size); ogs_trace(" CSFB_RESPONSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_csfb_response(ogs_pkbuf_t *pkbuf, ogs_nas_csfb_response_t *csfb_response) { uint16_t size = sizeof(ogs_nas_csfb_response_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, csfb_response, size); ogs_trace(" CSFB_RESPONSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.50 HashMME * O TLV 10 */ int ogs_nas_eps_decode_hashmme(ogs_nas_hashmme_t *hashmme, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_hashmme_t *source = (ogs_nas_hashmme_t *)pkbuf->data; hashmme->length = source->length; size = hashmme->length + sizeof(hashmme->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(hashmme, pkbuf->data - size, size); ogs_trace(" HASHMME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_hashmme(ogs_pkbuf_t *pkbuf, ogs_nas_hashmme_t *hashmme) { uint16_t size = hashmme->length + sizeof(hashmme->length); ogs_nas_hashmme_t target; memcpy(&target, hashmme, sizeof(ogs_nas_hashmme_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" HASHMME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.51 Replayed NAS message container * O TLV-E 3-n */ int ogs_nas_eps_decode_replayed_nas_message_container(ogs_nas_replayed_nas_message_container_t *replayed_nas_message_container, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_replayed_nas_message_container_t *source = (ogs_nas_replayed_nas_message_container_t *)pkbuf->data; replayed_nas_message_container->length = be16toh(source->length); size = replayed_nas_message_container->length + sizeof(replayed_nas_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); replayed_nas_message_container->buffer = pkbuf->data - size + sizeof(replayed_nas_message_container->length); ogs_trace(" REPLAYED_NAS_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, (void*)replayed_nas_message_container->buffer, replayed_nas_message_container->length); return size; } int ogs_nas_eps_encode_replayed_nas_message_container(ogs_pkbuf_t *pkbuf, ogs_nas_replayed_nas_message_container_t *replayed_nas_message_container) { uint16_t size = 0; uint16_t target; ogs_assert(replayed_nas_message_container); ogs_assert(replayed_nas_message_container->buffer); size = sizeof(replayed_nas_message_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); target = htobe16(replayed_nas_message_container->length); memcpy(pkbuf->data - size, &target, size); size = replayed_nas_message_container->length; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, replayed_nas_message_container->buffer, size); ogs_trace(" REPLAYED_NAS_MESSAGE_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return replayed_nas_message_container->length + sizeof(replayed_nas_message_container->length); } /* 9.9.3.52 Network policy * O TV 1 */ int ogs_nas_eps_decode_network_policy(ogs_nas_network_policy_t *network_policy, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_network_policy_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(network_policy, pkbuf->data - size, size); ogs_trace(" NETWORK_POLICY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_network_policy(ogs_pkbuf_t *pkbuf, ogs_nas_network_policy_t *network_policy) { uint16_t size = sizeof(ogs_nas_network_policy_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, network_policy, size); ogs_trace(" NETWORK_POLICY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.53 UE additional security capability * O TLV 6 */ int ogs_nas_eps_decode_ue_additional_security_capability(ogs_nas_ue_additional_security_capability_t *ue_additional_security_capability, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ue_additional_security_capability_t *source = (ogs_nas_ue_additional_security_capability_t *)pkbuf->data; ue_additional_security_capability->length = source->length; size = ue_additional_security_capability->length + sizeof(ue_additional_security_capability->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_additional_security_capability, pkbuf->data - size, size); ogs_trace(" UE_ADDITIONAL_SECURITY_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_additional_security_capability(ogs_pkbuf_t *pkbuf, ogs_nas_ue_additional_security_capability_t *ue_additional_security_capability) { uint16_t size = ue_additional_security_capability->length + sizeof(ue_additional_security_capability->length); ogs_nas_ue_additional_security_capability_t target; memcpy(&target, ue_additional_security_capability, sizeof(ogs_nas_ue_additional_security_capability_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" UE_ADDITIONAL_SECURITY_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.54 UE status * O TLV 3 */ int ogs_nas_eps_decode_ue_status(ogs_nas_ue_status_t *ue_status, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ue_status_t *source = (ogs_nas_ue_status_t *)pkbuf->data; ue_status->length = source->length; size = ue_status->length + sizeof(ue_status->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_status, pkbuf->data - size, size); ogs_trace(" UE_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_status(ogs_pkbuf_t *pkbuf, ogs_nas_ue_status_t *ue_status) { uint16_t size = ue_status->length + sizeof(ue_status->length); ogs_nas_ue_status_t target; memcpy(&target, ue_status, sizeof(ogs_nas_ue_status_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" UE_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.55 Additional information requested * O TV 2 */ int ogs_nas_eps_decode_additional_information_requested(ogs_nas_additional_information_requested_t *additional_information_requested, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_additional_information_requested_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(additional_information_requested, pkbuf->data - size, size); ogs_trace(" ADDITIONAL_INFORMATION_REQUESTED - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_additional_information_requested(ogs_pkbuf_t *pkbuf, ogs_nas_additional_information_requested_t *additional_information_requested) { uint16_t size = sizeof(ogs_nas_additional_information_requested_t); ogs_nas_additional_information_requested_t target; memcpy(&target, additional_information_requested, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" ADDITIONAL_INFORMATION_REQUESTED - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.56 Ciphering key data * O TLV-E 35-2291 */ int ogs_nas_eps_decode_ciphering_key_data(ogs_nas_ciphering_key_data_t *ciphering_key_data, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ciphering_key_data_t *source = (ogs_nas_ciphering_key_data_t *)pkbuf->data; ciphering_key_data->length = be16toh(source->length); size = ciphering_key_data->length + sizeof(ciphering_key_data->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); ciphering_key_data->buffer = pkbuf->data - size + sizeof(ciphering_key_data->length); ogs_trace(" CIPHERING_KEY_DATA - "); ogs_log_hexdump(OGS_LOG_TRACE, (void*)ciphering_key_data->buffer, ciphering_key_data->length); return size; } int ogs_nas_eps_encode_ciphering_key_data(ogs_pkbuf_t *pkbuf, ogs_nas_ciphering_key_data_t *ciphering_key_data) { uint16_t size = 0; uint16_t target; ogs_assert(ciphering_key_data); ogs_assert(ciphering_key_data->buffer); size = sizeof(ciphering_key_data->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); target = htobe16(ciphering_key_data->length); memcpy(pkbuf->data - size, &target, size); size = ciphering_key_data->length; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, ciphering_key_data->buffer, size); ogs_trace(" CIPHERING_KEY_DATA - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return ciphering_key_data->length + sizeof(ciphering_key_data->length); } /* 9.9.3.57 N1 UE network capability * O TLV 3-15 */ int ogs_nas_eps_decode_n1_ue_network_capability(ogs_nas_n1_ue_network_capability_t *n1_ue_network_capability, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_n1_ue_network_capability_t *source = (ogs_nas_n1_ue_network_capability_t *)pkbuf->data; n1_ue_network_capability->length = source->length; size = n1_ue_network_capability->length + sizeof(n1_ue_network_capability->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(n1_ue_network_capability, pkbuf->data - size, size); ogs_trace(" N1_UE_NETWORK_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_n1_ue_network_capability(ogs_pkbuf_t *pkbuf, ogs_nas_n1_ue_network_capability_t *n1_ue_network_capability) { uint16_t size = n1_ue_network_capability->length + sizeof(n1_ue_network_capability->length); ogs_nas_n1_ue_network_capability_t target; memcpy(&target, n1_ue_network_capability, sizeof(ogs_nas_n1_ue_network_capability_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" N1_UE_NETWORK_CAPABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.59 UE radio capability ID request * O TV 1 */ int ogs_nas_eps_decode_ue_radio_capability_id_request(ogs_nas_ue_radio_capability_id_request_t *ue_radio_capability_id_request, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ue_radio_capability_id_request_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_radio_capability_id_request, pkbuf->data - size, size); ogs_trace(" UE_RADIO_CAPABILITY_ID_REQUEST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_radio_capability_id_request(ogs_pkbuf_t *pkbuf, ogs_nas_ue_radio_capability_id_request_t *ue_radio_capability_id_request) { uint16_t size = sizeof(ogs_nas_ue_radio_capability_id_request_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, ue_radio_capability_id_request, size); ogs_trace(" UE_RADIO_CAPABILITY_ID_REQUEST - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.6 Daylight saving time * O TLV 3 */ int ogs_nas_eps_decode_daylight_saving_time(ogs_nas_daylight_saving_time_t *daylight_saving_time, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_daylight_saving_time_t *source = (ogs_nas_daylight_saving_time_t *)pkbuf->data; daylight_saving_time->length = source->length; size = daylight_saving_time->length + sizeof(daylight_saving_time->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(daylight_saving_time, pkbuf->data - size, size); ogs_trace(" DAYLIGHT_SAVING_TIME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_daylight_saving_time(ogs_pkbuf_t *pkbuf, ogs_nas_daylight_saving_time_t *daylight_saving_time) { uint16_t size = daylight_saving_time->length + sizeof(daylight_saving_time->length); ogs_nas_daylight_saving_time_t target; memcpy(&target, daylight_saving_time, sizeof(ogs_nas_daylight_saving_time_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" DAYLIGHT_SAVING_TIME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.60 UE radio capability ID * O TLV 3-n */ int ogs_nas_eps_decode_ue_radio_capability_id(ogs_nas_ue_radio_capability_id_t *ue_radio_capability_id, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_ue_radio_capability_id_t *source = (ogs_nas_ue_radio_capability_id_t *)pkbuf->data; ue_radio_capability_id->length = source->length; size = ue_radio_capability_id->length + sizeof(ue_radio_capability_id->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_radio_capability_id, pkbuf->data - size, size); ogs_trace(" UE_RADIO_CAPABILITY_ID - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_radio_capability_id(ogs_pkbuf_t *pkbuf, ogs_nas_ue_radio_capability_id_t *ue_radio_capability_id) { uint16_t size = ue_radio_capability_id->length + sizeof(ue_radio_capability_id->length); ogs_nas_ue_radio_capability_id_t target; memcpy(&target, ue_radio_capability_id, sizeof(ogs_nas_ue_radio_capability_id_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" UE_RADIO_CAPABILITY_ID - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.61 UE radio capability ID deletion indication * O TV 1 */ int ogs_nas_eps_decode_ue_radio_capability_id_deletion_indication(ogs_nas_ue_radio_capability_id_deletion_indication_t *ue_radio_capability_id_deletion_indication, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_ue_radio_capability_id_deletion_indication_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(ue_radio_capability_id_deletion_indication, pkbuf->data - size, size); ogs_trace(" UE_RADIO_CAPABILITY_ID_DELETION_INDICATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_ue_radio_capability_id_deletion_indication(ogs_pkbuf_t *pkbuf, ogs_nas_ue_radio_capability_id_deletion_indication_t *ue_radio_capability_id_deletion_indication) { uint16_t size = sizeof(ogs_nas_ue_radio_capability_id_deletion_indication_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, ue_radio_capability_id_deletion_indication, size); ogs_trace(" UE_RADIO_CAPABILITY_ID_DELETION_INDICATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.7 Detach type * M V 1/2 */ int ogs_nas_eps_decode_detach_type(ogs_nas_detach_type_t *detach_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_detach_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(detach_type, pkbuf->data - size, size); ogs_trace(" DETACH_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_detach_type(ogs_pkbuf_t *pkbuf, ogs_nas_detach_type_t *detach_type) { uint16_t size = sizeof(ogs_nas_detach_type_t); ogs_nas_detach_type_t target; memcpy(&target, detach_type, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" DETACH_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.8 DRX parameter * O TV 3 */ int ogs_nas_eps_decode_drx_parameter(ogs_nas_drx_parameter_t *drx_parameter, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_drx_parameter_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(drx_parameter, pkbuf->data - size, size); ogs_trace(" DRX_PARAMETER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_drx_parameter(ogs_pkbuf_t *pkbuf, ogs_nas_drx_parameter_t *drx_parameter) { uint16_t size = sizeof(ogs_nas_drx_parameter_t); ogs_nas_drx_parameter_t target; memcpy(&target, drx_parameter, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" DRX_PARAMETER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.3.9 EMM cause * O TV 2 */ int ogs_nas_eps_decode_emm_cause(ogs_nas_emm_cause_t *emm_cause, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_emm_cause_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(emm_cause, pkbuf->data - size, size); ogs_trace(" EMM_CAUSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_emm_cause(ogs_pkbuf_t *pkbuf, ogs_nas_emm_cause_t *emm_cause) { uint16_t size = sizeof(ogs_nas_emm_cause_t); ogs_nas_emm_cause_t target; memcpy(&target, emm_cause, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EMM_CAUSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.1 Access point name * M LV 2-101 */ int ogs_nas_eps_decode_access_point_name(ogs_nas_access_point_name_t *access_point_name, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_access_point_name_t *source = (ogs_nas_access_point_name_t *)pkbuf->data; access_point_name->length = source->length; size = access_point_name->length + sizeof(access_point_name->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(access_point_name, pkbuf->data - size, size); { char apn[OGS_MAX_APN_LEN]; access_point_name->length = ogs_fqdn_parse(apn, access_point_name->apn, access_point_name->length); ogs_cpystrn(access_point_name->apn, apn, ogs_min(access_point_name->length, OGS_MAX_APN_LEN) + 1); } ogs_trace(" ACCESS_POINT_NAME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_access_point_name(ogs_pkbuf_t *pkbuf, ogs_nas_access_point_name_t *access_point_name) { uint16_t size = access_point_name->length + sizeof(access_point_name->length); ogs_nas_access_point_name_t target; memcpy(&target, access_point_name, sizeof(ogs_nas_access_point_name_t)); target.length = ogs_fqdn_build(target.apn, access_point_name->apn, access_point_name->length); size = target.length + sizeof(target.length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" ACCESS_POINT_NAME - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.11 Protocol configuration options * O TLV 3-253 */ int ogs_nas_eps_decode_protocol_configuration_options(ogs_nas_protocol_configuration_options_t *protocol_configuration_options, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_protocol_configuration_options_t *source = (ogs_nas_protocol_configuration_options_t *)pkbuf->data; protocol_configuration_options->length = source->length; size = protocol_configuration_options->length + sizeof(protocol_configuration_options->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(protocol_configuration_options, pkbuf->data - size, size); ogs_trace(" PROTOCOL_CONFIGURATION_OPTIONS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_protocol_configuration_options(ogs_pkbuf_t *pkbuf, ogs_nas_protocol_configuration_options_t *protocol_configuration_options) { uint16_t size = protocol_configuration_options->length + sizeof(protocol_configuration_options->length); ogs_nas_protocol_configuration_options_t target; memcpy(&target, protocol_configuration_options, sizeof(ogs_nas_protocol_configuration_options_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" PROTOCOL_CONFIGURATION_OPTIONS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.12 Quality of service * O TLV 14-22 */ int ogs_nas_eps_decode_quality_of_service(ogs_nas_quality_of_service_t *quality_of_service, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_quality_of_service_t *source = (ogs_nas_quality_of_service_t *)pkbuf->data; quality_of_service->length = source->length; size = quality_of_service->length + sizeof(quality_of_service->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(quality_of_service, pkbuf->data - size, size); ogs_trace(" QUALITY_OF_SERVICE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_quality_of_service(ogs_pkbuf_t *pkbuf, ogs_nas_quality_of_service_t *quality_of_service) { uint16_t size = quality_of_service->length + sizeof(quality_of_service->length); ogs_nas_quality_of_service_t target; memcpy(&target, quality_of_service, sizeof(ogs_nas_quality_of_service_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" QUALITY_OF_SERVICE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.13 Radio priority * O TV 1 */ int ogs_nas_eps_decode_radio_priority(ogs_nas_radio_priority_t *radio_priority, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_radio_priority_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(radio_priority, pkbuf->data - size, size); ogs_trace(" RADIO_PRIORITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_radio_priority(ogs_pkbuf_t *pkbuf, ogs_nas_radio_priority_t *radio_priority) { uint16_t size = sizeof(ogs_nas_radio_priority_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, radio_priority, size); ogs_trace(" RADIO_PRIORITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.13A Re-attempt indicator * O TLV 3 */ int ogs_nas_eps_decode_re_attempt_indicator(ogs_nas_re_attempt_indicator_t *re_attempt_indicator, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_re_attempt_indicator_t *source = (ogs_nas_re_attempt_indicator_t *)pkbuf->data; re_attempt_indicator->length = source->length; size = re_attempt_indicator->length + sizeof(re_attempt_indicator->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(re_attempt_indicator, pkbuf->data - size, size); ogs_trace(" RE_ATTEMPT_INDICATOR - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_re_attempt_indicator(ogs_pkbuf_t *pkbuf, ogs_nas_re_attempt_indicator_t *re_attempt_indicator) { uint16_t size = re_attempt_indicator->length + sizeof(re_attempt_indicator->length); ogs_nas_re_attempt_indicator_t target; memcpy(&target, re_attempt_indicator, sizeof(ogs_nas_re_attempt_indicator_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" RE_ATTEMPT_INDICATOR - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.14 Request type * M V 1/2 */ int ogs_nas_eps_decode_request_type(ogs_nas_request_type_t *request_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_request_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(request_type, pkbuf->data - size, size); ogs_trace(" REQUEST_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_request_type(ogs_pkbuf_t *pkbuf, ogs_nas_request_type_t *request_type) { uint16_t size = sizeof(ogs_nas_request_type_t); ogs_nas_request_type_t target; memcpy(&target, request_type, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" REQUEST_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.15 Traffic flow aggregate description * M LV 2-256 */ int ogs_nas_eps_decode_traffic_flow_aggregate_description(ogs_nas_traffic_flow_aggregate_description_t *traffic_flow_aggregate_description, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_traffic_flow_aggregate_description_t *source = (ogs_nas_traffic_flow_aggregate_description_t *)pkbuf->data; traffic_flow_aggregate_description->length = source->length; size = traffic_flow_aggregate_description->length + sizeof(traffic_flow_aggregate_description->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(traffic_flow_aggregate_description, pkbuf->data - size, size); ogs_trace(" TRAFFIC_FLOW_AGGREGATE_DESCRIPTION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_traffic_flow_aggregate_description(ogs_pkbuf_t *pkbuf, ogs_nas_traffic_flow_aggregate_description_t *traffic_flow_aggregate_description) { uint16_t size = traffic_flow_aggregate_description->length + sizeof(traffic_flow_aggregate_description->length); ogs_nas_traffic_flow_aggregate_description_t target; memcpy(&target, traffic_flow_aggregate_description, sizeof(ogs_nas_traffic_flow_aggregate_description_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TRAFFIC_FLOW_AGGREGATE_DESCRIPTION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.16 Traffic flow template * M LV 2-256 */ int ogs_nas_eps_decode_traffic_flow_template(ogs_nas_traffic_flow_template_t *traffic_flow_template, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_traffic_flow_template_t *source = (ogs_nas_traffic_flow_template_t *)pkbuf->data; traffic_flow_template->length = source->length; size = traffic_flow_template->length + sizeof(traffic_flow_template->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(traffic_flow_template, pkbuf->data - size, size); ogs_trace(" TRAFFIC_FLOW_TEMPLATE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_traffic_flow_template(ogs_pkbuf_t *pkbuf, ogs_nas_traffic_flow_template_t *traffic_flow_template) { uint16_t size = traffic_flow_template->length + sizeof(traffic_flow_template->length); ogs_nas_traffic_flow_template_t target; memcpy(&target, traffic_flow_template, sizeof(ogs_nas_traffic_flow_template_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TRAFFIC_FLOW_TEMPLATE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.17 Transaction identifier * O TLV 3-4 */ int ogs_nas_eps_decode_transaction_identifier(ogs_nas_transaction_identifier_t *transaction_identifier, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_transaction_identifier_t *source = (ogs_nas_transaction_identifier_t *)pkbuf->data; transaction_identifier->length = source->length; size = transaction_identifier->length + sizeof(transaction_identifier->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(transaction_identifier, pkbuf->data - size, size); ogs_trace(" TRANSACTION_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_transaction_identifier(ogs_pkbuf_t *pkbuf, ogs_nas_transaction_identifier_t *transaction_identifier) { uint16_t size = transaction_identifier->length + sizeof(transaction_identifier->length); ogs_nas_transaction_identifier_t target; memcpy(&target, transaction_identifier, sizeof(ogs_nas_transaction_identifier_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" TRANSACTION_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.18 WLAN offload acceptability * O TV 1 */ int ogs_nas_eps_decode_wlan_offload_acceptability(ogs_nas_wlan_offload_acceptability_t *wlan_offload_acceptability, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_wlan_offload_acceptability_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(wlan_offload_acceptability, pkbuf->data - size, size); ogs_trace(" WLAN_OFFLOAD_ACCEPTABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_wlan_offload_acceptability(ogs_pkbuf_t *pkbuf, ogs_nas_wlan_offload_acceptability_t *wlan_offload_acceptability) { uint16_t size = sizeof(ogs_nas_wlan_offload_acceptability_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, wlan_offload_acceptability, size); ogs_trace(" WLAN_OFFLOAD_ACCEPTABILITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.19 NBIFOM container * O TLV 3-257 */ int ogs_nas_eps_decode_nbifom_container(ogs_nas_nbifom_container_t *nbifom_container, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_nbifom_container_t *source = (ogs_nas_nbifom_container_t *)pkbuf->data; nbifom_container->length = source->length; size = nbifom_container->length + sizeof(nbifom_container->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(nbifom_container, pkbuf->data - size, size); ogs_trace(" NBIFOM_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_nbifom_container(ogs_pkbuf_t *pkbuf, ogs_nas_nbifom_container_t *nbifom_container) { uint16_t size = nbifom_container->length + sizeof(nbifom_container->length); ogs_nas_nbifom_container_t target; memcpy(&target, nbifom_container, sizeof(ogs_nas_nbifom_container_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" NBIFOM_CONTAINER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.2 APN aggregate maximum bit rate * O TLV 4-8 */ int ogs_nas_eps_decode_apn_aggregate_maximum_bit_rate(ogs_nas_apn_aggregate_maximum_bit_rate_t *apn_aggregate_maximum_bit_rate, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_apn_aggregate_maximum_bit_rate_t *source = (ogs_nas_apn_aggregate_maximum_bit_rate_t *)pkbuf->data; apn_aggregate_maximum_bit_rate->length = source->length; size = apn_aggregate_maximum_bit_rate->length + sizeof(apn_aggregate_maximum_bit_rate->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(apn_aggregate_maximum_bit_rate, pkbuf->data - size, size); ogs_trace(" APN_AGGREGATE_MAXIMUM_BIT_RATE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_apn_aggregate_maximum_bit_rate(ogs_pkbuf_t *pkbuf, ogs_nas_apn_aggregate_maximum_bit_rate_t *apn_aggregate_maximum_bit_rate) { uint16_t size = apn_aggregate_maximum_bit_rate->length + sizeof(apn_aggregate_maximum_bit_rate->length); ogs_nas_apn_aggregate_maximum_bit_rate_t target; memcpy(&target, apn_aggregate_maximum_bit_rate, sizeof(ogs_nas_apn_aggregate_maximum_bit_rate_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" APN_AGGREGATE_MAXIMUM_BIT_RATE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.22 Header compression configuration * O TLV 5-257 */ int ogs_nas_eps_decode_header_compression_configuration(ogs_nas_header_compression_configuration_t *header_compression_configuration, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_header_compression_configuration_t *source = (ogs_nas_header_compression_configuration_t *)pkbuf->data; header_compression_configuration->length = source->length; size = header_compression_configuration->length + sizeof(header_compression_configuration->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(header_compression_configuration, pkbuf->data - size, size); header_compression_configuration->max_cid = be16toh(header_compression_configuration->max_cid); ogs_trace(" HEADER_COMPRESSION_CONFIGURATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_header_compression_configuration(ogs_pkbuf_t *pkbuf, ogs_nas_header_compression_configuration_t *header_compression_configuration) { uint16_t size = header_compression_configuration->length + sizeof(header_compression_configuration->length); ogs_nas_header_compression_configuration_t target; memcpy(&target, header_compression_configuration, sizeof(ogs_nas_header_compression_configuration_t)); target.max_cid = htobe16(header_compression_configuration->max_cid); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" HEADER_COMPRESSION_CONFIGURATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.23 Control plane only indication * O TV 1 */ int ogs_nas_eps_decode_control_plane_only_indication(ogs_nas_control_plane_only_indication_t *control_plane_only_indication, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_control_plane_only_indication_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(control_plane_only_indication, pkbuf->data - size, size); ogs_trace(" CONTROL_PLANE_ONLY_INDICATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_control_plane_only_indication(ogs_pkbuf_t *pkbuf, ogs_nas_control_plane_only_indication_t *control_plane_only_indication) { uint16_t size = sizeof(ogs_nas_control_plane_only_indication_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, control_plane_only_indication, size); ogs_trace(" CONTROL_PLANE_ONLY_INDICATION - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.26 Extended protocol configuration options * O TLV-E 4-65538 */ int ogs_nas_eps_decode_extended_protocol_configuration_options(ogs_nas_extended_protocol_configuration_options_t *extended_protocol_configuration_options, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_extended_protocol_configuration_options_t *source = (ogs_nas_extended_protocol_configuration_options_t *)pkbuf->data; extended_protocol_configuration_options->length = be16toh(source->length); size = extended_protocol_configuration_options->length + sizeof(extended_protocol_configuration_options->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); extended_protocol_configuration_options->buffer = pkbuf->data - size + sizeof(extended_protocol_configuration_options->length); ogs_trace(" EXTENDED_PROTOCOL_CONFIGURATION_OPTIONS - "); ogs_log_hexdump(OGS_LOG_TRACE, (void*)extended_protocol_configuration_options->buffer, extended_protocol_configuration_options->length); return size; } int ogs_nas_eps_encode_extended_protocol_configuration_options(ogs_pkbuf_t *pkbuf, ogs_nas_extended_protocol_configuration_options_t *extended_protocol_configuration_options) { uint16_t size = 0; uint16_t target; ogs_assert(extended_protocol_configuration_options); ogs_assert(extended_protocol_configuration_options->buffer); size = sizeof(extended_protocol_configuration_options->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); target = htobe16(extended_protocol_configuration_options->length); memcpy(pkbuf->data - size, &target, size); size = extended_protocol_configuration_options->length; ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, extended_protocol_configuration_options->buffer, size); ogs_trace(" EXTENDED_PROTOCOL_CONFIGURATION_OPTIONS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return extended_protocol_configuration_options->length + sizeof(extended_protocol_configuration_options->length); } /* 9.9.4.27 Header compression configuration status * O TLV 4 */ int ogs_nas_eps_decode_header_compression_configuration_status(ogs_nas_header_compression_configuration_status_t *header_compression_configuration_status, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_header_compression_configuration_status_t *source = (ogs_nas_header_compression_configuration_status_t *)pkbuf->data; header_compression_configuration_status->length = source->length; size = header_compression_configuration_status->length + sizeof(header_compression_configuration_status->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(header_compression_configuration_status, pkbuf->data - size, size); ogs_trace(" HEADER_COMPRESSION_CONFIGURATION_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_header_compression_configuration_status(ogs_pkbuf_t *pkbuf, ogs_nas_header_compression_configuration_status_t *header_compression_configuration_status) { uint16_t size = header_compression_configuration_status->length + sizeof(header_compression_configuration_status->length); ogs_nas_header_compression_configuration_status_t target; memcpy(&target, header_compression_configuration_status, sizeof(ogs_nas_header_compression_configuration_status_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" HEADER_COMPRESSION_CONFIGURATION_STATUS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.28 Serving PLMN rate control * O TLV 4 */ int ogs_nas_eps_decode_serving_plmn_rate_control(ogs_nas_serving_plmn_rate_control_t *serving_plmn_rate_control, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_serving_plmn_rate_control_t *source = (ogs_nas_serving_plmn_rate_control_t *)pkbuf->data; serving_plmn_rate_control->length = source->length; size = serving_plmn_rate_control->length + sizeof(serving_plmn_rate_control->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(serving_plmn_rate_control, pkbuf->data - size, size); ogs_trace(" SERVING_PLMN_RATE_CONTROL - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_serving_plmn_rate_control(ogs_pkbuf_t *pkbuf, ogs_nas_serving_plmn_rate_control_t *serving_plmn_rate_control) { uint16_t size = serving_plmn_rate_control->length + sizeof(serving_plmn_rate_control->length); ogs_nas_serving_plmn_rate_control_t target; memcpy(&target, serving_plmn_rate_control, sizeof(ogs_nas_serving_plmn_rate_control_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" SERVING_PLMN_RATE_CONTROL - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.29 Extended APN aggregate maximum bit rate * O TLV 8 */ int ogs_nas_eps_decode_extended_apn_aggregate_maximum_bit_rate(ogs_nas_extended_apn_aggregate_maximum_bit_rate_t *extended_apn_aggregate_maximum_bit_rate, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_extended_apn_aggregate_maximum_bit_rate_t *source = (ogs_nas_extended_apn_aggregate_maximum_bit_rate_t *)pkbuf->data; extended_apn_aggregate_maximum_bit_rate->length = source->length; size = extended_apn_aggregate_maximum_bit_rate->length + sizeof(extended_apn_aggregate_maximum_bit_rate->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(extended_apn_aggregate_maximum_bit_rate, pkbuf->data - size, size); ogs_trace(" EXTENDED_APN_AGGREGATE_MAXIMUM_BIT_RATE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_extended_apn_aggregate_maximum_bit_rate(ogs_pkbuf_t *pkbuf, ogs_nas_extended_apn_aggregate_maximum_bit_rate_t *extended_apn_aggregate_maximum_bit_rate) { uint16_t size = extended_apn_aggregate_maximum_bit_rate->length + sizeof(extended_apn_aggregate_maximum_bit_rate->length); ogs_nas_extended_apn_aggregate_maximum_bit_rate_t target; memcpy(&target, extended_apn_aggregate_maximum_bit_rate, sizeof(ogs_nas_extended_apn_aggregate_maximum_bit_rate_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EXTENDED_APN_AGGREGATE_MAXIMUM_BIT_RATE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.2A Connectivity type * O TV 1 */ int ogs_nas_eps_decode_connectivity_type(ogs_nas_connectivity_type_t *connectivity_type, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_connectivity_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(connectivity_type, pkbuf->data - size, size); ogs_trace(" CONNECTIVITY_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_connectivity_type(ogs_pkbuf_t *pkbuf, ogs_nas_connectivity_type_t *connectivity_type) { uint16_t size = sizeof(ogs_nas_connectivity_type_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, connectivity_type, size); ogs_trace(" CONNECTIVITY_TYPE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.3 EPS quality of service * M LV 2-14 */ int ogs_nas_eps_decode_eps_quality_of_service(ogs_nas_eps_quality_of_service_t *eps_quality_of_service, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_eps_quality_of_service_t *source = (ogs_nas_eps_quality_of_service_t *)pkbuf->data; eps_quality_of_service->length = source->length; size = eps_quality_of_service->length + sizeof(eps_quality_of_service->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(eps_quality_of_service, pkbuf->data - size, size); ogs_trace(" EPS_QUALITY_OF_SERVICE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_eps_quality_of_service(ogs_pkbuf_t *pkbuf, ogs_nas_eps_quality_of_service_t *eps_quality_of_service) { uint16_t size = eps_quality_of_service->length + sizeof(eps_quality_of_service->length); ogs_nas_eps_quality_of_service_t target; memcpy(&target, eps_quality_of_service, sizeof(ogs_nas_eps_quality_of_service_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EPS_QUALITY_OF_SERVICE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.30 Extended quality of service * O TLV 12 */ int ogs_nas_eps_decode_extended_quality_of_service(ogs_nas_extended_quality_of_service_t *extended_quality_of_service, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_extended_quality_of_service_t *source = (ogs_nas_extended_quality_of_service_t *)pkbuf->data; extended_quality_of_service->length = source->length; size = extended_quality_of_service->length + sizeof(extended_quality_of_service->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(extended_quality_of_service, pkbuf->data - size, size); ogs_trace(" EXTENDED_QUALITY_OF_SERVICE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_extended_quality_of_service(ogs_pkbuf_t *pkbuf, ogs_nas_extended_quality_of_service_t *extended_quality_of_service) { uint16_t size = extended_quality_of_service->length + sizeof(extended_quality_of_service->length); ogs_nas_extended_quality_of_service_t target; memcpy(&target, extended_quality_of_service, sizeof(ogs_nas_extended_quality_of_service_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" EXTENDED_QUALITY_OF_SERVICE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.4 ESM cause * O TV 2 */ int ogs_nas_eps_decode_esm_cause(ogs_nas_esm_cause_t *esm_cause, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_esm_cause_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(esm_cause, pkbuf->data - size, size); ogs_trace(" ESM_CAUSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_esm_cause(ogs_pkbuf_t *pkbuf, ogs_nas_esm_cause_t *esm_cause) { uint16_t size = sizeof(ogs_nas_esm_cause_t); ogs_nas_esm_cause_t target; memcpy(&target, esm_cause, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" ESM_CAUSE - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.5 ESM information transfer flag * O TV 1 */ int ogs_nas_eps_decode_esm_information_transfer_flag(ogs_nas_esm_information_transfer_flag_t *esm_information_transfer_flag, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_esm_information_transfer_flag_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(esm_information_transfer_flag, pkbuf->data - size, size); ogs_trace(" ESM_INFORMATION_TRANSFER_FLAG - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_esm_information_transfer_flag(ogs_pkbuf_t *pkbuf, ogs_nas_esm_information_transfer_flag_t *esm_information_transfer_flag) { uint16_t size = sizeof(ogs_nas_esm_information_transfer_flag_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, esm_information_transfer_flag, size); ogs_trace(" ESM_INFORMATION_TRANSFER_FLAG - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.6 Linked EPS bearer identity * M V 1/2 */ int ogs_nas_eps_decode_linked_eps_bearer_identity(ogs_nas_linked_eps_bearer_identity_t *linked_eps_bearer_identity, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_linked_eps_bearer_identity_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(linked_eps_bearer_identity, pkbuf->data - size, size); ogs_trace(" LINKED_EPS_BEARER_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_linked_eps_bearer_identity(ogs_pkbuf_t *pkbuf, ogs_nas_linked_eps_bearer_identity_t *linked_eps_bearer_identity) { uint16_t size = sizeof(ogs_nas_linked_eps_bearer_identity_t); ogs_nas_linked_eps_bearer_identity_t target; memcpy(&target, linked_eps_bearer_identity, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" LINKED_EPS_BEARER_IDENTITY - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.7 LLC service access point identifier * O TV 2 */ int ogs_nas_eps_decode_llc_service_access_point_identifier(ogs_nas_llc_service_access_point_identifier_t *llc_service_access_point_identifier, ogs_pkbuf_t *pkbuf) { uint16_t size = sizeof(ogs_nas_llc_service_access_point_identifier_t); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(llc_service_access_point_identifier, pkbuf->data - size, size); ogs_trace(" LLC_SERVICE_ACCESS_POINT_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_llc_service_access_point_identifier(ogs_pkbuf_t *pkbuf, ogs_nas_llc_service_access_point_identifier_t *llc_service_access_point_identifier) { uint16_t size = sizeof(ogs_nas_llc_service_access_point_identifier_t); ogs_nas_llc_service_access_point_identifier_t target; memcpy(&target, llc_service_access_point_identifier, size); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" LLC_SERVICE_ACCESS_POINT_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.8 Packet flow Identifier * O TLV 3 */ int ogs_nas_eps_decode_packet_flow_identifier(ogs_nas_packet_flow_identifier_t *packet_flow_identifier, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_packet_flow_identifier_t *source = (ogs_nas_packet_flow_identifier_t *)pkbuf->data; packet_flow_identifier->length = source->length; size = packet_flow_identifier->length + sizeof(packet_flow_identifier->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(packet_flow_identifier, pkbuf->data - size, size); ogs_trace(" PACKET_FLOW_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_packet_flow_identifier(ogs_pkbuf_t *pkbuf, ogs_nas_packet_flow_identifier_t *packet_flow_identifier) { uint16_t size = packet_flow_identifier->length + sizeof(packet_flow_identifier->length); ogs_nas_packet_flow_identifier_t target; memcpy(&target, packet_flow_identifier, sizeof(ogs_nas_packet_flow_identifier_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" PACKET_FLOW_IDENTIFIER - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } /* 9.9.4.9 PDN address * M LV 6-14 */ int ogs_nas_eps_decode_pdn_address(ogs_nas_pdn_address_t *pdn_address, ogs_pkbuf_t *pkbuf) { uint16_t size = 0; ogs_nas_pdn_address_t *source = (ogs_nas_pdn_address_t *)pkbuf->data; pdn_address->length = source->length; size = pdn_address->length + sizeof(pdn_address->length); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pdn_address, pkbuf->data - size, size); ogs_trace(" PDN_ADDRESS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; } int ogs_nas_eps_encode_pdn_address(ogs_pkbuf_t *pkbuf, ogs_nas_pdn_address_t *pdn_address) { uint16_t size = pdn_address->length + sizeof(pdn_address->length); ogs_nas_pdn_address_t target; memcpy(&target, pdn_address, sizeof(ogs_nas_pdn_address_t)); ogs_assert(ogs_pkbuf_pull(pkbuf, size)); memcpy(pkbuf->data - size, &target, size); ogs_trace(" PDN_ADDRESS - "); ogs_log_hexdump(OGS_LOG_TRACE, pkbuf->data - size, size); return size; }
gpl-3.0
hkzlab/libvk8055
src/debounce_map.c
1
1724
#define DEBOUNCE_MAP_LENGTH 256 static const Uint16 debounce_map[] = { 0, 1, 2, 3, 4, 5, 7, 9, 11, 13, 16, 18, 21, 25, 28, 32, 36, 40, 44, 49, 54, 59, 64, 70, 75, 81, 87, 94, 101, 107, 115, 122, 130, 137, 145, 154, 162, 171, 180, 189, 199, 208, 218, 228, 239, 249, 260, 271, 282, 294, 306, 317, 330, 342, 355, 368, 381, 394, 408, 421, 435, 450, 464, 479, 494, 509, 524, 540, 556, 572, 588, 605, 622, 639, 656, 674, 691, 709, 727, 746, 764, 783, 802, 822, 841, 861, 881, 901, 922, 942, 963, 984, 1006, 1027, 1049, 1071, 1094, 1116, 1139, 1162, 1185, 1209, 1232, 1256, 1280, 1305, 1329, 1354, 1379, 1405, 1430, 1456, 1482, 1508, 1535, 1561, 1588, 1615, 1643, 1670, 1698, 1726, 1755, 1783, 1812, 1841, 1870, 1899, 1929, 1959, 1989, 2019, 2050, 2081, 2112, 2143, 2175, 2206, 2238, 2271, 2303, 2336, 2369, 2402, 2435, 2469, 2502, 2537, 2571, 2605, 2640, 2675, 2710, 2746, 2781, 2817, 2853, 2890, 2926, 2963, 3000, 3037, 3075, 3112, 3150, 3189, 3227, 3266, 3304, 3344, 3383, 3422, 3462, 3502, 3543, 3583, 3624, 3665, 3706, 3747, 3789, 3831, 3873, 3915, 3958, 4000, 4043, 4087, 4130, 4174, 4218, 4262, 4306, 4351, 4396, 4441, 4486, 4532, 4578, 4624, 4670, 4716, 4763, 4810, 4857, 4904, 4952, 5000, 5048, 5096, 5145, 5193, 5242, 5292, 5341, 5391, 5441, 5491, 5541, 5592, 5643, 5694, 5745, 5797, 5848, 5900, 5952, 6005, 6058, 6110, 6164, 6217, 6271, 6324, 6378, 6433, 6487, 6542, 6597, 6652, 6708, 6763, 6819, 6875, 6932, 6988, 7045, 7102, 7159, 7217, 7275, 7332, 7391, 7449 };
gpl-3.0
fabienbaron/squeeze
src/models/modelcode_spots.c
1
4106
/* modelcode_ud bwsmearing.c: An offset UD with bw smearing parameter JDM MACIM - software for the creation of images consistent with data sets from optical interferometry, using a Monte-Carlo Markov Chain algorithm. Copyright (c) 2006 California Institute of Technology. Written by Dr. Michael Ireland with contributions from Prof. John Monnier (University of Michigan). For comments or questions about this software, please contact the author at mireland@gps.caltech.edu. 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 provided "as is" and 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. In no event shall California Institute of Technology be liable to any party for direct, indirect, special, incidental or consequential damages, including lost profits, arising out of the use of this software and its documentation, even if the California Institute of Technology has been advised of the possibility of such damage. The California Institute of Technology has no obligation to provide maintenance, support, updates, enhancements or modifications. 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. ------------------------------ JDM test code for imager program. Using JYoung code. model_UD: Uniform Disk model centered at (0,0) params: visib at uv=0, diameter in milliarcseconds, unresolved flux inputs: u,v, are in the wavelengths. logl is the a priori -log likelihood of the parameter combination. ------------------------------ To change this: ANY model is possible here, as long as model complex visibilities can be returned based on a combinarion of up to MAX_PARAMS (default 20 in macim.h) parameters. */ // params(0) = delta RA in mas from phase center (EAST => +) // params(1) = delta DEC in mas from phase center (NORTH => +) // params(2) = Brightness // params(3) = UD size (mas) // /* Globals: nparams, nbaselines, u, v*/ int model_vis(double *params, double complex *modvis, double *logl, double *flux_frac) { int status = 0; long i; double tempd, vis_primary = 1.0, delta_ra, delta_dec; double complex phase_factor; double l0, l1, l2, l3; double p0, p1, p2, p3; //priors double sig0, sig1, sig2, sig3; // width of priors // Enter priors: p0 = 0.0; sig0 = 3.0 ; p1 = 0.0; sig1 = 3.; p2 = .16; sig2 = 0.4; p3 = 0.5; sig3 = 1.0; delta_dec = params[1] / MAS_RAD; delta_ra = params[0] / MAS_RAD; for(i = 0; i < nbaselines; i++) { if(params[3] > 0) { tempd = PI * params[3] / MAS_RAD * sqrt(u[i] * u[i] + v[i] * v[i]) + 1e-15; vis_primary = 2 * j1(tempd) / tempd; } else vis_primary = 1.0; vis_primary *= params[2]; phase_factor = cexp(-2.0 * PI * (u[i] * delta_ra + v[i] * delta_dec)) ; modvis[i] = vis_primary * phase_factor; } // For vis0, allow equal probability between 0,1 l0 = exp(-.5 * pow((params[0] - p0) / sig0 , 2)); l1 = exp(-.5 * pow((params[1] - p1) / sig1 , 2)); l2 = exp(-.5 * pow((params[2] - p2) / sig2 , 2)); l3 = exp(-.5 * pow((params[3] - p3) / sig3 , 2)); if(params[2] < -0.3 || params[2] > 0.) l2 = 1e-6; if(params[3] < 0. || params[3] > 1.0) l3 = 1e-6; if((sqrt(params[0]*params[0] + params[1] * params[1]) + params[3]) > 1.375) { l0 = 1e-7; l1 = 1e-7; } *logl = -1.0 * log(l0 * l1 * l2 * l3); *flux_frac = 1.0 - params[2]; return (status != 0); }
gpl-3.0
Distrotech/guile
lib/safe-read.c
1
2172
/* An interface to read and write that retries after interrupts. Copyright (C) 1993-1994, 1998, 2002-2006, 2009-2013 Free Software Foundation, Inc. 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 <config.h> /* Specification. */ #ifdef SAFE_WRITE # include "safe-write.h" #else # include "safe-read.h" #endif /* Get ssize_t. */ #include <sys/types.h> #include <unistd.h> #include <errno.h> #ifdef EINTR # define IS_EINTR(x) ((x) == EINTR) #else # define IS_EINTR(x) 0 #endif #include <limits.h> #ifdef SAFE_WRITE # define safe_rw safe_write # define rw write #else # define safe_rw safe_read # define rw read # undef const # define const /* empty */ #endif /* Read(write) up to COUNT bytes at BUF from(to) descriptor FD, retrying if interrupted. Return the actual number of bytes read(written), zero for EOF, or SAFE_READ_ERROR(SAFE_WRITE_ERROR) upon error. */ size_t safe_rw (int fd, void const *buf, size_t count) { /* Work around a bug in Tru64 5.1. Attempting to read more than INT_MAX bytes fails with errno == EINVAL. See <http://lists.gnu.org/archive/html/bug-gnu-utils/2002-04/msg00010.html>. When decreasing COUNT, keep it block-aligned. */ enum { BUGGY_READ_MAXIMUM = INT_MAX & ~8191 }; for (;;) { ssize_t result = rw (fd, buf, count); if (0 <= result) return result; else if (IS_EINTR (errno)) continue; else if (errno == EINVAL && BUGGY_READ_MAXIMUM < count) count = BUGGY_READ_MAXIMUM; else return result; } }
gpl-3.0
ethereum/cpp-ethereum
test/tools/libtesteth/TestSuite.cpp
1
9416
// Aleth: Ethereum C++ client, tools and libraries. // Copyright 2017-2019 Aleth Authors. // Licensed under the GNU General Public License, Version 3. /// @file /// Base functions for all test suites #include <test/tools/libtesteth/JsonSpiritHeaders.h> #include <test/tools/libtesteth/Stats.h> #include <test/tools/libtesteth/TestHelper.h> #include <test/tools/libtesteth/TestSuite.h> #include <boost/algorithm/string.hpp> #include <string> using namespace std; using namespace dev; namespace fs = boost::filesystem; //Helper functions for test proccessing namespace { struct TestFileData { json_spirit::mValue data; h256 hash; }; void removeComments(json_spirit::mValue& _obj) { if (_obj.type() == json_spirit::obj_type) { list<string> removeList; for (auto& i: _obj.get_obj()) { if (i.first.substr(0, 2) == "//") { removeList.push_back(i.first); continue; } removeComments(i.second); } for (auto& i: removeList) _obj.get_obj().erase(_obj.get_obj().find(i)); } else if (_obj.type() == json_spirit::array_type) { for (auto& i: _obj.get_array()) removeComments(i); } } TestFileData readTestFile(fs::path const& _testFileName) { TestFileData testData; string const s = dev::contentsString(_testFileName); BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + _testFileName.string() + " is empty."); if (_testFileName.extension() == ".json") json_spirit::read_string(s, testData.data); else if (_testFileName.extension() == ".yml") testData.data = test::parseYamlToJson(s); else BOOST_ERROR("Unknow test format!" + test::TestOutputHelper::get().testFile().string()); string srcString = json_spirit::write_string(testData.data, false); if (test::Options::get().showhash) std::cout << "'" << srcString << "'" << std::endl; testData.hash = sha3(srcString); return testData; } void addClientInfo(json_spirit::mValue& _v, fs::path const& _testSource, h256 const& _testSourceHash) { for (auto& i: _v.get_obj()) { json_spirit::mObject& o = i.second.get_obj(); json_spirit::mObject clientinfo; string comment; if (o.count("_info")) { json_spirit::mObject& existingInfo = o["_info"].get_obj(); if (existingInfo.count("comment")) comment = existingInfo["comment"].get_str(); } clientinfo["filledwith"] = test::prepareVersionString(); clientinfo["lllcversion"] = test::prepareLLLCVersionString(); clientinfo["source"] = _testSource.string(); clientinfo["sourceHash"] = toString(_testSourceHash); clientinfo["comment"] = comment; o["_info"] = clientinfo; } } void checkFillerHash(fs::path const& _compiledTest, fs::path const& _sourceTest) { json_spirit::mValue filledTest; string const s = dev::contentsString(_compiledTest); BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " + _compiledTest.string() + " is empty."); json_spirit::read_string(s, filledTest); TestFileData fillerData = readTestFile(_sourceTest); for (auto& i: filledTest.get_obj()) { BOOST_REQUIRE_MESSAGE(i.second.type() == json_spirit::obj_type, i.first + " should contain an object under a test name."); json_spirit::mObject const& obj = i.second.get_obj(); BOOST_REQUIRE_MESSAGE(obj.count("_info") > 0, "_info section not set! " + _compiledTest.string()); json_spirit::mObject const& info = obj.at("_info").get_obj(); BOOST_REQUIRE_MESSAGE(info.count("sourceHash") > 0, "sourceHash not found in " + _compiledTest.string() + " in " + i.first); h256 const sourceHash = h256(info.at("sourceHash").get_str()); BOOST_CHECK_MESSAGE(sourceHash == fillerData.hash, "Test " + _compiledTest.string() + " in " + i.first + " is outdated. Filler hash is different! ( '" + sourceHash.hex().substr(0, 4) + "' != '" + fillerData.hash.hex().substr(0, 4) + "') "); } } } namespace dev { namespace test { string const c_fillerPostf = "Filler"; string const c_copierPostf = "Copier"; void TestSuite::runTestWithoutFiller(boost::filesystem::path const& _file) const { // Allow to execute a custom test .json file on any test suite auto& testOutput = test::TestOutputHelper::get(); testOutput.initTest(1); executeFile(_file); testOutput.finishTest(); } void TestSuite::runAllTestsInFolder(string const& _testFolder) const { // check that destination folder test files has according Filler file in src folder string const filter = test::Options::get().singleTestName.empty() ? string() : test::Options::get().singleTestName; vector<fs::path> const compiledFiles = test::getFiles(getFullPath(_testFolder), {".json", ".yml"} ,filter); for (auto const& file: compiledFiles) { fs::path const expectedFillerName = getFullPathFiller(_testFolder) / fs::path(file.stem().string() + c_fillerPostf + ".json"); fs::path const expectedFillerName2 = getFullPathFiller(_testFolder) / fs::path(file.stem().string() + c_fillerPostf + ".yml"); fs::path const expectedCopierName = getFullPathFiller(_testFolder) / fs::path(file.stem().string() + c_copierPostf + ".json"); BOOST_REQUIRE_MESSAGE(fs::exists(expectedFillerName) || fs::exists(expectedFillerName2) || fs::exists(expectedCopierName), "Compiled test folder contains test without Filler: " + file.filename().string()); BOOST_REQUIRE_MESSAGE(!(fs::exists(expectedFillerName) && fs::exists(expectedFillerName2) && fs::exists(expectedCopierName)), "Src test could either be Filler.json, Filler.yml or Copier.json: " + file.filename().string()); // Check that filled tests created from actual fillers if (Options::get().filltests == false) { if (fs::exists(expectedFillerName)) checkFillerHash(file, expectedFillerName); if (fs::exists(expectedFillerName2)) checkFillerHash(file, expectedFillerName2); if (fs::exists(expectedCopierName)) checkFillerHash(file, expectedCopierName); } } // run all tests vector<fs::path> const files = test::getFiles(getFullPathFiller(_testFolder), {".json", ".yml"}, filter.empty() ? filter : filter + "Filler"); auto& testOutput = test::TestOutputHelper::get(); testOutput.initTest(files.size()); for (auto const& file: files) { testOutput.showProgress(); testOutput.setCurrentTestFile(file); executeTest(_testFolder, file); } testOutput.finishTest(); } fs::path TestSuite::getFullPathFiller(string const& _testFolder) const { return test::getTestPath() / "src" / suiteFillerFolder() / _testFolder; } fs::path TestSuite::getFullPath(string const& _testFolder) const { return test::getTestPath() / suiteFolder() / _testFolder; } void TestSuite::executeTest(string const& _testFolder, fs::path const& _testFileName) const { fs::path const boostRelativeTestPath = fs::relative(_testFileName, getTestPath()); string testname = _testFileName.stem().string(); bool isCopySource = false; if (testname.rfind(c_fillerPostf) != string::npos) testname = testname.substr(0, testname.rfind("Filler")); else if (testname.rfind(c_copierPostf) != string::npos) { testname = testname.substr(0, testname.rfind(c_copierPostf)); isCopySource = true; } else BOOST_REQUIRE_MESSAGE(false, "Incorrect file suffix in the filler folder! " + _testFileName.string()); // Filename of the test that would be generated fs::path const boostTestPath = getFullPath(_testFolder) / fs::path(testname + ".json"); // TODO: An old unmaintained way to gather execution stats needs review. if (Options::get().stats) Listener::registerListener(Stats::get()); if (Options::get().filltests) { if (isCopySource) { clog << "Copying " << _testFileName.string() << "\n"; clog << " TO " << boostTestPath.string() << "\n"; assert(_testFileName.string() != boostTestPath.string()); TestOutputHelper::get().showProgress(); dev::test::copyFile(_testFileName, boostTestPath); BOOST_REQUIRE_MESSAGE(boost::filesystem::exists(boostTestPath.string()), "Error when copying the test file!"); // Update _info and build information of the copied test json_spirit::mValue v; string const s = asString(dev::contents(boostTestPath)); json_spirit::read_string(s, v); addClientInfo(v, boostRelativeTestPath, readTestFile(_testFileName).hash); writeFile(boostTestPath, asBytes(json_spirit::write_string(v, true))); } else { if (Options::get().singleTestName.empty()) cnote << "Populating tests..."; TestFileData fillerData = readTestFile(_testFileName); removeComments(fillerData.data); json_spirit::mValue output = doTests(fillerData.data, true); addClientInfo(output, boostRelativeTestPath, fillerData.hash); writeFile(boostTestPath, asBytes(json_spirit::write_string(output, true))); } } // Test is generated. Now run it and check that there should be no errors if (Options::get().verbosity > 1) std::cout << "TEST " << testname << ":\n"; Listener::notifySuiteStarted(testname); // Outdated logging executeFile(boostTestPath); } void TestSuite::executeFile(boost::filesystem::path const& _file) const { json_spirit::mValue v; string const s = asString(dev::contents(_file)); BOOST_REQUIRE_MESSAGE(s.length() > 0, "Contents of " << _file.string() << " is empty. Have you cloned the 'tests' repo branch develop and set ETHEREUM_TEST_PATH to its path?"); json_spirit::read_string(s, v); doTests(v, false); } } }
gpl-3.0
sphantix/ocsi
src/main/inform.c
1
2104
/* * File Name: inform.c * Author: Sphantix * Mail: sphantix@gmail.com * Created Time: Fri 27 Nov 2015 10:37:02 AM CST */ #include <libsol-util/utl_logging.h> #include <libsol-util/utl_memory.h> #include "inform.h" #include "event.h" static ocsi_event_info_t event_infos[] = { {OCSI_EVENT_FIRSTBOOT, OCSI_SOCKET_TCP, OCSI_CONNECTION_SHORT, OCSI_TRANS_PROTO_HTTP, OCSI_APP_PROTO_JSON}, {OCSI_EVENT_BOOT, OCSI_SOCKET_TCP, OCSI_CONNECTION_SHORT, OCSI_TRANS_PROTO_HTTP, OCSI_APP_PROTO_JSON}, }; void ocsi_inform_new_event(ocsi_t *ocsi, ocsi_uint_t type) { ocsi_event_t *ev = NULL; utlLog_debug("entered with event type=%d", type); /* Check for duplicate event codes in the send list. */ dlist_for_each_entry(ev, &ocsi->work_list, node) { if (ev->type == type) { utlLog_debug("event %d is already in send list, do nothing", type); return; } } if (ocsi->send_event_cnt < OCSI_MAX_EVENTS) { //get event from complete list if (ocsi->complete_event_cnt > 0) { ev = dlist_entry(&ocsi->complete_list, ocsi_event_t, node); dlist_del(&ev->node); ocsi->complete_event_cnt--; } else { ev = utlMem_alloc(sizeof(ocsi_event_t), ALLOC_ZEROIZE); if (!ev) { utlLog_error("alloc memory for new event error, and event error!"); return; } } ev->state = OCSI_EVENT_STATE_SEND; ev->type = type; ev->func = NULL; ev->ctx = NULL; ev->fd = -1; //register event ops if(event_infos[ev->type].socket == OCSI_SOCKET_TCP) { //register socket ops } //and event to send list dlist_add(&ev->node, &ocsi->work_list); ocsi->send_event_cnt++; utlLog_debug("adding event %d to send list, count is now %d", type, ocsi->send_event_cnt); } else { utlLog_error("too many events in send list, count=%d", ocsi->send_event_cnt); } }
gpl-3.0
librarian/arm-labs
lab2-test.c
1
3847
// Lab2 buttons and encoder // Copyright (C) 2010 Nikita A Menkovich menkovich@gmail.com // git repository can be found on: https://github.com/librarian/arm-labs #include "includes.h"; // total numbers of buttons #define NUM_BTN (sizeof BTN_addr / sizeof BTN_addr[0]) // total size of array div to total size of first element // BUG: if elements have different size, we could not take number of elements // configure buttons, if there will be keyboard, we could add addresses easy static int BTN_addr[] = { 0x0020, // btn1 0x0040, // btn2 0x0080, // btn3 0x0200 // btn4 }; int BTN_cur[NUM_BTN]; int BTN_prev[NUM_BTN]; int ENCA_cur, ENCA_prev; //Ãëîáàëüíûå ïåðåìåííûå òåêóùåãî è ïðåäûäóùåãî ñîñòîÿíèé êîíòàêòà À int ENCB_cur, ENCB_prev; //Ãëîáàëüíûå ïåðåìåííûå òåêóùåãî è ïðåäûäóùåãî ñîñòîÿíèé êîíòàêòà B int GetEncState() { int state = 0; ENCA_cur = (FIO0PIN & 0x00000800) >> 11; //×òåíèå òåêóùåãî ñîñòîÿíèÿ êîíòàêòà À ýíêîäåðà (P0.11) ENCB_cur = (FIO0PIN & 0x00200000) >> 21; //×òåíèå òåêóùåãî ñîñòîÿíèÿ êîíòàêòà B ýíêîäåðà (P0.21) if( (ENCA_cur != ENCA_prev) ) //Åñëè ñîñòîÿíèå êîíòàêòà À ýíêîäåðà èçìåíèëîñü { if( !ENCA_cur ) //Åñëè òåêóùåå ñîñòîÿíèå êîíòàêòà À ýíêîäåðà - 0 (ïåðåõîä èç 1) { if( !ENCB_cur ) //Åñëè òåêóùåå êîíòàêòà B ýíêîäåðà - 0 state = 1; //Ïåðåìåííàÿ ñîñòîÿíèÿ îçíà÷àåò, ÷òî âðàùåíèå ïî ÷àñîâîé else state = -1; //Ïåðåìåííàÿ ñîñòîÿíèÿ îçíà÷àåò, ÷òî âðàùåíèå ïðîòèâ ÷àñîâîé } else //Åñëè òåêóùåå ñîñòîÿíèå êîíòàêòà À ýíêîäåðà - 1 (ïåðåõîä èç 0) { if( ENCB_cur ) //Åñëè òåêóùåå êîíòàêòà B ýíêîäåðà - 1 state = 1; //Ïåðåìåííàÿ ñîñòîÿíèÿ îçíà÷àåò, ÷òî âðàùåíèå ïî ÷àñîâîé else state = -1; //Ïåðåìåííàÿ ñîñòîÿíèÿ îçíà÷àåò, ÷òî âðàùåíèå ïðîòèâ ÷àñîâîé } ENCA_prev = ENCA_cur;//Òåêóùåå ñîñòîÿíèå ñîõðàíÿåòñÿ â ïåðåìåííûõ, //êîòîðûå áóäóò ïðåäûäóùèìè â ñëåäóþùåì öèêëå ïðîâåðêè ENCB_prev = ENCB_cur; return state; //Âîçâðàùàåì ñîñòîÿíèå 0 åñëè ýíêîäåð íå âðàùàåòñÿ, //1 åñëè âðàùàåòñÿ ïî ÷àñîâîé è -1 åñëè ïðîòèâ ÷àñîâîé } } int GetBTNState(int btn) { int state = 0; BTN_cur[btn] = FIO0PIN & BTN_addr[btn]; if( BTN_cur[btn] != BTN_prev[btn]) // changed { if( !BTN_cur[btn] ) state = 1; // pressed } BTN_prev[btn] = BTN_cur[btn]; return state; } static void Delay(unsigned ms) { ms = ms/3000; while (ms != 0 ) { ms--; }; } void main (void) { int a = 1; // lamp number int direction = 1; // rotate left 1, rotate right 0 int move = 1; // if lights moving = 1 int speed = 2; // speed int btn = 0; // btn number FIO0DIR = 0x00000000; // Âñå ðàçðÿäû ïîðòà 0 íà ââîä äëÿ ÷òåíèÿ ñîñòîÿíèÿ êíîïîê è ýíêîäåðà FIO2DIR = 0x00FF; // Áèòû 0-7 ïîðòà 2 íà âûâîä äëÿ óïðàâëåíèÿ ñâåòîäèîäàìè ENCA_cur = ENCA_prev = (FIO0PIN & 0x00000800) >> 11; //×òåíèå íà÷àëüíîãî ñîñòîÿíèÿ êîíòàêòà À ýíêîäåðà (P0.11) ENCB_cur = ENCB_prev = (FIO0PIN & 0x00200000) >> 21; //×òåíèå íà÷àëüíîãî ñîñòîÿíèÿ êîíòàêòà B ýíêîäåðà (P0.21) for (btn = 0; btn <= NUM_BTN; btn++) { BTN_cur[btn] = BTN_prev[btn] = FIO0PIN & BTN_addr[btn]; // initialize all buttons } while (1)//Loop forever { if ( GetBtnState(0) ) move = 0; // pause if ( GetBtnState(1) ) move = 1; // play if ( GetBtnState(2) ) direction = !direction; // change direction if ( GetBtnState(3) ) direction = !direction; // change direction switch ( GetEncState() ) { case 1: // nd4spd speed = speed++; break; case -1: // nd4slw speed = speed--; break; } if ( move ) { if ( direction ) a <<= 1; // lights move to the right. equal *2 else a >>= 1; // lights move to the left. equal *2 } if ( ( a & 0x0100 ) && direction ) a = 1; // catch left and revert if ( ( !a ) && !direction ) a = 0x0080; // catch right and revert FIO2PIN = a; // stdout Delay(speed*1000); // delay nearly to 1 sec } }
gpl-3.0
ElkMonster/gloost-oma
src/Matrix.cpp
1
24438
/* ___ __ /\_ \ /\ \__ __ \//\ \ ___ ___ ____\ \ _\ /'_ `\ \ \ \ / __`\ / __`\ / __\\ \ \/ /\ \ \ \ \_\ \_/\ \ \ \/\ \ \ \/\__ \\ \ \_ \ \____ \/\____\ \____/\ \____/\/\____/ \ \__\ \/___/\ \/____/\/___/ \/___/ \/___/ \/__/ /\____/ \_/__/ OpenGL framework for fast demo programming http://www.gloost.org This file is part of the gloost framework. You can use it in parts or as whole under the terms of the GPL (http://www.gnu.org/licenses/#GPL). gloost is being created by Felix Weißig and Stephan Beck Felix Weißig (thesleeper@gmx.net), Stephan Beck (stephan@pixelstars.de) */ /// cpp includes #include <cstring> /// gloost includes #include <Matrix.h> #include <Vector3.h> #include <Point3.h> #include <Ray.h> namespace gloost { //////////////////////////////////////////////////////////////////////////////// /// class constructor Matrix::Matrix(): _data() { // setIdentity(); } //////////////////////////////////////////////////////////////////////////////// /// copy constructor Matrix::Matrix(const Matrix& m): _data() { (*this) = m; } //////////////////////////////////////////////////////////////////////////////// /// copy constructor Matrix::Matrix(const mathType v[16]): _data() { memcpy(_data, v, sizeof(mathType)*16); } //////////////////////////////////////////////////////////////////////////////// /// copy constructor //Matrix::Matrix(const mathType* v): // _data() //{ // for(unsigned int i=0; i != 16; ++i) // { // _data[i] = (mathType)v[i]; // } //} //////////////////////////////////////////////////////////////////////////////// /// value constructor Matrix::Matrix(const Vector3& col_1, const Vector3& col_2, const Vector3& col_3, const Point3& col_4): _data() { _data[0] = col_1[0]; _data[1] = col_1[1]; _data[2] = col_1[2]; _data[3] = 0; _data[4] = col_2[0]; _data[5] = col_2[1]; _data[6] = col_2[2]; _data[7] = 0; _data[8] = col_3[0]; _data[9] = col_3[1]; _data[10] = col_3[2]; _data[11] = 0; _data[12] = col_4[0]; _data[13] = col_4[1]; _data[14] = col_4[2]; _data[15] = 1; } //////////////////////////////////////////////////////////////////////////////// /// class destructor /*virtual*/ Matrix::~Matrix() { } //////////////////////////////////////////////////////////////////////////////// /// class destructor mathType Matrix::get( unsigned int i, unsigned int j) const { return _data[4*i+j]; } //////////////////////////////////////////////////////////////////////////////// /// class destructor void Matrix::set( unsigned int i, unsigned int j, mathType value) { _data[4*i+j] = value; } //////////////////////////////////////////////////////////////////////////////// /// set all values of the matrix void Matrix::setData(const mathType v[16]) { for(unsigned int i=0; i != 16; ++i) { _data[i] = (mathType)v[i]; } } //////////////////////////////////////////////////////////////////////////////// /// get 4x4 matrix as an vector of 16 mathTypes const mathType* Matrix::data() const { return (_data); } //////////////////////////////////////////////////////////////////////////////// /// get 4x4 matrix as an vector of 16 mathTypes mathType* Matrix::data() { return (_data); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setIdentity() { _data[0] = 1; _data[1] = 0; _data[2] = 0; _data[3] = 0; _data[4] = 0; _data[5] = 1; _data[6] = 0; _data[7] = 0; _data[8] = 0; _data[9] = 0; _data[10] = 1; _data[11] = 0; _data[12] = 0; _data[13] = 0; _data[14] = 0; _data[15] = 1; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::invert () { mathType rDet; Matrix result; mathType a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4; a1 = _data[0]; // data_[0].values[0]; b1 = _data[4]; // data_[1].values[0]; c1 = _data[8]; // data_[2].values[0]; d1 = _data[12]; // data_[3].values[0]; a2 = _data[1]; // data_[0].values[1]; b2 = _data[5]; // data_[1].values[1]; c2 = _data[9]; // data_[2].values[1]; d2 = _data[13]; // data_[3].values[1]; a3 = _data[2]; // data_[0].values[2]; b3 = _data[6]; // data_[1].values[2]; c3 = _data[10]; // data_[2].values[2]; d3 = _data[14]; // data_[3].values[2]; a4 = _data[3]; // data_[0].values[3]; b4 = _data[7]; // data_[1].values[3]; c4 = _data[11]; // data_[2].values[3]; d4 = _data[15]; // data_[3].values[3]; rDet = det(); if(fabs(rDet) < 0.00001) { //std::cout << std::endl << "fabs(rDet) < EPS: " << fabs(rDet) << std::endl; setIdentity(); return; } rDet = 1.f / rDet; result[0] = det3(b2, b3, b4, c2, c3, c4, d2, d3, d4) * rDet; result[1] = - det3(a2, a3, a4, c2, c3, c4, d2, d3, d4) * rDet; result[2] = det3(a2, a3, a4, b2, b3, b4, d2, d3, d4) * rDet; result[3] = - det3(a2, a3, a4, b2, b3, b4, c2, c3, c4) * rDet; result[4] = - det3(b1, b3, b4, c1, c3, c4, d1, d3, d4) * rDet; result[5] = det3(a1, a3, a4, c1, c3, c4, d1, d3, d4) * rDet; result[6] = - det3(a1, a3, a4, b1, b3, b4, d1, d3, d4) * rDet; result[7] = det3(a1, a3, a4, b1, b3, b4, c1, c3, c4) * rDet; result[8] = det3(b1, b2, b4, c1, c2, c4, d1, d2, d4) * rDet; result[9] = - det3(a1, a2, a4, c1, c2, c4, d1, d2, d4) * rDet; result[10] = det3(a1, a2, a4, b1, b2, b4, d1, d2, d4) * rDet; result[11] = - det3(a1, a2, a4, b1, b2, b4, c1, c2, c4) * rDet; result[12] = - det3(b1, b2, b3, c1, c2, c3, d1, d2, d3) * rDet; result[13] = det3(a1, a2, a3, c1, c2, c3, d1, d2, d3) * rDet; result[14] = - det3(a1, a2, a3, b1, b2, b3, d1, d2, d3) * rDet; result[15] = det3(a1, a2, a3, b1, b2, b3, c1, c2, c3) * rDet; *this = result; } //////////////////////////////////////////////////////////////////////////////// /// returns a inverted version of this matrix Matrix Matrix::inverted () const { mathType rDet; Matrix result; mathType a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4; a1 = _data[0]; // data_[0].values[0]; b1 = _data[4]; // data_[1].values[0]; c1 = _data[8]; // data_[2].values[0]; d1 = _data[12]; // data_[3].values[0]; a2 = _data[1]; // data_[0].values[1]; b2 = _data[5]; // data_[1].values[1]; c2 = _data[9]; // data_[2].values[1]; d2 = _data[13]; // data_[3].values[1]; a3 = _data[2]; // data_[0].values[2]; b3 = _data[6]; // data_[1].values[2]; c3 = _data[10]; // data_[2].values[2]; d3 = _data[14]; // data_[3].values[2]; a4 = _data[3]; // data_[0].values[3]; b4 = _data[7]; // data_[1].values[3]; c4 = _data[11]; // data_[2].values[3]; d4 = _data[15]; // data_[3].values[3]; rDet = det(); if(fabs(rDet) < 0.00001) { //std::cout << std::endl << "fabs(rDet) < EPS: " << fabs(rDet) << std::endl; // setIdentity(); Matrix i; i.setIdentity(); return i; } rDet = 1.f / rDet; result[0] = det3(b2, b3, b4, c2, c3, c4, d2, d3, d4) * rDet; result[1] = - det3(a2, a3, a4, c2, c3, c4, d2, d3, d4) * rDet; result[2] = det3(a2, a3, a4, b2, b3, b4, d2, d3, d4) * rDet; result[3] = - det3(a2, a3, a4, b2, b3, b4, c2, c3, c4) * rDet; result[4] = - det3(b1, b3, b4, c1, c3, c4, d1, d3, d4) * rDet; result[5] = det3(a1, a3, a4, c1, c3, c4, d1, d3, d4) * rDet; result[6] = - det3(a1, a3, a4, b1, b3, b4, d1, d3, d4) * rDet; result[7] = det3(a1, a3, a4, b1, b3, b4, c1, c3, c4) * rDet; result[8] = det3(b1, b2, b4, c1, c2, c4, d1, d2, d4) * rDet; result[9] = - det3(a1, a2, a4, c1, c2, c4, d1, d2, d4) * rDet; result[10] = det3(a1, a2, a4, b1, b2, b4, d1, d2, d4) * rDet; result[11] = - det3(a1, a2, a4, b1, b2, b4, c1, c2, c4) * rDet; result[12] = - det3(b1, b2, b3, c1, c2, c3, d1, d2, d3) * rDet; result[13] = det3(a1, a2, a3, c1, c2, c3, d1, d2, d3) * rDet; result[14] = - det3(a1, a2, a3, b1, b2, b3, d1, d2, d3) * rDet; result[15] = det3(a1, a2, a3, b1, b2, b3, c1, c2, c3) * rDet; return result;; } //////////////////////////////////////////////////////////////////////////////// /// transpose matrix void Matrix::transpose() { Matrix temp; temp[0] = _data[0]; temp[1] = _data[4]; temp[2] = _data[8]; temp[3] = _data[12]; temp[4] = _data[1]; temp[5] = _data[5]; temp[6] = _data[9]; temp[7] = _data[13]; temp[8] = _data[2]; temp[9] = _data[6]; temp[10] = _data[10]; temp[11] = _data[14]; temp[12] = _data[3]; temp[13] = _data[7]; temp[14] = _data[11]; temp[15] = _data[15]; (*this) = Matrix(temp._data); } //////////////////////////////////////////////////////////////////////////////// /// returns transposed matrix Matrix Matrix::transposed() const { Matrix temp; temp[0] = _data[0]; temp[1] = _data[4]; temp[2] = _data[8]; temp[3] = _data[12]; temp[4] = _data[1]; temp[5] = _data[5]; temp[6] = _data[9]; temp[7] = _data[13]; temp[8] = _data[2]; temp[9] = _data[6]; temp[10] = _data[10]; temp[11] = _data[14]; temp[12] = _data[3]; temp[13] = _data[7]; temp[14] = _data[11]; temp[15] = _data[15]; return temp; } //////////////////////////////////////////////////////////////////////////////// /// returns determinate of the rot/scale part of the matrix mathType Matrix::det3() const { // return (data_[0].values[0] * data_[1].values[1] * data_[2].values[2] + // data_[0].values[1] * data_[1].values[2] * data_[2].values[0] + // data_[0].values[2] * data_[1].values[0] * data_[2].values[1] - // data_[0].values[2] * data_[1].values[1] * data_[2].values[0] - // data_[0].values[1] * data_[1].values[0] * data_[2].values[2] - // data_[0].values[0] * data_[1].values[2] * data_[2].values[1]); std::cerr << "ATTENTION in Matrix::det3()" << std::endl; return 1234567; } //////////////////////////////////////////////////////////////////////////////// /// returns determinate of the matrix mathType Matrix::det() const { mathType a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4; a1 = _data[0]; // data_[0].values[0]; b1 = _data[4]; // data_[1].values[0]; c1 = _data[8]; // data_[2].values[0]; d1 = _data[12]; // data_[3].values[0]; a2 = _data[1]; // data_[0].values[1]; b2 = _data[5]; // data_[1].values[1]; c2 = _data[9]; // data_[2].values[1]; d2 = _data[13]; // data_[3].values[1]; a3 = _data[2]; // data_[0].values[2]; b3 = _data[6]; // data_[1].values[2]; c3 = _data[10]; // data_[2].values[2]; d3 = _data[14]; // data_[3].values[2]; a4 = _data[3]; // data_[0].values[3]; b4 = _data[7]; // data_[1].values[3]; c4 = _data[11]; // data_[2].values[3]; d4 = _data[15]; // data_[3].values[3]; return( a1 * det3(b2, b3, b4, c2, c3, c4, d2, d3, d4) - b1 * det3(a2, a3, a4, c2, c3, c4, d2, d3, d4) + c1 * det3(a2, a3, a4, b2, b3, b4, d2, d3, d4) - d1 * det3(a2, a3, a4, b2, b3, b4, c2, c3, c4)); } //////////////////////////////////////////////////////////////////////////////// /// returns determinante of an particular matrix mathType Matrix::det3(const mathType a1, const mathType a2, const mathType a3, const mathType b1, const mathType b2, const mathType b3, const mathType c1, const mathType c2, const mathType c3) const { return (a1 * b2 * c3) + (a2 * b3 * c1) + (a3 * b1 * c2) - (a1 * b3 * c2) - (a2 * b1 * c3) - (a3 * b2 * c1); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::mult (const Matrix& lhs) { Matrix temp; Matrix rhs = (*this); // M * this temp[0] = lhs[0]*rhs[0] + lhs[4]*rhs[1] + lhs[8]*rhs[2] + lhs[12]*rhs[3]; temp[1] = lhs[1]*rhs[0] + lhs[5]*rhs[1] + lhs[9]*rhs[2] + lhs[13]*rhs[3]; temp[2] = lhs[2]*rhs[0] + lhs[6]*rhs[1] + lhs[10]*rhs[2] + lhs[14]*rhs[3]; temp[3] = lhs[3]*rhs[0] + lhs[7]*rhs[1] + lhs[11]*rhs[2] + lhs[15]*rhs[3]; temp[4] = lhs[0]*rhs[4] + lhs[4]*rhs[5] + lhs[8]*rhs[6] + lhs[12]*rhs[7]; temp[5] = lhs[1]*rhs[4] + lhs[5]*rhs[5] + lhs[9]*rhs[6] + lhs[13]*rhs[7]; temp[6] = lhs[2]*rhs[4] + lhs[6]*rhs[5] + lhs[10]*rhs[6] + lhs[14]*rhs[7]; temp[7] = lhs[3]*rhs[4] + lhs[7]*rhs[5] + lhs[11]*rhs[6] + lhs[15]*rhs[7]; temp[8] = lhs[0]*rhs[8] + lhs[4]*rhs[9] + lhs[8]*rhs[10] + lhs[12]*rhs[11]; temp[9] = lhs[1]*rhs[8] + lhs[5]*rhs[9] + lhs[9]*rhs[10] + lhs[13]*rhs[11]; temp[10] = lhs[2]*rhs[8] + lhs[6]*rhs[9] + lhs[10]*rhs[10] + lhs[14]*rhs[11]; temp[11] = lhs[3]*rhs[8] + lhs[7]*rhs[9] + lhs[11]*rhs[10] + lhs[15]*rhs[11]; temp[12] = lhs[0]*rhs[12] + lhs[4]*rhs[13] + lhs[8]*rhs[14] + lhs[12]*rhs[15]; temp[13] = lhs[1]*rhs[12] + lhs[5]*rhs[13] + lhs[9]*rhs[14] + lhs[13]*rhs[15]; temp[14] = lhs[2]*rhs[12] + lhs[6]*rhs[13] + lhs[10]*rhs[14] + lhs[14]*rhs[15]; temp[15] = lhs[3]*rhs[12] + lhs[7]*rhs[13] + lhs[11]*rhs[14] + lhs[15]*rhs[15]; *this = temp; } //////////////////////////////////////////////////////////////////////////////// /// bool Matrix::equals(const Matrix& rhs, mathType epsylon) const { for (int i=0; i!=16; ++i) { if( std::abs(_data[i]-rhs[i]) > epsylon ) return false; } return true; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setTranslate(const mathType x, const mathType y, const mathType z) { _data[12] = x; _data[13] = y; _data[14] = z; _data[15] = 1.0; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setTranslate(Vector3 const& v) { _data[12] = v[0]; _data[13] = v[1]; _data[14] = v[2]; _data[15] = 1.0; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setTranslate(Point3 const& p) { _data[12] = p[0]; _data[13] = p[1]; _data[14] = p[2]; _data[15] = 1.0; } //////////////////////////////////////////////////////////////////////////////// /// Vector3 Matrix::getTranslate() const { return Vector3(_data[12], _data[13], _data[14]); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setScale(const mathType x, const mathType y, const mathType z) { _data[0] = x; _data[5] = y; _data[10] = z; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setScale(Vector3 const& v) { _data[0] = v[0]; _data[5] = v[1]; _data[10] = v[2]; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setScale(Point3 const& p) { _data[0] = p[0]; _data[5] = p[1]; _data[10] = p[2]; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setScale(mathType s) { _data[0] = s; _data[5] = s; _data[10] = s; } //////////////////////////////////////////////////////////////////////////////// /// Vector3 Matrix::getScale() const { return Vector3(_data[0], _data[5], _data[10]); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotate(const mathType x, const mathType y, const mathType z) { Matrix rotX; rotX.setRotateX(x); Matrix rotY; rotY.setRotateY(y); Matrix rotZ; rotZ.setRotateZ(z); (*this) = rotY*rotX*rotZ; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotate(Vector3 const& v) { setRotate(v[0], v[1], v[2] ); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotate(Point3 const& p) { setRotate(p[0], p[1], p[2]); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotate(Vector3 const& v, mathType angle) { setRotate(v[0]*angle, v[1]*angle, v[2]*angle); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotate(Point3 const& p, mathType angle) { setRotate(p[0]*angle, p[1]*angle, p[2]*angle); } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotateX(mathType angle) { setIdentity(); mathType cosine = cos(angle); mathType sine = sin(angle); _data[5] = cosine; _data[6] = sine; _data[9] = -sine; _data[10] = cosine; } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotateY(mathType angle) { setIdentity(); mathType cosine = cos(angle); mathType sine = sin(angle); _data[0] = cosine; _data[2] = -sine; // <-- Bug found on 2011.02.28 changed sign of _data[2] and _data[8] _data[8] = sine; // because rotation around Y was in wrong direction _data[10] = cosine; // http://en.wikipedia.org/wiki/Rotation_matrix#Rotations_in_three_dimensions } //////////////////////////////////////////////////////////////////////////////// /// void Matrix::setRotateZ(mathType angle) { setIdentity(); mathType cosine = cos(angle); mathType sine = sin(angle); _data[0] = cosine; _data[1] = sine; _data[4] = -sine; _data[5] = cosine; } //////////////////////////////////////////////////////////////////////////////// /// Matrix& Matrix::operator=(Matrix const& m) { memcpy(_data, m._data, sizeof(mathType)*16); return (*this); } //////////////////////////////////////////////////////////////////////////////// /// mathType& Matrix::operator[](unsigned int i) { return _data[i]; } //////////////////////////////////////////////////////////////////////////////// /// Read const mathType& Matrix::operator[](unsigned int i) const { return _data[i]; } //////////////////////////////////////////////////////////////////////////////// /// Matrix + Matrix Matrix operator+(const Matrix& lhs, const Matrix& rhs) { Matrix tmp; tmp[0] = lhs[0] + rhs[0]; tmp[1] = lhs[1] + rhs[1]; tmp[2] = lhs[2] + rhs[2]; tmp[3] = lhs[3] + rhs[3]; tmp[4] = lhs[4] + rhs[4]; tmp[5] = lhs[5] + rhs[5]; tmp[6] = lhs[6] + rhs[6]; tmp[7] = lhs[7] + rhs[7]; tmp[8] = lhs[8] + rhs[8]; tmp[9] = lhs[9] + rhs[9]; tmp[10] = lhs[10] + rhs[10]; tmp[11] = lhs[11] + rhs[11]; tmp[12] = lhs[12] + rhs[12]; tmp[13] = lhs[13] + rhs[13]; tmp[14] = lhs[14] + rhs[14]; tmp[15] = lhs[15] + rhs[15]; return tmp; } //////////////////////////////////////////////////////////////////////////////// /// Matrix - Matrix Matrix operator-(const Matrix& lhs, const Matrix& rhs) { Matrix tmp; tmp[0] = lhs[0] - rhs[0]; tmp[1] = lhs[1] - rhs[1]; tmp[2] = lhs[2] - rhs[2]; tmp[3] = lhs[3] - rhs[3]; tmp[4] = lhs[4] - rhs[4]; tmp[5] = lhs[5] - rhs[5]; tmp[6] = lhs[6] - rhs[6]; tmp[7] = lhs[7] - rhs[7]; tmp[8] = lhs[8] - rhs[8]; tmp[9] = lhs[9] - rhs[9]; tmp[10] = lhs[10] - rhs[10]; tmp[11] = lhs[11] - rhs[11]; tmp[12] = lhs[12] - rhs[12]; tmp[13] = lhs[13] - rhs[13]; tmp[14] = lhs[14] - rhs[14]; tmp[15] = lhs[15] - rhs[15]; return tmp; } //////////////////////////////////////////////////////////////////////////////// /// Scalar * Matrix Matrix operator*(mathType scalar, Matrix const& m) { Matrix tmp; tmp[0] = m[0] * scalar; tmp[1] = m[1] * scalar; tmp[2] = m[2] * scalar; tmp[3] = m[3] * scalar; tmp[4] = m[4] * scalar; tmp[5] = m[5] * scalar; tmp[6] = m[6] * scalar; tmp[7] = m[7] * scalar; tmp[8] = m[8] * scalar; tmp[9] = m[9] * scalar; tmp[10] = m[10] * scalar; tmp[11] = m[11] * scalar; tmp[12] = m[12] * scalar; tmp[13] = m[13] * scalar; tmp[14] = m[14] * scalar; tmp[15] = m[15] * scalar; return tmp; } //////////////////////////////////////////////////////////////////////////////// /// Matrix * Scalar Matrix operator*(Matrix const& m, mathType scalar ) { Matrix tmp; tmp[0] = m[0] * scalar; tmp[1] = m[1] * scalar; tmp[2] = m[2] * scalar; tmp[3] = m[3] * scalar; tmp[4] = m[4] * scalar; tmp[5] = m[5] * scalar; tmp[6] = m[6] * scalar; tmp[7] = m[7] * scalar; tmp[8] = m[8] * scalar; tmp[9] = m[9] * scalar; tmp[10] = m[10] * scalar; tmp[11] = m[11] * scalar; tmp[12] = m[12] * scalar; tmp[13] = m[13] * scalar; tmp[14] = m[14] * scalar; tmp[15] = m[15] * scalar; return tmp; } //////////////////////////////////////////////////////////////////////////////// /// Matrix * Vector Vector3 operator*(Matrix const& m, Vector3 const& v ) { return Vector3(m[0]*v[0] + m[4]*v[1] + m[8] *v[2], m[1]*v[0] + m[5]*v[1] + m[9] *v[2], m[2]*v[0] + m[6]*v[1] + m[10]*v[2]); } //////////////////////////////////////////////////////////////////////////////// /// matrix * point Point3 operator*(Matrix const& m, Point3 const& p ) { return Point3(m[0]*p[0] + m[4]*p[1] + m[8] *p[2] + m[12], m[1]*p[0] + m[5]*p[1] + m[9] *p[2] + m[13], m[2]*p[0] + m[6]*p[1] + m[10]*p[2] + m[14]); } //////////////////////////////////////////////////////////////////////////////// /// matrix * ray Ray operator*(Matrix const& m, Ray const& r ) { return Ray(m*r.getOrigin(), m*r.getDirection(), r.getT()); } //////////////////////////////////////////////////////////////////////////////// /// Matrix multiplication Matrix operator*(const Matrix& lhs, const Matrix& rhs) { Matrix temp; // M * this temp[0] = lhs[0]*rhs[0] + lhs[4]*rhs[1] + lhs[8]*rhs[2] + lhs[12]*rhs[3]; temp[1] = lhs[1]*rhs[0] + lhs[5]*rhs[1] + lhs[9]*rhs[2] + lhs[13]*rhs[3]; temp[2] = lhs[2]*rhs[0] + lhs[6]*rhs[1] + lhs[10]*rhs[2] + lhs[14]*rhs[3]; temp[3] = lhs[3]*rhs[0] + lhs[7]*rhs[1] + lhs[11]*rhs[2] + lhs[15]*rhs[3]; temp[4] = lhs[0]*rhs[4] + lhs[4]*rhs[5] + lhs[8]*rhs[6] + lhs[12]*rhs[7]; temp[5] = lhs[1]*rhs[4] + lhs[5]*rhs[5] + lhs[9]*rhs[6] + lhs[13]*rhs[7]; temp[6] = lhs[2]*rhs[4] + lhs[6]*rhs[5] + lhs[10]*rhs[6] + lhs[14]*rhs[7]; temp[7] = lhs[3]*rhs[4] + lhs[7]*rhs[5] + lhs[11]*rhs[6] + lhs[15]*rhs[7]; temp[8] = lhs[0]*rhs[8] + lhs[4]*rhs[9] + lhs[8]*rhs[10] + lhs[12]*rhs[11]; temp[9] = lhs[1]*rhs[8] + lhs[5]*rhs[9] + lhs[9]*rhs[10] + lhs[13]*rhs[11]; temp[10] = lhs[2]*rhs[8] + lhs[6]*rhs[9] + lhs[10]*rhs[10] + lhs[14]*rhs[11]; temp[11] = lhs[3]*rhs[8] + lhs[7]*rhs[9] + lhs[11]*rhs[10] + lhs[15]*rhs[11]; temp[12] = lhs[0]*rhs[12] + lhs[4]*rhs[13] + lhs[8]*rhs[14] + lhs[12]*rhs[15]; temp[13] = lhs[1]*rhs[12] + lhs[5]*rhs[13] + lhs[9]*rhs[14] + lhs[13]*rhs[15]; temp[14] = lhs[2]*rhs[12] + lhs[6]*rhs[13] + lhs[10]*rhs[14] + lhs[14]*rhs[15]; temp[15] = lhs[3]*rhs[12] + lhs[7]*rhs[13] + lhs[11]*rhs[14] + lhs[15]*rhs[15]; return temp; } //////////////////////////////////////////////////////////////////////////////// /// bool operator==(const Matrix& lhs, const Matrix& rhs) { return lhs.equals(rhs); } //////////////////////////////////////////////////////////////////////////////// /// bool operator!=(const Matrix& lhs, const Matrix& rhs) { return !(lhs == rhs); } //////////////////////////////////////////////////////////////////////////////// /// ostream std::ostream& operator<< (std::ostream& os, const Matrix& m) { os << "matrix[" << std::fixed << std::endl; os << " (" << m[0] << ", " << m[4] << ", " << m[8] << ", " << m[12] << ")," << std::endl; os << " (" << m[1] << ", " << m[5] << ", " << m[9] << ", " << m[13] << ")," << std::endl; os << " (" << m[2] << ", " << m[6] << ", " << m[10] << ", " << m[14] << ")," << std::endl; os << " (" << m[3] << ", " << m[7] << ", " << m[11] << ", " << m[15] << ") ]" << std::endl; return os; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// } // namespace gloost
gpl-3.0
chriskmanx/qmole
QMOLEDEV/libetpan-0.57/src/driver/tools/generic_cache.c
1
15478
/* * libEtPan! -- a mail stuff library * * Copyright (C) 2001, 2005 - DINH Viet Hoa * 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 libEtPan! project 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 AUTHORS 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 AUTHORS 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. */ /* * $Id: generic_cache.c,v 1.34 2008/02/20 22:15:51 hoa Exp $ */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "generic_cache.h" #include "libetpan-config.h" #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_SYS_MMAN_H # include <sys/mman.h> #endif #ifdef WIN32 # include "win_etpan.h" #endif #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include "maildriver_types.h" #include "imfcache.h" #include "chash.h" #include "mailmessage.h" #include "mail_cache_db.h" int generic_cache_create_dir(char * dirname) { struct stat buf; int r; r = stat(dirname, &buf); if (r != 0) { #ifdef WIN32 r = mkdir(dirname); #else r = mkdir(dirname, 0700); #endif if (r < 0) return MAIL_ERROR_FILE; } else { if (!S_ISDIR(buf.st_mode)) return MAIL_ERROR_FILE; } return MAIL_NO_ERROR; } int generic_cache_store(char * filename, char * content, size_t length) { int fd; char * str; fd = open(filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) return MAIL_ERROR_FILE; if (ftruncate(fd, length) < 0) return MAIL_ERROR_FILE; str = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (str == (char *)MAP_FAILED) return MAIL_ERROR_FILE; memcpy(str, content, length); msync(str, length, MS_SYNC); munmap(str, length); close(fd); return MAIL_NO_ERROR; } int generic_cache_read(char * filename, char ** result, size_t * result_len) { int fd; char * str; struct stat buf; MMAPString * mmapstr; char * content; int res; if (stat(filename, &buf) < 0) { res = MAIL_ERROR_CACHE_MISS; goto err; } fd = open(filename, O_RDONLY); if (fd == -1) { res = MAIL_ERROR_CACHE_MISS; goto err; } str = mmap(NULL, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (str == (char *)MAP_FAILED) { res = MAIL_ERROR_FILE; goto close; } mmapstr = mmap_string_new_len(str, buf.st_size); if (mmapstr == NULL) { res = MAIL_ERROR_MEMORY; goto unmap; } if (mmap_string_ref(mmapstr) < 0) { res = MAIL_ERROR_MEMORY; goto free; } content = mmapstr->str; munmap(str, buf.st_size); close(fd); * result = content; * result_len = buf.st_size; return MAIL_NO_ERROR; free: mmap_string_free(mmapstr); unmap: munmap(str, buf.st_size); close: close(fd); err: return res; } static int flags_extension_read(MMAPString * mmapstr, size_t * indx, clist ** result) { clist * list; int r; uint32_t count; uint32_t i; int res; r = mailimf_cache_int_read(mmapstr, indx, &count); if (r != MAIL_NO_ERROR) { res = r; goto err; } list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } for(i = 0 ; i < count ; i++) { char * str; r = mailimf_cache_string_read(mmapstr, indx, &str); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } r = clist_append(list, str); if (r < 0) { free(str); res = MAIL_ERROR_MEMORY; goto free_list; } } * result = list; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) free, NULL); clist_free(list); err: return res; } static int generic_flags_read(MMAPString * mmapstr, size_t * indx, struct mail_flags ** result) { clist * ext; int r; struct mail_flags * flags; uint32_t value; int res; r = mailimf_cache_int_read(mmapstr, indx, &value); if (r != MAIL_NO_ERROR) { res = r; goto err; } ext = NULL; r = flags_extension_read(mmapstr, indx, &ext); if (r != MAIL_NO_ERROR) { res = r; goto err; } flags = mail_flags_new(value, ext); if (flags == NULL) { res = r; goto free; } * result = flags; return MAIL_NO_ERROR; free: clist_foreach(ext, (clist_func) free, NULL); clist_free(ext); err: return res; } static int flags_extension_write(MMAPString * mmapstr, size_t * indx, clist * ext) { int r; clistiter * cur; r = mailimf_cache_int_write(mmapstr, indx, clist_count(ext)); if (r != MAIL_NO_ERROR) return r; for(cur = clist_begin(ext) ; cur != NULL ; cur = clist_next(cur)) { char * ext_flag; ext_flag = clist_content(cur); r = mailimf_cache_string_write(mmapstr, indx, ext_flag, strlen(ext_flag)); if (r != MAIL_NO_ERROR) return r; } return MAIL_NO_ERROR; } static int generic_flags_write(MMAPString * mmapstr, size_t * indx, struct mail_flags * flags) { int r; r = mailimf_cache_int_write(mmapstr, indx, flags->fl_flags & ~MAIL_FLAG_NEW); if (r != MAIL_NO_ERROR) return r; r = flags_extension_write(mmapstr, indx, flags->fl_extension); if (r != MAIL_NO_ERROR) return r; return MAIL_NO_ERROR; } static struct mail_flags * mail_flags_dup(struct mail_flags * flags) { clist * list; struct mail_flags * new_flags; int r; clistiter * cur; list = clist_new(); if (list == NULL) { goto err; } for(cur = clist_begin(flags->fl_extension) ; cur != NULL ; cur = clist_next(cur)) { char * ext; char * original_ext; original_ext = clist_content(cur); ext = strdup(original_ext); if (ext == NULL) { goto free; } r = clist_append(list, ext); if (r < 0) { free(ext); goto free; } } new_flags = mail_flags_new(flags->fl_flags, list); if (new_flags == NULL) { goto free; } return new_flags; free: clist_foreach(list, (clist_func) free, NULL); clist_free(list); err: return NULL; } static mailmessage * mailmessage_build(mailmessage * msg) { mailmessage * new_msg; new_msg = malloc(sizeof(* new_msg)); if (new_msg == NULL) goto err; new_msg->msg_session = msg->msg_session; new_msg->msg_driver = msg->msg_driver; new_msg->msg_index = msg->msg_index; if (msg->msg_uid == NULL) new_msg->msg_uid = NULL; else { new_msg->msg_uid = strdup(msg->msg_uid); if (new_msg->msg_uid == NULL) goto free; } new_msg->msg_cached = msg->msg_cached; new_msg->msg_size = msg->msg_size; new_msg->msg_fields = NULL; new_msg->msg_flags = mail_flags_dup(msg->msg_flags); if (new_msg->msg_flags == NULL) { free(new_msg->msg_uid); goto free; } new_msg->msg_mime = NULL; new_msg->msg_data = NULL; return new_msg; free: free(new_msg); err: return NULL; } struct mail_flags_store * mail_flags_store_new(void) { struct mail_flags_store * flags_store; flags_store = malloc(sizeof(struct mail_flags_store)); if (flags_store == NULL) goto err; flags_store->fls_tab = carray_new(128); if (flags_store->fls_tab == NULL) goto free; flags_store->fls_hash = chash_new(128, CHASH_COPYALL); if (flags_store->fls_hash == NULL) goto free_tab; return flags_store; free_tab: carray_free(flags_store->fls_tab); free: free(flags_store); err: return NULL; } void mail_flags_store_clear(struct mail_flags_store * flags_store) { unsigned int i; for(i = 0 ; i < carray_count(flags_store->fls_tab) ; i ++) { chashdatum key; mailmessage * msg; msg = carray_get(flags_store->fls_tab, i); key.data = &msg->msg_index; key.len = sizeof(msg->msg_index); chash_delete(flags_store->fls_hash, &key, NULL); mailmessage_free(msg); } carray_set_size(flags_store->fls_tab, 0); } void mail_flags_store_free(struct mail_flags_store * flags_store) { mail_flags_store_clear(flags_store); chash_free(flags_store->fls_hash); carray_free(flags_store->fls_tab); free(flags_store); } int mail_flags_store_set(struct mail_flags_store * flags_store, mailmessage * msg) { chashdatum key; chashdatum value; unsigned int indx; int res; int r; mailmessage * new_msg; if (msg->msg_flags == NULL) { res = MAIL_NO_ERROR; goto err; } /* duplicate needed message info */ new_msg = mailmessage_build(msg); if (new_msg == NULL) { res = MAIL_ERROR_MEMORY; goto err; } key.data = &new_msg->msg_index; key.len = sizeof(new_msg->msg_index); r = chash_get(flags_store->fls_hash, &key, &value); if (r == 0) { mailmessage * old_msg; indx = * (unsigned int *) value.data; old_msg = carray_get(flags_store->fls_tab, indx); mailmessage_free(old_msg); } else { r = carray_set_size(flags_store->fls_tab, carray_count(flags_store->fls_tab) + 1); if (r != 0) { res = MAIL_ERROR_MEMORY; goto err; } indx = carray_count(flags_store->fls_tab) - 1; } carray_set(flags_store->fls_tab, indx, new_msg); value.data = &indx; value.len = sizeof(indx); r = chash_set(flags_store->fls_hash, &key, &value, NULL); if (r < 0) { carray_delete(flags_store->fls_tab, indx); res = MAIL_ERROR_MEMORY; goto free; } return MAIL_NO_ERROR; free: mailmessage_free(new_msg); err: return res; } static int msg_index_compare(mailmessage ** msg1, mailmessage ** msg2) { return (* msg1)->msg_index - (* msg2)->msg_index; } void mail_flags_store_sort(struct mail_flags_store * flags_store) { qsort(carray_data(flags_store->fls_tab), carray_count(flags_store->fls_tab), sizeof(mailmessage *), (int (*)(const void *, const void *)) msg_index_compare); } struct mail_flags * mail_flags_store_get(struct mail_flags_store * flags_store, uint32_t indx) { struct mail_flags * flags; chashdatum key; chashdatum value; int r; unsigned int tab_index; mailmessage * msg; key.data = &indx; key.len = sizeof(indx); r = chash_get(flags_store->fls_hash, &key, &value); if (r < 0) return NULL; #if 0 flags = mail_flags_dup((struct mail_flags *) value.data); #endif tab_index = * (unsigned int *) value.data; msg = carray_get(flags_store->fls_tab, tab_index); if (msg->msg_flags == NULL) return NULL; flags = mail_flags_dup(msg->msg_flags); return flags; } int mail_flags_compare(struct mail_flags * flags1, struct mail_flags * flags2) { clistiter * cur1; if (clist_count(flags1->fl_extension) != clist_count(flags2->fl_extension)) return -1; for(cur1 = clist_begin(flags1->fl_extension) ; cur1 != NULL ; cur1 = clist_next(cur1)) { char * flag1; clistiter * cur2; int found; flag1 = clist_content(cur1); found = 0; for(cur2 = clist_begin(flags2->fl_extension) ; cur2 != NULL ; cur2 = clist_next(cur2)) { char * flag2; flag2 = clist_content(cur2); if (strcasecmp(flag1, flag2) == 0) { found = 1; break; } } if (!found) return -1; } return flags1->fl_flags - flags2->fl_flags; } int generic_cache_fields_read(struct mail_cache_db * cache_db, MMAPString * mmapstr, char * keyname, struct mailimf_fields ** result) { int r; int res; size_t cur_token; struct mailimf_fields * fields; void * data; size_t data_len; r = mail_cache_db_get(cache_db, keyname, strlen(keyname), &data, &data_len); if (r != 0) { res = MAIL_ERROR_CACHE_MISS; goto err; } r = mail_serialize_clear(mmapstr, &cur_token); if (r != MAIL_NO_ERROR) { res = r; goto err; } if (mmap_string_append_len(mmapstr, data, data_len) == NULL) { res = MAIL_ERROR_MEMORY; goto err; } r = mailimf_cache_fields_read(mmapstr, &cur_token, &fields); if (r != MAIL_NO_ERROR) { res = r; goto err; } * result = fields; return MAIL_NO_ERROR; err: return res; } int generic_cache_fields_write(struct mail_cache_db * cache_db, MMAPString * mmapstr, char * keyname, struct mailimf_fields * fields) { int r; int res; size_t cur_token; r = mail_serialize_clear(mmapstr, &cur_token); if (r != MAIL_NO_ERROR) { res = r; goto err; } r = mailimf_cache_fields_write(mmapstr, &cur_token, fields); if (r != MAIL_NO_ERROR) { res = r; goto err; } r = mail_cache_db_put(cache_db, keyname, strlen(keyname), mmapstr->str, mmapstr->len); if (r != 0) { res = MAIL_ERROR_FILE; goto err; } return MAIL_NO_ERROR; err: return res; } int generic_cache_flags_read(struct mail_cache_db * cache_db, MMAPString * mmapstr, char * keyname, struct mail_flags ** result) { int r; int res; size_t cur_token; struct mail_flags * flags; void * data; size_t data_len; data = NULL; data_len = 0; r = mail_cache_db_get(cache_db, keyname, strlen(keyname), &data, &data_len); if (r != 0) { res = MAIL_ERROR_CACHE_MISS; goto err; } r = mail_serialize_clear(mmapstr, &cur_token); if (r != MAIL_NO_ERROR) { res = r; goto err; } if (mmap_string_append_len(mmapstr, data, data_len) == NULL) { res = MAIL_ERROR_MEMORY; goto err; } flags = NULL; r = generic_flags_read(mmapstr, &cur_token, &flags); if (r != MAIL_NO_ERROR) { res = r; goto err; } * result = flags; return MAIL_NO_ERROR; err: return res; } int generic_cache_flags_write(struct mail_cache_db * cache_db, MMAPString * mmapstr, char * keyname, struct mail_flags * flags) { int r; int res; size_t cur_token; r = mail_serialize_clear(mmapstr, &cur_token); if (r != MAIL_NO_ERROR) { res = r; goto err; } r = generic_flags_write(mmapstr, &cur_token, flags); if (r != MAIL_NO_ERROR) { res = r; goto err; } r = mail_cache_db_put(cache_db, keyname, strlen(keyname), mmapstr->str, mmapstr->len); if (r != 0) { res = MAIL_ERROR_FILE; goto err; } return MAIL_NO_ERROR; err: return res; } int generic_cache_delete(struct mail_cache_db * cache_db, char * keyname) { int r; int res; r = mail_cache_db_del(cache_db, keyname, strlen(keyname)); if (r != 0) { res = MAIL_ERROR_FILE; goto err; } return MAIL_NO_ERROR; err: return res; }
gpl-3.0
freckles-the-pirate/plotline
src/lib/plotline.cpp
1
3998
#include "plotline.h" const QString Plotline::J_CHARACTERS = "characters", Plotline::J_SCENES = "scenes", Plotline::J_SYNOPSIS = "synopsis", Plotline::J_BRIEF = "brief", Plotline::J_COLOR = "color"; Plotline::Plotline(const QString &brief, const QString &synopsis, const QList<Scene *> &scenes, const QList<Character *> &characters, const QColor &color, Novel *novel, QUuid id, QObject *parent) : QObject(parent), Serializable(id) { this->mBrief = brief; this->mSynopsis = synopsis; this->mColor = color; this->mScenes = scenes; this->mNovel = novel; this->mCharacters = characters; } QString Plotline::brief() const { return mBrief; } void Plotline::setBrief(const QString &brief) { mBrief = brief; } QColor Plotline::getColor() const { return mColor; } void Plotline::setColor(const QColor &color) { this->mColor = color; } QString Plotline::synopsis() const { return mSynopsis; } void Plotline::setSynopsis(const QString &synopsis) { this->mSynopsis = synopsis; } QList<Character *> Plotline::characters() const { return mCharacters; } void Plotline::setCharacters(const QList<Character *> &characters) { this->mCharacters = characters; } void Plotline::addCharacter(Character *character, const int before) { if (before > 0) mCharacters.insert(before, character); else mCharacters.append(character); } void Plotline::removeCharacter(Character *character) { this->mCharacters.removeAll(character); } void Plotline::removeCharacter(const QString &label) { for (Character *c : mCharacters) if (c->label() == label) mCharacters.removeAll(c); } QList<Scene *> Plotline::getScenes() const { return this->mScenes; } void Plotline::setScenes(const QList<Scene *> &scenes) { mScenes = scenes; } Novel *Plotline::novel() { return this->mNovel; } void Plotline::setNovel(Novel *novel) { this->mNovel = novel; } QJsonObject Plotline::serialize() const{ QJsonObject plotline = QJsonObject(); QJsonArray jCharacters = QJsonArray(); for (Character *c : mCharacters) jCharacters.append(c->id().toString()); QJsonArray jScenes = QJsonArray(); for (Scene *s : mScenes) jScenes.append(s->id().toString()); plotline[J_CHARACTERS] = jCharacters; plotline[J_SCENES] = jScenes; plotline[J_BRIEF] = mBrief; plotline[J_SYNOPSIS] = mSynopsis; plotline[J_COLOR] = mColor.name(); plotline[JSON_ID] = id().toString(); return plotline; } Plotline *Plotline::deserialize(Novel *novel, const QJsonObject &object) { QUuid id = Serializable::deserialize(object); QString brief = QString(), synopsis = QString(); QList<Character *> characters; QList<Scene *> scenes; QColor color = QColor(); if (object.contains(J_BRIEF)) brief = object[J_BRIEF].toString(); if (object.contains(J_SYNOPSIS)) synopsis = object[J_SYNOPSIS].toString(); if (object.contains(J_CHARACTERS)) for (QJsonValue val : object[J_CHARACTERS].toArray()) characters.append(novel->character(QUuid(val.toString()))); if (object.contains(J_SCENES)) for (QJsonValue val : object[J_SCENES].toArray()) scenes.append(novel->scene(QUuid(val.toString()))); if (object.contains(J_COLOR)) color = QColor(object[J_COLOR].toString()); Plotline *plotline = new Plotline(brief, synopsis, scenes, characters, color, novel, id); return plotline; } QList<Plotline *> Plotline::deserialize(Novel *novel, const QJsonArray &object) { QList<Plotline *> plotlines = QList<Plotline *>(); for (QJsonValue value : object) if (value.isObject()) plotlines.append(Plotline::deserialize(novel, value.toObject())); return plotlines; }
gpl-3.0
sysizlayan/haptic_ccs
Embedded Code/Peripherals/I2C.c
1
4473
/* Copyright (C) 2015 Kristian Sloth Lauszus. All rights reserved. This software may be distributed and modified under the terms of the GNU General Public License version 2 (GPL2) as published by the Free Software Foundation and appearing in the file GPL2.TXT included in the packaging of this file. Please note that GPL2 Section 2[b] requires that all works based on this software must also be made publicly available under the terms of the GPL2 ("Copyleft"). Contact information ------------------- Kristian Sloth Lauszus Web : http://www.lauszus.com e-mail : lauszus@gmail.com */ #include "main.h" #include "I2C.h" void initI2C(void) { SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C1); // Enable I2C1 peripheral SysCtlDelay(2); // Insert a few cycles after enabling the peripheral to allow the clock to be fully activated SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); // Enable GPIOA peripheral SysCtlDelay(2); // Insert a few cycles after enabling the peripheral to allow the clock to be fully activated // Use alternate function GPIOPinConfigure(GPIO_PA6_I2C1SCL); GPIOPinConfigure(GPIO_PA7_I2C1SDA); GPIOPinTypeI2CSCL(GPIO_PORTA_BASE, GPIO_PIN_6); // Use pin with I2C SCL peripheral GPIOPinTypeI2C(GPIO_PORTA_BASE, GPIO_PIN_7); // Use pin with I2C peripheral I2CMasterInitExpClk(I2C1_BASE, SysCtlClockGet(), true); // Enable and set frequency to 400 kHz SysCtlDelay(2); // Insert a few cycles after enabling the I2C to allow the clock to be fully activated } void i2cWrite(uint8_t addr, uint8_t regAddr, uint8_t data) { i2cWriteData(addr, regAddr, &data, 1); } void i2cWriteData(uint8_t addr, uint8_t regAddr, uint8_t *data, uint8_t length) { uint8_t i; I2CMasterSlaveAddrSet(I2C1_BASE, addr, false); // Set to write mode I2CMasterDataPut(I2C1_BASE, regAddr); // Place address into data register I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_BURST_SEND_START); // Send start condition while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done for (i = 0; i < length - 1; i++) { I2CMasterDataPut(I2C1_BASE, data[i]); // Place data into data register I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_BURST_SEND_CONT); // Send continues condition while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done } I2CMasterDataPut(I2C1_BASE, data[length - 1]); // Place data into data register I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_BURST_SEND_FINISH); // Send finish condition while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done } uint8_t i2cRead(uint8_t addr, uint8_t regAddr) { I2CMasterSlaveAddrSet(I2C1_BASE, addr, false); // Set to write mode I2CMasterDataPut(I2C1_BASE, regAddr); // Place address into data register I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_SINGLE_SEND); // Send data while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done I2CMasterSlaveAddrSet(I2C1_BASE, addr, true); // Set to read mode I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_SINGLE_RECEIVE); // Tell master to read data while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done return I2CMasterDataGet(I2C1_BASE); // Read data } void i2cReadData(uint8_t addr, uint8_t regAddr, uint8_t *data, uint8_t length) { uint8_t i; I2CMasterSlaveAddrSet(I2C1_BASE, addr, false); // Set to write mode I2CMasterDataPut(I2C1_BASE, regAddr); // Place address into data register I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_SINGLE_SEND); // Send data while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done I2CMasterSlaveAddrSet(I2C1_BASE, addr, true); // Set to read mode I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_BURST_RECEIVE_START); // Send start condition while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done data[0] = I2CMasterDataGet(I2C1_BASE); // Place data into data register for (i = 1; i < length - 1; i++) { I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_BURST_RECEIVE_CONT); // Send continues condition while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done data[i] = I2CMasterDataGet(I2C1_BASE); // Place data into data register } I2CMasterControl(I2C1_BASE, I2C_MASTER_CMD_BURST_RECEIVE_FINISH); // Send finish condition while (I2CMasterBusy(I2C1_BASE)); // Wait until transfer is done data[length - 1] = I2CMasterDataGet(I2C1_BASE); // Place data into data register }
gpl-3.0
DMCsys/smartalkaudio
oss-survey/ffmpeg/libavformat/mmsh.c
1
12278
/* * MMS protocol over HTTP * Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com> * * 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 */ /* * Reference * Windows Media HTTP Streaming Protocol. * http://msdn.microsoft.com/en-us/library/cc251059(PROT.10).aspx */ #include <string.h> #include "libavutil/intreadwrite.h" #include "libavutil/avstring.h" #include "libavformat/internal.h" #include "mms.h" #include "asf.h" #include "http.h" #include "url.h" #define CHUNK_HEADER_LENGTH 4 // 2bytes chunk type and 2bytes chunk length. #define EXT_HEADER_LENGTH 8 // 4bytes sequence, 2bytes useless and 2bytes chunk length. // see Ref 2.2.1.8 #define USERAGENT "User-Agent: NSPlayer/4.1.0.3856\r\n" // see Ref 2.2.1.4.33 // the guid value can be changed to any valid value. #define CLIENTGUID "Pragma: xClientGUID={c77e7400-738a-11d2-9add-0020af0a3278}\r\n" // see Ref 2.2.3 for packet type define: // chunk type contains 2 fields: Frame and PacketID. // Frame is 0x24 or 0xA4(rarely), different PacketID indicates different packet type. typedef enum { CHUNK_TYPE_DATA = 0x4424, CHUNK_TYPE_ASF_HEADER = 0x4824, CHUNK_TYPE_END = 0x4524, CHUNK_TYPE_STREAM_CHANGE = 0x4324, } ChunkType; typedef struct { MMSContext mms; int request_seq; ///< request packet sequence int chunk_seq; ///< data packet sequence } MMSHContext; static int mmsh_close(URLContext *h) { MMSHContext *mmsh = (MMSHContext *)h->priv_data; MMSContext *mms = &mmsh->mms; if (mms->mms_hd) ffurl_close(mms->mms_hd); av_free(mms->streams); av_free(mms->asf_header); av_freep(&h->priv_data); return 0; } static ChunkType get_chunk_header(MMSHContext *mmsh, int *len) { MMSContext *mms = &mmsh->mms; uint8_t chunk_header[CHUNK_HEADER_LENGTH]; uint8_t ext_header[EXT_HEADER_LENGTH]; ChunkType chunk_type; int chunk_len, res, ext_header_len; res = ffurl_read_complete(mms->mms_hd, chunk_header, CHUNK_HEADER_LENGTH); if (res != CHUNK_HEADER_LENGTH) { av_log(NULL, AV_LOG_ERROR, "Read data packet header failed!\n"); return AVERROR(EIO); } chunk_type = AV_RL16(chunk_header); chunk_len = AV_RL16(chunk_header + 2); switch (chunk_type) { case CHUNK_TYPE_END: case CHUNK_TYPE_STREAM_CHANGE: ext_header_len = 4; break; case CHUNK_TYPE_ASF_HEADER: case CHUNK_TYPE_DATA: ext_header_len = 8; break; default: av_log(NULL, AV_LOG_ERROR, "Strange chunk type %d\n", chunk_type); return AVERROR_INVALIDDATA; } res = ffurl_read_complete(mms->mms_hd, ext_header, ext_header_len); if (res != ext_header_len) { av_log(NULL, AV_LOG_ERROR, "Read ext header failed!\n"); return AVERROR(EIO); } *len = chunk_len - ext_header_len; if (chunk_type == CHUNK_TYPE_END || chunk_type == CHUNK_TYPE_DATA) mmsh->chunk_seq = AV_RL32(ext_header); return chunk_type; } static int read_data_packet(MMSHContext *mmsh, const int len) { MMSContext *mms = &mmsh->mms; int res; if (len > sizeof(mms->in_buffer)) { av_log(NULL, AV_LOG_ERROR, "Data packet length %d exceeds the in_buffer size %zu\n", len, sizeof(mms->in_buffer)); return AVERROR(EIO); } res = ffurl_read_complete(mms->mms_hd, mms->in_buffer, len); av_dlog(NULL, "Data packet len = %d\n", len); if (res != len) { av_log(NULL, AV_LOG_ERROR, "Read data packet failed!\n"); return AVERROR(EIO); } if (len > mms->asf_packet_len) { av_log(NULL, AV_LOG_ERROR, "Chunk length %d exceed packet length %d\n",len, mms->asf_packet_len); return AVERROR_INVALIDDATA; } else { memset(mms->in_buffer + len, 0, mms->asf_packet_len - len); // padding } mms->read_in_ptr = mms->in_buffer; mms->remaining_in_len = mms->asf_packet_len; return 0; } static int get_http_header_data(MMSHContext *mmsh) { MMSContext *mms = &mmsh->mms; int res, len; ChunkType chunk_type; for (;;) { len = 0; res = chunk_type = get_chunk_header(mmsh, &len); if (res < 0) { return res; } else if (chunk_type == CHUNK_TYPE_ASF_HEADER){ // get asf header and stored it if (!mms->header_parsed) { if (mms->asf_header) { if (len != mms->asf_header_size) { mms->asf_header_size = len; av_dlog(NULL, "Header len changed from %d to %d\n", mms->asf_header_size, len); av_freep(&mms->asf_header); } } mms->asf_header = av_mallocz(len); if (!mms->asf_header) { return AVERROR(ENOMEM); } mms->asf_header_size = len; } if (len > mms->asf_header_size) { av_log(NULL, AV_LOG_ERROR, "Asf header packet len = %d exceed the asf header buf size %d\n", len, mms->asf_header_size); return AVERROR(EIO); } res = ffurl_read_complete(mms->mms_hd, mms->asf_header, len); if (res != len) { av_log(NULL, AV_LOG_ERROR, "Recv asf header data len %d != expected len %d\n", res, len); return AVERROR(EIO); } mms->asf_header_size = len; if (!mms->header_parsed) { res = ff_mms_asf_header_parser(mms); mms->header_parsed = 1; return res; } } else if (chunk_type == CHUNK_TYPE_DATA) { // read data packet and do padding return read_data_packet(mmsh, len); } else { if (len) { if (len > sizeof(mms->in_buffer)) { av_log(NULL, AV_LOG_ERROR, "Other packet len = %d exceed the in_buffer size %zu\n", len, sizeof(mms->in_buffer)); return AVERROR(EIO); } res = ffurl_read_complete(mms->mms_hd, mms->in_buffer, len); if (res != len) { av_log(NULL, AV_LOG_ERROR, "Read other chunk type data failed!\n"); return AVERROR(EIO); } else { av_dlog(NULL, "Skip chunk type %d \n", chunk_type); continue; } } } } return 0; } static int mmsh_open(URLContext *h, const char *uri, int flags) { int i, port, err; char httpname[256], path[256], host[128], location[1024]; char *stream_selection = NULL; char headers[1024]; MMSHContext *mmsh; MMSContext *mms; mmsh = h->priv_data = av_mallocz(sizeof(MMSHContext)); if (!h->priv_data) return AVERROR(ENOMEM); mmsh->request_seq = h->is_streamed = 1; mms = &mmsh->mms; av_strlcpy(location, uri, sizeof(location)); av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, path, sizeof(path), location); if (port<0) port = 80; // default mmsh protocol port ff_url_join(httpname, sizeof(httpname), "http", NULL, host, port, path); if (ffurl_alloc(&mms->mms_hd, httpname, AVIO_FLAG_READ) < 0) { return AVERROR(EIO); } snprintf(headers, sizeof(headers), "Accept: */*\r\n" USERAGENT "Host: %s:%d\r\n" "Pragma: no-cache,rate=1.000000,stream-time=0," "stream-offset=0:0,request-context=%u,max-duration=0\r\n" CLIENTGUID "Connection: Close\r\n\r\n", host, port, mmsh->request_seq++); ff_http_set_headers(mms->mms_hd, headers); err = ffurl_connect(mms->mms_hd); if (err) { goto fail; } err = get_http_header_data(mmsh); if (err) { av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n"); goto fail; } // close the socket and then reopen it for sending the second play request. ffurl_close(mms->mms_hd); memset(headers, 0, sizeof(headers)); if (ffurl_alloc(&mms->mms_hd, httpname, AVIO_FLAG_READ) < 0) { return AVERROR(EIO); } stream_selection = av_mallocz(mms->stream_num * 19 + 1); if (!stream_selection) return AVERROR(ENOMEM); for (i = 0; i < mms->stream_num; i++) { char tmp[20]; err = snprintf(tmp, sizeof(tmp), "ffff:%d:0 ", mms->streams[i].id); if (err < 0) goto fail; av_strlcat(stream_selection, tmp, mms->stream_num * 19 + 1); } // send play request err = snprintf(headers, sizeof(headers), "Accept: */*\r\n" USERAGENT "Host: %s:%d\r\n" "Pragma: no-cache,rate=1.000000,request-context=%u\r\n" "Pragma: xPlayStrm=1\r\n" CLIENTGUID "Pragma: stream-switch-count=%d\r\n" "Pragma: stream-switch-entry=%s\r\n" "Connection: Close\r\n\r\n", host, port, mmsh->request_seq++, mms->stream_num, stream_selection); av_freep(&stream_selection); if (err < 0) { av_log(NULL, AV_LOG_ERROR, "Build play request failed!\n"); goto fail; } av_dlog(NULL, "out_buffer is %s", headers); ff_http_set_headers(mms->mms_hd, headers); err = ffurl_connect(mms->mms_hd); if (err) { goto fail; } err = get_http_header_data(mmsh); if (err) { av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n"); goto fail; } av_dlog(NULL, "Connection successfully open\n"); return 0; fail: av_freep(&stream_selection); mmsh_close(h); av_dlog(NULL, "Connection failed with error %d\n", err); return err; } static int handle_chunk_type(MMSHContext *mmsh) { MMSContext *mms = &mmsh->mms; int res, len = 0; ChunkType chunk_type; chunk_type = get_chunk_header(mmsh, &len); switch (chunk_type) { case CHUNK_TYPE_END: mmsh->chunk_seq = 0; av_log(NULL, AV_LOG_ERROR, "Stream ended!\n"); return AVERROR(EIO); case CHUNK_TYPE_STREAM_CHANGE: mms->header_parsed = 0; if (res = get_http_header_data(mmsh)) { av_log(NULL, AV_LOG_ERROR,"Stream changed! Failed to get new header!\n"); return res; } break; case CHUNK_TYPE_DATA: return read_data_packet(mmsh, len); default: av_log(NULL, AV_LOG_ERROR, "Recv other type packet %d\n", chunk_type); return AVERROR_INVALIDDATA; } return 0; } static int mmsh_read(URLContext *h, uint8_t *buf, int size) { int res = 0; MMSHContext *mmsh = h->priv_data; MMSContext *mms = &mmsh->mms; do { if (mms->asf_header_read_size < mms->asf_header_size) { // copy asf header into buffer res = ff_mms_read_header(mms, buf, size); } else { if (!mms->remaining_in_len && (res = handle_chunk_type(mmsh))) return res; res = ff_mms_read_data(mms, buf, size); } } while (!res); return res; } URLProtocol ff_mmsh_protocol = { .name = "mmsh", .url_open = mmsh_open, .url_read = mmsh_read, .url_write = NULL, .url_seek = NULL, .url_close = mmsh_close, };
gpl-3.0
dassencio/cracking-the-code-interview
chapter04/4.02/solve.cpp
1
4993
/* * TASK: Determine whether there is a route between two nodes of a given * directed graph. */ #include <algorithm> #include <cassert> #include <iostream> #include <list> #include <queue> #include <unordered_set> #include <vector> /** @brief A directed graph represented by its adjacency list. */ class directed_graph { public: directed_graph(const size_t n) : adjacency_list_(n) { /* nothing needs to be done here */ } /** * @brief Creates a directed edge connecting node u to node v. * @note Complexity: O(1) in both time and space. */ void create_edge(const size_t u, const size_t v) { adjacency_list_[u].push_back(v); } /** * @brief Returns a list containing the nodes to which node u is connected. * @note Complexity: O(1) in both time and space. */ const std::list<size_t>& adjacency_list(const size_t u) const { return adjacency_list_[u]; } private: std::vector<std::list<size_t> > adjacency_list_; }; /** * @brief Returns true if a path between nodes s and d exists, false otherwise * (the existence of a path is determined using BFS). * @note Complexity: O(m+n) in time, O(n) in space, where m and n are the * number of edges and nodes on the graph respectively. */ bool has_path_bfs(const directed_graph& G, const size_t s, const size_t d) { std::queue<size_t> Q; std::unordered_set<size_t> explored; Q.push(s); explored.insert(s); while (Q.empty() == false) { const size_t u = Q.front(); Q.pop(); if (u == d) { return true; } /* go over the nodes to which u is connected */ for (const size_t v : G.adjacency_list(u)) { /* if we have not yet explored v */ if (explored.find(v) == explored.end()) { Q.push(v); explored.insert(v); } } } return false; } bool __has_path_dfs(const directed_graph& G, const size_t s, const size_t d, std::unordered_set<size_t>& explored) { explored.insert(s); /* go over the nodes to which s is connected */ for (const size_t v : G.adjacency_list(s)) { if (v == d) { return true; } /* if v was not yet explored */ if (explored.find(v) == explored.end()) { if (__has_path_dfs(G, v, d, explored) == true) { return true; } } } return false; } /** * @brief Returns true if a path between nodes s and d exists, false otherwise * (the existence of a path is determined using DFS). * @note Complexity: O(m+n) in time, O(n) in space, where m and n are the * number of edges and nodes on the graph respectively (the space * complexity is O(n) because the recursion will not go deepder than * n levels). */ bool has_path_dfs(const directed_graph& G, const size_t s, const size_t d) { /* trivial case: source and destination are the same node */ if (s == d) { return true; } std::unordered_set<size_t> explored; return __has_path_dfs(G, s, d, explored); } /** * @brief Creates a random directed graph with n nodes and m edges. * @note Complexity: O(n+m) in both time and space. */ directed_graph random_graph(const size_t n, size_t m) { static std::random_device device; static std::mt19937 generator(device()); directed_graph G(n); if (n > 0) { std::uniform_int_distribution<size_t> distribution(0, n - 1); while (m > 0) { size_t u = distribution(generator); size_t v = distribution(generator); G.create_edge(u, v); --m; } } return G; } int main() { for (size_t n = 0; n <= 20; ++n) { for (size_t m = 0; m <= n * n; ++m) { directed_graph G = random_graph(n, m); /* * check that both BFS and DFS yield the same * results for all pairs of nodes (u,v) in G */ for (size_t u = 0; u < n; ++u) { for (size_t v = 0; v < n; ++v) { assert(has_path_bfs(G, u, v) == has_path_dfs(G, u, v)); } } /* * sanity check: for all edges u -> v, a path between * u and v must exist */ for (size_t u = 0; u < n; ++u) { for (const size_t v : G.adjacency_list(u)) { assert(has_path_bfs(G, u, v) == true); assert(has_path_dfs(G, u, v) == true); } } } std::cout << "passed random tests for graphs of size " << n << std::endl; } return EXIT_SUCCESS; }
gpl-3.0
mdelcid/Progra3Examen2Tiburon-master
main.cpp
1
3465
// queue::push/pop #include <iostream> #include <list> #include <fstream> #include <stack> #include <queue> #include <set> #include <map> #include "Contacto.h" #include "Evaluador.h" #include "NodoBinario.h" using namespace std; //Escribe los datos del objeto contacto (dado) en un archivo binario con el nombre dado en la posicion dada //Nota: Se deben poder agregar varios contactos en un solo archivo void escribir(string nombre_archivo, Contacto*contacto, int posicion) {//https://github.com/Ceutec/Progra3EjerciciosEnClase/blob/master/2015Examen2-master/main.cpp referencia para este ejercicio ofstream out(nombre_archivo.c_str(),ios::in); out.seekp(43*posicion); out.write(contacto->nombre.c_str(),10); out.write(contacto->correo.c_str(),10); out.write((char*)&contacto->numero,4); out.close(); } //Devuelve un contacto previamente escrito (con la funcion escribir()) en un archivo binario con nombre dado en la posicion dada //Nota: Se deben poder leer varios contactos de un solo archivo Contacto* leer(string nombre_archivo, int posicion) {//https://github.com/Ceutec/Progra3EjerciciosEnClase/blob/master/2015Examen2-master/main.cpp referencia para este ejercicio ifstream in(nombre_archivo.c_str()); char nombre[10]; int numero; char correo[10]; in.seekg(43*posicion); in.read(nombre,10); in.read(correo,10); in.read((char*)&numero,4); in.close(); Contacto *c = new Contacto(nombre, correo, numero); return c; } //Devuelve un vector que contenga todos los nombres de los contactos previamente ingresados en el archivo con nombre dado vector<string> getNombres(string nombre_archivo) { vector<string>nombres; return nombres; } //Devuelve true si valor_buscado (dado) se encuentra dentro de mi_cola (dada), de lo contrario devuelve false bool existe(queue<char> mi_cola, char valor_buscado) {//https://github.com/mdelcid/clase7/blob/master/main.cpp link de referencia ejercicios realizados en clase while(!mi_cola.empty()) { if (mi_cola.front()==valor_buscado) return true; mi_cola.pop(); } return false; } //Devuelve true si valor (dado) existe dentro de mi_set (dado) bool existe(set<int> mi_set,int valor) {//https://github.com/mdelcid/clase7/blob/master/main.cpp link de referencia ejercicios realizados en clase // set<int>(mi_set); // mi_set.insert(10); if(mi_set.find(valor)!=mi_set.end()) return true; return false; } //Devuelve una lista inversa de mi_lista (dada) list<double> invertir(list<double>mi_lista) { list<double> invertida; return invertida; } //Devuelve la cantidad de nodos que contiene un arbol con raiz dada int contar(NodoBinario* raiz) { // void imprimir (); // { // imprimir(raiz); // } // void imprimir(Nodo* raiz) // { // if(raiz==NULL) // return; // cout<<raiz->valor<<endl; // imprimir(raiz->hijo_izq); // imprimir(raiz->hijo_der); // } return -1; } //Cambia todos los valores de un arbol con raiz dada void cambiarValores(NodoBinario* raiz,int nuevo_valor) { // if(raiz==NULL) // return; // // if(raiz->valor==nuevo_valor) // raiz->valor=nuevo_valor; // // buscarYReemplazar(raiz->hijo_izq,nuevo_valor, nuevo_valor); // buscarYReemplazar(raiz->hijo_der,nuevo_valor, nuevo_valor); } int main () { //Funcion evaluadora evaluar(); return 0; }
gpl-3.0
Fogost-Tower/Linux-Driver
led/first_drv.c
1
3324
#include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/delay.h> #include <asm/uaccess.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/arch/regs-gpio.h> #include <asm/hardware.h> #define ulong unsigned long #define uchar unsigned char #define uint unsigned int #define DEV_NAME "led" //É豸µÄÃû×Ö #define DEV_MAJOR 252 //É豸µÄÉ豸Ö÷É豸ºÅ static struct class *leds_class; //¶¨ÒåÉ豸Àà static struct class_device *leds_class_device[4]; //¶¨ÒåÉ豸Çý¶¯Àà /***********¶¨ÒåͨÓö˿ڵÄÎïÀíµØÖ·******************/ static ulong GPIO_VA; //¶¨ÒåͨÓö˿ڵÄÐéÄâµØÖ· #define GPIO_OFF(x) ((x)-0x56000000) #define GPFCON (*(volatile ulong *))(GPIO_VA+GPIO_OFF(0x56000050)) #define GPFDAT (*(volatile ulong *))(GPIO_VA+GPIO_OFF(0x56000054)) static int S3C2440_LEDS_OPEN(struct inode *inode,struct file *file) { int minor = MINOR(inode->i_dev); switch(minor) { case 0: { GPFCON &= ~((0x3<<(4*2)) | (0x3<<(5*2)) | (0x3<<(6*2))); GPFCON |= ((1<<(4*2)) | (1<<(5*2)) | (1<<(6*2))); GPFDAT &= ~((1<<4) | (1<<5) | (1<<6)); break; } case 1: { s3c2410_gpio_cfgpin(S3C2410_GPF4,S3C2410_GPF4_OUTP); s3c2410_gpio_setpin(S3C2410_GPF4,0); break; } case 2: { s3c2410_gpio_cfgpin(S3C2410_GPF5,S3C2410_GPF5_OUTP); s3c2410_gpio_setpin(S3C2410_GPF5,0); break; } case 3: { s3c2410_gpio_cfgpin(S3C2410_GPF6,S3C2410_GPF6_OUTP); s3c2410_gpio_setpin(S3C2410_GPF6,0); break; } } return 0; } static ssize_t S3C2440_LEDS_WRITE(struct file *file,const char __user *buf,size_t count,loff_t ppos) { int minor = MINOR(file->f_dentry->d_inode->i_rdev); char val; copy_from_user(&val,buf,1); switch(minor) { case 0: { s3c2410_gpio_setpin(S3C2410_GPF4,(val & 0x1)); s3c2410_gpio_setpin(S3C2410_GPF5,(val & 0x1)); s3c2410_gpio_setpin(S3C2410_GPF6,(val & 0x1)); break; } case 1: { s3c2410_gpio_setpin(S3C2410_GPF4,(val)); break; } case 2: { s3c2410_gpio_setpin(S3C2410_GPF5,(val)); break; } case 3: { s3c2410_gpio_setpin(S3C2410_GPF6,(val)); break; } } return 1; } static struct file_operations dev_oper= { .owner =THIS_MODULE, .open =S3C2440_LEDS_OPEN, .write =S3C2440_LEDS_WRITE, }; static int __init S3C2440_INIT(void) { int major; int i; major=register_chrdev(DEV_MAJOR,DEV_NAME,&dev_oper); leds_class=class_create(THIS_MODULE,"leds"); leds_class_device[0]=class_device_create(leds_class, NULL, MADEV(DEV_MAJOR,0), NULL, "leds"); //´´½¨leds²¢¹ÒÔØÉ豸Çý¶¯ºÅ 252 0 for(i=1;i<4;++i) { leds_class_device[i]=class_device_create(leds_class, NULL, MADEV(DEV_MAJOR,i) ,NULL ,"led%d", i); //´´½¨led£¨1/2/3£©²¢¹ÒÔØÉ豸Çý¶¯ºÅ 252 1/2/3 } GPIO_VA=ioremap(0x56000000,0x10000); if(!GPIO_VA) return -EIO; //¸ã¶®·µ»ØÖµ } static int __exit S3C2440_EXIT(void) { int i; unregister_chrdev(DEV_MAJOR,DEVNAME); for(i=0;i<4;++i) { class_device_unregister(leds_class_device[i]); } class_destroy(leds_class); iounmap(GPIO_VA); } module_init(S3C2440_INIT); //ÔÚʹÓÃinsmod µ÷Óøú¯Êý module_exit(S3C2440_EXIT); //ÔÚʹÓÃrmmod µ÷Óøú¯Êý MODULE_LICENCE("GPL");
gpl-3.0
mmoller2k/Float64
softfloat/s_shortShiftRightJamM.c
1
2713
/*============================================================================ This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic Package, Release 3a, by John R. Hauser. Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of California. 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 University 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 REGENTS 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 REGENTS 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 <stdint.h> #include "../include/platform.h" #include "../include/primitiveTypes.h" #ifndef softfloat_shortShiftRightJamM void softfloat_shortShiftRightJamM( uint_fast8_t size_words, const uint32_t *aPtr, uint_fast8_t count, uint32_t *zPtr ) { uint_fast8_t negCount; unsigned int index, lastIndex; uint32_t partWordZ, wordA; negCount = -count; index = indexWordLo( size_words ); lastIndex = indexWordHi( size_words ); wordA = aPtr[index]; partWordZ = wordA>>count; if ( partWordZ<<count != wordA ) partWordZ |= 1; while ( index != lastIndex ) { wordA = aPtr[index + wordIncr]; zPtr[index] = wordA<<(negCount & 31) | partWordZ; index += wordIncr; partWordZ = wordA>>count; } zPtr[index] = partWordZ; } #endif
gpl-3.0
RobertLuptonTheGood/psfex
src/fft.c
1
7539
/* * fft.c * * Functions dealing with FFT. * *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * This file part of: PSFEx * * Copyright: (C) 2008-2010 Emmanuel Bertin -- IAP/CNRS/UPMC * * License: GNU General Public License * * PSFEx 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. * PSFEx 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 PSFEx. If not, see <http://www.gnu.org/licenses/>. * * Last modified: 10/10/2010 * *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include <stdio.h> #include <stdlib.h> #include FFTW_H #include "define.h" #include "globals.h" #include "fft.h" #ifdef USE_THREADS #include "threads.h" #endif int firsttimeflag; #ifdef USE_THREADS pthread_mutex_t fftmutex; #endif #define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr /****** fft_init ************************************************************ PROTO void fft_init(int nthreads) PURPOSE Initialize the FFT routines INPUT -. OUTPUT -. NOTES Global preferences are used for multhreading. AUTHOR E. Bertin (IAP) VERSION 26/06/2009 ***/ void fft_init(int nthreads) { if (!firsttimeflag) { #ifdef USE_THREADS QPTHREAD_MUTEX_INIT(&fftmutex, NULL); #ifdef HAVE_FFTWF_MP if (nthreads > 1) { if (!fftwf_init_threads()) error(EXIT_FAILURE, "*Error*: thread initialization failed in ","FFTW"); fftwf_plan_with_nthreads(nthreads); } #endif #endif firsttimeflag = 1; } return; } /****** fft_end ************************************************************ PROTO void fft_init(int nthreads) PURPOSE Clear up stuff set by FFT routines INPUT -. OUTPUT -. NOTES -. AUTHOR E. Bertin (IAP) VERSION 26/06/2009 ***/ void fft_end(int nthreads) { if (firsttimeflag) { firsttimeflag = 0; #ifdef USE_THREADS if (nthreads > 1) { #ifdef HAVE_FFTWF_MP fftwf_cleanup_threads(); #endif QPTHREAD_MUTEX_DESTROY(&fftmutex); } else #endif fftwf_cleanup(); } return; } /****** fft_conv ************************************************************ PROTO void fft_conv(float *data1, float *fdata2, int width, int height) PURPOSE Optimized 2-dimensional FFT convolution using the FFTW library. INPUT ptr to the first image, ptr to the Fourier transform of the second image, image width, image height. OUTPUT -. NOTES For data1 and fdata2, memory must be allocated for size[0]* ... * 2*(size[naxis-1]/2+1) floats (padding required). AUTHOR E. Bertin (IAP) VERSION 15/04/2009 ***/ void fft_conv(float *data1, float *fdata2, int width, int height) { fftwf_plan plan; float *fdata1,*fdata1p,*fdata2p, real,imag, fac; int i, npix,npix2; /* Convert axis indexing to that of FFTW */ npix = width*height; npix2 = (((width>>1) + 1)<< 1) * height; /* Forward FFT "in place" for data1 */ #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif QFFTWMALLOC(fdata1, float, npix2); plan = fftwf_plan_dft_r2c_2d(height, width, data1, (fftwf_complex *)fdata1, FFTW_ESTIMATE|FFTW_DESTROY_INPUT); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif fftwf_execute(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif fftwf_destroy_plan(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif /* Actual convolution (Fourier product) */ fac = 1.0/npix; fdata1p = fdata1; fdata2p = fdata2; for (i=npix2/2; i--; fdata2p+=2) { real = *fdata1p **fdata2p - *(fdata1p+1)**(fdata2p+1); imag = *(fdata1p+1)**fdata2p + *fdata1p**(fdata2p+1); *(fdata1p++) = fac*real; *(fdata1p++) = fac*imag; } /* Reverse FFT */ #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif plan = fftwf_plan_dft_c2r_2d(height, width, (fftwf_complex *)fdata1, data1, FFTW_ESTIMATE|FFTW_DESTROY_INPUT); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif fftwf_execute(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif fftwf_destroy_plan(plan); /* Free the fdata1 scratch array */ QFFTWFREE(fdata1); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif return; } /****** fft_rtf ************************************************************ PROTO float *fft_rtf(float *data, int width, int height) PURPOSE Optimized 2-dimensional FFT "in place" using the FFTW library. INPUT ptr to the image, image width, image height. OUTPUT Pointer to the compressed, memory-allocated Fourier transform. NOTES Input data may end up corrupted. AUTHOR E. Bertin (IAP) VERSION 15/04/2009 ***/ float *fft_rtf(float *data, int width, int height) { fftwf_plan plan; float *fdata; int npix2; /* Convert axis indexing to that of FFTW */ npix2 = (((width>>1) + 1)<< 1) * height; /* Forward FFT "in place" for data1 */ #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif QFFTWMALLOC(fdata, float, npix2); plan = fftwf_plan_dft_r2c_2d(height, width, data, (fftwf_complex *)fdata, FFTW_ESTIMATE); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif fftwf_execute(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif fftwf_destroy_plan(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif return fdata; } /****** fft_ctf ************************************************************ PROTO void fft_ctf(float *data, int width, int height int sign) PURPOSE Optimized 2-dimensional complex FFT "in place" using the FFTW library. INPUT ptr to the image, image width, image height. OUTPUT -. NOTES -. AUTHOR E. Bertin (IAP) VERSION 15/04/2009 ***/ void fft_ctf(float *data, int width, int height, int sign) { fftwf_plan plan; /* Forward FFT "in place" for data1 */ #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif plan = fftwf_plan_dft_2d(height, width, (fftwf_complex *)data, (fftwf_complex *)data, sign, FFTW_ESTIMATE); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif fftwf_execute(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_LOCK(&fftmutex); #endif fftwf_destroy_plan(plan); #ifdef USE_THREADS QPTHREAD_MUTEX_UNLOCK(&fftmutex); #endif return; } /****** fft_shift ************************************************************ PROTO void fft_shift(float *data, int width, int height) PURPOSE (de-)scramble 2-dimensional Fourier plane. INPUT ptr to the image, image width, image height. OUTPUT -. NOTES -. AUTHOR E. Bertin (IAP) VERSION 21/04/2009 ***/ void fft_shift(float *data, int width, int height) { float *temp, *tempt, *datat; int i, xc,yc, x,y,x2,y2, npix; npix = width*height; QMALLOC(temp, float, width*height); datat = data; xc = width/2; yc = height/2; for (y=0; y<height; y++) { y2 = y-yc; if (y2<0) y2 += height; y2 *= width; for (x=0; x<width; x++) { x2 = x-xc; if (x2<0) x2 += width; temp[x2+y2] = *(datat++); } } tempt = temp; for (i=npix; i--;) *(data++) = *(tempt++); free(temp); return; }
gpl-3.0
therifboy/echelon-bo2
src/hud.cpp
1
10991
#include "hud.h" #include "game_mp/g_local_mp.h" #include <string.h> inline game_hudelem_s* G_HudElems(int index) { return &g_hudelems[index]; } game_hudelem_s* HudElem_Alloc(int client, he_type_t type) { game_hudelem_s* hud; if (client == 0x3FF) { for (int index = 1008; index < 1024; index++) { if ((hud = G_HudElems(index))->elem.type == HE_TYPE_FREE) { hud->elem.type = type; hud->elem.targetEntNum = hud->clientNum = client; hud->archived = 1; hud->elem.ui3dWindow = -1; return hud; } } } else { for (int index = client * 84; index < ((client + 1) * 84); index++) { if ((hud = G_HudElems(index))->elem.type == HE_TYPE_FREE) { hud->elem.type = type; hud->elem.targetEntNum = hud->clientNum = client; hud->archived = 1; hud->elem.ui3dWindow = -1; return hud; } } } ClearAll(client); return HudElem_Alloc(client, type); } game_hudelem_s* SetShader(int client, const char* material, hudelem_color_t color, short width, short height, float x, float y) { game_hudelem_s* elem = HudElem_Alloc(client, HE_TYPE_MATERIAL); elem->elem.materialIndex = G_MaterialIndex(material); elem->elem.color = color; elem->elem.width = width; elem->elem.height = height; elem->elem.x = x; elem->elem.y = y; return elem; } game_hudelem_s* SetShader(int client, int material, hudelem_color_t color, short width, short height, float x, float y) { game_hudelem_s* elem = HudElem_Alloc(client, HE_TYPE_MATERIAL); elem->elem.materialIndex = material; elem->elem.color = color; elem->elem.width = width; elem->elem.height = height; elem->elem.x = x; elem->elem.y = y; return elem; } game_hudelem_s* SetText(int client, const char* text, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, float x, float y) { game_hudelem_s* elem = HudElem_Alloc(client, HE_TYPE_TEXT); elem->elem.text = G_LocalizedStringIndex(text); elem->elem.color = color; elem->elem.glowColor = glowColor; elem->elem.fontScale = fontScale; elem->elem.font = font; elem->elem.x = x; elem->elem.y = y; return elem; } game_hudelem_s* SetText(int client, int text, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, float x, float y) { game_hudelem_s* elem = HudElem_Alloc(client, HE_TYPE_TEXT); elem->elem.text = text; elem->elem.color = color; elem->elem.glowColor = glowColor; elem->elem.fontScale = fontScale; elem->elem.font = font; elem->elem.x = x; elem->elem.y = y; return elem; } void ClearAll(int client) { if (client == 0x3FF) { for (int index = 1008; index < 1024; index++) { memset((void*)G_HudElems(index), 0, sizeof(game_hudelem_s)); } } else { for (int index = client * 84; index < ((client + 1) * 84); index++) { memset((void*)G_HudElems(index), 0, sizeof(game_hudelem_s)); } } } game_hudelem_s* SetFx(int client, const char* text, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, short letterTime, short decayStartTime, short decayDuration, int levelTime, int flags) { game_hudelem_s* elem = SetText(client, text, color, glowColor, font, fontScale, 180 - strlen(text), 125); elem->elem.fxBirthTime = (levelTime == -1 ? level->time : levelTime); elem->elem.fxLetterTime = letterTime; elem->elem.fxDecayStartTime = decayStartTime; elem->elem.fxDecayDuration = decayDuration; elem->elem.flags |= flags; return elem; } game_hudelem_s* SetWayPoint(const char* material, hudelem_color_t color, int team, float x, float y, float z) { game_hudelem_s* elem = HudElem_Alloc(0x3FF, HE_TYPE_WAYPOINT); elem->elem.offscreenMaterialIdx = G_MaterialIndex(material); elem->elem.x = x; elem->elem.y = y; elem->elem.z = z; elem->team = team; elem->elem.color = color; return elem; } game_hudelem_s* SetWayPoint(int material, hudelem_color_t color, int team, float x, float y, float z) { game_hudelem_s* elem = HudElem_Alloc(0x3FF, HE_TYPE_WAYPOINT); elem->elem.offscreenMaterialIdx = material; elem->elem.x = x; elem->elem.y = y; elem->elem.z = z; elem->team = team; elem->elem.color = color; return elem; } game_hudelem_s* SetValue(int client, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, float value, float x, float y) { game_hudelem_s* elem = HudElem_Alloc(client, HE_TYPE_VALUE); elem->elem.color = color; elem->elem.glowColor = glowColor; elem->elem.value = value; elem->elem.font = font; elem->elem.fontScale = fontScale; elem->elem.x = x; elem->elem.y = y; return elem; } game_hudelem_s* SetPlayerName(int client, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, int playerIndex, float x, float y) { game_hudelem_s* elem = HudElem_Alloc(client, HE_TYPE_PLAYERNAME); elem->elem.color = color; elem->elem.glowColor = glowColor; elem->elem.value = playerIndex; elem->elem.font = font; elem->elem.fontScale = fontScale; elem->elem.x = x; elem->elem.y = y; return elem; } game_hudelem_s* SetTypeWriter(int client, const char* text, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, short letterTime, short decayStartTime, short decayDuration, int levelTime) { game_hudelem_s* elem = SetFx(client, text, color, glowColor, font, fontScale, letterTime, decayStartTime, decayDuration, levelTime, HUDELEMFLAG_TYPEWRITER); return elem; } game_hudelem_s* SetDecodeFx(int client, const char* text, hudelem_color_t color, hudelem_color_t glowColor, he_font_t font, float fontScale, short letterTime, short decayStartTime, short decayDuration, int levelTime) { game_hudelem_s* elem = SetFx(client, text, color, glowColor, font, fontScale, letterTime, decayStartTime, decayDuration, levelTime, HUDELEMFLAG_COD7DECODE); return elem; } void FontScaleOverTime(game_hudelem_s* elem, short fontScaleDuration, float fontScale, int levelTime) { elem->elem.fromFontScale = elem->elem.fontScale; elem->elem.fontScale = fontScale; elem->elem.fontScaleTime = fontScaleDuration; elem->elem.fontScaleStartTime = (levelTime == -1 ? level->time : levelTime); elem->elem.fromAlignOrg = elem->elem.alignOrg; elem->elem.fromAlignScreen = elem->elem.alignScreen; } void ScaleOverTime(game_hudelem_s* elem, short scaleDuration, short width, short height, int levelTime) { elem->elem.fromWidth = elem->elem.width; elem->elem.fromHeight = elem->elem.height; elem->elem.width = width; elem->elem.height = height; elem->elem.scaleTime = scaleDuration; elem->elem.scaleStartTime = (levelTime == -1 ? level->time : levelTime); elem->elem.fromAlignOrg = elem->elem.alignOrg; elem->elem.fromAlignScreen = elem->elem.alignScreen; } void MoveOverTime(game_hudelem_s* elem, short moveDuration, float x, float y, int levelTime) { elem->elem.fromX = elem->elem.x; elem->elem.fromY = elem->elem.y; elem->elem.x = x; elem->elem.y = y; elem->elem.moveTime = moveDuration; elem->elem.fromAlignScreen = elem->elem.alignScreen; elem->elem.fromAlignOrg = elem->elem.fromAlignOrg; elem->elem.moveStartTime = (levelTime == -1 ? level->time : levelTime); elem->elem.fromAlignOrg = elem->elem.alignOrg; elem->elem.fromAlignScreen = elem->elem.alignScreen; } void FadeOverTime(game_hudelem_s* elem, short fadeDuration, hudelem_color_t color, int levelTime) { elem->elem.fromColor = elem->elem.color; elem->elem.color = color; elem->elem.fadeTime = fadeDuration; elem->elem.fadeStartTime = (levelTime == -1 ? level->time : levelTime); } void NullFx(game_hudelem_s* elem) { elem->elem.fadeStartTime = elem->elem.fadeTime = elem->elem.fontScaleStartTime = elem->elem.fontScaleTime = elem->elem.fxBirthTime = elem->elem.fxDecayDuration = elem->elem.fxDecayStartTime = elem->elem.fxLetterTime = elem->elem.fxRedactDecayDuration = elem->elem.fxRedactDecayStartTime = elem->elem.moveStartTime = elem->elem.moveTime = elem->elem.scaleStartTime = elem->elem.scaleTime = elem->elem.time = elem->elem.duration = 0; } void ClearHud(game_hudelem_s* elem) { memset(elem, 0, sizeof(game_hudelem_s)); } void FadeWhenTargeted(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_FADEWHENTARGETED; else elem->elem.flags &= ~HUDELEMFLAG_FADEWHENTARGETED; } void HideWhenDead(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_HIDEWHENDEAD; else elem->elem.flags &= ~HUDELEMFLAG_HIDEWHENDEAD; } void HideWhenInKillcam(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_HIDEWHENINKILLCAM; else elem->elem.flags &= ~HUDELEMFLAG_HIDEWHENINKILLCAM; } void HideWhenInDemo(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_HIDEWHENINDEMO; else elem->elem.flags &= ~HUDELEMFLAG_HIDEWHENINDEMO; } void HideWhenInMenu(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_HIDEWHENINMENU; else elem->elem.flags &= ~HUDELEMFLAG_HIDEWHENINMENU; } void HideWhenInScope(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_HIDEWHENINSCOPE; else elem->elem.flags &= ~HUDELEMFLAG_HIDEWHENINSCOPE; } void HideWhileRemoteControlling(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_HIDEWHILEREMOTECONTROLING; else elem->elem.flags &= ~HUDELEMFLAG_HIDEWHILEREMOTECONTROLING; } void ForeGround(game_hudelem_s* elem, bool value) { if (value) elem->elem.flags |= HUDELEMFLAG_FOREGROUND; else elem->elem.flags &= ~HUDELEMFLAG_FOREGROUND; } void Font(game_hudelem_s* elem, he_font_t font) { elem->elem.font = font; } void AlignX(game_hudelem_s* elem, alignX_t align) { elem->elem.alignOrg &= ~0xC; elem->elem.alignOrg |= (align << 2); } void AlignY(game_hudelem_s* elem, alignY_t align) { elem->elem.alignOrg &= ~0x3; elem->elem.alignOrg |= (align); } void HorzAlign(game_hudelem_s* elem, horzAlign_t align) { elem->elem.alignScreen &= 0x0F; elem->elem.alignScreen |= (align << 4); } void VertAlign(game_hudelem_s* elem, vertAlign_t align) { elem->elem.alignScreen &= 0xF0; elem->elem.alignScreen |= (align); } bool FadeWhenTargeted(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_FADEWHENTARGETED); } bool HideWhenDead(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_HIDEWHENDEAD); } bool HideWhenInKillcam(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_HIDEWHENINKILLCAM); } bool HideWhenInDemo(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_HIDEWHENINDEMO); } bool HideWhenInMenu(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_HIDEWHENINMENU); } bool HideWhenInScope(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_HIDEWHENINSCOPE); } bool HideWhileRemoteControlling(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_HIDEWHILEREMOTECONTROLING); } bool ForeGround(game_hudelem_s* elem) { return (elem->elem.flags & HUDELEMFLAG_FOREGROUND); }
gpl-3.0
femto-dev/femto
src/main/results.c
1
25125
/* (*) 2006-2013 Michael Ferguson <michaelferguson@acm.org> * This is a work of the United States Government and is not protected by copyright in the United States. 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/>. femto/src/main/results.c */ #include "results.h" #include <stdlib.h> #include "util.h" #include "buffer_funcs.h" void results_clear(results_t* results) { results->data = NULL; results->num_documents = 0; //memset(results, 0, sizeof(results_t)); } void results_clear_set_type(results_t* results, result_type_t type) { results_clear(results); results->type = type; } results_t empty_results(result_type_t type) { results_t ret; results_clear_set_type(&ret, type); return ret; } void results_destroy(results_t* results) { if( results->data ) free(results->data); results_clear_set_type(results, results->type); } result_type_t results_type(results_t* results) { return results->type; } void results_move(results_t* dst, results_t* src) { if( dst->data ) results_destroy( dst ); *dst = *src; results_clear(src); } int64_t results_data_size(results_t* results) { results_reader_t r; int64_t document, offset; int64_t ret = 0; error_t err; err = results_reader_create(&r, results); if( err ) return 0; while( results_reader_next(&r, &document, &offset) ) { ; // do nothing. } ret = r.buf.pos; results_reader_destroy(&r); return ret; } void results_print(FILE* f, results_t* results) { results_reader_t r; int64_t document, offset; error_t err; err = results_reader_create(&r, results); if( err ) { fprintf(f, "Results print error: %s", err_string(err)); } while( results_reader_next(&r, &document, &offset) ) { fprintf(f, "Result doc=%" PRIi64 " off=%" PRIi64"\n", document, offset); } results_reader_destroy(&r); } error_t results_copy(results_t* dst, results_t* src) { int64_t size; if( dst->data ) results_destroy( dst ); *dst = *src; size = results_data_size(src); dst->data = malloc(size); if( ! dst->data ) { dst->num_documents = 0; return ERR_MEM; } memcpy(dst->data, src->data, size); return ERR_NOERR; } size_t maximum_size_for_results(int64_t num) { return 3*sizeof(int64_t)*num; } int64_t results_num_results(results_t* results) { results_reader_t r; int64_t document, offset; int64_t ret = 0; error_t err; err = results_reader_create(&r, results); if( err ) return 0; while( results_reader_next(&r, &document, &offset) ) { ret++; } results_reader_destroy(&r); return ret; } // returns last static inline error_t append_document_internal(buffer_t* buf, int64_t result, int64_t* last_written, int64_t* num_written) { if( *num_written == 0 ) *last_written = 0; // we're going to add one to result so that we can encode an initial // zero. result++; // only append results that are greater than the last written. if( result <= *last_written ) return ERR_PARAM; buffer_encode_gamma(buf, result - *last_written); *last_written = result; *num_written = *num_written + 1; return ERR_NOERR; } error_t results_write_buffer(buffer_t* buf, results_t* results) { int64_t last, num_written; int64_t size; last = num_written = 0; // first, find the length of the results size = results_data_size(results); // next, append those bytes. memcpy(&buf->data[buf->len], results->data, size); return ERR_NOERR; } error_t results_create_sort(results_t* r, int64_t num, int64_t* results) { error_t err; int64_t unique; results_writer_t writer; // sort and dedup them! unique = sort_dedup(results, num, sizeof(int64_t), compare_int64); // store them in a results set! err = results_writer_create(&writer, RESULT_TYPE_DOCUMENTS); if( err ) return err; for( int64_t i = 0; i < unique; i++ ) { err = results_writer_append(&writer, results[i], 0); if( err ) goto error; } err = results_writer_finish(&writer, r); if( err ) goto error; err = ERR_NOERR; error: results_writer_destroy(&writer); return err; } int compare_location_info(const void* aP, const void* bP) { location_info_t* a = (location_info_t*) aP; location_info_t* b = (location_info_t*) bP; if( a->doc < b->doc ) return -1; else if ( a->doc > b->doc ) return 1; else { if( a->offset < b->offset ) return -1; if( a->offset > b->offset ) return 1; else return 0; } } error_t results_create_sort_locations(results_t* r, int64_t num, location_info_t* results) { error_t err; int64_t unique; results_writer_t writer; // sort and dedup them! unique = sort_dedup(results, num, sizeof(location_info_t), compare_location_info); // store them in a results set! err = results_writer_create(&writer, RESULT_TYPE_DOC_OFFSETS); if( err ) return err; for( int64_t i = 0; i < unique; i++ ) { err = results_writer_append(&writer, results[i].doc, results[i].offset); if( err ) goto error; } err = results_writer_finish(&writer, r); if( err ) goto error; err = ERR_NOERR; error: results_writer_destroy(&writer); return err; } error_t results_writer_create(results_writer_t* w, result_type_t type) { int start_size = 128; unsigned char* data = malloc(start_size); if( ! data ) return ERR_MEM; w->buf = build_buffer(start_size, data); w->last_document = 0; w->last_offset = 0; w->num_documents = 0; w->type = type; bsInitWrite(& w->buf); return ERR_NOERR; } error_t results_writer_append(results_writer_t* w, int64_t document, int64_t offset ) { error_t err; // make sure there's room for a gamma-encoded value in the results. err = buffer_extend(&w->buf, 5*sizeof(int64_t)); if( err ) return err; if( w->type == RESULT_TYPE_DOCUMENTS ) { // append the document number. err = append_document_internal(&w->buf, document, &w->last_document, &w->num_documents); if( err ) return err; } if( is_doc_offsets(w->type) ) { if( w->last_document != document+1 ) { if( w->num_documents != 0 ) { // append the "end of offsets" value. buffer_encode_gamma(&w->buf, 1 ); } // append the document number. err = append_document_internal(&w->buf, document, &w->last_document, &w->num_documents); if( err ) return err; // start the offsets at 0. w->last_offset = 0; } // append the offset. offset++; // add one to make numbers count from 1. if( w->last_offset == 0 && (w->type & RESULT_TYPE_REV_OFFSETS) ) { // the first offset should be <= 0. if( offset > 1 ) return ERR_PARAM; // we're recording negative offsets... // so write a "2" if the input was "0" // so write a "3" if the input was "-1" buffer_encode_gamma(&w->buf, 3 - offset); } else { if( offset <= w->last_offset ) return ERR_PARAM; buffer_encode_gamma(&w->buf, 1 + offset - w->last_offset); } w->last_offset = offset; } return ERR_NOERR; } error_t results_writer_finish(results_writer_t* w, results_t* out) { if( w->type & RESULT_TYPE_OFFSETS ) { // encode the "end of offsets" value buffer_encode_gamma(&w->buf, 1); } bsFinishWrite( & w->buf ); if( out->data ) results_destroy(out); out->data = w->buf.data; out->num_documents = w->num_documents; out->type = w->type; // clear the buffer. w->buf = build_buffer(0, NULL); w->num_documents = w->last_document = 0; return ERR_NOERR; } /* Frees memory created by results_writer_create. */ void results_writer_destroy(results_writer_t* w) { // normally the buffer is zeroed by finish(), but // if there was an error it might not be. free(w->buf.data); w->buf.data = NULL; } error_t results_reader_create(results_reader_t* r, results_t* in) { // the maximum size of the buffer isn't necessarily right, // but we don't check that in decode_gamma anyways, and also // we'll know if we're going off of the end from num_left. r->buf = build_buffer(0, in->data); r->last_document = 0; r->last_offset = 0; r->num_left = in->num_documents; r->type = in->type; r->is_in_offsets = 0; bsInitRead(& r->buf); return ERR_NOERR; } /* Reads the next result from a results_reader. Returns 0 if there was no result to read, or 1 if a result is returned in result. */ int results_reader_next(results_reader_t* r, int64_t* document, int64_t* offset) { if( r->type == RESULT_TYPE_DOCUMENTS ) { if( r->num_left > 0 ) { // read a result. r->last_document += buffer_decode_gamma(&r->buf); r->num_left--; // undo the adding one to handle initial zero. *document = r->last_document - 1; if( offset ) *offset = 0; return 1; } else { return 0; } } if( is_doc_offsets(r->type) ) { int64_t tmp; int repeat = 1; do { if( ! r->is_in_offsets ) { if( r->num_left > 0 ) { // read a new document number r->last_document += buffer_decode_gamma(&r->buf); r->num_left--; // undo the adding one to handle initial zero. //printf("decoded document %i\n", (int) r->last_document - 1); // next, read an offset. r->is_in_offsets = 1; r->last_offset = 0; repeat = 0; // we'll be done after we read the offset. } else { return 0; // no more documents left. } } *document = r->last_document - 1; if( r->is_in_offsets ) { // try reading an offset. tmp = buffer_decode_gamma(&r->buf); //printf("decoded offset gamma %i\n", (int) tmp); if( tmp == 1 ) { // "end of offsets" r->is_in_offsets = 0; // doesn't set done! } else { tmp--; // take away 1 from delta for end-of-offsets. if( r->last_offset == 0 && (r->type & RESULT_TYPE_REV_OFFSETS) ) { r->last_offset = 2 - tmp; } else { r->last_offset += tmp; } //printf("got offset %i\n", (int) r->last_offset - 1); if( offset ) { *offset = r->last_offset - 1; repeat = 0; } } } } while( repeat ); return 1; } return 0; } /** *Frees the memory created in results_reader_create. */ void results_reader_destroy(results_reader_t* r) { bsFinishRead(& r->buf); } error_t intersectResults(results_t* leftExpr, results_t* rightExpr, results_t* result) { int64_t left; // Current document for left & right terms of expression int64_t right; int64_t leftReadResult; //Ints representing whether or not the read was int64_t rightReadResult; //successful or not. results_reader_t leftReader; results_reader_t rightReader; results_writer_t writer; error_t error; error = results_reader_create(&leftReader,leftExpr); if(error) { return error; } error = results_reader_create(&rightReader,rightExpr); if(error) { return error; } error = results_writer_create(&writer, RESULT_TYPE_DOCUMENTS); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &left, NULL); rightReadResult = results_reader_next(&rightReader, &right, NULL); while( leftReadResult && rightReadResult ) { if(left < right) { leftReadResult = results_reader_next(&leftReader, &left, NULL); } else if ( left > right ) { rightReadResult = results_reader_next(&rightReader, &right, NULL); } else /* left == right */ { error = results_writer_append(&writer, left, 0); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &left, NULL); rightReadResult = results_reader_next(&rightReader, &right, NULL); } } error = results_writer_finish( &writer, result ); if(error) { return error; } results_writer_destroy(&writer); results_reader_destroy(&leftReader); results_reader_destroy(&rightReader); return ERR_NOERR; } error_t unionResults(results_t* leftExpr, results_t* rightExpr, results_t* result) { int64_t leftDoc; // Current document for left & right terms of expression int64_t rightDoc; int64_t leftOffset; int64_t rightOffset; int offsets; int64_t leftReadResult; //Ints representing whether or not the read was int64_t rightReadResult; //successful or not. results_reader_t leftReader; results_reader_t rightReader; results_writer_t writer; error_t error; if(leftExpr->type & RESULT_TYPE_OFFSETS ) { offsets = 1; } else { offsets = 0; } error = results_reader_create(&leftReader,leftExpr); if(error) { return error; } error = results_reader_create(&rightReader,rightExpr); if(error) { return error; } error = results_writer_create(&writer, leftExpr->type); if(error) { return error; } if(leftExpr->type != rightExpr->type) { printf("DIFFERENT TYPES!\n"); printf("left:%i right:%i\n",leftExpr->type,rightExpr->type); return ERR_PARAM; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); while( leftReadResult || rightReadResult ) { if(!leftReadResult) { error = results_writer_append(&writer, rightDoc, rightOffset); rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); if(error) { return error; } } else if(!rightReadResult) { error = results_writer_append(&writer, leftDoc, leftOffset); leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); if(error) { return error; } } else if( leftDoc < rightDoc) { error = results_writer_append(&writer, leftDoc, leftOffset); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); } else if ( leftDoc > rightDoc ) { error = results_writer_append(&writer, rightDoc, rightOffset); if(error) { return error; } rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); } else /* leftDoc == rightDoc */ { if(offsets) { if(leftOffset < rightOffset) { error = results_writer_append(&writer, leftDoc, leftOffset); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); } else if( leftOffset > rightOffset ) { error = results_writer_append(&writer, rightDoc, rightOffset); if(error) { return error; } rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); } else { // both are the same. error = results_writer_append(&writer, leftDoc, leftOffset); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); } } else { //Since not offset-based, doesnt matter which side we use since they //are equal. error = results_writer_append(&writer, leftDoc, 0); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); } } } error = results_writer_finish( &writer, result ); if(error) { return error; } results_writer_destroy(&writer); results_reader_destroy(&leftReader); results_reader_destroy(&rightReader); return ERR_NOERR; } error_t subtractResults(results_t* leftExpr, results_t* rightExpr, results_t* result) { int64_t left; // Current document for left & right terms of expression int64_t right; int64_t leftReadResult; //Ints representing whether or not the read was int64_t rightReadResult; //successful or not. results_reader_t leftReader; results_reader_t rightReader; results_writer_t writer; error_t error; error = results_reader_create(&leftReader,leftExpr); if(error) { return error; } error = results_reader_create(&rightReader,rightExpr); if(error) { return error; } error = results_writer_create(&writer, RESULT_TYPE_DOCUMENTS); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &left, NULL); rightReadResult = results_reader_next(&rightReader, &right, NULL); while( leftReadResult ) { if( !rightReadResult || ( left < right ) ) { error = results_writer_append(&writer, left,0); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &left, NULL); } else if ( left > right ) { rightReadResult = results_reader_next(&rightReader, &right, NULL); } else /* left == right */ { leftReadResult = results_reader_next(&leftReader, &left, NULL); rightReadResult = results_reader_next(&rightReader, &right, NULL); } } error = results_writer_finish( &writer, result ); if(error) { return error; } results_writer_destroy(&writer); results_reader_destroy(&leftReader); results_reader_destroy(&rightReader); return ERR_NOERR; } error_t thenResults(results_t* leftExpr, results_t* rightExpr, results_t* result, int distance) { int64_t leftDoc; // Current document for left & right terms of expression int64_t rightDoc; int64_t leftOffset; // Document offsets for results being evaluated int64_t rightOffset; int64_t width; //Distance between two offsets within the same doc (right - left) int64_t leftReadResult; //Ints representing whether or not the read was int64_t rightReadResult; //successful or not. results_reader_t leftReader; results_reader_t rightReader; results_writer_t writer; error_t error; int positive_distance; int64_t minOffset; if( distance > 0 ) positive_distance = distance; else positive_distance = - distance; error = results_reader_create(&leftReader,leftExpr); if(error) { return error; } error = results_reader_create(&rightReader,rightExpr); if(error) { return error; } if( ! is_doc_offsets(leftExpr->type) ) { // the expressions must both be doc-offsets return ERR_PARAM; } if( ! is_doc_offsets(rightExpr->type) ) { // the expressions must both be doc-offsets return ERR_PARAM; } if( leftExpr->type != rightExpr->type ) { return ERR_PARAM; } error = results_writer_create(&writer,leftExpr->type); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); rightReadResult = results_reader_next(&rightReader, &rightDoc,&rightOffset); while( leftReadResult && rightReadResult ) { if( leftDoc < rightDoc ) { leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); } else if( leftDoc > rightDoc ) { rightReadResult = results_reader_next(&rightReader, &rightDoc,&rightOffset); } else { width = rightOffset - leftOffset; // minOffset is the minimum of the two if ( rightOffset < leftOffset ) minOffset = rightOffset; else minOffset = leftOffset; if(distance < 0) { width = - width; } if(0 < width && width <= positive_distance) { //append and advance leftmost(minimum) offset //which doc used when appending doesnt matter since they are equal error = results_writer_append(&writer, leftDoc, minOffset); if(error) { return error; } } if ( rightOffset < leftOffset ) { //advance right rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); } else /* width > distance */ { //advance left leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); } } } error = results_writer_finish( &writer, result ); if(error) { return error; } results_writer_destroy(&writer); results_reader_destroy(&leftReader); results_reader_destroy(&rightReader); return ERR_NOERR; } error_t withinResults(results_t* leftExpr, results_t* rightExpr, results_t* result, int distance) { int64_t leftDoc; // Current document for left & right terms of expression int64_t rightDoc; int64_t leftOffset; // Document offsets for results being evaluated int64_t rightOffset; int64_t width; //Distance between two offsets within the same doc (right - left) int64_t leftReadResult; //Ints representing whether or not the read was int64_t rightReadResult; //successful or not. results_reader_t leftReader; results_reader_t rightReader; results_writer_t writer; error_t error; int positive_distance; int64_t minOffset; if( distance > 0 ) positive_distance = distance; else positive_distance = - distance; error = results_reader_create(&leftReader,leftExpr); if(error) { return error; } error = results_reader_create(&rightReader,rightExpr); if(error) { return error; } if( ! is_doc_offsets(leftExpr->type) ) { // the expressions must both be doc-offsets return ERR_PARAM; } if( ! is_doc_offsets(rightExpr->type) ) { // the expressions must both be doc-offsets return ERR_PARAM; } if( leftExpr->type != rightExpr->type ) { return ERR_PARAM; } error = results_writer_create(&writer,leftExpr->type); if(error) { return error; } leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); rightReadResult = results_reader_next(&rightReader, &rightDoc,&rightOffset); while( leftReadResult && rightReadResult ) { if( leftDoc < rightDoc ) { leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); } else if( leftDoc > rightDoc ) { rightReadResult = results_reader_next(&rightReader, &rightDoc,&rightOffset); } else { width = rightOffset - leftOffset; if(width < 0) { width = -width; } // minOffset is the minimum of the two if ( rightOffset < leftOffset ) minOffset = rightOffset; else minOffset = leftOffset; if(width <= positive_distance) { //append and advance leftmost(minimum) offset //which doc used doesnt matter since they are equal error = results_writer_append(&writer, leftDoc, minOffset); if(error) { return error; } } if ( rightOffset < leftOffset ) { //advance right rightReadResult = results_reader_next(&rightReader, &rightDoc, &rightOffset); } else /* width > distance */ { //advance left leftReadResult = results_reader_next(&leftReader, &leftDoc, &leftOffset); } } } error = results_writer_finish( &writer, result ); if(error) { return error; } results_writer_destroy(&writer); results_reader_destroy(&leftReader); results_reader_destroy(&rightReader); return ERR_NOERR; }
gpl-3.0
iodoom-gitorious/windowshasyous-dhewg-iodoom3
neo/d3xp/ai/AI_events.cpp
1
76884
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 Source Code 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. Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 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 Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" /*********************************************************************** AI Events ***********************************************************************/ const idEventDef AI_FindEnemy( "findEnemy", "d", 'e' ); const idEventDef AI_FindEnemyAI( "findEnemyAI", "d", 'e' ); const idEventDef AI_FindEnemyInCombatNodes( "findEnemyInCombatNodes", NULL, 'e' ); const idEventDef AI_ClosestReachableEnemyOfEntity( "closestReachableEnemyOfEntity", "E", 'e' ); const idEventDef AI_HeardSound( "heardSound", "d", 'e' ); const idEventDef AI_SetEnemy( "setEnemy", "E" ); const idEventDef AI_ClearEnemy( "clearEnemy" ); const idEventDef AI_MuzzleFlash( "muzzleFlash", "s" ); const idEventDef AI_CreateMissile( "createMissile", "s", 'e' ); const idEventDef AI_AttackMissile( "attackMissile", "s", 'e' ); const idEventDef AI_FireMissileAtTarget( "fireMissileAtTarget", "ss", 'e' ); const idEventDef AI_LaunchMissile( "launchMissile", "vv", 'e' ); #ifdef _D3XP const idEventDef AI_LaunchProjectile( "launchProjectile", "s" ); #endif const idEventDef AI_AttackMelee( "attackMelee", "s", 'd' ); const idEventDef AI_DirectDamage( "directDamage", "es" ); const idEventDef AI_RadiusDamageFromJoint( "radiusDamageFromJoint", "ss" ); const idEventDef AI_BeginAttack( "attackBegin", "s" ); const idEventDef AI_EndAttack( "attackEnd" ); const idEventDef AI_MeleeAttackToJoint( "meleeAttackToJoint", "ss", 'd' ); const idEventDef AI_RandomPath( "randomPath", NULL, 'e' ); const idEventDef AI_CanBecomeSolid( "canBecomeSolid", NULL, 'f' ); const idEventDef AI_BecomeSolid( "becomeSolid" ); const idEventDef AI_BecomeRagdoll( "becomeRagdoll", NULL, 'd' ); const idEventDef AI_StopRagdoll( "stopRagdoll" ); const idEventDef AI_SetHealth( "setHealth", "f" ); const idEventDef AI_GetHealth( "getHealth", NULL, 'f' ); const idEventDef AI_AllowDamage( "allowDamage" ); const idEventDef AI_IgnoreDamage( "ignoreDamage" ); const idEventDef AI_GetCurrentYaw( "getCurrentYaw", NULL, 'f' ); const idEventDef AI_TurnTo( "turnTo", "f" ); const idEventDef AI_TurnToPos( "turnToPos", "v" ); const idEventDef AI_TurnToEntity( "turnToEntity", "E" ); const idEventDef AI_MoveStatus( "moveStatus", NULL, 'd' ); const idEventDef AI_StopMove( "stopMove" ); const idEventDef AI_MoveToCover( "moveToCover" ); const idEventDef AI_MoveToEnemy( "moveToEnemy" ); const idEventDef AI_MoveToEnemyHeight( "moveToEnemyHeight" ); const idEventDef AI_MoveOutOfRange( "moveOutOfRange", "ef" ); const idEventDef AI_MoveToAttackPosition( "moveToAttackPosition", "es" ); const idEventDef AI_Wander( "wander" ); const idEventDef AI_MoveToEntity( "moveToEntity", "e" ); const idEventDef AI_MoveToPosition( "moveToPosition", "v" ); const idEventDef AI_SlideTo( "slideTo", "vf" ); const idEventDef AI_FacingIdeal( "facingIdeal", NULL, 'd' ); const idEventDef AI_FaceEnemy( "faceEnemy" ); const idEventDef AI_FaceEntity( "faceEntity", "E" ); const idEventDef AI_GetCombatNode( "getCombatNode", NULL, 'e' ); const idEventDef AI_EnemyInCombatCone( "enemyInCombatCone", "Ed", 'd' ); const idEventDef AI_WaitMove( "waitMove" ); const idEventDef AI_GetJumpVelocity( "getJumpVelocity", "vff", 'v' ); const idEventDef AI_EntityInAttackCone( "entityInAttackCone", "E", 'd' ); const idEventDef AI_CanSeeEntity( "canSee", "E", 'd' ); const idEventDef AI_SetTalkTarget( "setTalkTarget", "E" ); const idEventDef AI_GetTalkTarget( "getTalkTarget", NULL, 'e' ); const idEventDef AI_SetTalkState( "setTalkState", "d" ); const idEventDef AI_EnemyRange( "enemyRange", NULL, 'f' ); const idEventDef AI_EnemyRange2D( "enemyRange2D", NULL, 'f' ); const idEventDef AI_GetEnemy( "getEnemy", NULL, 'e' ); const idEventDef AI_GetEnemyPos( "getEnemyPos", NULL, 'v' ); const idEventDef AI_GetEnemyEyePos( "getEnemyEyePos", NULL, 'v' ); const idEventDef AI_PredictEnemyPos( "predictEnemyPos", "f", 'v' ); const idEventDef AI_CanHitEnemy( "canHitEnemy", NULL, 'd' ); const idEventDef AI_CanHitEnemyFromAnim( "canHitEnemyFromAnim", "s", 'd' ); const idEventDef AI_CanHitEnemyFromJoint( "canHitEnemyFromJoint", "s", 'd' ); const idEventDef AI_EnemyPositionValid( "enemyPositionValid", NULL, 'd' ); const idEventDef AI_ChargeAttack( "chargeAttack", "s" ); const idEventDef AI_TestChargeAttack( "testChargeAttack", NULL, 'f' ); const idEventDef AI_TestMoveToPosition( "testMoveToPosition", "v", 'd' ); const idEventDef AI_TestAnimMoveTowardEnemy( "testAnimMoveTowardEnemy", "s", 'd' ); const idEventDef AI_TestAnimMove( "testAnimMove", "s", 'd' ); const idEventDef AI_TestMeleeAttack( "testMeleeAttack", NULL, 'd' ); const idEventDef AI_TestAnimAttack( "testAnimAttack", "s", 'd' ); const idEventDef AI_Shrivel( "shrivel", "f" ); const idEventDef AI_Burn( "burn" ); const idEventDef AI_ClearBurn( "clearBurn" ); const idEventDef AI_PreBurn( "preBurn" ); const idEventDef AI_SetSmokeVisibility( "setSmokeVisibility", "dd" ); const idEventDef AI_NumSmokeEmitters( "numSmokeEmitters", NULL, 'd' ); const idEventDef AI_WaitAction( "waitAction", "s" ); const idEventDef AI_StopThinking( "stopThinking" ); const idEventDef AI_GetTurnDelta( "getTurnDelta", NULL, 'f' ); const idEventDef AI_GetMoveType( "getMoveType", NULL, 'd' ); const idEventDef AI_SetMoveType( "setMoveType", "d" ); const idEventDef AI_SaveMove( "saveMove" ); const idEventDef AI_RestoreMove( "restoreMove" ); const idEventDef AI_AllowMovement( "allowMovement", "f" ); const idEventDef AI_JumpFrame( "<jumpframe>" ); const idEventDef AI_EnableClip( "enableClip" ); const idEventDef AI_DisableClip( "disableClip" ); const idEventDef AI_EnableGravity( "enableGravity" ); const idEventDef AI_DisableGravity( "disableGravity" ); const idEventDef AI_EnableAFPush( "enableAFPush" ); const idEventDef AI_DisableAFPush( "disableAFPush" ); const idEventDef AI_SetFlySpeed( "setFlySpeed", "f" ); const idEventDef AI_SetFlyOffset( "setFlyOffset", "d" ); const idEventDef AI_ClearFlyOffset( "clearFlyOffset" ); const idEventDef AI_GetClosestHiddenTarget( "getClosestHiddenTarget", "s", 'e' ); const idEventDef AI_GetRandomTarget( "getRandomTarget", "s", 'e' ); const idEventDef AI_TravelDistanceToPoint( "travelDistanceToPoint", "v", 'f' ); const idEventDef AI_TravelDistanceToEntity( "travelDistanceToEntity", "e", 'f' ); const idEventDef AI_TravelDistanceBetweenPoints( "travelDistanceBetweenPoints", "vv", 'f' ); const idEventDef AI_TravelDistanceBetweenEntities( "travelDistanceBetweenEntities", "ee", 'f' ); const idEventDef AI_LookAtEntity( "lookAt", "Ef" ); const idEventDef AI_LookAtEnemy( "lookAtEnemy", "f" ); const idEventDef AI_SetJointMod( "setBoneMod", "d" ); const idEventDef AI_ThrowMoveable( "throwMoveable" ); const idEventDef AI_ThrowAF( "throwAF" ); const idEventDef AI_RealKill( "<kill>" ); const idEventDef AI_Kill( "kill" ); const idEventDef AI_WakeOnFlashlight( "wakeOnFlashlight", "d" ); const idEventDef AI_LocateEnemy( "locateEnemy" ); const idEventDef AI_KickObstacles( "kickObstacles", "Ef" ); const idEventDef AI_GetObstacle( "getObstacle", NULL, 'e' ); const idEventDef AI_PushPointIntoAAS( "pushPointIntoAAS", "v", 'v' ); const idEventDef AI_GetTurnRate( "getTurnRate", NULL, 'f' ); const idEventDef AI_SetTurnRate( "setTurnRate", "f" ); const idEventDef AI_AnimTurn( "animTurn", "f" ); const idEventDef AI_AllowHiddenMovement( "allowHiddenMovement", "d" ); const idEventDef AI_TriggerParticles( "triggerParticles", "s" ); const idEventDef AI_FindActorsInBounds( "findActorsInBounds", "vv", 'e' ); const idEventDef AI_CanReachPosition( "canReachPosition", "v", 'd' ); const idEventDef AI_CanReachEntity( "canReachEntity", "E", 'd' ); const idEventDef AI_CanReachEnemy( "canReachEnemy", NULL, 'd' ); const idEventDef AI_GetReachableEntityPosition( "getReachableEntityPosition", "e", 'v' ); #ifdef _D3XP const idEventDef AI_MoveToPositionDirect( "moveToPositionDirect", "v" ); const idEventDef AI_AvoidObstacles( "avoidObstacles", "d" ); const idEventDef AI_TriggerFX( "triggerFX", "ss" ); const idEventDef AI_StartEmitter( "startEmitter", "sss", 'e' ); const idEventDef AI_GetEmitter( "getEmitter", "s", 'e' ); const idEventDef AI_StopEmitter( "stopEmitter", "s" ); #endif CLASS_DECLARATION( idActor, idAI ) EVENT( EV_Activate, idAI::Event_Activate ) EVENT( EV_Touch, idAI::Event_Touch ) EVENT( AI_FindEnemy, idAI::Event_FindEnemy ) EVENT( AI_FindEnemyAI, idAI::Event_FindEnemyAI ) EVENT( AI_FindEnemyInCombatNodes, idAI::Event_FindEnemyInCombatNodes ) EVENT( AI_ClosestReachableEnemyOfEntity, idAI::Event_ClosestReachableEnemyOfEntity ) EVENT( AI_HeardSound, idAI::Event_HeardSound ) EVENT( AI_SetEnemy, idAI::Event_SetEnemy ) EVENT( AI_ClearEnemy, idAI::Event_ClearEnemy ) EVENT( AI_MuzzleFlash, idAI::Event_MuzzleFlash ) EVENT( AI_CreateMissile, idAI::Event_CreateMissile ) EVENT( AI_AttackMissile, idAI::Event_AttackMissile ) EVENT( AI_FireMissileAtTarget, idAI::Event_FireMissileAtTarget ) EVENT( AI_LaunchMissile, idAI::Event_LaunchMissile ) #ifdef _D3XP EVENT( AI_LaunchProjectile, idAI::Event_LaunchProjectile ) #endif EVENT( AI_AttackMelee, idAI::Event_AttackMelee ) EVENT( AI_DirectDamage, idAI::Event_DirectDamage ) EVENT( AI_RadiusDamageFromJoint, idAI::Event_RadiusDamageFromJoint ) EVENT( AI_BeginAttack, idAI::Event_BeginAttack ) EVENT( AI_EndAttack, idAI::Event_EndAttack ) EVENT( AI_MeleeAttackToJoint, idAI::Event_MeleeAttackToJoint ) EVENT( AI_RandomPath, idAI::Event_RandomPath ) EVENT( AI_CanBecomeSolid, idAI::Event_CanBecomeSolid ) EVENT( AI_BecomeSolid, idAI::Event_BecomeSolid ) EVENT( EV_BecomeNonSolid, idAI::Event_BecomeNonSolid ) EVENT( AI_BecomeRagdoll, idAI::Event_BecomeRagdoll ) EVENT( AI_StopRagdoll, idAI::Event_StopRagdoll ) EVENT( AI_SetHealth, idAI::Event_SetHealth ) EVENT( AI_GetHealth, idAI::Event_GetHealth ) EVENT( AI_AllowDamage, idAI::Event_AllowDamage ) EVENT( AI_IgnoreDamage, idAI::Event_IgnoreDamage ) EVENT( AI_GetCurrentYaw, idAI::Event_GetCurrentYaw ) EVENT( AI_TurnTo, idAI::Event_TurnTo ) EVENT( AI_TurnToPos, idAI::Event_TurnToPos ) EVENT( AI_TurnToEntity, idAI::Event_TurnToEntity ) EVENT( AI_MoveStatus, idAI::Event_MoveStatus ) EVENT( AI_StopMove, idAI::Event_StopMove ) EVENT( AI_MoveToCover, idAI::Event_MoveToCover ) EVENT( AI_MoveToEnemy, idAI::Event_MoveToEnemy ) EVENT( AI_MoveToEnemyHeight, idAI::Event_MoveToEnemyHeight ) EVENT( AI_MoveOutOfRange, idAI::Event_MoveOutOfRange ) EVENT( AI_MoveToAttackPosition, idAI::Event_MoveToAttackPosition ) EVENT( AI_Wander, idAI::Event_Wander ) EVENT( AI_MoveToEntity, idAI::Event_MoveToEntity ) EVENT( AI_MoveToPosition, idAI::Event_MoveToPosition ) EVENT( AI_SlideTo, idAI::Event_SlideTo ) EVENT( AI_FacingIdeal, idAI::Event_FacingIdeal ) EVENT( AI_FaceEnemy, idAI::Event_FaceEnemy ) EVENT( AI_FaceEntity, idAI::Event_FaceEntity ) EVENT( AI_WaitAction, idAI::Event_WaitAction ) EVENT( AI_GetCombatNode, idAI::Event_GetCombatNode ) EVENT( AI_EnemyInCombatCone, idAI::Event_EnemyInCombatCone ) EVENT( AI_WaitMove, idAI::Event_WaitMove ) EVENT( AI_GetJumpVelocity, idAI::Event_GetJumpVelocity ) EVENT( AI_EntityInAttackCone, idAI::Event_EntityInAttackCone ) EVENT( AI_CanSeeEntity, idAI::Event_CanSeeEntity ) EVENT( AI_SetTalkTarget, idAI::Event_SetTalkTarget ) EVENT( AI_GetTalkTarget, idAI::Event_GetTalkTarget ) EVENT( AI_SetTalkState, idAI::Event_SetTalkState ) EVENT( AI_EnemyRange, idAI::Event_EnemyRange ) EVENT( AI_EnemyRange2D, idAI::Event_EnemyRange2D ) EVENT( AI_GetEnemy, idAI::Event_GetEnemy ) EVENT( AI_GetEnemyPos, idAI::Event_GetEnemyPos ) EVENT( AI_GetEnemyEyePos, idAI::Event_GetEnemyEyePos ) EVENT( AI_PredictEnemyPos, idAI::Event_PredictEnemyPos ) EVENT( AI_CanHitEnemy, idAI::Event_CanHitEnemy ) EVENT( AI_CanHitEnemyFromAnim, idAI::Event_CanHitEnemyFromAnim ) EVENT( AI_CanHitEnemyFromJoint, idAI::Event_CanHitEnemyFromJoint ) EVENT( AI_EnemyPositionValid, idAI::Event_EnemyPositionValid ) EVENT( AI_ChargeAttack, idAI::Event_ChargeAttack ) EVENT( AI_TestChargeAttack, idAI::Event_TestChargeAttack ) EVENT( AI_TestAnimMoveTowardEnemy, idAI::Event_TestAnimMoveTowardEnemy ) EVENT( AI_TestAnimMove, idAI::Event_TestAnimMove ) EVENT( AI_TestMoveToPosition, idAI::Event_TestMoveToPosition ) EVENT( AI_TestMeleeAttack, idAI::Event_TestMeleeAttack ) EVENT( AI_TestAnimAttack, idAI::Event_TestAnimAttack ) EVENT( AI_Shrivel, idAI::Event_Shrivel ) EVENT( AI_Burn, idAI::Event_Burn ) EVENT( AI_PreBurn, idAI::Event_PreBurn ) EVENT( AI_SetSmokeVisibility, idAI::Event_SetSmokeVisibility ) EVENT( AI_NumSmokeEmitters, idAI::Event_NumSmokeEmitters ) EVENT( AI_ClearBurn, idAI::Event_ClearBurn ) EVENT( AI_StopThinking, idAI::Event_StopThinking ) EVENT( AI_GetTurnDelta, idAI::Event_GetTurnDelta ) EVENT( AI_GetMoveType, idAI::Event_GetMoveType ) EVENT( AI_SetMoveType, idAI::Event_SetMoveType ) EVENT( AI_SaveMove, idAI::Event_SaveMove ) EVENT( AI_RestoreMove, idAI::Event_RestoreMove ) EVENT( AI_AllowMovement, idAI::Event_AllowMovement ) EVENT( AI_JumpFrame, idAI::Event_JumpFrame ) EVENT( AI_EnableClip, idAI::Event_EnableClip ) EVENT( AI_DisableClip, idAI::Event_DisableClip ) EVENT( AI_EnableGravity, idAI::Event_EnableGravity ) EVENT( AI_DisableGravity, idAI::Event_DisableGravity ) EVENT( AI_EnableAFPush, idAI::Event_EnableAFPush ) EVENT( AI_DisableAFPush, idAI::Event_DisableAFPush ) EVENT( AI_SetFlySpeed, idAI::Event_SetFlySpeed ) EVENT( AI_SetFlyOffset, idAI::Event_SetFlyOffset ) EVENT( AI_ClearFlyOffset, idAI::Event_ClearFlyOffset ) EVENT( AI_GetClosestHiddenTarget, idAI::Event_GetClosestHiddenTarget ) EVENT( AI_GetRandomTarget, idAI::Event_GetRandomTarget ) EVENT( AI_TravelDistanceToPoint, idAI::Event_TravelDistanceToPoint ) EVENT( AI_TravelDistanceToEntity, idAI::Event_TravelDistanceToEntity ) EVENT( AI_TravelDistanceBetweenPoints, idAI::Event_TravelDistanceBetweenPoints ) EVENT( AI_TravelDistanceBetweenEntities, idAI::Event_TravelDistanceBetweenEntities ) EVENT( AI_LookAtEntity, idAI::Event_LookAtEntity ) EVENT( AI_LookAtEnemy, idAI::Event_LookAtEnemy ) EVENT( AI_SetJointMod, idAI::Event_SetJointMod ) EVENT( AI_ThrowMoveable, idAI::Event_ThrowMoveable ) EVENT( AI_ThrowAF, idAI::Event_ThrowAF ) EVENT( EV_GetAngles, idAI::Event_GetAngles ) EVENT( EV_SetAngles, idAI::Event_SetAngles ) EVENT( AI_RealKill, idAI::Event_RealKill ) EVENT( AI_Kill, idAI::Event_Kill ) EVENT( AI_WakeOnFlashlight, idAI::Event_WakeOnFlashlight ) EVENT( AI_LocateEnemy, idAI::Event_LocateEnemy ) EVENT( AI_KickObstacles, idAI::Event_KickObstacles ) EVENT( AI_GetObstacle, idAI::Event_GetObstacle ) EVENT( AI_PushPointIntoAAS, idAI::Event_PushPointIntoAAS ) EVENT( AI_GetTurnRate, idAI::Event_GetTurnRate ) EVENT( AI_SetTurnRate, idAI::Event_SetTurnRate ) EVENT( AI_AnimTurn, idAI::Event_AnimTurn ) EVENT( AI_AllowHiddenMovement, idAI::Event_AllowHiddenMovement ) EVENT( AI_TriggerParticles, idAI::Event_TriggerParticles ) EVENT( AI_FindActorsInBounds, idAI::Event_FindActorsInBounds ) EVENT( AI_CanReachPosition, idAI::Event_CanReachPosition ) EVENT( AI_CanReachEntity, idAI::Event_CanReachEntity ) EVENT( AI_CanReachEnemy, idAI::Event_CanReachEnemy ) EVENT( AI_GetReachableEntityPosition, idAI::Event_GetReachableEntityPosition ) #ifdef _D3XP EVENT( AI_MoveToPositionDirect, idAI::Event_MoveToPositionDirect ) EVENT( AI_AvoidObstacles, idAI::Event_AvoidObstacles ) EVENT( AI_TriggerFX, idAI::Event_TriggerFX ) EVENT( AI_StartEmitter, idAI::Event_StartEmitter ) EVENT( AI_GetEmitter, idAI::Event_GetEmitter ) EVENT( AI_StopEmitter, idAI::Event_StopEmitter ) #endif END_CLASS /* ===================== idAI::Event_Activate ===================== */ void idAI::Event_Activate( idEntity *activator ) { Activate( activator ); } /* ===================== idAI::Event_Touch ===================== */ void idAI::Event_Touch( idEntity *other, trace_t *trace ) { if ( !enemy.GetEntity() && !other->fl.notarget && ( ReactionTo( other ) & ATTACK_ON_ACTIVATE ) ) { Activate( other ); } AI_PUSHED = true; } /* ===================== idAI::Event_FindEnemy ===================== */ void idAI::Event_FindEnemy( int useFOV ) { int i; idEntity *ent; idActor *actor; if ( gameLocal.InPlayerPVS( this ) ) { for ( i = 0; i < gameLocal.numClients ; i++ ) { ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idActor::Type ) ) { continue; } actor = static_cast<idActor *>( ent ); if ( ( actor->health <= 0 ) || !( ReactionTo( actor ) & ATTACK_ON_SIGHT ) ) { continue; } if ( CanSee( actor, useFOV != 0 ) ) { idThread::ReturnEntity( actor ); return; } } } idThread::ReturnEntity( NULL ); } /* ===================== idAI::Event_FindEnemyAI ===================== */ void idAI::Event_FindEnemyAI( int useFOV ) { idEntity *ent; idActor *actor; idActor *bestEnemy; float bestDist; float dist; idVec3 delta; pvsHandle_t pvs; pvs = gameLocal.pvs.SetupCurrentPVS( GetPVSAreas(), GetNumPVSAreas() ); bestDist = idMath::INFINITY; bestEnemy = NULL; for ( ent = gameLocal.activeEntities.Next(); ent != NULL; ent = ent->activeNode.Next() ) { if ( ent->fl.hidden || ent->fl.isDormant || !ent->IsType( idActor::Type ) ) { continue; } actor = static_cast<idActor *>( ent ); if ( ( actor->health <= 0 ) || !( ReactionTo( actor ) & ATTACK_ON_SIGHT ) ) { continue; } if ( !gameLocal.pvs.InCurrentPVS( pvs, actor->GetPVSAreas(), actor->GetNumPVSAreas() ) ) { continue; } delta = physicsObj.GetOrigin() - actor->GetPhysics()->GetOrigin(); dist = delta.LengthSqr(); if ( ( dist < bestDist ) && CanSee( actor, useFOV != 0 ) ) { bestDist = dist; bestEnemy = actor; } } gameLocal.pvs.FreeCurrentPVS( pvs ); idThread::ReturnEntity( bestEnemy ); } /* ===================== idAI::Event_FindEnemyInCombatNodes ===================== */ void idAI::Event_FindEnemyInCombatNodes( void ) { int i, j; idCombatNode *node; idEntity *ent; idEntity *targetEnt; idActor *actor; if ( !gameLocal.InPlayerPVS( this ) ) { // don't locate the player when we're not in his PVS idThread::ReturnEntity( NULL ); return; } for ( i = 0; i < gameLocal.numClients ; i++ ) { ent = gameLocal.entities[ i ]; if ( !ent || !ent->IsType( idActor::Type ) ) { continue; } actor = static_cast<idActor *>( ent ); if ( ( actor->health <= 0 ) || !( ReactionTo( actor ) & ATTACK_ON_SIGHT ) ) { continue; } for( j = 0; j < targets.Num(); j++ ) { targetEnt = targets[ j ].GetEntity(); if ( !targetEnt || !targetEnt->IsType( idCombatNode::Type ) ) { continue; } node = static_cast<idCombatNode *>( targetEnt ); if ( !node->IsDisabled() && node->EntityInView( actor, actor->GetPhysics()->GetOrigin() ) ) { idThread::ReturnEntity( actor ); return; } } } idThread::ReturnEntity( NULL ); } /* ===================== idAI::Event_ClosestReachableEnemyOfEntity ===================== */ void idAI::Event_ClosestReachableEnemyOfEntity( idEntity *team_mate ) { idActor *actor; idActor *ent; idActor *bestEnt; float bestDistSquared; float distSquared; idVec3 delta; int areaNum; int enemyAreaNum; aasPath_t path; if ( !team_mate->IsType( idActor::Type ) ) { gameLocal.Error( "Entity '%s' is not an AI character or player", team_mate->GetName() ); } actor = static_cast<idActor *>( team_mate ); const idVec3 &origin = physicsObj.GetOrigin(); areaNum = PointReachableAreaNum( origin ); bestDistSquared = idMath::INFINITY; bestEnt = NULL; for( ent = actor->enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if ( ent->fl.hidden ) { continue; } delta = ent->GetPhysics()->GetOrigin() - origin; distSquared = delta.LengthSqr(); if ( distSquared < bestDistSquared ) { const idVec3 &enemyPos = ent->GetPhysics()->GetOrigin(); enemyAreaNum = PointReachableAreaNum( enemyPos ); if ( ( areaNum != 0 ) && PathToGoal( path, areaNum, origin, enemyAreaNum, enemyPos ) ) { bestEnt = ent; bestDistSquared = distSquared; } } } idThread::ReturnEntity( bestEnt ); } /* ===================== idAI::Event_HeardSound ===================== */ void idAI::Event_HeardSound( int ignore_team ) { // check if we heard any sounds in the last frame idActor *actor = gameLocal.GetAlertEntity(); if ( actor && ( !ignore_team || ( ReactionTo( actor ) & ATTACK_ON_SIGHT ) ) && gameLocal.InPlayerPVS( this ) ) { idVec3 pos = actor->GetPhysics()->GetOrigin(); idVec3 org = physicsObj.GetOrigin(); float dist = ( pos - org ).LengthSqr(); if ( dist < Square( AI_HEARING_RANGE ) ) { idThread::ReturnEntity( actor ); return; } } idThread::ReturnEntity( NULL ); } /* ===================== idAI::Event_SetEnemy ===================== */ void idAI::Event_SetEnemy( idEntity *ent ) { if ( !ent ) { ClearEnemy(); } else if ( !ent->IsType( idActor::Type ) ) { gameLocal.Error( "'%s' is not an idActor (player or ai controlled character)", ent->name.c_str() ); } else { SetEnemy( static_cast<idActor *>( ent ) ); } } /* ===================== idAI::Event_ClearEnemy ===================== */ void idAI::Event_ClearEnemy( void ) { ClearEnemy(); } /* ===================== idAI::Event_MuzzleFlash ===================== */ void idAI::Event_MuzzleFlash( const char *jointname ) { idVec3 muzzle; idMat3 axis; GetMuzzle( jointname, muzzle, axis ); TriggerWeaponEffects( muzzle ); } /* ===================== idAI::Event_CreateMissile ===================== */ void idAI::Event_CreateMissile( const char *jointname ) { idVec3 muzzle; idMat3 axis; if ( !projectileDef ) { gameLocal.Warning( "%s (%s) doesn't have a projectile specified", name.c_str(), GetEntityDefName() ); return idThread::ReturnEntity( NULL ); } GetMuzzle( jointname, muzzle, axis ); CreateProjectile( muzzle, viewAxis[ 0 ] * physicsObj.GetGravityAxis() ); if ( projectile.GetEntity() ) { if ( !jointname || !jointname[ 0 ] ) { projectile.GetEntity()->Bind( this, true ); } else { projectile.GetEntity()->BindToJoint( this, jointname, true ); } } idThread::ReturnEntity( projectile.GetEntity() ); } /* ===================== idAI::Event_AttackMissile ===================== */ void idAI::Event_AttackMissile( const char *jointname ) { idProjectile *proj; proj = LaunchProjectile( jointname, enemy.GetEntity(), true ); idThread::ReturnEntity( proj ); } /* ===================== idAI::Event_FireMissileAtTarget ===================== */ void idAI::Event_FireMissileAtTarget( const char *jointname, const char *targetname ) { idEntity *aent; idProjectile *proj; aent = gameLocal.FindEntity( targetname ); if ( !aent ) { gameLocal.Warning( "Entity '%s' not found for 'fireMissileAtTarget'", targetname ); } proj = LaunchProjectile( jointname, aent, false ); idThread::ReturnEntity( proj ); } /* ===================== idAI::Event_LaunchMissile ===================== */ void idAI::Event_LaunchMissile( const idVec3 &org, const idAngles &ang ) { idVec3 start; trace_t tr; idBounds projBounds; const idClipModel *projClip; idMat3 axis; float distance; if ( !projectileDef ) { gameLocal.Warning( "%s (%s) doesn't have a projectile specified", name.c_str(), GetEntityDefName() ); idThread::ReturnEntity( NULL ); return; } axis = ang.ToMat3(); if ( !projectile.GetEntity() ) { CreateProjectile( org, axis[ 0 ] ); } // make sure the projectile starts inside the monster bounding box const idBounds &ownerBounds = physicsObj.GetAbsBounds(); projClip = projectile.GetEntity()->GetPhysics()->GetClipModel(); projBounds = projClip->GetBounds().Rotate( projClip->GetAxis() ); // check if the owner bounds is bigger than the projectile bounds if ( ( ( ownerBounds[1][0] - ownerBounds[0][0] ) > ( projBounds[1][0] - projBounds[0][0] ) ) && ( ( ownerBounds[1][1] - ownerBounds[0][1] ) > ( projBounds[1][1] - projBounds[0][1] ) ) && ( ( ownerBounds[1][2] - ownerBounds[0][2] ) > ( projBounds[1][2] - projBounds[0][2] ) ) ) { if ( (ownerBounds - projBounds).RayIntersection( org, viewAxis[ 0 ], distance ) ) { start = org + distance * viewAxis[ 0 ]; } else { start = ownerBounds.GetCenter(); } } else { // projectile bounds bigger than the owner bounds, so just start it from the center start = ownerBounds.GetCenter(); } gameLocal.clip.Translation( tr, start, org, projClip, projClip->GetAxis(), MASK_SHOT_RENDERMODEL, this ); // launch the projectile idThread::ReturnEntity( projectile.GetEntity() ); projectile.GetEntity()->Launch( tr.endpos, axis[ 0 ], vec3_origin ); projectile = NULL; TriggerWeaponEffects( tr.endpos ); lastAttackTime = gameLocal.time; } #ifdef _D3XP /* ===================== idAI::Event_LaunchProjectile ===================== */ void idAI::Event_LaunchProjectile( const char *entityDefName ) { idVec3 muzzle, start, dir; const idDict *projDef; idMat3 axis; const idClipModel *projClip; idBounds projBounds; trace_t tr; idEntity *ent; const char *clsname; float distance; idProjectile *proj = NULL; projDef = gameLocal.FindEntityDefDict( entityDefName ); gameLocal.SpawnEntityDef( *projDef, &ent, false ); if ( !ent ) { clsname = projectileDef->GetString( "classname" ); gameLocal.Error( "Could not spawn entityDef '%s'", clsname ); } if ( !ent->IsType( idProjectile::Type ) ) { clsname = ent->GetClassname(); gameLocal.Error( "'%s' is not an idProjectile", clsname ); } proj = ( idProjectile * )ent; GetMuzzle( "pistol", muzzle, axis ); proj->Create( this, muzzle, axis[0] ); // make sure the projectile starts inside the monster bounding box const idBounds &ownerBounds = physicsObj.GetAbsBounds(); projClip = proj->GetPhysics()->GetClipModel(); projBounds = projClip->GetBounds().Rotate( projClip->GetAxis() ); if ( (ownerBounds - projBounds).RayIntersection( muzzle, viewAxis[ 0 ], distance ) ) { start = muzzle + distance * viewAxis[ 0 ]; } else { start = ownerBounds.GetCenter(); } gameLocal.clip.Translation( tr, start, muzzle, projClip, projClip->GetAxis(), MASK_SHOT_RENDERMODEL, this ); muzzle = tr.endpos; GetAimDir( muzzle, enemy.GetEntity(), this, dir ); proj->Launch( muzzle, dir, vec3_origin ); TriggerWeaponEffects( muzzle ); } #endif /* ===================== idAI::Event_AttackMelee ===================== */ void idAI::Event_AttackMelee( const char *meleeDefName ) { bool hit; hit = AttackMelee( meleeDefName ); idThread::ReturnInt( hit ); } /* ===================== idAI::Event_DirectDamage ===================== */ void idAI::Event_DirectDamage( idEntity *damageTarget, const char *damageDefName ) { DirectDamage( damageDefName, damageTarget ); } /* ===================== idAI::Event_RadiusDamageFromJoint ===================== */ void idAI::Event_RadiusDamageFromJoint( const char *jointname, const char *damageDefName ) { jointHandle_t joint; idVec3 org; idMat3 axis; if ( !jointname || !jointname[ 0 ] ) { org = physicsObj.GetOrigin(); } else { joint = animator.GetJointHandle( jointname ); if ( joint == INVALID_JOINT ) { gameLocal.Error( "Unknown joint '%s' on %s", jointname, GetEntityDefName() ); } GetJointWorldTransform( joint, gameLocal.time, org, axis ); } gameLocal.RadiusDamage( org, this, this, this, this, damageDefName ); } /* ===================== idAI::Event_RandomPath ===================== */ void idAI::Event_RandomPath( void ) { idPathCorner *path; path = idPathCorner::RandomPath( this, NULL ); idThread::ReturnEntity( path ); } /* ===================== idAI::Event_BeginAttack ===================== */ void idAI::Event_BeginAttack( const char *name ) { BeginAttack( name ); } /* ===================== idAI::Event_EndAttack ===================== */ void idAI::Event_EndAttack( void ) { EndAttack(); } /* ===================== idAI::Event_MeleeAttackToJoint ===================== */ void idAI::Event_MeleeAttackToJoint( const char *jointname, const char *meleeDefName ) { jointHandle_t joint; idVec3 start; idVec3 end; idMat3 axis; trace_t trace; idEntity *hitEnt; joint = animator.GetJointHandle( jointname ); if ( joint == INVALID_JOINT ) { gameLocal.Error( "Unknown joint '%s' on %s", jointname, GetEntityDefName() ); } animator.GetJointTransform( joint, gameLocal.time, end, axis ); end = physicsObj.GetOrigin() + ( end + modelOffset ) * viewAxis * physicsObj.GetGravityAxis(); start = GetEyePosition(); if ( ai_debugMove.GetBool() ) { gameRenderWorld->DebugLine( colorYellow, start, end, gameLocal.msec ); } gameLocal.clip.TranslationEntities( trace, start, end, NULL, mat3_identity, MASK_SHOT_BOUNDINGBOX, this ); if ( trace.fraction < 1.0f ) { hitEnt = gameLocal.GetTraceEntity( trace ); if ( hitEnt && hitEnt->IsType( idActor::Type ) ) { DirectDamage( meleeDefName, hitEnt ); idThread::ReturnInt( true ); return; } } idThread::ReturnInt( false ); } /* ===================== idAI::Event_CanBecomeSolid ===================== */ void idAI::Event_CanBecomeSolid( void ) { int i; int num; #ifdef _D3XP bool returnValue = true; #endif idEntity * hit; idClipModel *cm; idClipModel *clipModels[ MAX_GENTITIES ]; num = gameLocal.clip.ClipModelsTouchingBounds( physicsObj.GetAbsBounds(), MASK_MONSTERSOLID, clipModels, MAX_GENTITIES ); for ( i = 0; i < num; i++ ) { cm = clipModels[ i ]; // don't check render entities if ( cm->IsRenderModel() ) { continue; } hit = cm->GetEntity(); if ( ( hit == this ) || !hit->fl.takedamage ) { continue; } #ifdef _D3XP if ( (spawnClearMoveables && hit->IsType( idMoveable::Type )) || (hit->IsType( idBarrel::Type ) || hit->IsType( idExplodingBarrel::Type) ) ) { idVec3 push; push = hit->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin(); push.z = 30.f; push.NormalizeFast(); if ( (idMath::Fabs(push.x) < 0.15f) && (idMath::Fabs(push.y) < 0.15f) ) { push.x = 10.f; push.y = 10.f; push.z = 15.f; push.NormalizeFast(); } push *= 300.f; hit->GetPhysics()->SetLinearVelocity( push ); } #endif if ( physicsObj.ClipContents( cm ) ) { #ifdef _D3XP returnValue = false; #else idThread::ReturnFloat( false ); return; #endif } } #ifdef _D3XP idThread::ReturnFloat( returnValue ); #else idThread::ReturnFloat( true ); #endif } /* ===================== idAI::Event_BecomeSolid ===================== */ void idAI::Event_BecomeSolid( void ) { physicsObj.EnableClip(); if ( spawnArgs.GetBool( "big_monster" ) ) { physicsObj.SetContents( 0 ); } else if ( use_combat_bbox ) { physicsObj.SetContents( CONTENTS_BODY|CONTENTS_SOLID ); } else { physicsObj.SetContents( CONTENTS_BODY ); } physicsObj.GetClipModel()->Link( gameLocal.clip ); fl.takedamage = !spawnArgs.GetBool( "noDamage" ); } /* ===================== idAI::Event_BecomeNonSolid ===================== */ void idAI::Event_BecomeNonSolid( void ) { fl.takedamage = false; physicsObj.SetContents( 0 ); physicsObj.GetClipModel()->Unlink(); } /* ===================== idAI::Event_BecomeRagdoll ===================== */ void idAI::Event_BecomeRagdoll( void ) { bool result; result = StartRagdoll(); idThread::ReturnInt( result ); } /* ===================== idAI::Event_StopRagdoll ===================== */ void idAI::Event_StopRagdoll( void ) { StopRagdoll(); // set back the monster physics SetPhysics( &physicsObj ); } /* ===================== idAI::Event_SetHealth ===================== */ void idAI::Event_SetHealth( float newHealth ) { health = newHealth; fl.takedamage = true; if ( health > 0 ) { AI_DEAD = false; } else { AI_DEAD = true; } } /* ===================== idAI::Event_GetHealth ===================== */ void idAI::Event_GetHealth( void ) { idThread::ReturnFloat( health ); } /* ===================== idAI::Event_AllowDamage ===================== */ void idAI::Event_AllowDamage( void ) { fl.takedamage = true; } /* ===================== idAI::Event_IgnoreDamage ===================== */ void idAI::Event_IgnoreDamage( void ) { fl.takedamage = false; } /* ===================== idAI::Event_GetCurrentYaw ===================== */ void idAI::Event_GetCurrentYaw( void ) { idThread::ReturnFloat( current_yaw ); } /* ===================== idAI::Event_TurnTo ===================== */ void idAI::Event_TurnTo( float angle ) { TurnToward( angle ); } /* ===================== idAI::Event_TurnToPos ===================== */ void idAI::Event_TurnToPos( const idVec3 &pos ) { TurnToward( pos ); } /* ===================== idAI::Event_TurnToEntity ===================== */ void idAI::Event_TurnToEntity( idEntity *ent ) { if ( ent ) { TurnToward( ent->GetPhysics()->GetOrigin() ); } } /* ===================== idAI::Event_MoveStatus ===================== */ void idAI::Event_MoveStatus( void ) { idThread::ReturnInt( move.moveStatus ); } /* ===================== idAI::Event_StopMove ===================== */ void idAI::Event_StopMove( void ) { StopMove( MOVE_STATUS_DONE ); } /* ===================== idAI::Event_MoveToCover ===================== */ void idAI::Event_MoveToCover( void ) { idActor *enemyEnt = enemy.GetEntity(); StopMove( MOVE_STATUS_DEST_NOT_FOUND ); if ( !enemyEnt || !MoveToCover( enemyEnt, lastVisibleEnemyPos ) ) { return; } } /* ===================== idAI::Event_MoveToEnemy ===================== */ void idAI::Event_MoveToEnemy( void ) { StopMove( MOVE_STATUS_DEST_NOT_FOUND ); if ( !enemy.GetEntity() || !MoveToEnemy() ) { return; } } /* ===================== idAI::Event_MoveToEnemyHeight ===================== */ void idAI::Event_MoveToEnemyHeight( void ) { StopMove( MOVE_STATUS_DEST_NOT_FOUND ); MoveToEnemyHeight(); } /* ===================== idAI::Event_MoveOutOfRange ===================== */ void idAI::Event_MoveOutOfRange( idEntity *entity, float range ) { StopMove( MOVE_STATUS_DEST_NOT_FOUND ); MoveOutOfRange( entity, range ); } /* ===================== idAI::Event_MoveToAttackPosition ===================== */ void idAI::Event_MoveToAttackPosition( idEntity *entity, const char *attack_anim ) { int anim; StopMove( MOVE_STATUS_DEST_NOT_FOUND ); anim = GetAnim( ANIMCHANNEL_LEGS, attack_anim ); if ( !anim ) { gameLocal.Error( "Unknown anim '%s'", attack_anim ); } MoveToAttackPosition( entity, anim ); } /* ===================== idAI::Event_MoveToEntity ===================== */ void idAI::Event_MoveToEntity( idEntity *ent ) { StopMove( MOVE_STATUS_DEST_NOT_FOUND ); if ( ent ) { MoveToEntity( ent ); } } /* ===================== idAI::Event_MoveToPosition ===================== */ void idAI::Event_MoveToPosition( const idVec3 &pos ) { StopMove( MOVE_STATUS_DONE ); MoveToPosition( pos ); } /* ===================== idAI::Event_SlideTo ===================== */ void idAI::Event_SlideTo( const idVec3 &pos, float time ) { SlideToPosition( pos, time ); } /* ===================== idAI::Event_Wander ===================== */ void idAI::Event_Wander( void ) { WanderAround(); } /* ===================== idAI::Event_FacingIdeal ===================== */ void idAI::Event_FacingIdeal( void ) { bool facing = FacingIdeal(); idThread::ReturnInt( facing ); } /* ===================== idAI::Event_FaceEnemy ===================== */ void idAI::Event_FaceEnemy( void ) { FaceEnemy(); } /* ===================== idAI::Event_FaceEntity ===================== */ void idAI::Event_FaceEntity( idEntity *ent ) { FaceEntity( ent ); } /* ===================== idAI::Event_WaitAction ===================== */ void idAI::Event_WaitAction( const char *waitForState ) { if ( idThread::BeginMultiFrameEvent( this, &AI_WaitAction ) ) { SetWaitState( waitForState ); } if ( !WaitState() ) { idThread::EndMultiFrameEvent( this, &AI_WaitAction ); } } /* ===================== idAI::Event_GetCombatNode ===================== */ void idAI::Event_GetCombatNode( void ) { int i; float dist; idEntity *targetEnt; idCombatNode *node; float bestDist; idCombatNode *bestNode; idActor *enemyEnt = enemy.GetEntity(); if ( !targets.Num() ) { // no combat nodes idThread::ReturnEntity( NULL ); return; } if ( !enemyEnt || !EnemyPositionValid() ) { // don't return a combat node if we don't have an enemy or // if we can see he's not in the last place we saw him #ifdef _D3XP if ( team == 0 ) { // find the closest attack node to the player bestNode = NULL; const idVec3 &myPos = physicsObj.GetOrigin(); const idVec3 &playerPos = gameLocal.GetLocalPlayer()->GetPhysics()->GetOrigin(); bestDist = ( myPos - playerPos ).LengthSqr(); for( i = 0; i < targets.Num(); i++ ) { targetEnt = targets[ i ].GetEntity(); if ( !targetEnt || !targetEnt->IsType( idCombatNode::Type ) ) { continue; } node = static_cast<idCombatNode *>( targetEnt ); if ( !node->IsDisabled() ) { idVec3 org = node->GetPhysics()->GetOrigin(); dist = ( playerPos - org ).LengthSqr(); if ( dist < bestDist ) { bestNode = node; bestDist = dist; } } } idThread::ReturnEntity( bestNode ); return; } #endif idThread::ReturnEntity( NULL ); return; } // find the closest attack node that can see our enemy and is closer than our enemy bestNode = NULL; const idVec3 &myPos = physicsObj.GetOrigin(); bestDist = ( myPos - lastVisibleEnemyPos ).LengthSqr(); for( i = 0; i < targets.Num(); i++ ) { targetEnt = targets[ i ].GetEntity(); if ( !targetEnt || !targetEnt->IsType( idCombatNode::Type ) ) { continue; } node = static_cast<idCombatNode *>( targetEnt ); if ( !node->IsDisabled() && node->EntityInView( enemyEnt, lastVisibleEnemyPos ) ) { idVec3 org = node->GetPhysics()->GetOrigin(); dist = ( myPos - org ).LengthSqr(); if ( dist < bestDist ) { bestNode = node; bestDist = dist; } } } idThread::ReturnEntity( bestNode ); } /* ===================== idAI::Event_EnemyInCombatCone ===================== */ void idAI::Event_EnemyInCombatCone( idEntity *ent, int use_current_enemy_location ) { idCombatNode *node; bool result; idActor *enemyEnt = enemy.GetEntity(); if ( !targets.Num() ) { // no combat nodes idThread::ReturnInt( false ); return; } if ( !enemyEnt ) { // have to have an enemy idThread::ReturnInt( false ); return; } if ( !ent || !ent->IsType( idCombatNode::Type ) ) { // not a combat node idThread::ReturnInt( false ); return; } #ifdef _D3XP //Allow the level designers define attack nodes that the enemy should never leave. //This is different that the turrent type combat nodes because they can play an animation if(ent->spawnArgs.GetBool("neverLeave", "0")) { idThread::ReturnInt( true ); return; } #endif node = static_cast<idCombatNode *>( ent ); if ( use_current_enemy_location ) { const idVec3 &pos = enemyEnt->GetPhysics()->GetOrigin(); result = node->EntityInView( enemyEnt, pos ); } else { result = node->EntityInView( enemyEnt, lastVisibleEnemyPos ); } idThread::ReturnInt( result ); } /* ===================== idAI::Event_WaitMove ===================== */ void idAI::Event_WaitMove( void ) { idThread::BeginMultiFrameEvent( this, &AI_WaitMove ); if ( MoveDone() ) { idThread::EndMultiFrameEvent( this, &AI_WaitMove ); } } /* ===================== idAI::Event_GetJumpVelocity ===================== */ void idAI::Event_GetJumpVelocity( const idVec3 &pos, float speed, float max_height ) { idVec3 start; idVec3 end; idVec3 dir; float dist; bool result; idEntity *enemyEnt = enemy.GetEntity(); if ( !enemyEnt ) { idThread::ReturnVector( vec3_zero ); return; } if ( speed <= 0.0f ) { gameLocal.Error( "Invalid speed. speed must be > 0." ); } start = physicsObj.GetOrigin(); end = pos; dir = end - start; dist = dir.Normalize(); if ( dist > 16.0f ) { dist -= 16.0f; end -= dir * 16.0f; } result = PredictTrajectory( start, end, speed, physicsObj.GetGravity(), physicsObj.GetClipModel(), MASK_MONSTERSOLID, max_height, this, enemyEnt, ai_debugMove.GetBool() ? 4000 : 0, dir ); if ( result ) { idThread::ReturnVector( dir * speed ); } else { idThread::ReturnVector( vec3_zero ); } } /* ===================== idAI::Event_EntityInAttackCone ===================== */ void idAI::Event_EntityInAttackCone( idEntity *ent ) { float attack_cone; idVec3 delta; float yaw; float relYaw; if ( !ent ) { idThread::ReturnInt( false ); return; } delta = ent->GetPhysics()->GetOrigin() - GetEyePosition(); // get our gravity normal const idVec3 &gravityDir = GetPhysics()->GetGravityNormal(); // infinite vertical vision, so project it onto our orientation plane delta -= gravityDir * ( gravityDir * delta ); delta.Normalize(); yaw = delta.ToYaw(); attack_cone = spawnArgs.GetFloat( "attack_cone", "70" ); relYaw = idMath::AngleNormalize180( ideal_yaw - yaw ); if ( idMath::Fabs( relYaw ) < ( attack_cone * 0.5f ) ) { idThread::ReturnInt( true ); } else { idThread::ReturnInt( false ); } } /* ===================== idAI::Event_CanSeeEntity ===================== */ void idAI::Event_CanSeeEntity( idEntity *ent ) { if ( !ent ) { idThread::ReturnInt( false ); return; } bool cansee = CanSee( ent, false ); idThread::ReturnInt( cansee ); } /* ===================== idAI::Event_SetTalkTarget ===================== */ void idAI::Event_SetTalkTarget( idEntity *target ) { if ( target && !target->IsType( idActor::Type ) ) { gameLocal.Error( "Cannot set talk target to '%s'. Not a character or player.", target->GetName() ); } talkTarget = static_cast<idActor *>( target ); if ( target ) { AI_TALK = true; } else { AI_TALK = false; } } /* ===================== idAI::Event_GetTalkTarget ===================== */ void idAI::Event_GetTalkTarget( void ) { idThread::ReturnEntity( talkTarget.GetEntity() ); } /* ================ idAI::Event_SetTalkState ================ */ void idAI::Event_SetTalkState( int state ) { if ( ( state < 0 ) || ( state >= NUM_TALK_STATES ) ) { gameLocal.Error( "Invalid talk state (%d)", state ); } talk_state = static_cast<talkState_t>( state ); } /* ===================== idAI::Event_EnemyRange ===================== */ void idAI::Event_EnemyRange( void ) { float dist; idActor *enemyEnt = enemy.GetEntity(); if ( enemyEnt ) { dist = ( enemyEnt->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin() ).Length(); } else { // Just some really high number dist = idMath::INFINITY; } idThread::ReturnFloat( dist ); } /* ===================== idAI::Event_EnemyRange2D ===================== */ void idAI::Event_EnemyRange2D( void ) { float dist; idActor *enemyEnt = enemy.GetEntity(); if ( enemyEnt ) { dist = ( enemyEnt->GetPhysics()->GetOrigin().ToVec2() - GetPhysics()->GetOrigin().ToVec2() ).Length(); } else { // Just some really high number dist = idMath::INFINITY; } idThread::ReturnFloat( dist ); } /* ===================== idAI::Event_GetEnemy ===================== */ void idAI::Event_GetEnemy( void ) { idThread::ReturnEntity( enemy.GetEntity() ); } /* ===================== idAI::Event_GetEnemyPos ===================== */ void idAI::Event_GetEnemyPos( void ) { idThread::ReturnVector( lastVisibleEnemyPos ); } /* ===================== idAI::Event_GetEnemyEyePos ===================== */ void idAI::Event_GetEnemyEyePos( void ) { idThread::ReturnVector( lastVisibleEnemyPos + lastVisibleEnemyEyeOffset ); } /* ===================== idAI::Event_PredictEnemyPos ===================== */ void idAI::Event_PredictEnemyPos( float time ) { predictedPath_t path; idActor *enemyEnt = enemy.GetEntity(); // if no enemy set if ( !enemyEnt ) { idThread::ReturnVector( physicsObj.GetOrigin() ); return; } // predict the enemy movement idAI::PredictPath( enemyEnt, aas, lastVisibleEnemyPos, enemyEnt->GetPhysics()->GetLinearVelocity(), SEC2MS( time ), SEC2MS( time ), ( move.moveType == MOVETYPE_FLY ) ? SE_BLOCKED : ( SE_BLOCKED | SE_ENTER_LEDGE_AREA ), path ); idThread::ReturnVector( path.endPos ); } /* ===================== idAI::Event_CanHitEnemy ===================== */ void idAI::Event_CanHitEnemy( void ) { trace_t tr; idEntity *hit; idActor *enemyEnt = enemy.GetEntity(); if ( !AI_ENEMY_VISIBLE || !enemyEnt ) { idThread::ReturnInt( false ); return; } // don't check twice per frame if ( gameLocal.time == lastHitCheckTime ) { idThread::ReturnInt( lastHitCheckResult ); return; } lastHitCheckTime = gameLocal.time; idVec3 toPos = enemyEnt->GetEyePosition(); idVec3 eye = GetEyePosition(); idVec3 dir; // expand the ray out as far as possible so we can detect anything behind the enemy dir = toPos - eye; dir.Normalize(); toPos = eye + dir * MAX_WORLD_SIZE; gameLocal.clip.TracePoint( tr, eye, toPos, MASK_SHOT_BOUNDINGBOX, this ); hit = gameLocal.GetTraceEntity( tr ); if ( tr.fraction >= 1.0f || ( hit == enemyEnt ) ) { lastHitCheckResult = true; } else if ( ( tr.fraction < 1.0f ) && ( hit->IsType( idAI::Type ) ) && ( static_cast<idAI *>( hit )->team != team ) ) { lastHitCheckResult = true; } else { lastHitCheckResult = false; } idThread::ReturnInt( lastHitCheckResult ); } /* ===================== idAI::Event_CanHitEnemyFromAnim ===================== */ void idAI::Event_CanHitEnemyFromAnim( const char *animname ) { int anim; idVec3 dir; idVec3 local_dir; idVec3 fromPos; idMat3 axis; idVec3 start; trace_t tr; float distance; idActor *enemyEnt = enemy.GetEntity(); if ( !AI_ENEMY_VISIBLE || !enemyEnt ) { idThread::ReturnInt( false ); return; } anim = GetAnim( ANIMCHANNEL_LEGS, animname ); if ( !anim ) { idThread::ReturnInt( false ); return; } // just do a ray test if close enough if ( enemyEnt->GetPhysics()->GetAbsBounds().IntersectsBounds( physicsObj.GetAbsBounds().Expand( 16.0f ) ) ) { Event_CanHitEnemy(); return; } // calculate the world transform of the launch position const idVec3 &org = physicsObj.GetOrigin(); dir = lastVisibleEnemyPos - org; physicsObj.GetGravityAxis().ProjectVector( dir, local_dir ); local_dir.z = 0.0f; local_dir.ToVec2().Normalize(); axis = local_dir.ToMat3(); fromPos = physicsObj.GetOrigin() + missileLaunchOffset[ anim ] * axis; if ( projectileClipModel == NULL ) { CreateProjectileClipModel(); } // check if the owner bounds is bigger than the projectile bounds const idBounds &ownerBounds = physicsObj.GetAbsBounds(); const idBounds &projBounds = projectileClipModel->GetBounds(); if ( ( ( ownerBounds[1][0] - ownerBounds[0][0] ) > ( projBounds[1][0] - projBounds[0][0] ) ) && ( ( ownerBounds[1][1] - ownerBounds[0][1] ) > ( projBounds[1][1] - projBounds[0][1] ) ) && ( ( ownerBounds[1][2] - ownerBounds[0][2] ) > ( projBounds[1][2] - projBounds[0][2] ) ) ) { if ( (ownerBounds - projBounds).RayIntersection( org, viewAxis[ 0 ], distance ) ) { start = org + distance * viewAxis[ 0 ]; } else { start = ownerBounds.GetCenter(); } } else { // projectile bounds bigger than the owner bounds, so just start it from the center start = ownerBounds.GetCenter(); } gameLocal.clip.Translation( tr, start, fromPos, projectileClipModel, mat3_identity, MASK_SHOT_RENDERMODEL, this ); fromPos = tr.endpos; if ( GetAimDir( fromPos, enemy.GetEntity(), this, dir ) ) { idThread::ReturnInt( true ); } else { idThread::ReturnInt( false ); } } /* ===================== idAI::Event_CanHitEnemyFromJoint ===================== */ void idAI::Event_CanHitEnemyFromJoint( const char *jointname ) { trace_t tr; idVec3 muzzle; idMat3 axis; idVec3 start; float distance; idActor *enemyEnt = enemy.GetEntity(); if ( !AI_ENEMY_VISIBLE || !enemyEnt ) { idThread::ReturnInt( false ); return; } // don't check twice per frame if ( gameLocal.time == lastHitCheckTime ) { idThread::ReturnInt( lastHitCheckResult ); return; } lastHitCheckTime = gameLocal.time; const idVec3 &org = physicsObj.GetOrigin(); idVec3 toPos = enemyEnt->GetEyePosition(); jointHandle_t joint = animator.GetJointHandle( jointname ); if ( joint == INVALID_JOINT ) { gameLocal.Error( "Unknown joint '%s' on %s", jointname, GetEntityDefName() ); } animator.GetJointTransform( joint, gameLocal.time, muzzle, axis ); muzzle = org + ( muzzle + modelOffset ) * viewAxis * physicsObj.GetGravityAxis(); if ( projectileClipModel == NULL ) { CreateProjectileClipModel(); } // check if the owner bounds is bigger than the projectile bounds const idBounds &ownerBounds = physicsObj.GetAbsBounds(); const idBounds &projBounds = projectileClipModel->GetBounds(); if ( ( ( ownerBounds[1][0] - ownerBounds[0][0] ) > ( projBounds[1][0] - projBounds[0][0] ) ) && ( ( ownerBounds[1][1] - ownerBounds[0][1] ) > ( projBounds[1][1] - projBounds[0][1] ) ) && ( ( ownerBounds[1][2] - ownerBounds[0][2] ) > ( projBounds[1][2] - projBounds[0][2] ) ) ) { if ( (ownerBounds - projBounds).RayIntersection( org, viewAxis[ 0 ], distance ) ) { start = org + distance * viewAxis[ 0 ]; } else { start = ownerBounds.GetCenter(); } } else { // projectile bounds bigger than the owner bounds, so just start it from the center start = ownerBounds.GetCenter(); } gameLocal.clip.Translation( tr, start, muzzle, projectileClipModel, mat3_identity, MASK_SHOT_BOUNDINGBOX, this ); muzzle = tr.endpos; gameLocal.clip.Translation( tr, muzzle, toPos, projectileClipModel, mat3_identity, MASK_SHOT_BOUNDINGBOX, this ); if ( tr.fraction >= 1.0f || ( gameLocal.GetTraceEntity( tr ) == enemyEnt ) ) { lastHitCheckResult = true; } else { lastHitCheckResult = false; } idThread::ReturnInt( lastHitCheckResult ); } /* ===================== idAI::Event_EnemyPositionValid ===================== */ void idAI::Event_EnemyPositionValid( void ) { bool result; result = EnemyPositionValid(); idThread::ReturnInt( result ); } /* ===================== idAI::Event_ChargeAttack ===================== */ void idAI::Event_ChargeAttack( const char *damageDef ) { idActor *enemyEnt = enemy.GetEntity(); StopMove( MOVE_STATUS_DEST_NOT_FOUND ); if ( enemyEnt ) { idVec3 enemyOrg; if ( move.moveType == MOVETYPE_FLY ) { // position destination so that we're in the enemy's view enemyOrg = enemyEnt->GetEyePosition(); enemyOrg -= enemyEnt->GetPhysics()->GetGravityNormal() * fly_offset; } else { enemyOrg = enemyEnt->GetPhysics()->GetOrigin(); } BeginAttack( damageDef ); DirectMoveToPosition( enemyOrg ); TurnToward( enemyOrg ); } } /* ===================== idAI::Event_TestChargeAttack ===================== */ void idAI::Event_TestChargeAttack( void ) { idActor *enemyEnt = enemy.GetEntity(); predictedPath_t path; idVec3 end; if ( !enemyEnt ) { idThread::ReturnFloat( 0.0f ); return; } if ( move.moveType == MOVETYPE_FLY ) { // position destination so that we're in the enemy's view end = enemyEnt->GetEyePosition(); end -= enemyEnt->GetPhysics()->GetGravityNormal() * fly_offset; } else { end = enemyEnt->GetPhysics()->GetOrigin(); } idAI::PredictPath( this, aas, physicsObj.GetOrigin(), end - physicsObj.GetOrigin(), 1000, 1000, ( move.moveType == MOVETYPE_FLY ) ? SE_BLOCKED : ( SE_ENTER_OBSTACLE | SE_BLOCKED | SE_ENTER_LEDGE_AREA ), path ); if ( ai_debugMove.GetBool() ) { gameRenderWorld->DebugLine( colorGreen, physicsObj.GetOrigin(), end, gameLocal.msec ); gameRenderWorld->DebugBounds( path.endEvent == 0 ? colorYellow : colorRed, physicsObj.GetBounds(), end, gameLocal.msec ); } if ( ( path.endEvent == 0 ) || ( path.blockingEntity == enemyEnt ) ) { idVec3 delta = end - physicsObj.GetOrigin(); float time = delta.LengthFast(); idThread::ReturnFloat( time ); } else { idThread::ReturnFloat( 0.0f ); } } /* ===================== idAI::Event_TestAnimMoveTowardEnemy ===================== */ void idAI::Event_TestAnimMoveTowardEnemy( const char *animname ) { int anim; predictedPath_t path; idVec3 moveVec; float yaw; idVec3 delta; idActor *enemyEnt; enemyEnt = enemy.GetEntity(); if ( !enemyEnt ) { idThread::ReturnInt( false ); return; } anim = GetAnim( ANIMCHANNEL_LEGS, animname ); if ( !anim ) { gameLocal.DWarning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() ); idThread::ReturnInt( false ); return; } delta = enemyEnt->GetPhysics()->GetOrigin() - physicsObj.GetOrigin(); yaw = delta.ToYaw(); moveVec = animator.TotalMovementDelta( anim ) * idAngles( 0.0f, yaw, 0.0f ).ToMat3() * physicsObj.GetGravityAxis(); idAI::PredictPath( this, aas, physicsObj.GetOrigin(), moveVec, 1000, 1000, ( move.moveType == MOVETYPE_FLY ) ? SE_BLOCKED : ( SE_ENTER_OBSTACLE | SE_BLOCKED | SE_ENTER_LEDGE_AREA ), path ); if ( ai_debugMove.GetBool() ) { gameRenderWorld->DebugLine( colorGreen, physicsObj.GetOrigin(), physicsObj.GetOrigin() + moveVec, gameLocal.msec ); gameRenderWorld->DebugBounds( path.endEvent == 0 ? colorYellow : colorRed, physicsObj.GetBounds(), physicsObj.GetOrigin() + moveVec, gameLocal.msec ); } idThread::ReturnInt( path.endEvent == 0 ); } /* ===================== idAI::Event_TestAnimMove ===================== */ void idAI::Event_TestAnimMove( const char *animname ) { int anim; predictedPath_t path; idVec3 moveVec; anim = GetAnim( ANIMCHANNEL_LEGS, animname ); if ( !anim ) { gameLocal.DWarning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() ); idThread::ReturnInt( false ); return; } moveVec = animator.TotalMovementDelta( anim ) * idAngles( 0.0f, ideal_yaw, 0.0f ).ToMat3() * physicsObj.GetGravityAxis(); idAI::PredictPath( this, aas, physicsObj.GetOrigin(), moveVec, 1000, 1000, ( move.moveType == MOVETYPE_FLY ) ? SE_BLOCKED : ( SE_ENTER_OBSTACLE | SE_BLOCKED | SE_ENTER_LEDGE_AREA ), path ); if ( ai_debugMove.GetBool() ) { gameRenderWorld->DebugLine( colorGreen, physicsObj.GetOrigin(), physicsObj.GetOrigin() + moveVec, gameLocal.msec ); gameRenderWorld->DebugBounds( path.endEvent == 0 ? colorYellow : colorRed, physicsObj.GetBounds(), physicsObj.GetOrigin() + moveVec, gameLocal.msec ); } idThread::ReturnInt( path.endEvent == 0 ); } /* ===================== idAI::Event_TestMoveToPosition ===================== */ void idAI::Event_TestMoveToPosition( const idVec3 &position ) { predictedPath_t path; idAI::PredictPath( this, aas, physicsObj.GetOrigin(), position - physicsObj.GetOrigin(), 1000, 1000, ( move.moveType == MOVETYPE_FLY ) ? SE_BLOCKED : ( SE_ENTER_OBSTACLE | SE_BLOCKED | SE_ENTER_LEDGE_AREA ), path ); if ( ai_debugMove.GetBool() ) { gameRenderWorld->DebugLine( colorGreen, physicsObj.GetOrigin(), position, gameLocal.msec ); gameRenderWorld->DebugBounds( colorYellow, physicsObj.GetBounds(), position, gameLocal.msec ); if ( path.endEvent ) { gameRenderWorld->DebugBounds( colorRed, physicsObj.GetBounds(), path.endPos, gameLocal.msec ); } } idThread::ReturnInt( path.endEvent == 0 ); } /* ===================== idAI::Event_TestMeleeAttack ===================== */ void idAI::Event_TestMeleeAttack( void ) { bool result = TestMelee(); idThread::ReturnInt( result ); } /* ===================== idAI::Event_TestAnimAttack ===================== */ void idAI::Event_TestAnimAttack( const char *animname ) { int anim; predictedPath_t path; anim = GetAnim( ANIMCHANNEL_LEGS, animname ); if ( !anim ) { gameLocal.DWarning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() ); idThread::ReturnInt( false ); return; } idAI::PredictPath( this, aas, physicsObj.GetOrigin(), animator.TotalMovementDelta( anim ), 1000, 1000, ( move.moveType == MOVETYPE_FLY ) ? SE_BLOCKED : ( SE_ENTER_OBSTACLE | SE_BLOCKED | SE_ENTER_LEDGE_AREA ), path ); idThread::ReturnInt( path.blockingEntity && ( path.blockingEntity == enemy.GetEntity() ) ); } /* ===================== idAI::Event_Shrivel ===================== */ void idAI::Event_Shrivel( float shrivel_time ) { float t; if ( idThread::BeginMultiFrameEvent( this, &AI_Shrivel ) ) { if ( shrivel_time <= 0.0f ) { idThread::EndMultiFrameEvent( this, &AI_Shrivel ); return; } shrivel_rate = 0.001f / shrivel_time; shrivel_start = gameLocal.time; } t = ( gameLocal.time - shrivel_start ) * shrivel_rate; if ( t > 0.25f ) { renderEntity.noShadow = true; } if ( t > 1.0f ) { t = 1.0f; idThread::EndMultiFrameEvent( this, &AI_Shrivel ); } renderEntity.shaderParms[ SHADERPARM_MD5_SKINSCALE ] = 1.0f - t * 0.5f; UpdateVisuals(); } /* ===================== idAI::Event_PreBurn ===================== */ void idAI::Event_PreBurn( void ) { #ifdef _D3XP // No grabbing after the burn has started! noGrab = true; #endif // for now this just turns shadows off renderEntity.noShadow = true; } /* ===================== idAI::Event_Burn ===================== */ void idAI::Event_Burn( void ) { renderEntity.shaderParms[ SHADERPARM_TIME_OF_DEATH ] = gameLocal.time * 0.001f; SpawnParticles( "smoke_burnParticleSystem" ); UpdateVisuals(); } /* ===================== idAI::Event_ClearBurn ===================== */ void idAI::Event_ClearBurn( void ) { renderEntity.noShadow = spawnArgs.GetBool( "noshadows" ); renderEntity.shaderParms[ SHADERPARM_TIME_OF_DEATH ] = 0.0f; UpdateVisuals(); } /* ===================== idAI::Event_SetSmokeVisibility ===================== */ void idAI::Event_SetSmokeVisibility( int num, int on ) { int i; int time; if ( num >= particles.Num() ) { gameLocal.Warning( "Particle #%d out of range (%d particles) on entity '%s'", num, particles.Num(), name.c_str() ); return; } if ( on != 0 ) { time = gameLocal.time; BecomeActive( TH_UPDATEPARTICLES ); } else { time = 0; } if ( num >= 0 ) { particles[ num ].time = time; } else { for ( i = 0; i < particles.Num(); i++ ) { particles[ i ].time = time; } } UpdateVisuals(); } /* ===================== idAI::Event_NumSmokeEmitters ===================== */ void idAI::Event_NumSmokeEmitters( void ) { idThread::ReturnInt( particles.Num() ); } /* ===================== idAI::Event_StopThinking ===================== */ void idAI::Event_StopThinking( void ) { BecomeInactive( TH_THINK ); idThread *thread = idThread::CurrentThread(); if ( thread ) { thread->DoneProcessing(); } } /* ===================== idAI::Event_GetTurnDelta ===================== */ void idAI::Event_GetTurnDelta( void ) { float amount; if ( turnRate ) { amount = idMath::AngleNormalize180( ideal_yaw - current_yaw ); idThread::ReturnFloat( amount ); } else { idThread::ReturnFloat( 0.0f ); } } /* ===================== idAI::Event_GetMoveType ===================== */ void idAI::Event_GetMoveType( void ) { idThread::ReturnInt( move.moveType ); } /* ===================== idAI::Event_SetMoveTypes ===================== */ void idAI::Event_SetMoveType( int moveType ) { if ( ( moveType < 0 ) || ( moveType >= NUM_MOVETYPES ) ) { gameLocal.Error( "Invalid movetype %d", moveType ); } move.moveType = static_cast<moveType_t>( moveType ); if ( move.moveType == MOVETYPE_FLY ) { travelFlags = TFL_WALK|TFL_AIR|TFL_FLY; } else { travelFlags = TFL_WALK|TFL_AIR; } } /* ===================== idAI::Event_SaveMove ===================== */ void idAI::Event_SaveMove( void ) { savedMove = move; } /* ===================== idAI::Event_RestoreMove ===================== */ void idAI::Event_RestoreMove( void ) { idVec3 goalPos; idVec3 dest; switch( savedMove.moveCommand ) { case MOVE_NONE : StopMove( savedMove.moveStatus ); break; case MOVE_FACE_ENEMY : FaceEnemy(); break; case MOVE_FACE_ENTITY : FaceEntity( savedMove.goalEntity.GetEntity() ); break; case MOVE_TO_ENEMY : MoveToEnemy(); break; case MOVE_TO_ENEMYHEIGHT : MoveToEnemyHeight(); break; case MOVE_TO_ENTITY : MoveToEntity( savedMove.goalEntity.GetEntity() ); break; case MOVE_OUT_OF_RANGE : MoveOutOfRange( savedMove.goalEntity.GetEntity(), savedMove.range ); break; case MOVE_TO_ATTACK_POSITION : MoveToAttackPosition( savedMove.goalEntity.GetEntity(), savedMove.anim ); break; case MOVE_TO_COVER : MoveToCover( savedMove.goalEntity.GetEntity(), lastVisibleEnemyPos ); break; case MOVE_TO_POSITION : MoveToPosition( savedMove.moveDest ); break; case MOVE_TO_POSITION_DIRECT : DirectMoveToPosition( savedMove.moveDest ); break; case MOVE_SLIDE_TO_POSITION : SlideToPosition( savedMove.moveDest, savedMove.duration ); break; case MOVE_WANDER : WanderAround(); break; } if ( GetMovePos( goalPos ) ) { CheckObstacleAvoidance( goalPos, dest ); } } /* ===================== idAI::Event_AllowMovement ===================== */ void idAI::Event_AllowMovement( float flag ) { allowMove = ( flag != 0.0f ); } /* ===================== idAI::Event_JumpFrame ===================== */ void idAI::Event_JumpFrame( void ) { AI_JUMP = true; } /* ===================== idAI::Event_EnableClip ===================== */ void idAI::Event_EnableClip( void ) { physicsObj.SetClipMask( MASK_MONSTERSOLID ); disableGravity = false; } /* ===================== idAI::Event_DisableClip ===================== */ void idAI::Event_DisableClip( void ) { physicsObj.SetClipMask( 0 ); disableGravity = true; } /* ===================== idAI::Event_EnableGravity ===================== */ void idAI::Event_EnableGravity( void ) { disableGravity = false; } /* ===================== idAI::Event_DisableGravity ===================== */ void idAI::Event_DisableGravity( void ) { disableGravity = true; } /* ===================== idAI::Event_EnableAFPush ===================== */ void idAI::Event_EnableAFPush( void ) { af_push_moveables = true; } /* ===================== idAI::Event_DisableAFPush ===================== */ void idAI::Event_DisableAFPush( void ) { af_push_moveables = false; } /* ===================== idAI::Event_SetFlySpeed ===================== */ void idAI::Event_SetFlySpeed( float speed ) { if ( move.speed == fly_speed ) { move.speed = speed; } fly_speed = speed; } /* ================ idAI::Event_SetFlyOffset ================ */ void idAI::Event_SetFlyOffset( int offset ) { fly_offset = offset; } /* ================ idAI::Event_ClearFlyOffset ================ */ void idAI::Event_ClearFlyOffset( void ) { spawnArgs.GetInt( "fly_offset", "0", fly_offset ); } /* ===================== idAI::Event_GetClosestHiddenTarget ===================== */ void idAI::Event_GetClosestHiddenTarget( const char *type ) { int i; idEntity *ent; idEntity *bestEnt; float time; float bestTime; const idVec3 &org = physicsObj.GetOrigin(); idActor *enemyEnt = enemy.GetEntity(); if ( !enemyEnt ) { // no enemy to hide from idThread::ReturnEntity( NULL ); return; } if ( targets.Num() == 1 ) { ent = targets[ 0 ].GetEntity(); if ( ent && idStr::Cmp( ent->GetEntityDefName(), type ) == 0 ) { if ( !EntityCanSeePos( enemyEnt, lastVisibleEnemyPos, ent->GetPhysics()->GetOrigin() ) ) { idThread::ReturnEntity( ent ); return; } } idThread::ReturnEntity( NULL ); return; } bestEnt = NULL; bestTime = idMath::INFINITY; for( i = 0; i < targets.Num(); i++ ) { ent = targets[ i ].GetEntity(); if ( ent && idStr::Cmp( ent->GetEntityDefName(), type ) == 0 ) { const idVec3 &destOrg = ent->GetPhysics()->GetOrigin(); time = TravelDistance( org, destOrg ); if ( ( time >= 0.0f ) && ( time < bestTime ) ) { if ( !EntityCanSeePos( enemyEnt, lastVisibleEnemyPos, destOrg ) ) { bestEnt = ent; bestTime = time; } } } } idThread::ReturnEntity( bestEnt ); } /* ===================== idAI::Event_GetRandomTarget ===================== */ void idAI::Event_GetRandomTarget( const char *type ) { int i; int num; int which; idEntity *ent; idEntity *ents[ MAX_GENTITIES ]; num = 0; for( i = 0; i < targets.Num(); i++ ) { ent = targets[ i ].GetEntity(); if ( ent && idStr::Cmp( ent->GetEntityDefName(), type ) == 0 ) { ents[ num++ ] = ent; if ( num >= MAX_GENTITIES ) { break; } } } if ( !num ) { idThread::ReturnEntity( NULL ); return; } which = gameLocal.random.RandomInt( num ); idThread::ReturnEntity( ents[ which ] ); } /* ================ idAI::Event_TravelDistanceToPoint ================ */ void idAI::Event_TravelDistanceToPoint( const idVec3 &pos ) { float time; time = TravelDistance( physicsObj.GetOrigin(), pos ); idThread::ReturnFloat( time ); } /* ================ idAI::Event_TravelDistanceToEntity ================ */ void idAI::Event_TravelDistanceToEntity( idEntity *ent ) { float time; time = TravelDistance( physicsObj.GetOrigin(), ent->GetPhysics()->GetOrigin() ); idThread::ReturnFloat( time ); } /* ================ idAI::Event_TravelDistanceBetweenPoints ================ */ void idAI::Event_TravelDistanceBetweenPoints( const idVec3 &source, const idVec3 &dest ) { float time; time = TravelDistance( source, dest ); idThread::ReturnFloat( time ); } /* ================ idAI::Event_TravelDistanceBetweenEntities ================ */ void idAI::Event_TravelDistanceBetweenEntities( idEntity *source, idEntity *dest ) { float time; assert( source ); assert( dest ); time = TravelDistance( source->GetPhysics()->GetOrigin(), dest->GetPhysics()->GetOrigin() ); idThread::ReturnFloat( time ); } /* ===================== idAI::Event_LookAtEntity ===================== */ void idAI::Event_LookAtEntity( idEntity *ent, float duration ) { if ( ent == this ) { ent = NULL; } if ( ( ent != focusEntity.GetEntity() ) || ( focusTime < gameLocal.time ) ) { focusEntity = ent; alignHeadTime = gameLocal.time; forceAlignHeadTime = gameLocal.time + SEC2MS( 1 ); blink_time = 0; } focusTime = gameLocal.time + SEC2MS( duration ); } /* ===================== idAI::Event_LookAtEnemy ===================== */ void idAI::Event_LookAtEnemy( float duration ) { idActor *enemyEnt; enemyEnt = enemy.GetEntity(); if ( ( enemyEnt != focusEntity.GetEntity() ) || ( focusTime < gameLocal.time ) ) { focusEntity = enemyEnt; alignHeadTime = gameLocal.time; forceAlignHeadTime = gameLocal.time + SEC2MS( 1 ); blink_time = 0; } focusTime = gameLocal.time + SEC2MS( duration ); } /* =============== idAI::Event_SetJointMod =============== */ void idAI::Event_SetJointMod( int allow ) { allowJointMod = ( allow != 0 ); } /* ================ idAI::Event_ThrowMoveable ================ */ void idAI::Event_ThrowMoveable( void ) { idEntity *ent; idEntity *moveable = NULL; for ( ent = GetNextTeamEntity(); ent != NULL; ent = ent->GetNextTeamEntity() ) { if ( ent->GetBindMaster() == this && ent->IsType( idMoveable::Type ) ) { moveable = ent; break; } } if ( moveable ) { moveable->Unbind(); moveable->PostEventMS( &EV_SetOwner, 200, 0 ); } } /* ================ idAI::Event_ThrowAF ================ */ void idAI::Event_ThrowAF( void ) { idEntity *ent; idEntity *af = NULL; for ( ent = GetNextTeamEntity(); ent != NULL; ent = ent->GetNextTeamEntity() ) { if ( ent->GetBindMaster() == this && ent->IsType( idAFEntity_Base::Type ) ) { af = ent; break; } } if ( af ) { af->Unbind(); af->PostEventMS( &EV_SetOwner, 200, 0 ); } } /* ================ idAI::Event_SetAngles ================ */ void idAI::Event_SetAngles( idAngles const &ang ) { current_yaw = ang.yaw; viewAxis = idAngles( 0, current_yaw, 0 ).ToMat3(); } /* ================ idAI::Event_GetAngles ================ */ void idAI::Event_GetAngles( void ) { idThread::ReturnVector( idVec3( 0.0f, current_yaw, 0.0f ) ); } /* ================ idAI::Event_RealKill ================ */ void idAI::Event_RealKill( void ) { health = 0; if ( af.IsLoaded() ) { // clear impacts af.Rest(); // physics is turned off by calling af.Rest() BecomeActive( TH_PHYSICS ); } Killed( this, this, 0, vec3_zero, INVALID_JOINT ); } /* ================ idAI::Event_Kill ================ */ void idAI::Event_Kill( void ) { PostEventMS( &AI_RealKill, 0 ); } /* ================ idAI::Event_WakeOnFlashlight ================ */ void idAI::Event_WakeOnFlashlight( int enable ) { wakeOnFlashlight = ( enable != 0 ); } /* ================ idAI::Event_LocateEnemy ================ */ void idAI::Event_LocateEnemy( void ) { idActor *enemyEnt; int areaNum; enemyEnt = enemy.GetEntity(); if ( !enemyEnt ) { return; } enemyEnt->GetAASLocation( aas, lastReachableEnemyPos, areaNum ); SetEnemyPosition(); UpdateEnemyPosition(); } /* ================ idAI::Event_KickObstacles ================ */ void idAI::Event_KickObstacles( idEntity *kickEnt, float force ) { idVec3 dir; idEntity *obEnt; if ( kickEnt ) { obEnt = kickEnt; } else { obEnt = move.obstacle.GetEntity(); } if ( obEnt ) { dir = obEnt->GetPhysics()->GetOrigin() - physicsObj.GetOrigin(); dir.Normalize(); } else { dir = viewAxis[ 0 ]; } KickObstacles( dir, force, obEnt ); } /* ================ idAI::Event_GetObstacle ================ */ void idAI::Event_GetObstacle( void ) { idThread::ReturnEntity( move.obstacle.GetEntity() ); } /* ================ idAI::Event_PushPointIntoAAS ================ */ void idAI::Event_PushPointIntoAAS( const idVec3 &pos ) { int areaNum; idVec3 newPos; areaNum = PointReachableAreaNum( pos ); if ( areaNum ) { newPos = pos; aas->PushPointIntoAreaNum( areaNum, newPos ); idThread::ReturnVector( newPos ); } else { idThread::ReturnVector( pos ); } } /* ================ idAI::Event_GetTurnRate ================ */ void idAI::Event_GetTurnRate( void ) { idThread::ReturnFloat( turnRate ); } /* ================ idAI::Event_SetTurnRate ================ */ void idAI::Event_SetTurnRate( float rate ) { turnRate = rate; } /* ================ idAI::Event_AnimTurn ================ */ void idAI::Event_AnimTurn( float angles ) { turnVel = 0.0f; anim_turn_angles = angles; if ( angles ) { anim_turn_yaw = current_yaw; anim_turn_amount = idMath::Fabs( idMath::AngleNormalize180( current_yaw - ideal_yaw ) ); if ( anim_turn_amount > anim_turn_angles ) { anim_turn_amount = anim_turn_angles; } } else { anim_turn_amount = 0.0f; animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( 0, 1.0f ); animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( 1, 0.0f ); animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( 0, 1.0f ); animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( 1, 0.0f ); } } /* ================ idAI::Event_AllowHiddenMovement ================ */ void idAI::Event_AllowHiddenMovement( int enable ) { allowHiddenMovement = ( enable != 0 ); } /* ================ idAI::Event_TriggerParticles ================ */ void idAI::Event_TriggerParticles( const char *jointName ) { TriggerParticles( jointName ); } /* ===================== idAI::Event_FindActorsInBounds ===================== */ void idAI::Event_FindActorsInBounds( const idVec3 &mins, const idVec3 &maxs ) { idEntity * ent; idEntity * entityList[ MAX_GENTITIES ]; int numListedEntities; int i; numListedEntities = gameLocal.clip.EntitiesTouchingBounds( idBounds( mins, maxs ), CONTENTS_BODY, entityList, MAX_GENTITIES ); for( i = 0; i < numListedEntities; i++ ) { ent = entityList[ i ]; if ( ent != this && !ent->IsHidden() && ( ent->health > 0 ) && ent->IsType( idActor::Type ) ) { idThread::ReturnEntity( ent ); return; } } idThread::ReturnEntity( NULL ); } /* ================ idAI::Event_CanReachPosition ================ */ void idAI::Event_CanReachPosition( const idVec3 &pos ) { aasPath_t path; int toAreaNum; int areaNum; toAreaNum = PointReachableAreaNum( pos ); areaNum = PointReachableAreaNum( physicsObj.GetOrigin() ); if ( !toAreaNum || !PathToGoal( path, areaNum, physicsObj.GetOrigin(), toAreaNum, pos ) ) { idThread::ReturnInt( false ); } else { idThread::ReturnInt( true ); } } /* ================ idAI::Event_CanReachEntity ================ */ void idAI::Event_CanReachEntity( idEntity *ent ) { aasPath_t path; int toAreaNum; int areaNum; idVec3 pos; if ( !ent ) { idThread::ReturnInt( false ); return; } if ( move.moveType != MOVETYPE_FLY ) { if ( !ent->GetFloorPos( 64.0f, pos ) ) { idThread::ReturnInt( false ); return; } if ( ent->IsType( idActor::Type ) && static_cast<idActor *>( ent )->OnLadder() ) { idThread::ReturnInt( false ); return; } } else { pos = ent->GetPhysics()->GetOrigin(); } toAreaNum = PointReachableAreaNum( pos ); if ( !toAreaNum ) { idThread::ReturnInt( false ); return; } const idVec3 &org = physicsObj.GetOrigin(); areaNum = PointReachableAreaNum( org ); if ( !toAreaNum || !PathToGoal( path, areaNum, org, toAreaNum, pos ) ) { idThread::ReturnInt( false ); } else { idThread::ReturnInt( true ); } } /* ================ idAI::Event_CanReachEnemy ================ */ void idAI::Event_CanReachEnemy( void ) { aasPath_t path; int toAreaNum; int areaNum; idVec3 pos; idActor *enemyEnt; enemyEnt = enemy.GetEntity(); if ( !enemyEnt ) { idThread::ReturnInt( false ); return; } if ( move.moveType != MOVETYPE_FLY ) { if ( enemyEnt->OnLadder() ) { idThread::ReturnInt( false ); return; } enemyEnt->GetAASLocation( aas, pos, toAreaNum ); } else { pos = enemyEnt->GetPhysics()->GetOrigin(); toAreaNum = PointReachableAreaNum( pos ); } if ( !toAreaNum ) { idThread::ReturnInt( false ); return; } const idVec3 &org = physicsObj.GetOrigin(); areaNum = PointReachableAreaNum( org ); if ( !PathToGoal( path, areaNum, org, toAreaNum, pos ) ) { idThread::ReturnInt( false ); } else { idThread::ReturnInt( true ); } } /* ================ idAI::Event_GetReachableEntityPosition ================ */ void idAI::Event_GetReachableEntityPosition( idEntity *ent ) { int toAreaNum; idVec3 pos; if ( move.moveType != MOVETYPE_FLY ) { if ( !ent->GetFloorPos( 64.0f, pos ) ) { // NOTE: not a good way to return 'false' return idThread::ReturnVector( vec3_zero ); } if ( ent->IsType( idActor::Type ) && static_cast<idActor *>( ent )->OnLadder() ) { // NOTE: not a good way to return 'false' return idThread::ReturnVector( vec3_zero ); } } else { pos = ent->GetPhysics()->GetOrigin(); } if ( aas ) { toAreaNum = PointReachableAreaNum( pos ); aas->PushPointIntoAreaNum( toAreaNum, pos ); } idThread::ReturnVector( pos ); } #ifdef _D3XP /* ================ idAI::Event_MoveToPositionDirect ================ */ void idAI::Event_MoveToPositionDirect( const idVec3 &pos ) { StopMove( MOVE_STATUS_DONE ); DirectMoveToPosition( pos ); } /* ================ idAI::Event_AvoidObstacles ================ */ void idAI::Event_AvoidObstacles( int ignore) { ignore_obstacles = (ignore == 1) ? false : true; } /* ================ idAI::Event_TriggerFX ================ */ void idAI::Event_TriggerFX( const char* joint, const char* fx ) { TriggerFX(joint, fx); } void idAI::Event_StartEmitter( const char* name, const char* joint, const char* particle ) { idEntity *ent = StartEmitter(name, joint, particle); idThread::ReturnEntity(ent); } void idAI::Event_GetEmitter( const char* name ) { idThread::ReturnEntity(GetEmitter(name)); } void idAI::Event_StopEmitter( const char* name ) { StopEmitter(name); } #endif
gpl-3.0
nidhugg/nidhugg
tests/litmus/C-tests/MP+PPO597.c
2
1974
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[4]; atomic_int atom_1_r1_1; atomic_int atom_1_r11_1; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v3_cmpeq = (v2_r1 == v2_r1); if (v3_cmpeq) goto lbl_LC00; else goto lbl_LC00; lbl_LC00:; atomic_store_explicit(&vars[2], 1, memory_order_seq_cst); int v5_r5 = atomic_load_explicit(&vars[2], memory_order_seq_cst); int v6_r6 = v5_r5 ^ v5_r5; int v9_r7 = atomic_load_explicit(&vars[3+v6_r6], memory_order_seq_cst); int v10_r9 = v9_r7 ^ v9_r7; int v11_r9 = v10_r9 + 1; atomic_store_explicit(&vars[0], v11_r9, memory_order_seq_cst); int v13_r11 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v20 = (v2_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v20, memory_order_seq_cst); int v21 = (v13_r11 == 1); atomic_store_explicit(&atom_1_r11_1, v21, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[3], 0); atomic_init(&vars[0], 0); atomic_init(&vars[2], 0); atomic_init(&vars[1], 0); atomic_init(&atom_1_r1_1, 0); atomic_init(&atom_1_r11_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v14 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v15 = (v14 == 2); int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v17 = atomic_load_explicit(&atom_1_r11_1, memory_order_seq_cst); int v18_conj = v16 & v17; int v19_conj = v15 & v18_conj; if (v19_conj == 1) assert(0); return 0; }
gpl-3.0
joel16/Cyanogen3DS
source/libs/libsftd/source/texture_atlas.c
2
2417
#include <stdlib.h> #include <string.h> #include "texture_atlas.h" texture_atlas *texture_atlas_create(int width, int height, sf2d_texfmt format, sf2d_place place) { texture_atlas *atlas = malloc(sizeof(*atlas)); if (!atlas) return NULL; bp2d_rectangle rect; rect.x = 0; rect.y = 0; rect.w = width; rect.h = height; atlas->tex = sf2d_create_texture(width, height, format, place); sf2d_texture_set_params(atlas->tex, GPU_TEXTURE_MAG_FILTER(GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR)); sf2d_texture_tile32(atlas->tex); atlas->bp_root = bp2d_create(&rect); atlas->htab = int_htab_create(256); return atlas; } void texture_atlas_free(texture_atlas *atlas) { sf2d_free_texture(atlas->tex); bp2d_free(atlas->bp_root); int_htab_free(atlas->htab); free(atlas); } int texture_atlas_insert(texture_atlas *atlas, unsigned int character, const void *image, int width, int height, int bitmap_left, int bitmap_top, int advance_x, int advance_y, int glyph_size) { bp2d_size size; size.w = width; size.h = height; bp2d_position pos; if (bp2d_insert(atlas->bp_root, &size, &pos) == 0) return 0; atlas_htab_entry *entry = malloc(sizeof(*entry)); entry->rect.x = pos.x; entry->rect.y = pos.y; entry->rect.w = width; entry->rect.h = height; entry->bitmap_left = bitmap_left; entry->bitmap_top = bitmap_top; entry->advance_x = advance_x; entry->advance_y = advance_y; entry->glyph_size = glyph_size; int_htab_insert(atlas->htab, character, entry); int i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { sf2d_set_pixel(atlas->tex, pos.x + j, pos.y + i, __builtin_bswap32(*(unsigned int *)(image + (j + i*width)*4))); } } GSPGPU_FlushDataCache(atlas->tex->tex.data, atlas->tex->tex.size); return 1; } int texture_atlas_exists(texture_atlas *atlas, unsigned int character) { return int_htab_find(atlas->htab, character) != NULL; } void texture_atlas_get(texture_atlas *atlas, unsigned int character, bp2d_rectangle *rect, int *bitmap_left, int *bitmap_top, int *advance_x, int *advance_y, int *glyph_size) { atlas_htab_entry *entry = int_htab_find(atlas->htab, character); rect->x = entry->rect.x; rect->y = entry->rect.y; rect->w = entry->rect.w; rect->h = entry->rect.h; *bitmap_left = entry->bitmap_left; *bitmap_top = entry->bitmap_top; *advance_x = entry->advance_x; *advance_y = entry->advance_y; *glyph_size = entry->glyph_size; }
gpl-3.0
fehrler/Readout_Simulation
test.cpp
2
2584
/* ROME (ReadOut Modelling Environment) Copyright © 2017 Rudolf Schimassek (rudolf.schimassek@kit.edu), Felix Ehrler (felix.ehrler@kit.edu), Karlsruhe Institute of Technology (KIT) - ASIC and Detector Laboratory (ADL) 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/>. This file is part of the ROME simulation framework. */ #include <iostream> #include <string> #include <map> #include <utility> #include "evaluation.cpp" int test() { std::cout << "test" << std::endl; Evaluation asd = Evaluation(); std::map<int, int> encoding; for(int i=0;i<12;++i) encoding.insert(std::make_pair(i,1<<i)); for(int i = 20; i < 55; i += 5) { asd.ClearHits(); std::stringstream s(""); s << i << "_12_1_readhits.dat"; asd.LoadPassedOutputHits(s.str()); asd.SeparateHits(encoding); TH1* hist = asd.GenerateDelayHistogram("timestamp","Detector", -100,15000,10); TGraph* graph = asd.GenerateIntegrationCurve(hist); TCanvas* c1 = asd.Plot(hist, "Readout Delay (in Timestamps)", "Counts", ""); TCanvas* c2 = asd.Plot(graph, "Readout Delay (in Timestamps)", "Integrated Fraction of Hits", "AP*"); s.str(""); s << i << "_12_1_ReadoutDelay.svg"; c1->SaveAs(s.str().c_str()); s.str(""); s << i << "_12_1_IntegratedFraction.svg"; c2->SaveAs(s.str().c_str()); } /* asd.LoadInputHits("25_4_3_eventgen.dat"); asd.LoadPassedOutputHits("25_4_3_readhits.dat"); asd.LoadFailedOutputHits("25_4_3_losthits.dat"); TH1* hist = asd.GenerateDelayHistogram("timestamp", "Detector", 0, 10000, 10); TGraph* graph = asd.GenerateIntegrationCurve(hist); asd.Plot(hist, "Readout Delay (in Timestamps)", "Counts", ""); asd.Plot(graph, "Readout Delay (in Timestamps)", "Integrated Fraction of Hits", "AP*"); */ std::cout << "test" << std::endl; return 0; }
gpl-3.0
jpinelo/Depthmap
src/depthmap/TopoMetDlg.cpp
2
2335
// Depthmap - spatial network analysis platform // Copyright (C) 2000-2010 University College London, Alasdair Turner // 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/>. // TopoMetDlg.cpp : implementation file // #include "stdafx.h" #include "Depthmap.h" #include "TopoMetDlg.h" // CTopoMetDlg dialog IMPLEMENT_DYNAMIC(CTopoMetDlg, CDialog) CTopoMetDlg::CTopoMetDlg(CWnd* pParent /*=NULL*/) : CDialog(CTopoMetDlg::IDD, pParent) , m_topological(0) , m_radius(_T("")) , m_selected_only(FALSE) { m_radius = _T("n"); } CTopoMetDlg::~CTopoMetDlg() { } void CTopoMetDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Radio(pDX, IDC_TOPOLOGICAL, m_topological); DDX_Text(pDX, IDC_RADIUS, m_radius); DDX_Check(pDX, IDC_SELECTED_ONLY, m_selected_only); } BEGIN_MESSAGE_MAP(CTopoMetDlg, CDialog) ON_BN_CLICKED(IDOK, &CTopoMetDlg::OnBnClickedOk) END_MESSAGE_MAP() // CTopoMetDlg message handlers void CTopoMetDlg::OnBnClickedOk() { UpdateData(TRUE); m_radius.TrimLeft(' '); m_radius.TrimRight(' '); // my own validate on the radius (note: on fail to convert, atoi returns 0) if (m_radius.IsEmpty() || m_radius.FindOneOf(_T("nN123456789")) == -1) { AfxMessageBox(_T("The radius must either be numeric or 'n'")); m_radius = _T("n"); UpdateData(FALSE); return; } if (m_radius == "n" || m_radius == "N") { m_dradius = -1.0; } else { m_dradius = _wtof(m_radius); if (m_dradius <= 0.0) { AfxMessageBox(_T("The radius must either be 'n' or a number in the range 0.0 to infinity")); return; } } OnOK(); }
gpl-3.0
yfiumefreddo/Pcf
src/Switch.System.Windows.Forms/src/Native/CommonDialogApiWin32.cpp
2
10474
#if defined(_WIN32) #define UNICODE #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <CommCtrl.h> #include <ShlObj.h> #include <Switch/Undef.hpp> #include "Api.hpp" #include <Switch/System/Buffer.hpp> #include "../../include/Switch/System/Windows/Forms/ColorDialog.hpp" #include "../../include/Switch/System/Windows/Forms/FolderBrowserDialog.hpp" #include "../../include/Switch/System/Windows/Forms/FontDialog.hpp" #include "../../include/Switch/System/Windows/Forms/OpenFileDialog.hpp" #include "../../include/Switch/System/Windows/Forms/SaveFileDialog.hpp" using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; namespace { Array<byte> ToFilter(const Array<string>& filters) { int32 length = 1; for (auto& filter : filters) length += (int32)filter.Length + 1; Array<byte> result(length * sizeof(wchar)); int32 index = 0; for (auto& filter : filters) { Buffer::BlockCopy((const void*)filter.w_str().c_str(), filter.Length * sizeof(wchar), 0, (void*)result.Data(), result.Length * sizeof(wchar), index, filter.Length * sizeof(wchar)); index += (int32)filter.Length * sizeof(wchar) + sizeof(wchar); } result[index] += '\0'; return result; } static int CALLBACK BrowseFolderCallback(HWND hwnd, UINT message, LPARAM lParam, LPARAM lpData) { if (message == BFFM_INITIALIZED) { LPCTSTR path = reinterpret_cast<LPCTSTR>(lpData); ::SendMessage(hwnd, BFFM_SETSELECTION, true, (LPARAM)path); } return 0; } } bool Native::CommonDialogApi::RunColorDialog(intptr hwnd, System::Windows::Forms::ColorDialog& colorDialog) { CHOOSECOLOR chooseColor; memset(&chooseColor, 0, sizeof(chooseColor)); chooseColor.lStructSize = sizeof(chooseColor); chooseColor.hwndOwner = hwnd != IntPtr::Zero ? (HWND)hwnd : GetActiveWindow(); chooseColor.rgbResult = RGB(colorDialog.Color().R, colorDialog.Color().G, colorDialog.Color().B); COLORREF customColors[16]; for (int32 index = 0; index < colorDialog.CustomColors().Length; index++) customColors[index] = RGB(colorDialog.CustomColors()[index].R, colorDialog.CustomColors()[index].G, colorDialog.CustomColors()[index].B); chooseColor.lpCustColors = customColors; int flags = CC_RGBINIT; // | CC_ENABLEHOOK; if (!colorDialog.AllowFullOpen) flags |= CC_PREVENTFULLOPEN; if (colorDialog.AnyColor) flags |= CC_ANYCOLOR; if (colorDialog.FullOpen && colorDialog.AllowFullOpen) flags |= CC_FULLOPEN; if (colorDialog.ShowHelp) flags |= CC_SHOWHELP; if (colorDialog.SolidColorOnly) flags |= CC_SOLIDCOLOR; chooseColor.Flags = flags; if (!ChooseColor(&chooseColor)) return false; colorDialog.Color = System::Drawing::Color::FromArgb(255, GetRValue(chooseColor.rgbResult), GetGValue(chooseColor.rgbResult), GetBValue(chooseColor.rgbResult)); for (int32 index = 0; index < colorDialog.CustomColors().Length; index++) colorDialog.CustomColors()[index] = System::Drawing::Color::FromArgb(255, GetRValue(customColors[index]), GetGValue(customColors[index]), GetBValue(customColors[index])); return true; } bool Native::CommonDialogApi::RunFolderBrowserDialog(intptr hwnd, System::Windows::Forms::FolderBrowserDialog& folderBrowserDialog) { CoInitializeEx(null, COINIT_APARTMENTTHREADED); BROWSEINFO browserInfo; ZeroMemory(&browserInfo, sizeof(browserInfo)); browserInfo.hwndOwner = (HWND)hwnd; PIDLIST_ABSOLUTE rootPath; if (folderBrowserDialog.RootFolder != Environment::SpecialFolder::Desktop && SHParseDisplayName(Environment::GetFolderPath(folderBrowserDialog.RootFolder).w_str().c_str(), null, &rootPath, SFGAO_FILESYSTEM, null) == S_OK) browserInfo.pidlRoot = rootPath; browserInfo.lParam = reinterpret_cast<LPARAM>(folderBrowserDialog.SelectedPath().w_str().c_str()); browserInfo.lpszTitle = folderBrowserDialog.Description().w_str().c_str(); int32 flags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE; if (!folderBrowserDialog.ShowNewFolderButton) flags |= BIF_NONEWFOLDERBUTTON; browserInfo.ulFlags = flags; //browserInfo.lpfn = BrowseFolderCallback; PCIDLIST_ABSOLUTE result = SHBrowseForFolder(&browserInfo); if (!result) return false; wchar path[MAX_PATH]; SHGetPathFromIDList(result, path); folderBrowserDialog.SelectedPath = path; return true; } bool Native::CommonDialogApi::RunFontDialog(intptr hwnd, System::Windows::Forms::FontDialog& fontDialog) { CHOOSEFONT chooseFont; memset(&chooseFont, 0, sizeof(chooseFont)); chooseFont.lStructSize = sizeof(chooseFont); chooseFont.hwndOwner = (HWND)hwnd; LOGFONT logFont; GetObject((HANDLE)fontDialog.Font().ToHFont(), sizeof(logFont), &logFont); chooseFont.lpLogFont = &logFont; chooseFont.iPointSize = as<int32>(fontDialog.Font().SizeInPoints()); int32 flags = CF_SCREENFONTS | CF_INITTOLOGFONTSTRUCT | CF_TTONLY; if (!fontDialog.AllowSimulations) flags |= CF_NOSIMULATIONS; if (!fontDialog.AllowVectorFonts) flags |= CF_NOVECTORFONTS; if (!fontDialog.AllowVerticalFonts) flags |= CF_NOVERTFONTS; if (!fontDialog.AllowScriptChange) flags |= CF_SELECTSCRIPT; if (fontDialog.FixedPitchOnly) flags |= CF_FIXEDPITCHONLY; if (fontDialog.FontMustExist) flags |= CF_FORCEFONTEXIST; if (fontDialog.ScriptOnly) flags |= CF_SCRIPTSONLY; if (fontDialog.ShowApply) flags |= CF_APPLY; if (fontDialog.ShowColor || fontDialog.ShowEffects) flags |= CF_EFFECTS; if (fontDialog.ShowHelp) flags |= CF_SHOWHELP; if (fontDialog.MaxSize > 0 || fontDialog.MinSize > 0) flags |= CF_LIMITSIZE; chooseFont.Flags = flags; chooseFont.rgbColors = RGB(fontDialog.Color().R, fontDialog.Color().G, fontDialog.Color().B); chooseFont.nSizeMax = fontDialog.MaxSize; chooseFont.nSizeMin = fontDialog.MinSize; if (!ChooseFont(&chooseFont)) return false; fontDialog.Font = System::Drawing::Font::FromLogFont(logFont); fontDialog.Color = System::Drawing::Color::FromArgb(255, GetRValue(chooseFont.rgbColors), GetGValue(chooseFont.rgbColors), GetBValue(chooseFont.rgbColors)); return true; } bool Native::CommonDialogApi::RunOpenFileDialog(intptr hwnd, System::Windows::Forms::OpenFileDialog& openFileDialog) { OPENFILENAME openFileName; ZeroMemory(&openFileName, sizeof(openFileName)); openFileName.lStructSize = sizeof(openFileName); openFileName.hwndOwner = hwnd != IntPtr::Zero ? (HWND)hwnd : GetActiveWindow(); const Array<byte> filter = ToFilter(openFileDialog.Filter().Split('|')); openFileName.lpstrFilter = openFileDialog.Filter() != "" ? (LPWSTR)filter.Data() : null; openFileName.lpstrCustomFilter = null; openFileName.nFilterIndex = openFileDialog.Filter() != "" ? openFileDialog.FilterIndex : 0; std::wstring fileName(MAX_PATH, ' '); openFileName.lpstrFile = (LPWSTR)fileName.c_str(); openFileName.nMaxFile = MAX_PATH; wchar fileTitle[MAX_PATH]; fileTitle[0] = 0; openFileName.lpstrFileTitle = fileTitle; openFileName.nMaxFileTitle = MAX_PATH; std::wstring initialDirectory = openFileDialog.InitialDirectory().w_str(); openFileName.lpstrInitialDir = initialDirectory.c_str(); std::wstring title = openFileDialog.Title().w_str(); openFileName.lpstrTitle = title.c_str(); int32 flags = OFN_EXPLORER; if (openFileDialog.Multiselect) flags |= OFN_ALLOWMULTISELECT; if (!openFileDialog.DereferenceLinks) flags |= OFN_NODEREFERENCELINKS; if (openFileDialog.CheckFileExists) flags |= OFN_PATHMUSTEXIST; if (openFileDialog.ReadOnlyChecked) flags |= OFN_READONLY; if (openFileDialog.ShowHelp) flags |= OFN_SHOWHELP; openFileName.Flags = flags; openFileName.nFileOffset = 0; openFileName.nFileExtension = 0; std::wstring defaultExt = openFileDialog.DefaultExt().w_str(); openFileName.lpstrDefExt = defaultExt.c_str(); BOOL result = GetOpenFileName(&openFileName); if (!result && CommDlgExtendedError() == 0) return false; if (!result && CommDlgExtendedError() == FNERR_BUFFERTOOSMALL) { int32 size = (int32) * fileName.c_str(); fileName = std::wstring(size, ' '); openFileName.lpstrFile = (LPWSTR)fileName.c_str(); result = GetOpenFileName(&openFileName); } if (!result && CommDlgExtendedError() != 0) throw InvalidOperationException(caller_); if (!openFileDialog.Multiselect) openFileDialog.FileName = fileName; else { System::Collections::Generic::List<string> fileNames; string path = fileName; for (int32 index = (int32)wcslen(fileName.c_str()) + 1; fileName.c_str()[index] != 0; index += (int32)wcslen(&fileName.c_str()[index]) + 1) fileNames.Add(System::IO::Path::Combine(path, &fileName.c_str()[index])); openFileDialog.FileName = fileNames[0]; openFileDialog.__set__file_names__(fileNames.ToArray()); } return true; } bool Native::CommonDialogApi::RunSaveFileDialog(intptr hwnd, System::Windows::Forms::SaveFileDialog& saveFileDialog) { OPENFILENAME openFileName; ZeroMemory(&openFileName, sizeof(openFileName)); openFileName.lStructSize = sizeof(openFileName); openFileName.hwndOwner = hwnd != IntPtr::Zero ? (HWND)hwnd : GetActiveWindow(); const Array<byte> filter = ToFilter(saveFileDialog.Filter().Split('|')); openFileName.lpstrFilter = saveFileDialog.Filter() != "" ? (LPWSTR)filter.Data() : null; openFileName.lpstrCustomFilter = null; openFileName.nFilterIndex = saveFileDialog.Filter() != "" ? saveFileDialog.FilterIndex : 0; wchar fileName[MAX_PATH]; wcscpy(fileName, saveFileDialog.FileName().w_str().c_str()); openFileName.lpstrFile = fileName; openFileName.nMaxFile = MAX_PATH; wchar fileTitle[MAX_PATH]; fileTitle[0] = 0; openFileName.lpstrFileTitle = fileTitle; openFileName.nMaxFileTitle = MAX_PATH; std::wstring initialDirectory = saveFileDialog.InitialDirectory().w_str(); openFileName.lpstrInitialDir = initialDirectory.c_str(); std::wstring title = saveFileDialog.Title().w_str(); openFileName.lpstrTitle = title.c_str(); int32 flags = 0; if (saveFileDialog.CreatePrompt) flags |= OFN_CREATEPROMPT; if (!saveFileDialog.DereferenceLinks) flags |= OFN_NODEREFERENCELINKS; if (saveFileDialog.CheckFileExists) flags |= OFN_PATHMUSTEXIST; if (saveFileDialog.ShowHelp) flags |= OFN_SHOWHELP; openFileName.Flags = flags; openFileName.nFileOffset = 0; openFileName.nFileExtension = 0; std::wstring defaultExt = saveFileDialog.DefaultExt().w_str(); openFileName.lpstrDefExt = defaultExt.c_str(); if (!GetSaveFileName(&openFileName)) return false; saveFileDialog.FileName = fileName; return true; } #endif
gpl-3.0
tonilogar/ToolsPcot
OpePcot/identificadorcoordenadas.cpp
2
2072
// DepuPcot // Copyright (C) {2014} {Antonio López García} // tologar@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 "identificadorcoordenadas.h" IdentificadorCoordenadas::IdentificadorCoordenadas(QObject *parent) : QObject(parent) { _identificador=QString(); //Estos valores a -1, en realidad deben de ser valores //que no sean valores validos dentro del sistema _xa=-1; _ya=-1; _xb=-1; _yb=-1; } IdentificadorCoordenadas::IdentificadorCoordenadas(QObject *parent, QString identificador,double xa, double ya,double xb, double yb) { _identificador=identificador; _xa=xa; _ya=ya; _xb=xb; _yb=yb; } //Getter QString IdentificadorCoordenadas::getIdentificador() { return _identificador; } double IdentificadorCoordenadas::getXa() { return _xa; } double IdentificadorCoordenadas::getYa() { return _ya; } double IdentificadorCoordenadas::getXb() { return _xb; } double IdentificadorCoordenadas::getYb() { return _yb; } //Setter void IdentificadorCoordenadas::setIdentificador(QString identificador) { _identificador=identificador; } void IdentificadorCoordenadas::setXa(double xa) { _xa=xa; } void IdentificadorCoordenadas::setYa(double ya) { _ya=ya; } void IdentificadorCoordenadas::setXb(double xb) { _xb=xb; } void IdentificadorCoordenadas::setYb(double yb) { _yb=yb; }
gpl-3.0
konopka90/freeablo
apps/launcher/mainwindow.cpp
2
4606
#include "ui_mainwindow.h" #include "mainwindow.h" #include <QListWidgetItem> #include <QMessageBox> #include <QDir> #include <QFile> #include "playpage.h" #include "graphicspage.h" namespace Launcher { MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setupListWidget(); createIcons(); ui->pagesWidget->setCurrentIndex(0); connect(ui->closeButton, SIGNAL(clicked(bool)), this, SLOT(close())); connect(ui->playButton, SIGNAL(clicked(bool)), this, SLOT(play())); mSettings.loadUserSettings(); mPlayPage = QSharedPointer<PlayPage>(new PlayPage(ui, mSettings)); mGraphicsPage = QSharedPointer<GraphicsPage>(new GraphicsPage(ui, mSettings)); mPlayPage->loadSettings(); mGraphicsPage->loadSettings(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::setupListWidget() { ui->listWidget->setViewMode(QListView::IconMode); ui->listWidget->setWrapping(false); ui->listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->listWidget->setIconSize(QSize(48, 48)); ui->listWidget->setMovement(QListView::Static); ui->listWidget->setSpacing(4); ui->listWidget->setCurrentRow(0); ui->listWidget->setFlow(QListView::LeftToRight); } void MainWindow::createIcons() { QPixmap playPixmap("resources/launcher/play.png"); QIcon playIcon(playPixmap); QListWidgetItem *playButton = new QListWidgetItem(ui->listWidget); playButton->setIcon(playIcon); playButton->setText(tr("Play")); playButton->setTextAlignment(Qt::AlignCenter); playButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QPixmap graphicsPixmap("resources/launcher/graphics.png"); QIcon graphicsIcon(graphicsPixmap); QListWidgetItem *graphicsButton = new QListWidgetItem(ui->listWidget); graphicsButton->setIcon(graphicsIcon); graphicsButton->setText(tr("Graphics")); graphicsButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); connect(ui->listWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(changePage(QListWidgetItem*,QListWidgetItem*))); ui->listWidget->setCurrentRow(0); } void MainWindow::play() { if(!writeSettings()) qApp->quit(); if(!mPlayPage->hasMaster()) { QMessageBox msgBox; msgBox.setWindowTitle(tr("No game file selected")); msgBox.setIcon(QMessageBox::Warning); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setText(tr("<br><b>You do not have a game file selected.</b><br><br> \ Freeablo will not start without a game file selected.<br>")); msgBox.exec(); return; } if(mProcessInvoker.startProcess(QLatin1String("freeablo"),true)) return qApp->quit(); } void MainWindow::changePage(QListWidgetItem * current, QListWidgetItem * previous) { if (!current) current = previous; int currentIndex = ui->listWidget->row(current); ui->pagesWidget->setCurrentIndex(currentIndex); } bool MainWindow::writeSettings() { mPlayPage->saveSettings(); mGraphicsPage->saveSettings(); QString userPath = QString::fromUtf8(Settings::Settings::USER_DIR.c_str()); QDir dir(userPath); if (!dir.exists()) { QMessageBox msgBox; msgBox.setWindowTitle(tr("Error reading Freeablo configuration directory")); msgBox.setIcon(QMessageBox::Critical); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setText(tr("<br><b>Could not read \"%0\"</b><br><br> \ Could not read \"%0\".<br>").arg(userPath)); msgBox.exec(); return false; } QFile file(Settings::Settings::USER_PATH.c_str()); if (!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)) { // File cannot be opened or created QMessageBox msgBox; msgBox.setWindowTitle(tr("Error writing Freeablo configuration file")); msgBox.setIcon(QMessageBox::Critical); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setText(tr("<br><b>Could not open or create %0 for writing</b><br><br> \ Please make sure you have the right permissions \ and try again.<br>").arg(file.fileName())); msgBox.exec(); return false; } return mSettings.save(); } void MainWindow::closeEvent(QCloseEvent *event) { writeSettings(); event->accept(); } }
gpl-3.0
Daedalus12/brewtarget
src/mashstep.cpp
2
7866
/* * mashstep.cpp is part of Brewtarget, and is Copyright the following * authors 2009-2014 * - Philip Greggory Lee <rocketman768@gmail.com> * * Brewtarget 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. * * Brewtarget 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 <QVector> #include "mashstep.h" #include "brewtarget.h" QStringList MashStep::types = QStringList() << "Infusion" << "Temperature" << "Decoction"; QStringList MashStep::typesTr = QStringList() << QObject::tr("Infusion") << QObject::tr("Temperature") << QObject::tr("Decoction"); QHash<QString,QString> MashStep::tagToProp = MashStep::tagToPropHash(); QHash<QString,QString> MashStep::tagToPropHash() { QHash<QString,QString> propHash; propHash["NAME"] = "name"; //propHash["TYPE"] = "type"; propHash["INFUSE_AMOUNT"] = "infuseAmount_l"; propHash["STEP_TEMP"] = "stepTemp_c"; propHash["STEP_TIME"] = "stepTime_min"; propHash["RAMP_TIME"] = "rampTime_min"; propHash["END_TEMP"] = "endTemp_c"; propHash["INFUSE_TEMP"] = "infuseTemp_c"; propHash["DECOCTION_AMOUNT"] = "decoctionAmount_l"; return propHash; } bool operator<(MashStep &m1, MashStep &m2) { return m1.name() < m2.name(); } bool operator==(MashStep &m1, MashStep &m2) { return m1.name() == m2.name(); } //==============================CONSTRUCTORS==================================== /* void MashStep::setDefaults() { name = ""; type = TYPEINFUSION; infuseAmount_l = 0.0; infuseTemp_c = 0.0; stepTemp_c = 0.0; stepTime_min = 0.0; rampTime_min = 0.0; endTemp_c = 0.0; decoctionAmount_l = 0.0; } */ MashStep::MashStep() : BeerXMLElement() { } /* void MashStep::fromNode(const QDomNode& mashStepNode) { QDomNode node, child; QDomText textNode; QString property, value; setDefaults(); for( node = mashStepNode.firstChild(); ! node.isNull(); node = node.nextSibling() ) { if( ! node.isElement() ) { Brewtarget::log(Brewtarget::WARNING, QObject::tr("Node at line %1 is not an element.").arg(textNode.lineNumber()) ); continue; } child = node.firstChild(); if( child.isNull() || ! child.isText() ) continue; property = node.nodeName(); textNode = child.toText(); value = textNode.nodeValue(); if( property == "NAME" ) { name = value; } else if( property == "VERSION" ) { if( version != getInt(textNode) ) Brewtarget::log(Brewtarget::ERROR, QObject::tr("YEAST says it is not version %1. Line %2").arg(version).arg(textNode.lineNumber()) ); } else if( property == "TYPE" ) { int ndx = types.indexOf(value); if( ndx < 0 ) Brewtarget::log(Brewtarget::ERROR, QObject::tr("%1 is not a valid type for MASHSTEP. Line %2").arg(value).arg(textNode.lineNumber()) ); else setType(static_cast<MashStep::Type>(ndx)); } else if( property == "INFUSE_AMOUNT" ) { setInfuseAmount_l(getDouble(textNode)); } else if( property == "STEP_TEMP" ) { setStepTemp_c(getDouble(textNode)); } else if( property == "STEP_TIME" ) { setStepTime_min(getDouble(textNode)); } else if( property == "RAMP_TIME" ) { setRampTime_min(getDouble(textNode)); } else if( property == "END_TEMP" ) { setEndTemp_c(getDouble(textNode)); } else if( property == "INFUSE_TEMP" ) { setInfuseTemp_c(getDouble(textNode)); } else if( property == "DECOCTION_AMOUNT" ) { setDecoctionAmount_l(getDouble(textNode)); } else Brewtarget::log(Brewtarget::WARNING, QObject::tr("Unsupported MASHSTEP property: %1. Line %2").arg(property).arg(node.lineNumber()) ); } } */ //================================"SET" METHODS================================= void MashStep::setName( const QString &var ) { set("name", "name", var); emit changedName(var); } void MashStep::setInfuseTemp_c(double var) { set("infuseTemp_c", "infuse_temp", var); } void MashStep::setType( Type t ) { set("type", "mstype", types.at(t)); } void MashStep::setInfuseAmount_l( double var ) { if( var < 0.0 ) { Brewtarget::logW( QString("Mashstep: number cannot be negative: %1").arg(var) ); return; } else { set("infuseAmount_l", "infuse_amount", var); } } void MashStep::setStepTemp_c( double var ) { if( var < -273.15 ) { Brewtarget::logW( QString("Mashstep: temp below absolute zero: %1").arg(var) ); return; } else { set("stepTemp_c", "step_temp", var); } } void MashStep::setStepTime_min( double var ) { if( var < 0.0 ) { Brewtarget::logW( QString("Mashstep: step time cannot be negative: %1").arg(var) ); return; } else { set("stepTime_min", "step_time", var); } } void MashStep::setRampTime_min( double var ) { if( var < 0.0 ) { Brewtarget::logW( QString("Mashstep: ramp time cannot be negative: %1").arg(var) ); return; } else { set("rampTime_min", "ramp_time", var); } } void MashStep::setEndTemp_c( double var ) { if( var < -273.15 ) { Brewtarget::logW( QString("Mashstep: temp below absolute zero: %1").arg(var) ); return; } else { set("endTemp_c", "end_temp", var); } } void MashStep::setDecoctionAmount_l(double var) { set("decoctionAmount_l", "decoction_amount", var); } //============================="GET" METHODS==================================== QString MashStep::name() const { return get("name").toString(); } MashStep::Type MashStep::type() const { return static_cast<MashStep::Type>(types.indexOf(get("mstype").toString())); } const QString MashStep::typeString() const { return get("mstype").toString(); } const QString MashStep::typeStringTr() const { return typesTr.at(type()); } double MashStep::infuseTemp_c() const { return Brewtarget::toDouble(get("infuse_temp").toString(), "MashStep::infuseTemp_c()"); } double MashStep::infuseAmount_l() const { return Brewtarget::toDouble(get("infuse_amount").toString(), "MashStep::infuseAmount_l()"); } double MashStep::stepTemp_c() const { return Brewtarget::toDouble(get("step_temp").toString(), "MashStep::stepTemp_c()"); } double MashStep::stepTime_min() const { return Brewtarget::toDouble(get("step_time").toString(), "MashStep::stepTime_min()"); } double MashStep::rampTime_min() const { return Brewtarget::toDouble(get("ramp_time").toString(), "MashStep::rampTime_min()"); } double MashStep::endTemp_c() const { return Brewtarget::toDouble(get("end_temp").toString(), "MashStep::endTemp_c()"); } double MashStep::decoctionAmount_l() const { return Brewtarget::toDouble(get("decoction_amount").toString(), "MashStep::decoctionAmount_l()"); } int MashStep::stepNumber() const { return get("step_number").toInt(); } bool MashStep::isValidType( const QString &str ) const { static const QString types[] = {"Infusion", "Temperature", "Decoction"}; static const unsigned int size = 3; unsigned int i; for( i = 0; i < size; ++i ) if( str == types[i] ) return true; return false; }
gpl-3.0
binghongcha08/pyQMD
QMC/MC_exchange/permute_variation/mod.f90
2
1281
module sci implicit real*8(a-h,o-z) real*8, public, parameter :: pi = 4.d0*atan(1.d0) complex*16, public, parameter :: im=(0d0,1d0) real (kind = 8), parameter :: half = 0.5d0 real (kind = 8), parameter :: one = 1d0 real (kind = 8), parameter :: au2k = 3.2d5 integer*4 :: nb ! number of basis in the linear fitting end module ! --- parameters for Monte Carlo integration module Monte implicit none real (kind = 8) :: pSum, eSqdSum, envSum, enkSum, envpSum, enkpSum, rDpSum real (kind = 8) :: pSqdSum, hSqdSum integer*4 :: nAccept integer (kind = 4), parameter :: nx = 400 ! only used for one-dimensional problem integer (kind = 8), parameter :: NWalkers = 20, MCSteps = 1000000 integer (kind = 8) idum real (kind = 8) xmin, xmax, dx real (kind = 8) delta integer (kind = 8), parameter :: ndim = 3 end module ! --- parameters associated with AQP calculation module AQP use Monte, only : ndim implicit none real (kind = 8), dimension(ndim,ndim) :: rb real (kind = 8), dimension(ndim) :: ra, rc, rd save end module
gpl-3.0
minPSVSDK/VHL
hook/threadmgr.c
2
6592
/* threadmgr.c : Wraps calls to handle threads Copyright (C) 2015 hgoel0974 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <psp2/kernel/error.h> #include <psp2/kernel/threadmgr.h> #include <psp2/types.h> #include <string.h> #include <hook/threadmgr.h> #include <vhl.h> void initThreadmgr() { globals_t *globals = getGlobals(); globals->threadmgrSema = sceKernelCreateSema("vhlThreadmgrSema", 0, MAX_THREADS_NUM, MAX_THREADS_NUM, NULL); globals->threadmgrMutex = sceKernelCreateMutex("vhlThreadmgrMutex", 0, 0, NULL); } static int exitDeleteCb() { return hook_sceKernelExitDeleteThread(0); } static int hookEntry(SceSize args, void *argp) { SceKernelSemaInfo info; globals_t *globals; SceUID uid; int res; uid = sceKernelGetThreadId(); globals = getGlobals(); sceKernelLockMutexCB(globals->threadmgrMutex, 1, NULL); info.size = sizeof(info); res = sceKernelGetSemaInfo(globals->threadmgrSema, &info); if (res) goto fail; while (globals->threadmgrTable[info.currentCount].uid != uid) { if (info.currentCount >= info.maxCount) { res = SCE_KERNEL_ERROR_ERROR; goto fail; } info.currentCount++; } globals->threadmgrTable[info.currentCount].exitDeleteCb = sceKernelCreateCallback("vhlUserExitDeleteCb", 0, exitDeleteCb, NULL); sceKernelUnlockMutex(globals->threadmgrMutex, 1); return globals->threadmgrTable[info.currentCount].entry(args, argp); fail: sceKernelUnlockMutex(globals->threadmgrMutex, 1); return res; } SceUID hook_sceKernelCreateThread(const char *name, SceKernelThreadEntry entry, int initPriority, SceSize stackSize, SceUInt attr, int cpuAffinityMask, const SceKernelThreadOptParam *option) { SceKernelSemaInfo info; globals_t *globals; SceUID uid; int res; globals = getGlobals(); sceKernelLockMutexCB(globals->threadmgrMutex, 1, NULL); res = sceKernelPollSema(globals->threadmgrSema, 1); if (res) goto force; info.size = sizeof(info); res = sceKernelGetSemaInfo(globals->threadmgrSema, &info); if (res) goto force; uid = sceKernelCreateThread(name, hookEntry, initPriority, stackSize, attr, cpuAffinityMask, option); if (uid >= 0) { globals->threadmgrTable[info.currentCount].uid = uid; globals->threadmgrTable[info.currentCount].entry = entry; globals->threadmgrTable[info.currentCount].exitDeleteCb = SCE_KERNEL_ERROR_ERROR; } sceKernelUnlockMutex(globals->threadmgrMutex, 1); return uid; force: sceKernelUnlockMutex(globals->threadmgrMutex, 1); return sceKernelCreateThread(name, entry, initPriority, stackSize, attr, cpuAffinityMask, option); } int hook_sceKernelExitDeleteThread(int res) { SceKernelSemaInfo info; globals_t *globals; SceUID uid; int i; globals = getGlobals(); uid = sceKernelGetThreadId(); DEBUG_PRINTF("Exiting thread 0x%08X (res: 0x%08X)", uid, res); sceKernelLockMutex(globals->threadmgrMutex, 1, NULL); info.size = sizeof(info); i = sceKernelGetSemaInfo(globals->threadmgrSema, &info); if (i == 0) { for (i = info.currentCount; i < info.maxCount; i++) { if (globals->threadmgrTable[info.currentCount].uid == uid) { if (i != info.currentCount) memcpy(globals->threadmgrTable + i, globals->threadmgrTable + info.currentCount, sizeof(thInfo_t)); sceKernelSignalSema(globals->threadmgrSema, 1); break; } } } sceKernelUnlockMutex(globals->threadmgrMutex, 1); sceKernelDelayThread(16384); return sceKernelExitDeleteThread(res); } int terminateDeleteAllUserThreads() { SceKernelSemaInfo semaInfo; SceKernelThreadInfo threadInfo; globals_t *globals; int res; globals = getGlobals(); sceKernelLockMutex(globals->threadmgrMutex, 1, NULL); semaInfo.size = sizeof(semaInfo); res = sceKernelGetSemaInfo(globals->threadmgrSema, &semaInfo); if (res) return res; while (semaInfo.currentCount < semaInfo.maxCount) { res = sceKernelGetThreadInfo(globals->threadmgrTable[semaInfo.currentCount].uid, &threadInfo); if (res == 0 && (threadInfo.status == PSP2_THREAD_STOPPED || threadInfo.status == PSP2_THREAD_KILLED)) sceKernelDeleteThread(globals->threadmgrTable[semaInfo.currentCount].uid); else sceKernelNotifyCallback(globals->threadmgrTable[semaInfo.currentCount].exitDeleteCb, 0); semaInfo.currentCount++; } sceKernelUnlockMutex(globals->threadmgrMutex, 1); sceKernelWaitSema(globals->threadmgrSema, MAX_THREADS_NUM, NULL); sceKernelSignalSema(globals->threadmgrSema, MAX_THREADS_NUM); return 0; } int waitAllUserThreadsEndCB(SceUInt *timeout) { SceUID uid = getGlobals()->threadmgrSema; int res; res = sceKernelWaitSemaCB(uid, MAX_THREADS_NUM, timeout); if (res) return res; return sceKernelSignalSema(uid, MAX_THREADS_NUM); }
gpl-3.0
baoping/Red-Bull-Media-Player
3rdParty/src/taglib-1.6.1/taglib/mp4/mp4tag.cpp
2
17322
/************************************************************************** copyright : (C) 2007 by Lukáš Lalinský email : lalinsky@gmail.com **************************************************************************/ /*************************************************************************** * 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; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef WITH_MP4 #include <tdebug.h> #include <tstring.h> #include "mp4atom.h" #include "mp4tag.h" #include "id3v1genres.h" using namespace TagLib; class MP4::Tag::TagPrivate { public: TagPrivate() : file(0), atoms(0) {} ~TagPrivate() {} File *file; Atoms *atoms; ItemListMap items; }; MP4::Tag::Tag(File *file, MP4::Atoms *atoms) { d = new TagPrivate; d->file = file; d->atoms = atoms; MP4::Atom *ilst = atoms->find("moov", "udta", "meta", "ilst"); if(!ilst) { //debug("Atom moov.udta.meta.ilst not found."); return; } for(unsigned int i = 0; i < ilst->children.size(); i++) { MP4::Atom *atom = ilst->children[i]; file->seek(atom->offset + 8); if(atom->name == "----") { parseFreeForm(atom, file); } else if(atom->name == "trkn" || atom->name == "disk") { parseIntPair(atom, file); } else if(atom->name == "cpil" || atom->name == "pgap" || atom->name == "pcst") { parseBool(atom, file); } else if(atom->name == "tmpo") { parseInt(atom, file); } else if(atom->name == "gnre") { parseGnre(atom, file); } else if(atom->name == "covr") { parseCovr(atom, file); } else { parseText(atom, file); } } } MP4::Tag::~Tag() { delete d; } ByteVectorList MP4::Tag::parseData(MP4::Atom *atom, TagLib::File *file, int expectedFlags, bool freeForm) { ByteVectorList result; ByteVector data = file->readBlock(atom->length - 8); int i = 0; unsigned int pos = 0; while(pos < data.size()) { int length = data.mid(pos, 4).toUInt(); ByteVector name = data.mid(pos + 4, 4); int flags = data.mid(pos + 8, 4).toUInt(); if(freeForm && i < 2) { if(i == 0 && name != "mean") { debug("MP4: Unexpected atom \"" + name + "\", expecting \"mean\""); return result; } else if(i == 1 && name != "name") { debug("MP4: Unexpected atom \"" + name + "\", expecting \"name\""); return result; } result.append(data.mid(pos + 12, length - 12)); } else { if(name != "data") { debug("MP4: Unexpected atom \"" + name + "\", expecting \"data\""); return result; } if(expectedFlags == -1 || flags == expectedFlags) { result.append(data.mid(pos + 16, length - 16)); } } pos += length; i++; } return result; } void MP4::Tag::parseInt(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if(data.size()) { d->items.insert(atom->name, (int)data[0].toShort()); } } void MP4::Tag::parseGnre(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if(data.size()) { int idx = (int)data[0].toShort(); if(!d->items.contains("\251gen") && idx > 0) { d->items.insert("\251gen", StringList(ID3v1::genre(idx - 1))); } } } void MP4::Tag::parseIntPair(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if(data.size()) { int a = data[0].mid(2, 2).toShort(); int b = data[0].mid(4, 2).toShort(); d->items.insert(atom->name, MP4::Item(a, b)); } } void MP4::Tag::parseBool(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file); if(data.size()) { bool value = data[0].size() ? data[0][0] != '\0' : false; d->items.insert(atom->name, value); } } void MP4::Tag::parseText(MP4::Atom *atom, TagLib::File *file, int expectedFlags) { ByteVectorList data = parseData(atom, file, expectedFlags); if(data.size()) { StringList value; for(unsigned int i = 0; i < data.size(); i++) { value.append(String(data[i], String::UTF8)); } d->items.insert(atom->name, value); } } void MP4::Tag::parseFreeForm(MP4::Atom *atom, TagLib::File *file) { ByteVectorList data = parseData(atom, file, 1, true); if(data.size() > 2) { StringList value; for(unsigned int i = 2; i < data.size(); i++) { value.append(String(data[i], String::UTF8)); } String name = "----:" + data[0] + ':' + data[1]; d->items.insert(name, value); } } void MP4::Tag::parseCovr(MP4::Atom *atom, TagLib::File *file) { MP4::CoverArtList value; ByteVector data = file->readBlock(atom->length - 8); unsigned int pos = 0; while(pos < data.size()) { int length = data.mid(pos, 4).toUInt(); ByteVector name = data.mid(pos + 4, 4); int flags = data.mid(pos + 8, 4).toUInt(); if(name != "data") { debug("MP4: Unexpected atom \"" + name + "\", expecting \"data\""); return; } if(flags == MP4::CoverArt::PNG || flags == MP4::CoverArt::JPEG) { value.append(MP4::CoverArt(MP4::CoverArt::Format(flags), data.mid(pos + 16, length - 16))); } pos += length; } if(value.size() > 0) d->items.insert(atom->name, value); } ByteVector MP4::Tag::padIlst(const ByteVector &data, int length) { if (length == -1) { length = ((data.size() + 1023) & ~1023) - data.size(); } return renderAtom("free", ByteVector(length, '\1')); } ByteVector MP4::Tag::renderAtom(const ByteVector &name, const ByteVector &data) { return ByteVector::fromUInt(data.size() + 8) + name + data; } ByteVector MP4::Tag::renderData(const ByteVector &name, int flags, const ByteVectorList &data) { ByteVector result; for(unsigned int i = 0; i < data.size(); i++) { result.append(renderAtom("data", ByteVector::fromUInt(flags) + ByteVector(4, '\0') + data[i])); } return renderAtom(name, result); } ByteVector MP4::Tag::renderBool(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(1, item.toBool() ? '\1' : '\0')); return renderData(name, 0x15, data); } ByteVector MP4::Tag::renderInt(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector::fromShort(item.toInt())); return renderData(name, 0x15, data); } ByteVector MP4::Tag::renderIntPair(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(2, '\0') + ByteVector::fromShort(item.toIntPair().first) + ByteVector::fromShort(item.toIntPair().second) + ByteVector(2, '\0')); return renderData(name, 0x15, data); } ByteVector MP4::Tag::renderIntPairNoTrailing(const ByteVector &name, MP4::Item &item) { ByteVectorList data; data.append(ByteVector(2, '\0') + ByteVector::fromShort(item.toIntPair().first) + ByteVector::fromShort(item.toIntPair().second)); return renderData(name, 0x15, data); } ByteVector MP4::Tag::renderText(const ByteVector &name, MP4::Item &item, int flags) { ByteVectorList data; StringList value = item.toStringList(); for(unsigned int i = 0; i < value.size(); i++) { data.append(value[i].data(String::UTF8)); } return renderData(name, flags, data); } ByteVector MP4::Tag::renderCovr(const ByteVector &name, MP4::Item &item) { ByteVector data; MP4::CoverArtList value = item.toCoverArtList(); for(unsigned int i = 0; i < value.size(); i++) { data.append(renderAtom("data", ByteVector::fromUInt(value[i].format()) + ByteVector(4, '\0') + value[i].data())); } return renderAtom(name, data); } ByteVector MP4::Tag::renderFreeForm(const String &name, MP4::Item &item) { StringList header = StringList::split(name, ":"); if (header.size() != 3) { debug("MP4: Invalid free-form item name \"" + name + "\""); return ByteVector::null; } ByteVector data; data.append(renderAtom("mean", ByteVector::fromUInt(0) + header[1].data(String::UTF8))); data.append(renderAtom("name", ByteVector::fromUInt(0) + header[2].data(String::UTF8))); StringList value = item.toStringList(); for(unsigned int i = 0; i < value.size(); i++) { data.append(renderAtom("data", ByteVector::fromUInt(1) + ByteVector(4, '\0') + value[i].data(String::UTF8))); } return renderAtom("----", data); } bool MP4::Tag::save() { ByteVector data; for(MP4::ItemListMap::Iterator i = d->items.begin(); i != d->items.end(); i++) { const String name = i->first; if(name.startsWith("----")) { data.append(renderFreeForm(name, i->second)); } else if(name == "trkn") { data.append(renderIntPair(name.data(String::Latin1), i->second)); } else if(name == "disk") { data.append(renderIntPairNoTrailing(name.data(String::Latin1), i->second)); } else if(name == "cpil" || name == "pgap" || name == "pcst") { data.append(renderBool(name.data(String::Latin1), i->second)); } else if(name == "tmpo") { data.append(renderInt(name.data(String::Latin1), i->second)); } else if(name == "covr") { data.append(renderCovr(name.data(String::Latin1), i->second)); } else if(name.size() == 4){ data.append(renderText(name.data(String::Latin1), i->second)); } else { debug("MP4: Unknown item name \"" + name + "\""); } } data = renderAtom("ilst", data); AtomList path = d->atoms->path("moov", "udta", "meta", "ilst"); if(path.size() == 4) { saveExisting(data, path); } else { saveNew(data); } return true; } void MP4::Tag::updateParents(AtomList &path, long delta, int ignore) { for(unsigned int i = 0; i < path.size() - ignore; i++) { d->file->seek(path[i]->offset); long size = d->file->readBlock(4).toUInt(); // 64-bit if (size == 1) { d->file->seek(4, File::Current); // Skip name long long longSize = d->file->readBlock(8).toLongLong(); // Seek the offset of the 64-bit size d->file->seek(path[i]->offset + 8); d->file->writeBlock(ByteVector::fromLongLong(longSize + delta)); } // 32-bit else { d->file->seek(path[i]->offset); d->file->writeBlock(ByteVector::fromUInt(size + delta)); } } } void MP4::Tag::updateOffsets(long delta, long offset) { MP4::Atom *moov = d->atoms->find("moov"); if(moov) { MP4::AtomList stco = moov->findall("stco", true); for(unsigned int i = 0; i < stco.size(); i++) { MP4::Atom *atom = stco[i]; if(atom->offset > offset) { atom->offset += delta; } d->file->seek(atom->offset + 12); ByteVector data = d->file->readBlock(atom->length - 12); unsigned int count = data.mid(0, 4).toUInt(); d->file->seek(atom->offset + 16); int pos = 4; while(count--) { long o = data.mid(pos, 4).toUInt(); if(o > offset) { o += delta; } d->file->writeBlock(ByteVector::fromUInt(o)); pos += 4; } } MP4::AtomList co64 = moov->findall("co64", true); for(unsigned int i = 0; i < co64.size(); i++) { MP4::Atom *atom = co64[i]; if(atom->offset > offset) { atom->offset += delta; } d->file->seek(atom->offset + 12); ByteVector data = d->file->readBlock(atom->length - 12); unsigned int count = data.mid(0, 4).toUInt(); d->file->seek(atom->offset + 16); int pos = 4; while(count--) { long long o = data.mid(pos, 8).toLongLong(); if(o > offset) { o += delta; } d->file->writeBlock(ByteVector::fromLongLong(o)); pos += 8; } } } MP4::Atom *moof = d->atoms->find("moof"); if(moof) { MP4::AtomList tfhd = moof->findall("tfhd", true); for(unsigned int i = 0; i < tfhd.size(); i++) { MP4::Atom *atom = tfhd[i]; if(atom->offset > offset) { atom->offset += delta; } d->file->seek(atom->offset + 9); ByteVector data = d->file->readBlock(atom->offset - 9); unsigned int flags = (ByteVector(1, '\0') + data.mid(0, 3)).toUInt(); if(flags & 1) { long long o = data.mid(7, 8).toLongLong(); if(o > offset) { o += delta; } d->file->seek(atom->offset + 16); d->file->writeBlock(ByteVector::fromLongLong(o)); } } } } void MP4::Tag::saveNew(ByteVector &data) { data = renderAtom("meta", TagLib::ByteVector(4, '\0') + renderAtom("hdlr", TagLib::ByteVector(8, '\0') + TagLib::ByteVector("mdirappl") + TagLib::ByteVector(9, '\0')) + data + padIlst(data)); AtomList path = d->atoms->path("moov", "udta"); if(path.size() != 2) { path = d->atoms->path("moov"); data = renderAtom("udta", data); } long offset = path[path.size() - 1]->offset + 8; d->file->insert(data, offset, 0); updateParents(path, data.size()); updateOffsets(data.size(), offset); } void MP4::Tag::saveExisting(ByteVector &data, AtomList &path) { MP4::Atom *ilst = path[path.size() - 1]; long offset = ilst->offset; long length = ilst->length; MP4::Atom *meta = path[path.size() - 2]; AtomList::Iterator index = meta->children.find(ilst); // check if there is an atom before 'ilst', and possibly use it as padding if(index != meta->children.begin()) { AtomList::Iterator prevIndex = index; prevIndex--; MP4::Atom *prev = *prevIndex; if(prev->name == "free") { offset = prev->offset; length += prev->length; } } // check if there is an atom after 'ilst', and possibly use it as padding AtomList::Iterator nextIndex = index; nextIndex++; if(nextIndex != meta->children.end()) { MP4::Atom *next = *nextIndex; if(next->name == "free") { length += next->length; } } long delta = data.size() - length; if(delta > 0 || (delta < 0 && delta > -8)) { data.append(padIlst(data)); delta = data.size() - length; } else if(delta < 0) { data.append(padIlst(data, -delta - 8)); delta = 0; } d->file->insert(data, offset, length); if(delta) { updateParents(path, delta, 1); updateOffsets(delta, offset); } } String MP4::Tag::title() const { if(d->items.contains("\251nam")) return d->items["\251nam"].toStringList().toString(", "); return String::null; } String MP4::Tag::artist() const { if(d->items.contains("\251ART")) return d->items["\251ART"].toStringList().toString(", "); return String::null; } String MP4::Tag::album() const { if(d->items.contains("\251alb")) return d->items["\251alb"].toStringList().toString(", "); return String::null; } String MP4::Tag::comment() const { if(d->items.contains("\251cmt")) return d->items["\251cmt"].toStringList().toString(", "); return String::null; } String MP4::Tag::genre() const { if(d->items.contains("\251gen")) return d->items["\251gen"].toStringList().toString(", "); return String::null; } unsigned int MP4::Tag::year() const { if(d->items.contains("\251day")) return d->items["\251day"].toStringList().toString().toInt(); return 0; } unsigned int MP4::Tag::track() const { if(d->items.contains("trkn")) return d->items["trkn"].toIntPair().first; return 0; } void MP4::Tag::setTitle(const String &value) { d->items["\251nam"] = StringList(value); } void MP4::Tag::setArtist(const String &value) { d->items["\251ART"] = StringList(value); } void MP4::Tag::setAlbum(const String &value) { d->items["\251alb"] = StringList(value); } void MP4::Tag::setComment(const String &value) { d->items["\251cmt"] = StringList(value); } void MP4::Tag::setGenre(const String &value) { d->items["\251gen"] = StringList(value); } void MP4::Tag::setYear(uint value) { d->items["\251day"] = StringList(String::number(value)); } void MP4::Tag::setTrack(uint value) { d->items["trkn"] = MP4::Item(value, 0); } MP4::ItemListMap & MP4::Tag::itemListMap() { return d->items; } #endif
gpl-3.0
autc04/Retro68
gcc/libgfortran/generated/iall_i16.c
3
12928
/* Implementation of the IALL intrinsic Copyright (C) 2010-2019 Free Software Foundation, Inc. Contributed by Tobias Burnus <burnus@net-b.de> This file is part of the GNU Fortran runtime library (libgfortran). Libgfortran 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. Libgfortran 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. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ #include "libgfortran.h" #if defined (HAVE_GFC_INTEGER_16) && defined (HAVE_GFC_INTEGER_16) extern void iall_i16 (gfc_array_i16 * const restrict, gfc_array_i16 * const restrict, const index_type * const restrict); export_proto(iall_i16); void iall_i16 (gfc_array_i16 * const restrict retarray, gfc_array_i16 * const restrict array, const index_type * const restrict pdim) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type sstride[GFC_MAX_DIMENSIONS]; index_type dstride[GFC_MAX_DIMENSIONS]; const GFC_INTEGER_16 * restrict base; GFC_INTEGER_16 * restrict dest; index_type rank; index_type n; index_type len; index_type delta; index_type dim; int continue_loop; /* Make dim zero based to avoid confusion. */ rank = GFC_DESCRIPTOR_RANK (array) - 1; dim = (*pdim) - 1; if (unlikely (dim < 0 || dim > rank)) { runtime_error ("Dim argument incorrect in IALL intrinsic: " "is %ld, should be between 1 and %ld", (long int) dim + 1, (long int) rank + 1); } len = GFC_DESCRIPTOR_EXTENT(array,dim); if (len < 0) len = 0; delta = GFC_DESCRIPTOR_STRIDE(array,dim); for (n = 0; n < dim; n++) { sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n); extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); if (extent[n] < 0) extent[n] = 0; } for (n = dim; n < rank; n++) { sstride[n] = GFC_DESCRIPTOR_STRIDE(array, n + 1); extent[n] = GFC_DESCRIPTOR_EXTENT(array, n + 1); if (extent[n] < 0) extent[n] = 0; } if (retarray->base_addr == NULL) { size_t alloc_size, str; for (n = 0; n < rank; n++) { if (n == 0) str = 1; else str = GFC_DESCRIPTOR_STRIDE(retarray,n-1) * extent[n-1]; GFC_DIMENSION_SET(retarray->dim[n], 0, extent[n] - 1, str); } retarray->offset = 0; retarray->dtype.rank = rank; alloc_size = GFC_DESCRIPTOR_STRIDE(retarray,rank-1) * extent[rank-1]; retarray->base_addr = xmallocarray (alloc_size, sizeof (GFC_INTEGER_16)); if (alloc_size == 0) { /* Make sure we have a zero-sized array. */ GFC_DIMENSION_SET(retarray->dim[0], 0, -1, 1); return; } } else { if (rank != GFC_DESCRIPTOR_RANK (retarray)) runtime_error ("rank of return array incorrect in" " IALL intrinsic: is %ld, should be %ld", (long int) (GFC_DESCRIPTOR_RANK (retarray)), (long int) rank); if (unlikely (compile_options.bounds_check)) bounds_ifunction_return ((array_t *) retarray, extent, "return value", "IALL"); } for (n = 0; n < rank; n++) { count[n] = 0; dstride[n] = GFC_DESCRIPTOR_STRIDE(retarray,n); if (extent[n] <= 0) return; } base = array->base_addr; dest = retarray->base_addr; continue_loop = 1; while (continue_loop) { const GFC_INTEGER_16 * restrict src; GFC_INTEGER_16 result; src = base; { result = (GFC_INTEGER_16) -1; if (len <= 0) *dest = 0; else { #if ! defined HAVE_BACK_ARG for (n = 0; n < len; n++, src += delta) { #endif result &= *src; } *dest = result; } } /* Advance to the next element. */ count[0]++; base += sstride[0]; dest += dstride[0]; n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ base -= sstride[n] * extent[n]; dest -= dstride[n] * extent[n]; n++; if (n >= rank) { /* Break out of the loop. */ continue_loop = 0; break; } else { count[n]++; base += sstride[n]; dest += dstride[n]; } } } } extern void miall_i16 (gfc_array_i16 * const restrict, gfc_array_i16 * const restrict, const index_type * const restrict, gfc_array_l1 * const restrict); export_proto(miall_i16); void miall_i16 (gfc_array_i16 * const restrict retarray, gfc_array_i16 * const restrict array, const index_type * const restrict pdim, gfc_array_l1 * const restrict mask) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type sstride[GFC_MAX_DIMENSIONS]; index_type dstride[GFC_MAX_DIMENSIONS]; index_type mstride[GFC_MAX_DIMENSIONS]; GFC_INTEGER_16 * restrict dest; const GFC_INTEGER_16 * restrict base; const GFC_LOGICAL_1 * restrict mbase; index_type rank; index_type dim; index_type n; index_type len; index_type delta; index_type mdelta; int mask_kind; if (mask == NULL) { #ifdef HAVE_BACK_ARG iall_i16 (retarray, array, pdim, back); #else iall_i16 (retarray, array, pdim); #endif return; } dim = (*pdim) - 1; rank = GFC_DESCRIPTOR_RANK (array) - 1; if (unlikely (dim < 0 || dim > rank)) { runtime_error ("Dim argument incorrect in IALL intrinsic: " "is %ld, should be between 1 and %ld", (long int) dim + 1, (long int) rank + 1); } len = GFC_DESCRIPTOR_EXTENT(array,dim); if (len <= 0) return; mbase = mask->base_addr; mask_kind = GFC_DESCRIPTOR_SIZE (mask); if (mask_kind == 1 || mask_kind == 2 || mask_kind == 4 || mask_kind == 8 #ifdef HAVE_GFC_LOGICAL_16 || mask_kind == 16 #endif ) mbase = GFOR_POINTER_TO_L1 (mbase, mask_kind); else runtime_error ("Funny sized logical array"); delta = GFC_DESCRIPTOR_STRIDE(array,dim); mdelta = GFC_DESCRIPTOR_STRIDE_BYTES(mask,dim); for (n = 0; n < dim; n++) { sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n); mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask,n); extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); if (extent[n] < 0) extent[n] = 0; } for (n = dim; n < rank; n++) { sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n + 1); mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask, n + 1); extent[n] = GFC_DESCRIPTOR_EXTENT(array, n + 1); if (extent[n] < 0) extent[n] = 0; } if (retarray->base_addr == NULL) { size_t alloc_size, str; for (n = 0; n < rank; n++) { if (n == 0) str = 1; else str= GFC_DESCRIPTOR_STRIDE(retarray,n-1) * extent[n-1]; GFC_DIMENSION_SET(retarray->dim[n], 0, extent[n] - 1, str); } alloc_size = GFC_DESCRIPTOR_STRIDE(retarray,rank-1) * extent[rank-1]; retarray->offset = 0; retarray->dtype.rank = rank; if (alloc_size == 0) { /* Make sure we have a zero-sized array. */ GFC_DIMENSION_SET(retarray->dim[0], 0, -1, 1); return; } else retarray->base_addr = xmallocarray (alloc_size, sizeof (GFC_INTEGER_16)); } else { if (rank != GFC_DESCRIPTOR_RANK (retarray)) runtime_error ("rank of return array incorrect in IALL intrinsic"); if (unlikely (compile_options.bounds_check)) { bounds_ifunction_return ((array_t *) retarray, extent, "return value", "IALL"); bounds_equal_extents ((array_t *) mask, (array_t *) array, "MASK argument", "IALL"); } } for (n = 0; n < rank; n++) { count[n] = 0; dstride[n] = GFC_DESCRIPTOR_STRIDE(retarray,n); if (extent[n] <= 0) return; } dest = retarray->base_addr; base = array->base_addr; while (base) { const GFC_INTEGER_16 * restrict src; const GFC_LOGICAL_1 * restrict msrc; GFC_INTEGER_16 result; src = base; msrc = mbase; { result = 0; for (n = 0; n < len; n++, src += delta, msrc += mdelta) { if (*msrc) result &= *src; } *dest = result; } /* Advance to the next element. */ count[0]++; base += sstride[0]; mbase += mstride[0]; dest += dstride[0]; n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ base -= sstride[n] * extent[n]; mbase -= mstride[n] * extent[n]; dest -= dstride[n] * extent[n]; n++; if (n >= rank) { /* Break out of the loop. */ base = NULL; break; } else { count[n]++; base += sstride[n]; mbase += mstride[n]; dest += dstride[n]; } } } } extern void siall_i16 (gfc_array_i16 * const restrict, gfc_array_i16 * const restrict, const index_type * const restrict, GFC_LOGICAL_4 *); export_proto(siall_i16); void siall_i16 (gfc_array_i16 * const restrict retarray, gfc_array_i16 * const restrict array, const index_type * const restrict pdim, GFC_LOGICAL_4 * mask) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type dstride[GFC_MAX_DIMENSIONS]; GFC_INTEGER_16 * restrict dest; index_type rank; index_type n; index_type dim; if (mask == NULL || *mask) { #ifdef HAVE_BACK_ARG iall_i16 (retarray, array, pdim, back); #else iall_i16 (retarray, array, pdim); #endif return; } /* Make dim zero based to avoid confusion. */ dim = (*pdim) - 1; rank = GFC_DESCRIPTOR_RANK (array) - 1; if (unlikely (dim < 0 || dim > rank)) { runtime_error ("Dim argument incorrect in IALL intrinsic: " "is %ld, should be between 1 and %ld", (long int) dim + 1, (long int) rank + 1); } for (n = 0; n < dim; n++) { extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); if (extent[n] <= 0) extent[n] = 0; } for (n = dim; n < rank; n++) { extent[n] = GFC_DESCRIPTOR_EXTENT(array,n + 1); if (extent[n] <= 0) extent[n] = 0; } if (retarray->base_addr == NULL) { size_t alloc_size, str; for (n = 0; n < rank; n++) { if (n == 0) str = 1; else str = GFC_DESCRIPTOR_STRIDE(retarray,n-1) * extent[n-1]; GFC_DIMENSION_SET(retarray->dim[n], 0, extent[n] - 1, str); } retarray->offset = 0; retarray->dtype.rank = rank; alloc_size = GFC_DESCRIPTOR_STRIDE(retarray,rank-1) * extent[rank-1]; if (alloc_size == 0) { /* Make sure we have a zero-sized array. */ GFC_DIMENSION_SET(retarray->dim[0], 0, -1, 1); return; } else retarray->base_addr = xmallocarray (alloc_size, sizeof (GFC_INTEGER_16)); } else { if (rank != GFC_DESCRIPTOR_RANK (retarray)) runtime_error ("rank of return array incorrect in" " IALL intrinsic: is %ld, should be %ld", (long int) (GFC_DESCRIPTOR_RANK (retarray)), (long int) rank); if (unlikely (compile_options.bounds_check)) { for (n=0; n < rank; n++) { index_type ret_extent; ret_extent = GFC_DESCRIPTOR_EXTENT(retarray,n); if (extent[n] != ret_extent) runtime_error ("Incorrect extent in return value of" " IALL intrinsic in dimension %ld:" " is %ld, should be %ld", (long int) n + 1, (long int) ret_extent, (long int) extent[n]); } } } for (n = 0; n < rank; n++) { count[n] = 0; dstride[n] = GFC_DESCRIPTOR_STRIDE(retarray,n); } dest = retarray->base_addr; while(1) { *dest = 0; count[0]++; dest += dstride[0]; n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ dest -= dstride[n] * extent[n]; n++; if (n >= rank) return; else { count[n]++; dest += dstride[n]; } } } } #endif
gpl-3.0
madevgeny/cppcheck
gui/settingsdialog.cpp
3
11640
/* * 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 <QDialog> #include <QWidget> #include <QList> #include <QListWidgetItem> #include <QSettings> #include <QFileDialog> #include <QThread> #include "settingsdialog.h" #include "applicationdialog.h" #include "applicationlist.h" #include "translationhandler.h" #include "common.h" SettingsDialog::SettingsDialog(ApplicationList *list, TranslationHandler *translator, QWidget *parent) : QDialog(parent), mApplications(list), mTempApplications(new ApplicationList(this)), mTranslator(translator) { mUI.setupUi(this); QSettings settings; mTempApplications->Copy(list); mUI.mJobs->setText(settings.value(SETTINGS_CHECK_THREADS, 1).toString()); mUI.mForce->setCheckState(BoolToCheckState(settings.value(SETTINGS_CHECK_FORCE, false).toBool())); mUI.mShowFullPath->setCheckState(BoolToCheckState(settings.value(SETTINGS_SHOW_FULL_PATH, false).toBool())); mUI.mShowNoErrorsMessage->setCheckState(BoolToCheckState(settings.value(SETTINGS_SHOW_NO_ERRORS, false).toBool())); mUI.mShowDebugWarnings->setCheckState(BoolToCheckState(settings.value(SETTINGS_SHOW_DEBUG_WARNINGS, false).toBool())); mUI.mSaveAllErrors->setCheckState(BoolToCheckState(settings.value(SETTINGS_SAVE_ALL_ERRORS, false).toBool())); mUI.mSaveFullPath->setCheckState(BoolToCheckState(settings.value(SETTINGS_SAVE_FULL_PATH, false).toBool())); mUI.mInlineSuppressions->setCheckState(BoolToCheckState(settings.value(SETTINGS_INLINE_SUPPRESSIONS, false).toBool())); mUI.mEnableInconclusive->setCheckState(BoolToCheckState(settings.value(SETTINGS_INCONCLUSIVE_ERRORS, false).toBool())); mUI.mShowErrorId->setCheckState(BoolToCheckState(settings.value(SETTINGS_SHOW_ERROR_ID, false).toBool())); connect(mUI.mButtons, SIGNAL(accepted()), this, SLOT(Ok())); connect(mUI.mButtons, SIGNAL(rejected()), this, SLOT(reject())); connect(mUI.mBtnAddApplication, SIGNAL(clicked()), this, SLOT(AddApplication())); connect(mUI.mBtnRemoveApplication, SIGNAL(clicked()), this, SLOT(RemoveApplication())); connect(mUI.mBtnEditApplication, SIGNAL(clicked()), this, SLOT(EditApplication())); connect(mUI.mBtnDefaultApplication, SIGNAL(clicked()), this, SLOT(DefaultApplication())); connect(mUI.mListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(EditApplication())); connect(mUI.mBtnAddIncludePath, SIGNAL(clicked()), this, SLOT(AddIncludePath())); connect(mUI.mBtnRemoveIncludePath, SIGNAL(clicked()), this, SLOT(RemoveIncludePath())); connect(mUI.mBtnEditIncludePath, SIGNAL(clicked()), this, SLOT(EditIncludePath())); mUI.mListWidget->setSortingEnabled(false); PopulateApplicationList(); const int count = QThread::idealThreadCount(); if (count != -1) mUI.mLblIdealThreads->setText(QString::number(count)); else mUI.mLblIdealThreads->setText(tr("N/A")); LoadSettings(); InitTranslationsList(); InitIncludepathsList(); } SettingsDialog::~SettingsDialog() { SaveSettings(); } void SettingsDialog::AddIncludePath(const QString &path) { if (path.isNull() || path.isEmpty()) return; QListWidgetItem *item = new QListWidgetItem(path); item->setFlags(item->flags() | Qt::ItemIsEditable); mUI.mListIncludePaths->addItem(item); } void SettingsDialog::InitIncludepathsList() { QSettings settings; const QString allPaths = settings.value(SETTINGS_GLOBAL_INCLUDE_PATHS).toString(); const QStringList paths = allPaths.split(";", QString::SkipEmptyParts); foreach(QString path, paths) { AddIncludePath(path); } } void SettingsDialog::InitTranslationsList() { const QString current = mTranslator->GetCurrentLanguage(); QList<TranslationInfo> translations = mTranslator->GetTranslations(); foreach(TranslationInfo translation, translations) { QListWidgetItem *item = new QListWidgetItem; item->setText(translation.mName); item->setData(LangCodeRole, QVariant(translation.mCode)); mUI.mListLanguages->addItem(item); if (translation.mCode == current || translation.mCode == current.mid(0, 2)) mUI.mListLanguages->setCurrentItem(item); } } Qt::CheckState SettingsDialog::BoolToCheckState(bool yes) { if (yes) { return Qt::Checked; } return Qt::Unchecked; } bool SettingsDialog::CheckStateToBool(Qt::CheckState state) { if (state == Qt::Checked) { return true; } return false; } void SettingsDialog::LoadSettings() { QSettings settings; resize(settings.value(SETTINGS_CHECK_DIALOG_WIDTH, 800).toInt(), settings.value(SETTINGS_CHECK_DIALOG_HEIGHT, 600).toInt()); } void SettingsDialog::SaveSettings() const { QSettings settings; settings.setValue(SETTINGS_CHECK_DIALOG_WIDTH, size().width()); settings.setValue(SETTINGS_CHECK_DIALOG_HEIGHT, size().height()); } void SettingsDialog::SaveSettingValues() const { int jobs = mUI.mJobs->text().toInt(); if (jobs <= 0) { jobs = 1; } QSettings settings; settings.setValue(SETTINGS_CHECK_THREADS, jobs); SaveCheckboxValue(&settings, mUI.mForce, SETTINGS_CHECK_FORCE); SaveCheckboxValue(&settings, mUI.mSaveAllErrors, SETTINGS_SAVE_ALL_ERRORS); SaveCheckboxValue(&settings, mUI.mSaveFullPath, SETTINGS_SAVE_FULL_PATH); SaveCheckboxValue(&settings, mUI.mShowFullPath, SETTINGS_SHOW_FULL_PATH); SaveCheckboxValue(&settings, mUI.mShowNoErrorsMessage, SETTINGS_SHOW_NO_ERRORS); SaveCheckboxValue(&settings, mUI.mShowDebugWarnings, SETTINGS_SHOW_DEBUG_WARNINGS); SaveCheckboxValue(&settings, mUI.mInlineSuppressions, SETTINGS_INLINE_SUPPRESSIONS); SaveCheckboxValue(&settings, mUI.mEnableInconclusive, SETTINGS_INCONCLUSIVE_ERRORS); SaveCheckboxValue(&settings, mUI.mShowErrorId, SETTINGS_SHOW_ERROR_ID); const QListWidgetItem *currentLang = mUI.mListLanguages->currentItem(); if (currentLang) { const QString langcode = currentLang->data(LangCodeRole).toString(); settings.setValue(SETTINGS_LANGUAGE, langcode); } const int count = mUI.mListIncludePaths->count(); QString includePaths; for (int i = 0; i < count; i++) { QListWidgetItem *item = mUI.mListIncludePaths->item(i); includePaths += item->text(); includePaths += ";"; } settings.setValue(SETTINGS_GLOBAL_INCLUDE_PATHS, includePaths); } void SettingsDialog::SaveCheckboxValue(QSettings *settings, QCheckBox *box, const QString &name) { settings->setValue(name, CheckStateToBool(box->checkState())); } void SettingsDialog::AddApplication() { Application app; ApplicationDialog dialog(tr("Add a new application"), app, this); if (dialog.exec() == QDialog::Accepted) { mTempApplications->AddApplication(app); mUI.mListWidget->addItem(app.getName()); } } void SettingsDialog::RemoveApplication() { QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems(); foreach(QListWidgetItem *item, selected) { const int removeIndex = mUI.mListWidget->row(item); const int currentDefault = mTempApplications->GetDefaultApplication(); mTempApplications->RemoveApplication(removeIndex); if (removeIndex == currentDefault) // If default app is removed set default to unknown mTempApplications->SetDefault(-1); else if (removeIndex < currentDefault) // Move default app one up if earlier app was removed mTempApplications->SetDefault(currentDefault - 1); } mUI.mListWidget->clear(); PopulateApplicationList(); } void SettingsDialog::EditApplication() { QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems(); QListWidgetItem *item = 0; foreach(item, selected) { int row = mUI.mListWidget->row(item); Application& app = mTempApplications->GetApplication(row); ApplicationDialog dialog(tr("Modify an application"), app, this); if (dialog.exec() == QDialog::Accepted) { item->setText(app.getName()); } } } void SettingsDialog::DefaultApplication() { QList<QListWidgetItem *> selected = mUI.mListWidget->selectedItems(); if (!selected.isEmpty()) { int index = mUI.mListWidget->row(selected[0]); mTempApplications->SetDefault(index); mUI.mListWidget->clear(); PopulateApplicationList(); } } void SettingsDialog::PopulateApplicationList() { const int defapp = mTempApplications->GetDefaultApplication(); for (int i = 0; i < mTempApplications->GetApplicationCount(); i++) { const Application& app = mTempApplications->GetApplication(i); QString name = app.getName(); if (i == defapp) { name += " "; name += tr("[Default]"); } mUI.mListWidget->addItem(name); } // Select default application, or if there is no default app then the // first item. if (defapp == -1) mUI.mListWidget->setCurrentRow(0); else { if (mTempApplications->GetApplicationCount() > defapp) mUI.mListWidget->setCurrentRow(defapp); else mUI.mListWidget->setCurrentRow(0); } } void SettingsDialog::Ok() { mApplications->Copy(mTempApplications); accept(); } bool SettingsDialog::ShowFullPath() const { return CheckStateToBool(mUI.mShowFullPath->checkState()); } bool SettingsDialog::SaveFullPath() const { return CheckStateToBool(mUI.mSaveFullPath->checkState()); } bool SettingsDialog::SaveAllErrors() const { return CheckStateToBool(mUI.mSaveAllErrors->checkState()); } bool SettingsDialog::ShowNoErrorsMessage() const { return CheckStateToBool(mUI.mShowNoErrorsMessage->checkState()); } bool SettingsDialog::ShowErrorId() const { return CheckStateToBool(mUI.mShowErrorId->checkState()); } bool SettingsDialog::ShowInconclusive() const { return CheckStateToBool(mUI.mEnableInconclusive->checkState()); } void SettingsDialog::AddIncludePath() { QString selectedDir = QFileDialog::getExistingDirectory(this, tr("Select include directory"), GetPath(SETTINGS_LAST_INCLUDE_PATH)); if (!selectedDir.isEmpty()) { AddIncludePath(selectedDir); SetPath(SETTINGS_LAST_INCLUDE_PATH, selectedDir); } } void SettingsDialog::RemoveIncludePath() { const int row = mUI.mListIncludePaths->currentRow(); QListWidgetItem *item = mUI.mListIncludePaths->takeItem(row); delete item; } void SettingsDialog::EditIncludePath() { QListWidgetItem *item = mUI.mListIncludePaths->currentItem(); mUI.mListIncludePaths->editItem(item); }
gpl-3.0
iphydf/c-toxcore
toxav/rtp.c
3
31534
/* SPDX-License-Identifier: GPL-3.0-or-later * Copyright © 2016-2018 The TokTok team. * Copyright © 2013-2015 Tox project. */ #include "rtp.h" #include <assert.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include "bwcontroller.h" #include "../toxcore/Messenger.h" #include "../toxcore/ccompat.h" #include "../toxcore/logger.h" #include "../toxcore/mono_time.h" #include "../toxcore/util.h" /** * The number of milliseconds we want to keep a keyframe in the buffer for, * even though there are no free slots for incoming frames. */ #define VIDEO_KEEP_KEYFRAME_IN_BUFFER_FOR_MS 15 /** * return -1 on failure, 0 on success * */ static int rtp_send_custom_lossy_packet(Tox *tox, int32_t friendnumber, const uint8_t *data, uint32_t length) { Tox_Err_Friend_Custom_Packet error; tox_friend_send_lossy_packet(tox, friendnumber, data, (size_t)length, &error); if (error == TOX_ERR_FRIEND_CUSTOM_PACKET_OK) { return 0; } return -1; } // allocate_len is NOT including header! static struct RTPMessage *new_message(const struct RTPHeader *header, size_t allocate_len, const uint8_t *data, uint16_t data_length) { assert(allocate_len >= data_length); struct RTPMessage *msg = (struct RTPMessage *)calloc(1, sizeof(struct RTPMessage) + allocate_len); if (msg == nullptr) { return nullptr; } msg->len = data_length; // result without header msg->header = *header; memcpy(msg->data, data, msg->len); return msg; } /** * Instruct the caller to clear slot 0. */ #define GET_SLOT_RESULT_DROP_OLDEST_SLOT (-1) /** * Instruct the caller to drop the incoming packet. */ #define GET_SLOT_RESULT_DROP_INCOMING (-2) /** * Find the next free slot in work_buffer for the incoming data packet. * * - If the data packet belongs to a frame that's already in the work_buffer then * use that slot. * - If there is no free slot return GET_SLOT_RESULT_DROP_OLDEST_SLOT. * - If the data packet is too old return GET_SLOT_RESULT_DROP_INCOMING. * * If there is a keyframe being assembled in slot 0, keep it a bit longer and * do not kick it out right away if all slots are full instead kick out the new * incoming interframe. */ static int8_t get_slot(const Logger *log, struct RTPWorkBufferList *wkbl, bool is_keyframe, const struct RTPHeader *header, bool is_multipart) { if (is_multipart) { // This RTP message is part of a multipart frame, so we try to find an // existing slot with the previous parts of the frame in it. for (uint8_t i = 0; i < wkbl->next_free_entry; ++i) { const struct RTPWorkBuffer *slot = &wkbl->work_buffer[i]; if ((slot->buf->header.sequnum == header->sequnum) && (slot->buf->header.timestamp == header->timestamp)) { // Sequence number and timestamp match, so this slot belongs to // the same frame. // // In reality, these will almost certainly either both match or // both not match. Only if somehow there were 65535 frames // between, the timestamp will matter. return i; } } } // The message may or may not be part of a multipart frame. // // If it is part of a multipart frame, then this is an entirely new frame // for which we did not have a slot *or* the frame is so old that its slot // has been evicted by now. // // |----------- time -----------> // _________________ // slot 0 | | // ----------------- // _________________ // slot 1 | | // ----------------- // ____________ // slot 2 | | -> frame too old, drop // ------------ // // // // |----------- time -----------> // _________________ // slot 0 | | // ----------------- // _________________ // slot 1 | | // ----------------- // ____________ // slot 2 | | -> ok, start filling in a new slot // ------------ // If there is a free slot: if (wkbl->next_free_entry < USED_RTP_WORKBUFFER_COUNT) { // If there is at least one filled slot: if (wkbl->next_free_entry > 0) { // Get the most recently filled slot. const struct RTPWorkBuffer *slot = &wkbl->work_buffer[wkbl->next_free_entry - 1]; // If the incoming packet is older than our newest slot, drop it. // This is the first situation in the above diagram. if (slot->buf->header.timestamp > header->timestamp) { LOGGER_DEBUG(log, "workbuffer:2:timestamp too old"); return GET_SLOT_RESULT_DROP_INCOMING; } } // Not all slots are filled, and the packet is newer than our most // recent slot, so it's a new frame we want to start assembling. This is // the second situation in the above diagram. return wkbl->next_free_entry; } // If the incoming frame is a key frame, then stop assembling the oldest // slot, regardless of whether there was a keyframe in that or not. if (is_keyframe) { return GET_SLOT_RESULT_DROP_OLDEST_SLOT; } // The incoming slot is not a key frame, so we look at slot 0 to see what to // do next. const struct RTPWorkBuffer *slot = &wkbl->work_buffer[0]; // The incoming frame is not a key frame, but the existing slot 0 is also // not a keyframe, so we stop assembling the existing frame and make space // for the new one. if (!slot->is_keyframe) { return GET_SLOT_RESULT_DROP_OLDEST_SLOT; } // If this key frame is fully received, we also stop assembling and clear // slot 0. This also means sending the frame to the decoder. if (slot->received_len == slot->buf->header.data_length_full) { return GET_SLOT_RESULT_DROP_OLDEST_SLOT; } // This is a key frame, not fully received yet, but it's already much older // than the incoming frame, so we stop assembling it and send whatever part // we did receive to the decoder. if (slot->buf->header.timestamp + VIDEO_KEEP_KEYFRAME_IN_BUFFER_FOR_MS <= header->timestamp) { return GET_SLOT_RESULT_DROP_OLDEST_SLOT; } // This is a key frame, it's not too old yet, so we keep it in its slot for // a little longer. LOGGER_INFO(log, "keep KEYFRAME in workbuffer"); return GET_SLOT_RESULT_DROP_INCOMING; } /** * Returns an assembled frame (as much data as we currently have for this frame, * some pieces may be missing) * * If there are no frames ready, we return NULL. If this function returns * non-NULL, it transfers ownership of the message to the caller, i.e. the * caller is responsible for storing it elsewhere or calling `free()`. */ static struct RTPMessage *process_frame(const Logger *log, struct RTPWorkBufferList *wkbl, uint8_t slot_id) { assert(wkbl->next_free_entry >= 0); if (wkbl->next_free_entry == 0) { // There are no frames in any slot. return nullptr; } // Slot 0 contains a key frame, slot_id points at an interframe that is // relative to that key frame, so we don't use it yet. if (wkbl->work_buffer[0].is_keyframe && slot_id != 0) { LOGGER_DEBUG(log, "process_frame:KEYFRAME waiting in slot 0"); return nullptr; } // Either slot_id is 0 and slot 0 is a key frame, or there is no key frame // in slot 0 (and slot_id is anything). struct RTPWorkBuffer *const slot = &wkbl->work_buffer[slot_id]; // Move ownership of the frame out of the slot into m_new. struct RTPMessage *const m_new = slot->buf; slot->buf = nullptr; assert(wkbl->next_free_entry >= 1 && wkbl->next_free_entry <= USED_RTP_WORKBUFFER_COUNT); if (slot_id != wkbl->next_free_entry - 1) { // The slot is not the last slot, so we created a gap. We move all the // entries after it one step up. for (uint8_t i = slot_id; i < wkbl->next_free_entry - 1; ++i) { // Move entry (i+1) into entry (i). wkbl->work_buffer[i] = wkbl->work_buffer[i + 1]; } } // We now have a free entry at the end of the array. --wkbl->next_free_entry; // Clear the newly freed entry. const struct RTPWorkBuffer empty = {0}; wkbl->work_buffer[wkbl->next_free_entry] = empty; // Move ownership of the frame to the caller. return m_new; } /** * @param log A logger. * @param wkbl The list of in-progress frames, i.e. all the slots. * @param slot_id The slot we want to fill the data into. * @param is_keyframe Whether the data is part of a key frame. * @param header The RTP header from the incoming packet. * @param incoming_data The pure payload without header. * @param incoming_data_length The length in bytes of the incoming data payload. */ static bool fill_data_into_slot(const Logger *log, struct RTPWorkBufferList *wkbl, const uint8_t slot_id, bool is_keyframe, const struct RTPHeader *header, const uint8_t *incoming_data, uint16_t incoming_data_length) { // We're either filling the data into an existing slot, or in a new one that // is the next free entry. assert(slot_id <= wkbl->next_free_entry); struct RTPWorkBuffer *const slot = &wkbl->work_buffer[slot_id]; assert(header != nullptr); assert(is_keyframe == (bool)((header->flags & RTP_KEY_FRAME) != 0)); if (slot->received_len == 0) { assert(slot->buf == nullptr); // No data for this slot has been received, yet, so we create a new // message for it with enough memory for the entire frame. struct RTPMessage *msg = (struct RTPMessage *)calloc(1, sizeof(struct RTPMessage) + header->data_length_full); if (msg == nullptr) { LOGGER_ERROR(log, "Out of memory while trying to allocate for frame of size %u", (unsigned)header->data_length_full); // Out of memory: throw away the incoming data. return false; } // Unused in the new video receiving code, as it's 16 bit and can't hold // the full length of large frames. Instead, we use slot->received_len. msg->len = 0; msg->header = *header; slot->buf = msg; slot->is_keyframe = is_keyframe; slot->received_len = 0; assert(wkbl->next_free_entry < USED_RTP_WORKBUFFER_COUNT); ++wkbl->next_free_entry; } // We already checked this when we received the packet, but we rely on it // here, so assert again. assert(header->offset_full < header->data_length_full); // Copy the incoming chunk of data into the correct position in the full // frame data array. memcpy( slot->buf->data + header->offset_full, incoming_data, incoming_data_length ); // Update the total received length of this slot. slot->received_len += incoming_data_length; // Update received length also in the header of the message, for later use. slot->buf->header.received_length_full = slot->received_len; return slot->received_len == header->data_length_full; } static void update_bwc_values(const Logger *log, RTPSession *session, const struct RTPMessage *msg) { if (session->first_packets_counter < DISMISS_FIRST_LOST_VIDEO_PACKET_COUNT) { ++session->first_packets_counter; } else { const uint32_t data_length_full = msg->header.data_length_full; // without header const uint32_t received_length_full = msg->header.received_length_full; // without header bwc_add_recv(session->bwc, data_length_full); if (received_length_full < data_length_full) { LOGGER_DEBUG(log, "BWC: full length=%u received length=%d", data_length_full, received_length_full); bwc_add_lost(session->bwc, data_length_full - received_length_full); } } } /** * Handle a single RTP video packet. * * The packet may or may not be part of a multipart frame. This function will * find out and handle it appropriately. * * @param session The current RTP session with: * <code> * session->mcb == vc_queue_message() // this function is called from here * session->mp == struct RTPMessage * * session->cs == call->video.second // == VCSession created by vc_new() call * </code> * @param header The RTP header deserialised from the packet. * @param incoming_data The packet data *not* header, i.e. this is the actual * payload. * @param incoming_data_length The packet length *not* including header, i.e. * this is the actual payload length. * @param log A logger. * * @retval -1 on error. * @retval 0 on success. */ static int handle_video_packet(RTPSession *session, const struct RTPHeader *header, const uint8_t *incoming_data, uint16_t incoming_data_length, const Logger *log) { // Full frame length in bytes. The frame may be split into multiple packets, // but this value is the complete assembled frame size. const uint32_t full_frame_length = header->data_length_full; // Current offset in the frame. If this is the first packet of a multipart // frame or it's not a multipart frame, then this value is 0. const uint32_t offset = header->offset_full; // without header // The sender tells us whether this is a key frame. const bool is_keyframe = (header->flags & RTP_KEY_FRAME) != 0; LOGGER_DEBUG(log, "-- handle_video_packet -- full lens=%u len=%u offset=%u is_keyframe=%s", (unsigned)incoming_data_length, (unsigned)full_frame_length, (unsigned)offset, is_keyframe ? "K" : "."); LOGGER_DEBUG(log, "wkbl->next_free_entry:003=%d", session->work_buffer_list->next_free_entry); const bool is_multipart = full_frame_length != incoming_data_length; /* The message was sent in single part */ int8_t slot_id = get_slot(log, session->work_buffer_list, is_keyframe, header, is_multipart); LOGGER_DEBUG(log, "slot num=%d", slot_id); // get_slot told us to drop the packet, so we ignore it. if (slot_id == GET_SLOT_RESULT_DROP_INCOMING) { return -1; } // get_slot said there is no free slot. if (slot_id == GET_SLOT_RESULT_DROP_OLDEST_SLOT) { LOGGER_DEBUG(log, "there was no free slot, so we process the oldest frame"); // We now own the frame. struct RTPMessage *m_new = process_frame(log, session->work_buffer_list, 0); // The process_frame function returns NULL if there is no slot 0, i.e. // the work buffer list is completely empty. It can't be empty, because // get_slot just told us it's full, so process_frame must return non-null. assert(m_new != nullptr); LOGGER_DEBUG(log, "-- handle_video_packet -- CALLBACK-001a b0=%d b1=%d", (int)m_new->data[0], (int)m_new->data[1]); update_bwc_values(log, session, m_new); // Pass ownership of m_new to the callback. session->mcb(session->m->mono_time, session->cs, m_new); // Now we no longer own m_new. m_new = nullptr; // Now we must have a free slot, so we either get that slot, i.e. >= 0, // or get told to drop the incoming packet if it's too old. slot_id = get_slot(log, session->work_buffer_list, is_keyframe, header, /* is_multipart */false); if (slot_id == GET_SLOT_RESULT_DROP_INCOMING) { // The incoming frame is too old, so we drop it. return -1; } } // We must have a valid slot here. assert(slot_id >= 0); LOGGER_DEBUG(log, "fill_data_into_slot.1"); // fill in this part into the slot buffer at the correct offset if (!fill_data_into_slot( log, session->work_buffer_list, slot_id, is_keyframe, header, incoming_data, incoming_data_length)) { // Memory allocation failed. Return error. return -1; } struct RTPMessage *m_new = process_frame(log, session->work_buffer_list, slot_id); if (m_new != nullptr) { LOGGER_DEBUG(log, "-- handle_video_packet -- CALLBACK-003a b0=%d b1=%d", (int)m_new->data[0], (int)m_new->data[1]); update_bwc_values(log, session, m_new); session->mcb(session->m->mono_time, session->cs, m_new); m_new = nullptr; } return 0; } /** * @retval -1 on error. * @retval 0 on success. */ static int handle_rtp_packet(Messenger *m, uint32_t friendnumber, const uint8_t *data, uint16_t length, void *object) { RTPSession *session = (RTPSession *)object; if (session == nullptr || length < RTP_HEADER_SIZE + 1) { LOGGER_WARNING(m->log, "No session or invalid length of received buffer!"); return -1; } // Get the packet type. const uint8_t packet_type = data[0]; ++data; --length; // Unpack the header. struct RTPHeader header; rtp_header_unpack(data, &header); if (header.pt != packet_type % 128) { LOGGER_WARNING(m->log, "RTPHeader packet type and Tox protocol packet type did not agree: %d != %d", header.pt, packet_type % 128); return -1; } if (header.pt != session->payload_type % 128) { LOGGER_WARNING(m->log, "RTPHeader packet type does not match this session's payload type: %d != %d", header.pt, session->payload_type % 128); return -1; } if ((header.flags & RTP_LARGE_FRAME) != 0 && header.offset_full >= header.data_length_full) { LOGGER_ERROR(m->log, "Invalid video packet: frame offset (%u) >= full frame length (%u)", (unsigned)header.offset_full, (unsigned)header.data_length_full); return -1; } if (header.offset_lower >= header.data_length_lower) { LOGGER_ERROR(m->log, "Invalid old protocol video packet: frame offset (%u) >= full frame length (%u)", (unsigned)header.offset_lower, (unsigned)header.data_length_lower); return -1; } LOGGER_DEBUG(m->log, "header.pt %d, video %d", (uint8_t)header.pt, RTP_TYPE_VIDEO % 128); // The sender uses the new large-frame capable protocol and is sending a // video packet. if ((header.flags & RTP_LARGE_FRAME) != 0 && header.pt == (RTP_TYPE_VIDEO % 128)) { return handle_video_packet(session, &header, data + RTP_HEADER_SIZE, length - RTP_HEADER_SIZE, m->log); } // everything below here is for the old 16 bit protocol ------------------ if (header.data_length_lower == length - RTP_HEADER_SIZE) { /* The message is sent in single part */ /* Message is not late; pick up the latest parameters */ session->rsequnum = header.sequnum; session->rtimestamp = header.timestamp; bwc_add_recv(session->bwc, length); /* Invoke processing of active multiparted message */ if (session->mp != nullptr) { session->mcb(session->m->mono_time, session->cs, session->mp); session->mp = nullptr; } /* The message came in the allowed time; */ return session->mcb(session->m->mono_time, session->cs, new_message(&header, length - RTP_HEADER_SIZE, data + RTP_HEADER_SIZE, length - RTP_HEADER_SIZE)); } /* The message is sent in multiple parts */ if (session->mp != nullptr) { /* There are 2 possible situations in this case: * 1) being that we got the part of already processing message. * 2) being that we got the part of a new/old message. * * We handle them differently as we only allow a single multiparted * processing message */ if (session->mp->header.sequnum == header.sequnum && session->mp->header.timestamp == header.timestamp) { /* First case */ /* Make sure we have enough allocated memory */ if (session->mp->header.data_length_lower - session->mp->len < length - RTP_HEADER_SIZE || session->mp->header.data_length_lower <= header.offset_lower) { /* There happened to be some corruption on the stream; * continue wihtout this part */ return 0; } memcpy(session->mp->data + header.offset_lower, data + RTP_HEADER_SIZE, length - RTP_HEADER_SIZE); session->mp->len += length - RTP_HEADER_SIZE; bwc_add_recv(session->bwc, length); if (session->mp->len == session->mp->header.data_length_lower) { /* Received a full message; now push it for the further * processing. */ session->mcb(session->m->mono_time, session->cs, session->mp); session->mp = nullptr; } } else { /* Second case */ if (session->mp->header.timestamp > header.timestamp) { /* The received message part is from the old message; * discard it. */ return 0; } /* Push the previous message for processing */ session->mcb(session->m->mono_time, session->cs, session->mp); session->mp = nullptr; goto NEW_MULTIPARTED; } } else { /* In this case threat the message as if it was received in order */ /* This is also a point for new multiparted messages */ NEW_MULTIPARTED: /* Message is not late; pick up the latest parameters */ session->rsequnum = header.sequnum; session->rtimestamp = header.timestamp; bwc_add_recv(session->bwc, length); /* Store message. */ session->mp = new_message(&header, header.data_length_lower, data + RTP_HEADER_SIZE, length - RTP_HEADER_SIZE); if (session->mp != nullptr) { memmove(session->mp->data + header.offset_lower, session->mp->data, session->mp->len); } else { LOGGER_WARNING(m->log, "new_message() returned a null pointer"); return -1; } } return 0; } size_t rtp_header_pack(uint8_t *const rdata, const struct RTPHeader *header) { uint8_t *p = rdata; *p = (header->ve & 3) << 6 | (header->pe & 1) << 5 | (header->xe & 1) << 4 | (header->cc & 0xf); ++p; *p = (header->ma & 1) << 7 | (header->pt & 0x7f); ++p; p += net_pack_u16(p, header->sequnum); p += net_pack_u32(p, header->timestamp); p += net_pack_u32(p, header->ssrc); p += net_pack_u64(p, header->flags); p += net_pack_u32(p, header->offset_full); p += net_pack_u32(p, header->data_length_full); p += net_pack_u32(p, header->received_length_full); for (size_t i = 0; i < RTP_PADDING_FIELDS; ++i) { p += net_pack_u32(p, 0); } p += net_pack_u16(p, header->offset_lower); p += net_pack_u16(p, header->data_length_lower); assert(p == rdata + RTP_HEADER_SIZE); return p - rdata; } size_t rtp_header_unpack(const uint8_t *data, struct RTPHeader *header) { const uint8_t *p = data; header->ve = (*p >> 6) & 3; header->pe = (*p >> 5) & 1; header->xe = (*p >> 4) & 1; header->cc = *p & 0xf; ++p; header->ma = (*p >> 7) & 1; header->pt = *p & 0x7f; ++p; p += net_unpack_u16(p, &header->sequnum); p += net_unpack_u32(p, &header->timestamp); p += net_unpack_u32(p, &header->ssrc); p += net_unpack_u64(p, &header->flags); p += net_unpack_u32(p, &header->offset_full); p += net_unpack_u32(p, &header->data_length_full); p += net_unpack_u32(p, &header->received_length_full); p += sizeof(uint32_t) * RTP_PADDING_FIELDS; p += net_unpack_u16(p, &header->offset_lower); p += net_unpack_u16(p, &header->data_length_lower); assert(p == data + RTP_HEADER_SIZE); return p - data; } RTPSession *rtp_new(int payload_type, Messenger *m, Tox *tox, uint32_t friendnumber, BWController *bwc, void *cs, rtp_m_cb *mcb) { assert(mcb != nullptr); assert(cs != nullptr); assert(m != nullptr); RTPSession *session = (RTPSession *)calloc(1, sizeof(RTPSession)); if (session == nullptr) { LOGGER_WARNING(m->log, "Alloc failed! Program might misbehave!"); return nullptr; } session->work_buffer_list = (struct RTPWorkBufferList *)calloc(1, sizeof(struct RTPWorkBufferList)); if (session->work_buffer_list == nullptr) { LOGGER_ERROR(m->log, "out of memory while allocating work buffer list"); free(session); return nullptr; } // First entry is free. session->work_buffer_list->next_free_entry = 0; session->ssrc = payload_type == RTP_TYPE_VIDEO ? 0 : random_u32(m->rng); session->payload_type = payload_type; session->m = m; session->tox = tox; session->friend_number = friendnumber; // set NULL just in case session->mp = nullptr; session->first_packets_counter = 1; /* Also set payload type as prefix */ session->bwc = bwc; session->cs = cs; session->mcb = mcb; if (-1 == rtp_allow_receiving(session)) { LOGGER_WARNING(m->log, "Failed to start rtp receiving mode"); free(session->work_buffer_list); free(session); return nullptr; } return session; } void rtp_kill(RTPSession *session) { if (session == nullptr) { return; } LOGGER_DEBUG(session->m->log, "Terminated RTP session: %p", (void *)session); rtp_stop_receiving(session); LOGGER_DEBUG(session->m->log, "Terminated RTP session V3 work_buffer_list->next_free_entry: %d", (int)session->work_buffer_list->next_free_entry); for (int8_t i = 0; i < session->work_buffer_list->next_free_entry; ++i) { free(session->work_buffer_list->work_buffer[i].buf); } free(session->work_buffer_list); free(session); } int rtp_allow_receiving(RTPSession *session) { if (session == nullptr) { return -1; } if (m_callback_rtp_packet(session->m, session->friend_number, session->payload_type, handle_rtp_packet, session) == -1) { LOGGER_WARNING(session->m->log, "Failed to register rtp receive handler"); return -1; } LOGGER_DEBUG(session->m->log, "Started receiving on session: %p", (void *)session); return 0; } int rtp_stop_receiving(RTPSession *session) { if (session == nullptr) { return -1; } m_callback_rtp_packet(session->m, session->friend_number, session->payload_type, nullptr, nullptr); LOGGER_DEBUG(session->m->log, "Stopped receiving on session: %p", (void *)session); return 0; } /** * Send a frame of audio or video data, chunked in @ref RTPMessage instances. * * @param session The A/V session to send the data for. * @param data A byte array of length @p length. * @param length The number of bytes to send from @p data. * @param is_keyframe Whether this video frame is a key frame. If it is an * audio frame, this parameter is ignored. */ int rtp_send_data(RTPSession *session, const uint8_t *data, uint32_t length, bool is_keyframe, const Logger *log) { if (session == nullptr) { LOGGER_ERROR(log, "No session!"); return -1; } struct RTPHeader header = {0}; header.ve = 2; // this is unused in toxav header.pe = 0; header.xe = 0; header.cc = 0; header.ma = 0; header.pt = session->payload_type % 128; header.sequnum = session->sequnum; header.timestamp = current_time_monotonic(session->m->mono_time); header.ssrc = session->ssrc; header.offset_lower = 0; // here the highest bits gets stripped anyway, no need to do keyframe bit magic here! header.data_length_lower = length; if (session->payload_type == RTP_TYPE_VIDEO) { header.flags = RTP_LARGE_FRAME; } uint16_t length_safe = (uint16_t)length; if (length > UINT16_MAX) { length_safe = UINT16_MAX; } header.data_length_lower = length_safe; header.data_length_full = length; // without header header.offset_lower = 0; header.offset_full = 0; if (is_keyframe) { header.flags |= RTP_KEY_FRAME; } VLA(uint8_t, rdata, length + RTP_HEADER_SIZE + 1); memset(rdata, 0, SIZEOF_VLA(rdata)); rdata[0] = session->payload_type; // packet id == payload_type if (MAX_CRYPTO_DATA_SIZE > (length + RTP_HEADER_SIZE + 1)) { /* * The length is lesser than the maximum allowed length (including header) * Send the packet in single piece. */ rtp_header_pack(rdata + 1, &header); memcpy(rdata + 1 + RTP_HEADER_SIZE, data, length); if (-1 == rtp_send_custom_lossy_packet(session->tox, session->friend_number, rdata, SIZEOF_VLA(rdata))) { char *netstrerror = net_new_strerror(net_error()); LOGGER_WARNING(session->m->log, "RTP send failed (len: %u)! net error: %s", (unsigned)SIZEOF_VLA(rdata), netstrerror); net_kill_strerror(netstrerror); } } else { /* * The length is greater than the maximum allowed length (including header) * Send the packet in multiple pieces. */ uint32_t sent = 0; uint16_t piece = MAX_CRYPTO_DATA_SIZE - (RTP_HEADER_SIZE + 1); while ((length - sent) + RTP_HEADER_SIZE + 1 > MAX_CRYPTO_DATA_SIZE) { rtp_header_pack(rdata + 1, &header); memcpy(rdata + 1 + RTP_HEADER_SIZE, data + sent, piece); if (-1 == rtp_send_custom_lossy_packet(session->tox, session->friend_number, rdata, piece + RTP_HEADER_SIZE + 1)) { char *netstrerror = net_new_strerror(net_error()); LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! net error: %s", piece + RTP_HEADER_SIZE + 1, netstrerror); net_kill_strerror(netstrerror); } sent += piece; header.offset_lower = sent; header.offset_full = sent; // raw data offset, without any header } /* Send remaining */ piece = length - sent; if (piece != 0) { rtp_header_pack(rdata + 1, &header); memcpy(rdata + 1 + RTP_HEADER_SIZE, data + sent, piece); if (-1 == rtp_send_custom_lossy_packet(session->tox, session->friend_number, rdata, piece + RTP_HEADER_SIZE + 1)) { char *netstrerror = net_new_strerror(net_error()); LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! net error: %s", piece + RTP_HEADER_SIZE + 1, netstrerror); net_kill_strerror(netstrerror); } } } ++session->sequnum; return 0; }
gpl-3.0
thededman/emu-ex-plus-alpha
GBA.emu/src/vbam/gba/Mode2.cpp
3
12539
#include "GBA.h" #include "Globals.h" #include "GBAGfx.h" void mode2RenderLine(MixColorType *lineMix, GBALCD &lcd, const GBAMem::IoMem &ioMem) { #ifdef GBALCD_TEMP_LINE_BUFFER u32 lcd.line2[240]; //gfxClearArray(lcd.line2); u32 lcd.line3[240]; //gfxClearArray(lcd.line3); u32 lcd.lineOBJ[240]; #endif const u16 *palette = (u16 *)lcd.paletteRAM; const auto BLDMOD = ioMem.BLDMOD; const auto COLEV = ioMem.COLEV; const auto COLY = ioMem.COLY; const auto VCOUNT = ioMem.VCOUNT; const auto MOSAIC = ioMem.MOSAIC; const auto DISPCNT = ioMem.DISPCNT; if(lcd.layerEnable & 0x0400) { int changed = lcd.gfxBG2Changed; if(lcd.gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(lcd.vram, ioMem.BG2CNT, ioMem.BG2X_L, ioMem.BG2X_H, ioMem.BG2Y_L, ioMem.BG2Y_H, ioMem.BG2PA, ioMem.BG2PB, ioMem.BG2PC, ioMem.BG2PD, lcd.gfxBG2X, lcd.gfxBG2Y, changed, lcd.line2, VCOUNT, MOSAIC, palette); } if(lcd.layerEnable & 0x0800) { int changed = lcd.gfxBG3Changed; if(lcd.gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(lcd.vram, ioMem.BG3CNT, ioMem.BG3X_L, ioMem.BG3X_H, ioMem.BG3Y_L, ioMem.BG3Y_H, ioMem.BG3PA, ioMem.BG3PB, ioMem.BG3PC, ioMem.BG3PD, lcd.gfxBG3X, lcd.gfxBG3Y, changed, lcd.line3, VCOUNT, MOSAIC, palette); } gfxDrawSprites(lcd, lcd.lineOBJ, VCOUNT, MOSAIC, DISPCNT); u32 backdrop; if(customBackdropColor == -1) { backdrop = (READ16LE(&palette[0]) | 0x30000000); } else { backdrop = ((customBackdropColor & 0x7FFF) | 0x30000000); } for(int x = 0; x < 240; x++) { u32 color = backdrop; u8 top = 0x20; if((u8)(lcd.line2[x]>>24) < (u8)(color >> 24)) { color = lcd.line2[x]; top = 0x04; } if((u8)(lcd.line3[x]>>24) < (u8)(color >> 24)) { color = lcd.line3[x]; top = 0x08; } if((u8)(lcd.lineOBJ[x]>>24) < (u8)(color >> 24)) { color = lcd.lineOBJ[x]; top = 0x10; } if((top & 0x10) && (color & 0x00010000)) { // semi-transparent OBJ u32 back = backdrop; u8 top2 = 0x20; if((u8)(lcd.line2[x]>>24) < (u8)(back >> 24)) { back = lcd.line2[x]; top2 = 0x04; } if((u8)(lcd.line3[x]>>24) < (u8)(back >> 24)) { back = lcd.line3[x]; top2 = 0x08; } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); else { switch((BLDMOD >> 6) & 3) { case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } } lineMix[x] = convColor(color); } lcd.gfxBG2Changed = 0; lcd.gfxBG3Changed = 0; lcd.gfxLastVCOUNT = VCOUNT; } void mode2RenderLineNoWindow(MixColorType *lineMix, GBALCD &lcd, const GBAMem::IoMem &ioMem) { #ifdef GBALCD_TEMP_LINE_BUFFER u32 lcd.line2[240]; //gfxClearArray(lcd.line2); u32 lcd.line3[240]; //gfxClearArray(lcd.line3); u32 lcd.lineOBJ[240]; #endif const u16 *palette = (u16 *)lcd.paletteRAM; const auto BLDMOD = ioMem.BLDMOD; const auto COLEV = ioMem.COLEV; const auto COLY = ioMem.COLY; const auto VCOUNT = ioMem.VCOUNT; const auto MOSAIC = ioMem.MOSAIC; const auto DISPCNT = ioMem.DISPCNT; if(lcd.layerEnable & 0x0400) { int changed = lcd.gfxBG2Changed; if(lcd.gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(lcd.vram, ioMem.BG2CNT, ioMem.BG2X_L, ioMem.BG2X_H, ioMem.BG2Y_L, ioMem.BG2Y_H, ioMem.BG2PA, ioMem.BG2PB, ioMem.BG2PC, ioMem.BG2PD, lcd.gfxBG2X, lcd.gfxBG2Y, changed, lcd.line2, VCOUNT, MOSAIC, palette); } if(lcd.layerEnable & 0x0800) { int changed = lcd.gfxBG3Changed; if(lcd.gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(lcd.vram, ioMem.BG3CNT, ioMem.BG3X_L, ioMem.BG3X_H, ioMem.BG3Y_L, ioMem.BG3Y_H, ioMem.BG3PA, ioMem.BG3PB, ioMem.BG3PC, ioMem.BG3PD, lcd.gfxBG3X, lcd.gfxBG3Y, changed, lcd.line3, VCOUNT, MOSAIC, palette); } gfxDrawSprites(lcd, lcd.lineOBJ, VCOUNT, MOSAIC, DISPCNT); u32 backdrop; if(customBackdropColor == -1) { backdrop = (READ16LE(&palette[0]) | 0x30000000); } else { backdrop = ((customBackdropColor & 0x7FFF) | 0x30000000); } for(int x = 0; x < 240; x++) { u32 color = backdrop; u8 top = 0x20; if((u8)(lcd.line2[x]>>24) < (u8)(color >> 24)) { color = lcd.line2[x]; top = 0x04; } if((u8)(lcd.line3[x]>>24) < (u8)(color >> 24)) { color = lcd.line3[x]; top = 0x08; } if((u8)(lcd.lineOBJ[x]>>24) < (u8)(color >> 24)) { color = lcd.lineOBJ[x]; top = 0x10; } if(!(color & 0x00010000)) { switch((BLDMOD >> 6) & 3) { case 0: break; case 1: { if(top & BLDMOD) { u32 back = backdrop; u8 top2 = 0x20; if((u8)(lcd.line2[x]>>24) < (u8)(back >> 24)) { if(top != 0x04) { back = lcd.line2[x]; top2 = 0x04; } } if((u8)(lcd.line3[x]>>24) < (u8)(back >> 24)) { if(top != 0x08) { back = lcd.line3[x]; top2 = 0x08; } } if((u8)(lcd.lineOBJ[x]>>24) < (u8)(back >> 24)) { if(top != 0x10) { back = lcd.lineOBJ[x]; top2 = 0x10; } } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); } } break; case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } else { // semi-transparent OBJ u32 back = backdrop; u8 top2 = 0x20; if((u8)(lcd.line2[x]>>24) < (u8)(back >> 24)) { back = lcd.line2[x]; top2 = 0x04; } if((u8)(lcd.line3[x]>>24) < (u8)(back >> 24)) { back = lcd.line3[x]; top2 = 0x08; } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); else { switch((BLDMOD >> 6) & 3) { case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } } lineMix[x] = convColor(color); } lcd.gfxBG2Changed = 0; lcd.gfxBG3Changed = 0; lcd.gfxLastVCOUNT = VCOUNT; } void mode2RenderLineAll(MixColorType *lineMix, GBALCD &lcd, const GBAMem::IoMem &ioMem) { #ifdef GBALCD_TEMP_LINE_BUFFER u32 lcd.line2[240]; //gfxClearArray(lcd.line2); u32 lcd.line3[240]; //gfxClearArray(lcd.line3); u32 lcd.lineOBJ[240]; #endif const u16 *palette = (u16 *)lcd.paletteRAM; const auto BLDMOD = ioMem.BLDMOD; const auto COLEV = ioMem.COLEV; const auto COLY = ioMem.COLY; const auto WIN0V = ioMem.WIN0V; const auto WIN1V = ioMem.WIN1V; const auto WININ = ioMem.WININ; const auto WINOUT = ioMem.WINOUT; const auto VCOUNT = ioMem.VCOUNT; const auto MOSAIC = ioMem.MOSAIC; const auto DISPCNT = ioMem.DISPCNT; bool inWindow0 = false; bool inWindow1 = false; if(lcd.layerEnable & 0x2000) { u8 v0 = WIN0V >> 8; u8 v1 = WIN0V & 255; inWindow0 = ((v0 == v1) && (v0 >= 0xe8)); if(v1 >= v0) inWindow0 |= (VCOUNT >= v0 && VCOUNT < v1); else inWindow0 |= (VCOUNT >= v0 || VCOUNT < v1); } if(lcd.layerEnable & 0x4000) { u8 v0 = WIN1V >> 8; u8 v1 = WIN1V & 255; inWindow1 = ((v0 == v1) && (v0 >= 0xe8)); if(v1 >= v0) inWindow1 |= (VCOUNT >= v0 && VCOUNT < v1); else inWindow1 |= (VCOUNT >= v0 || VCOUNT < v1); } if(lcd.layerEnable & 0x0400) { int changed = lcd.gfxBG2Changed; if(lcd.gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(lcd.vram, ioMem.BG2CNT, ioMem.BG2X_L, ioMem.BG2X_H, ioMem.BG2Y_L, ioMem.BG2Y_H, ioMem.BG2PA, ioMem.BG2PB, ioMem.BG2PC, ioMem.BG2PD, lcd.gfxBG2X, lcd.gfxBG2Y, changed, lcd.line2, VCOUNT, MOSAIC, palette); } if(lcd.layerEnable & 0x0800) { int changed = lcd.gfxBG3Changed; if(lcd.gfxLastVCOUNT > VCOUNT) changed = 3; gfxDrawRotScreen(lcd.vram, ioMem.BG3CNT, ioMem.BG3X_L, ioMem.BG3X_H, ioMem.BG3Y_L, ioMem.BG3Y_H, ioMem.BG3PA, ioMem.BG3PB, ioMem.BG3PC, ioMem.BG3PD, lcd.gfxBG3X, lcd.gfxBG3Y, changed, lcd.line3, VCOUNT, MOSAIC, palette); } gfxDrawSprites(lcd, lcd.lineOBJ, VCOUNT, MOSAIC, DISPCNT); gfxDrawOBJWin(lcd, lcd.lineOBJWin, VCOUNT, DISPCNT); u32 backdrop; if(customBackdropColor == -1) { backdrop = (READ16LE(&palette[0]) | 0x30000000); } else { backdrop = ((customBackdropColor & 0x7FFF) | 0x30000000); } u8 inWin0Mask = WININ & 0xFF; u8 inWin1Mask = WININ >> 8; u8 outMask = WINOUT & 0xFF; for(int x = 0; x < 240; x++) { u32 color = backdrop; u8 top = 0x20; u8 mask = outMask; if(!(lcd.lineOBJWin[x] & 0x80000000)) { mask = WINOUT >> 8; } if(inWindow1) { if(lcd.gfxInWin1[x]) mask = inWin1Mask; } if(inWindow0) { if(lcd.gfxInWin0[x]) { mask = inWin0Mask; } } if(lcd.line2[x] < color && (mask & 4)) { color = lcd.line2[x]; top = 0x04; } if((u8)(lcd.line3[x]>>24) < (u8)(color >> 24) && (mask & 8)) { color = lcd.line3[x]; top = 0x08; } if((u8)(lcd.lineOBJ[x]>>24) < (u8)(color >> 24) && (mask & 16)) { color = lcd.lineOBJ[x]; top = 0x10; } if(color & 0x00010000) { // semi-transparent OBJ u32 back = backdrop; u8 top2 = 0x20; if((mask & 4) && lcd.line2[x] < back) { back = lcd.line2[x]; top2 = 0x04; } if((mask & 8) && (u8)(lcd.line3[x]>>24) < (u8)(back >> 24)) { back = lcd.line3[x]; top2 = 0x08; } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); else { switch((BLDMOD >> 6) & 3) { case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } } else if(mask & 32) { // special FX on the window switch((BLDMOD >> 6) & 3) { case 0: break; case 1: { if(top & BLDMOD) { u32 back = backdrop; u8 top2 = 0x20; if((mask & 4) && lcd.line2[x] < back) { if(top != 0x04) { back = lcd.line2[x]; top2 = 0x04; } } if((mask & 8) && (u8)(lcd.line3[x]>>24) < (u8)(back >> 24)) { if(top != 0x08) { back = lcd.line3[x]; top2 = 0x08; } } if((mask & 16) && (u8)(lcd.lineOBJ[x]>>24) < (u8)(back >> 24)) { if(top != 0x10) { back = lcd.lineOBJ[x]; top2 = 0x10; } } if(top2 & (BLDMOD>>8)) color = gfxAlphaBlend(color, back, coeff[COLEV & 0x1F], coeff[(COLEV >> 8) & 0x1F]); } } break; case 2: if(BLDMOD & top) color = gfxIncreaseBrightness(color, coeff[COLY & 0x1F]); break; case 3: if(BLDMOD & top) color = gfxDecreaseBrightness(color, coeff[COLY & 0x1F]); break; } } lineMix[x] = convColor(color); } lcd.gfxBG2Changed = 0; lcd.gfxBG3Changed = 0; lcd.gfxLastVCOUNT = VCOUNT; }
gpl-3.0
regneq/ZeldaClassic
allegro/tests/akaitest.c
4
18819
/* ______ ___ ___ * /\ _ \ /\_ \ /\_ \ * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___ * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\ * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \ * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/ * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/ * /\____/ * \_/__/ * * Audio input test program for the Allegro library. * * By Shawn Hargreaves. * * See readme.txt for copyright information. */ #include <stdio.h> #include <string.h> #include <math.h> #include "allegro.h" /* the current sound */ SAMPLE *the_sample = NULL; /* table of voice numbers for each MIDI key */ int voice[128]; /* lookup table for the MIDI pitch -> sample frequency conversion */ float pitch[128]; /* ring buffer for storing MIDI input */ #define MIDI_BUFFER_SIZE 4096 volatile int midi_buffer_head = 0; volatile int midi_buffer_tail = 0; volatile unsigned char midi_buffer[MIDI_BUFFER_SIZE]; /* the current MIDI command and data bytes */ int midi_cmd = -1; int midi_data1 = -1; int midi_data2 = -1; /* interrupt hook for dealing with MIDI input */ void midi_input_callback(unsigned char data) { midi_buffer[midi_buffer_tail] = data; midi_buffer_tail++; if (midi_buffer_tail >= MIDI_BUFFER_SIZE) midi_buffer_tail = 0; } END_OF_FUNCTION(midi_input_callback); /* checks if there is any data in the MIDI input buffer */ int midi_waiting(void) { if (midi_buffer_head == midi_buffer_tail) return 0; else return 1; } /* reads a byte from the MIDI input buffer */ int get_midi(void) { int ret; if (midi_buffer_head == midi_buffer_tail) return -1; ret = midi_buffer[midi_buffer_head]; midi_buffer_head++; if (midi_buffer_head >= MIDI_BUFFER_SIZE) midi_buffer_head = 0; return ret; } /* trigger a sample */ void start_note(int note, int vol) { if (voice[note] >= 0) { voice_stop(voice[note]); deallocate_voice(voice[note]); } voice[note] = allocate_voice(the_sample); if (voice[note] >= 0) { voice_set_frequency(voice[note], MIN(pitch[note]*the_sample->freq, 0x7FFFF)); voice_set_volume(voice[note], vol); voice_start(voice[note]); } } /* kill off a playing sample */ void stop_note(int note) { if (voice[note] >= 0) { voice_stop(voice[note]); deallocate_voice(voice[note]); voice[note] = -1; } } /* load samples in from disk */ int load_proc(int msg, DIALOG *d, int c) { int ret = d_button_proc(msg, d, c); if (ret & D_CLOSE) { static char name[80*6] = EMPTY_STRING; /* 80 chars * max UTF8 char width */ if (file_select_ex("Load Sample", name, "wav;voc", sizeof(name), 0, 0)) { if (the_sample) destroy_sample(the_sample); the_sample = load_sample(name); if (!the_sample) alert("Error reading sample", NULL, NULL, "What a pity", NULL, 13, 0); } return D_REDRAW; } return ret; } char record_length[16] = "5.0"; char record_freq[16] = ""; int waveform_proc(int msg, DIALOG *d, int c); DIALOG record_dialog[] = { /* (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) (dp2) (dp3) */ { d_shadow_box_proc, 160, 120, 321, 265, 255, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { d_ctext_proc, 320, 136, 0, 0, 255, 0, 0, 0, 0, 0, "Record Sample", NULL, NULL }, { d_button_proc, 208, 336, 97, 25, 255, 0, 13, D_EXIT, 0, 0, "OK", NULL, NULL }, { d_button_proc, 338, 336, 97, 25, 255, 0, 27, D_EXIT, 0, 0, "Cancel", NULL, NULL }, { d_text_proc, 208, 176, 0, 0, 255, 0, 0, 0, 0, 0, "Length:", NULL, NULL }, { d_edit_proc, 277, 176, 64, 8, 255, 0, 0, 0, 15, 0, record_length, NULL, NULL }, { d_text_proc, 208, 200, 0, 0, 255, 0, 0, 0, 0, 0, "Freq:", NULL, NULL }, { d_edit_proc, 277, 200, 64, 8, 255, 0, 0, 0, 15, 0, record_freq, NULL, NULL }, { d_text_proc, 208, 224, 0, 0, 255, 0, 0, 0, 0, 0, "16 bit:", NULL, NULL }, { d_check_proc, 272, 221, 17, 13, 255, 0, 0, 0, 0, 0, "", NULL, NULL }, { d_text_proc, 208, 248, 0, 0, 255, 0, 0, 0, 0, 0, "Stereo:", NULL, NULL }, { d_check_proc, 272, 245, 17, 13, 255, 0, 0, 0, 0, 0, "", NULL, NULL }, { d_radio_proc, 368, 176, 49, 13, 255, 0, 0, D_SELECTED, 1, 0, "Mic", NULL, NULL }, { d_radio_proc, 368, 200, 49, 13, 255, 0, 0, 0, 1, 0, "Line", NULL, NULL }, { d_radio_proc, 368, 224, 49, 13, 255, 0, 0, 0, 1, 0, "CD", NULL, NULL }, { waveform_proc, 208, 280, 226, 32, 1, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; #define RECORD_OK 2 #define RECORD_CANCEL 3 #define RECORD_LENGTH 5 #define RECORD_FREQ 7 #define RECORD_16BIT 9 #define RECORD_STEREO 11 #define RECORD_MIC 12 #define RECORD_LINE 13 #define RECORD_CD 14 int waveform_size = 0; unsigned char *waveform_buffer = NULL; /* display the input waveform for the sampling dialog */ int waveform_proc(int msg, DIALOG *d, int c) { int rate, source, i; static int last_source = -1; switch (msg) { case MSG_START: rate = get_sound_input_cap_parm(8000, 8, FALSE); if (rate > 0) rate = 8000; else if (rate < 0) rate = -rate; else return D_O_K; waveform_size = start_sound_input(rate, 8, FALSE); if (waveform_size > 0) { waveform_buffer = malloc(waveform_size); memset(waveform_buffer, 0x80, waveform_size); } break; case MSG_END: if (waveform_buffer) { stop_sound_input(); free(waveform_buffer); waveform_buffer = NULL; waveform_size = 0; } break; case MSG_DRAW: if (waveform_buffer) { for (i=0; i<MIN(d->w, waveform_size); i++) { if (waveform_buffer[i] < 0x80) { vline(screen, d->x+i, d->y, d->y+waveform_buffer[i]*d->h/255-1, d->bg); vline(screen, d->x+i, d->y+waveform_buffer[i]*d->h/255, d->y+d->h/2, d->fg); vline(screen, d->x+i, d->y+d->h/2+1, d->y+d->h, d->bg); } else { vline(screen, d->x+i, d->y, d->y+d->h/2-1, d->bg); vline(screen, d->x+i, d->y+d->h/2, d->y+waveform_buffer[i]*d->h/255, d->fg); vline(screen, d->x+i, d->y+waveform_buffer[i]*d->h/255+1, d->y+d->h, d->bg); } } } break; case MSG_IDLE: if (waveform_buffer) { if (read_sound_input(waveform_buffer)) { freeze_mouse_flag = TRUE; poll_mouse(); object_message(d, MSG_DRAW, 0); freeze_mouse_flag = FALSE; } } if (record_dialog[RECORD_MIC].flags & D_SELECTED) source = SOUND_INPUT_MIC; else if (record_dialog[RECORD_LINE].flags & D_SELECTED) source = SOUND_INPUT_LINE; else source = SOUND_INPUT_CD; if (source != last_source) { set_sound_input_source(source); last_source = source; } break; } return D_O_K; } /* main sample recording function */ int record_proc(int msg, DIALOG *d, int c) { int ret = d_button_proc(msg, d, c); int sel = -1; int bits; int stereo; int freq, freq2; int buffer_size; int bytes_per_sample; int sample_len; int sample_todo; int sample_todo_orig; char *sample_data; float length; if (ret & D_CLOSE) { bits = get_sound_input_cap_bits(); stereo = get_sound_input_cap_stereo(); if (!bits) { alert("The current audio input driver does", "not support sample recording", NULL, "I'll change it then", NULL, 13, 0); return D_REDRAW; } if (bits&16) record_dialog[RECORD_16BIT].flags |= D_SELECTED; else record_dialog[RECORD_16BIT].flags &= ~D_SELECTED; if (stereo) record_dialog[RECORD_STEREO].flags |= D_SELECTED; else record_dialog[RECORD_STEREO].flags &= ~D_SELECTED; if (!record_freq[0]) sprintf(record_freq, "%d", get_sound_input_cap_rate(((bits&16) ? 16 : 8), stereo)); retry: /* ask the user for settings */ if (do_dialog(record_dialog, sel) == RECORD_OK) { length = atof(record_length); freq = atof(record_freq); bits = (record_dialog[RECORD_16BIT].flags & D_SELECTED) ? 16 : 8; stereo = (record_dialog[RECORD_STEREO].flags & D_SELECTED) ? TRUE : FALSE; /* make sure we got a valid length */ if ((length < 0.1) || (length > 30)) { alert("Please enter a length", "between 0.1 and 30 seconds", NULL, "Understood", NULL, 13, 0); sel = RECORD_LENGTH; goto retry; } /* make sure we got a valid frequency */ if ((freq < 4000) || (freq > 50000)) { alert("Please enter a sampling frequency", "between 4000 and 50000", NULL, "Understood", NULL, 13, 0); sel = RECORD_FREQ; goto retry; } /* check that the card likes this frequency */ freq2 = get_sound_input_cap_parm(freq, bits, stereo); if (freq2 == 0) { alert("The current input driver does", "not support these settings", NULL, "Drat", NULL, 13, 0); sel = RECORD_16BIT; goto retry; } if (freq2 < 0) { sprintf(record_freq, "%d", -freq2); alert("Invalid sampling frequency", "Suggested alternative:", record_freq, "Understood", NULL, 13, 0); sel = RECORD_FREQ; goto retry; } /* set the sample source */ if (record_dialog[RECORD_MIC].flags & D_SELECTED) set_sound_input_source(SOUND_INPUT_MIC); else if (record_dialog[RECORD_LINE].flags & D_SELECTED) set_sound_input_source(SOUND_INPUT_LINE); else if (record_dialog[RECORD_CD].flags & D_SELECTED) set_sound_input_source(SOUND_INPUT_CD); /* draw progress bar */ show_mouse(NULL); rect(screen, 95, 175, 545, 273, 255); rectfill(screen, 96, 176, 544, 272, 0); rect(screen, 127, 235, 513, 257, 255); rectfill(screen, 128, 236, 512, 256, 8); textout_centre_ex(screen, font, "Recording...", 320, 200, 255, -1); /* start the input! */ buffer_size = start_sound_input(freq, bits, stereo); if (buffer_size <= 0) { alert("Error recording sample", NULL, NULL, "Drat", NULL, 13, 0); destroy_sample(the_sample); the_sample = NULL; show_mouse(screen); return D_REDRAW; } /* round the sample length to an even number of buffer transfers. * Really the recording code ought to handle odd amounts of data * left over at the end, but it is much easier like this :-) */ bytes_per_sample = ((bits==8) ? 1 : sizeof(short)) * ((stereo) ? 2 : 1); sample_len = length * freq; sample_len = MAX((((sample_len * bytes_per_sample) / buffer_size) * buffer_size), buffer_size) / bytes_per_sample; sample_todo = sample_todo_orig = sample_len * bytes_per_sample; if (the_sample) destroy_sample(the_sample); /* create a new sample to hold our data */ the_sample = create_sample(bits, stereo, freq, sample_len); sample_data = (char *)the_sample->data; /* discard the first input buffer, to prevent clicks */ do { } while (!read_sound_input(sample_data)); /* finally, record the sound */ while (sample_todo >= buffer_size) { if (read_sound_input(sample_data)) { sample_data += buffer_size; sample_todo -= buffer_size; rectfill(screen, 128, 236, 128+(sample_todo_orig-sample_todo)*384/sample_todo_orig, 256, 1); } } stop_sound_input(); show_mouse(screen); } return D_REDRAW; } return ret; } /* helper for redrawing a specific part of the keyboard object */ void redraw_keyboard(DIALOG *d, int c) { set_clip_rect(screen, d->x+(c-36)*12-6, d->y, d->x+(c-36)*12+18, d->y+d->h); object_message(d, MSG_DRAW, 0); set_clip_rect(screen, 0, 0, SCREEN_W-1, SCREEN_H-1); } /* GUI interface for playing sounds */ int piano_proc(int msg, DIALOG *d, int c) { static char blackkey[12] = { FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE }; int i, l, r; switch (msg) { case MSG_START: d->d1 = -1; break; case MSG_DRAW: /* display the keyboard graphic */ for (i=0; i<d->w/12; i++) { if (!blackkey[i%12]) { l = i*12; r = (i+1)*12; if (i > 0 && blackkey[(i-1)%12]) l -= 6; if (blackkey[(i+1)%12]) r += 6; rectfill(screen, d->x+l+1, d->y+1, d->x+r-1, d->y+d->h-1, (voice[i+36] >= 0) ? 1 : d->bg); rect(screen, d->x+l, d->y, d->x+r, d->y+d->h, d->fg); } } for (i=0; i<d->w/12; i++) { if (blackkey[i%12]) { l = i*12 + 1; r = (i+1)*12 - 1; rectfill(screen, d->x+l, d->y+d->h/4, d->x+r, d->y+d->h, (voice[i+36] >= 0) ? 1 : d->fg); } } break; case MSG_CLICK: /* handle mouse clicks (playing sounds from the GUI) */ if (!the_sample) { alert("You must read in or record a", "sample before you can play it", NULL, "Sorry. I won't do it again", NULL, 13, 0); return D_O_K; } do { poll_mouse(); i = ((mouse_x - d->x) / 12) + 36; if (i != d->d1) { if (d->d1 >= 0) { stop_note(d->d1); redraw_keyboard(d, d->d1); d->d1 = -1; } d->d1 = i; start_note(d->d1, 255); redraw_keyboard(d, d->d1); } } while (mouse_b); if (d->d1 >= 0) { stop_note(d->d1); redraw_keyboard(d, d->d1); d->d1 = -1; } break; case MSG_IDLE: /* check for MIDI input */ if (midi_waiting()) { i = get_midi(); if (i & 0x80) { /* start of a new MIDI command */ midi_cmd = i&0xF0; midi_data1 = -1; midi_data2 = -1; } else if (midi_data1 < 0) { /* got the first parameter */ midi_data1 = i; } else if (midi_data2 < 0) { /* got the second parameter */ midi_data2 = i; if (the_sample) { if ((midi_cmd == 0x80) || ((midi_cmd == 0x90) && (midi_data2 == 0))) { /* note off */ stop_note(midi_data1); redraw_keyboard(d, midi_data1); } else if (midi_cmd == 0x90) { /* note on */ start_note(midi_data1, midi_data2); redraw_keyboard(d, midi_data1); } } midi_data1 = -1; midi_data2 = -1; } } break; } return D_O_K; } DIALOG the_dialog[] = { /* (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) (dp2) (dp3) */ { d_clear_proc, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, NULL, NULL, NULL }, { d_ctext_proc, 320, 4, 0, 0, 255, 8, 0, 0, 0, 0, "Audio input test program for Allegro " ALLEGRO_VERSION_STR ", " ALLEGRO_PLATFORM_STR, NULL, NULL }, { d_ctext_proc, 320, 20, 0, 0, 255, 8, 0, 0, 0, 0, "By Shawn Hargreaves, " ALLEGRO_DATE_STR, NULL, NULL }, { d_text_proc, 224, 88, 0, 0, 255, 8, 0, 0, 0, 0, "MIDI Input:", NULL, NULL }, { d_text_proc, 328, 88, 0, 0, 255, 8, 0, 0, 0, 0, NULL, NULL, NULL }, { d_text_proc, 216, 112, 0, 0, 255, 8, 0, 0, 0, 0, "Audio Input:", NULL, NULL }, { d_text_proc, 328, 112, 0, 0, 255, 8, 0, 0, 0, 0, NULL, NULL, NULL }, { d_text_proc, 208, 136, 0, 0, 255, 8, 0, 0, 0, 0, "Audio Output:", NULL, NULL }, { d_text_proc, 328, 136, 0, 0, 255, 8, 0, 0, 0, 0, NULL, NULL, NULL }, { load_proc, 160, 232, 129, 25, 255, 0, 0, D_EXIT, 0, 0, "Load Sample", NULL, NULL }, { record_proc, 352, 232, 129, 25, 255, 0, 0, D_EXIT, 0, 0, "Record Sample", NULL, NULL }, { d_button_proc, 256, 320, 129, 25, 255, 0, 0, D_EXIT, 0, 0, "Quit", NULL, NULL }, { piano_proc, 2, 440, 636, 40, 255, 0, 0, 0, 0, 0, NULL, NULL, NULL }, { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL } }; int main(void) { int i; for (i=0; i<128; i++) voice[i] = -1; pitch[127] = 48; for (i=126; i>=0; i--) pitch[i] = pitch[i+1] / pow(2.0, 1.0/12.0); if (allegro_init() != 0) return 1; install_keyboard(); install_mouse(); install_timer(); if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) { allegro_message("\nError initialising sound\n%s\n", allegro_error); return 1; } if (install_sound_input(DIGI_AUTODETECT, MIDI_AUTODETECT) != 0) { allegro_message("\nError initialising sound input\n%s\n\n" "Try changing the digi_input_card and midi_input_card settings in your\n" "allegro.cfg, in particular disabling (set to zero) one of those drivers.\n", allegro_error); return 1; } if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0) != 0) { set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); allegro_message("Error setting graphics mode\n%s\n", allegro_error); return 1; } set_palette(desktop_palette); LOCK_VARIABLE(midi_buffer_head); LOCK_VARIABLE(midi_buffer_tail); LOCK_VARIABLE(midi_buffer); LOCK_FUNCTION(midi_input_callback); midi_recorder = midi_input_callback; the_dialog[4].dp = (void*)midi_input_driver->name; the_dialog[6].dp = (void*)digi_input_driver->name; the_dialog[8].dp = (void*)digi_driver->name; do_dialog(the_dialog, -1); if (the_sample) destroy_sample(the_sample); return 0; } END_OF_MAIN()
gpl-3.0
jmysona/simpaticoMicelle
src/mcMd/mcMoves/ring/CfbRingRebridgeMove.cpp
4
9648
/* * Simpatico - Simulation Package for Polymeric and Molecular Liquids * * Copyright 2010 - 2014, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "CfbRingRebridgeMove.h" #include <mcMd/mcSimulation/McSystem.h> #include <mcMd/simulation/Simulation.h> #ifndef INTER_NOPAIR #include <mcMd/potentials/pair/McPairPotential.h> #endif #include <mcMd/species/Ring.h> #include <util/boundary/Boundary.h> #include <mcMd/chemistry/Molecule.h> #include <mcMd/chemistry/Bond.h> #include <mcMd/chemistry/Atom.h> #include <util/global.h> namespace McMd { using namespace Util; /* * Constructor */ CfbRingRebridgeMove::CfbRingRebridgeMove(McSystem& system) : CfbRebridgeBase(system), speciesId_(-1), nRegrow_(-1) { setClassName("CfbRingRebridgeMove"); } /* * Read parameters speciesId, nRegrow, and nTrial */ void CfbRingRebridgeMove::readParameters(std::istream& in) { // Read parameters readProbability(in); read<int>(in, "speciesId", speciesId_); read<int>(in, "nRegrow", nRegrow_); // Read parameters hold by RebridgeBase CfbRebridgeBase::readParameters(in); // Initialize tables for spring constants and normalizations. setup(); // Use dynamic_cast to check that the Species is actually a Linear species Ring* ringPtr; ringPtr = dynamic_cast<Ring*>(&(simulation().species(speciesId_))); if (!ringPtr) { UTIL_THROW("Not a Ring species"); } // Allocate array to store old positions oldPos_.allocate(nRegrow_); } /* * Load state from an archive. */ void CfbRingRebridgeMove::loadParameters(Serializable::IArchive& ar) { McMove::loadParameters(ar); loadParameter<int>(ar, "speciesId", speciesId_); loadParameter<int>(ar, "nRegrow", nRegrow_); CfbRebridgeBase::loadParameters(ar); // Validate Ring* ringPtr; ringPtr = dynamic_cast<Ring*>(&(simulation().species(speciesId_))); if (!ringPtr) { UTIL_THROW("Species is not a Ring species"); } // Initialize tables for spring constants and normalizations. setup(); oldPos_.allocate(nRegrow_); } /* * Save state to an archive. */ void CfbRingRebridgeMove::save(Serializable::OArchive& ar) { McMove::save(ar); ar & speciesId_; ar & nRegrow_; CfbRebridgeBase::save(ar); } /* * Generate, attempt and accept or reject a Monte Carlo move. * * Convention for index * nAtom * _____________________________________ * | | * 0 1 2 3 ... nAtom-1 * o---o---o---o---o---o---o---o---o---o * bonds: 0 1 2 3 nAtom-1 * * The algorithm is slightly different from that for linear molecules since a * ring molecule does not have ends. The operation of moving the atom pointers * have to account for the periodic boundary conditions, which is achived with * the help of modId(int s, int n) method. * */ bool CfbRingRebridgeMove::move() { Molecule *molPtr; // pointer to randomly chosen molecule Atom *thisPtr; // pointer to the current end atom Atom *tempPtr; // pointer to the current end atom int *bonds, iBond; int nAtom, sign, beginId, endId, i; double rosen_r, rosen_f; double energy_r, energy_f; bool accept; incrementNAttempt(); // Choose a molecule at random molPtr = &(system().randomMolecule(speciesId_)); nAtom = molPtr->nAtom(); // Require that chain length - 2 >= nRegrow_ if (nRegrow_ > nAtom - 2) { UTIL_THROW("nRegrow_ >= chain length"); } // Allocate bonds array bonds = new int[nRegrow_ + 1]; // Choose the beginId of the growing interior bridge beginId = random().uniformInt(0, nAtom); // Choose direction and fill bonds array: sign = +1 if beginId < endId if (random().uniform(0.0, 1.0) > 0.5) { sign = +1; endId = (beginId + (nRegrow_ - 1)) % nAtom; // Save bond types iBond = endId; for (i = 0; i < nRegrow_ + 1; ++i) { bonds[i] = molPtr->bond(iBond).typeId(); iBond--; if (iBond < 0) iBond += nAtom; } } else { sign = -1; endId = beginId; beginId = (endId + (nRegrow_ - 1)) % nAtom; // Save bond types iBond = endId - 1; if (iBond < 0) iBond += nAtom; for (i = 0; i < nRegrow_ + 1; ++i) { bonds[i] = molPtr->bond(iBond).typeId(); iBond++; if (iBond >= nAtom) iBond -= nAtom; } } // Store current atomic positions from segment to be regrown tempPtr = &(molPtr->atom(beginId)); for (i = 0; i < nRegrow_; ++i) { thisPtr = tempPtr + modId(beginId + i*sign, nAtom) - beginId; oldPos_[i] = thisPtr->position(); } // Delete atoms: endId -> beginId deleteSequence(sign, molPtr, endId, bonds, rosen_r, energy_r); // Regrow atoms: endId -> beginId addSequence(sign, molPtr, beginId, bonds, rosen_f, energy_f); // Release bonds array delete [] bonds; // Decide whether to accept or reject accept = random().metropolis(rosen_f/rosen_r); if (accept) { // Increment counter for accepted moves of this class. incrementNAccept(); // If the move is accepted, keep current positions. } else { // If the move is rejected, restore old positions tempPtr = &(molPtr->atom(beginId)); for (i = 0; i < nRegrow_; ++i) { thisPtr = tempPtr + modId(beginId + i*sign, nAtom) - beginId; //system().moveAtom(*thisPtr, oldPos_[i]); thisPtr->position() = oldPos_[i]; #ifndef INTER_NOPAIR system().pairPotential().updateAtomCell(*thisPtr); #endif } } return accept; } /* * Delete a consecutive sequence of atoms in a Ring. */ void CfbRingRebridgeMove::deleteSequence(int sign, Molecule *molPtr, int endId, int *bonds, double &rosenbluth, double &energy) { Atom *endPtr; Atom *thisPtr; Atom *prevPtr; Atom *nextPtr; int prevBType, nextBType, nAtom; double rosen_r, energy_r; // Initialize weight rosenbluth = 1.0; energy = 0.0; nAtom = molPtr->nAtom(); endPtr = &(molPtr->atom(endId)); // Step 1: delete the last atom if (nRegrow_ >= 1) { thisPtr = endPtr; prevPtr = endPtr + modId(endId - sign,nAtom) - endId; nextPtr = endPtr + modId(endId + sign,nAtom) - endId; nextBType = bonds[0]; prevBType = bonds[1]; // Orientation biased trimer rebridge move deleteMiddleAtom(thisPtr, prevPtr, nextPtr, prevBType, nextBType, rosen_r, energy_r); #ifndef INTER_NOPAIR system().pairPotential().deleteAtom(*thisPtr); #endif rosenbluth *= rosen_r; energy += energy_r; } // step 2: delete the remaining atoms for (int i = 0; i < nRegrow_ - 1; ++i) { thisPtr = endPtr + modId(endId - (i+1)*sign, nAtom) - endId; prevPtr = endPtr + modId(endId - (i+2)*sign, nAtom) - endId; prevBType = bonds[i+2]; deleteEndAtom(thisPtr, prevPtr, prevBType, rosen_r, energy_r); #ifndef INTER_NOPAIR system().pairPotential().deleteAtom(*thisPtr); #endif rosenbluth *= rosen_r; energy += energy_r; } } /* * Add a consecutive sequence of atoms in a Ring. */ void CfbRingRebridgeMove::addSequence(int sign, Molecule *molPtr, int beginId, int *bonds, double &rosenbluth, double &energy) { Atom *beginPtr; Atom *thisPtr; Atom *prevPtr; Atom *nextPtr; int prevBType, nextBType, nAtom; double rosen_f, energy_f; // Initialize weight rosenbluth = 1.0; energy = 0.0; // Step 1: grow the first nRegrow_ - 1 atoms nAtom = molPtr->nAtom(); beginPtr = &(molPtr->atom(beginId)); for (int i = 0; i < nRegrow_ - 1; ++i) { thisPtr = beginPtr + modId(beginId+i*sign,nAtom) - beginId; prevPtr = beginPtr + modId(beginId+(i-1)*sign,nAtom) - beginId; prevBType = bonds[nRegrow_ - i]; addEndAtom(thisPtr, prevPtr, prevBType, rosen_f, energy_f); #ifndef INTER_NOPAIR system().pairPotential().addAtom(*thisPtr); #endif rosenbluth *= rosen_f; energy += energy_f; } // Step 2: grow the last atoms if (nRegrow_ >= 1) { prevPtr = beginPtr + modId(beginId+(nRegrow_-2)*sign,nAtom) - beginId; thisPtr = beginPtr + modId(beginId+(nRegrow_-1)*sign,nAtom) - beginId; nextPtr = beginPtr + modId(beginId+nRegrow_*sign,nAtom) - beginId; prevBType = bonds[1]; nextBType = bonds[0]; // Invoke the orientation biased trimer re-bridging move addMiddleAtom(thisPtr, prevPtr, nextPtr, prevBType, nextBType, rosen_f, energy_f); #ifndef INTER_NOPAIR system().pairPotential().addAtom(*thisPtr); #endif rosenbluth *= rosen_f; energy += energy_f; } } }
gpl-3.0
montimaj/ShaktiT_LLVM
llvm/tools/clang/test/OpenMP/target_data_ast_print.cpp
4
5290
// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER void foo() {} template <typename T, int C> T tmain(T argc, T *argv) { T i, j, b, c, d, e, x[20]; #pragma omp target data map(to: c) i = argc; #pragma omp target data map(to: c) if (target data: j > 0) foo(); #pragma omp target data map(to: c) if (b) foo(); #pragma omp target data map(c) foo(); #pragma omp target data map(c) if(b>e) foo(); #pragma omp target data map(x[0:10], c) foo(); #pragma omp target data map(to: c) map(from: d) foo(); #pragma omp target data map(always,alloc: e) foo(); // nesting a target region #pragma omp target data map(e) { #pragma omp target map(always, alloc: e) foo(); } return 0; } // CHECK: template <typename T, int C> T tmain(T argc, T *argv) { // CHECK-NEXT: T i, j, b, c, d, e, x[20]; // CHECK-NEXT: #pragma omp target data map(to: c) // CHECK-NEXT: i = argc; // CHECK-NEXT: #pragma omp target data map(to: c) if(target data: j > 0) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(to: c) if(b) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: c) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: c) if(b > e) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: x[0:10],c) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(to: c) map(from: d) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(always,alloc: e) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: e) // CHECK-NEXT: { // CHECK-NEXT: #pragma omp target map(always,alloc: e) // CHECK-NEXT: foo(); // CHECK: template<> int tmain<int, 5>(int argc, int *argv) { // CHECK-NEXT: int i, j, b, c, d, e, x[20]; // CHECK-NEXT: #pragma omp target data map(to: c) // CHECK-NEXT: i = argc; // CHECK-NEXT: #pragma omp target data map(to: c) if(target data: j > 0) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(to: c) if(b) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: c) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: c) if(b > e) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: x[0:10],c) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(to: c) map(from: d) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(always,alloc: e) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: e) // CHECK-NEXT: { // CHECK-NEXT: #pragma omp target map(always,alloc: e) // CHECK-NEXT: foo(); // CHECK: template<> char tmain<char, 1>(char argc, char *argv) { // CHECK-NEXT: char i, j, b, c, d, e, x[20]; // CHECK-NEXT: #pragma omp target data map(to: c) // CHECK-NEXT: i = argc; // CHECK-NEXT: #pragma omp target data map(to: c) if(target data: j > 0) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(to: c) if(b) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: c) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: c) if(b > e) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: x[0:10],c) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(to: c) map(from: d) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(always,alloc: e) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target data map(tofrom: e) // CHECK-NEXT: { // CHECK-NEXT: #pragma omp target map(always,alloc: e) // CHECK-NEXT: foo(); int main (int argc, char **argv) { int b = argc, c, d, e, f, g, x[20]; static int a; // CHECK: static int a; #pragma omp target data map(to: c) // CHECK: #pragma omp target data map(to: c) a=2; // CHECK-NEXT: a = 2; #pragma omp target data map(to: c) if (target data: b) // CHECK: #pragma omp target data map(to: c) if(target data: b) foo(); // CHECK-NEXT: foo(); #pragma omp target data map(to: c) if (b > g) // CHECK: #pragma omp target data map(to: c) if(b > g) foo(); // CHECK-NEXT: foo(); #pragma omp target data map(c) // CHECK-NEXT: #pragma omp target data map(tofrom: c) foo(); // CHECK-NEXT: foo(); #pragma omp target data map(c) if(b>g) // CHECK-NEXT: #pragma omp target data map(tofrom: c) if(b > g) foo(); // CHECK-NEXT: foo(); #pragma omp target data map(x[0:10], c) // CHECK-NEXT: #pragma omp target data map(tofrom: x[0:10],c) foo(); // CHECK-NEXT: foo(); #pragma omp target data map(to: c) map(from: d) // CHECK-NEXT: #pragma omp target data map(to: c) map(from: d) foo(); // CHECK-NEXT: foo(); #pragma omp target data map(always,alloc: e) // CHECK-NEXT: #pragma omp target data map(always,alloc: e) foo(); // CHECK-NEXT: foo(); // nesting a target region #pragma omp target data map(e) // CHECK-NEXT: #pragma omp target data map(tofrom: e) { // CHECK-NEXT: { #pragma omp target map(always, alloc: e) // CHECK-NEXT: #pragma omp target map(always,alloc: e) foo(); // CHECK-NEXT: foo(); } return tmain<int, 5>(argc, &argc) + tmain<char, 1>(argv[0][0], argv[0]); } #endif
gpl-3.0
smithzvk/gsl-scattered-interpolation
specfunc/bessel_Jnu.c
4
6153
/* specfunc/bessel_Jnu.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, 2017 Konrad Griessinger * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_sf_sincos_pi.h> #include "error.h" #include "bessel.h" #include "bessel_olver.h" #include "bessel_temme.h" /* Evaluate at large enough nu to apply asymptotic * results and apply backward recurrence. */ #if 0 static int bessel_J_recur_asymp(const double nu, const double x, gsl_sf_result * Jnu, gsl_sf_result * Jnup1) { const double nu_cut = 25.0; int n; int steps = ceil(nu_cut - nu) + 1; gsl_sf_result r_Jnp1; gsl_sf_result r_Jn; int stat_O1 = gsl_sf_bessel_Jnu_asymp_Olver_e(nu + steps + 1.0, x, &r_Jnp1); int stat_O2 = gsl_sf_bessel_Jnu_asymp_Olver_e(nu + steps, x, &r_Jn); double r_fe = fabs(r_Jnp1.err/r_Jnp1.val) + fabs(r_Jn.err/r_Jn.val); double Jnp1 = r_Jnp1.val; double Jn = r_Jn.val; double Jnm1; double Jnp1_save; for(n=steps; n>0; n--) { Jnm1 = 2.0*(nu+n)/x * Jn - Jnp1; Jnp1 = Jn; Jnp1_save = Jn; Jn = Jnm1; } Jnu->val = Jn; Jnu->err = (r_fe + GSL_DBL_EPSILON * (steps + 1.0)) * fabs(Jn); Jnup1->val = Jnp1_save; Jnup1->err = (r_fe + GSL_DBL_EPSILON * (steps + 1.0)) * fabs(Jnp1_save); return GSL_ERROR_SELECT_2(stat_O1, stat_O2); } #endif /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_bessel_Jnupos_e(const double nu, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x == 0.0) { if(nu == 0.0) { result->val = 1.0; result->err = 0.0; } else { result->val = 0.0; result->err = 0.0; } return GSL_SUCCESS; } else if(x*x < 10.0*(nu+1.0)) { return gsl_sf_bessel_IJ_taylor_e(nu, x, -1, 100, GSL_DBL_EPSILON, result); } else if(nu > 50.0) { return gsl_sf_bessel_Jnu_asymp_Olver_e(nu, x, result); } else if(x > 1000.0) { /* We need this to avoid feeding large x to CF1; note that * due to the above check, we know that n <= 50. See similar * block in bessel_Jn.c. */ return gsl_sf_bessel_Jnu_asympx_e(nu, x, result); } else { /* -1/2 <= mu <= 1/2 */ int N = (int)(nu + 0.5); double mu = nu - N; /* Determine the J ratio at nu. */ double Jnup1_Jnu; double sgn_Jnu; const int stat_CF1 = gsl_sf_bessel_J_CF1(nu, x, &Jnup1_Jnu, &sgn_Jnu); if(x < 2.0) { /* Determine Y_mu, Y_mup1 directly and recurse forward to nu. * Then use the CF1 information to solve for J_nu and J_nup1. */ gsl_sf_result Y_mu, Y_mup1; const int stat_mu = gsl_sf_bessel_Y_temme(mu, x, &Y_mu, &Y_mup1); double Ynm1 = Y_mu.val; double Yn = Y_mup1.val; double Ynp1 = 0.0; int n; for(n=1; n<N; n++) { Ynp1 = 2.0*(mu+n)/x * Yn - Ynm1; Ynm1 = Yn; Yn = Ynp1; } result->val = 2.0/(M_PI*x) / (Jnup1_Jnu*Yn - Ynp1); result->err = GSL_DBL_EPSILON * (N + 2.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_mu, stat_CF1); } else { /* Recurse backward from nu to mu, determining the J ratio * at mu. Use this together with a Steed method CF2 to * determine the actual J_mu, and thus obtain the normalization. */ double Jmu; double Jmup1_Jmu; double sgn_Jmu; double Jmuprime_Jmu; double P, Q; const int stat_CF2 = gsl_sf_bessel_JY_steed_CF2(mu, x, &P, &Q); double gamma; double Jnp1 = sgn_Jnu * GSL_SQRT_DBL_MIN * Jnup1_Jnu; double Jn = sgn_Jnu * GSL_SQRT_DBL_MIN; double Jnm1; int n; for(n=N; n>0; n--) { Jnm1 = 2.0*(mu+n)/x * Jn - Jnp1; Jnp1 = Jn; Jn = Jnm1; } Jmup1_Jmu = Jnp1/Jn; sgn_Jmu = GSL_SIGN(Jn); Jmuprime_Jmu = mu/x - Jmup1_Jmu; gamma = (P - Jmuprime_Jmu)/Q; Jmu = sgn_Jmu * sqrt(2.0/(M_PI*x) / (Q + gamma*(P-Jmuprime_Jmu))); result->val = Jmu * (sgn_Jnu * GSL_SQRT_DBL_MIN) / Jn; result->err = 2.0 * GSL_DBL_EPSILON * (N + 2.0) * fabs(result->val); return GSL_ERROR_SELECT_2(stat_CF2, stat_CF1); } } } int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(x <= 0.0) { DOMAIN_ERROR(result); } else if (nu < 0.0) { int Jstatus = gsl_sf_bessel_Jnupos_e(-nu, x, result); double Jval = result->val; double Jerr = result->err; int Ystatus = gsl_sf_bessel_Ynupos_e(-nu, x, result); double Yval = result->val; double Yerr = result->err; /* double s = sin(M_PI*nu), c = cos(M_PI*nu); */ int sinstatus = gsl_sf_sin_pi_e(nu, result); double s = result->val; double serr = result->err; int cosstatus = gsl_sf_cos_pi_e(nu, result); double c = result->val; double cerr = result->err; result->val = s*Yval + c*Jval; result->err = fabs(c*Yerr) + fabs(s*Jerr) + fabs(cerr*Yval) + fabs(serr*Jval); return GSL_ERROR_SELECT_4(Jstatus, Ystatus, sinstatus, cosstatus); } else return gsl_sf_bessel_Jnupos_e(nu, x, result); } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_bessel_Jnu(const double nu, const double x) { EVAL_RESULT(gsl_sf_bessel_Jnu_e(nu, x, &result)); }
gpl-3.0
ctubio/claws
src/plugins/vcalendar/day-view.c
4
30599
/* * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client * * Copyright (c) 2007-2008 Juha Kautto (juha at xfce.org) * Copyright (c) 2008 Colin Leroy (colin@colino.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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #include "claws-features.h" #endif #include <stddef.h> #include <glib.h> #include <glib/gi18n.h> #include "defs.h" #ifdef USE_PTHREAD #include <pthread.h> #endif #include <string.h> #include <time.h> #include <glib.h> #include <glib/gprintf.h> #include <gdk/gdkkeysyms.h> #include <gdk/gdk.h> #include <gtk/gtk.h> #include "summaryview.h" #include "vcalendar.h" #include "vcal_folder.h" #include "vcal_prefs.h" #include "vcal_manager.h" #include "common-views.h" #include "vcal_meeting_gtk.h" #define MAX_DAYS 40 struct _day_win { GtkAccelGroup *accel_group; GtkWidget *Window; GtkWidget *Vbox; GtkWidget *Menubar; GtkWidget *File_menu; GtkWidget *File_menu_new; GtkWidget *File_menu_close; GtkWidget *View_menu; GtkWidget *View_menu_refresh; GtkWidget *Go_menu; GtkWidget *Go_menu_today; GtkWidget *Go_menu_prev; GtkWidget *Go_menu_next; GtkWidget *Toolbar; GtkWidget *Create_toolbutton; GtkWidget *Previous_toolbutton; GtkWidget *Today_toolbutton; GtkWidget *Next_toolbutton; GtkWidget *Refresh_toolbutton; GtkWidget *Close_toolbutton; GtkWidget *StartDate_button; GtkRequisition StartDate_button_req; GtkWidget *day_spin; GtkWidget *day_view_vbox; GtkWidget *scroll_win_h; GtkWidget *dtable_h; /* header of day table */ GtkWidget *scroll_win; GtkWidget *dtable; /* day table */ GtkRequisition hour_req; GtkWidget *header[MAX_DAYS]; GtkWidget *element[24][MAX_DAYS]; GtkWidget *line[24][MAX_DAYS]; guint upd_timer; gdouble scroll_pos; /* remember the scroll position */ GdkColor bg1, bg2, line_color, bg_today, fg_sunday; GList *apptw_list; /* keep track of appointments being updated */ struct tm startdate; FolderItem *item; gulong selsig; GtkWidget *view_menu; GtkWidget *event_menu; GtkActionGroup *event_group; GtkUIManager *ui_manager; }; static gchar *get_locale_date(struct tm *tmdate) { gchar *d = g_malloc(100); strftime(d, 99, "%x", tmdate); return d; } static void set_scroll_position(day_win *dw) { GtkAdjustment *v_adj; v_adj = gtk_scrolled_window_get_vadjustment( GTK_SCROLLED_WINDOW(dw->scroll_win)); if (dw->scroll_pos > 0) /* we have old value */ gtk_adjustment_set_value(v_adj, dw->scroll_pos); else if (dw->scroll_pos < 0) /* default: let's try to start roughly from line 8 = 8 o'clock */ gtk_adjustment_set_value(v_adj, v_adj->upper/3); gtk_adjustment_changed(v_adj); } static gboolean scroll_position_timer(gpointer user_data) { set_scroll_position((day_win *)user_data); return(FALSE); /* only once */ } static void get_scroll_position(day_win *dw) { GtkAdjustment *v_adj; v_adj = gtk_scrolled_window_get_vadjustment( GTK_SCROLLED_WINDOW(dw->scroll_win)); dw->scroll_pos = gtk_adjustment_get_value(v_adj); } void dw_close_window(day_win *dw) { vcal_view_set_summary_page(dw->Vbox, dw->selsig); g_free(dw); dw = NULL; } static char *orage_tm_date_to_i18_date(struct tm *tm_date) { static char i18_date[32]; if (strftime(i18_date, 32, "%x", tm_date) == 0) g_error("Orage: orage_tm_date_to_i18_date too long string in strftime"); return(i18_date); } static void changeSelectedDate(day_win *dw, gint day) { if (day > 0) { do { orage_move_day(&(dw->startdate), 1); } while (--day > 0); } else { do { orage_move_day(&(dw->startdate), -1); } while (++day < 0); } } static gint on_Previous_clicked(GtkWidget *button, GdkEventButton *event, day_win *dw) { int days = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(dw->day_spin)); changeSelectedDate(dw, -days); refresh_day_win(dw); return TRUE; } static gint on_Next_clicked(GtkWidget *button, GdkEventButton *event, day_win *dw) { int days = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(dw->day_spin)); changeSelectedDate(dw, +days); refresh_day_win(dw); return TRUE; } static void dw_summary_selected(GtkCMCTree *ctree, GtkCMCTreeNode *row, gint column, day_win *dw) { MsgInfo *msginfo = gtk_cmctree_node_get_row_data(ctree, row); int days = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(dw->day_spin)); if (msginfo && msginfo->msgid) { VCalEvent *event = vcal_manager_load_event(msginfo->msgid); if (event) { time_t t_first = mktime(&dw->startdate); time_t t_start = icaltime_as_timet(icaltime_from_string(event->dtstart)); struct tm tm_start; gboolean changed = FALSE; GtkAdjustment *v_adj; #ifdef G_OS_WIN32 if (t_start < 0) t_start = 1; #endif localtime_r(&t_start, &tm_start); tm_start.tm_hour = tm_start.tm_min = tm_start.tm_sec = 0; t_start = mktime(&tm_start); while (t_start < t_first) { changeSelectedDate(dw, -days); t_first = mktime(&dw->startdate); changed = TRUE; } while (t_start > t_first + (days-1)*24*60*60) { changeSelectedDate(dw, +days); t_first = mktime(&dw->startdate); changed = TRUE; } t_start = icaltime_as_timet(icaltime_from_string(event->dtstart)); #ifdef G_OS_WIN32 if (t_start < 0) t_start = 1; #endif localtime_r(&t_start, &tm_start); if (changed) { debug_print("changed from %s\n", event->summary); v_adj = gtk_scrolled_window_get_vadjustment( GTK_SCROLLED_WINDOW(dw->scroll_win)); #ifdef G_OS_WIN32 if (t_start < 0) t_start = 1; #endif localtime_r(&t_start, &tm_start); if (tm_start.tm_hour > 2) gtk_adjustment_set_value(v_adj, (v_adj->upper-v_adj->page_size)/(24/(tm_start.tm_hour-2))); else gtk_adjustment_set_value(v_adj, 0); gtk_adjustment_changed(v_adj); refresh_day_win(dw); } } vcal_manager_free_event(event); } } static void day_view_new_meeting_cb(day_win *dw, gpointer data_i, gpointer data_s) { int offset = GPOINTER_TO_INT(data_i); struct tm tm_date = dw->startdate; int offset_h = offset % 1000; int offset_d = (offset-offset_h) / 1000; guint monthdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int mon = tm_date.tm_mon; if (((tm_date.tm_year%4) == 0) && (((tm_date.tm_year%100) != 0) || ((tm_date.tm_year%400) == 0))) monthdays[1] = 29; if (offset_d > monthdays[mon]) { while (tm_date.tm_mday > 1) orage_move_day(&tm_date, 1); offset_d -= monthdays[mon]; } while (offset_d > tm_date.tm_mday) { orage_move_day(&tm_date, 1); } while (offset_d < tm_date.tm_mday) { orage_move_day(&tm_date, -1); } tm_date.tm_hour = offset_h; vcal_meeting_create_with_start(NULL, &tm_date); } static void day_view_edit_meeting_cb(day_win *dw, gpointer data_i, gpointer data_s) { const gchar *uid = (gchar *)data_s; vcal_view_select_event (uid, dw->item, TRUE, G_CALLBACK(dw_summary_selected), dw); } static void day_view_cancel_meeting_cb(day_win *dw, gpointer data_i, gpointer data_s) { const gchar *uid = (gchar *)data_s; vcalendar_cancel_meeting(dw->item, uid); } static void day_view_today_cb(day_win *dw, gpointer data_i, gpointer data_s) { time_t now = time(NULL); struct tm tm_today; localtime_r(&now, &tm_today); while (tm_today.tm_wday != 1) orage_move_day(&tm_today, -1); dw->startdate = tm_today; refresh_day_win(dw); } static void header_button_clicked_cb(GtkWidget *button, day_win *dw) { int offset = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "offset")); day_view_new_meeting_cb(dw, GINT_TO_POINTER(offset), NULL); } static void on_button_press_event_cb(GtkWidget *widget , GdkEventButton *event, gpointer *user_data) { day_win *dw = (day_win *)user_data; gchar *uid = g_object_get_data(G_OBJECT(widget), "UID"); gpointer offset = g_object_get_data(G_OBJECT(widget), "offset"); if (event->button == 1) { if (uid) vcal_view_select_event (uid, dw->item, (event->type==GDK_2BUTTON_PRESS), G_CALLBACK(dw_summary_selected), dw); } if (event->button == 3) { g_object_set_data(G_OBJECT(dw->Vbox), "menu_win", dw); g_object_set_data(G_OBJECT(dw->Vbox), "menu_data_i", offset); g_object_set_data(G_OBJECT(dw->Vbox), "menu_data_s", uid); g_object_set_data(G_OBJECT(dw->Vbox), "new_meeting_cb", day_view_new_meeting_cb); g_object_set_data(G_OBJECT(dw->Vbox), "edit_meeting_cb", day_view_edit_meeting_cb); g_object_set_data(G_OBJECT(dw->Vbox), "cancel_meeting_cb", day_view_cancel_meeting_cb); g_object_set_data(G_OBJECT(dw->Vbox), "go_today_cb", day_view_today_cb); if (uid) gtk_menu_popup(GTK_MENU(dw->event_menu), NULL, NULL, NULL, NULL, event->button, event->time); else gtk_menu_popup(GTK_MENU(dw->view_menu), NULL, NULL, NULL, NULL, event->button, event->time); } } static void add_row(day_win *dw, VCalEvent *event, gint days) { gint row, start_row, end_row; gint col, start_col, end_col, first_col, last_col; gint height, start_height, end_height; gchar *text, *tip, *start_date, *end_date; GtkWidget *ev, *lab, *hb; time_t t_start, t_end; struct tm tm_first, tm_start, tm_end; /* First clarify timings */ t_start = icaltime_as_timet(icaltime_from_string(event->dtstart)); if (event->dtend && *event->dtend) t_end = icaltime_as_timet(icaltime_from_string(event->dtend)); else t_end = t_start; #ifdef G_OS_WIN32 if (t_start < 0) t_start = 1; if (t_end < 0) t_end = 1; #endif localtime_r(&t_start, &tm_start); localtime_r(&t_end, &tm_end); tm_first = dw->startdate; tm_first.tm_year += 1900; tm_first.tm_mon += 1; tm_start.tm_year += 1900; tm_start.tm_mon += 1; tm_end.tm_year += 1900; tm_end.tm_mon += 1; start_col = orage_days_between(&tm_first, &tm_start)+1; end_col = orage_days_between(&tm_first, &tm_end)+1; if (end_col < 1) return; if (start_col > days) return; else { col = start_col; row = tm_start.tm_hour; } /* then add the appointment */ text = g_strdup(event->summary?event->summary : _("Unknown")); ev = gtk_event_box_new(); lab = gtk_label_new(text); gtk_misc_set_alignment(GTK_MISC(lab), 0.0, 0.5); gtk_label_set_ellipsize(GTK_LABEL(lab), PANGO_ELLIPSIZE_END); gtk_container_add(GTK_CONTAINER(ev), lab); if ((row % 2) == 1) gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg1); else gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg2); if (dw->element[row][col] == NULL) { hb = gtk_hbox_new(TRUE, 3); dw->element[row][col] = hb; } else { hb = dw->element[row][col]; /* FIXME: set some real bar here to make it visible that we * have more than 1 appointment here */ } if (orage_days_between(&tm_start, &tm_end) == 0) tip = g_strdup_printf("%s\n%02d:%02d-%02d:%02d\n%s" , text, tm_start.tm_hour, tm_start.tm_min , tm_end.tm_hour, tm_end.tm_min, event->description); else { /* we took the date in unnormalized format, so we need to do that now */ start_date = g_strdup(orage_tm_date_to_i18_date(&tm_start)); end_date = g_strdup(orage_tm_date_to_i18_date(&tm_end)); tip = g_strdup_printf("%s\n%s %02d:%02d - %s %02d:%02d\n%s" , text , start_date, tm_start.tm_hour, tm_start.tm_min , end_date, tm_end.tm_hour, tm_end.tm_min , event->description); g_free(start_date); g_free(end_date); } CLAWS_SET_TIP(ev, tip); /* gtk_box_pack_start(GTK_BOX(hb2), ev, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(hb), hb2, TRUE, TRUE, 0); */ gtk_box_pack_start(GTK_BOX(hb), ev, TRUE, TRUE, 0); g_object_set_data_full(G_OBJECT(ev), "UID", g_strdup(event->uid), g_free); g_object_set_data(G_OBJECT(ev), "offset", GINT_TO_POINTER(tm_start.tm_mday*1000 + tm_start.tm_hour)); g_signal_connect((gpointer)ev, "button-press-event" , G_CALLBACK(on_button_press_event_cb), dw); g_free(tip); g_free(text); /* and finally draw the line to show how long the appointment is, * but only if it is Busy type event (=availability != 0) * and it is not whole day event */ if (TRUE) { height = dw->StartDate_button_req.height; /* * same_date = !strncmp(start_ical_time, end_ical_time, 8); * */ if (start_col < 1) first_col = 1; else first_col = start_col; if (end_col > days) last_col = days; else last_col = end_col; for (col = first_col; col <= last_col; col++) { if (col == start_col) start_row = tm_start.tm_hour; else start_row = 0; if (col == end_col) end_row = tm_end.tm_hour; else end_row = 23; for (row = start_row; row <= end_row; row++) { if (row == tm_start.tm_hour && col == start_col) start_height = tm_start.tm_min*height/60; else start_height = 0; if (row == tm_end.tm_hour && col == end_col) end_height = tm_end.tm_min*height/60; else end_height = height; dw->line[row][col] = build_line(1, start_height , 2, end_height-start_height, dw->line[row][col] , &dw->line_color); } } } } static void app_rows(day_win *dw, FolderItem *item) { GSList *events = vcal_get_events_list(item); GSList *cur = NULL; int days = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(dw->day_spin)); for (cur = events; cur ; cur = cur->next) { VCalEvent *event = (VCalEvent *) (cur->data); add_row(dw, event, days); vcal_manager_free_event(event); } g_slist_free(events); } static void app_data(day_win *dw, FolderItem *item) { app_rows(dw, item); } static void fill_days(day_win *dw, gint days, FolderItem *item, gint first_col_day) { gint row, col, height, width; GtkWidget *ev, *hb; height = dw->StartDate_button_req.height; width = dw->StartDate_button_req.width; /* first clear the structure */ for (col = 1; col < days+1; col++) { dw->header[col] = NULL; for (row = 0; row < 24; row++) { dw->element[row][col] = NULL; /* gdk_draw_rectangle(, , , left_x, top_y, width, height); */ dw->line[row][col] = build_line(0, 0, 3, height, NULL , &dw->line_color); } } app_data(dw, item); for (col = 1; col < days+1; col++) { hb = gtk_hbox_new(FALSE, 0); /* check if we have full day events and put them to header */ if (dw->header[col]) { gtk_box_pack_start(GTK_BOX(hb), dw->header[col], TRUE, TRUE, 0); gtk_widget_set_size_request(hb, width, -1); } else { ev = gtk_event_box_new(); gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg2); gtk_box_pack_start(GTK_BOX(hb), ev, TRUE, TRUE, 0); } gtk_table_attach(GTK_TABLE(dw->dtable_h), hb, col, col+1, 1, 2 , (GTK_FILL), (0), 0, 0); /* check rows */ for (row = 0; row < 24; row++) { hb = gtk_hbox_new(FALSE, 0); if (row == 0) gtk_widget_set_size_request(hb, width, -1); if (dw->element[row][col]) { gtk_box_pack_start(GTK_BOX(hb), dw->line[row][col] , FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(hb), dw->element[row][col] , TRUE, TRUE, 0); gtk_widget_set_size_request(hb, width, -1); } else { ev = gtk_event_box_new(); g_object_set_data(G_OBJECT(ev), "offset", GINT_TO_POINTER(first_col_day*1000 + row)); g_signal_connect((gpointer)ev, "button-press-event" , G_CALLBACK(on_button_press_event_cb), dw); /* name = gtk_label_new(" "); gtk_container_add(GTK_CONTAINER(ev), name); */ if ((row % 2) == 1) gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg1); else gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg2); gtk_box_pack_start(GTK_BOX(hb), dw->line[row][col] , FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(hb), ev, TRUE, TRUE, 0); } gtk_table_attach(GTK_TABLE(dw->dtable), hb, col, col+1, row, row+1 , (GTK_FILL), (0), 0, 0); } first_col_day++; } } static void build_day_view_header(day_win *dw, char *start_date) { GtkWidget *hbox, *label, *space_label; SummaryView *summaryview = NULL; int avail_w = 0, avail_d = 0; hbox = gtk_hbox_new(FALSE, 0); label = gtk_label_new(_("Start")); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 10); /* start date button */ dw->StartDate_button = gtk_button_new(); gtk_box_pack_start(GTK_BOX(hbox), dw->StartDate_button, FALSE, FALSE, 0); space_label = gtk_label_new(" "); gtk_box_pack_start(GTK_BOX(hbox), space_label, FALSE, FALSE, 0); space_label = gtk_label_new(" "); gtk_box_pack_start(GTK_BOX(hbox), space_label, FALSE, FALSE, 0); label = gtk_label_new(_("Show")); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 10); /* show days spin = how many days to show */ dw->day_spin = gtk_spin_button_new_with_range(1, MAX_DAYS, 1); gtk_spin_button_set_wrap(GTK_SPIN_BUTTON(dw->day_spin), TRUE); gtk_widget_set_size_request(dw->day_spin, 40, -1); gtk_box_pack_start(GTK_BOX(hbox), dw->day_spin, FALSE, FALSE, 0); label = gtk_label_new(_("days")); gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 5); space_label = gtk_label_new(" "); gtk_box_pack_start(GTK_BOX(hbox), space_label, FALSE, FALSE, 0); /* sizes */ gtk_button_set_label(GTK_BUTTON(dw->StartDate_button) , (const gchar *)start_date); gtk_widget_size_request(dw->StartDate_button, &dw->StartDate_button_req); dw->StartDate_button_req.width += dw->StartDate_button_req.width/10; label = gtk_label_new("00"); gtk_widget_size_request(label, &dw->hour_req); if (mainwindow_get_mainwindow()) { GtkAllocation allocation; summaryview = mainwindow_get_mainwindow()->summaryview; allocation = summaryview->mainwidget_book->allocation; avail_w = allocation.width - 20 - 2*(dw->hour_req.width); avail_d = avail_w / dw->StartDate_button_req.width; } if (avail_d >= 7) { avail_d = 7; gtk_widget_set_size_request(dw->StartDate_button, avail_w / avail_d, -1); gtk_widget_size_request(dw->StartDate_button, &dw->StartDate_button_req); } /* initial values */ if (avail_d) gtk_spin_button_set_value(GTK_SPIN_BUTTON(dw->day_spin), avail_d); } static void build_day_view_colours(day_win *dw) { GtkStyle *def_style; GdkColormap *pic1_cmap; GtkWidget *ctree = NULL; def_style = gtk_widget_get_default_style(); pic1_cmap = gdk_colormap_get_system(); if (mainwindow_get_mainwindow()) { ctree = mainwindow_get_mainwindow()->summaryview->ctree; } if (ctree) { dw->bg1 = ctree->style->bg[GTK_STATE_NORMAL]; dw->bg2 = ctree->style->bg[GTK_STATE_NORMAL]; } else { dw->bg1 = def_style->bg[GTK_STATE_NORMAL]; dw->bg2 = def_style->bg[GTK_STATE_NORMAL]; } dw->bg1.red += (dw->bg1.red < 63000 ? 2000 : -2000); dw->bg1.green += (dw->bg1.green < 63000 ? 2000 : -2000); dw->bg1.blue += (dw->bg1.blue < 63000 ? 2000 : -2000); gdk_colormap_alloc_color(pic1_cmap, &dw->bg1, FALSE, TRUE); dw->bg2.red += (dw->bg2.red > 1000 ? -1000 : 1000); dw->bg2.green += (dw->bg2.green > 1000 ? -1000 : 1000); dw->bg2.blue += (dw->bg2.blue > 1000 ? -1000 : 1000); gdk_colormap_alloc_color(pic1_cmap, &dw->bg2, FALSE, TRUE); if (!gdk_color_parse("white", &dw->line_color)) { dw->line_color.red = 239 * (65535/255); dw->line_color.green = 235 * (65535/255); dw->line_color.blue = 230 * (65535/255); } if (!gdk_color_parse("blue", &dw->fg_sunday)) { g_warning("color parse failed: red\n"); dw->fg_sunday.red = 10 * (65535/255); dw->fg_sunday.green = 10 * (65535/255); dw->fg_sunday.blue = 255 * (65535/255); } if (!gdk_color_parse("gold", &dw->bg_today)) { g_warning("color parse failed: gold\n"); dw->bg_today.red = 255 * (65535/255); dw->bg_today.green = 215 * (65535/255); dw->bg_today.blue = 115 * (65535/255); } if (ctree) { dw->fg_sunday.red = (dw->fg_sunday.red + ctree->style->fg[GTK_STATE_SELECTED].red)/2; dw->fg_sunday.green = (dw->fg_sunday.green + ctree->style->fg[GTK_STATE_SELECTED].red)/2; dw->fg_sunday.blue = (3*dw->fg_sunday.blue + ctree->style->fg[GTK_STATE_SELECTED].red)/4; dw->bg_today.red = (3*dw->bg_today.red + ctree->style->bg[GTK_STATE_NORMAL].red)/4; dw->bg_today.green = (3*dw->bg_today.green + ctree->style->bg[GTK_STATE_NORMAL].red)/4; dw->bg_today.blue = (3*dw->bg_today.blue + ctree->style->bg[GTK_STATE_NORMAL].red)/4; } gdk_colormap_alloc_color(pic1_cmap, &dw->line_color, FALSE, TRUE); gdk_colormap_alloc_color(pic1_cmap, &dw->fg_sunday, FALSE, TRUE); gdk_colormap_alloc_color(pic1_cmap, &dw->bg_today, FALSE, TRUE); } static void fill_hour(day_win *dw, gint col, gint row, char *text) { GtkWidget *name, *ev; ev = gtk_event_box_new(); name = gtk_label_new(text); gtk_container_add(GTK_CONTAINER(ev), name); if ((row % 2) == 1) gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg1); else gtk_widget_modify_bg(ev, GTK_STATE_NORMAL, &dw->bg2); gtk_widget_set_size_request(ev, dw->hour_req.width , dw->StartDate_button_req.height); if (text) gtk_table_attach(GTK_TABLE(dw->dtable), ev, col, col+1, row, row+1 , (GTK_FILL), (0), 0, 0); else /* special, needed for header table full day events */ gtk_table_attach(GTK_TABLE(dw->dtable_h), ev, col, col+1, row, row+1 , (GTK_FILL), (0), 0, 0); } static void build_day_view_table(day_win *dw) { gint days; /* number of days to show */ gint i = 0; GtkWidget *label, *button; char text[5+1], *date, *today; struct tm tm_date, tm_today; guint monthdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; GtkWidget *vp; time_t t = time(NULL); GtkWidget *arrow; gchar *tip; gint first_col_day = -1; #ifdef G_OS_WIN32 if (t < 0) t = 1; #endif localtime_r(&t, &tm_today); days = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(dw->day_spin)); today = get_locale_date(&tm_today); /****** header of day table = days columns ******/ dw->scroll_win_h = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dw->scroll_win_h) , GTK_POLICY_AUTOMATIC, GTK_POLICY_NEVER); gtk_box_pack_start(GTK_BOX(dw->Vbox), dw->scroll_win_h , TRUE, TRUE, 0); dw->day_view_vbox = gtk_vbox_new(FALSE, 0); gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(dw->scroll_win_h) , dw->day_view_vbox); /* gtk_container_add(GTK_CONTAINER(dw->scroll_win_h), dw->day_view_vbox); */ /* row 1= day header buttons * row 2= full day events after the buttons */ dw->dtable_h = gtk_table_new(2 , days+2, FALSE); gtk_box_pack_start(GTK_BOX(dw->day_view_vbox), dw->dtable_h , FALSE, FALSE, 0); tm_date = dw->startdate; if (((tm_date.tm_year%4) == 0) && (((tm_date.tm_year%100) != 0) || ((tm_date.tm_year%400) == 0))) monthdays[1] = 29; i=0; dw->Previous_toolbutton = gtk_event_box_new(); gtk_event_box_set_visible_window(GTK_EVENT_BOX(dw->Previous_toolbutton), FALSE); gtk_container_set_border_width(GTK_CONTAINER(dw->Previous_toolbutton), 0); arrow = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_NONE); gtk_container_add(GTK_CONTAINER(dw->Previous_toolbutton), arrow); gtk_table_attach(GTK_TABLE(dw->dtable_h), dw->Previous_toolbutton, i, i+1, 0, 1 , (GTK_FILL), (0), 0, 0); gtk_widget_show_all(dw->Previous_toolbutton); g_signal_connect((gpointer)dw->Previous_toolbutton, "button_release_event" , G_CALLBACK(on_Previous_clicked), dw); tip = g_strdup_printf("Back %d days", days); CLAWS_SET_TIP(dw->Previous_toolbutton, tip); g_free(tip); for (i = 1; i < days+1; i++) { tip = g_malloc(100); strftime(tip, 99, "%A %d %B %Y", &tm_date); if (first_col_day == -1) first_col_day = tm_date.tm_mday; date = get_locale_date(&tm_date); button = gtk_button_new(); gtk_button_set_label(GTK_BUTTON(button), date); if (strcmp(today, date) == 0) { gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &dw->bg_today); } if (tm_date.tm_wday % 7 == 0) { label = gtk_bin_get_child(GTK_BIN(button)); gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &dw->fg_sunday); } CLAWS_SET_TIP(button, tip); g_free(tip); gtk_widget_set_size_request(button, dw->StartDate_button_req.width, -1); g_signal_connect((gpointer)button, "clicked" , G_CALLBACK(header_button_clicked_cb), dw); g_object_set_data(G_OBJECT(button), "offset", GINT_TO_POINTER(tm_date.tm_mday*1000)); gtk_table_attach(GTK_TABLE(dw->dtable_h), button, i, i+1, 0, 1 , (GTK_FILL), (0), 0, 0); if (++tm_date.tm_mday == (monthdays[tm_date.tm_mon]+1)) { if (++tm_date.tm_mon == 12) { ++tm_date.tm_year; tm_date.tm_mon = 0; } tm_date.tm_mday = 1; } ++tm_date.tm_wday; tm_date.tm_wday %=7; g_free(date); } dw->Next_toolbutton = gtk_event_box_new(); gtk_event_box_set_visible_window(GTK_EVENT_BOX(dw->Next_toolbutton), FALSE); gtk_container_set_border_width(GTK_CONTAINER(dw->Next_toolbutton), 0); arrow = gtk_arrow_new(GTK_ARROW_RIGHT, GTK_SHADOW_NONE); gtk_container_add(GTK_CONTAINER(dw->Next_toolbutton), arrow); gtk_table_attach(GTK_TABLE(dw->dtable_h), dw->Next_toolbutton, i, i+1, 0, 1 , (GTK_FILL), (0), 0, 0); gtk_widget_show_all(dw->Next_toolbutton); g_signal_connect((gpointer)dw->Next_toolbutton, "button_release_event" , G_CALLBACK(on_Next_clicked), dw); tip = g_strdup_printf("Forward %d days", days); CLAWS_SET_TIP(dw->Next_toolbutton, tip); g_free(tip); g_free(today); /****** body of day table ******/ dw->scroll_win = gtk_scrolled_window_new(NULL, NULL); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(dw->scroll_win) , GTK_SHADOW_NONE); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(dw->scroll_win) , GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); gtk_scrolled_window_set_placement(GTK_SCROLLED_WINDOW(dw->scroll_win) , GTK_CORNER_TOP_LEFT); gtk_box_pack_start(GTK_BOX(dw->day_view_vbox), dw->scroll_win , TRUE, TRUE, 0); vp = gtk_viewport_new(NULL, NULL); gtk_viewport_set_shadow_type(GTK_VIEWPORT(vp), GTK_SHADOW_NONE); gtk_container_add(GTK_CONTAINER(dw->scroll_win), vp); dw->dtable = gtk_table_new(24, days+2, FALSE); gtk_container_add(GTK_CONTAINER(vp), dw->dtable); gtk_widget_show_all(dw->dtable_h); /* hours column = hour rows */ for (i = 0; i < 24; i++) { g_sprintf(text, "%02d", i); /* ev is needed for background colour */ fill_hour(dw, 0, i, text); fill_hour(dw, days+1, i, text); } fill_days(dw, days, dw->item, first_col_day); } void refresh_day_win(day_win *dw) { get_scroll_position(dw); gtk_widget_destroy(dw->scroll_win_h); build_day_view_table(dw); gtk_widget_show_all(dw->scroll_win_h); /* I was not able to get this work without the timer. Ugly yes, but * it works and does not hurt - much */ g_timeout_add(100, (GSourceFunc)scroll_position_timer, (gpointer)dw); } day_win *create_day_win(FolderItem *item, struct tm tmdate) { day_win *dw; char *start_date = get_locale_date(&tmdate); /* initialisation + main window + base vbox */ dw = g_new0(day_win, 1); dw->scroll_pos = -1; /* not set */ dw->accel_group = gtk_accel_group_new(); while (tmdate.tm_wday != 1) orage_move_day(&tmdate, -1); dw->startdate = tmdate; dw->startdate.tm_hour = 0; dw->startdate.tm_min = 0; dw->startdate.tm_sec = 0; dw->Vbox = gtk_vbox_new(FALSE, 0); dw->item = item; build_day_view_colours(dw); build_day_view_header(dw, start_date); build_day_view_table(dw); gtk_widget_show_all(dw->Vbox); dw->selsig = vcal_view_set_calendar_page(dw->Vbox, G_CALLBACK(dw_summary_selected), dw); vcal_view_create_popup_menus(dw->Vbox, &dw->view_menu, &dw->event_menu, &dw->event_group, &dw->ui_manager); g_timeout_add(100, (GtkFunction)scroll_position_timer, (gpointer)dw); return(dw); }
gpl-3.0
parallaxinc/propgcc
gcc/gcc/tree-ssa-forwprop.c
5
66953
/* Forward propagation of expressions for single use variables. Copyright (C) 2004, 2005, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "tm_p.h" #include "basic-block.h" #include "timevar.h" #include "tree-pretty-print.h" #include "tree-flow.h" #include "tree-pass.h" #include "tree-dump.h" #include "langhooks.h" #include "flags.h" #include "gimple.h" #include "expr.h" /* This pass propagates the RHS of assignment statements into use sites of the LHS of the assignment. It's basically a specialized form of tree combination. It is hoped all of this can disappear when we have a generalized tree combiner. One class of common cases we handle is forward propagating a single use variable into a COND_EXPR. bb0: x = a COND b; if (x) goto ... else goto ... Will be transformed into: bb0: if (a COND b) goto ... else goto ... Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1). Or (assuming c1 and c2 are constants): bb0: x = a + c1; if (x EQ/NEQ c2) goto ... else goto ... Will be transformed into: bb0: if (a EQ/NEQ (c2 - c1)) goto ... else goto ... Similarly for x = a - c1. Or bb0: x = !a if (x) goto ... else goto ... Will be transformed into: bb0: if (a == 0) goto ... else goto ... Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1). For these cases, we propagate A into all, possibly more than one, COND_EXPRs that use X. Or bb0: x = (typecast) a if (x) goto ... else goto ... Will be transformed into: bb0: if (a != 0) goto ... else goto ... (Assuming a is an integral type and x is a boolean or x is an integral and a is a boolean.) Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1). For these cases, we propagate A into all, possibly more than one, COND_EXPRs that use X. In addition to eliminating the variable and the statement which assigns a value to the variable, we may be able to later thread the jump without adding insane complexity in the dominator optimizer. Also note these transformations can cascade. We handle this by having a worklist of COND_EXPR statements to examine. As we make a change to a statement, we put it back on the worklist to examine on the next iteration of the main loop. A second class of propagation opportunities arises for ADDR_EXPR nodes. ptr = &x->y->z; res = *ptr; Will get turned into res = x->y->z; Or ptr = (type1*)&type2var; res = *ptr Will get turned into (if type1 and type2 are the same size and neither have volatile on them): res = VIEW_CONVERT_EXPR<type1>(type2var) Or ptr = &x[0]; ptr2 = ptr + <constant>; Will get turned into ptr2 = &x[constant/elementsize]; Or ptr = &x[0]; offset = index * element_size; offset_p = (pointer) offset; ptr2 = ptr + offset_p Will get turned into: ptr2 = &x[index]; Or ssa = (int) decl res = ssa & 1 Provided that decl has known alignment >= 2, will get turned into res = 0 We also propagate casts into SWITCH_EXPR and COND_EXPR conditions to allow us to remove the cast and {NOT_EXPR,NEG_EXPR} into a subsequent {NOT_EXPR,NEG_EXPR}. This will (of course) be extended as other needs arise. */ static bool forward_propagate_addr_expr (tree name, tree rhs); /* Set to true if we delete EH edges during the optimization. */ static bool cfg_changed; static tree rhs_to_tree (tree type, gimple stmt); /* Get the next statement we can propagate NAME's value into skipping trivial copies. Returns the statement that is suitable as a propagation destination or NULL_TREE if there is no such one. This only returns destinations in a single-use chain. FINAL_NAME_P if non-NULL is written to the ssa name that represents the use. */ static gimple get_prop_dest_stmt (tree name, tree *final_name_p) { use_operand_p use; gimple use_stmt; do { /* If name has multiple uses, bail out. */ if (!single_imm_use (name, &use, &use_stmt)) return NULL; /* If this is not a trivial copy, we found it. */ if (!gimple_assign_ssa_name_copy_p (use_stmt) || gimple_assign_rhs1 (use_stmt) != name) break; /* Continue searching uses of the copy destination. */ name = gimple_assign_lhs (use_stmt); } while (1); if (final_name_p) *final_name_p = name; return use_stmt; } /* Get the statement we can propagate from into NAME skipping trivial copies. Returns the statement which defines the propagation source or NULL_TREE if there is no such one. If SINGLE_USE_ONLY is set considers only sources which have a single use chain up to NAME. If SINGLE_USE_P is non-null, it is set to whether the chain to NAME is a single use chain or not. SINGLE_USE_P is not written to if SINGLE_USE_ONLY is set. */ static gimple get_prop_source_stmt (tree name, bool single_use_only, bool *single_use_p) { bool single_use = true; do { gimple def_stmt = SSA_NAME_DEF_STMT (name); if (!has_single_use (name)) { single_use = false; if (single_use_only) return NULL; } /* If name is defined by a PHI node or is the default def, bail out. */ if (!is_gimple_assign (def_stmt)) return NULL; /* If def_stmt is not a simple copy, we possibly found it. */ if (!gimple_assign_ssa_name_copy_p (def_stmt)) { tree rhs; if (!single_use_only && single_use_p) *single_use_p = single_use; /* We can look through pointer conversions in the search for a useful stmt for the comparison folding. */ rhs = gimple_assign_rhs1 (def_stmt); if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)) && TREE_CODE (rhs) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (gimple_assign_lhs (def_stmt))) && POINTER_TYPE_P (TREE_TYPE (rhs))) name = rhs; else return def_stmt; } else { /* Continue searching the def of the copy source name. */ name = gimple_assign_rhs1 (def_stmt); } } while (1); } /* Checks if the destination ssa name in DEF_STMT can be used as propagation source. Returns true if so, otherwise false. */ static bool can_propagate_from (gimple def_stmt) { use_operand_p use_p; ssa_op_iter iter; gcc_assert (is_gimple_assign (def_stmt)); /* If the rhs has side-effects we cannot propagate from it. */ if (gimple_has_volatile_ops (def_stmt)) return false; /* If the rhs is a load we cannot propagate from it. */ if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_reference || TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_declaration) return false; /* Constants can be always propagated. */ if (gimple_assign_single_p (def_stmt) && is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt))) return true; /* We cannot propagate ssa names that occur in abnormal phi nodes. */ FOR_EACH_SSA_USE_OPERAND (use_p, def_stmt, iter, SSA_OP_USE) if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (USE_FROM_PTR (use_p))) return false; /* If the definition is a conversion of a pointer to a function type, then we can not apply optimizations as some targets require function pointers to be canonicalized and in this case this optimization could eliminate a necessary canonicalization. */ if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt))) { tree rhs = gimple_assign_rhs1 (def_stmt); if (POINTER_TYPE_P (TREE_TYPE (rhs)) && TREE_CODE (TREE_TYPE (TREE_TYPE (rhs))) == FUNCTION_TYPE) return false; } return true; } /* Remove a copy chain ending in NAME along the defs. If NAME was replaced in its only use then this function can be used to clean up dead stmts. Returns true if cleanup-cfg has to run. */ static bool remove_prop_source_from_use (tree name) { gimple_stmt_iterator gsi; gimple stmt; bool cfg_changed = false; do { basic_block bb; if (!has_zero_uses (name)) return cfg_changed; stmt = SSA_NAME_DEF_STMT (name); gsi = gsi_for_stmt (stmt); bb = gimple_bb (stmt); release_defs (stmt); gsi_remove (&gsi, true); cfg_changed |= gimple_purge_dead_eh_edges (bb); name = (gimple_assign_copy_p (stmt)) ? gimple_assign_rhs1 (stmt) : NULL; } while (name && TREE_CODE (name) == SSA_NAME); return cfg_changed; } /* Return the rhs of a gimple_assign STMT in a form of a single tree, converted to type TYPE. This should disappear, but is needed so we can combine expressions and use the fold() interfaces. Long term, we need to develop folding and combine routines that deal with gimple exclusively . */ static tree rhs_to_tree (tree type, gimple stmt) { location_t loc = gimple_location (stmt); enum tree_code code = gimple_assign_rhs_code (stmt); if (get_gimple_rhs_class (code) == GIMPLE_TERNARY_RHS) return fold_build3_loc (loc, code, type, gimple_assign_rhs1 (stmt), gimple_assign_rhs2 (stmt), gimple_assign_rhs3 (stmt)); else if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS) return fold_build2_loc (loc, code, type, gimple_assign_rhs1 (stmt), gimple_assign_rhs2 (stmt)); else if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS) return build1 (code, type, gimple_assign_rhs1 (stmt)); else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS) return gimple_assign_rhs1 (stmt); else gcc_unreachable (); } /* Combine OP0 CODE OP1 in the context of a COND_EXPR. Returns the folded result in a form suitable for COND_EXPR_COND or NULL_TREE, if there is no suitable simplified form. If INVARIANT_ONLY is true only gimple_min_invariant results are considered simplified. */ static tree combine_cond_expr_cond (location_t loc, enum tree_code code, tree type, tree op0, tree op1, bool invariant_only) { tree t; gcc_assert (TREE_CODE_CLASS (code) == tcc_comparison); t = fold_binary_loc (loc, code, type, op0, op1); if (!t) return NULL_TREE; /* Require that we got a boolean type out if we put one in. */ gcc_assert (TREE_CODE (TREE_TYPE (t)) == TREE_CODE (type)); /* Canonicalize the combined condition for use in a COND_EXPR. */ t = canonicalize_cond_expr_cond (t); /* Bail out if we required an invariant but didn't get one. */ if (!t || (invariant_only && !is_gimple_min_invariant (t))) return NULL_TREE; return t; } /* Propagate from the ssa name definition statements of COND_EXPR in GIMPLE_COND statement STMT into the conditional if that simplifies it. Returns zero if no statement was changed, one if there were changes and two if cfg_cleanup needs to run. This must be kept in sync with forward_propagate_into_cond. */ static int forward_propagate_into_gimple_cond (gimple stmt) { int did_something = 0; location_t loc = gimple_location (stmt); do { tree tmp = NULL_TREE; tree name = NULL_TREE, rhs0 = NULL_TREE, rhs1 = NULL_TREE; gimple def_stmt; bool single_use0_p = false, single_use1_p = false; enum tree_code code = gimple_cond_code (stmt); /* We can do tree combining on SSA_NAME and comparison expressions. */ if (TREE_CODE_CLASS (gimple_cond_code (stmt)) == tcc_comparison) { /* For comparisons use the first operand, that is likely to simplify comparisons against constants. */ if (TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME) { name = gimple_cond_lhs (stmt); def_stmt = get_prop_source_stmt (name, false, &single_use0_p); if (def_stmt && can_propagate_from (def_stmt)) { tree op1 = gimple_cond_rhs (stmt); rhs0 = rhs_to_tree (TREE_TYPE (op1), def_stmt); tmp = combine_cond_expr_cond (loc, code, boolean_type_node, rhs0, op1, !single_use0_p); } } /* If that wasn't successful, try the second operand. */ if (tmp == NULL_TREE && TREE_CODE (gimple_cond_rhs (stmt)) == SSA_NAME) { tree op0 = gimple_cond_lhs (stmt); name = gimple_cond_rhs (stmt); def_stmt = get_prop_source_stmt (name, false, &single_use1_p); if (!def_stmt || !can_propagate_from (def_stmt)) return did_something; rhs1 = rhs_to_tree (TREE_TYPE (op0), def_stmt); tmp = combine_cond_expr_cond (loc, code, boolean_type_node, op0, rhs1, !single_use1_p); } /* If that wasn't successful either, try both operands. */ if (tmp == NULL_TREE && rhs0 != NULL_TREE && rhs1 != NULL_TREE) tmp = combine_cond_expr_cond (loc, code, boolean_type_node, rhs0, fold_convert_loc (loc, TREE_TYPE (rhs0), rhs1), !(single_use0_p && single_use1_p)); } if (tmp) { if (dump_file && tmp) { tree cond = build2 (gimple_cond_code (stmt), boolean_type_node, gimple_cond_lhs (stmt), gimple_cond_rhs (stmt)); fprintf (dump_file, " Replaced '"); print_generic_expr (dump_file, cond, 0); fprintf (dump_file, "' with '"); print_generic_expr (dump_file, tmp, 0); fprintf (dump_file, "'\n"); } gimple_cond_set_condition_from_tree (stmt, unshare_expr (tmp)); update_stmt (stmt); /* Remove defining statements. */ if (remove_prop_source_from_use (name) || is_gimple_min_invariant (tmp)) did_something = 2; else if (did_something == 0) did_something = 1; /* Continue combining. */ continue; } break; } while (1); return did_something; } /* Propagate from the ssa name definition statements of COND_EXPR in the rhs of statement STMT into the conditional if that simplifies it. Returns zero if no statement was changed, one if there were changes and two if cfg_cleanup needs to run. This must be kept in sync with forward_propagate_into_gimple_cond. */ static int forward_propagate_into_cond (gimple_stmt_iterator *gsi_p) { gimple stmt = gsi_stmt (*gsi_p); location_t loc = gimple_location (stmt); int did_something = 0; do { tree tmp = NULL_TREE; tree cond = gimple_assign_rhs1 (stmt); tree name, rhs0 = NULL_TREE, rhs1 = NULL_TREE; gimple def_stmt; bool single_use0_p = false, single_use1_p = false; /* We can do tree combining on SSA_NAME and comparison expressions. */ if (COMPARISON_CLASS_P (cond) && TREE_CODE (TREE_OPERAND (cond, 0)) == SSA_NAME) { /* For comparisons use the first operand, that is likely to simplify comparisons against constants. */ name = TREE_OPERAND (cond, 0); def_stmt = get_prop_source_stmt (name, false, &single_use0_p); if (def_stmt && can_propagate_from (def_stmt)) { tree op1 = TREE_OPERAND (cond, 1); rhs0 = rhs_to_tree (TREE_TYPE (op1), def_stmt); tmp = combine_cond_expr_cond (loc, TREE_CODE (cond), boolean_type_node, rhs0, op1, !single_use0_p); } /* If that wasn't successful, try the second operand. */ if (tmp == NULL_TREE && TREE_CODE (TREE_OPERAND (cond, 1)) == SSA_NAME) { tree op0 = TREE_OPERAND (cond, 0); name = TREE_OPERAND (cond, 1); def_stmt = get_prop_source_stmt (name, false, &single_use1_p); if (!def_stmt || !can_propagate_from (def_stmt)) return did_something; rhs1 = rhs_to_tree (TREE_TYPE (op0), def_stmt); tmp = combine_cond_expr_cond (loc, TREE_CODE (cond), boolean_type_node, op0, rhs1, !single_use1_p); } /* If that wasn't successful either, try both operands. */ if (tmp == NULL_TREE && rhs0 != NULL_TREE && rhs1 != NULL_TREE) tmp = combine_cond_expr_cond (loc, TREE_CODE (cond), boolean_type_node, rhs0, fold_convert_loc (loc, TREE_TYPE (rhs0), rhs1), !(single_use0_p && single_use1_p)); } else if (TREE_CODE (cond) == SSA_NAME) { name = cond; def_stmt = get_prop_source_stmt (name, true, NULL); if (def_stmt || !can_propagate_from (def_stmt)) return did_something; rhs0 = gimple_assign_rhs1 (def_stmt); tmp = combine_cond_expr_cond (loc, NE_EXPR, boolean_type_node, rhs0, build_int_cst (TREE_TYPE (rhs0), 0), false); } if (tmp) { if (dump_file && tmp) { fprintf (dump_file, " Replaced '"); print_generic_expr (dump_file, cond, 0); fprintf (dump_file, "' with '"); print_generic_expr (dump_file, tmp, 0); fprintf (dump_file, "'\n"); } gimple_assign_set_rhs_from_tree (gsi_p, unshare_expr (tmp)); stmt = gsi_stmt (*gsi_p); update_stmt (stmt); /* Remove defining statements. */ if (remove_prop_source_from_use (name) || is_gimple_min_invariant (tmp)) did_something = 2; else if (did_something == 0) did_something = 1; /* Continue combining. */ continue; } break; } while (1); return did_something; } /* We've just substituted an ADDR_EXPR into stmt. Update all the relevant data structures to match. */ static void tidy_after_forward_propagate_addr (gimple stmt) { /* We may have turned a trapping insn into a non-trapping insn. */ if (maybe_clean_or_replace_eh_stmt (stmt, stmt) && gimple_purge_dead_eh_edges (gimple_bb (stmt))) cfg_changed = true; if (TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR) recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt)); } /* DEF_RHS contains the address of the 0th element in an array. USE_STMT uses type of DEF_RHS to compute the address of an arbitrary element within the array. The (variable) byte offset of the element is contained in OFFSET. We walk back through the use-def chains of OFFSET to verify that it is indeed computing the offset of an element within the array and extract the index corresponding to the given byte offset. We then try to fold the entire address expression into a form &array[index]. If we are successful, we replace the right hand side of USE_STMT with the new address computation. */ static bool forward_propagate_addr_into_variable_array_index (tree offset, tree def_rhs, gimple_stmt_iterator *use_stmt_gsi) { tree index, tunit; gimple offset_def, use_stmt = gsi_stmt (*use_stmt_gsi); tree new_rhs, tmp; if (TREE_CODE (TREE_OPERAND (def_rhs, 0)) == ARRAY_REF) tunit = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (def_rhs))); else if (TREE_CODE (TREE_TYPE (TREE_OPERAND (def_rhs, 0))) == ARRAY_TYPE) tunit = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (TREE_TYPE (def_rhs)))); else return false; if (!host_integerp (tunit, 1)) return false; /* Get the offset's defining statement. */ offset_def = SSA_NAME_DEF_STMT (offset); /* Try to find an expression for a proper index. This is either a multiplication expression by the element size or just the ssa name we came along in case the element size is one. In that case, however, we do not allow multiplications because they can be computing index to a higher level dimension (PR 37861). */ if (integer_onep (tunit)) { if (is_gimple_assign (offset_def) && gimple_assign_rhs_code (offset_def) == MULT_EXPR) return false; index = offset; } else { /* The statement which defines OFFSET before type conversion must be a simple GIMPLE_ASSIGN. */ if (!is_gimple_assign (offset_def)) return false; /* The RHS of the statement which defines OFFSET must be a multiplication of an object by the size of the array elements. This implicitly verifies that the size of the array elements is constant. */ if (gimple_assign_rhs_code (offset_def) == MULT_EXPR && TREE_CODE (gimple_assign_rhs2 (offset_def)) == INTEGER_CST && tree_int_cst_equal (gimple_assign_rhs2 (offset_def), tunit)) { /* The first operand to the MULT_EXPR is the desired index. */ index = gimple_assign_rhs1 (offset_def); } /* If we have idx * tunit + CST * tunit re-associate that. */ else if ((gimple_assign_rhs_code (offset_def) == PLUS_EXPR || gimple_assign_rhs_code (offset_def) == MINUS_EXPR) && TREE_CODE (gimple_assign_rhs1 (offset_def)) == SSA_NAME && TREE_CODE (gimple_assign_rhs2 (offset_def)) == INTEGER_CST && (tmp = div_if_zero_remainder (EXACT_DIV_EXPR, gimple_assign_rhs2 (offset_def), tunit)) != NULL_TREE) { gimple offset_def2 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (offset_def)); if (is_gimple_assign (offset_def2) && gimple_assign_rhs_code (offset_def2) == MULT_EXPR && TREE_CODE (gimple_assign_rhs2 (offset_def2)) == INTEGER_CST && tree_int_cst_equal (gimple_assign_rhs2 (offset_def2), tunit)) { index = fold_build2 (gimple_assign_rhs_code (offset_def), TREE_TYPE (offset), gimple_assign_rhs1 (offset_def2), tmp); } else return false; } else return false; } /* Replace the pointer addition with array indexing. */ index = force_gimple_operand_gsi (use_stmt_gsi, index, true, NULL_TREE, true, GSI_SAME_STMT); if (TREE_CODE (TREE_OPERAND (def_rhs, 0)) == ARRAY_REF) { new_rhs = unshare_expr (def_rhs); TREE_OPERAND (TREE_OPERAND (new_rhs, 0), 1) = index; } else { new_rhs = build4 (ARRAY_REF, TREE_TYPE (TREE_TYPE (TREE_TYPE (def_rhs))), unshare_expr (TREE_OPERAND (def_rhs, 0)), index, integer_zero_node, NULL_TREE); new_rhs = build_fold_addr_expr (new_rhs); if (!useless_type_conversion_p (TREE_TYPE (gimple_assign_lhs (use_stmt)), TREE_TYPE (new_rhs))) { new_rhs = force_gimple_operand_gsi (use_stmt_gsi, new_rhs, true, NULL_TREE, true, GSI_SAME_STMT); new_rhs = fold_convert (TREE_TYPE (gimple_assign_lhs (use_stmt)), new_rhs); } } gimple_assign_set_rhs_from_tree (use_stmt_gsi, new_rhs); use_stmt = gsi_stmt (*use_stmt_gsi); /* That should have created gimple, so there is no need to record information to undo the propagation. */ fold_stmt_inplace (use_stmt); tidy_after_forward_propagate_addr (use_stmt); return true; } /* NAME is a SSA_NAME representing DEF_RHS which is of the form ADDR_EXPR <whatever>. Try to forward propagate the ADDR_EXPR into the use USE_STMT. Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF node or for recovery of array indexing from pointer arithmetic. Return true if the propagation was successful (the propagation can be not totally successful, yet things may have been changed). */ static bool forward_propagate_addr_expr_1 (tree name, tree def_rhs, gimple_stmt_iterator *use_stmt_gsi, bool single_use_p) { tree lhs, rhs, rhs2, array_ref; gimple use_stmt = gsi_stmt (*use_stmt_gsi); enum tree_code rhs_code; bool res = true; gcc_assert (TREE_CODE (def_rhs) == ADDR_EXPR); lhs = gimple_assign_lhs (use_stmt); rhs_code = gimple_assign_rhs_code (use_stmt); rhs = gimple_assign_rhs1 (use_stmt); /* Trivial cases. The use statement could be a trivial copy or a useless conversion. Recurse to the uses of the lhs as copyprop does not copy through different variant pointers and FRE does not catch all useless conversions. Treat the case of a single-use name and a conversion to def_rhs type separate, though. */ if (TREE_CODE (lhs) == SSA_NAME && ((rhs_code == SSA_NAME && rhs == name) || CONVERT_EXPR_CODE_P (rhs_code))) { /* Only recurse if we don't deal with a single use or we cannot do the propagation to the current statement. In particular we can end up with a conversion needed for a non-invariant address which we cannot do in a single statement. */ if (!single_use_p || (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs)) && (!is_gimple_min_invariant (def_rhs) || (INTEGRAL_TYPE_P (TREE_TYPE (lhs)) && POINTER_TYPE_P (TREE_TYPE (def_rhs)) && (TYPE_PRECISION (TREE_TYPE (lhs)) > TYPE_PRECISION (TREE_TYPE (def_rhs))))))) return forward_propagate_addr_expr (lhs, def_rhs); gimple_assign_set_rhs1 (use_stmt, unshare_expr (def_rhs)); if (useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs))) gimple_assign_set_rhs_code (use_stmt, TREE_CODE (def_rhs)); else gimple_assign_set_rhs_code (use_stmt, NOP_EXPR); return true; } /* Propagate through constant pointer adjustments. */ if (TREE_CODE (lhs) == SSA_NAME && rhs_code == POINTER_PLUS_EXPR && rhs == name && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST) { tree new_def_rhs; /* As we come here with non-invariant addresses in def_rhs we need to make sure we can build a valid constant offsetted address for further propagation. Simply rely on fold building that and check after the fact. */ new_def_rhs = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (rhs)), def_rhs, fold_convert (ptr_type_node, gimple_assign_rhs2 (use_stmt))); if (TREE_CODE (new_def_rhs) == MEM_REF && !is_gimple_mem_ref_addr (TREE_OPERAND (new_def_rhs, 0))) return false; new_def_rhs = build_fold_addr_expr_with_type (new_def_rhs, TREE_TYPE (rhs)); /* Recurse. If we could propagate into all uses of lhs do not bother to replace into the current use but just pretend we did. */ if (TREE_CODE (new_def_rhs) == ADDR_EXPR && forward_propagate_addr_expr (lhs, new_def_rhs)) return true; if (useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (new_def_rhs))) gimple_assign_set_rhs_with_ops (use_stmt_gsi, TREE_CODE (new_def_rhs), new_def_rhs, NULL_TREE); else if (is_gimple_min_invariant (new_def_rhs)) gimple_assign_set_rhs_with_ops (use_stmt_gsi, NOP_EXPR, new_def_rhs, NULL_TREE); else return false; gcc_assert (gsi_stmt (*use_stmt_gsi) == use_stmt); update_stmt (use_stmt); return true; } /* Now strip away any outer COMPONENT_REF/ARRAY_REF nodes from the LHS. ADDR_EXPR will not appear on the LHS. */ lhs = gimple_assign_lhs (use_stmt); while (handled_component_p (lhs)) lhs = TREE_OPERAND (lhs, 0); /* Now see if the LHS node is a MEM_REF using NAME. If so, propagate the ADDR_EXPR into the use of NAME and fold the result. */ if (TREE_CODE (lhs) == MEM_REF && TREE_OPERAND (lhs, 0) == name) { tree def_rhs_base; HOST_WIDE_INT def_rhs_offset; /* If the address is invariant we can always fold it. */ if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0), &def_rhs_offset))) { double_int off = mem_ref_offset (lhs); tree new_ptr; off = double_int_add (off, shwi_to_double_int (def_rhs_offset)); if (TREE_CODE (def_rhs_base) == MEM_REF) { off = double_int_add (off, mem_ref_offset (def_rhs_base)); new_ptr = TREE_OPERAND (def_rhs_base, 0); } else new_ptr = build_fold_addr_expr (def_rhs_base); TREE_OPERAND (lhs, 0) = new_ptr; TREE_OPERAND (lhs, 1) = double_int_to_tree (TREE_TYPE (TREE_OPERAND (lhs, 1)), off); tidy_after_forward_propagate_addr (use_stmt); /* Continue propagating into the RHS if this was not the only use. */ if (single_use_p) return true; } /* If the LHS is a plain dereference and the value type is the same as that of the pointed-to type of the address we can put the dereferenced address on the LHS preserving the original alias-type. */ else if (gimple_assign_lhs (use_stmt) == lhs && useless_type_conversion_p (TREE_TYPE (TREE_OPERAND (def_rhs, 0)), TREE_TYPE (gimple_assign_rhs1 (use_stmt)))) { tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0); tree new_offset, new_base, saved; while (handled_component_p (*def_rhs_basep)) def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0); saved = *def_rhs_basep; if (TREE_CODE (*def_rhs_basep) == MEM_REF) { new_base = TREE_OPERAND (*def_rhs_basep, 0); new_offset = int_const_binop (PLUS_EXPR, TREE_OPERAND (lhs, 1), TREE_OPERAND (*def_rhs_basep, 1), 0); } else { new_base = build_fold_addr_expr (*def_rhs_basep); new_offset = TREE_OPERAND (lhs, 1); } *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep), new_base, new_offset); gimple_assign_set_lhs (use_stmt, unshare_expr (TREE_OPERAND (def_rhs, 0))); *def_rhs_basep = saved; tidy_after_forward_propagate_addr (use_stmt); /* Continue propagating into the RHS if this was not the only use. */ if (single_use_p) return true; } else /* We can have a struct assignment dereferencing our name twice. Note that we didn't propagate into the lhs to not falsely claim we did when propagating into the rhs. */ res = false; } /* Strip away any outer COMPONENT_REF, ARRAY_REF or ADDR_EXPR nodes from the RHS. */ rhs = gimple_assign_rhs1 (use_stmt); if (TREE_CODE (rhs) == ADDR_EXPR) rhs = TREE_OPERAND (rhs, 0); while (handled_component_p (rhs)) rhs = TREE_OPERAND (rhs, 0); /* Now see if the RHS node is a MEM_REF using NAME. If so, propagate the ADDR_EXPR into the use of NAME and fold the result. */ if (TREE_CODE (rhs) == MEM_REF && TREE_OPERAND (rhs, 0) == name) { tree def_rhs_base; HOST_WIDE_INT def_rhs_offset; if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0), &def_rhs_offset))) { double_int off = mem_ref_offset (rhs); tree new_ptr; off = double_int_add (off, shwi_to_double_int (def_rhs_offset)); if (TREE_CODE (def_rhs_base) == MEM_REF) { off = double_int_add (off, mem_ref_offset (def_rhs_base)); new_ptr = TREE_OPERAND (def_rhs_base, 0); } else new_ptr = build_fold_addr_expr (def_rhs_base); TREE_OPERAND (rhs, 0) = new_ptr; TREE_OPERAND (rhs, 1) = double_int_to_tree (TREE_TYPE (TREE_OPERAND (rhs, 1)), off); fold_stmt_inplace (use_stmt); tidy_after_forward_propagate_addr (use_stmt); return res; } /* If the LHS is a plain dereference and the value type is the same as that of the pointed-to type of the address we can put the dereferenced address on the LHS preserving the original alias-type. */ else if (gimple_assign_rhs1 (use_stmt) == rhs && useless_type_conversion_p (TREE_TYPE (gimple_assign_lhs (use_stmt)), TREE_TYPE (TREE_OPERAND (def_rhs, 0)))) { tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0); tree new_offset, new_base, saved; while (handled_component_p (*def_rhs_basep)) def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0); saved = *def_rhs_basep; if (TREE_CODE (*def_rhs_basep) == MEM_REF) { new_base = TREE_OPERAND (*def_rhs_basep, 0); new_offset = int_const_binop (PLUS_EXPR, TREE_OPERAND (rhs, 1), TREE_OPERAND (*def_rhs_basep, 1), 0); } else { new_base = build_fold_addr_expr (*def_rhs_basep); new_offset = TREE_OPERAND (rhs, 1); } *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep), new_base, new_offset); gimple_assign_set_rhs1 (use_stmt, unshare_expr (TREE_OPERAND (def_rhs, 0))); *def_rhs_basep = saved; fold_stmt_inplace (use_stmt); tidy_after_forward_propagate_addr (use_stmt); return res; } } /* If the use of the ADDR_EXPR is not a POINTER_PLUS_EXPR, there is nothing to do. */ if (gimple_assign_rhs_code (use_stmt) != POINTER_PLUS_EXPR || gimple_assign_rhs1 (use_stmt) != name) return false; /* The remaining cases are all for turning pointer arithmetic into array indexing. They only apply when we have the address of element zero in an array. If that is not the case then there is nothing to do. */ array_ref = TREE_OPERAND (def_rhs, 0); if ((TREE_CODE (array_ref) != ARRAY_REF || TREE_CODE (TREE_TYPE (TREE_OPERAND (array_ref, 0))) != ARRAY_TYPE || TREE_CODE (TREE_OPERAND (array_ref, 1)) != INTEGER_CST) && TREE_CODE (TREE_TYPE (array_ref)) != ARRAY_TYPE) return false; rhs2 = gimple_assign_rhs2 (use_stmt); /* Try to optimize &x[C1] p+ C2 where C2 is a multiple of the size of the elements in X into &x[C1 + C2/element size]. */ if (TREE_CODE (rhs2) == INTEGER_CST) { tree new_rhs = maybe_fold_stmt_addition (gimple_location (use_stmt), TREE_TYPE (def_rhs), def_rhs, rhs2); if (new_rhs) { tree type = TREE_TYPE (gimple_assign_lhs (use_stmt)); new_rhs = unshare_expr (new_rhs); if (!useless_type_conversion_p (type, TREE_TYPE (new_rhs))) { if (!is_gimple_min_invariant (new_rhs)) new_rhs = force_gimple_operand_gsi (use_stmt_gsi, new_rhs, true, NULL_TREE, true, GSI_SAME_STMT); new_rhs = fold_convert (type, new_rhs); } gimple_assign_set_rhs_from_tree (use_stmt_gsi, new_rhs); use_stmt = gsi_stmt (*use_stmt_gsi); update_stmt (use_stmt); tidy_after_forward_propagate_addr (use_stmt); return true; } } /* Try to optimize &x[0] p+ OFFSET where OFFSET is defined by converting a multiplication of an index by the size of the array elements, then the result is converted into the proper type for the arithmetic. */ if (TREE_CODE (rhs2) == SSA_NAME && (TREE_CODE (array_ref) != ARRAY_REF || integer_zerop (TREE_OPERAND (array_ref, 1))) && useless_type_conversion_p (TREE_TYPE (name), TREE_TYPE (def_rhs)) /* Avoid problems with IVopts creating PLUS_EXPRs with a different type than their operands. */ && useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs))) return forward_propagate_addr_into_variable_array_index (rhs2, def_rhs, use_stmt_gsi); return false; } /* STMT is a statement of the form SSA_NAME = ADDR_EXPR <whatever>. Try to forward propagate the ADDR_EXPR into all uses of the SSA_NAME. Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF node or for recovery of array indexing from pointer arithmetic. Returns true, if all uses have been propagated into. */ static bool forward_propagate_addr_expr (tree name, tree rhs) { int stmt_loop_depth = gimple_bb (SSA_NAME_DEF_STMT (name))->loop_depth; imm_use_iterator iter; gimple use_stmt; bool all = true; bool single_use_p = has_single_use (name); FOR_EACH_IMM_USE_STMT (use_stmt, iter, name) { bool result; tree use_rhs; /* If the use is not in a simple assignment statement, then there is nothing we can do. */ if (gimple_code (use_stmt) != GIMPLE_ASSIGN) { if (!is_gimple_debug (use_stmt)) all = false; continue; } /* If the use is in a deeper loop nest, then we do not want to propagate non-invariant ADDR_EXPRs into the loop as that is likely adding expression evaluations into the loop. */ if (gimple_bb (use_stmt)->loop_depth > stmt_loop_depth && !is_gimple_min_invariant (rhs)) { all = false; continue; } { gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt); result = forward_propagate_addr_expr_1 (name, rhs, &gsi, single_use_p); /* If the use has moved to a different statement adjust the update machinery for the old statement too. */ if (use_stmt != gsi_stmt (gsi)) { update_stmt (use_stmt); use_stmt = gsi_stmt (gsi); } update_stmt (use_stmt); } all &= result; /* Remove intermediate now unused copy and conversion chains. */ use_rhs = gimple_assign_rhs1 (use_stmt); if (result && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME && TREE_CODE (use_rhs) == SSA_NAME && has_zero_uses (gimple_assign_lhs (use_stmt))) { gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt); release_defs (use_stmt); gsi_remove (&gsi, true); } } return all && has_zero_uses (name); } /* Forward propagate the comparison defined in STMT like cond_1 = x CMP y to uses of the form a_1 = (T')cond_1 a_1 = !cond_1 a_1 = cond_1 != 0 Returns true if stmt is now unused. */ static bool forward_propagate_comparison (gimple stmt) { tree name = gimple_assign_lhs (stmt); gimple use_stmt; tree tmp = NULL_TREE; /* Don't propagate ssa names that occur in abnormal phis. */ if ((TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs1 (stmt))) || (TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_assign_rhs2 (stmt)))) return false; /* Do not un-cse comparisons. But propagate through copies. */ use_stmt = get_prop_dest_stmt (name, &name); if (!use_stmt) return false; /* Conversion of the condition result to another integral type. */ if (is_gimple_assign (use_stmt) && (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (use_stmt)) || TREE_CODE_CLASS (gimple_assign_rhs_code (use_stmt)) == tcc_comparison || gimple_assign_rhs_code (use_stmt) == TRUTH_NOT_EXPR) && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (use_stmt)))) { tree lhs = gimple_assign_lhs (use_stmt); /* We can propagate the condition into a conversion. */ if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (use_stmt))) { /* Avoid using fold here as that may create a COND_EXPR with non-boolean condition as canonical form. */ tmp = build2 (gimple_assign_rhs_code (stmt), TREE_TYPE (lhs), gimple_assign_rhs1 (stmt), gimple_assign_rhs2 (stmt)); } /* We can propagate the condition into X op CST where op is EQ_EXPR or NE_EXPR and CST is either one or zero. */ else if (TREE_CODE_CLASS (gimple_assign_rhs_code (use_stmt)) == tcc_comparison && TREE_CODE (gimple_assign_rhs1 (use_stmt)) == SSA_NAME && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST) { enum tree_code code = gimple_assign_rhs_code (use_stmt); tree cst = gimple_assign_rhs2 (use_stmt); tree cond; cond = build2 (gimple_assign_rhs_code (stmt), TREE_TYPE (cst), gimple_assign_rhs1 (stmt), gimple_assign_rhs2 (stmt)); tmp = combine_cond_expr_cond (gimple_location (use_stmt), code, TREE_TYPE (lhs), cond, cst, false); if (tmp == NULL_TREE) return false; } /* We can propagate the condition into a statement that computes the logical negation of the comparison result. */ else if (gimple_assign_rhs_code (use_stmt) == TRUTH_NOT_EXPR) { tree type = TREE_TYPE (gimple_assign_rhs1 (stmt)); bool nans = HONOR_NANS (TYPE_MODE (type)); enum tree_code code; code = invert_tree_comparison (gimple_assign_rhs_code (stmt), nans); if (code == ERROR_MARK) return false; tmp = build2 (code, TREE_TYPE (lhs), gimple_assign_rhs1 (stmt), gimple_assign_rhs2 (stmt)); } else return false; { gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt); gimple_assign_set_rhs_from_tree (&gsi, unshare_expr (tmp)); use_stmt = gsi_stmt (gsi); update_stmt (use_stmt); } if (dump_file && (dump_flags & TDF_DETAILS)) { tree old_rhs = rhs_to_tree (TREE_TYPE (gimple_assign_lhs (stmt)), stmt); fprintf (dump_file, " Replaced '"); print_generic_expr (dump_file, old_rhs, dump_flags); fprintf (dump_file, "' with '"); print_generic_expr (dump_file, tmp, dump_flags); fprintf (dump_file, "'\n"); } /* Remove defining statements. */ return remove_prop_source_from_use (name); } return false; } /* If we have lhs = ~x (STMT), look and see if earlier we had x = ~y. If so, we can change STMT into lhs = y which can later be copy propagated. Similarly for negation. This could trivially be formulated as a forward propagation to immediate uses. However, we already had an implementation from DOM which used backward propagation via the use-def links. It turns out that backward propagation is actually faster as there's less work to do for each NOT/NEG expression we find. Backwards propagation needs to look at the statement in a single backlink. Forward propagation needs to look at potentially more than one forward link. */ static void simplify_not_neg_expr (gimple_stmt_iterator *gsi_p) { gimple stmt = gsi_stmt (*gsi_p); tree rhs = gimple_assign_rhs1 (stmt); gimple rhs_def_stmt = SSA_NAME_DEF_STMT (rhs); /* See if the RHS_DEF_STMT has the same form as our statement. */ if (is_gimple_assign (rhs_def_stmt) && gimple_assign_rhs_code (rhs_def_stmt) == gimple_assign_rhs_code (stmt)) { tree rhs_def_operand = gimple_assign_rhs1 (rhs_def_stmt); /* Verify that RHS_DEF_OPERAND is a suitable SSA_NAME. */ if (TREE_CODE (rhs_def_operand) == SSA_NAME && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand)) { gimple_assign_set_rhs_from_tree (gsi_p, rhs_def_operand); stmt = gsi_stmt (*gsi_p); update_stmt (stmt); } } } /* STMT is a SWITCH_EXPR for which we attempt to find equivalent forms of the condition which we may be able to optimize better. */ static void simplify_gimple_switch (gimple stmt) { tree cond = gimple_switch_index (stmt); tree def, to, ti; gimple def_stmt; /* The optimization that we really care about is removing unnecessary casts. That will let us do much better in propagating the inferred constant at the switch target. */ if (TREE_CODE (cond) == SSA_NAME) { def_stmt = SSA_NAME_DEF_STMT (cond); if (is_gimple_assign (def_stmt)) { if (gimple_assign_rhs_code (def_stmt) == NOP_EXPR) { int need_precision; bool fail; def = gimple_assign_rhs1 (def_stmt); /* ??? Why was Jeff testing this? We are gimple... */ gcc_checking_assert (is_gimple_val (def)); to = TREE_TYPE (cond); ti = TREE_TYPE (def); /* If we have an extension that preserves value, then we can copy the source value into the switch. */ need_precision = TYPE_PRECISION (ti); fail = false; if (! INTEGRAL_TYPE_P (ti)) fail = true; else if (TYPE_UNSIGNED (to) && !TYPE_UNSIGNED (ti)) fail = true; else if (!TYPE_UNSIGNED (to) && TYPE_UNSIGNED (ti)) need_precision += 1; if (TYPE_PRECISION (to) < need_precision) fail = true; if (!fail) { gimple_switch_set_index (stmt, def); update_stmt (stmt); } } } } } /* For pointers p2 and p1 return p2 - p1 if the difference is known and constant, otherwise return NULL. */ static tree constant_pointer_difference (tree p1, tree p2) { int i, j; #define CPD_ITERATIONS 5 tree exps[2][CPD_ITERATIONS]; tree offs[2][CPD_ITERATIONS]; int cnt[2]; for (i = 0; i < 2; i++) { tree p = i ? p1 : p2; tree off = size_zero_node; gimple stmt; enum tree_code code; /* For each of p1 and p2 we need to iterate at least twice, to handle ADDR_EXPR directly in p1/p2, SSA_NAME with ADDR_EXPR or POINTER_PLUS_EXPR etc. on definition's stmt RHS. Iterate a few extra times. */ j = 0; do { if (!POINTER_TYPE_P (TREE_TYPE (p))) break; if (TREE_CODE (p) == ADDR_EXPR) { tree q = TREE_OPERAND (p, 0); HOST_WIDE_INT offset; tree base = get_addr_base_and_unit_offset (q, &offset); if (base) { q = base; if (offset) off = size_binop (PLUS_EXPR, off, size_int (offset)); } if (TREE_CODE (q) == MEM_REF && TREE_CODE (TREE_OPERAND (q, 0)) == SSA_NAME) { p = TREE_OPERAND (q, 0); off = size_binop (PLUS_EXPR, off, double_int_to_tree (sizetype, mem_ref_offset (q))); } else { exps[i][j] = q; offs[i][j++] = off; break; } } if (TREE_CODE (p) != SSA_NAME) break; exps[i][j] = p; offs[i][j++] = off; if (j == CPD_ITERATIONS) break; stmt = SSA_NAME_DEF_STMT (p); if (!is_gimple_assign (stmt) || gimple_assign_lhs (stmt) != p) break; code = gimple_assign_rhs_code (stmt); if (code == POINTER_PLUS_EXPR) { if (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST) break; off = size_binop (PLUS_EXPR, off, gimple_assign_rhs2 (stmt)); p = gimple_assign_rhs1 (stmt); } else if (code == ADDR_EXPR || code == NOP_EXPR) p = gimple_assign_rhs1 (stmt); else break; } while (1); cnt[i] = j; } for (i = 0; i < cnt[0]; i++) for (j = 0; j < cnt[1]; j++) if (exps[0][i] == exps[1][j]) return size_binop (MINUS_EXPR, offs[0][i], offs[1][j]); return NULL_TREE; } /* *GSI_P is a GIMPLE_CALL to a builtin function. Optimize memcpy (p, "abcd", 4); memset (p + 4, ' ', 3); into memcpy (p, "abcd ", 7); call if the latter can be stored by pieces during expansion. */ static bool simplify_builtin_call (gimple_stmt_iterator *gsi_p, tree callee2) { gimple stmt1, stmt2 = gsi_stmt (*gsi_p); tree vuse = gimple_vuse (stmt2); if (vuse == NULL) return false; stmt1 = SSA_NAME_DEF_STMT (vuse); switch (DECL_FUNCTION_CODE (callee2)) { case BUILT_IN_MEMSET: if (gimple_call_num_args (stmt2) != 3 || gimple_call_lhs (stmt2) || CHAR_BIT != 8 || BITS_PER_UNIT != 8) break; else { tree callee1; tree ptr1, src1, str1, off1, len1, lhs1; tree ptr2 = gimple_call_arg (stmt2, 0); tree val2 = gimple_call_arg (stmt2, 1); tree len2 = gimple_call_arg (stmt2, 2); tree diff, vdef, new_str_cst; gimple use_stmt; unsigned int ptr1_align; unsigned HOST_WIDE_INT src_len; char *src_buf; use_operand_p use_p; if (!host_integerp (val2, 0) || !host_integerp (len2, 1)) break; if (is_gimple_call (stmt1)) { /* If first stmt is a call, it needs to be memcpy or mempcpy, with string literal as second argument and constant length. */ callee1 = gimple_call_fndecl (stmt1); if (callee1 == NULL_TREE || DECL_BUILT_IN_CLASS (callee1) != BUILT_IN_NORMAL || gimple_call_num_args (stmt1) != 3) break; if (DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMCPY && DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMPCPY) break; ptr1 = gimple_call_arg (stmt1, 0); src1 = gimple_call_arg (stmt1, 1); len1 = gimple_call_arg (stmt1, 2); lhs1 = gimple_call_lhs (stmt1); if (!host_integerp (len1, 1)) break; str1 = string_constant (src1, &off1); if (str1 == NULL_TREE) break; if (!host_integerp (off1, 1) || compare_tree_int (off1, TREE_STRING_LENGTH (str1) - 1) > 0 || compare_tree_int (len1, TREE_STRING_LENGTH (str1) - tree_low_cst (off1, 1)) > 0 || TREE_CODE (TREE_TYPE (str1)) != ARRAY_TYPE || TYPE_MODE (TREE_TYPE (TREE_TYPE (str1))) != TYPE_MODE (char_type_node)) break; } else if (gimple_assign_single_p (stmt1)) { /* Otherwise look for length 1 memcpy optimized into assignment. */ ptr1 = gimple_assign_lhs (stmt1); src1 = gimple_assign_rhs1 (stmt1); if (TREE_CODE (ptr1) != MEM_REF || TYPE_MODE (TREE_TYPE (ptr1)) != TYPE_MODE (char_type_node) || !host_integerp (src1, 0)) break; ptr1 = build_fold_addr_expr (ptr1); callee1 = NULL_TREE; len1 = size_one_node; lhs1 = NULL_TREE; off1 = size_zero_node; str1 = NULL_TREE; } else break; diff = constant_pointer_difference (ptr1, ptr2); if (diff == NULL && lhs1 != NULL) { diff = constant_pointer_difference (lhs1, ptr2); if (DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY && diff != NULL) diff = size_binop (PLUS_EXPR, diff, fold_convert (sizetype, len1)); } /* If the difference between the second and first destination pointer is not constant, or is bigger than memcpy length, bail out. */ if (diff == NULL || !host_integerp (diff, 1) || tree_int_cst_lt (len1, diff)) break; /* Use maximum of difference plus memset length and memcpy length as the new memcpy length, if it is too big, bail out. */ src_len = tree_low_cst (diff, 1); src_len += tree_low_cst (len2, 1); if (src_len < (unsigned HOST_WIDE_INT) tree_low_cst (len1, 1)) src_len = tree_low_cst (len1, 1); if (src_len > 1024) break; /* If mempcpy value is used elsewhere, bail out, as mempcpy with bigger length will return different result. */ if (lhs1 != NULL_TREE && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY && (TREE_CODE (lhs1) != SSA_NAME || !single_imm_use (lhs1, &use_p, &use_stmt) || use_stmt != stmt2)) break; /* If anything reads memory in between memcpy and memset call, the modified memcpy call might change it. */ vdef = gimple_vdef (stmt1); if (vdef != NULL && (!single_imm_use (vdef, &use_p, &use_stmt) || use_stmt != stmt2)) break; ptr1_align = get_pointer_alignment (ptr1, BIGGEST_ALIGNMENT); /* Construct the new source string literal. */ src_buf = XALLOCAVEC (char, src_len + 1); if (callee1) memcpy (src_buf, TREE_STRING_POINTER (str1) + tree_low_cst (off1, 1), tree_low_cst (len1, 1)); else src_buf[0] = tree_low_cst (src1, 0); memset (src_buf + tree_low_cst (diff, 1), tree_low_cst (val2, 1), tree_low_cst (len2, 1)); src_buf[src_len] = '\0'; /* Neither builtin_strncpy_read_str nor builtin_memcpy_read_str handle embedded '\0's. */ if (strlen (src_buf) != src_len) break; rtl_profile_for_bb (gimple_bb (stmt2)); /* If the new memcpy wouldn't be emitted by storing the literal by pieces, this optimization might enlarge .rodata too much, as commonly used string literals couldn't be shared any longer. */ if (!can_store_by_pieces (src_len, builtin_strncpy_read_str, src_buf, ptr1_align, false)) break; new_str_cst = build_string_literal (src_len, src_buf); if (callee1) { /* If STMT1 is a mem{,p}cpy call, adjust it and remove memset call. */ if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY) gimple_call_set_lhs (stmt1, NULL_TREE); gimple_call_set_arg (stmt1, 1, new_str_cst); gimple_call_set_arg (stmt1, 2, build_int_cst (TREE_TYPE (len1), src_len)); update_stmt (stmt1); unlink_stmt_vdef (stmt2); gsi_remove (gsi_p, true); release_defs (stmt2); if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY) release_ssa_name (lhs1); return true; } else { /* Otherwise, if STMT1 is length 1 memcpy optimized into assignment, remove STMT1 and change memset call into memcpy call. */ gimple_stmt_iterator gsi = gsi_for_stmt (stmt1); if (!is_gimple_val (ptr1)) ptr1 = force_gimple_operand_gsi (gsi_p, ptr1, true, NULL_TREE, true, GSI_SAME_STMT); gimple_call_set_fndecl (stmt2, built_in_decls [BUILT_IN_MEMCPY]); gimple_call_set_arg (stmt2, 0, ptr1); gimple_call_set_arg (stmt2, 1, new_str_cst); gimple_call_set_arg (stmt2, 2, build_int_cst (TREE_TYPE (len2), src_len)); unlink_stmt_vdef (stmt1); gsi_remove (&gsi, true); release_defs (stmt1); update_stmt (stmt2); return false; } } break; default: break; } return false; } /* Run bitwise and assignments throug the folder. If the first argument is an ssa name that is itself a result of a typecast of an ADDR_EXPR to an integer, feed the ADDR_EXPR to the folder rather than the ssa name. */ static void simplify_bitwise_and (gimple_stmt_iterator *gsi, gimple stmt) { tree res; tree arg1 = gimple_assign_rhs1 (stmt); tree arg2 = gimple_assign_rhs2 (stmt); if (TREE_CODE (arg2) != INTEGER_CST) return; if (TREE_CODE (arg1) == SSA_NAME && !SSA_NAME_IS_DEFAULT_DEF (arg1)) { gimple def = SSA_NAME_DEF_STMT (arg1); if (gimple_assign_cast_p (def) && INTEGRAL_TYPE_P (gimple_expr_type (def))) { tree op = gimple_assign_rhs1 (def); if (TREE_CODE (op) == ADDR_EXPR) arg1 = op; } } res = fold_binary_loc (gimple_location (stmt), BIT_AND_EXPR, TREE_TYPE (gimple_assign_lhs (stmt)), arg1, arg2); if (res && is_gimple_min_invariant (res)) { gimple_assign_set_rhs_from_tree (gsi, res); update_stmt (stmt); } return; } /* Perform re-associations of the plus or minus statement STMT that are always permitted. Returns true if the CFG was changed. */ static bool associate_plusminus (gimple stmt) { tree rhs1 = gimple_assign_rhs1 (stmt); tree rhs2 = gimple_assign_rhs2 (stmt); enum tree_code code = gimple_assign_rhs_code (stmt); gimple_stmt_iterator gsi; bool changed; /* We can't reassociate at all for saturating types. */ if (TYPE_SATURATING (TREE_TYPE (rhs1))) return false; /* First contract negates. */ do { changed = false; /* A +- (-B) -> A -+ B. */ if (TREE_CODE (rhs2) == SSA_NAME) { gimple def_stmt = SSA_NAME_DEF_STMT (rhs2); if (is_gimple_assign (def_stmt) && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR) { code = (code == MINUS_EXPR) ? PLUS_EXPR : MINUS_EXPR; gimple_assign_set_rhs_code (stmt, code); rhs2 = gimple_assign_rhs1 (def_stmt); gimple_assign_set_rhs2 (stmt, rhs2); gimple_set_modified (stmt, true); changed = true; } } /* (-A) + B -> B - A. */ if (TREE_CODE (rhs1) == SSA_NAME && code == PLUS_EXPR) { gimple def_stmt = SSA_NAME_DEF_STMT (rhs1); if (is_gimple_assign (def_stmt) && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR) { code = MINUS_EXPR; gimple_assign_set_rhs_code (stmt, code); rhs1 = rhs2; gimple_assign_set_rhs1 (stmt, rhs1); rhs2 = gimple_assign_rhs1 (def_stmt); gimple_assign_set_rhs2 (stmt, rhs2); gimple_set_modified (stmt, true); changed = true; } } } while (changed); /* We can't reassociate floating-point or fixed-point plus or minus because of saturation to +-Inf. */ if (FLOAT_TYPE_P (TREE_TYPE (rhs1)) || FIXED_POINT_TYPE_P (TREE_TYPE (rhs1))) goto out; /* Second match patterns that allow contracting a plus-minus pair irrespective of overflow issues. (A +- B) - A -> +- B (A +- B) -+ B -> A (CST +- A) +- CST -> CST +- A (A + CST) +- CST -> A + CST ~A + A -> -1 ~A + 1 -> -A A - (A +- B) -> -+ B A +- (B +- A) -> +- B CST +- (CST +- A) -> CST +- A CST +- (A +- CST) -> CST +- A A + ~A -> -1 via commutating the addition and contracting operations to zero by reassociation. */ gsi = gsi_for_stmt (stmt); if (TREE_CODE (rhs1) == SSA_NAME) { gimple def_stmt = SSA_NAME_DEF_STMT (rhs1); if (is_gimple_assign (def_stmt)) { enum tree_code def_code = gimple_assign_rhs_code (def_stmt); if (def_code == PLUS_EXPR || def_code == MINUS_EXPR) { tree def_rhs1 = gimple_assign_rhs1 (def_stmt); tree def_rhs2 = gimple_assign_rhs2 (def_stmt); if (operand_equal_p (def_rhs1, rhs2, 0) && code == MINUS_EXPR) { /* (A +- B) - A -> +- B. */ code = ((def_code == PLUS_EXPR) ? TREE_CODE (def_rhs2) : NEGATE_EXPR); rhs1 = def_rhs2; rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } else if (operand_equal_p (def_rhs2, rhs2, 0) && code != def_code) { /* (A +- B) -+ B -> A. */ code = TREE_CODE (def_rhs1); rhs1 = def_rhs1; rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } else if (TREE_CODE (rhs2) == INTEGER_CST && TREE_CODE (def_rhs1) == INTEGER_CST) { /* (CST +- A) +- CST -> CST +- A. */ tree cst = fold_binary (code, TREE_TYPE (rhs1), def_rhs1, rhs2); if (cst && !TREE_OVERFLOW (cst)) { code = def_code; gimple_assign_set_rhs_code (stmt, code); rhs1 = cst; gimple_assign_set_rhs1 (stmt, rhs1); rhs2 = def_rhs2; gimple_assign_set_rhs2 (stmt, rhs2); gimple_set_modified (stmt, true); } } else if (TREE_CODE (rhs2) == INTEGER_CST && TREE_CODE (def_rhs2) == INTEGER_CST && def_code == PLUS_EXPR) { /* (A + CST) +- CST -> A + CST. */ tree cst = fold_binary (code, TREE_TYPE (rhs1), def_rhs2, rhs2); if (cst && !TREE_OVERFLOW (cst)) { code = PLUS_EXPR; gimple_assign_set_rhs_code (stmt, code); rhs1 = def_rhs1; gimple_assign_set_rhs1 (stmt, rhs1); rhs2 = cst; gimple_assign_set_rhs2 (stmt, rhs2); gimple_set_modified (stmt, true); } } } else if (def_code == BIT_NOT_EXPR && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))) { tree def_rhs1 = gimple_assign_rhs1 (def_stmt); if (code == PLUS_EXPR && operand_equal_p (def_rhs1, rhs2, 0)) { /* ~A + A -> -1. */ code = INTEGER_CST; rhs1 = build_int_cst_type (TREE_TYPE (rhs2), -1); rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } else if (code == PLUS_EXPR && integer_onep (rhs1)) { /* ~A + 1 -> -A. */ code = NEGATE_EXPR; rhs1 = def_rhs1; rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } } } } if (rhs2 && TREE_CODE (rhs2) == SSA_NAME) { gimple def_stmt = SSA_NAME_DEF_STMT (rhs2); if (is_gimple_assign (def_stmt)) { enum tree_code def_code = gimple_assign_rhs_code (def_stmt); if (def_code == PLUS_EXPR || def_code == MINUS_EXPR) { tree def_rhs1 = gimple_assign_rhs1 (def_stmt); tree def_rhs2 = gimple_assign_rhs2 (def_stmt); if (operand_equal_p (def_rhs1, rhs1, 0) && code == MINUS_EXPR) { /* A - (A +- B) -> -+ B. */ code = ((def_code == PLUS_EXPR) ? NEGATE_EXPR : TREE_CODE (def_rhs2)); rhs1 = def_rhs2; rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } else if (operand_equal_p (def_rhs2, rhs1, 0) && code != def_code) { /* A +- (B +- A) -> +- B. */ code = ((code == PLUS_EXPR) ? TREE_CODE (def_rhs1) : NEGATE_EXPR); rhs1 = def_rhs1; rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } else if (TREE_CODE (rhs1) == INTEGER_CST && TREE_CODE (def_rhs1) == INTEGER_CST) { /* CST +- (CST +- A) -> CST +- A. */ tree cst = fold_binary (code, TREE_TYPE (rhs2), rhs1, def_rhs1); if (cst && !TREE_OVERFLOW (cst)) { code = (code == def_code ? PLUS_EXPR : MINUS_EXPR); gimple_assign_set_rhs_code (stmt, code); rhs1 = cst; gimple_assign_set_rhs1 (stmt, rhs1); rhs2 = def_rhs2; gimple_assign_set_rhs2 (stmt, rhs2); gimple_set_modified (stmt, true); } } else if (TREE_CODE (rhs1) == INTEGER_CST && TREE_CODE (def_rhs2) == INTEGER_CST) { /* CST +- (A +- CST) -> CST +- A. */ tree cst = fold_binary (def_code == code ? PLUS_EXPR : MINUS_EXPR, TREE_TYPE (rhs2), rhs1, def_rhs2); if (cst && !TREE_OVERFLOW (cst)) { rhs1 = cst; gimple_assign_set_rhs1 (stmt, rhs1); rhs2 = def_rhs1; gimple_assign_set_rhs2 (stmt, rhs2); gimple_set_modified (stmt, true); } } } else if (def_code == BIT_NOT_EXPR && INTEGRAL_TYPE_P (TREE_TYPE (rhs2))) { tree def_rhs1 = gimple_assign_rhs1 (def_stmt); if (code == PLUS_EXPR && operand_equal_p (def_rhs1, rhs1, 0)) { /* A + ~A -> -1. */ code = INTEGER_CST; rhs1 = build_int_cst_type (TREE_TYPE (rhs1), -1); rhs2 = NULL_TREE; gimple_assign_set_rhs_with_ops (&gsi, code, rhs1, NULL_TREE); gcc_assert (gsi_stmt (gsi) == stmt); gimple_set_modified (stmt, true); } } } } out: if (gimple_modified_p (stmt)) { fold_stmt_inplace (stmt); update_stmt (stmt); if (maybe_clean_or_replace_eh_stmt (stmt, stmt) && gimple_purge_dead_eh_edges (gimple_bb (stmt))) return true; } return false; } /* Main entry point for the forward propagation optimizer. */ static unsigned int tree_ssa_forward_propagate_single_use_vars (void) { basic_block bb; unsigned int todoflags = 0; cfg_changed = false; FOR_EACH_BB (bb) { gimple_stmt_iterator gsi; /* Note we update GSI within the loop as necessary. */ for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); ) { gimple stmt = gsi_stmt (gsi); /* If this statement sets an SSA_NAME to an address, try to propagate the address into the uses of the SSA_NAME. */ if (is_gimple_assign (stmt)) { tree lhs = gimple_assign_lhs (stmt); tree rhs = gimple_assign_rhs1 (stmt); if (TREE_CODE (lhs) != SSA_NAME) { gsi_next (&gsi); continue; } if (gimple_assign_rhs_code (stmt) == ADDR_EXPR /* Handle pointer conversions on invariant addresses as well, as this is valid gimple. */ || (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt)) && TREE_CODE (rhs) == ADDR_EXPR && POINTER_TYPE_P (TREE_TYPE (lhs)))) { tree base = get_base_address (TREE_OPERAND (rhs, 0)); if ((!base || !DECL_P (base) || decl_address_invariant_p (base)) && !stmt_references_abnormal_ssa_name (stmt) && forward_propagate_addr_expr (lhs, rhs)) { release_defs (stmt); todoflags |= TODO_remove_unused_locals; gsi_remove (&gsi, true); } else gsi_next (&gsi); } else if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR && can_propagate_from (stmt)) { if (TREE_CODE (gimple_assign_rhs2 (stmt)) == INTEGER_CST /* ??? Better adjust the interface to that function instead of building new trees here. */ && forward_propagate_addr_expr (lhs, build1 (ADDR_EXPR, TREE_TYPE (rhs), fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (rhs)), rhs, fold_convert (ptr_type_node, gimple_assign_rhs2 (stmt)))))) { release_defs (stmt); todoflags |= TODO_remove_unused_locals; gsi_remove (&gsi, true); } else if (is_gimple_min_invariant (rhs)) { /* Make sure to fold &a[0] + off_1 here. */ fold_stmt_inplace (stmt); update_stmt (stmt); if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR) gsi_next (&gsi); } else gsi_next (&gsi); } else if ((gimple_assign_rhs_code (stmt) == BIT_NOT_EXPR || gimple_assign_rhs_code (stmt) == NEGATE_EXPR) && TREE_CODE (rhs) == SSA_NAME) { simplify_not_neg_expr (&gsi); gsi_next (&gsi); } else if (gimple_assign_rhs_code (stmt) == COND_EXPR) { /* In this case the entire COND_EXPR is in rhs1. */ int did_something; fold_defer_overflow_warnings (); did_something = forward_propagate_into_cond (&gsi); stmt = gsi_stmt (gsi); if (did_something == 2) cfg_changed = true; fold_undefer_overflow_warnings (!TREE_NO_WARNING (rhs) && did_something, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL); gsi_next (&gsi); } else if (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_comparison) { if (forward_propagate_comparison (stmt)) cfg_changed = true; gsi_next (&gsi); } else if (gimple_assign_rhs_code (stmt) == BIT_AND_EXPR) { simplify_bitwise_and (&gsi, stmt); gsi_next (&gsi); } else if (gimple_assign_rhs_code (stmt) == PLUS_EXPR || gimple_assign_rhs_code (stmt) == MINUS_EXPR) { cfg_changed |= associate_plusminus (stmt); gsi_next (&gsi); } else gsi_next (&gsi); } else if (gimple_code (stmt) == GIMPLE_SWITCH) { simplify_gimple_switch (stmt); gsi_next (&gsi); } else if (gimple_code (stmt) == GIMPLE_COND) { int did_something; fold_defer_overflow_warnings (); did_something = forward_propagate_into_gimple_cond (stmt); if (did_something == 2) cfg_changed = true; fold_undefer_overflow_warnings (did_something, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL); gsi_next (&gsi); } else if (is_gimple_call (stmt)) { tree callee = gimple_call_fndecl (stmt); if (callee == NULL_TREE || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL || !simplify_builtin_call (&gsi, callee)) gsi_next (&gsi); } else gsi_next (&gsi); } } if (cfg_changed) todoflags |= TODO_cleanup_cfg; return todoflags; } static bool gate_forwprop (void) { return flag_tree_forwprop; } struct gimple_opt_pass pass_forwprop = { { GIMPLE_PASS, "forwprop", /* name */ gate_forwprop, /* gate */ tree_ssa_forward_propagate_single_use_vars, /* execute */ NULL, /* sub */ NULL, /* next */ 0, /* static_pass_number */ TV_TREE_FORWPROP, /* tv_id */ PROP_cfg | PROP_ssa, /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_dump_func | TODO_ggc_collect | TODO_update_ssa | TODO_verify_ssa /* todo_flags_finish */ } };
gpl-3.0
AlexanderFabisch/OpenANN
src/SigmaPi.cpp
5
8823
#include <OpenANN/layers/SigmaPi.h> #include <OpenANN/util/Random.h> #include <OpenANN/util/OpenANNException.h> namespace OpenANN { double SigmaPi::Constraint::operator()(int p1, int p2) const { throw OpenANNException("Constrain operator (p1, p2) must be implemented"); return 0.0; } double SigmaPi::Constraint::operator()(int p1, int p2, int p3) const { throw OpenANNException("Constrain operator (p1, p2, p3) must be implemented"); return 0.0; } double SigmaPi::Constraint::operator()(int p1, int p2, int p3, int p4) const { throw OpenANNException("Constrain operator (p1, p2, p3, p4) must be implemented"); return 0.0; } bool SigmaPi::Constraint::isDefault() const { return false; } struct NoConstraint : public OpenANN::SigmaPi::Constraint { virtual bool isDefault() const { return true; } }; SigmaPi::SigmaPi(OutputInfo info, bool bias, ActivationFunction act, double stdDev) : info(info), bias(bias), act(act), stdDev(stdDev), x(1, info.outputs() + bias), e(1, info.outputs()) { if(bias) x(info.outputs()) = 1.0; } void SigmaPi::initializeParameters() { RandomNumberGenerator rng; for(int i = 0; i < nodes.size(); ++i) for(int j = 0; j < nodes[i].size(); ++j) w[nodes[i][j].weight] = rng.sampleNormalDistribution<double>() * stdDev; } void SigmaPi::updatedParameters() { } void SigmaPi::forwardPropagate(Eigen::MatrixXd* x, Eigen::MatrixXd*& y, bool dropout, double* error) { const int N = x->rows(); this->x.conservativeResize(N, Eigen::NoChange); a.conservativeResize(N, Eigen::NoChange); this->x.rightCols(1).setZero(); this->y.conservativeResize(N, Eigen::NoChange); this->x.leftCols(info.outputs()) = *x; #pragma omp parallel for for(int instance = 0; instance < N; instance++) { int i = 0; for(HigherOrderNeuron* n = &nodes.front(); n <= &nodes.back(); ++n) { double sum = 0.0; for(HigherOrderUnit* u = &n->front(); u <= &n->back(); ++u) { double korrelation = 1.0; for(int k = 0; k < u->position.size(); ++k) { korrelation *= (*x)(instance, u->position.at(k)); } sum = sum + w[u->weight] * korrelation; } a(instance, i++) = sum; } } activationFunction(act, a, this->y); y = &(this->y); } void SigmaPi::backpropagate(Eigen::MatrixXd* error_in, Eigen::MatrixXd*& error_out, bool backpropToPrevious) { const int N = a.rows(); e.conservativeResize(N, Eigen::NoChange); deltas.conservativeResize(N, Eigen::NoChange); yd.conservativeResize(N, Eigen::NoChange); e.setZero(); for(int i = 0; i < wd.size(); ++i) wd[i] = 0.0; activationFunctionDerivative(act, y, yd); for(int instance = 0; instance < N; instance++) { int i = 0; for(HigherOrderNeuron* n = &nodes.front(); n <= &nodes.back(); ++n) { deltas(instance, i) = (*error_in)(instance, i) * yd(instance, i); for(HigherOrderUnit* u = &n->front(); u <= &n->back(); ++u) { double korrelation = 1.0; for(int k = 0; k < u->position.size(); ++k) { int index = u->position.at(k); korrelation *= x(instance, index); e(instance, index) += w[u->weight] * deltas(instance, i); } wd[u->weight] += deltas(instance, i) * korrelation; } ++i; } } error_out = &e; } Eigen::MatrixXd& SigmaPi::getOutput() { return y; } OutputInfo SigmaPi::initialize(std::vector<double*>& parameterPointers, std::vector<double*>& parameterDerivativePointers) { int J = nodes.size(); for(int i = 0; i < w.size(); ++i) { parameterPointers.push_back(&(w[i])); parameterDerivativePointers.push_back(&(wd[i])); } y.resize(1, J + bias); yd.resize(1, J); deltas.resize(1, J); a.resize(1, J); initializeParameters(); OutputInfo info; info.dimensions.push_back(J); return info; } SigmaPi& SigmaPi::secondOrderNodes(int numbers) { NoConstraint constrain; return secondOrderNodes(numbers, constrain); } SigmaPi& SigmaPi::thirdOrderNodes(int numbers) { NoConstraint constrain; return thirdOrderNodes(numbers, constrain); } SigmaPi& SigmaPi::fourthOrderNodes(int numbers) { NoConstraint constrain; return fourthOrderNodes(numbers, constrain); } SigmaPi& SigmaPi::secondOrderNodes(int numbers, const Constraint& constraint) { int I = info.outputs() + bias; for(int i = 0; i < numbers; ++i) { HigherOrderNeuron neuron; for(int p1 = 0; p1 < (I - 1); ++p1) { for(int p2 = p1 + 1; p2 < I; ++p2) { HigherOrderUnit snd_order_unit; snd_order_unit.position.push_back(p1); snd_order_unit.position.push_back(p2); if(!constraint.isDefault()) { double ref = constraint(p1, p2); size_t found = neuron.size(); for(int j = 0; j < neuron.size(); ++j) { if(std::fabs(w[neuron[j].weight] - ref) < 0.001) { found = j; j = neuron.size(); } } if(found >= neuron.size()) { snd_order_unit.weight = w.size(); w.push_back(ref); wd.push_back(ref); } else { snd_order_unit.weight = neuron[found].weight; } } else { snd_order_unit.weight = w.size(); w.push_back(0.0); wd.push_back(0.0); } neuron.push_back(snd_order_unit); } } nodes.push_back(neuron); } return *this; } SigmaPi& SigmaPi::thirdOrderNodes(int numbers, const Constraint& constraint) { int I = info.outputs() + bias; for(int i = 0; i < numbers; ++i) { HigherOrderNeuron neuron; for(int p1 = 0; p1 < (I - 2); ++p1) { for(int p2 = p1 + 1; p2 < (I - 1); ++p2) { for(int p3 = p2 + 1; p3 < I; ++p3) { HigherOrderUnit honn_unit; honn_unit.position.push_back(p1); honn_unit.position.push_back(p2); honn_unit.position.push_back(p3); if(!constraint.isDefault()) { double ref = constraint(p1, p2, p3); size_t found = neuron.size(); for(int j = 0; j < neuron.size(); ++j) { if(std::fabs(w[neuron[j].weight] - ref) < 0.001) { found = j; j = neuron.size(); } } if(found >= neuron.size()) { honn_unit.weight = w.size(); w.push_back(ref); wd.push_back(ref); } else { honn_unit.weight = neuron[found].weight; } } else { honn_unit.weight = w.size(); w.push_back(0.0); wd.push_back(0.0); } neuron.push_back(honn_unit); } } } nodes.push_back(neuron); } return *this; } SigmaPi& SigmaPi::fourthOrderNodes(int numbers, const Constraint& constraint) { int I = info.outputs() + bias; for(int i = 0; i < numbers; ++i) { HigherOrderNeuron neuron; for(int p1 = 0; p1 < (I - 3); ++p1) { for(int p2 = p1 + 1; p2 < (I - 2); ++p2) { for(int p3 = p2 + 1; p3 < (I - 1); ++p3) { for(int p4 = p3 + 1; p4 < I; ++p4) { HigherOrderUnit honn_unit; honn_unit.position.push_back(p1); honn_unit.position.push_back(p2); honn_unit.position.push_back(p3); honn_unit.position.push_back(p4); if(!constraint.isDefault()) { double ref = constraint(p1, p2, p3, p4); size_t found = neuron.size(); for(int j = 0; j < neuron.size(); ++j) { if(std::fabs(w[neuron[j].weight] - ref) < 0.001) { found = j; j = neuron.size(); } } if(found >= neuron.size()) { honn_unit.weight = w.size(); w.push_back(ref); wd.push_back(ref); } else { honn_unit.weight = neuron[found].weight; } } else { honn_unit.weight = w.size(); w.push_back(0.0); wd.push_back(0.0); } neuron.push_back(honn_unit); } } } } nodes.push_back(neuron); } return *this; } Eigen::VectorXd SigmaPi::getParameters() { throw OpenANNException("SigmaPi::getParameters() is not implemented!"); } }
gpl-3.0
zhuyue1314/pathgrind
valgrind-r12356/coregrind/m_replacemalloc/vg_replace_malloc.c
5
35499
/*--------------------------------------------------------------------*/ /*--- Replacements for malloc() et al, which run on the simulated ---*/ /*--- CPU. vg_replace_malloc.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of Valgrind, a dynamic binary instrumentation framework. Copyright (C) 2000-2011 Julian Seward jseward@acm.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 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 GNU General Public License is contained in the file COPYING. */ /* --------------------------------------------------------------------- ALL THE CODE IN THIS FILE RUNS ON THE SIMULATED CPU. These functions are drop-in replacements for malloc() and friends. They have global scope, but are not intended to be called directly. See pub_core_redir.h for the gory details. This file can be linked into the vg_preload_<tool>.so file for any tool that wishes to know about calls to malloc(). The tool must define all the functions that will be called via 'info'. It is called vg_replace_malloc.c because this filename appears in stack traces, so we want the name to be (hopefully!) meaningful to users. IMPORTANT: this file must not contain any floating point code, nor any integer division. This is because on ARM these can cause calls to helper functions, which will be unresolved within this .so. Although it is usually the case that the client's ld.so instance can bind them at runtime to the relevant functions in the client executable, there is no guarantee of this; and so the client may die via a runtime link failure. Hence the only safe approach is to avoid such function calls in the first place. See "#define CALLOC" below for a specific example. A useful command is for f in `find . -name "*preload*.so*"` ; \ do nm -A $f | grep " U " ; \ done to see all the undefined symbols in all the preload shared objects. ------------------------------------------------------------------ */ #include "pub_core_basics.h" #include "pub_core_vki.h" // VKI_EINVAL, VKI_ENOMEM #include "pub_core_clreq.h" // for VALGRIND_INTERNAL_PRINTF, // VALGRIND_NON_SIMD_CALL[12] #include "pub_core_debuginfo.h" // needed for pub_core_redir.h :( #include "pub_core_mallocfree.h" // for VG_MIN_MALLOC_SZB, VG_AR_CLIENT #include "pub_core_redir.h" // for VG_REPLACE_FUNCTION_* #include "pub_core_replacemalloc.h" /* Assignment of behavioural equivalence class tags: 1NNNP is intended to be reserved for the Valgrind core. Current usage: 10010 ALLOC_or_NULL 10020 ZONEALLOC_or_NULL 10030 ALLOC_or_BOMB 10040 ZONEFREE 10050 FREE 10060 ZONECALLOC 10070 CALLOC 10080 ZONEREALLOC 10090 REALLOC 10100 ZONEMEMALIGN 10110 MEMALIGN 10120 VALLOC 10130 ZONEVALLOC 10140 MALLOPT 10150 MALLOC_TRIM 10160 POSIX_MEMALIGN 10170 MALLOC_USABLE_SIZE 10180 PANIC 10190 MALLOC_STATS 10200 MALLINFO 10210 DEFAULT_ZONE 10220 ZONE_CHECK */ /* 2 Apr 05: the Portland Group compiler, which uses cfront/ARM style mangling, could be supported properly by the redirects in this module. Except we can't because it doesn't put its allocation functions in libpgc.so but instead hardwires them into the compilation unit holding main(), which makes them impossible to intercept directly. Fortunately those fns seem to route everything through to malloc/free. mid-06: could be improved, since we can now intercept in the main executable too. */ /* Call here to exit if we can't continue. On Android we can't call _exit for some reason, so we have to blunt-instrument it. */ __attribute__ ((__noreturn__)) static inline void my_exit ( int x ) { # if defined(VGPV_arm_linux_android) __asm__ __volatile__(".word 0xFFFFFFFF"); while (1) {} # else extern __attribute__ ((__noreturn__)) void _exit(int status); _exit(x); # endif } /* Same problem with getpagesize. */ static inline int my_getpagesize ( void ) { # if defined(VGPV_arm_linux_android) return 4096; /* kludge - link failure on Android, for some reason */ # else extern int getpagesize (void); return getpagesize(); # endif } /* Compute the high word of the double-length unsigned product of U and V. This is for calloc argument overflow checking; see comments below. Algorithm as described in Hacker's Delight, chapter 8. */ static UWord umulHW ( UWord u, UWord v ) { UWord u0, v0, w0, rHi; UWord u1, v1, w1,w2,t; UWord halfMask = sizeof(UWord)==4 ? (UWord)0xFFFF : (UWord)0xFFFFFFFFULL; UWord halfShift = sizeof(UWord)==4 ? 16 : 32; u0 = u & halfMask; u1 = u >> halfShift; v0 = v & halfMask; v1 = v >> halfShift; w0 = u0 * v0; t = u1 * v0 + (w0 >> halfShift); w1 = t & halfMask; w2 = t >> halfShift; w1 = u0 * v1 + w1; rHi = u1 * v1 + w2 + (w1 >> halfShift); return rHi; } /*------------------------------------------------------------*/ /*--- Replacing malloc() et al ---*/ /*------------------------------------------------------------*/ /* This struct is initially empty. Before the first use of any of these functions, we make a client request which fills in the fields. */ static struct vg_mallocfunc_info info; static int init_done; /* Startup hook - called as init section */ __attribute__((constructor)) static void init(void); #define MALLOC_TRACE(format, args...) \ if (info.clo_trace_malloc) { \ VALGRIND_INTERNAL_PRINTF(format, ## args ); } /* Below are new versions of malloc, __builtin_new, free, __builtin_delete, calloc, realloc, memalign, and friends. None of these functions are called directly - they are not meant to be found by the dynamic linker. But ALL client calls to malloc() and friends wind up here eventually. They get called because vg_replace_malloc installs a bunch of code redirects which causes Valgrind to use these functions rather than the ones they're replacing. */ /*---------------------- malloc ----------------------*/ /* Generate a replacement for 'fnname' in object 'soname', which calls 'vg_replacement' to allocate memory. If that fails, return NULL. */ #define ALLOC_or_NULL(soname, fnname, vg_replacement) \ \ void* VG_REPLACE_FUNCTION_EZU(10010,soname,fnname) (SizeT n); \ void* VG_REPLACE_FUNCTION_EZU(10010,soname,fnname) (SizeT n) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE(#fnname "(%llu)", (ULong)n ); \ \ v = (void*)VALGRIND_NON_SIMD_CALL1( info.tl_##vg_replacement, n ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #define ZONEALLOC_or_NULL(soname, fnname, vg_replacement) \ \ void* VG_REPLACE_FUNCTION_EZU(10020,soname,fnname) (void *zone, SizeT n); \ void* VG_REPLACE_FUNCTION_EZU(10020,soname,fnname) (void *zone, SizeT n) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE(#fnname "(%p, %llu)", zone, (ULong)n ); \ \ v = (void*)VALGRIND_NON_SIMD_CALL1( info.tl_##vg_replacement, n ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } /* Generate a replacement for 'fnname' in object 'soname', which calls 'vg_replacement' to allocate memory. If that fails, it bombs the system. */ #define ALLOC_or_BOMB(soname, fnname, vg_replacement) \ \ void* VG_REPLACE_FUNCTION_EZU(10030,soname,fnname) (SizeT n); \ void* VG_REPLACE_FUNCTION_EZU(10030,soname,fnname) (SizeT n) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE(#fnname "(%llu)", (ULong)n ); \ \ v = (void*)VALGRIND_NON_SIMD_CALL1( info.tl_##vg_replacement, n ); \ MALLOC_TRACE(" = %p\n", v ); \ if (NULL == v) { \ VALGRIND_PRINTF( \ "new/new[] failed and should throw an exception, but Valgrind\n"); \ VALGRIND_PRINTF_BACKTRACE( \ " cannot throw exceptions and so is aborting instead. Sorry.\n"); \ my_exit(1); \ } \ return v; \ } // Each of these lines generates a replacement function: // (from_so, from_fn, v's replacement) // malloc #if defined(VGO_linux) ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, malloc, malloc); ALLOC_or_NULL(VG_Z_LIBC_SONAME, malloc, malloc); #elif defined(VGO_darwin) ALLOC_or_NULL(VG_Z_LIBC_SONAME, malloc, malloc); ZONEALLOC_or_NULL(VG_Z_LIBC_SONAME, malloc_zone_malloc, malloc); #endif /*---------------------- new ----------------------*/ #if defined(VGO_linux) // operator new(unsigned int), not mangled (for gcc 2.96) ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, builtin_new, __builtin_new); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, builtin_new, __builtin_new); ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, __builtin_new, __builtin_new); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, __builtin_new, __builtin_new); // operator new(unsigned int), GNU mangling #if VG_WORDSIZE == 4 ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znwj, __builtin_new); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znwj, __builtin_new); #endif // operator new(unsigned long), GNU mangling #if VG_WORDSIZE == 8 ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znwm, __builtin_new); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znwm, __builtin_new); #endif #elif defined(VGO_darwin) // operator new(unsigned int), GNU mangling #if VG_WORDSIZE == 4 //ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znwj, __builtin_new); //ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znwj, __builtin_new); #endif // operator new(unsigned long), GNU mangling #if 1 // FIXME: is this right? //ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znwm, __builtin_new); //ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znwm, __builtin_new); #endif #endif /*---------------------- new nothrow ----------------------*/ #if defined(VGO_linux) // operator new(unsigned, std::nothrow_t const&), GNU mangling #if VG_WORDSIZE == 4 ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnwjRKSt9nothrow_t, __builtin_new); ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnwjRKSt9nothrow_t, __builtin_new); #endif // operator new(unsigned long, std::nothrow_t const&), GNU mangling #if VG_WORDSIZE == 8 ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnwmRKSt9nothrow_t, __builtin_new); ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnwmRKSt9nothrow_t, __builtin_new); #endif #elif defined(VGO_darwin) // operator new(unsigned, std::nothrow_t const&), GNU mangling #if VG_WORDSIZE == 4 //ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnwjRKSt9nothrow_t, __builtin_new); //ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnwjRKSt9nothrow_t, __builtin_new); #endif // operator new(unsigned long, std::nothrow_t const&), GNU mangling #if 1 // FIXME: is this right? //ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnwmRKSt9nothrow_t, __builtin_new); //ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnwmRKSt9nothrow_t, __builtin_new); #endif #endif /*---------------------- new [] ----------------------*/ #if defined(VGO_linux) // operator new[](unsigned int), not mangled (for gcc 2.96) ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, __builtin_vec_new, __builtin_vec_new ); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, __builtin_vec_new, __builtin_vec_new ); // operator new[](unsigned int), GNU mangling #if VG_WORDSIZE == 4 ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znaj, __builtin_vec_new ); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znaj, __builtin_vec_new ); #endif // operator new[](unsigned long), GNU mangling #if VG_WORDSIZE == 8 ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znam, __builtin_vec_new ); ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znam, __builtin_vec_new ); #endif #elif defined(VGO_darwin) // operator new[](unsigned int), GNU mangling #if VG_WORDSIZE == 4 //ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znaj, __builtin_vec_new ); //ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znaj, __builtin_vec_new ); #endif // operator new[](unsigned long), GNU mangling #if 1 // FIXME: is this right? //ALLOC_or_BOMB(VG_Z_LIBSTDCXX_SONAME, _Znam, __builtin_vec_new ); //ALLOC_or_BOMB(VG_Z_LIBC_SONAME, _Znam, __builtin_vec_new ); #endif #endif /*---------------------- new [] nothrow ----------------------*/ #if defined(VGO_linux) // operator new[](unsigned, std::nothrow_t const&), GNU mangling #if VG_WORDSIZE == 4 ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnajRKSt9nothrow_t, __builtin_vec_new ); ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnajRKSt9nothrow_t, __builtin_vec_new ); #endif // operator new[](unsigned long, std::nothrow_t const&), GNU mangling #if VG_WORDSIZE == 8 ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnamRKSt9nothrow_t, __builtin_vec_new ); ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnamRKSt9nothrow_t, __builtin_vec_new ); #endif #elif defined(VGO_darwin) // operator new[](unsigned, std::nothrow_t const&), GNU mangling #if VG_WORDSIZE == 4 //ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnajRKSt9nothrow_t, __builtin_vec_new ); //ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnajRKSt9nothrow_t, __builtin_vec_new ); #endif // operator new[](unsigned long, std::nothrow_t const&), GNU mangling #if 1 // FIXME: is this right? //ALLOC_or_NULL(VG_Z_LIBSTDCXX_SONAME, _ZnamRKSt9nothrow_t, __builtin_vec_new ); //ALLOC_or_NULL(VG_Z_LIBC_SONAME, _ZnamRKSt9nothrow_t, __builtin_vec_new ); #endif #endif /*---------------------- free ----------------------*/ /* Generate a replacement for 'fnname' in object 'soname', which calls 'vg_replacement' to free previously allocated memory. */ #define ZONEFREE(soname, fnname, vg_replacement) \ \ void VG_REPLACE_FUNCTION_EZU(10040,soname,fnname) (void *zone, void *p); \ void VG_REPLACE_FUNCTION_EZU(10040,soname,fnname) (void *zone, void *p) \ { \ if (!init_done) init(); \ MALLOC_TRACE(#fnname "(%p, %p)\n", zone, p ); \ if (p == NULL) \ return; \ (void)VALGRIND_NON_SIMD_CALL1( info.tl_##vg_replacement, p ); \ } #define FREE(soname, fnname, vg_replacement) \ \ void VG_REPLACE_FUNCTION_EZU(10050,soname,fnname) (void *p); \ void VG_REPLACE_FUNCTION_EZU(10050,soname,fnname) (void *p) \ { \ if (!init_done) init(); \ MALLOC_TRACE(#fnname "(%p)\n", p ); \ if (p == NULL) \ return; \ (void)VALGRIND_NON_SIMD_CALL1( info.tl_##vg_replacement, p ); \ } #if defined(VGO_linux) FREE(VG_Z_LIBSTDCXX_SONAME, free, free ); FREE(VG_Z_LIBC_SONAME, free, free ); #elif defined(VGO_darwin) FREE(VG_Z_LIBC_SONAME, free, free ); ZONEFREE(VG_Z_LIBC_SONAME, malloc_zone_free, free ); #endif /*---------------------- cfree ----------------------*/ // cfree #if defined(VGO_linux) FREE(VG_Z_LIBSTDCXX_SONAME, cfree, free ); FREE(VG_Z_LIBC_SONAME, cfree, free ); #elif defined(VGO_darwin) //FREE(VG_Z_LIBSTDCXX_SONAME, cfree, free ); //FREE(VG_Z_LIBC_SONAME, cfree, free ); #endif /*---------------------- delete ----------------------*/ #if defined(VGO_linux) // operator delete(void*), not mangled (for gcc 2.96) FREE(VG_Z_LIBSTDCXX_SONAME, __builtin_delete, __builtin_delete ); FREE(VG_Z_LIBC_SONAME, __builtin_delete, __builtin_delete ); // operator delete(void*), GNU mangling FREE(VG_Z_LIBSTDCXX_SONAME, _ZdlPv, __builtin_delete ); FREE(VG_Z_LIBC_SONAME, _ZdlPv, __builtin_delete ); #elif defined(VGO_darwin) // operator delete(void*), GNU mangling //FREE(VG_Z_LIBSTDCXX_SONAME, _ZdlPv, __builtin_delete ); //FREE(VG_Z_LIBC_SONAME, _ZdlPv, __builtin_delete ); #endif /*---------------------- delete nothrow ----------------------*/ #if defined(VGO_linux) // operator delete(void*, std::nothrow_t const&), GNU mangling FREE(VG_Z_LIBSTDCXX_SONAME, _ZdlPvRKSt9nothrow_t, __builtin_delete ); FREE(VG_Z_LIBC_SONAME, _ZdlPvRKSt9nothrow_t, __builtin_delete ); #elif defined(VGO_darwin) // operator delete(void*, std::nothrow_t const&), GNU mangling //FREE(VG_Z_LIBSTDCXX_SONAME, _ZdlPvRKSt9nothrow_t, __builtin_delete ); //FREE(VG_Z_LIBC_SONAME, _ZdlPvRKSt9nothrow_t, __builtin_delete ); #endif /*---------------------- delete [] ----------------------*/ #if defined(VGO_linux) // operator delete[](void*), not mangled (for gcc 2.96) FREE(VG_Z_LIBSTDCXX_SONAME, __builtin_vec_delete, __builtin_vec_delete ); FREE(VG_Z_LIBC_SONAME, __builtin_vec_delete, __builtin_vec_delete ); // operator delete[](void*), GNU mangling FREE(VG_Z_LIBSTDCXX_SONAME, _ZdaPv, __builtin_vec_delete ); FREE(VG_Z_LIBC_SONAME, _ZdaPv, __builtin_vec_delete ); #elif defined(VGO_darwin) // operator delete[](void*), not mangled (for gcc 2.96) //FREE(VG_Z_LIBSTDCXX_SONAME, __builtin_vec_delete, __builtin_vec_delete ); //FREE(VG_Z_LIBC_SONAME, __builtin_vec_delete, __builtin_vec_delete ); // operator delete[](void*), GNU mangling //FREE(VG_Z_LIBSTDCXX_SONAME, _ZdaPv, __builtin_vec_delete ); //FREE(VG_Z_LIBC_SONAME, _ZdaPv, __builtin_vec_delete ); #endif /*---------------------- delete [] nothrow ----------------------*/ #if defined(VGO_linux) // operator delete[](void*, std::nothrow_t const&), GNU mangling FREE(VG_Z_LIBSTDCXX_SONAME, _ZdaPvRKSt9nothrow_t, __builtin_vec_delete ); FREE(VG_Z_LIBC_SONAME, _ZdaPvRKSt9nothrow_t, __builtin_vec_delete ); #elif defined(VGO_darwin) // operator delete[](void*, std::nothrow_t const&), GNU mangling //FREE(VG_Z_LIBSTDCXX_SONAME, _ZdaPvRKSt9nothrow_t, __builtin_vec_delete ); //FREE(VG_Z_LIBC_SONAME, _ZdaPvRKSt9nothrow_t, __builtin_vec_delete ); #endif /*---------------------- calloc ----------------------*/ #define ZONECALLOC(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10060,soname,fnname) \ ( void *zone, SizeT nmemb, SizeT size ); \ void* VG_REPLACE_FUNCTION_EZU(10060,soname,fnname) \ ( void *zone, SizeT nmemb, SizeT size ) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE("zone_calloc(%p, %llu,%llu)", zone, (ULong)nmemb, (ULong)size ); \ \ v = (void*)VALGRIND_NON_SIMD_CALL2( info.tl_calloc, nmemb, size ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #define CALLOC(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10070,soname,fnname) \ ( SizeT nmemb, SizeT size ); \ void* VG_REPLACE_FUNCTION_EZU(10070,soname,fnname) \ ( SizeT nmemb, SizeT size ) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE("calloc(%llu,%llu)", (ULong)nmemb, (ULong)size ); \ \ /* Protect against overflow. See bug 24078. (that bug number is invalid. Which one really?) */ \ /* But don't use division, since that produces an external symbol reference on ARM, in the form of a call to __aeabi_uidiv. It's normally OK, because ld.so manages to resolve it to something in the executable, or one of its shared objects. But that isn't guaranteed to be the case, and it has been observed to fail in rare cases, eg: echo x | valgrind /bin/sed -n "s/.*-\>\ //p" So instead compute the high word of the product and check it is zero. */ \ if (umulHW(size, nmemb) != 0) return NULL; \ v = (void*)VALGRIND_NON_SIMD_CALL2( info.tl_calloc, nmemb, size ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #if defined(VGO_linux) CALLOC(VG_Z_LIBC_SONAME, calloc); #elif defined(VGO_darwin) CALLOC(VG_Z_LIBC_SONAME, calloc); ZONECALLOC(VG_Z_LIBC_SONAME, malloc_zone_calloc); #endif /*---------------------- realloc ----------------------*/ #define ZONEREALLOC(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10080,soname,fnname) \ ( void *zone, void* ptrV, SizeT new_size ); \ void* VG_REPLACE_FUNCTION_EZU(10080,soname,fnname) \ ( void *zone, void* ptrV, SizeT new_size ) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE("zone_realloc(%p,%p,%llu)", zone, ptrV, (ULong)new_size ); \ \ if (ptrV == NULL) \ /* We need to call a malloc-like function; so let's use \ one which we know exists. GrP fixme use zonemalloc instead? */ \ return VG_REPLACE_FUNCTION_EZU(10010,VG_Z_LIBC_SONAME,malloc) \ (new_size); \ if (new_size <= 0) { \ VG_REPLACE_FUNCTION_EZU(10050,VG_Z_LIBC_SONAME,free)(ptrV); \ MALLOC_TRACE(" = 0\n"); \ return NULL; \ } \ v = (void*)VALGRIND_NON_SIMD_CALL2( info.tl_realloc, ptrV, new_size ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #define REALLOC(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10090,soname,fnname) \ ( void* ptrV, SizeT new_size );\ void* VG_REPLACE_FUNCTION_EZU(10090,soname,fnname) \ ( void* ptrV, SizeT new_size ) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE("realloc(%p,%llu)", ptrV, (ULong)new_size ); \ \ if (ptrV == NULL) \ /* We need to call a malloc-like function; so let's use \ one which we know exists. */ \ return VG_REPLACE_FUNCTION_EZU(10010,VG_Z_LIBC_SONAME,malloc) \ (new_size); \ if (new_size <= 0) { \ VG_REPLACE_FUNCTION_EZU(10050,VG_Z_LIBC_SONAME,free)(ptrV); \ MALLOC_TRACE(" = 0\n"); \ return NULL; \ } \ v = (void*)VALGRIND_NON_SIMD_CALL2( info.tl_realloc, ptrV, new_size ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #if defined(VGO_linux) REALLOC(VG_Z_LIBC_SONAME, realloc); #elif defined(VGO_darwin) REALLOC(VG_Z_LIBC_SONAME, realloc); ZONEREALLOC(VG_Z_LIBC_SONAME, malloc_zone_realloc); #endif /*---------------------- memalign ----------------------*/ #define ZONEMEMALIGN(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10100,soname,fnname) \ ( void *zone, SizeT alignment, SizeT n ); \ void* VG_REPLACE_FUNCTION_EZU(10100,soname,fnname) \ ( void *zone, SizeT alignment, SizeT n ) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE("zone_memalign(%p, al %llu, size %llu)", \ zone, (ULong)alignment, (ULong)n ); \ \ /* Round up to minimum alignment if necessary. */ \ if (alignment < VG_MIN_MALLOC_SZB) \ alignment = VG_MIN_MALLOC_SZB; \ \ /* Round up to nearest power-of-two if necessary (like glibc). */ \ while (0 != (alignment & (alignment - 1))) alignment++; \ \ v = (void*)VALGRIND_NON_SIMD_CALL2( info.tl_memalign, alignment, n ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #define MEMALIGN(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10110,soname,fnname) \ ( SizeT alignment, SizeT n ); \ void* VG_REPLACE_FUNCTION_EZU(10110,soname,fnname) \ ( SizeT alignment, SizeT n ) \ { \ void* v; \ \ if (!init_done) init(); \ MALLOC_TRACE("memalign(al %llu, size %llu)", \ (ULong)alignment, (ULong)n ); \ \ /* Round up to minimum alignment if necessary. */ \ if (alignment < VG_MIN_MALLOC_SZB) \ alignment = VG_MIN_MALLOC_SZB; \ \ /* Round up to nearest power-of-two if necessary (like glibc). */ \ while (0 != (alignment & (alignment - 1))) alignment++; \ \ v = (void*)VALGRIND_NON_SIMD_CALL2( info.tl_memalign, alignment, n ); \ MALLOC_TRACE(" = %p\n", v ); \ return v; \ } #if defined(VGO_linux) MEMALIGN(VG_Z_LIBC_SONAME, memalign); #elif defined(VGO_darwin) MEMALIGN(VG_Z_LIBC_SONAME, memalign); ZONEMEMALIGN(VG_Z_LIBC_SONAME, malloc_zone_memalign); #endif /*---------------------- valloc ----------------------*/ #define VALLOC(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10120,soname,fnname) ( SizeT size ); \ void* VG_REPLACE_FUNCTION_EZU(10120,soname,fnname) ( SizeT size ) \ { \ static int pszB = 0; \ if (pszB == 0) \ pszB = my_getpagesize(); \ return VG_REPLACE_FUNCTION_EZU(10110,VG_Z_LIBC_SONAME,memalign) \ ((SizeT)pszB, size); \ } #define ZONEVALLOC(soname, fnname) \ \ void* VG_REPLACE_FUNCTION_EZU(10130,soname,fnname) \ ( void *zone, SizeT size ); \ void* VG_REPLACE_FUNCTION_EZU(10130,soname,fnname) \ ( void *zone, SizeT size ) \ { \ static int pszB = 0; \ if (pszB == 0) \ pszB = my_getpagesize(); \ return VG_REPLACE_FUNCTION_EZU(10110,VG_Z_LIBC_SONAME,memalign) \ ((SizeT)pszB, size); \ } #if defined(VGO_linux) VALLOC(VG_Z_LIBC_SONAME, valloc); #elif defined(VGO_darwin) VALLOC(VG_Z_LIBC_SONAME, valloc); ZONEVALLOC(VG_Z_LIBC_SONAME, malloc_zone_valloc); #endif /*---------------------- mallopt ----------------------*/ /* Various compatibility wrapper functions, for glibc and libstdc++. */ #define MALLOPT(soname, fnname) \ \ int VG_REPLACE_FUNCTION_EZU(10140,soname,fnname) ( int cmd, int value ); \ int VG_REPLACE_FUNCTION_EZU(10140,soname,fnname) ( int cmd, int value ) \ { \ /* In glibc-2.2.4, 1 denotes a successful return value for \ mallopt */ \ return 1; \ } #if defined(VGO_linux) MALLOPT(VG_Z_LIBC_SONAME, mallopt); #elif defined(VGO_darwin) //MALLOPT(VG_Z_LIBC_SONAME, mallopt); #endif /*---------------------- malloc_trim ----------------------*/ // Documentation says: // malloc_trim(size_t pad); // // If possible, gives memory back to the system (via negative arguments to // sbrk) if there is unused memory at the `high' end of the malloc pool. // You can call this after freeing large blocks of memory to potentially // reduce the system-level memory requirements of a program. However, it // cannot guarantee to reduce memory. Under some allocation patterns, // some large free blocks of memory will be locked between two used // chunks, so they cannot be given back to the system. // // The `pad' argument to malloc_trim represents the amount of free // trailing space to leave untrimmed. If this argument is zero, only the // minimum amount of memory to maintain internal data structures will be // left (one page or less). Non-zero arguments can be supplied to maintain // enough trailing space to service future expected allocations without // having to re-obtain memory from the system. // // Malloc_trim returns 1 if it actually released any memory, else 0. On // systems that do not support "negative sbrks", it will always return 0. // // For simplicity, we always return 0. #define MALLOC_TRIM(soname, fnname) \ \ int VG_REPLACE_FUNCTION_EZU(10150,soname,fnname) ( SizeT pad ); \ int VG_REPLACE_FUNCTION_EZU(10150,soname,fnname) ( SizeT pad ) \ { \ /* 0 denotes that malloc_trim() either wasn't able \ to do anything, or was not implemented */ \ return 0; \ } #if defined(VGO_linux) MALLOC_TRIM(VG_Z_LIBC_SONAME, malloc_trim); #elif defined(VGO_darwin) //MALLOC_TRIM(VG_Z_LIBC_SONAME, malloc_trim); #endif /*---------------------- posix_memalign ----------------------*/ #define POSIX_MEMALIGN(soname, fnname) \ \ int VG_REPLACE_FUNCTION_EZU(10160,soname,fnname) \ ( void **memptr, SizeT alignment, SizeT size ); \ int VG_REPLACE_FUNCTION_EZU(10160,soname,fnname) \ ( void **memptr, SizeT alignment, SizeT size ) \ { \ void *mem; \ \ /* Test whether the alignment argument is valid. It must be \ a power of two multiple of sizeof (void *). */ \ if (alignment % sizeof (void *) != 0 \ || (alignment & (alignment - 1)) != 0) \ return VKI_EINVAL; \ \ mem = VG_REPLACE_FUNCTION_EZU(10110,VG_Z_LIBC_SONAME,memalign) \ (alignment, size); \ \ if (mem != NULL) { \ *memptr = mem; \ return 0; \ } \ \ return VKI_ENOMEM; \ } #if defined(VGO_linux) POSIX_MEMALIGN(VG_Z_LIBC_SONAME, posix_memalign); #elif defined(VGO_darwin) //POSIX_MEMALIGN(VG_Z_LIBC_SONAME, posix_memalign); #endif /*---------------------- malloc_usable_size ----------------------*/ #define MALLOC_USABLE_SIZE(soname, fnname) \ \ SizeT VG_REPLACE_FUNCTION_EZU(10170,soname,fnname) ( void* p ); \ SizeT VG_REPLACE_FUNCTION_EZU(10170,soname,fnname) ( void* p ) \ { \ SizeT pszB; \ \ if (!init_done) init(); \ MALLOC_TRACE("malloc_usable_size(%p)", p ); \ if (NULL == p) \ return 0; \ \ pszB = (SizeT)VALGRIND_NON_SIMD_CALL1( info.tl_malloc_usable_size, p ); \ MALLOC_TRACE(" = %llu\n", (ULong)pszB ); \ \ return pszB; \ } #if defined(VGO_linux) MALLOC_USABLE_SIZE(VG_Z_LIBC_SONAME, malloc_usable_size); MALLOC_USABLE_SIZE(VG_Z_LIBC_SONAME, malloc_size); #elif defined(VGO_darwin) //MALLOC_USABLE_SIZE(VG_Z_LIBC_SONAME, malloc_usable_size); MALLOC_USABLE_SIZE(VG_Z_LIBC_SONAME, malloc_size); #endif /*---------------------- (unimplemented) ----------------------*/ /* Bomb out if we get any of these. */ static void panic(const char *str) { VALGRIND_PRINTF_BACKTRACE("Program aborting because of call to %s\n", str); my_exit(99); *(volatile int *)0 = 'x'; } #define PANIC(soname, fnname) \ \ void VG_REPLACE_FUNCTION_EZU(10180,soname,fnname) ( void ); \ void VG_REPLACE_FUNCTION_EZU(10180,soname,fnname) ( void ) \ { \ panic(#fnname); \ } #if defined(VGO_linux) PANIC(VG_Z_LIBC_SONAME, pvalloc); PANIC(VG_Z_LIBC_SONAME, malloc_get_state); PANIC(VG_Z_LIBC_SONAME, malloc_set_state); #elif defined(VGO_darwin) PANIC(VG_Z_LIBC_SONAME, pvalloc); PANIC(VG_Z_LIBC_SONAME, malloc_get_state); PANIC(VG_Z_LIBC_SONAME, malloc_set_state); #endif #define MALLOC_STATS(soname, fnname) \ \ void VG_REPLACE_FUNCTION_EZU(10190,soname,fnname) ( void ); \ void VG_REPLACE_FUNCTION_EZU(10190,soname,fnname) ( void ) \ { \ /* Valgrind's malloc_stats implementation does nothing. */ \ } #if defined(VGO_linux) MALLOC_STATS(VG_Z_LIBC_SONAME, malloc_stats); #elif defined(VGO_darwin) //MALLOC_STATS(VG_Z_LIBC_SONAME, malloc_stats); #endif /*---------------------- mallinfo ----------------------*/ // mi must be static; if it is auto then Memcheck thinks it is // uninitialised when used by the caller of this function, because Memcheck // doesn't know that the call to mallinfo fills in mi. #define MALLINFO(soname, fnname) \ \ struct vg_mallinfo VG_REPLACE_FUNCTION_EZU(10200,soname,fnname) ( void ); \ struct vg_mallinfo VG_REPLACE_FUNCTION_EZU(10200,soname,fnname) ( void ) \ { \ static struct vg_mallinfo mi; \ if (!init_done) init(); \ MALLOC_TRACE("mallinfo()\n"); \ (void)VALGRIND_NON_SIMD_CALL1( info.mallinfo, &mi ); \ return mi; \ } #if defined(VGO_linux) MALLINFO(VG_Z_LIBC_SONAME, mallinfo); #elif defined(VGO_darwin) //MALLINFO(VG_Z_LIBC_SONAME, mallinfo); #endif /*------------------ Darwin zone stuff ------------------*/ #if defined(VGO_darwin) static vki_malloc_zone_t vg_default_zone = { NULL, // reserved1 NULL, // reserved2 NULL, // GrP fixme: malloc_size (void*)VG_REPLACE_FUNCTION_EZU(10020,VG_Z_LIBC_SONAME,malloc_zone_malloc), (void*)VG_REPLACE_FUNCTION_EZU(10060,VG_Z_LIBC_SONAME,malloc_zone_calloc), (void*)VG_REPLACE_FUNCTION_EZU(10130,VG_Z_LIBC_SONAME,malloc_zone_valloc), (void*)VG_REPLACE_FUNCTION_EZU(10040,VG_Z_LIBC_SONAME,malloc_zone_free), (void*)VG_REPLACE_FUNCTION_EZU(10080,VG_Z_LIBC_SONAME,malloc_zone_realloc), NULL, // GrP fixme: destroy "ValgrindMallocZone", NULL, // batch_malloc NULL, // batch_free NULL, // GrP fixme: introspect 2, // version (GrP fixme 3?) NULL, /* memalign */ // DDD: this field exists in Mac OS 10.6, but not 10.5. NULL, /* free_definite_size */ NULL, /* pressure_relief */ }; #define DEFAULT_ZONE(soname, fnname) \ \ void *VG_REPLACE_FUNCTION_EZU(10210,soname,fnname) ( void ); \ void *VG_REPLACE_FUNCTION_EZU(10210,soname,fnname) ( void ) \ { \ return &vg_default_zone; \ } DEFAULT_ZONE(VG_Z_LIBC_SONAME, malloc_default_zone); #define ZONE_FROM_PTR(soname, fnname) \ \ void *VG_REPLACE_FUNCTION_EZU(10220,soname,fnname) ( void* ptr ); \ void *VG_REPLACE_FUNCTION_EZU(10220,soname,fnname) ( void* ptr ) \ { \ return &vg_default_zone; \ } ZONE_FROM_PTR(VG_Z_LIBC_SONAME, malloc_zone_from_ptr); // GrP fixme bypass libc's use of zone->introspect->check #define ZONE_CHECK(soname, fnname) \ \ int VG_REPLACE_FUNCTION_EZU(10230,soname,fnname)(void* zone); \ int VG_REPLACE_FUNCTION_EZU(10230,soname,fnname)(void* zone) \ { \ return 1; \ } //ZONE_CHECK(VG_Z_LIBC_SONAME, malloc_zone_check); #endif /* defined(VGO_darwin) */ /*------------------ (startup related) ------------------*/ /* All the code in here is unused until this function is called */ __attribute__((constructor)) static void init(void) { // This doesn't look thread-safe, but it should be ok... Bart says: // // Every program I know of calls malloc() at least once before calling // pthread_create(). So init_done gets initialized before any thread is // created, and is only read when multiple threads are active // simultaneously. Such an access pattern is safe. // // If the assignment to the variable init_done would be triggering a race // condition, both DRD and Helgrind would report this race. // // By the way, although the init() function in // coregrind/m_replacemalloc/vg_replace_malloc.c has been declared // __attribute__((constructor)), it is not safe to remove the variable // init_done. This is because it is possible that malloc() and hence // init() gets called before shared library initialization finished. // if (init_done) return; init_done = 1; VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__GET_MALLOCFUNCS, &info, 0, 0, 0, 0); } /*--------------------------------------------------------------------*/ /*--- end ---*/ /*--------------------------------------------------------------------*/
gpl-3.0
jmue/cppcheck
test/testpreprocessor.cpp
5
153143
/* * 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/>. */ // The preprocessor that Cppcheck uses is a bit special. Instead of generating // the code for a known configuration, it generates the code for each configuration. #include "testsuite.h" #include "preprocessor.h" #include "tokenize.h" #include "token.h" #include "settings.h" #include <map> #include <string> #include <set> #ifdef _MSC_VER // Visual Studio complains about truncated values for '(char)0xff' and '(char)0xfe' // TODO: Is there any nice way to fix these warnings? #pragma warning( disable : 4310 ) #endif class TestPreprocessor : public TestFixture { public: TestPreprocessor() : TestFixture("TestPreprocessor") { Preprocessor::macroChar = '$'; } class OurPreprocessor : public Preprocessor { public: static std::string replaceIfDefined(std::string str) { Settings settings; Preprocessor p(settings); p.replaceIfDefined(str); return str; } static std::string expandMacros(const char code[], ErrorLogger *errorLogger = 0) { return Preprocessor::expandMacros(code, "file.cpp", "", errorLogger); } static int getHeaderFileName(std::string &str) { return Preprocessor::getHeaderFileName(str); } }; private: void run() { // Just read the code into a string. Perform simple cleanup of the code TEST_CASE(readCode1); TEST_CASE(readCode2); // #4308 - convert C++11 raw string to plain old C string TEST_CASE(readCode3); TEST_CASE(readCode4); // #4351 - escaped whitespace in gcc // reading utf-16 file TEST_CASE(utf16); // remove comments TEST_CASE(removeComments); // The bug that started the whole work with the new preprocessor TEST_CASE(Bug2190219); TEST_CASE(test1); TEST_CASE(test2); TEST_CASE(test3); TEST_CASE(test4); TEST_CASE(test5); TEST_CASE(test6); TEST_CASE(test7); TEST_CASE(test7a); TEST_CASE(test7b); TEST_CASE(test7c); TEST_CASE(test7d); TEST_CASE(test7e); TEST_CASE(test8); // #if A==1 => cfg: A=1 TEST_CASE(test9); // Don't crash for invalid code TEST_CASE(test10); // Ticket #5139 TEST_CASE(error1); // #error => don't extract any code TEST_CASE(error2); // #error with extended chars TEST_CASE(error3); TEST_CASE(error4); // #2919 - wrong filename is reported TEST_CASE(error5); TEST_CASE(if0_exclude); TEST_CASE(if0_whitespace); TEST_CASE(if0_else); TEST_CASE(if0_elif); // Don't handle include in a #if 0 block TEST_CASE(if0_include_1); TEST_CASE(if0_include_2); // Handling include guards (don't create extra configuration for it) TEST_CASE(includeguard1); TEST_CASE(includeguard2); TEST_CASE(newlines); TEST_CASE(comments1); TEST_CASE(if0); TEST_CASE(if1); TEST_CASE(elif); // Test the Preprocessor::match_cfg_def TEST_CASE(match_cfg_def); TEST_CASE(if_cond1); TEST_CASE(if_cond2); TEST_CASE(if_cond3); TEST_CASE(if_cond4); TEST_CASE(if_cond5); TEST_CASE(if_cond6); TEST_CASE(if_cond8); TEST_CASE(if_cond9); TEST_CASE(if_cond10); TEST_CASE(if_cond11); TEST_CASE(if_cond12); TEST_CASE(if_cond13); TEST_CASE(if_cond14); TEST_CASE(if_cond15); // #4456 - segfault TEST_CASE(if_or_1); TEST_CASE(if_or_2); TEST_CASE(if_macro_eq_macro); // #3536 TEST_CASE(ticket_3675); TEST_CASE(ticket_3699); TEST_CASE(ticket_4922); // #4922 TEST_CASE(multiline1); TEST_CASE(multiline2); TEST_CASE(multiline3); TEST_CASE(multiline4); TEST_CASE(multiline5); TEST_CASE(remove_asm); TEST_CASE(if_defined); // "#if defined(AAA)" => "#ifdef AAA" TEST_CASE(if_not_defined); // "#if !defined(AAA)" => "#ifndef AAA" // Macros.. TEST_CASE(macro_simple1); TEST_CASE(macro_simple2); TEST_CASE(macro_simple3); TEST_CASE(macro_simple4); TEST_CASE(macro_simple5); TEST_CASE(macro_simple6); TEST_CASE(macro_simple7); TEST_CASE(macro_simple8); TEST_CASE(macro_simple9); TEST_CASE(macro_simple10); TEST_CASE(macro_simple11); TEST_CASE(macro_simple12); TEST_CASE(macro_simple13); TEST_CASE(macro_simple14); TEST_CASE(macro_simple15); TEST_CASE(macro_simple16); // #4703: Macro parameters not trimmed TEST_CASE(macro_simple17); // #5074: isExpandedMacro not set TEST_CASE(macro_simple18); // (1e-7) TEST_CASE(macroInMacro1); TEST_CASE(macroInMacro2); TEST_CASE(macro_mismatch); TEST_CASE(macro_linenumbers); TEST_CASE(macro_nopar); TEST_CASE(macro_switchCase); TEST_CASE(macro_NULL); // skip #define NULL .. it is replaced in the tokenizer TEST_CASE(string1); TEST_CASE(string2); TEST_CASE(string3); TEST_CASE(preprocessor_undef); TEST_CASE(defdef); // Defined multiple times TEST_CASE(preprocessor_doublesharp); TEST_CASE(preprocessor_include_in_str); TEST_CASE(va_args_1); TEST_CASE(va_args_2); TEST_CASE(va_args_3); TEST_CASE(va_args_4); TEST_CASE(multi_character_character); TEST_CASE(stringify); TEST_CASE(stringify2); TEST_CASE(stringify3); TEST_CASE(stringify4); TEST_CASE(stringify5); TEST_CASE(ifdefwithfile); TEST_CASE(pragma); TEST_CASE(pragma_asm_1); TEST_CASE(pragma_asm_2); TEST_CASE(pragma_once); TEST_CASE(endifsemicolon); TEST_CASE(missing_doublequote); TEST_CASE(handle_error); TEST_CASE(dup_defines); TEST_CASE(unicodeInCode); TEST_CASE(unicodeInComment); TEST_CASE(unicodeInString); TEST_CASE(define_part_of_func); TEST_CASE(conditionalDefine); TEST_CASE(multiline_comment); TEST_CASE(macro_parameters); TEST_CASE(newline_in_macro); TEST_CASE(includes); TEST_CASE(ifdef_ifdefined); // define and then ifdef TEST_CASE(define_if1); TEST_CASE(define_if2); TEST_CASE(define_if3); TEST_CASE(define_if4); // #4079 - #define X +123 TEST_CASE(define_if5); // #4516 - #define B (A & 0x00f0) TEST_CASE(define_if6); // #4863 - #define B (A?-1:1) TEST_CASE(define_ifdef); TEST_CASE(define_ifndef1); TEST_CASE(define_ifndef2); TEST_CASE(ifndef_define); TEST_CASE(undef_ifdef); TEST_CASE(endfile); TEST_CASE(redundant_config); TEST_CASE(testPreprocessorRead1); TEST_CASE(testPreprocessorRead2); TEST_CASE(testPreprocessorRead3); TEST_CASE(testPreprocessorRead4); TEST_CASE(invalid_define_1); // #2605 - hang for: '#define =' TEST_CASE(invalid_define_2); // #4036 - hang for: '#define () {(int f(x) }' // Show 'missing include' warnings TEST_CASE(missingInclude); // inline suppression, missingInclude TEST_CASE(inline_suppression_for_missing_include); // Using -D to predefine symbols TEST_CASE(predefine1); TEST_CASE(predefine2); TEST_CASE(predefine3); TEST_CASE(predefine4); TEST_CASE(predefine5); // automatically define __cplusplus TEST_CASE(predefine6); // using -D and -f => check all matching configurations // Test Preprocessor::simplifyCondition TEST_CASE(simplifyCondition); TEST_CASE(invalidElIf); // #2942 segfault // Defines are given: test Preprocessor::handleIncludes TEST_CASE(def_handleIncludes); TEST_CASE(def_missingInclude); TEST_CASE(def_handleIncludes_ifelse1); // problems in handleIncludes for #else TEST_CASE(def_handleIncludes_ifelse2); TEST_CASE(def_handleIncludes_ifelse3); // #4868 - crash TEST_CASE(def_valueWithParentheses); // #3531 // Using -U to undefine symbols TEST_CASE(undef1); TEST_CASE(undef2); TEST_CASE(undef3); TEST_CASE(undef4); TEST_CASE(undef5); TEST_CASE(undef6); TEST_CASE(undef7); TEST_CASE(undef8); TEST_CASE(undef9); TEST_CASE(undef10); TEST_CASE(handleUndef); TEST_CASE(macroChar); TEST_CASE(validateCfg); TEST_CASE(if_sizeof); TEST_CASE(double_include); // #5717 TEST_CASE(invalid_ifs); // #5909 TEST_CASE(garbage); } void readCode1() { const char code[] = " \t a //\n" " #aa\t /* remove this */\tb \r\n"; Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::string codestr(preprocessor.read(istr,"test.c")); ASSERT_EQUALS("a\n#aa b\n", codestr); } void readCode2() { const char code[] = "R\"( \" \\ ' /* abc */ \n)\";"; Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::string codestr(preprocessor.read(istr,"test.c")); ASSERT_EQUALS("\" \\\" \\\\ ' /* abc */ \\n\"\n;", codestr); } void readCode3() { const char code[] = "func(#errorname)"; Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::string codestr(preprocessor.read(istr,"test.c")); ASSERT_EQUALS("func(#errorname)", codestr); } void readCode4() { const char code[] = "char c = '\\ ';"; Settings settings; errout.str(""); Preprocessor preprocessor(settings, this); std::istringstream istr(code); ASSERT_EQUALS("char c = '\\ ';", preprocessor.read(istr,"test.c")); ASSERT_EQUALS("", errout.str()); } void utf16() { Settings settings; Preprocessor preprocessor(settings, this); // a => a { const char code[] = { (char)0xff, (char)0xfe, 'a', '\0' }; std::string s(code, sizeof(code)); std::istringstream istr(s); ASSERT_EQUALS("a", preprocessor.read(istr, "test.c")); } { const char code[] = { (char)0xfe, (char)0xff, '\0', 'a' }; std::string s(code, sizeof(code)); std::istringstream istr(s); ASSERT_EQUALS("a", preprocessor.read(istr, "test.c")); } // extended char => 0xff { const char code[] = { (char)0xff, (char)0xfe, 'a', 'a' }; std::string s(code, sizeof(code)); std::istringstream istr(s); const char expected[] = { (char)0xff, 0 }; ASSERT_EQUALS(expected, preprocessor.read(istr, "test.c")); } { const char code[] = { (char)0xfe, (char)0xff, 'a', 'a' }; std::string s(code, sizeof(code)); std::istringstream istr(s); const char expected[] = { (char)0xff, 0 }; ASSERT_EQUALS(expected, preprocessor.read(istr, "test.c")); } // \r\n => \n { const char code[] = { (char)0xff, (char)0xfe, '\r', '\0', '\n', '\0' }; std::string s(code, sizeof(code)); std::istringstream istr(s); ASSERT_EQUALS("\n", preprocessor.read(istr, "test.c")); } { const char code[] = { (char)0xfe, (char)0xff, '\0', '\r', '\0', '\n' }; std::string s(code, sizeof(code)); std::istringstream istr(s); ASSERT_EQUALS("\n", preprocessor.read(istr, "test.c")); } } void removeComments() { Settings settings; Preprocessor preprocessor(settings, this); // #3837 - asm comments const char code[] = "void test(void) {\n" " __asm\n" " {\n" " ;---- тест\n" " }\n" "}\n"; ASSERT_EQUALS(true, std::string::npos == preprocessor.removeComments(code, "3837.c").find("----")); ASSERT_EQUALS(" __asm123", preprocessor.removeComments(" __asm123", "3837.cpp")); ASSERT_EQUALS("\" __asm { ; } \"", preprocessor.removeComments("\" __asm { ; } \"", "3837.cpp")); ASSERT_EQUALS("__asm__ volatile { \"\" }", preprocessor.removeComments("__asm__ volatile { \"\" }", "3837.cpp")); // #4873 ASSERT_EQUALS("__asm { }", preprocessor.removeComments("__asm { /* This is a comment */ }", "4873.cpp")); // #5169 ASSERT_EQUALS("#define A(B) __asm__(\"int $3\"); int wait=1;\n", preprocessor.removeComments("#define A(B) __asm__(\"int $3\"); /**/ int wait=1;\n", "5169.c")); } void Bug2190219() { const char filedata[] = "int main()\n" "{\n" "#ifdef __cplusplus\n" " int* flags = new int[10];\n" "#else\n" " int* flags = (int*)malloc((10)*sizeof(int));\n" "#endif\n" "\n" "#ifdef __cplusplus\n" " delete [] flags;\n" "#else\n" " free(flags);\n" "#endif\n" "}\n"; // Expected result.. std::map<std::string, std::string> expected; expected[""] = "int main()\n" "{\n" "\n" "\n" "\n" "int* flags = (int*)malloc((10)*sizeof(int));\n" "\n" "\n" "\n" "\n" "\n" "free(flags);\n" "\n" "}\n"; expected["__cplusplus"] = "int main()\n" "{\n" "\n" "int* flags = new int[10];\n" "\n" "\n" "\n" "\n" "\n" "delete [] flags;\n" "\n" "\n" "\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(expected[""], actual[""]); ASSERT_EQUALS(expected["__cplusplus"], actual["__cplusplus"]); ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test1() { const char filedata[] = "#ifdef WIN32 \n" " abcdef\n" "#else \n" " qwerty\n" "#endif \n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\nqwerty\n\n", actual[""]); ASSERT_EQUALS("\nabcdef\n\n\n\n", actual["WIN32"]); ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test2() { const char filedata[] = "# ifndef WIN32\n" " \" # ifdef WIN32\" // a comment\n" " # else \n" " qwerty\n" " # endif \n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\" # ifdef WIN32\"\n\n\n\n", actual[""]); ASSERT_EQUALS("\n\n\nqwerty\n\n", actual["WIN32"]); ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test3() { const char filedata[] = "#ifdef ABC\n" "a\n" "#ifdef DEF\n" "b\n" "#endif\n" "c\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\na\n\n\n\nc\n\n", actual["ABC"]); ASSERT_EQUALS("\na\n\nb\n\nc\n\n", actual["ABC;DEF"]); ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); } void test4() { const char filedata[] = "#ifdef ABC\n" "A\n" "#endif\t\n" "#ifdef ABC\n" "A\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\nA\n\n\nA\n\n", actual["ABC"]); ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test5() { const char filedata[] = "#ifdef ABC\n" "A\n" "#else\n" "B\n" "#ifdef DEF\n" "C\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\nB\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\nA\n\n\n\n\n\n\n", actual["ABC"]); ASSERT_EQUALS("\n\n\nB\n\nC\n\n\n", actual["DEF"]); ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); } void test6() { const char filedata[] = "#if(A)\n" "#if ( A ) \n" "#if A\n" "#if defined((A))\n" "#elif defined (A)\n"; std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); const std::string actual(preprocessor.read(istr, "test.c")); // Compare results.. ASSERT_EQUALS("#if A\n#if A\n#if A\n#if defined(A)\n#elif defined(A)\n", actual); } void test7() { const char filedata[] = "#ifdef ABC\n" "A\n" "#ifdef ABC\n" "B\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Make sure an error message is written.. TODO_ASSERT_EQUALS("[file.c:3]: (error) ABC is already guaranteed to be defined\n", "", errout.str()); // Compare results.. ASSERT_EQUALS("\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\nA\n\nB\n\n\n", actual["ABC"]); ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); test7a(); test7b(); test7c(); test7d(); } void test7a() { const char filedata[] = "#ifndef ABC\n" "A\n" "#ifndef ABC\n" "B\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Make sure an error message is written.. TODO_ASSERT_EQUALS("[file.c:3]: (error) ABC is already guaranteed NOT to be defined\n", "", errout.str()); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test7b() { const char filedata[] = "#ifndef ABC\n" "A\n" "#ifdef ABC\n" "B\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Make sure an error message is written.. TODO_ASSERT_EQUALS("[file.c:3]: (error) ABC is already guaranteed NOT to be defined\n", "", errout.str()); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test7c() { const char filedata[] = "#ifdef ABC\n" "A\n" "#ifndef ABC\n" "B\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Make sure an error message is written.. TODO_ASSERT_EQUALS("[file.c:3]: (error) ABC is already guaranteed to be defined\n", "", errout.str()); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test7d() { const char filedata[] = "#if defined(ABC)\n" "A\n" "#if defined(ABC)\n" "B\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Make sure an error message is written.. TODO_ASSERT_EQUALS("[file.c:3]: (error) ABC is already guaranteed to be defined\n", "", errout.str()); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test7e() { const char filedata[] = "#ifdef ABC\n" "#file \"test.h\"\n" "#ifndef test_h\n" "#define test_h\n" "#ifdef ABC\n" "#endif\n" "#endif\n" "#endfile\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Make sure an error message is written.. ASSERT_EQUALS("", errout.str()); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void test8() { const char filedata[] = "#if A == 1\n" "1\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // No error.. ASSERT_EQUALS("", errout.str()); // Compare results.. ASSERT_EQUALS(2U, actual.size()); ASSERT_EQUALS("\n\n\n", actual[""]); ASSERT_EQUALS("\n1\n\n", actual["A=1"]); } void test9() { const char filedata[] = "#if\n" "#else\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; settings._maxConfigs = 1; settings.userDefines = "X"; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // <- don't crash } void test10() { // Ticket #5139 const char filedata[] = "#define foo a.foo\n" "#define bar foo\n" "#define baz bar+0\n" "#if 0\n" "#endif"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); } void error1() { const char filedata[] = "#ifdef A\n" ";\n" "#else\n" "#error abcd\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); errout.str(""); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("", actual[""]); ASSERT_EQUALS("\n;\n\n\n\n", actual["A"]); } void error2() { errout.str(""); const char filedata[] = "#error \xAB\n" "#warning \xAB\n" "123"; // Read string.. std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#error\n\n123", preprocessor.read(istr,"test.c")); } void error3() { errout.str(""); Settings settings; settings.userDefines = "__cplusplus"; Preprocessor preprocessor(settings, this); const std::string code("#error hello world!\n"); preprocessor.getcode(code, "X", "test.c"); ASSERT_EQUALS("[test.c:1]: (error) #error hello world!\n", errout.str()); } // Ticket #2919 - wrong filename reported for #error void error4() { // In included file { errout.str(""); Settings settings; settings.userDefines = "TEST"; Preprocessor preprocessor(settings, this); const std::string code("#file \"ab.h\"\n#error hello world!\n#endfile"); preprocessor.getcode(code, "TEST", "test.c"); ASSERT_EQUALS("[ab.h:1]: (error) #error hello world!\n", errout.str()); } // After including a file { errout.str(""); Settings settings; settings.userDefines = "TEST"; Preprocessor preprocessor(settings, this); const std::string code("#file \"ab.h\"\n\n#endfile\n#error aaa"); preprocessor.getcode(code, "TEST", "test.c"); ASSERT_EQUALS("[test.c:2]: (error) #error aaa\n", errout.str()); } } void error5() { errout.str(""); Settings settings; settings.userDefines = "FOO"; settings._force = true; // No message if --force is given Preprocessor preprocessor(settings, this); const std::string code("#error hello world!\n"); preprocessor.getcode(code, "X", "test.c"); ASSERT_EQUALS("", errout.str()); } void if0_exclude() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream code("#if 0\n" "A\n" "#endif\n" "B\n"); ASSERT_EQUALS("#if 0\n\n#endif\nB\n", preprocessor.read(code,"")); std::istringstream code2("#if (0)\n" "A\n" "#endif\n" "B\n"); ASSERT_EQUALS("#if 0\n\n#endif\nB\n", preprocessor.read(code2,"")); } void if0_whitespace() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream code(" # if 0 \n" "A\n" " # endif \n" "B\n"); ASSERT_EQUALS("#if 0\n\n#endif\nB\n", preprocessor.read(code,"")); } void if0_else() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream code("#if 0\n" "A\n" "#else\n" "B\n" "#endif\n" "C\n"); ASSERT_EQUALS("#if 0\n\n#else\nB\n#endif\nC\n", preprocessor.read(code,"")); std::istringstream code2("#if 1\n" "A\n" "#else\n" "B\n" "#endif\n" "C\n"); TODO_ASSERT_EQUALS("#if 1\nA\n#else\n\n#endif\nC\n", "#if 1\nA\n#else\nB\n#endif\nC\n", preprocessor.read(code2,"")); } void if0_elif() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream code("#if 0\n" "A\n" "#elif 1\n" "B\n" "#endif\n" "C\n"); ASSERT_EQUALS("#if 0\n\n#elif 1\nB\n#endif\nC\n", preprocessor.read(code,"")); } void if0_include_1() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream code("#if 0\n" "#include \"a.h\"\n" "#endif\n" "AB\n"); ASSERT_EQUALS("#if 0\n\n#endif\nAB\n", preprocessor.read(code,"")); } void if0_include_2() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream code("#if 0\n" "#include \"a.h\"\n" "#ifdef WIN32\n" "#else\n" "#endif\n" "#endif\n" "AB\n"); ASSERT_EQUALS("#if 0\n\n#ifdef WIN32\n#else\n#endif\n#endif\nAB\n", preprocessor.read(code,"")); } void includeguard1() { // Handling include guards.. const char filedata[] = "#file \"abc.h\"\n" "#ifndef abcH\n" "#define abcH\n" "#endif\n" "#endfile\n" "#ifdef ABC\n" "#endif"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Expected configurations: "" and "ABC" ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void includeguard2() { // Handling include guards.. const char filedata[] = "#file \"abc.h\"\n" "foo\n" "#ifdef ABC\n" "\n" "#endif\n" "#endfile\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Expected configurations: "" and "ABC" ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS(true, actual.find("") != actual.end()); ASSERT_EQUALS(true, actual.find("ABC") != actual.end()); } void ifdefwithfile() { // Handling include guards.. const char filedata[] = "#ifdef ABC\n" "#file \"abc.h\"\n" "class A{};/*\n\n\n\n\n\n\n*/\n" "#endfile\n" "#endif\n" "int main() {}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Expected configurations: "" and "ABC" ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n#file \"abc.h\"\n\n\n\n\n\n\n\n\n#endfile\n\nint main() {}\n", actual[""]); ASSERT_EQUALS("\n#file \"abc.h\"\nclass A{};\n\n\n\n\n\n\n\n#endfile\n\nint main() {}\n", actual["ABC"]); } void newlines() { const char filedata[] = "\r\r\n\n"; // Preprocess std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\n", preprocessor.read(istr, "test.c")); } void comments1() { { const char filedata[] = "/*\n" "#ifdef WIN32\n" "#endif\n" "*/\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n", actual[""]); ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); } { const char filedata[] = "/*\n" "\x080 #ifdef WIN32\n" "#endif\n" "*/\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n", actual[""]); ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); } { const char filedata[] = "void f()\n" "{\n" " *p = a / *b / *c;\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("void f()\n{\n*p = a / *b / *c;\n}\n", actual[""]); ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); } } void if0() { const char filedata[] = " # if /* comment */ 0 // comment\n" "#ifdef WIN32\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n", actual[""]); ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); } void if1() { const char filedata[] = " # if /* comment */ 1 // comment\n" "ABC\n" " # endif \n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\nABC\n\n", actual[""]); ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); } void elif() { { const char filedata[] = "#if DEF1\n" "ABC\n" "#elif DEF2\n" "DEF\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\nABC\n\n\n\n", actual["DEF1"]); ASSERT_EQUALS("\n\n\nDEF\n\n", actual["DEF2"]); ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); } { const char filedata[] = "#if(defined DEF1)\n" "ABC\n" "#elif(defined DEF2)\n" "DEF\n" "#else\n" "GHI\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n\nGHI\n\n", actual[""]); ASSERT_EQUALS("\nABC\n\n\n\n\n\n", actual["DEF1"]); ASSERT_EQUALS("\n\n\nDEF\n\n\n\n", actual["DEF2"]); ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); } } void match_cfg_def() { Settings settings; Preprocessor preprocessor(settings, this); { std::map<std::string, std::string> cfg; ASSERT_EQUALS(false, preprocessor.match_cfg_def(cfg, "A>1||defined(B)")); } { std::map<std::string, std::string> cfg; cfg["A"] = ""; cfg["B"] = ""; ASSERT_EQUALS(true, preprocessor.match_cfg_def(cfg, "defined(A)&&defined(B)")); } { std::map<std::string, std::string> cfg; cfg["ABC"] = ""; ASSERT_EQUALS(false, preprocessor.match_cfg_def(cfg, "defined(A)")); ASSERT_EQUALS(true, preprocessor.match_cfg_def(cfg, "!defined(A)")); ASSERT_EQUALS(false, preprocessor.match_cfg_def(cfg, "!defined(ABC)&&!defined(DEF)")); ASSERT_EQUALS(true, preprocessor.match_cfg_def(cfg, "!defined(A)&&!defined(B)")); } { std::map<std::string, std::string> cfg; cfg["A"] = "1"; cfg["B"] = "2"; ASSERT_EQUALS(true, preprocessor.match_cfg_def(cfg, "A==1")); ASSERT_EQUALS(true, preprocessor.match_cfg_def(cfg, "A<2")); ASSERT_EQUALS(false, preprocessor.match_cfg_def(cfg, "A==2")); ASSERT_EQUALS(false, preprocessor.match_cfg_def(cfg, "A<1")); ASSERT_EQUALS(false, preprocessor.match_cfg_def(cfg, "A>=1&&B<=A")); ASSERT_EQUALS(true, preprocessor.match_cfg_def(cfg, "A==1 && A==1")); } } void if_cond1() { const char filedata[] = "#if LIBVER>100\n" " A\n" "#else\n" " B\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\nB\n\n", actual[""]); TODO_ASSERT_EQUALS("\nA\n\n\n\n", "", actual["LIBVER=101"]); } void if_cond2() { const char filedata[] = "#ifdef A\n" "a\n" "#endif\n" "#if defined(A) && defined(B)\n" "ab\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\na\n\n\n\n\n", actual["A"]); ASSERT_EQUALS("\na\n\n\nab\n\n", actual["A;B"]); if_cond2b(); if_cond2c(); if_cond2d(); if_cond2e(); } void if_cond2b() { const char filedata[] = "#ifndef A\n" "!a\n" "#ifdef B\n" "b\n" "#endif\n" "#else\n" "a\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n!a\n\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\n\n\n\n\n\na\n\n", actual["A"]); ASSERT_EQUALS("\n!a\n\nb\n\n\n\n\n", actual["B"]); } void if_cond2c() { const char filedata[] = "#ifndef A\n" "!a\n" "#ifdef B\n" "b\n" "#else\n" "!b\n" "#endif\n" "#else\n" "a\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n!a\n\n\n\n!b\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\n\n\n\n\n\n\n\na\n\n", actual["A"]); ASSERT_EQUALS("\n!a\n\nb\n\n\n\n\n\n\n", actual["B"]); } void if_cond2d() { const char filedata[] = "#ifndef A\n" "!a\n" "#ifdef B\n" "b\n" "#else\n" "!b\n" "#endif\n" "#else\n" "a\n" "#ifdef B\n" "b\n" "#else\n" "!b\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(4, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n!a\n\n\n\n!b\n\n\n\n\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\n\n\n\n\n\n\n\na\n\n\n\n!b\n\n\n", actual["A"]); ASSERT_EQUALS("\n\n\n\n\n\n\n\na\n\nb\n\n\n\n\n", actual["A;B"]); ASSERT_EQUALS("\n!a\n\nb\n\n\n\n\n\n\n\n\n\n\n\n", actual["B"]); } void if_cond2e() { const char filedata[] = "#if !defined(A)\n" "!a\n" "#elif !defined(B)\n" "!b\n" "#endif\n"; // Preprocess => actual result.. errout.str(""); std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; settings.debug = settings.debugwarnings = true; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n!a\n\n\n\n", actual[""]); ASSERT_EQUALS("\n\n\n!b\n\n", actual["A"]); TODO_ASSERT_EQUALS("\n\n\n\n\n", "", actual["A;B"]); ASSERT_EQUALS("", errout.str()); } void if_cond3() { const char filedata[] = "#ifdef A\n" "a\n" "#if defined(B) && defined(C)\n" "abc\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\na\n\n\n\n\n", actual["A"]); ASSERT_EQUALS("\na\n\nabc\n\n\n", actual["A;B;C"]); } void if_cond4() { { const char filedata[] = "#define A\n" "#define B\n" "#if defined A || defined B\n" "ab\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\nab\n\n", actual[""]); } { const char filedata[] = "#if A\n" "{\n" "#if (defined(B))\n" "foo();\n" "#endif\n" "}\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(3, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\n{\n\n\n\n}\n\n", actual["A"]); ASSERT_EQUALS("\n{\n\nfoo();\n\n}\n\n", actual["A;B"]); } { const char filedata[] = "#define A\n" "#define B\n" "#if (defined A) || defined (B)\n" "ab\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\nab\n\n", actual[""]); } { const char filedata[] = "#if (A)\n" "foo();\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\n", actual[""]); ASSERT_EQUALS("\nfoo();\n\n", actual["A"]); } { const char filedata[] = "#if! A\n" "foo();\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. TODO_ASSERT_EQUALS(2, 1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\nfoo();\n\n", actual[""]); } } void if_cond5() { const char filedata[] = "#if defined(A) && defined(B)\n" "ab\n" "#endif\n" "cd\n" "#if defined(B) && defined(A)\n" "ef\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\ncd\n\n\n\n", actual[""]); ASSERT_EQUALS("\nab\n\ncd\n\nef\n\n", actual["A;B"]); } void if_cond6() { const char filedata[] = "\n" "#if defined(A) && defined(B))\n" "#endif\n"; errout.str(""); // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("[file.c:2]: (error) mismatching number of '(' and ')' in this line: defined(A)&&defined(B))\n", errout.str()); } void if_cond8() { const char filedata[] = "#if defined(A) + defined(B) + defined(C) != 1\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, (int)actual.size()); ASSERT_EQUALS("\n\n", actual[""]); } void if_cond9() { const char filedata[] = "#if !defined _A\n" "abc\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, (int)actual.size()); ASSERT_EQUALS("\nabc\n\n", actual[""]); } void if_cond10() { const char filedata[] = "#if !defined(a) && !defined(b)\n" "#if defined(and)\n" "#endif\n" "#endif\n"; // Preprocess => don't crash.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); } void if_cond11() { errout.str(""); const char filedata[] = "#if defined(L_fixunssfdi) && LIBGCC2_HAS_SF_MODE\n" "#if LIBGCC2_HAS_DF_MODE\n" "#elif FLT_MANT_DIG < W_TYPE_SIZE\n" "#endif\n" "#endif\n"; std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); ASSERT_EQUALS("", errout.str()); } void if_cond12() { const char filedata[] = "#define A (1)\n" "#if A == 1\n" ";\n" "#endif\n"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n;\n\n", preprocessor.getcode(filedata,"","")); } void if_cond13() { const char filedata[] = "#if ('A' == 0x41)\n" "123\n" "#endif\n"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n123\n\n", preprocessor.getcode(filedata,"","")); } void if_cond14() { const char filedata[] = "#if !(A)\n" "123\n" "#endif\n"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n123\n\n", preprocessor.getcode(filedata,"","")); } void if_cond15() { // #4456 - segmentation fault const char filedata[] = "#if ((A >= B) && (C != D))\n" "#if (E < F(1))\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "4456.c"); // <- don't crash in Preprocessor::getcfgs -> Tokenize -> number of template parameters } void if_or_1() { const char filedata[] = "#if defined(DEF_10) || defined(DEF_11)\n" "a1;\n" "#endif\n"; errout.str(""); output.str(""); // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; settings.debug = settings.debugwarnings = true; settings.addEnabled("missingInclude"); Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, (int)actual.size()); ASSERT_EQUALS("\n\n\n", actual[""]); // the "defined(DEF_10) || defined(DEF_11)" are not handled correctly.. ASSERT_EQUALS("(debug) unhandled configuration: defined(DEF_10)||defined(DEF_11)\n", errout.str()); TODO_ASSERT_EQUALS(2, 1, actual.size()); TODO_ASSERT_EQUALS("\na1;\n\n", "", actual["DEF_10"]); } void if_or_2() { const std::string code("#if X || Y\n" "a1;\n" "#endif\n"); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\na1;\n\n", preprocessor.getcode(code, "X", "test.c")); ASSERT_EQUALS("\na1;\n\n", preprocessor.getcode(code, "Y", "test.c")); } void if_macro_eq_macro() { const std::string code("#define A B\n" "#define B 1\n" "#define C 1\n" "#if A == C\n" "Wilma\n" "#else\n" "Betty\n" "#endif\n"); Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::map<std::string, std::string> actual; preprocessor.preprocess(istr, actual, "file.c"); ASSERT_EQUALS("\n\n\n\nWilma\n\n\n\n", actual[""]); } void ticket_3675() { const std::string code("#ifdef YYSTACKSIZE\n" "#define YYMAXDEPTH YYSTACKSIZE\n" "#else\n" "#define YYSTACKSIZE YYMAXDEPTH\n" "#endif\n" "#if YYDEBUG\n" "#endif\n"); Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::map<std::string, std::string> actual; preprocessor.preprocess(istr, actual, "file.c"); // There's nothing to assert. It just needs to not hang. } void ticket_3699() { const std::string code("#define INLINE __forceinline\n" "#define inline __forceinline\n" "#define __forceinline inline\n" "#if !defined(_WIN32)\n" "#endif\n" "INLINE inline __forceinline\n" ); Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::map<std::string, std::string> actual; preprocessor.preprocess(istr, actual, "file.c"); // First, it must not hang. Second, inline must becomes inline, and __forceinline must become __forceinline. ASSERT_EQUALS("\n\n\n\n\n$$$__forceinline $$inline $$__forceinline\n", actual[""]); } void ticket_4922() { // #4922 const std::string code("__asm__ \n" "{ int extern __value) 0; (double return (\"\" } extern\n" "__typeof __finite (__finite) __finite __inline \"__GI___finite\");"); Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::map<std::string, std::string> actual; preprocessor.preprocess(istr, actual, "file.cpp"); } void multiline1() { const char filedata[] = "#define str \"abc\" \\\n" " \"def\" \n" "abcdef = str;\n"; // Preprocess => actual result.. std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#define str \"abc\" \"def\"\n\nabcdef = str;\n", preprocessor.read(istr, "test.c")); } void multiline2() { const char filedata[] = "#define sqr(aa) aa * \\\n" " aa\n" "sqr(5);\n"; // Preprocess => actual result.. std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#define sqr(aa) aa * aa\n\nsqr(5);\n", preprocessor.read(istr, "test.c")); } void multiline3() { const char filedata[] = "const char *str = \"abc\\\n" "def\\\n" "ghi\"\n"; // Preprocess => actual result.. std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("const char *str = \"abcdefghi\"\n\n\n", preprocessor.read(istr, "test.c")); } void multiline4() { errout.str(""); const char filedata[] = "#define A int a = 4;\\ \n" " int b = 5;\n" "A\n"; // Preprocess => actual result.. Settings settings; std::istringstream istr(filedata); std::map<std::string, std::string> actual; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); #ifdef __GNUC__ ASSERT_EQUALS("\n\n$int $a = $4; $int $b = $5;\n", actual[""]); #else ASSERT_EQUALS("\nint b = 5;\n$int $a = $4;\\\n", actual[""]); #endif ASSERT_EQUALS("", errout.str()); } void multiline5() { errout.str(""); const char filedata[] = "#define ABC int a /*\n" "*/= 4;\n" "int main(){\n" "ABC\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\nint main(){\n$int $a = $4;\n}\n", actual[""]); ASSERT_EQUALS("", errout.str()); } void remove_asm() const { std::string str1("#asm\nmov ax,bx\n#endasm"); Preprocessor::removeAsm(str1); ASSERT_EQUALS("asm(\nmov ax,bx\n);", str1); std::string str2("\n#asm\nmov ax,bx\n#endasm\n"); Preprocessor::removeAsm(str2); ASSERT_EQUALS("\nasm(\nmov ax,bx\n);\n", str2); } void if_defined() const { { const char filedata[] = "#if defined(AAA)\n" "#endif\n"; ASSERT_EQUALS("#ifdef AAA\n#endif\n", OurPreprocessor::replaceIfDefined(filedata)); } { ASSERT_EQUALS("#elif A\n", OurPreprocessor::replaceIfDefined("#elif defined(A)\n")); } } void if_not_defined() const { const char filedata[] = "#if !defined(AAA)\n" "#endif\n"; ASSERT_EQUALS("#ifndef AAA\n#endif\n", OurPreprocessor::replaceIfDefined(filedata)); } void macro_simple1() const { { const char filedata[] = "#define AAA(aa) f(aa)\n" "AAA(5);\n"; ASSERT_EQUALS("\n$f($5);\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define AAA(aa) f(aa)\n" "AAA (5);\n"; ASSERT_EQUALS("\n$f($5);\n", OurPreprocessor::expandMacros(filedata)); } } void macro_simple2() const { const char filedata[] = "#define min(x,y) x<y?x:y\n" "min(a(),b());\n"; ASSERT_EQUALS("\n$a()<$b()?$a():$b();\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple3() const { const char filedata[] = "#define A 4\n" "A AA\n"; ASSERT_EQUALS("\n$4 AA\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple4() const { const char filedata[] = "#define TEMP_1 if( temp > 0 ) return 1;\n" "TEMP_1\n"; ASSERT_EQUALS("\n$if( $temp > $0 ) $return $1;\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple5() const { const char filedata[] = "#define ABC if( temp > 0 ) return 1;\n" "\n" "void foo()\n" "{\n" " int temp = 0;\n" " ABC\n" "}\n"; ASSERT_EQUALS("\n\nvoid foo()\n{\n int temp = 0;\n $if( $temp > $0 ) $return $1;\n}\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple6() const { const char filedata[] = "#define ABC (a+b+c)\n" "ABC\n"; ASSERT_EQUALS("\n$($a+$b+$c)\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple7() const { const char filedata[] = "#define ABC(str) str\n" "ABC(\"(\")\n"; ASSERT_EQUALS("\n$\"(\"\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple8() const { const char filedata[] = "#define ABC 123\n" "#define ABCD 1234\n" "ABC ABCD\n"; ASSERT_EQUALS("\n\n$123 $1234\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple9() const { const char filedata[] = "#define ABC(a) f(a)\n" "ABC( \"\\\"\" );\n" "ABC( \"g\" );\n"; ASSERT_EQUALS("\n$f(\"\\\"\");\n$f(\"g\");\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple10() const { const char filedata[] = "#define ABC(t) t x\n" "ABC(unsigned long);\n"; ASSERT_EQUALS("\n$unsigned $long $x;\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple11() const { const char filedata[] = "#define ABC(x) delete x\n" "ABC(a);\n"; ASSERT_EQUALS("\n$delete $a;\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple12() const { const char filedata[] = "#define AB ab.AB\n" "AB.CD\n"; ASSERT_EQUALS("\n$ab.$AB.CD\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple13() const { const char filedata[] = "#define TRACE(x)\n" "TRACE(;if(a))\n"; ASSERT_EQUALS("\n$\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple14() const { const char filedata[] = "#define A \" a \"\n" "printf(A);\n"; ASSERT_EQUALS("\nprintf($\" a \");\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple15() const { const char filedata[] = "#define FOO\"foo\"\n" "FOO\n"; ASSERT_EQUALS("\n$\"foo\"\n", OurPreprocessor::expandMacros(filedata)); } void macro_simple16() const { // # 4703 const char filedata[] = "#define MACRO( A, B, C ) class A##B##C##Creator {};\n" "MACRO( B\t, U , G )"; ASSERT_EQUALS("\n$class $BUGCreator{};", OurPreprocessor::expandMacros(filedata)); } void macro_simple17() const { // # 5074 - the Token::isExpandedMacro() doesn't always indicate properly if token comes from macro // It would probably be OK if the generated code was // "\n123+$123" since the first 123 comes from the source code const char filedata[] = "#define MACRO(A) A+123\n" "MACRO(123)"; ASSERT_EQUALS("\n$123+$123", OurPreprocessor::expandMacros(filedata)); } void macro_simple18() const { // (1e-7) const char filedata1[] = "#define A (1e-7)\n" "a=A;"; ASSERT_EQUALS("\na=$($1e-7);", OurPreprocessor::expandMacros(filedata1)); const char filedata2[] = "#define A (1E-7)\n" "a=A;"; ASSERT_EQUALS("\na=$($1E-7);", OurPreprocessor::expandMacros(filedata2)); const char filedata3[] = "#define A (1e+7)\n" "a=A;"; ASSERT_EQUALS("\na=$($1e+7);", OurPreprocessor::expandMacros(filedata3)); const char filedata4[] = "#define A (1.e+7)\n" "a=A;"; ASSERT_EQUALS("\na=$($1.e+7);", OurPreprocessor::expandMacros(filedata4)); const char filedata5[] = "#define A (1.7f)\n" "a=A;"; ASSERT_EQUALS("\na=$($1.7f);", OurPreprocessor::expandMacros(filedata5)); const char filedata6[] = "#define A (.1)\n" "a=A;"; ASSERT_EQUALS("\na=$($.1);", OurPreprocessor::expandMacros(filedata6)); const char filedata7[] = "#define A (1.)\n" "a=A;"; ASSERT_EQUALS("\na=$($1.);", OurPreprocessor::expandMacros(filedata7)); const char filedata8[] = "#define A (8.0E+007)\n" "a=A;"; ASSERT_EQUALS("\na=$($8.0E+007);", OurPreprocessor::expandMacros(filedata8)); } void macroInMacro1() const { { const char filedata[] = "#define A(m) long n = m; n++;\n" "#define B(n) A(n)\n" "B(0)\n"; ASSERT_EQUALS("\n\n$$long $n=$0;$n++;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A B\n" "#define B 3\n" "A\n"; ASSERT_EQUALS("\n\n$$3\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define DBG(fmt, args...) printf(fmt, ## args)\n" "#define D(fmt, args...) DBG(fmt, ## args)\n" "DBG(\"hello\");\n"; ASSERT_EQUALS("\n\n$printf(\"hello\");\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define DBG(fmt, args...) printf(fmt, ## args)\n" "#define D(fmt, args...) DBG(fmt, ## args)\n" "DBG(\"hello: %d\",3);\n"; ASSERT_EQUALS("\n\n$printf(\"hello: %d\",$3);\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define BC(b, c...) 0##b * 0##c\n" "#define ABC(a, b...) a + BC(b)\n" "\n" "ABC(1);\n" "ABC(2,3);\n" "ABC(4,5,6);\n"; ASSERT_EQUALS("\n\n\n$1+$$0*$0;\n$2+$$03*$0;\n$4+$$05*$06;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A 4\n" "#define B(a) a,A\n" "B(2);\n"; ASSERT_EQUALS("\n\n$2, $4;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A(x) (x)\n" "#define B )A(\n" "#define C )A(\n"; ASSERT_EQUALS("\n\n\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A(x) (x*2)\n" "#define B A(\n" "foo B(i));\n"; ASSERT_EQUALS("\n\nfoo $$(($i)*$2);\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define foo foo\n" "foo\n"; ASSERT_EQUALS("\n$foo\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define B(A1, A2) } while (0)\n" "#define A(name) void foo##name() { do { B(1, 2); }\n" "A(0)\n" "A(1)\n"; ASSERT_EQUALS("\n\n$void $foo0(){$do{$$}$while($0);}\n$void $foo1(){$do{$$}$while($0);}\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define B(x) (\n" "#define A() B(xx)\n" "B(1) A() ) )\n"; ASSERT_EQUALS("\n\n$( $$( ) )\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define PTR1 (\n" "#define PTR2 PTR1 PTR1\n" "int PTR2 PTR2 foo )))) = 0;\n"; ASSERT_EQUALS("\n\nint $$( $$( $$( $$( foo )))) = 0;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define PTR1 (\n" "PTR1 PTR1\n"; ASSERT_EQUALS("\n$( $(\n", OurPreprocessor::expandMacros(filedata)); } } void macroInMacro2() const { const char filedata[] = "#define A(x) a##x\n" "#define B 0\n" "A(B)\n"; ASSERT_EQUALS("\n\n$aB\n", OurPreprocessor::expandMacros(filedata)); } void macro_mismatch() const { const char filedata[] = "#define AAA(aa,bb) f(aa)\n" "AAA(5);\n"; ASSERT_EQUALS("\nAAA(5);\n", OurPreprocessor::expandMacros(filedata)); } void macro_linenumbers() const { const char filedata[] = "#define AAA(a)\n" "AAA(5\n" "\n" ")\n" "int a;\n"; ASSERT_EQUALS("\n$" "\n" "\n" "\n" "int a;\n", OurPreprocessor::expandMacros(filedata)); } void macro_nopar() const { const char filedata[] = "#define AAA( ) { NULL }\n" "AAA()\n"; ASSERT_EQUALS("\n${ $NULL }\n", OurPreprocessor::expandMacros(filedata)); } void macro_switchCase() const { { // Make sure "case 2" doesn't become "case2" const char filedata[] = "#define A( b ) " "switch( a ){ " "case 2: " " break; " "}\n" "A( 5 );\n"; ASSERT_EQUALS("\n$switch($a){$case $2:$break;};\n", OurPreprocessor::expandMacros(filedata)); } { // Make sure "2 BB" doesn't become "2BB" const char filedata[] = "#define A() AA : 2 BB\n" "A();\n"; ASSERT_EQUALS("\n$AA : $2 $BB;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A }\n" "#define B() A\n" "#define C( a ) B() break;\n" "{C( 2 );\n"; ASSERT_EQUALS("\n\n\n{$$$}$break;;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A }\n" "#define B() A\n" "#define C( a ) B() _break;\n" "{C( 2 );\n"; ASSERT_EQUALS("\n\n\n{$$$}$_break;;\n", OurPreprocessor::expandMacros(filedata)); } { const char filedata[] = "#define A }\n" "#define B() A\n" "#define C( a ) B() 5;\n" "{C( 2 );\n"; ASSERT_EQUALS("\n\n\n{$$$}$5;;\n", OurPreprocessor::expandMacros(filedata)); } } void macro_NULL() const { // Let the tokenizer handle NULL. // See ticket #4482 - UB when passing NULL to variadic function ASSERT_EQUALS("\n$0", OurPreprocessor::expandMacros("#define null 0\nnull")); ASSERT_EQUALS("\nNULL", OurPreprocessor::expandMacros("#define NULL 0\nNULL")); } void string1() { const char filedata[] = "int main()" "{" " const char *a = \"#define A\n\";" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("int main(){ const char *a = \"#define A\n\";}\n", actual[""]); } void string2() const { const char filedata[] = "#define AAA 123\n" "str = \"AAA\"\n"; // Compare results.. ASSERT_EQUALS("\nstr = \"AAA\"\n", OurPreprocessor::expandMacros(filedata)); } void string3() const { const char filedata[] = "str(\";\");\n"; // Compare results.. ASSERT_EQUALS("str(\";\");\n", OurPreprocessor::expandMacros(filedata)); } void preprocessor_undef() { { const char filedata[] = "#define AAA int a;\n" "#undef AAA\n" "#define AAA char b=0;\n" "AAA\n"; // Compare results.. ASSERT_EQUALS("\n\n\n$char $b=$0;\n", OurPreprocessor::expandMacros(filedata)); } { // ticket #403 const char filedata[] = "#define z p[2]\n" "#undef z\n" "int z;\n" "z = 0;\n"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\nint z;\nz = 0;\n", preprocessor.getcode(filedata, "", "")); } } void defdef() const { const char filedata[] = "#define AAA 123\n" "#define AAA 456\n" "#define AAA 789\n" "AAA\n"; // Compare results.. ASSERT_EQUALS("\n\n\n$789\n", OurPreprocessor::expandMacros(filedata)); } void preprocessor_doublesharp() const { // simple testcase without ## const char filedata1[] = "#define TEST(var,val) var = val\n" "TEST(foo,20);\n"; ASSERT_EQUALS("\n$foo=$20;\n", OurPreprocessor::expandMacros(filedata1)); // simple testcase with ## const char filedata2[] = "#define TEST(var,val) var##_##val = val\n" "TEST(foo,20);\n"; ASSERT_EQUALS("\n$foo_20=$20;\n", OurPreprocessor::expandMacros(filedata2)); // concat macroname const char filedata3[] = "#define ABCD 123\n" "#define A(B) A##B\n" "A(BCD)\n"; ASSERT_EQUALS("\n\n$$123\n", OurPreprocessor::expandMacros(filedata3)); // Ticket #1802 - inner ## must be expanded before outer macro const char filedata4[] = "#define A(B) A##B\n" "#define a(B) A(B)\n" "a(A(B))\n"; ASSERT_EQUALS("\n\n$$AAB\n", OurPreprocessor::expandMacros(filedata4)); // Ticket #1802 - inner ## must be expanded before outer macro const char filedata5[] = "#define AB(A,B) A##B\n" "#define ab(A,B) AB(A,B)\n" "ab(a,AB(b,c))\n"; ASSERT_EQUALS("\n\n$$abc\n", OurPreprocessor::expandMacros(filedata5)); // Ticket #1802 const char filedata6[] = "#define AB_(A,B) A ## B\n" "#define AB(A,B) AB_(A,B)\n" "#define ab(suf) AB(X, AB_(_, suf))\n" "#define X x\n" "ab(y)\n"; ASSERT_EQUALS("\n\n\n\n$$$x_y\n", OurPreprocessor::expandMacros(filedata6)); } void preprocessor_include_in_str() { const char filedata[] = "int main()\n" "{\n" "const char *a = \"#include <string>\n\";\n" "return 0;\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("int main()\n{\nconst char *a = \"#include <string>\n\";\nreturn 0;\n}\n", actual[""]); } void va_args_1() const { const char filedata[] = "#define DBG(fmt...) printf(fmt)\n" "DBG(\"[0x%lx-0x%lx)\", pstart, pend);\n"; // Preprocess.. std::string actual = OurPreprocessor::expandMacros(filedata); ASSERT_EQUALS("\n$printf(\"[0x%lx-0x%lx)\",$pstart,$pend);\n", actual); } void va_args_2() const { const char filedata[] = "#define DBG(fmt, args...) printf(fmt, ## args)\n" "DBG(\"hello\");\n"; // Preprocess.. std::string actual = OurPreprocessor::expandMacros(filedata); ASSERT_EQUALS("\n$printf(\"hello\");\n", actual); } void va_args_3() const { const char filedata[] = "#define FRED(...) { fred(__VA_ARGS__); }\n" "FRED(123)\n"; ASSERT_EQUALS("\n${ $fred($123); }\n", OurPreprocessor::expandMacros(filedata)); } void va_args_4() const { const char filedata[] = "#define FRED(name, ...) name (__VA_ARGS__)\n" "FRED(abc, 123)\n"; ASSERT_EQUALS("\n$abc($123)\n", OurPreprocessor::expandMacros(filedata)); } void multi_character_character() { const char filedata[] = "#define FOO 'ABCD'\n" "int main()\n" "{\n" "if( FOO == 0 );\n" "return 0;\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\nint main()\n{\nif( $'ABCD' == 0 );\nreturn 0;\n}\n", actual[""]); } void stringify() const { const char filedata[] = "#define STRINGIFY(x) #x\n" "STRINGIFY(abc)\n"; // expand macros.. std::string actual = OurPreprocessor::expandMacros(filedata); ASSERT_EQUALS("\n$\"abc\"\n", actual); } void stringify2() const { const char filedata[] = "#define A(x) g(#x)\n" "A(abc);\n"; // expand macros.. std::string actual = OurPreprocessor::expandMacros(filedata); ASSERT_EQUALS("\n$g(\"abc\");\n", actual); } void stringify3() const { const char filedata[] = "#define A(x) g(#x)\n" "A( abc);\n"; // expand macros.. std::string actual = OurPreprocessor::expandMacros(filedata); ASSERT_EQUALS("\n$g(\"abc\");\n", actual); } void stringify4() const { const char filedata[] = "#define A(x) #x\n" "1 A(\n" "abc\n" ") 2\n"; // expand macros.. std::string actual = OurPreprocessor::expandMacros(filedata); ASSERT_EQUALS("\n1 $\n\n\"abc\" 2\n", actual); } void stringify5() const { const char filedata[] = "#define A(x) a(#x,x)\n" "A(foo(\"\\\"\"))\n"; ASSERT_EQUALS("\n$a(\"foo(\\\"\\\\\\\"\\\")\",$foo(\"\\\"\"))\n", OurPreprocessor::expandMacros(filedata)); } void pragma() { const char filedata[] = "#pragma once\n" "void f()\n" "{\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\nvoid f()\n{\n}\n", actual[""]); } void pragma_asm_1() { const char filedata[] = "#pragma asm\n" " mov r1, 11\n" "#pragma endasm\n" "aaa\n" "#pragma asm foo\n" " mov r1, 11\n" "#pragma endasm bar\n" "bbb"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\naaa\n\n\n\nbbb\n", actual[""]); } void pragma_asm_2() { const char filedata[] = "#pragma asm\n" " mov @w1, 11\n" "#pragma endasm ( temp=@w1 )\n" "bbb"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\nasm(temp);\nbbb\n", actual[""]); } void pragma_once() { const char code[] = "#pragma once\n" "int x"; Settings settings; Preprocessor preprocessor(settings, this); const std::list<std::string> includePaths; std::map<std::string,std::string> defs; std::set<std::string> pragmaOnce; preprocessor.handleIncludes(code, "123.h", includePaths, defs, pragmaOnce, std::list<std::string>()); ASSERT_EQUALS(1U, pragmaOnce.size()); ASSERT_EQUALS("123.h", *(pragmaOnce.begin())); } void endifsemicolon() { const char filedata[] = "void f() {\n" "#ifdef A\n" "#endif;\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); const std::string expected("void f() {\n\n\n}\n"); ASSERT_EQUALS(expected, actual[""]); ASSERT_EQUALS(expected, actual["A"]); } void handle_error() { { const char filedata[] = "#define A \n" "#define B don't want to \\\n" "more text\n" "void f()\n" "{\n" " char a = 'a'; // '\n" "}\n"; const char expected[] = "\n" "\n" "\n" "void f()\n" "{\n" "char a = 'a';\n" "}\n"; errout.str(""); // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); ASSERT_EQUALS(expected, actual[""]); ASSERT_EQUALS("", errout.str()); } } void missing_doublequote() { { const char filedata[] = "#define a\n" "#ifdef 1\n" "\"\n" "#endif\n"; // expand macros.. errout.str(""); const std::string actual(OurPreprocessor::expandMacros(filedata, this)); ASSERT_EQUALS("", actual); ASSERT_EQUALS("[file.cpp:3]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout.str()); } { const char filedata[] = "#file \"abc.h\"\n" "#define a\n" "\"\n" "#endfile\n"; // expand macros.. errout.str(""); const std::string actual(OurPreprocessor::expandMacros(filedata, this)); ASSERT_EQUALS("", actual); ASSERT_EQUALS("[abc.h:2]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout.str()); } { const char filedata[] = "#file \"abc.h\"\n" "#define a\n" "#endfile\n" "\"\n"; // expand macros.. errout.str(""); const std::string actual(OurPreprocessor::expandMacros(filedata, this)); ASSERT_EQUALS("", actual); ASSERT_EQUALS("[file.cpp:2]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout.str()); } { const char filedata[] = "#define A 1\n" "#define B \"\n" "int a = A;\n"; // expand macros.. errout.str(""); const std::string actual(OurPreprocessor::expandMacros(filedata, this)); ASSERT_EQUALS("\n\nint a = $1;\n", actual); ASSERT_EQUALS("", errout.str()); } { const char filedata[] = "void foo()\n" "{\n" "\n" "\n" "\n" "int a = 0;\n" "printf(Text\");\n" "}\n"; // expand macros.. errout.str(""); OurPreprocessor::expandMacros(filedata, this); ASSERT_EQUALS("[file.cpp:7]: (error) No pair for character (\"). Can't process file. File is either invalid or unicode, which is currently not supported.\n", errout.str()); } } void unicodeInCode() { const std::string filedata("a\xC8"); std::istringstream istr(filedata); errout.str(""); Settings settings; Preprocessor preprocessor(settings, this); preprocessor.read(istr, "test.cpp"); ASSERT_EQUALS("[test.cpp:1]: (error) The code contains unhandled characters (character code = 0xc8). Checking continues, but do not expect valid results.\n", errout.str()); } void unicodeInComment() { const std::string filedata("//\xC8"); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("", preprocessor.read(istr, "test.cpp")); } void unicodeInString() { const std::string filedata("\"\xC8\""); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS(filedata, preprocessor.read(istr, "test.cpp")); } void define_part_of_func() { errout.str(""); const char filedata[] = "#define A g(\n" "void f() {\n" " A );\n" " }\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\nvoid f() {\n$g( );\n}\n", actual[""]); ASSERT_EQUALS("", errout.str()); } void conditionalDefine() { const char filedata[] = "#ifdef A\n" "#define N 10\n" "#else\n" "#define N 20\n" "#endif\n" "N"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\n\n\n\n$20\n", actual[""]); ASSERT_EQUALS("\n\n\n\n\n$10\n", actual["A"]); ASSERT_EQUALS("", errout.str()); } void multiline_comment() { errout.str(""); const char filedata[] = "#define ABC {// \\\n" "}\n" "void f() ABC }\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\n\nvoid f() ${ }\n", actual[""]); ASSERT_EQUALS("", errout.str()); } void macro_parameters() { errout.str(""); const char filedata[] = "#define BC(a, b, c, arg...) \\\n" "AB(a, b, c, ## arg)\n" "\n" "void f()\n" "{\n" " BC(3);\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c", std::list<std::string>()); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("", actual[""]); ASSERT_EQUALS("[file.c:6]: (error) Syntax error. Not enough parameters for macro 'BC'.\n", errout.str()); } void newline_in_macro() { errout.str(""); const char filedata[] = "#define ABC(str) printf( str )\n" "void f()\n" "{\n" " ABC(\"\\n\");\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c", std::list<std::string>()); // Compare results.. ASSERT_EQUALS(1, static_cast<unsigned int>(actual.size())); ASSERT_EQUALS("\nvoid f()\n{\n$printf(\"\\n\");\n}\n", actual[""]); ASSERT_EQUALS("", errout.str()); } void includes() const { { std::string src = "#include a.h"; ASSERT_EQUALS(OurPreprocessor::NoHeader, OurPreprocessor::getHeaderFileName(src)); ASSERT_EQUALS("", src); } { std::string src = "#include \"b.h\""; ASSERT_EQUALS(OurPreprocessor::UserHeader, OurPreprocessor::getHeaderFileName(src)); ASSERT_EQUALS("b.h", src); } { std::string src = "#include <c.h>"; ASSERT_EQUALS(OurPreprocessor::SystemHeader, OurPreprocessor::getHeaderFileName(src)); ASSERT_EQUALS("c.h", src); } { std::string src = "#include \"d/d.h\""; ASSERT_EQUALS(OurPreprocessor::UserHeader, OurPreprocessor::getHeaderFileName(src)); ASSERT_EQUALS("d/d.h", src); } { std::string src = "#include \"e\\e.h\""; ASSERT_EQUALS(OurPreprocessor::UserHeader, OurPreprocessor::getHeaderFileName(src)); ASSERT_EQUALS("e/e.h", src); } } void ifdef_ifdefined() { const char filedata[] = "#ifdef ABC\n" "A\n" "#endif\t\n" "#if defined ABC\n" "A\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n\n\n", actual[""]); ASSERT_EQUALS("\nA\n\n\nA\n\n", actual["ABC"]); ASSERT_EQUALS(2, static_cast<unsigned int>(actual.size())); } void define_if1() { Settings settings; Preprocessor preprocessor(settings, this); { const char filedata[] = "#define A 0\n" "#if A\n" "FOO\n" "#endif"; ASSERT_EQUALS("\n\n\n\n", preprocessor.getcode(filedata,"","")); } { const char filedata[] = "#define A 1\n" "#if A==1\n" "FOO\n" "#endif"; ASSERT_EQUALS("\n\nFOO\n\n", preprocessor.getcode(filedata,"","")); } } void define_if2() { const char filedata[] = "#define A 22\n" "#define B A\n" "#if (B==A) || (B==C)\n" "FOO\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\nFOO\n\n", preprocessor.getcode(filedata,"","")); } void define_if3() { const char filedata[] = "#define A 0\n" "#if (A==0)\n" "FOO\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\nFOO\n\n", preprocessor.getcode(filedata,"","")); } void define_if4() { const char filedata[] = "#define X +123\n" "#if X==123\n" "FOO\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\nFOO\n\n", preprocessor.getcode(filedata,"","")); } void define_if5() { // #4516 - #define B (A & 0x00f0) { const char filedata[] = "#define A 0x0010\n" "#define B (A & 0x00f0)\n" "#if B==0x0010\n" "FOO\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\nFOO\n\n", preprocessor.getcode(filedata,"","")); } { const char filedata[] = "#define A 0x00f0\n" "#define B (16)\n" "#define C (B & A)\n" "#if C==0x0010\n" "FOO\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\n\nFOO\n\n", preprocessor.getcode(filedata,"","")); } { const char filedata[] = "#define A (1+A)\n" // don't hang for recursive macros "#if A==1\n" "FOO\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\n\n", preprocessor.getcode(filedata,"","")); } } void define_if6() { // #4516 - #define B (A?1:-1) const char filedata[] = "#ifdef A\n" "#define B (A?1:-1)\n" "#endif\n" "\n" "#if B < 0\n" "123\n" "#endif\n" "\n" "#if B >= 0\n" "456\n" "#endif\n"; Settings settings; Preprocessor preprocessor(settings, this); const std::string actualA0 = preprocessor.getcode(filedata, "A=0", "test.c"); ASSERT_EQUALS(true, actualA0.find("123") != std::string::npos); ASSERT_EQUALS(false, actualA0.find("456") != std::string::npos); const std::string actualA1 = preprocessor.getcode(filedata, "A=1", "test.c"); ASSERT_EQUALS(false, actualA1.find("123") != std::string::npos); ASSERT_EQUALS(true, actualA1.find("456") != std::string::npos); } void define_ifdef() { { const char filedata[] = "#define ABC\n" "#ifndef ABC\n" "A\n" "#else\n" "B\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\nB\n\n", actual[""]); ASSERT_EQUALS(1, (int)actual.size()); } { const char filedata[] = "#define A 1\n" "#ifdef A\n" "A\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n$1\n\n", actual[""]); ASSERT_EQUALS(1, (int)actual.size()); } { const char filedata[] = "#define A 1\n" "#if A==1\n" "A\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n$1\n\n", actual[""]); ASSERT_EQUALS(1, (int)actual.size()); } { const char filedata[] = "#define A 1\n" "#if A>0\n" "A\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n$1\n\n", actual[""]); ASSERT_EQUALS(1, (int)actual.size()); } { const char filedata[] = "#define A 1\n" "#if 0\n" "#undef A\n" "#endif\n" "A\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n$1\n", actual[""]); ASSERT_EQUALS(1, (int)actual.size()); } } void define_ifndef1() { const char filedata[] = "#define A(x) (x)\n" "#ifndef A\n" ";\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("\n\n\n\n", actual[""]); ASSERT_EQUALS(1U, actual.size()); } void define_ifndef2() { const char filedata[] = "#ifdef A\n" "#define B char\n" "#endif\n" "#ifndef B\n" "#define B int\n" "#endif\n" "B me;\n"; // Preprocess => actual result.. Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\n\n\n\n$int me;\n", preprocessor.getcode(filedata, "", "a.cpp")); ASSERT_EQUALS("\n\n\n\n\n\n$char me;\n", preprocessor.getcode(filedata, "A", "a.cpp")); } void ifndef_define() { const char filedata[] = "#ifndef A\n" "#define A(x) x\n" "#endif\n" "A(123);"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\n\n$123;\n", actual[""]); } void undef_ifdef() { const char filedata[] = "#undef A\n" "#ifdef A\n" "123\n" "#endif\n"; // Preprocess => actual result.. Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\n\n\n\n", preprocessor.getcode(filedata, "", "a.cpp")); ASSERT_EQUALS("\n\n\n\n", preprocessor.getcode(filedata, "A", "a.cpp")); } void redundant_config() { const char filedata[] = "int main() {\n" "#ifdef FOO\n" "#ifdef BAR\n" " std::cout << 1;\n" "#endif\n" "#endif\n" "\n" "#ifdef BAR\n" "#ifdef FOO\n" " std::cout << 2;\n" "#endif\n" "#endif\n" "}\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(4, (int)actual.size()); ASSERT(actual.find("") != actual.end()); ASSERT(actual.find("BAR") != actual.end()); ASSERT(actual.find("FOO") != actual.end()); ASSERT(actual.find("BAR;FOO") != actual.end()); } void endfile() { const char filedata[] = "char a[] = \"#endfile\";\n" "char b[] = \"#endfile\";\n" "#include \"notfound.h\"\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("char a[] = \"#endfile\";\nchar b[] = \"#endfile\";\n\n", actual[""]); ASSERT_EQUALS(1, (int)actual.size()); } void dup_defines() { const char filedata[] = "#ifdef A\n" "#define B\n" "#if defined(B) && defined(A)\n" "a\n" "#else\n" "b\n" "#endif\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // B will always be defined if A is defined; the following test // cases should be fixed whenever this other bug is fixed TODO_ASSERT_EQUALS(2, 3, static_cast<unsigned int>(actual.size())); if (actual.find("A") == actual.end()) { ASSERT_EQUALS("A is checked", "failed"); } else { ASSERT_EQUALS("A is checked", "A is checked"); } if (actual.find("A;A;B") != actual.end()) { ASSERT_EQUALS("A;A;B is NOT checked", "failed"); } else { ASSERT_EQUALS("A;A;B is NOT checked", "A;A;B is NOT checked"); } } void testPreprocessorRead1() { const std::string filedata("/*\n*/ # /*\n*/ defi\\\nne FO\\\nO 10\\\n20"); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#define FOO 1020", preprocessor.read(istr, "test.cpp")); } void testPreprocessorRead2() { const std::string filedata("\"foo\\\\\nbar\""); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("\"foo\\bar\"", preprocessor.read(istr, "test.cpp")); } void testPreprocessorRead3() { const std::string filedata("#define A \" a \"\n\" b\""); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS(filedata, preprocessor.read(istr, "test.cpp")); } void testPreprocessorRead4() { { // test < \\> < > (unescaped) const std::string filedata("#define A \" \\\\\"/*space*/ \" \""); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#define A \" \\\\\" \" \"", preprocessor.read(istr, "test.cpp")); } { // test <" \\\" "> (unescaped) const std::string filedata("#define A \" \\\\\\\" \""); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#define A \" \\\\\\\" \"", preprocessor.read(istr, "test.cpp")); } { // test <" \\\\"> <" "> (unescaped) const std::string filedata("#define A \" \\\\\\\\\"/*space*/ \" \""); std::istringstream istr(filedata); Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS("#define A \" \\\\\\\\\" \" \"", preprocessor.read(istr, "test.cpp")); } } void invalid_define_1() { Settings settings; Preprocessor preprocessor(settings, this); std::istringstream src("#define =\n"); std::string processedFile; std::list<std::string> cfg; std::list<std::string> paths; preprocessor.preprocess(src, processedFile, cfg, "", paths); // don't hang } void invalid_define_2() { // #4036 - hang Settings settings; Preprocessor preprocessor(settings, this); std::istringstream src("#define () {(int f(x) }\n"); std::string processedFile; std::list<std::string> cfg; std::list<std::string> paths; preprocessor.preprocess(src, processedFile, cfg, "", paths); // don't hang } void missingInclude() { Settings settings; Preprocessor preprocessor(settings, this); Preprocessor::missingIncludeFlag = false; std::istringstream src("#include \"missing.h\"\n"); std::string processedFile; std::list<std::string> cfg; std::list<std::string> paths; ASSERT_EQUALS(false, Preprocessor::missingIncludeFlag); preprocessor.preprocess(src, processedFile, cfg, "test.c", paths); ASSERT_EQUALS(true, Preprocessor::missingIncludeFlag); } void inline_suppression_for_missing_include() { Preprocessor::missingIncludeFlag = false; Settings settings; settings._inlineSuppressions = true; settings.addEnabled("all"); Preprocessor preprocessor(settings, this); std::istringstream src("// cppcheck-suppress missingInclude\n" "#include \"missing.h\"\n" "int x;"); std::string processedFile; std::list<std::string> cfg; std::list<std::string> paths; // Don't report that the include is missing errout.str(""); preprocessor.preprocess(src, processedFile, cfg, "test.c", paths); ASSERT_EQUALS("", errout.str()); ASSERT_EQUALS(false, Preprocessor::missingIncludeFlag); } void predefine1() { const std::string src("#if defined X || Y\n" "Fred & Wilma\n" "#endif\n"); Settings settings; Preprocessor preprocessor(settings, this); std::string actual = preprocessor.getcode(src, "X=1", "test.c"); ASSERT_EQUALS("\nFred & Wilma\n\n", actual); } void predefine2() { const std::string src("#if defined(X) && Y\n" "Fred & Wilma\n" "#endif\n"); { Settings settings; Preprocessor preprocessor(settings, this); std::string actual = preprocessor.getcode(src, "X=1", "test.c"); ASSERT_EQUALS("\n\n\n", actual); } { Settings settings; Preprocessor preprocessor(settings, this); std::string actual = preprocessor.getcode(src, "X=1;Y=2", "test.c"); ASSERT_EQUALS("\nFred & Wilma\n\n", actual); } } void predefine3() { // #2871 - define in source is not used if -D is used const char code[] = "#define X 1\n" "#define Y X\n" "#if (X == Y)\n" "Fred & Wilma\n" "#endif\n"; Settings settings; Preprocessor preprocessor(settings,this); const std::string actual = preprocessor.getcode(code, "TEST", "test.c"); ASSERT_EQUALS("\n\n\nFred & Wilma\n\n", actual); } void predefine4() { // #3577 const char code[] = "char buf[X];\n"; Settings settings; Preprocessor preprocessor(settings,this); const std::string actual = preprocessor.getcode(code, "X=123", "test.c"); ASSERT_EQUALS("char buf[$123];\n", actual); } void predefine5() { // #3737, #5119 - automatically define __cplusplus // #3737... const char code[] = "#ifdef __cplusplus\n123\n#endif"; Settings settings; Preprocessor preprocessor(settings,this); ASSERT_EQUALS("\n\n\n", preprocessor.getcode(code, "X=123", "test.c")); ASSERT_EQUALS("\n123\n\n", preprocessor.getcode(code, "X=123", "test.cpp")); // #5119... ASSERT_EQUALS(false, Preprocessor::cplusplus(nullptr,"test.c")); ASSERT_EQUALS(true, Preprocessor::cplusplus(nullptr,"test.cpp")); ASSERT_EQUALS(true, Preprocessor::cplusplus(&settings,"test.cpp")); settings.userUndefs.insert("__cplusplus"); ASSERT_EQUALS(false, Preprocessor::cplusplus(&settings,"test.cpp")); } void predefine6() { // #3737 - using -D and -f => check all matching configurations const char filedata[] = "#ifdef A\n" "1\n" "#else\n" "2\n" "#endif\n" "#ifdef B\n" "3\n" "#else\n" "4\n" "#endif"; // actual result.. Settings settings; Preprocessor preprocessor(settings, this); std::map<std::string, std::string> defs; defs["A"] = "1"; const std::list<std::string> configs = preprocessor.getcfgs(filedata, "test1.c", defs); // Compare actual result with expected result.. ASSERT_EQUALS(2U, configs.size()); ASSERT_EQUALS("", configs.front()); ASSERT_EQUALS("B", configs.back()); } void simplifyCondition() { // Ticket #2794 std::map<std::string, std::string> cfg; cfg["C"] = ""; std::string condition("defined(A) || defined(B) || defined(C)"); Settings settings; Preprocessor preprocessor(settings, this); preprocessor.simplifyCondition(cfg, condition, true); ASSERT_EQUALS("1", condition); } void invalidElIf() { // #2942 - segfault const char code[] = "#elif (){\n"; Settings settings; Preprocessor preprocessor(settings,this); const std::string actual = preprocessor.getcode(code, "TEST", "test.c"); ASSERT_EQUALS("\n", actual); } void def_handleIncludes() { const std::string filePath("test.c"); const std::list<std::string> includePaths; std::map<std::string,std::string> defs; Settings settings; Preprocessor preprocessor(settings, this); // ifdef { defs.clear(); defs["A"] = ""; { std::set<std::string> pragmaOnce; const std::string code("#ifdef A\n123\n#endif\n"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n123\n\n", actual); }{ std::set<std::string> pragmaOnce; const std::string code("#ifdef B\n123\n#endif\n"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n\n\n", actual); } } // ifndef { defs.clear(); defs["A"] = ""; { std::set<std::string> pragmaOnce; const std::string code("#ifndef A\n123\n#endif\n"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n\n\n", actual); }{ std::set<std::string> pragmaOnce; const std::string code("#ifndef B\n123\n#endif\n"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n123\n\n", actual); } } // define - ifndef { std::set<std::string> pragmaOnce; defs.clear(); const std::string code("#ifndef X\n#define X\n123\n#endif\n" "#ifndef X\n#define X\n123\n#endif\n"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n#define X\n123\n\n" "\n\n\n\n", actual); } // #define => #if { std::set<std::string> pragmaOnce; defs.clear(); const std::string code("#define X 123\n" "#if X==123\n" "456\n" "#endif\n"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("#define X 123\n\n456\n\n", actual); } // #elif { const std::string code("#if defined(A)\n" "1\n" "#elif defined(B)\n" "2\n" "#elif defined(C)\n" "3\n" "#else\n" "4\n" "#endif"); { std::set<std::string> pragmaOnce; defs.clear(); defs["A"] = ""; defs["C"] = ""; const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n1\n\n\n\n\n\n\n\n", actual); } { std::set<std::string> pragmaOnce; defs.clear(); defs["B"] = ""; const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n\n\n2\n\n\n\n\n\n", actual); } { std::set<std::string> pragmaOnce; defs.clear(); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n\n\n\n\n\n\n4\n\n", actual); } } // #endif { // see also endifsemicolon const std::string code("{\n#ifdef X\n#endif;\n}"); std::set<std::string> pragmaOnce; defs.clear(); defs["Z"] = ""; const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("{\n\n\n}\n", actual); } // #undef { const std::string code("#ifndef X\n" "#define X\n" "123\n" "#endif\n"); std::set<std::string> pragmaOnce; pragmaOnce.clear(); defs.clear(); const std::string actual1(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); pragmaOnce.clear(); defs.clear(); const std::string actual(preprocessor.handleIncludes(code + "#undef X\n" + code, filePath, includePaths, defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS(actual1 + "#undef X\n" + actual1, actual); } // #error { errout.str(""); std::set<std::string> pragmaOnce; defs.clear(); const std::string code("#ifndef X\n#error abc\n#endif"); const std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("\n#error abc\n\n", actual); } } void def_missingInclude() { const std::list<std::string> includePaths; std::map<std::string,std::string> defs; defs["AA"] = ""; Settings settings; Preprocessor preprocessor(settings,this); // missing local include { const std::string code("#include \"missing-include!!.h\"\n"); std::set<std::string> pragmaOnce; pragmaOnce.clear(); errout.str(""); settings = Settings(); preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("", errout.str()); pragmaOnce.clear(); errout.str(""); settings.checkConfiguration = true; preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("[test.c:1]: (information) Include file: \"missing-include!!.h\" not found.\n", errout.str()); pragmaOnce.clear(); errout.str(""); settings.nomsg.addSuppression("missingInclude"); preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("", errout.str()); } // missing system header { const std::string code("#include <missing-include!!.h>\n"); std::set<std::string> pragmaOnce; pragmaOnce.clear(); errout.str(""); settings = Settings(); preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("", errout.str()); pragmaOnce.clear(); errout.str(""); settings.checkConfiguration = true; preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("[test.c:1]: (information) Include file: <missing-include!!.h> not found. Please note: Cppcheck does not need standard library headers to get proper results.\n", errout.str()); pragmaOnce.clear(); errout.str(""); settings.nomsg.addSuppression("missingIncludeSystem"); preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("", errout.str()); pragmaOnce.clear(); errout.str(""); settings = Settings(); settings.nomsg.addSuppression("missingInclude"); preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("", errout.str()); } // #3285 - #elif { const std::string code("#ifdef GNU\n" "#elif defined(WIN32)\n" "#include \"missing-include!!.h\"\n" "#endif"); defs.clear(); defs["GNU"] = ""; std::set<std::string> pragmaOnce; errout.str(""); settings = Settings(); preprocessor.handleIncludes(code,"test.c",includePaths,defs,pragmaOnce,std::list<std::string>()); ASSERT_EQUALS("", errout.str()); } } void def_handleIncludes_ifelse1() { const std::string filePath("test.c"); const std::list<std::string> includePaths; std::map<std::string,std::string> defs; Settings settings; Preprocessor preprocessor(settings, this); // #3405 { std::set<std::string> pragmaOnce; defs.clear(); defs["A"] = ""; const std::string code("\n#ifndef PAL_UTIL_UTILS_H_\n" "#define PAL_UTIL_UTILS_H_\n" "1\n" "#ifndef USE_BOOST\n" "2\n" "#else\n" "3\n" "#endif\n" "4\n" "#endif\n" "\n" "#ifndef PAL_UTIL_UTILS_H_\n" "#define PAL_UTIL_UTILS_H_\n" "5\n" "#ifndef USE_BOOST\n" "6\n" "#else\n" "7\n" "#endif\n" "8\n" "#endif\n" "\n"); std::string actual(preprocessor.handleIncludes(code,filePath,includePaths,defs,pragmaOnce,std::list<std::string>())); // the 1,2,4 should be in the result actual.erase(0, actual.find('1')); while (actual.find('\n') != std::string::npos) actual.erase(actual.find('\n'), 1); ASSERT_EQUALS("124", actual); } // #3418 { std::set<std::string> pragmaOnce; defs.clear(); const char code[] = "#define A 1\n" "#define B A\n" "#if A == B\n" "123\n" "#endif\n"; std::string actual(preprocessor.handleIncludes(code, filePath, includePaths, defs,pragmaOnce,std::list<std::string>())); ASSERT_EQUALS("#define A 1\n#define B A\n\n123\n\n", actual); } } void def_handleIncludes_ifelse2() { // #3651 const char code[] = "#if defined(A)\n" "\n" "#if defined(B)\n" "#endif\n" "\n" "#elif defined(C)\n" "\n" "#else\n" "\n" "123\n" "\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); const std::list<std::string> includePaths; std::map<std::string,std::string> defs; defs["A"] = "1"; std::set<std::string> pragmaOnce; ASSERT_EQUALS(std::string::npos, // No "123" in the output preprocessor.handleIncludes(code, "test.c", includePaths, defs, pragmaOnce,std::list<std::string>()).find("123")); } void def_handleIncludes_ifelse3() { // #4865 const char code[] = "#ifdef A\n" "#if defined(SOMETHING_NOT_DEFINED)\n" "#else\n" "#endif\n" "#else\n" "#endif"; Settings settings; settings.userUndefs.insert("A"); Preprocessor preprocessor(settings, this); const std::list<std::string> includePaths; std::map<std::string,std::string> defs; defs["B"] = "1"; defs["C"] = "1"; std::set<std::string> pragmaOnce; preprocessor.handleIncludes(code, "test.c", includePaths, defs, pragmaOnce, std::list<std::string>()); // don't crash } void def_valueWithParentheses() { // #define should introduce a new symbol regardless of parentheses in the value // and regardless of white space in weird places (people do this for some reason). const char code[] = "#define A (Fred)\n" " # define B (Flintstone)\n" " #define C (Barney)\n" "\t#\tdefine\tD\t(Rubble)\t\t\t\n"; const std::string filePath("test.c"); const std::list<std::string> includePaths; std::map<std::string,std::string> defs; std::set<std::string> pragmaOnce; Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); const std::string s(preprocessor.read(istr, "")); preprocessor.handleIncludes(s, filePath, includePaths, defs, pragmaOnce, std::list<std::string>()); ASSERT(defs.find("A") != defs.end()); ASSERT_EQUALS("(Fred)", defs["A"]); ASSERT(defs.find("B") != defs.end()); ASSERT_EQUALS("(Flintstone)", defs["B"]); ASSERT(defs.find("C") != defs.end()); ASSERT_EQUALS("(Barney)", defs["C"]); ASSERT(defs.find("D") != defs.end()); ASSERT_EQUALS("(Rubble)", defs["D"]); } void undef1() { Settings settings; const char filedata[] = "#ifdef X\n" "Fred & Wilma\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\n\n", actual[""]); } void undef2() { Settings settings; const char filedata[] = "#ifndef X\n" "Fred & Wilma\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\nFred & Wilma\n\n", actual[""]); } void undef3() { Settings settings; const char filedata[] = "#define X\n" "#ifdef X\n" "Fred & Wilma\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\n\n\n", actual[""]); } void undef4() { Settings settings; const char filedata[] = "#define X Y\n" "#ifdef X\n" "Fred & Wilma\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\n\n\n", actual[""]); } void undef5() { Settings settings; const char filedata[] = "#define X() Y\n" "#ifdef X\n" "Fred & Wilma\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\n\n\n", actual[""]); } void undef6() { Settings settings; const char filedata[] = "#define X Y\n" "#ifdef X\n" "Fred & Wilma\n" "#else\n" "Barney & Betty\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\n\n\nBarney & Betty\n\n", actual[""]); } void undef7() { Settings settings; const char filedata[] = "#define X XDefined\n" "X;\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); TODO_ASSERT_EQUALS("\n;\n","\n$XDefined;\n", actual[""]); } void undef8() { Settings settings; const char filedata[] = "#ifdef HAVE_CONFIG_H\n" "#include \"config.h\"\n" "#endif\n" "\n" "void foo();\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines settings.checkConfiguration = true; errout.str(""); Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS("[file.c:2]: (information) Include file: \"config.h\" not found.\n", errout.str()); ASSERT_EQUALS("\n\n\n\n\n", actual[""]); } void undef9() { Settings settings; const char filedata[] = "#define X Y\n" "#ifndef X\n" "Fred & Wilma\n" "#else\n" "Barney & Betty\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); // Compare results.. ASSERT_EQUALS(1U, actual.size()); ASSERT_EQUALS("\n\nFred & Wilma\n\n\n\n", actual[""]); } void undef10() { Settings settings; const char filedata[] = "#ifndef X\n" "#endif\n" "#ifndef Y\n" "#endif\n"; // Preprocess => actual result.. std::istringstream istr(filedata); settings.userUndefs.insert("X"); // User undefs should override internal defines Preprocessor preprocessor(settings, this); std::string processedFile; std::list<std::string> resultConfigurations; const std::list<std::string> includePaths; preprocessor.preprocess(istr, processedFile, resultConfigurations, "file.c", includePaths); // Compare results. Two configurations "" and "Y". No "X". ASSERT_EQUALS(2U, resultConfigurations.size()); ASSERT_EQUALS("", resultConfigurations.front()); ASSERT_EQUALS("Y", resultConfigurations.back()); } void handleUndef() { Settings settings; settings.userUndefs.insert("X"); const Preprocessor preprocessor(settings, this); std::list<std::string> configurations; // configurations to keep configurations.clear(); configurations.push_back("XY;"); configurations.push_back("AX;"); configurations.push_back("A;XY"); preprocessor.handleUndef(configurations); ASSERT_EQUALS(3U, configurations.size()); // configurations to remove configurations.clear(); configurations.push_back("X;Y"); configurations.push_back("X=1;Y"); configurations.push_back("A;X;B"); configurations.push_back("A;X=1;B"); configurations.push_back("A;X"); configurations.push_back("A;X=1"); preprocessor.handleUndef(configurations); ASSERT_EQUALS(0U, configurations.size()); } void macroChar() const { const char filedata[] = "#define X 1\nX\n"; ASSERT_EQUALS("\n$1\n", OurPreprocessor::expandMacros(filedata,nullptr)); OurPreprocessor::macroChar = char(1); ASSERT_EQUALS("\n" + std::string(char(1),1U) + "1\n", OurPreprocessor::expandMacros(filedata,nullptr)); OurPreprocessor::macroChar = '$'; } void validateCfg() { Settings settings; Preprocessor preprocessor(settings, this); ASSERT_EQUALS(true, preprocessor.validateCfg("", "X=42")); // don't hang when parsing cfg ASSERT_EQUALS(false, preprocessor.validateCfg("int y=Y;", "X=42;Y")); ASSERT_EQUALS(false, preprocessor.validateCfg("int x=X;", "X")); ASSERT_EQUALS(false, preprocessor.validateCfg("X=1;", "X")); ASSERT_EQUALS(true, preprocessor.validateCfg("int x=X;", "Y")); ASSERT_EQUALS(true, preprocessor.validateCfg("FOO_DEBUG()", "DEBUG")); ASSERT_EQUALS(true, preprocessor.validateCfg("\"DEBUG()\"", "DEBUG")); ASSERT_EQUALS(true, preprocessor.validateCfg("\"\\\"DEBUG()\"", "DEBUG")); ASSERT_EQUALS(false, preprocessor.validateCfg("\"DEBUG()\" DEBUG", "DEBUG")); ASSERT_EQUALS(true, preprocessor.validateCfg("#undef DEBUG", "DEBUG")); // #4301: // #ifdef A // int a = A; // <- using macro. must use -D so "A" will get a proper value errout.str(""); settings.addEnabled("all"); preprocessor.setFile0("test.c"); ASSERT_EQUALS(false, preprocessor.validateCfg("int a=A;", "A")); ASSERT_EQUALS("[test.c:1]: (information) Skipping configuration 'A' since the value of 'A' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.\n", errout.str()); // #4949: // #ifdef A // a |= A; // <- using macro. must use -D so "A" will get a proper value errout.str(""); Settings settings1; settings = settings1; ASSERT_EQUALS("", preprocessor.getcode("if (x) a|=A;", "A", "test.c")); ASSERT_EQUALS("", errout.str()); settings.addEnabled("information"); ASSERT_EQUALS("", preprocessor.getcode("if (x) a|=A;", "A", "test.c")); ASSERT_EQUALS("[test.c:1]: (information) Skipping configuration 'A' since the value of 'A' is unknown. Use -D if you want to check it. You can use -U to skip it explicitly.\n", errout.str()); } void if_sizeof() { // #4071 static const char* code = "#if sizeof(unsigned short) == 2\n" "Fred & Wilma\n" "#elif sizeof(unsigned short) == 4\n" "Fred & Wilma\n" "#else\n" "#endif"; Settings settings; Preprocessor preprocessor(settings, this); std::istringstream istr(code); std::map<std::string, std::string> actual; preprocessor.preprocess(istr, actual, "file.c"); ASSERT_EQUALS("\nFred & Wilma\n\n\n\n\n", actual[""]); } void double_include() { const char code[] = "int x"; Settings settings; Preprocessor preprocessor(settings, this); std::list<std::string> includePaths; includePaths.push_back("."); includePaths.push_back("."); std::map<std::string,std::string> defs; std::set<std::string> pragmaOnce; preprocessor.handleIncludes(code, "123.h", includePaths, defs, pragmaOnce, std::list<std::string>()); } void invalid_ifs() { const char filedata[] = "#ifdef\n" "#endif\n" "#ifdef !\n" "#endif\n" "#if defined\n" "#endif\n" "#define f(x) x\n" "#if f(2\n" "#endif\n" "int x;\n"; // Preprocess => don't crash.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); } void garbage() { const char filedata[] = "V\n" "#define X b #endif #line 0 \"x\" ;\n" "#if ! defined ( Y ) #endif"; // Preprocess => don't crash.. std::istringstream istr(filedata); std::map<std::string, std::string> actual; Settings settings; Preprocessor preprocessor(settings, this); preprocessor.preprocess(istr, actual, "file.c"); } }; REGISTER_TEST(TestPreprocessor)
gpl-3.0
yGO77/betaflight
src/main/telemetry/srxl.c
6
7209
/* * This file is part of Cleanflight. * * Cleanflight 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. * * Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>. */ #include <stdbool.h> #include <stdint.h> #include <string.h> #include "platform.h" #ifdef TELEMETRY #include "config/feature.h" #include "build/version.h" #include "common/streambuf.h" #include "common/utils.h" #include "sensors/battery.h" #include "io/gps.h" #include "io/serial.h" #include "fc/rc_controls.h" #include "fc/runtime_config.h" #include "io/gps.h" #include "flight/imu.h" #include "rx/rx.h" #include "rx/spektrum.h" #include "telemetry/telemetry.h" #include "telemetry/srxl.h" #include "fc/config.h" #define SRXL_CYCLETIME_US 100000 // 100ms, 10 Hz #define SRXL_ADDRESS_FIRST 0xA5 #define SRXL_ADDRESS_SECOND 0x80 #define SRXL_PACKET_LENGTH 0x15 #define SRXL_FRAMETYPE_TELE_QOS 0x7F #define SRXL_FRAMETYPE_TELE_RPM 0x7E #define SRXL_FRAMETYPE_POWERBOX 0x0A #define SRXL_FRAMETYPE_SID 0x00 static bool srxlTelemetryEnabled; static uint16_t srxlCrc; static uint8_t srxlFrame[SRXL_FRAME_SIZE_MAX]; #define SRXL_POLY 0x1021 static uint16_t srxlCrc16(uint16_t crc, uint8_t data) { crc = crc ^ data << 8; for (int i = 0; i < 8; i++) { if (crc & 0x8000) { crc = crc << 1 ^ SRXL_POLY; } else { crc = crc << 1; } } return crc; } static void srxlInitializeFrame(sbuf_t *dst) { srxlCrc = 0; dst->ptr = srxlFrame; dst->end = ARRAYEND(srxlFrame); sbufWriteU8(dst, SRXL_ADDRESS_FIRST); sbufWriteU8(dst, SRXL_ADDRESS_SECOND); sbufWriteU8(dst, SRXL_PACKET_LENGTH); } static void srxlSerialize8(sbuf_t *dst, uint8_t v) { sbufWriteU8(dst, v); srxlCrc = srxlCrc16(srxlCrc, v); } static void srxlSerialize16(sbuf_t *dst, uint16_t v) { // Use BigEndian format srxlSerialize8(dst, (v >> 8)); srxlSerialize8(dst, (uint8_t)v); } static void srxlFinalize(sbuf_t *dst) { sbufWriteU16(dst, srxlCrc); sbufSwitchToReader(dst, srxlFrame); // write the telemetry frame to the receiver. srxlRxWriteTelemetryData(sbufPtr(dst), sbufBytesRemaining(dst)); } /* SRXL frame has the structure: <0xA5><0x80><Length><16-byte telemetry packet><2 Byte CRC of payload> The <Length> shall be 0x15 (length of the 16-byte telemetry packet + overhead). */ /* typedef struct { UINT8 identifier; // Source device = 0x7F UINT8 sID; // Secondary ID UINT16 A; UINT16 B; UINT16 L; UINT16 R; UINT16 F; UINT16 H; UINT16 rxVoltage; // Volts, 0.01V increments } STRU_TELE_QOS; */ void srxlFrameQos(sbuf_t *dst) { srxlSerialize8(dst, SRXL_FRAMETYPE_TELE_QOS); srxlSerialize8(dst, SRXL_FRAMETYPE_SID); srxlSerialize16(dst, 0xFFFF); // A srxlSerialize16(dst, 0xFFFF); // B srxlSerialize16(dst, 0xFFFF); // L srxlSerialize16(dst, 0xFFFF); // R srxlSerialize16(dst, 0xFFFF); // F srxlSerialize16(dst, 0xFFFF); // H srxlSerialize16(dst, 0xFFFF); // rxVoltage } /* typedef struct { UINT8 identifier; // Source device = 0x7E UINT8 sID; // Secondary ID UINT16 microseconds; // microseconds between pulse leading edges UINT16 volts; // 0.01V increments INT16 temperature; // degrees F INT8 dBm_A, // Average signal for A antenna in dBm dBm_B; // Average signal for B antenna in dBm. // If only 1 antenna, set B = A } STRU_TELE_RPM; */ void srxlFrameRpm(sbuf_t *dst) { srxlSerialize8(dst, SRXL_FRAMETYPE_TELE_RPM); srxlSerialize8(dst, SRXL_FRAMETYPE_SID); srxlSerialize16(dst, 0xFFFF); // pulse leading edges srxlSerialize16(dst, getVbat() * 10); // vbat is in units of 0.1V srxlSerialize16(dst, 0x7FFF); // temperature srxlSerialize8(dst, 0xFF); // dbmA srxlSerialize8(dst, 0xFF); // dbmB /* unused */ srxlSerialize16(dst, 0xFFFF); srxlSerialize16(dst, 0xFFFF); srxlSerialize16(dst, 0xFFFF); } /* typedef struct { UINT8 identifier; // Source device = 0x0A UINT8 sID; // Secondary ID UINT16 volt1; // Volts, 0.01v UINT16 volt2; // Volts, 0.01v UINT16 capacity1; // mAh, 1mAh UINT16 capacity2; // mAh, 1mAh UINT16 spare16_1; UINT16 spare16_2; UINT8 spare; UINT8 alarms; // Alarm bitmask (see below) } STRU_TELE_POWERBOX; */ #define TELE_PBOX_ALARM_VOLTAGE_1 (0x01) #define TELE_PBOX_ALARM_VOLTAGE_2 (0x02) #define TELE_PBOX_ALARM_CAPACITY_1 (0x04) #define TELE_PBOX_ALARM_CAPACITY_2 (0x08) //#define TELE_PBOX_ALARM_RPM (0x10) //#define TELE_PBOX_ALARM_TEMPERATURE (0x20) #define TELE_PBOX_ALARM_RESERVED_1 (0x40) #define TELE_PBOX_ALARM_RESERVED_2 (0x80) void srxlFramePowerBox(sbuf_t *dst) { srxlSerialize8(dst, SRXL_FRAMETYPE_POWERBOX); srxlSerialize8(dst, SRXL_FRAMETYPE_SID); srxlSerialize16(dst, getVbat() * 10); // vbat is in units of 0.1V - vbat1 srxlSerialize16(dst, getVbat() * 10); // vbat is in units of 0.1V - vbat2 srxlSerialize16(dst, amperage / 10); srxlSerialize16(dst, 0xFFFF); srxlSerialize16(dst, 0xFFFF); // spare srxlSerialize16(dst, 0xFFFF); // spare srxlSerialize8(dst, 0xFF); // spare srxlSerialize8(dst, 0x00); // ALARMS } // schedule array to decide how often each type of frame is sent #define SRXL_SCHEDULE_COUNT_MAX 3 typedef void (*srxlSchedulePtr)(sbuf_t *dst); const srxlSchedulePtr srxlScheduleFuncs[SRXL_SCHEDULE_COUNT_MAX] = { /* must send srxlFrameQos, Rpm and then alternating items of our own */ srxlFrameQos, srxlFrameRpm, srxlFramePowerBox }; static void processSrxl(void) { static uint8_t srxlScheduleIndex = 0; sbuf_t srxlPayloadBuf; sbuf_t *dst = &srxlPayloadBuf; srxlSchedulePtr srxlPtr = srxlScheduleFuncs[srxlScheduleIndex]; if (srxlPtr) { srxlInitializeFrame(dst); srxlPtr(dst); srxlFinalize(dst); } srxlScheduleIndex = (srxlScheduleIndex + 1) % SRXL_SCHEDULE_COUNT_MAX; } void initSrxlTelemetry(void) { // check if there is a serial port open for SRXL telemetry (ie opened by the SRXL RX) // and feature is enabled, if so, set SRXL telemetry enabled srxlTelemetryEnabled = srxlRxIsActive(); } bool checkSrxlTelemetryState(void) { return srxlTelemetryEnabled; } /* * Called periodically by the scheduler */ void handleSrxlTelemetry(timeUs_t currentTimeUs) { static uint32_t srxlLastCycleTime; if (!srxlTelemetryEnabled) { return; } // Actual telemetry data only needs to be sent at a low frequency, ie 10Hz if (currentTimeUs >= srxlLastCycleTime + SRXL_CYCLETIME_US) { srxlLastCycleTime = currentTimeUs; processSrxl(); } } #endif
gpl-3.0
alexandre433/WireRepack-Rework-By-SkyLiner
Source/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp
6
11092
/* * Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.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 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/>. */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "MotionMaster.h" #include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "temple_of_ahnqiraj.h" #include "TemporarySummon.h" enum Spells { SPELL_POISON_SHOCK = 25993, SPELL_POISONBOLT_VOLLEY = 25991, SPELL_TOXIN = 26575, SPELL_VISCIDUS_SLOWED = 26034, SPELL_VISCIDUS_SLOWED_MORE = 26036, SPELL_VISCIDUS_FREEZE = 25937, SPELL_REJOIN_VISCIDUS = 25896, SPELL_VISCIDUS_EXPLODE = 25938, SPELL_VISCIDUS_SUICIDE = 26003, SPELL_VISCIDUS_SHRINKS = 25893, // Removed from client, in world.spell_dbc SPELL_MEMBRANE_VISCIDUS = 25994, // damage reduction spell - removed from DBC SPELL_VISCIDUS_WEAKNESS = 25926, // aura which procs at damage - should trigger the slow spells - removed from DBC SPELL_VISCIDUS_GROWS = 25897, // removed from DBC SPELL_SUMMON_GLOBS = 25885, // summons npc 15667 using spells from 25865 to 25884; All spells have target coords - removed from DBC SPELL_VISCIDUS_TELEPORT = 25904, // removed from DBC }; enum Events { EVENT_POISONBOLT_VOLLEY = 1, EVENT_POISON_SHOCK = 2, EVENT_RESET_PHASE = 3 }; enum Phases { PHASE_FROST = 1, PHASE_MELEE = 2, PHASE_GLOB = 3 }; enum Emotes { EMOTE_SLOW = 0, EMOTE_FREEZE = 1, EMOTE_FROZEN = 2, EMOTE_CRACK = 3, EMOTE_SHATTER = 4, EMOTE_EXPLODE = 5 }; enum HitCounter { HITCOUNTER_SLOW = 100, HITCOUNTER_SLOW_MORE = 150, HITCOUNTER_FREEZE = 200, HITCOUNTER_CRACK = 50, HITCOUNTER_SHATTER = 100, HITCOUNTER_EXPLODE = 150, }; enum MovePoints { ROOM_CENTER = 1 }; Position const ViscidusCoord = { -7992.36f, 908.19f, -52.62f, 1.68f }; /// @todo Visci isn't in room middle float const RoomRadius = 40.0f; /// @todo Not sure if its correct class boss_viscidus : public CreatureScript { public: boss_viscidus() : CreatureScript("boss_viscidus") { } struct boss_viscidusAI : public BossAI { boss_viscidusAI(Creature* creature) : BossAI(creature, DATA_VISCIDUS) { Initialize(); } void Initialize() { _hitcounter = 0; _phase = PHASE_FROST; } void Reset() override { _Reset(); Initialize(); } void DamageTaken(Unit* attacker, uint32& /*damage*/) override { if (_phase != PHASE_MELEE) return; ++_hitcounter; if (attacker->HasUnitState(UNIT_STATE_MELEE_ATTACKING) && _hitcounter >= HITCOUNTER_EXPLODE) { Talk(EMOTE_EXPLODE); events.Reset(); _phase = PHASE_GLOB; DoCast(me, SPELL_VISCIDUS_EXPLODE); me->SetVisible(false); me->RemoveAura(SPELL_TOXIN); me->RemoveAura(SPELL_VISCIDUS_FREEZE); uint8 NumGlobes = me->GetHealthPct() / 5.0f; for (uint8 i = 0; i < NumGlobes; ++i) { float Angle = i * 2 * float(M_PI) / NumGlobes; float X = ViscidusCoord.GetPositionX() + std::cos(Angle) * RoomRadius; float Y = ViscidusCoord.GetPositionY() + std::sin(Angle) * RoomRadius; float Z = -35.0f; if (TempSummon* Glob = me->SummonCreature(NPC_GLOB_OF_VISCIDUS, X, Y, Z)) { Glob->UpdateAllowedPositionZ(X, Y, Z); Glob->NearTeleportTo(X, Y, Z, 0.0f); Glob->GetMotionMaster()->MovePoint(ROOM_CENTER, ViscidusCoord); } } } else if (_hitcounter == HITCOUNTER_SHATTER) Talk(EMOTE_SHATTER); else if (_hitcounter == HITCOUNTER_CRACK) Talk(EMOTE_CRACK); } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if ((spell->GetSchoolMask() & SPELL_SCHOOL_MASK_FROST) && _phase == PHASE_FROST && me->GetHealthPct() > 5.0f) { ++_hitcounter; if (_hitcounter >= HITCOUNTER_FREEZE) { _hitcounter = 0; Talk(EMOTE_FROZEN); _phase = PHASE_MELEE; DoCast(me, SPELL_VISCIDUS_FREEZE); me->RemoveAura(SPELL_VISCIDUS_SLOWED_MORE); events.ScheduleEvent(EVENT_RESET_PHASE, 15000); } else if (_hitcounter >= HITCOUNTER_SLOW_MORE) { Talk(EMOTE_FREEZE); me->RemoveAura(SPELL_VISCIDUS_SLOWED); DoCast(me, SPELL_VISCIDUS_SLOWED_MORE); } else if (_hitcounter >= HITCOUNTER_SLOW) { Talk(EMOTE_SLOW); DoCast(me, SPELL_VISCIDUS_SLOWED); } } } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); events.Reset(); InitSpells(); } void InitSpells() { DoCast(me, SPELL_TOXIN); events.ScheduleEvent(EVENT_POISONBOLT_VOLLEY, urand(10000, 15000)); events.ScheduleEvent(EVENT_POISON_SHOCK, urand(7000, 12000)); } void EnterEvadeMode(EvadeReason why) override { summons.DespawnAll(); ScriptedAI::EnterEvadeMode(why); } void JustDied(Unit* /*killer*/) override { DoCast(me, SPELL_VISCIDUS_SUICIDE); summons.DespawnAll(); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; if (_phase == PHASE_GLOB && summons.empty()) { ResetThreatList(); me->NearTeleportTo(ViscidusCoord.GetPositionX(), ViscidusCoord.GetPositionY(), ViscidusCoord.GetPositionZ(), ViscidusCoord.GetOrientation()); _hitcounter = 0; _phase = PHASE_FROST; InitSpells(); me->SetVisible(true); } events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_POISONBOLT_VOLLEY: DoCast(me, SPELL_POISONBOLT_VOLLEY); events.ScheduleEvent(EVENT_POISONBOLT_VOLLEY, urand(10000, 15000)); break; case EVENT_POISON_SHOCK: DoCast(me, SPELL_POISON_SHOCK); events.ScheduleEvent(EVENT_POISON_SHOCK, urand(7000, 12000)); break; case EVENT_RESET_PHASE: _hitcounter = 0; _phase = PHASE_FROST; break; default: break; } } if (_phase != PHASE_GLOB) DoMeleeAttackIfReady(); } private: uint8 _hitcounter; Phases _phase; }; CreatureAI* GetAI(Creature* creature) const override { return GetAQ40AI<boss_viscidusAI>(creature); } }; class npc_glob_of_viscidus : public CreatureScript { public: npc_glob_of_viscidus() : CreatureScript("boss_glob_of_viscidus") { } struct npc_glob_of_viscidusAI : public ScriptedAI { npc_glob_of_viscidusAI(Creature* creature) : ScriptedAI(creature) { } void JustDied(Unit* /*killer*/) override { InstanceScript* Instance = me->GetInstanceScript(); if (Creature* Viscidus = ObjectAccessor::GetCreature(*me, Instance->GetGuidData(DATA_VISCIDUS))) { if (BossAI* ViscidusAI = dynamic_cast<BossAI*>(Viscidus->GetAI())) ViscidusAI->SummonedCreatureDespawn(me); if (Viscidus->IsAlive() && Viscidus->GetHealthPct() < 5.0f) { Viscidus->SetVisible(true); if (Viscidus->GetVictim()) Viscidus->EnsureVictim()->Kill(Viscidus); } else { Viscidus->SetHealth(Viscidus->GetHealth() - Viscidus->GetMaxHealth() / 20); Viscidus->CastSpell(Viscidus, SPELL_VISCIDUS_SHRINKS); } } } void MovementInform(uint32 /*type*/, uint32 id) override { if (id == ROOM_CENTER) { DoCast(me, SPELL_REJOIN_VISCIDUS); if (TempSummon* summon = me->ToTempSummon()) summon->UnSummon(); } } }; CreatureAI* GetAI(Creature* creature) const override { return GetAQ40AI<npc_glob_of_viscidusAI>(creature); } }; void AddSC_boss_viscidus() { new boss_viscidus(); new npc_glob_of_viscidus(); }
gpl-3.0
krzysztof/pykep
src/third_party/cspice/bsrchd_c.c
7
4172
/* -Procedure bsrchd_c ( Binary search for a double precision value ) -Abstract Do a binary search for a key value within a double precision array, assumed to be in increasing order. Return the index of the matching array entry, or -1 if the key value is not found. -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 ARRAY SEARCH */ #include "SpiceUsr.h" #include "SpiceZfc.h" #include "SpiceZim.h" #undef bsrchd_c SpiceInt bsrchd_c ( SpiceDouble value, SpiceInt ndim, ConstSpiceDouble * array ) /* -Brief_I/O VARIABLE I/O DESCRIPTION -------- --- -------------------------------------------------- value I Value to find in array. ndim I Dimension of array. array I Array to be searched. The function returns the index of the input key value in the input array, or -1 if the value is not found. -Detailed_Input value is the value to be found in the input array. ndim is the number of elements in the input array. array is the array to be searched. The elements in the array are assumed to sorted in increasing order. -Detailed_Output The function returns the index of the input value in the input array. Indices range from zero to ndim-1. If the input array does not contain the specified value, the function returns -1. If the input array contains more than one occurrence of the specified value, the returned index may point to any of the occurrences. -Parameters None. -Exceptions Error free. If ndim < 1 the value of the function is -1. -Files None. -Particulars A binary search is performed on the input array. If an element of the array is found to match the input value, the index of that element is returned. If no matching element is found, -1 is returned. -Examples Let array contain the following elements: -11.0 0.0 22.0 750.0 Then bsrchd_c ( -11.0, 4, array ) == 0 bsrchd_c ( 22.0, 4, array ) == 2 bsrchd_c ( 751.0, 4, array ) == -1 -Restrictions array is assumed to be sorted in increasing order. If this condition is not met, the results of bsrchd_c are unpredictable. -Author_and_Institution N.J. Bachman (JPL) I.M. Underwood (JPL) -Literature_References None. -Version -CSPICE Version 1.0.0, 22-AUG-2002 (NJB) (IMU) -Index_Entries binary search for a double precision value -& */ { /* Begin bsrchd_c */ /* Note that we adjust the return value to make it a C-style index. */ return ( bsrchd_ ( (doublereal *) &value, (integer *) &ndim, (doublereal *) array ) - 1 ); } /* End bsrchd_c */
gpl-3.0
darioizzo/pykep
src/third_party/cspice/mxmtg.c
7
7520
/* mxmtg.f -- translated by f2c (version 19980913). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* $Procedure MXMTG ( Matrix times matrix transpose, general dimension ) */ /* Subroutine */ int mxmtg_(doublereal *m1, doublereal *m2, integer *nr1, integer *nc1c2, integer *nr2, doublereal *mout) { /* System generated locals */ integer m1_dim1, m1_dim2, m1_offset, m2_dim1, m2_dim2, m2_offset, mout_dim1, mout_dim2, mout_offset, i__1, i__2, i__3, i__4, i__5; /* Builtin functions */ integer s_rnge(char *, integer, char *, integer); /* Local variables */ integer i__, j, k; doublereal sum; /* $ Abstract */ /* Multiply a matrix and the transpose of a matrix, both of */ /* arbitrary size. */ /* $ 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 */ /* MATRIX */ /* $ Declarations */ /* $ Brief_I/O */ /* VARIABLE I/O DESCRIPTION */ /* -------- --- -------------------------------------------------- */ /* M1 I Left-hand matrix to be multiplied. */ /* M2 I Right-hand matrix whose transpose is to be */ /* multiplied. */ /* NR1 I Row dimension of M1 and row dimension of MOUT. */ /* NC1C2 I Column dimension of M1 and column dimension of */ /* M2. */ /* NR2 I Row dimension of M2 and column dimension of */ /* MOUT. */ /* MOUT O Product matrix M1 * M2**T. */ /* MOUT must not overwrite either M1 or M2. */ /* $ Detailed_Input */ /* M1 M1 may be any double precision matrix of arbitrary size. */ /* M2 M2 may be any double precision matrix of arbitrary size. */ /* The number of columns in M2 must match the number of */ /* columns in M1. */ /* NR1 The number of rows in both M1 and MOUT. */ /* NC1C2 The number of columns in M1 and (by necessity) the number */ /* of columns of M2. */ /* NR2 The number of rows in both M2 and the number of columns */ /* in MOUT. */ /* $ Detailed_Output */ /* MOUT This is a double precision matrix of dimension NR1 x NR2. */ /* T */ /* MOUT is the product matrix given by MOUT = (M1) x (M2) */ /* where the superscript "T" denotes the transpose matrix. */ /* MOUT must not overwrite M1 or M2. */ /* $ Parameters */ /* None. */ /* $ Particulars */ /* The code reflects precisely the following mathematical expression */ /* For each value of the subscript I from 1 to NR1, and J from 1 */ /* to NR2: */ /* MOUT(I,J) = Summation from K=1 to NC1C2 of ( M1(I,K) * M2(J,K) ) */ /* Notice that the order of the subscripts of M2 are reversed from */ /* what they would be if this routine merely multiplied M1 and M2. */ /* It is this transposition of subscripts that makes this routine */ /* multiply M1 and the TRANPOSE of M2. */ /* Since this subroutine operates on matrices of arbitrary size, it */ /* is not feasible to buffer intermediate results. Thus, MOUT */ /* should NOT overwrite either M1 or M2. */ /* $ Examples */ /* Let M1 = | 1.0D0 2.0D0 3.0D0 | NR1 = 2 */ /* | | NC1C2 = 3 */ /* | 3.0D0 2.0D0 1.0D0 | NR2 = 4 */ /* Let M2 = | 1.0D0 2.0D0 0.0D0 | */ /* | | */ /* | 2.0D0 1.0D0 2.0D0 | */ /* | | */ /* | 1.0D0 2.0D0 0.0D0 | */ /* | | */ /* | 2.0D0 1.0D0 2.0D0 | */ /* then the call */ /* CALL MXMTG ( M1, M2, NR1, NC1C2, NR2, MOUT ) */ /* produces the matrix */ /* MOUT = | 5.0D0 10.0D0 5.0D0 10.0D0 | */ /* | | */ /* | 7.0D0 10.0D0 7.0D0 10.0D0 | */ /* $ Restrictions */ /* No error checking is performed to prevent numeric overflow or */ /* underflow. */ /* No error checking is performed to determine if the input and */ /* output matrices have, in fact, been correctly dimensioned. */ /* The user is responsible for checking the magnitudes of the */ /* elements of M1 and M2 so that a floating point overflow does */ /* not occur. */ /* $ Exceptions */ /* Error free. */ /* $ Files */ /* None. */ /* $ Author_and_Institution */ /* W.M. Owen (JPL) */ /* $ Literature_References */ /* None. */ /* $ Version */ /* - SPICELIB Version 1.0.1, 10-MAR-1992 (WLT) */ /* Comment section for permuted index source lines was added */ /* following the header. */ /* - SPICELIB Version 1.0.0, 31-JAN-1990 (WMO) */ /* -& */ /* $ Index_Entries */ /* matrix times matrix_transpose n-dimensional_case */ /* -& */ /* Local variables */ /* Perform the matrix multiplication */ /* Parameter adjustments */ m1_dim1 = *nr1; m1_dim2 = *nc1c2; m1_offset = m1_dim1 + 1; mout_dim1 = *nr1; mout_dim2 = *nr2; mout_offset = mout_dim1 + 1; m2_dim1 = *nr2; m2_dim2 = *nc1c2; m2_offset = m2_dim1 + 1; /* Function Body */ i__1 = *nr1; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = *nr2; for (j = 1; j <= i__2; ++j) { sum = 0.; i__3 = *nc1c2; for (k = 1; k <= i__3; ++k) { sum += m1[(i__4 = i__ + k * m1_dim1 - m1_offset) < m1_dim1 * m1_dim2 && 0 <= i__4 ? i__4 : s_rnge("m1", i__4, "mxmtg_", (ftnlen)206)] * m2[(i__5 = j + k * m2_dim1 - m2_offset) < m2_dim1 * m2_dim2 && 0 <= i__5 ? i__5 : s_rnge("m2", i__5, "mxmtg_", (ftnlen)206)]; } mout[(i__3 = i__ + j * mout_dim1 - mout_offset) < mout_dim1 * mout_dim2 && 0 <= i__3 ? i__3 : s_rnge("mout", i__3, "mxmtg_", (ftnlen)209)] = sum; } } return 0; } /* mxmtg_ */
gpl-3.0
SOWRON/SC
src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp
8
6557
/* * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.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 "ScriptPCH.h" #include "naxxramas.h" #define SAY_GREET RAND(-1533000, -1533004, -1533005, -1533006, -1533007) #define SAY_AGGRO RAND(-1533001, -1533002, -1533003) #define SAY_SLAY -1533008 #define MOB_CRYPT_GUARD 16573 const Position GuardSummonPos = {3333.72f, -3476.30f, 287.1f, 6.2801f}; enum Events { EVENT_NONE, EVENT_IMPALE, EVENT_LOCUST, EVENT_SPAWN_GUARDIAN_NORMAL, EVENT_BERSERK, }; enum Spells { SPELL_IMPALE_10 = 28783, SPELL_IMPALE_25 = 56090, SPELL_LOCUST_SWARM_10 = 28785, SPELL_LOCUST_SWARM_25 = 54021, SPELL_SUMMON_CORPSE_SCARABS_PLR = 29105, // This spawns 5 corpse scarabs on top of player SPELL_SUMMON_CORPSE_SCARABS_MOB = 28864, // This spawns 10 corpse scarabs on top of dead guards SPELL_BERSERK = 27680, }; enum { ACHIEV_TIMED_START_EVENT = 9891, }; class boss_anubrekhan : public CreatureScript { public: boss_anubrekhan() : CreatureScript("boss_anubrekhan") { } CreatureAI* GetAI(Creature* creature) const { return new boss_anubrekhanAI (creature); } struct boss_anubrekhanAI : public BossAI { boss_anubrekhanAI(Creature* creature) : BossAI(creature, BOSS_ANUBREKHAN) {} bool hasTaunted; void Reset() { _Reset(); hasTaunted = false; if (GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) { Position pos; // respawn guard using home position, // otherwise, after a wipe, they respawn where boss was at wipe moment. pos = me->GetHomePosition(); pos.m_positionY -= 10.0f; me->SummonCreature(MOB_CRYPT_GUARD, pos, TEMPSUMMON_CORPSE_DESPAWN); pos = me->GetHomePosition(); pos.m_positionY += 10.0f; me->SummonCreature(MOB_CRYPT_GUARD, pos, TEMPSUMMON_CORPSE_DESPAWN); } } void KilledUnit(Unit* victim) { //Force the player to spawn corpse scarabs via spell, TODO: Check percent chance for scarabs, 20% at the moment if (!(rand()%5)) if (victim->GetTypeId() == TYPEID_PLAYER) victim->CastSpell(victim, SPELL_SUMMON_CORPSE_SCARABS_PLR, true, NULL, NULL, me->GetGUID()); DoScriptText(SAY_SLAY, me); } void JustDied(Unit*) { _JustDied(); // start achievement timer (kill Maexna within 20 min) if (instance) instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } void EnterCombat(Unit* /*who*/) { _EnterCombat(); DoScriptText(SAY_AGGRO, me); events.ScheduleEvent(EVENT_IMPALE, urand(10000, 20000)); events.ScheduleEvent(EVENT_LOCUST, 90000); events.ScheduleEvent(EVENT_BERSERK, 600000); if (GetDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL) events.ScheduleEvent(EVENT_SPAWN_GUARDIAN_NORMAL, urand(15000, 20000)); } void MoveInLineOfSight(Unit* who) { if (!hasTaunted && me->IsWithinDistInMap(who, 60.0f) && who->GetTypeId() == TYPEID_PLAYER) { DoScriptText(SAY_GREET, me); hasTaunted = true; } ScriptedAI::MoveInLineOfSight(who); } void SummonedCreatureDespawn(Creature* summon) { BossAI::SummonedCreatureDespawn(summon); // check if it is an actual killed guard if (!me->isAlive() || summon->isAlive() || summon->GetEntry() != MOB_CRYPT_GUARD) return; summon->CastSpell(summon, SPELL_SUMMON_CORPSE_SCARABS_MOB, true, NULL, NULL, me->GetGUID()); } void UpdateAI(const uint32 diff) { if (!UpdateVictim() || !CheckInRoom()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_IMPALE: //Cast Impale on a random target //Do NOT cast it when we are afflicted by locust swarm if (!me->HasAura(RAID_MODE(SPELL_LOCUST_SWARM_10, SPELL_LOCUST_SWARM_25))) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, RAID_MODE(SPELL_IMPALE_10, SPELL_IMPALE_25)); events.ScheduleEvent(EVENT_IMPALE, urand(10000, 20000)); break; case EVENT_LOCUST: // TODO : Add Text DoCast(me, RAID_MODE(SPELL_LOCUST_SWARM_10, SPELL_LOCUST_SWARM_25)); DoSummon(MOB_CRYPT_GUARD, GuardSummonPos, 0, TEMPSUMMON_CORPSE_DESPAWN); events.ScheduleEvent(EVENT_LOCUST, 90000); break; case EVENT_SPAWN_GUARDIAN_NORMAL: // TODO : Add Text DoSummon(MOB_CRYPT_GUARD, GuardSummonPos, 0, TEMPSUMMON_CORPSE_DESPAWN); break; case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); events.ScheduleEvent(EVENT_BERSERK, 600000); break; } } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_anubrekhan() { new boss_anubrekhan(); }
gpl-3.0
Halajohn/ARMware
ARMware/src/Gtk/MachineScreen.cpp
8
26021
// ARMware - an ARM emulator // Copyright (C) <2007> Wei Hu <wei.hu.tw@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/>. // // System include // #include <cassert> #if TRACE_DRAW_SCREEN #include <iostream> #endif #if WIN32 #pragma warning(disable: 4250) #endif #include <gtkmm/main.h> // Local include // #include "../Memory.hpp" #include "../ColorTableTraits.hpp" #include "../LCDController.hpp" #include "../AtmelMicro.hpp" #include "MachineScreen.hpp" namespace ARMware { ///////////////////////////////// Private //////////////////////////////////// //============================== Operation =================================== void MachineScreen::init_pixmap_and_pixbuf(uint32_t const width, uint32_t const height) { // :NOTE: Wei 2004-Apr-13: // // I create a pixbuf of 32-bit per pixel. // // The reason why I create a pixbuf with an alpha channel is just because // that each pixel is 4-byte long. // // This size will meet the alignment requirement in most case, and should be // faster. // :NOTE: Wei 2004-Jul-12: // // The reason why the height of the pixbuf is 'height + 8' when using ENABLE_DRAWING_ASM // is because I will get 8 pixels data at most at once. // // Thus I have to increment the height to avoid the segmentation fault. mp_pixbuf = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true, // has_alpha 8, // bits_per_sample width, #if ENABLE_DRAWING_ASM height + 8 #else height #endif ); // Clear the pixbuf's buffer to black // // :NOTE: Wei 2004-Apr-13: // // Because mp_pixbuf has an alpha channel, // thus I have to set the value of the alpha channel to 0xFF to show the // RGB value I set. mp_pixbuf->fill(0x000000FF); mp_pixmap = Gdk::Pixmap::create(m_drawing_area.get_window(), width, height, -1 ); mp_pixmap->draw_pixbuf(mp_empty_gc, mp_pixbuf, 0, 0, // src 0, 0, // dest static_cast<int>(width), static_cast<int>(height), Gdk::RGB_DITHER_NONE, 0, 0 // dither offset ); // I don't want the drawing area to have a backing pixmap, // I will redraw part of it in the expose event signal handler. m_drawing_area.get_window()->set_back_pixmap(Glib::RefPtr<Gdk::Pixmap>(), false // parent_relative ); m_drawing_area.get_window()->draw_drawable(m_drawing_area.get_style()->get_bg_gc(Gtk::STATE_NORMAL), mp_pixmap, 0, 0, // src x, y (i.e. mp_pixmap) 0, 0 // dest x, y (i.e. m_drawing_area.get_window()) ); } template<MachineScreen::PanelEnum T_panel> inline uint32_t MachineScreen::get_panel_start_address() const { switch (T_panel) { case PANEL_1: return m_frame_buffer_addr_1; case PANEL_2: return m_frame_buffer_addr_2; default: assert(!"Should not reach here."); return 0; } } template<MachineScreen::PanelEnum T_panel, MachineScreen::DualPanelEnum T_dual> inline guint8 * MachineScreen::get_pixbuf_start_address() const { switch (T_dual) { case SINGLE: assert(PANEL_1 == T_panel); return mp_pixbuf->get_pixels(); case DUAL: switch (T_panel) { case PANEL_1: return mp_pixbuf->get_pixels(); case PANEL_2: // :NOTE: Wei 2004-Jun-29: // // The pixel width of Gdk pixbuf is 4-byte. // (Alpha, red, green, blue) return mp_pixbuf->get_pixels() + ((DISPLAY_WIDTH >> 1) << 2); default: assert(!"Should not reach here."); return 0; } default: assert(!"Should not reach here."); return 0; } } template<MachineScreen::PanelEnum T_panel, MachineScreen::DualPanelEnum T_dual> inline uint32_t MachineScreen::get_drawing_left() const { switch (T_dual) { case SINGLE: assert(PANEL_1 == T_panel); return m_dirty_left; case DUAL: switch (T_panel) { case PANEL_1: return ((m_dirty_left < (DISPLAY_WIDTH >> 1)) ? m_dirty_left : (DISPLAY_WIDTH >> 1)); case PANEL_2: return ((m_dirty_left < (DISPLAY_WIDTH >> 1)) ? (DISPLAY_WIDTH >> 1) : m_dirty_left); default: assert(!"Should not reach here."); return 0; } default: assert(!"Should not reach here."); return 0; } } template<MachineScreen::PanelEnum T_panel, MachineScreen::DualPanelEnum T_dual> inline uint32_t MachineScreen::get_drawing_right() const { switch (T_dual) { case SINGLE: assert(PANEL_1 == T_panel); return m_dirty_right; case DUAL: switch (T_panel) { case PANEL_1: return ((m_dirty_right < (DISPLAY_WIDTH >> 1)) ? m_dirty_right : (DISPLAY_WIDTH >> 1)); case PANEL_2: return ((m_dirty_right < (DISPLAY_WIDTH >> 1)) ? (DISPLAY_WIDTH >> 1) : m_dirty_right); default: assert(!"Should not reach here."); return 0; } default: assert(!"Should not reach here."); return 0; } } #if ENABLE_DRAWING_ASM // :NOTE: Wei 2004-Jul-12: // // The 'psrlq' for MMX & 'psrldq' for SSE are different. // // 'psrlq' uses bits as element to shift, however, // 'psrldq' uses bytes as element to shift. #define MMX_STORE_PIXEL(mmx_r) "subl %6, %%edi \n\t" \ "psrlq $32, %%" #mmx_r "\n\t" \ "maskmovq %%mm2, %%" #mmx_r "\n\t" #define SSE2_STORE_PIXEL(sse_r) "subl %6, %%edi \n\t" \ "psrldq $4, %%" #sse_r "\n\t" \ "maskmovdqu %%xmm2, %%" #sse_r "\n\t" // :NOTE: Wei 2004-Jul-12: // // If just drawing 1 or 2 pixels, then we can eliminate some operations, see below. #define MMX_DRAW_1_2_PIXELS_PROLOGUE \ asm volatile ( \ "movq %0, %%mm0 \n\t" /* read 4 pixels */ \ "movq %%mm0, %%mm1 \n\t" \ "movq %%mm0, %%mm2 \n\t" \ \ "pand %1, %%mm0 \n\t" /* mm0: red */ \ "pand %2, %%mm1 \n\t" /* mm1: green */ \ "pand %3, %%mm2 \n\t" /* mm2: blue */ \ \ "psrlw $8, %%mm0\n\t" /* red shift right 12, multiply 16 */ \ "psrlw $3, %%mm1\n\t" /* green shift right 7, multiply 16 */ \ "psllw $3, %%mm2\n\t" /* blue shift right 1, multiply 16 */ \ \ "packuswb %%mm3, %%mm0 \n\t" /* mm0: low 32-bit red */ \ "packuswb %%mm3, %%mm1 \n\t" /* mm1: low 32-bit green */ \ "packuswb %%mm3, %%mm2 \n\t" /* mm2: low 32-bit blue */ \ \ "punpcklbw %%mm1, %%mm0 \n\t" /* mm0: 64-bit {green, red} */ \ /* "movq %%mm0, %%mm1 \n\t" --> mm1: 64-bit {green, red} */ \ "punpcklbw %4, %%mm2 \n\t" /* mm2: 64-bit {alpha, blue} */ \ \ "punpcklwd %%mm2, %%mm0 \n\t" /* mm0: 64-bit {alpha, blue, green, red} */ \ /* "punpckhwd %%mm2, %%mm1 \n\t" --> mm1: 64-bit {alpha, blue, green, red} */ \ \ "movl %5, %%edi \n\t" /* edi: dest address */ \ \ "movl $0xFFFFFFFF, %%edx \n\t" \ "movd %%edx, %%mm2 \n\t" /* mm2: 0x00000000FFFFFFFF */ \ "maskmovq %%mm2, %%mm0 \n\t" #define MMX_DRAW_PIXELS_PROLOGUE \ asm volatile ( \ "movq %0, %%mm0 \n\t" /* read 4 pixels */ \ "movq %%mm0, %%mm1 \n\t" \ "movq %%mm0, %%mm2 \n\t" \ \ "pand %1, %%mm0 \n\t" /* mm0: red */ \ "pand %2, %%mm1 \n\t" /* mm1: green */ \ "pand %3, %%mm2 \n\t" /* mm2: blue */ \ \ "psrlw $8, %%mm0\n\t" /* red shift right 12, multiply 16 */ \ "psrlw $3, %%mm1\n\t" /* green shift right 7, multiply 16 */ \ "psllw $3, %%mm2\n\t" /* blue shift right 1, multiply 16 */ \ \ "packuswb %%mm3, %%mm0 \n\t" /* mm0: low 32-bit red */ \ "packuswb %%mm3, %%mm1 \n\t" /* mm1: low 32-bit green */ \ "packuswb %%mm3, %%mm2 \n\t" /* mm2: low 32-bit blue */ \ \ "punpcklbw %%mm1, %%mm0 \n\t" /* mm0: 64-bit {green, red} */ \ "movq %%mm0, %%mm1 \n\t" /* mm1: 64-bit {green, red} */ \ "punpcklbw %4, %%mm2 \n\t" /* mm2: 64-bit {alpha, blue} */ \ \ "punpcklwd %%mm2, %%mm0 \n\t" /* mm0: 64-bit {alpha, blue, green, red} */ \ "punpckhwd %%mm2, %%mm1 \n\t" /* mm1: 64-bit {alpha, blue, green, red} */ \ \ "movl %5, %%edi \n\t" /* edi: dest address */ \ \ "movl $0xFFFFFFFF, %%edx \n\t" \ "movd %%edx, %%mm2 \n\t" /* mm2: 0x00000000FFFFFFFF */ \ "maskmovq %%mm2, %%mm0 \n\t" #define SSE2_DRAW_PIXELS_PROLOGUE \ asm volatile ( \ "movdqu %0, %%xmm0 \n\t" /* read 8 pixels */ \ "movdqa %%xmm0, %%xmm1 \n\t" \ "movdqa %%xmm0, %%xmm2 \n\t" \ \ "pand %1, %%xmm0 \n\t" /* xmm0: red */ \ "pand %2, %%xmm1 \n\t" /* xmm1: green */ \ "pand %3, %%xmm2 \n\t" /* xmm2: blue */ \ \ "psrlw $8, %%xmm0\n\t" /* red shift right 12, multiply 16 */ \ "psrlw $3, %%xmm1\n\t" /* green shift right 7, multiply 16 */ \ "psllw $3, %%xmm2\n\t" /* blue shift right 1, multiply 16 */ \ \ "packuswb %%xmm3, %%xmm0 \n\t" /* xmm0: low 64-bit red */ \ "packuswb %%xmm3, %%xmm1 \n\t" /* xmm1: low 64-bit green */ \ "packuswb %%xmm3, %%xmm2 \n\t" /* xmm2: low 64-bit blue */ \ \ "punpcklbw %%xmm1, %%xmm0 \n\t" /* xmm0: 128-bit {green, red} */ \ "movdqa %%xmm0, %%xmm1 \n\t" /* xmm1: 128-bit {green, red} */ \ "punpcklbw %4, %%xmm2 \n\t" /* xmm2: 128-bit {alpha, blue} */ \ \ "punpcklwd %%xmm2, %%xmm0 \n\t" /* xmm0: 128-bit {alpha, blue, green, red} */ \ "punpckhwd %%xmm2, %%xmm1 \n\t" /* xmm1: 128-bit {alpha, blue, green, red} */ \ \ "movl %5, %%edi \n\t" /* edi: dest address */ \ \ "movl $0xFFFFFFFF, %%edx \n\t" \ "movd %%edx, %%xmm2 \n\t" /* xmm2: 0x000000000000000000000000FFFFFFFF */ \ "maskmovdqu %%xmm2, %%xmm0 \n\t" #define MMX_DRAW_PIXELS_EPILOGUE \ "subl %6, %%edi \n\t" \ "movl %%edi, %5" \ : \ : "m" (mp_memory[curr_addr]), \ "m" (m_red_bitmask.m_low), \ "m" (m_green_bitmask.m_low), \ "m" (m_blue_bitmask.m_low), \ "m" (m_alpha_value.m_low), \ "m" (dest), \ "r" (row_length) \ : "edx", "edi", "memory", "mm0", "mm1", "mm2" \ ) #define SSE2_DRAW_PIXELS_EPILOGUE \ "subl %6, %%edi \n\t" \ "movl %%edi, %5" \ : \ : "m" (mp_memory[curr_addr]), \ "m" (m_red_bitmask), \ "m" (m_green_bitmask), \ "m" (m_blue_bitmask), \ "m" (m_alpha_value), \ "m" (dest), \ "r" (row_length) \ : "edx", "edi", "memory", "xmm0", "xmm1", "xmm2" \ ) // :NOTE: Wei 2004-Jul-12: // // The reason why I have the following 1, 2, 3, 4, 5, 6, 7, 8 pixels drawing routines // is because I want to minimize the store operations in the end of each drawing routines. // // Ex: If I just need to drawing 6 pixels, however, I use drawing_8_pixels() to drawing, // then I drawing 2 unnecessary pixels. // And because of the load/store to memory is slow, thus I want to minimize its uses. #define MMX_DRAW_1_PIXELS \ MMX_DRAW_1_2_PIXELS_PROLOGUE \ MMX_DRAW_PIXELS_EPILOGUE #define MMX_DRAW_2_PIXELS \ MMX_DRAW_1_2_PIXELS_PROLOGUE \ \ MMX_STORE_PIXEL(mm0) \ \ MMX_DRAW_PIXELS_EPILOGUE #define MMX_DRAW_3_PIXELS \ MMX_DRAW_PIXELS_PROLOGUE \ \ MMX_STORE_PIXEL(mm0) \ \ "subl %6, %%edi \n\t" \ "maskmovq %%mm2, %%mm1 \n\t" \ \ MMX_DRAW_PIXELS_EPILOGUE #define MMX_DRAW_4_PIXELS \ MMX_DRAW_PIXELS_PROLOGUE \ \ MMX_STORE_PIXEL(mm0) \ \ "subl %6, %%edi \n\t" \ "maskmovq %%mm2, %%mm1 \n\t" \ \ MMX_STORE_PIXEL(mm1) \ \ MMX_DRAW_PIXELS_EPILOGUE #define SSE2_DRAW_5_PIXELS \ SSE2_DRAW_PIXELS_PROLOGUE \ \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ \ "subl %6, %%edi \n\t" \ "maskmovdqu %%xmm2, %%xmm1 \n\t" \ \ SSE2_DRAW_PIXELS_EPILOGUE #define SSE2_DRAW_6_PIXELS \ SSE2_DRAW_PIXELS_PROLOGUE \ \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ \ "subl %6, %%edi \n\t" \ "maskmovdqu %%xmm2, %%xmm1 \n\t" \ \ SSE2_STORE_PIXEL(xmm1) \ \ SSE2_DRAW_PIXELS_EPILOGUE #define SSE2_DRAW_7_PIXELS \ SSE2_DRAW_PIXELS_PROLOGUE \ \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ \ "subl %6, %%edi \n\t" \ "maskmovdqu %%xmm2, %%xmm1 \n\t" \ \ SSE2_STORE_PIXEL(xmm1) \ SSE2_STORE_PIXEL(xmm1) \ \ SSE2_DRAW_PIXELS_EPILOGUE #define SSE2_DRAW_8_PIXELS \ SSE2_DRAW_PIXELS_PROLOGUE \ \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ SSE2_STORE_PIXEL(xmm0) \ \ "subl %6, %%edi \n\t" \ "maskmovdqu %%xmm2, %%xmm1 \n\t" \ \ SSE2_STORE_PIXEL(xmm1) \ SSE2_STORE_PIXEL(xmm1) \ SSE2_STORE_PIXEL(xmm1) \ \ SSE2_DRAW_PIXELS_EPILOGUE inline void MachineScreen::drawing_1_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { MMX_DRAW_1_PIXELS; curr_addr += (1 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_2_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { MMX_DRAW_2_PIXELS; curr_addr += (2 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_3_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { MMX_DRAW_3_PIXELS; curr_addr += (3 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_4_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { MMX_DRAW_4_PIXELS; curr_addr += (4 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_5_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { SSE2_DRAW_5_PIXELS; curr_addr += (5 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_6_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { SSE2_DRAW_6_PIXELS; curr_addr += (6 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_7_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { SSE2_DRAW_7_PIXELS; curr_addr += (7 * BYTES_PER_PIXEL); } inline void MachineScreen::drawing_8_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { SSE2_DRAW_8_PIXELS; curr_addr += (8 * BYTES_PER_PIXEL); } #else // ENABLE_DRAWING_ASM inline void MachineScreen::drawing_1_pixel(uint32_t &curr_addr, uint8_t *&dest, uint32_t const row_length) const { uint16_t const pixel = *reinterpret_cast<uint16_t *>(&(mp_memory[curr_addr])); curr_addr += BYTES_PER_PIXEL; *reinterpret_cast<uint32_t *>(dest) = (0xFF000000 | mRedTable[(pixel >> RED_OFFSET) /* & RED_MAX_VALUE */] | mGreenTable[(pixel >> GREEN_OFFSET) & GREEN_MAX_VALUE] | mBlueTable[(pixel >> BLUE_OFFSET) & BLUE_MAX_VALUE] ); dest -= row_length; } #endif // ENABLE_DRAWING_ASM template<MachineScreen::PanelEnum T_panel, MachineScreen::DualPanelEnum T_dual> inline void MachineScreen::draw_panel() { #if TRACE_DRAW_SCREEN g_log_file << "SCREEN: drawing: "; #endif assert(mp_memory != 0); if (false == dirty_rect_in_this_panel<T_panel, T_dual>()) { return; } uint32_t const machine_bpl = DISPLAY_HEIGHT * BYTES_PER_PIXEL; // bytes per line uint32_t const start_addr = (get_panel_start_address<T_panel>() + (DISPLAY_HEIGHT * BYTES_PER_PIXEL * get_x_diff<T_panel, T_dual>()) + (((DISPLAY_HEIGHT - m_dirty_bottom)) * BYTES_PER_PIXEL)); uint32_t prev_addr = start_addr; guint8 * const pixbuf_startaddress = get_pixbuf_start_address<T_panel, T_dual>(); uint32_t const row_length = mp_pixbuf->get_rowstride(); uint8_t *dest_base = pixbuf_startaddress + ((m_dirty_bottom - 1) * row_length) + (m_dirty_left << 2); uint32_t curr_addr; uint8_t *dest; #if ENABLE_DRAWING_ASM uint32_t const height = (m_dirty_bottom - m_dirty_top); uint32_t const p8_count = (height >> 3); uint32_t const p1_count = (height & (8 - 1)); #endif for (uint32_t x = get_drawing_left<T_panel, T_dual>(); x < get_drawing_right<T_panel, T_dual>(); ++x) { curr_addr = prev_addr; dest = dest_base; prev_addr = curr_addr; #if ENABLE_DRAWING_ASM for (uint32_t c8 = 0; c8 < p8_count; ++c8) { drawing_8_pixel(curr_addr, dest, row_length); } switch (p1_count) { case 0: break; case 1: drawing_1_pixel(curr_addr, dest, row_length); break; case 2: drawing_2_pixel(curr_addr, dest, row_length); break; case 3: drawing_3_pixel(curr_addr, dest, row_length); break; case 4: drawing_4_pixel(curr_addr, dest, row_length); break; case 5: drawing_5_pixel(curr_addr, dest, row_length); break; case 6: drawing_6_pixel(curr_addr, dest, row_length); break; case 7: drawing_7_pixel(curr_addr, dest, row_length); break; default: assert(!"Should not reach here."); break; } #else for (uint32_t y = m_dirty_top; y < m_dirty_bottom; ++y) { drawing_1_pixel(curr_addr, dest, row_length); } #endif dest_base += 4; prev_addr += machine_bpl; } #if ENABLE_DRAWING_ASM asm volatile ("emms"); #endif #if TRACE_DRAW_SCREEN g_log_file << std::endl; #endif mp_pixmap->draw_pixbuf(mp_empty_gc, mp_pixbuf, m_dirty_left, m_dirty_top, // src m_dirty_left, m_dirty_top, // dest static_cast<int>(m_dirty_right - m_dirty_left), static_cast<int>(m_dirty_bottom - m_dirty_top), Gdk::RGB_DITHER_NONE, 0, 0 // dither offset ); // Force X Window Server to send an expose event to the m_drawing_area. m_drawing_area.get_window()->clear_area_e(m_dirty_left, m_dirty_top, m_dirty_right - m_dirty_left, m_dirty_bottom - m_dirty_top); } //============================ Signal handler ================================ void MachineScreen::on_drawing_area_size_allocate(Gtk::Allocation &alloc) { if (false == mp_pixmap) { mp_pixmap.clear(); } if (false == mp_pixbuf) { mp_pixbuf.clear(); } init_pixmap_and_pixbuf(alloc.get_width(), alloc.get_height()); } void MachineScreen::on_drawing_area_expose_event(GdkEventExpose *event) { #if TRACE_DRAW_SCREEN g_log_file << "SCREEN: expose (" << std::dec << event->area.x << ", " << event->area.y << ", " << event->area.width << ", " << event->area.height << ")" << std::endl; #endif m_drawing_area.get_window()->draw_drawable(m_drawing_area.get_style()->get_bg_gc(Gtk::STATE_NORMAL), mp_pixmap, event->area.x, event->area.y, event->area.x, event->area.y, event->area.width, event->area.height); } void MachineScreen::on_drawing_area_button_press_event(GdkEventButton *event) { assert(mp_atmel != 0); // :NOTE: Wei 2004-Jul-06: // // Ignore Gdk::DOUBLE_BUTTON_PRESS & Gdk::TRIPLE_BUTTON_PRESS if (GDK_BUTTON_PRESS == event->type) { mp_atmel->receive_touch_panel_pen_down_event(event); } } void MachineScreen::on_drawing_area_button_release_event(GdkEventButton *event) { assert(mp_atmel != 0); mp_atmel->receive_touch_panel_pen_up_event(event); } void MachineScreen::on_drawing_area_motion_notify_event(GdkEventMotion *event) { assert(mp_atmel != 0); assert(Gdk::BUTTON1_MASK == (event->state & Gdk::BUTTON1_MASK)); mp_atmel->receive_touch_panel_pen_move_event(event); } ///////////////////////////////// Public //////////////////////////////////// //============================== Life cycle ================================= MachineScreen::MachineScreen() : m_table(1, 1, true), m_lcd_status(0), mp_memory(0), mp_LCD_controller(0), mp_atmel(0) { set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); add(m_table); m_table.attach(m_drawing_area, 0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 0, 0); m_drawing_area.set_double_buffered(false); m_drawing_area.signal_size_allocate(). connect(sigc::mem_fun(*this, &MachineScreen::on_drawing_area_size_allocate)); m_drawing_area.signal_expose_event(). connect_notify(sigc::mem_fun(*this, &MachineScreen::on_drawing_area_expose_event)); show_all_children(); clear_dirty_rect(); #if ENABLE_DRAWING_ASM m_red_bitmask.m_low = 0xF800F800F800F800LL; m_red_bitmask.m_high = m_red_bitmask.m_low; m_green_bitmask.m_low = 0x07E007E007E007E0LL; m_green_bitmask.m_high = m_green_bitmask.m_low; m_blue_bitmask.m_low = 0x001F001F001F001FLL; m_blue_bitmask.m_high = m_blue_bitmask.m_low; m_alpha_value.m_low = 0xFFFFFFFFFFFFFFFFLL; m_alpha_value.m_high = 0; #endif } MachineScreen::~MachineScreen() { if (false == mp_pixmap) { mp_pixmap.clear(); } if (false == mp_pixbuf) { mp_pixbuf.clear(); } } //============================= Operation =================================== void MachineScreen::register_atmel_micro(AtmelMicro * const atmel) { mp_atmel = atmel; m_drawing_area.add_events(Gdk::BUTTON_PRESS_MASK); m_drawing_area.add_events(Gdk::BUTTON_RELEASE_MASK); m_drawing_area.add_events(Gdk::BUTTON1_MOTION_MASK); m_drawing_area.signal_button_press_event(). connect_notify(sigc::mem_fun(*this, &MachineScreen::on_drawing_area_button_press_event)); m_drawing_area.signal_button_release_event(). connect_notify(sigc::mem_fun(*this, &MachineScreen::on_drawing_area_button_release_event)); m_drawing_area.signal_motion_notify_event(). connect_notify(sigc::mem_fun(*this, &MachineScreen::on_drawing_area_motion_notify_event)); } void MachineScreen::get_and_store_next_armware_event() { Gtk::Main::iteration(false); } void MachineScreen::change_screen_size(uint32_t const width, uint32_t const height) { m_drawing_area.set_size_request(width, height); } bool MachineScreen::draw_screen() { switch (m_lcd_status) { case 0: case DUAL_PANEL: // disable drawing break; case ENABLE_DRAWING: // single panel if (true == has_dirty_rect()) { draw_panel<PANEL_1, SINGLE>(); clear_dirty_rect(); } mp_LCD_controller->finish_one_frame(); break; case (ENABLE_DRAWING | DUAL_PANEL): if (true == has_dirty_rect()) { draw_panel<PANEL_1, DUAL>(); draw_panel<PANEL_2, DUAL>(); clear_dirty_rect(); } mp_LCD_controller->finish_one_frame(); break; default: assert(!"Should not reach here."); break; } // :NOTE: Wei 2004-Jun-29: // // Return true so the function will be called again; // returning false removes this timeout function. return true; } }
gpl-3.0
wdkk/iSuperColliderKit
external_libraries/oscpack/examples/OscDump.cpp
10
2562
/* oscpack -- Open Sound Control packet manipulation library http://www.audiomulch.com/~rossb/oscpack Copyright (c) 2004-2005 Ross Bencina <rossb@audiomulch.com> 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. Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. 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 THE AUTHORS OR COPYRIGHT HOLDERS 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. */ /* OscDump prints incoming Osc packets. Unlike the Berkeley dumposc program OscDump uses a different printing format which indicates the type of each message argument. */ #include <iostream> #include <cstring> #include <cstdlib> #include "osc/OscReceivedElements.h" #include "osc/OscPrintReceivedElements.h" #include "ip/UdpSocket.h" #include "ip/PacketListener.h" class OscDumpPacketListener : public PacketListener{ public: virtual void ProcessPacket( const char *data, int size, const IpEndpointName& remoteEndpoint ) { std::cout << osc::ReceivedPacket( data, size ); } }; int main(int argc, char* argv[]) { if( argc >= 2 && strcmp( argv[1], "-h" ) == 0 ){ std::cout << "usage: OscDump [port]\n"; return 0; } int port = 7000; if( argc >= 2 ) port = atoi( argv[1] ); OscDumpPacketListener listener; UdpListeningReceiveSocket s( IpEndpointName( IpEndpointName::ANY_ADDRESS, port ), &listener ); std::cout << "listening for input on port " << port << "...\n"; std::cout << "press ctrl-c to end\n"; s.RunUntilSigInt(); std::cout << "finishing.\n"; return 0; }
gpl-3.0
evancich/apm_motor
modules/PX4NuttX/nuttx/graphics/nxglib/lcd/nxglib_getrectangle.c
10
4113
/**************************************************************************** * graphics/nxglib/lcd/nxglib_getrectangle.c * * Copyright (C) 2011 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * 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 NuttX 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 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <nuttx/lcd/lcd.h> #include <nuttx/nx/nxglib.h> #include "nxglib_bitblit.h" /**************************************************************************** * Pre-Processor Definitions ****************************************************************************/ /**************************************************************************** * Private Types ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nxgl_moverectangle_*bpp * * Descripton: * Fetch a rectangular region from LCD GRAM memory. The source is * expressed as a rectangle. * ****************************************************************************/ void NXGL_FUNCNAME(nxgl_getrectangle,NXGLIB_SUFFIX) (FAR struct lcd_planeinfo_s *pinfo, FAR const struct nxgl_rect_s *rect, FAR void *dest, unsigned int deststride) { FAR uint8_t *dline; unsigned int ncols; unsigned int srcrow; /* Get the width of the rectange to move in pixels. */ ncols = rect->pt2.x - rect->pt1.x + 1; /* dline = address of the first row pixel */ dline = (FAR uint8_t *)dest; /* Copy the rectangle */ for (srcrow = rect->pt1.y; srcrow <= rect->pt2.y; srcrow++) { (void)pinfo->getrun(srcrow, rect->pt1.x, dline, ncols); dline += deststride; } }
gpl-3.0
Pulfer/clementine-vkservice
src/devices/gpoddevice.cpp
10
6589
/* This file is part of Clementine. Copyright 2010, David Sansome <me@davidsansome.com> Clementine 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. Clementine 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 Clementine. If not, see <http://www.gnu.org/licenses/>. */ #include "devicemanager.h" #include "gpoddevice.h" #include "gpodloader.h" #include "core/logging.h" #include "core/application.h" #include "library/librarybackend.h" #include "library/librarymodel.h" #include <QDir> #include <QFile> #include <QThread> #include <QtDebug> #include <gpod/itdb.h> GPodDevice::GPodDevice( const QUrl& url, DeviceLister* lister, const QString& unique_id, DeviceManager* manager, Application* app, int database_id, bool first_time) : ConnectedDevice(url, lister, unique_id, manager, app, database_id, first_time), loader_thread_(new QThread(this)), loader_(NULL), db_(NULL) { } void GPodDevice::Init() { InitBackendDirectory(url_.path(), first_time_); model_->Init(); loader_ = new GPodLoader(url_.path(), app_->task_manager(), backend_, shared_from_this()); loader_->moveToThread(loader_thread_); connect(loader_, SIGNAL(Error(QString)), SIGNAL(Error(QString))); connect(loader_, SIGNAL(TaskStarted(int)), SIGNAL(TaskStarted(int))); connect(loader_, SIGNAL(LoadFinished(Itdb_iTunesDB*)), SLOT(LoadFinished(Itdb_iTunesDB*))); connect(loader_thread_, SIGNAL(started()), loader_, SLOT(LoadDatabase())); loader_thread_->start(); } GPodDevice::~GPodDevice() { } void GPodDevice::LoadFinished(Itdb_iTunesDB* db) { QMutexLocker l(&db_mutex_); db_ = db; db_wait_cond_.wakeAll(); loader_->deleteLater(); loader_ = NULL; } bool GPodDevice::StartCopy(QList<Song::FileType>* supported_filetypes) { { // Wait for the database to be loaded QMutexLocker l(&db_mutex_); if (!db_) db_wait_cond_.wait(&db_mutex_); } // Ensure only one "organise files" can be active at any one time db_busy_.lock(); if (supported_filetypes) GetSupportedFiletypes(supported_filetypes); return true; } Itdb_Track* GPodDevice::AddTrackToITunesDb(const Song& metadata) { // Create the track Itdb_Track* track = itdb_track_new(); metadata.ToItdb(track); // Add it to the DB and the master playlist // The DB takes ownership of the track itdb_track_add(db_, track, -1); Itdb_Playlist* mpl = itdb_playlist_mpl(db_); itdb_playlist_add_track(mpl, track, -1); return track; } void GPodDevice::AddTrackToModel(Itdb_Track* track, const QString& prefix) { // Add it to our LibraryModel Song metadata_on_device; metadata_on_device.InitFromItdb(track, prefix); metadata_on_device.set_directory_id(1); songs_to_add_ << metadata_on_device; } bool GPodDevice::CopyToStorage(const CopyJob& job) { Q_ASSERT(db_); Itdb_Track* track = AddTrackToITunesDb(job.metadata_); // Copy the file GError* error = NULL; itdb_cp_track_to_ipod(track, QDir::toNativeSeparators(job.source_) .toLocal8Bit().constData(), &error); if (error) { qLog(Error) << "copying failed:" << error->message; app_->AddError(QString::fromUtf8(error->message)); g_error_free(error); // Need to remove the track from the db again itdb_track_remove(track); return false; } AddTrackToModel(track, url_.path()); // Remove the original if it was requested if (job.remove_original_) { QFile::remove(job.source_); } return true; } void GPodDevice::WriteDatabase(bool success) { if (success) { // Write the itunes database GError* error = NULL; itdb_write(db_, &error); if (error) { qLog(Error) << "writing database failed:" << error->message; app_->AddError(QString::fromUtf8(error->message)); g_error_free(error); } else { FinaliseDatabase(); // Update the library model if (!songs_to_add_.isEmpty()) backend_->AddOrUpdateSongs(songs_to_add_); if (!songs_to_remove_.isEmpty()) backend_->DeleteSongs(songs_to_remove_); } } songs_to_add_.clear(); songs_to_remove_.clear(); db_busy_.unlock(); } void GPodDevice::FinishCopy(bool success) { WriteDatabase(success); ConnectedDevice::FinishCopy(success); } void GPodDevice::StartDelete() { StartCopy(NULL); } bool GPodDevice::RemoveTrackFromITunesDb(const QString& path, const QString& relative_to) { QString ipod_filename = path; if (!relative_to.isEmpty() && path.startsWith(relative_to)) ipod_filename.remove(0, relative_to.length() + (relative_to.endsWith('/') ? -1 : 0)); ipod_filename.replace('/', ':'); // Find the track in the itdb, identify it by its filename Itdb_Track* track = NULL; for (GList* tracks = db_->tracks ; tracks != NULL ; tracks = tracks->next) { Itdb_Track* t = static_cast<Itdb_Track*>(tracks->data); if (t->ipod_path == ipod_filename) { track = t; break; } } if (track == NULL) { qLog(Warning) << "Couldn't find song" << path << "in iTunesDB"; return false; } // Remove the track from all playlists for (GList* playlists = db_->playlists ; playlists != NULL ; playlists = playlists->next) { Itdb_Playlist* playlist = static_cast<Itdb_Playlist*>(playlists->data); if (itdb_playlist_contains_track(playlist, track)) { itdb_playlist_remove_track(playlist, track); } } // Remove the track from the database, this frees the struct too itdb_track_remove(track); return true; } bool GPodDevice::DeleteFromStorage(const DeleteJob& job) { Q_ASSERT(db_); if (!RemoveTrackFromITunesDb(job.metadata_.url().toLocalFile(), url_.path())) return false; // Remove the file if (!QFile::remove(job.metadata_.url().toLocalFile())) return false; // Remove it from our library model songs_to_remove_ << job.metadata_; return true; } void GPodDevice::FinishDelete(bool success) { WriteDatabase(success); ConnectedDevice::FinishDelete(success); } bool GPodDevice::GetSupportedFiletypes(QList<Song::FileType>* ret) { *ret << Song::Type_Mp4; *ret << Song::Type_Mpeg; return true; }
gpl-3.0
lidan-fnst/samba
source3/rpc_server/mdssvc/sparql_mapping.c
11
9013
/* Unix SMB/CIFS implementation. Main metadata server / Spotlight routines Copyright (C) Ralph Boehme 2012-2014 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 "replace.h" #include "sparql_mapping.h" const struct sl_attr_map *sl_attr_map_by_spotlight(const char *sl_attr) { static const struct sl_attr_map spotlight_sparql_attr_map[] = { { .spotlight_attr = "*", .type = ssmt_fts, .sparql_attr = "fts:match", }, /* Filesystem metadata */ { .spotlight_attr = "kMDItemFSLabel", .type = ssmt_num, .sparql_attr = NULL, }, { .spotlight_attr = "kMDItemDisplayName", .type = ssmt_str, .sparql_attr = "nfo:fileName", }, { .spotlight_attr = "kMDItemFSName", .type = ssmt_str, .sparql_attr = "nfo:fileName", }, { .spotlight_attr = "kMDItemFSContentChangeDate", .type = ssmt_date, .sparql_attr = "nfo:fileLastModified", }, { .spotlight_attr = "kMDItemLastUsedDate", .type = ssmt_date, .sparql_attr = "nfo:fileLastAccessed", }, /* Common metadata */ { .spotlight_attr = "kMDItemTextContent", .type = ssmt_fts, .sparql_attr = "fts:match", }, { .spotlight_attr = "kMDItemContentCreationDate", .type = ssmt_date, .sparql_attr = "nie:contentCreated", }, { .spotlight_attr = "kMDItemContentModificationDate", .type = ssmt_date, .sparql_attr = "nfo:fileLastModified", }, { .spotlight_attr = "kMDItemAttributeChangeDate", .type = ssmt_date, .sparql_attr = "nfo:fileLastModified", }, { .spotlight_attr = "kMDItemAuthors", .type = ssmt_str, .sparql_attr = "dc:creator", }, { .spotlight_attr = "kMDItemCopyright", .type = ssmt_str, .sparql_attr = "nie:copyright", }, { .spotlight_attr = "kMDItemCountry", .type = ssmt_str, .sparql_attr = "nco:country", }, { .spotlight_attr = "kMDItemCreator", .type = ssmt_str, .sparql_attr = "dc:creator", }, { .spotlight_attr = "kMDItemDurationSeconds", .type = ssmt_num, .sparql_attr = "nfo:duration", }, { .spotlight_attr = "kMDItemNumberOfPages", .type = ssmt_num, .sparql_attr = "nfo:pageCount", }, { .spotlight_attr = "kMDItemTitle", .type = ssmt_str, .sparql_attr = "nie:title", }, { .spotlight_attr = "kMDItemCity", .type = ssmt_str, .sparql_attr = "nco:locality", }, { .spotlight_attr = "kMDItemCoverage", .type = ssmt_str, .sparql_attr = "nco:locality", }, { .spotlight_attr = "_kMDItemGroupId", .type = ssmt_type, .sparql_attr = NULL, }, { .spotlight_attr = "kMDItemContentTypeTree", .type = ssmt_type, .sparql_attr = NULL, }, { .spotlight_attr = "kMDItemContentType", .type = ssmt_type, .sparql_attr = NULL, }, /* Image metadata */ { .spotlight_attr = "kMDItemPixelWidth", .type = ssmt_num, .sparql_attr = "nfo:width", }, { .spotlight_attr = "kMDItemPixelHeight", .type = ssmt_num, .sparql_attr = "nfo:height", }, { .spotlight_attr = "kMDItemColorSpace", .type = ssmt_str, .sparql_attr = "nexif:colorSpace", }, { .spotlight_attr = "kMDItemBitsPerSample", .type = ssmt_num, .sparql_attr = "nfo:colorDepth", }, { .spotlight_attr = "kMDItemFocalLength", .type = ssmt_num, .sparql_attr = "nmm:focalLength", }, { .spotlight_attr = "kMDItemISOSpeed", .type = ssmt_num, .sparql_attr = "nmm:isoSpeed", }, { .spotlight_attr = "kMDItemOrientation", .type = ssmt_bool, .sparql_attr = "nfo:orientation", }, { .spotlight_attr = "kMDItemResolutionWidthDPI", .type = ssmt_num, .sparql_attr = "nfo:horizontalResolution", }, { .spotlight_attr = "kMDItemResolutionHeightDPI", .type = ssmt_num, .sparql_attr = "nfo:verticalResolution", }, { .spotlight_attr = "kMDItemExposureTimeSeconds", .type = ssmt_num, .sparql_attr = "nmm:exposureTime", }, /* Audio metadata */ { .spotlight_attr = "kMDItemComposer", .type = ssmt_str, .sparql_attr = "nmm:composer", }, { .spotlight_attr = "kMDItemMusicalGenre", .type = ssmt_str, .sparql_attr = "nfo:genre", }, }; size_t i; for (i = 0; i < ARRAY_SIZE(spotlight_sparql_attr_map); i++) { const struct sl_attr_map *m = &spotlight_sparql_attr_map[i]; int cmp; cmp = strcmp(m->spotlight_attr, sl_attr); if (cmp == 0) { return m; } } return NULL; } const struct sl_type_map *sl_type_map_by_spotlight(const char *sl_type) { static const struct sl_type_map spotlight_sparql_type_map[] = { { .spotlight_type = "1", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nmo#Email", }, { .spotlight_type = "2", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nco#Contact", }, { .spotlight_type = "3", .type = kMDTypeMapNotSup, .sparql_type = NULL, /*PrefPane*/ }, { .spotlight_type = "4", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Font", }, { .spotlight_type = "5", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Bookmark", }, { .spotlight_type = "6", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nco#Contact", }, { .spotlight_type = "7", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Video", }, { .spotlight_type = "8", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Executable", }, { .spotlight_type = "9", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Folder", }, { .spotlight_type = "10", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Audio", }, { .spotlight_type = "11", .type = kMDTypeMapMime, .sparql_type = "application/pdf", }, { .spotlight_type = "12", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Presentation", }, { .spotlight_type = "13", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Image", }, { .spotlight_type = "public.jpeg", .type = kMDTypeMapMime, .sparql_type = "image/jpeg", }, { .spotlight_type = "public.tiff", .type = kMDTypeMapMime, .sparql_type = "image/tiff", }, { .spotlight_type = "com.compuserve.gif", .type = kMDTypeMapMime, .sparql_type = "image/gif", }, { .spotlight_type = "public.png", .type = kMDTypeMapMime, .sparql_type = "image/png", }, { .spotlight_type = "com.microsoft.bmp", .type = kMDTypeMapMime, .sparql_type = "image/bmp", }, { .spotlight_type = "public.content", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Document", }, { .spotlight_type = "public.mp3", .type = kMDTypeMapMime, .sparql_type = "audio/mpeg", }, { .spotlight_type = "public.mpeg-4-audio", .type = kMDTypeMapMime, .sparql_type = "audio/x-aac", }, { .spotlight_type = "com.apple.application", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Software", }, { .spotlight_type = "public.text", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#TextDocument", }, { .spotlight_type = "public.plain-text", .type = kMDTypeMapMime, .sparql_type = "text/plain", }, { .spotlight_type = "public.rtf", .type = kMDTypeMapMime, .sparql_type = "text/rtf", }, { .spotlight_type = "public.html", .type = kMDTypeMapMime, .sparql_type = "text/html", }, { .spotlight_type = "public.xml", .type = kMDTypeMapMime, .sparql_type = "text/xml", }, { .spotlight_type = "public.source-code", .type = kMDTypeMapRDF, .sparql_type = "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#SourceCode", }, }; size_t i; for (i = 0; i < ARRAY_SIZE(spotlight_sparql_type_map); i++) { const struct sl_type_map *m = &spotlight_sparql_type_map[i]; int cmp; cmp = strcmp(m->spotlight_type, sl_type); if (cmp == 0) { return m; } } return NULL; }
gpl-3.0