code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<HTML> <CENTER><A HREF = "http://lammps.sandia.gov">LAMMPS WWW Site</A> - <A HREF = "Manual.html">LAMMPS Documentation</A> - <A HREF = "Section_commands.html#comm">LAMMPS Commands</A> </CENTER> <HR> <H3>compute rdf command </H3> <P><B>Syntax:</B> </P> <PRE>compute ID group-ID rdf Nbin itype1 jtype1 itype2 jtype2 ... </PRE> <UL><LI>ID, group-ID are documented in <A HREF = "compute.html">compute</A> command <LI>rdf = style name of this compute command <LI>Nbin = number of RDF bins <LI>itypeN = central atom type for Nth RDF histogram (see asterisk form below) <LI>jtypeN = distribution atom type for Nth RDF histogram (see asterisk form below) </UL> <P><B>Examples:</B> </P> <PRE>compute 1 all rdf 100 compute 1 all rdf 100 1 1 compute 1 all rdf 100 * 3 compute 1 fluid rdf 500 1 1 1 2 2 1 2 2 compute 1 fluid rdf 500 1*3 2 5 *10 </PRE> <P><B>Description:</B> </P> <P>Define a computation that calculates the radial distribution function (RDF), also called g(r), and the coordination number for a group of particles. Both are calculated in histogram form by binning pairwise distances into <I>Nbin</I> bins from 0.0 to the maximum force cutoff defined by the <A HREF = "pair_style.html">pair_style</A> command. The bins are of uniform size in radial distance. Thus a single bin encompasses a thin shell of distances in 3d and a thin ring of distances in 2d. </P> <P>IMPORTANT NOTE: If you have a bonded system, then the settings of <A HREF = "special_bonds.html">special_bonds</A> command can remove pairwise interactions between atoms in the same bond, angle, or dihedral. This is the default setting for the <A HREF = "special_bonds.html">special_bonds</A> command, and means those pairwise interactions do not appear in the neighbor list. Because this fix uses the neighbor list, it also means those pairs will not be included in the RDF. One way to get around this, is to write a dump file, and use the <A HREF = "rerun.html">rerun</A> command to compute the RDF for snapshots in the dump file. The rerun script can use a <A HREF = "special_bonds.html">special_bonds</A> command that includes all pairs in the neighbor list. </P> <P>The <I>itypeN</I> and <I>jtypeN</I> arguments are optional. These arguments must come in pairs. If no pairs are listed, then a single histogram is computed for g(r) between all atom types. If one or more pairs are listed, then a separate histogram is generated for each <I>itype</I>,<I>jtype</I> pair. </P> <P>The <I>itypeN</I> and <I>jtypeN</I> settings can be specified in one of two ways. An explicit numeric value can be used, as in the 4th example above. Or a wild-card asterisk can be used to specify a range of atom types. This takes the form "*" or "*n" or "n*" or "m*n". If N = the number of atom types, then an asterisk with no numeric values means all types from 1 to N. A leading asterisk means all types from 1 to n (inclusive). A trailing asterisk means all types from n to N (inclusive). A middle asterisk means all types from m to n (inclusive). </P> <P>If both <I>itypeN</I> and <I>jtypeN</I> are single values, as in the 4th example above, this means that a g(r) is computed where atoms of type <I>itypeN</I> are the central atom, and atoms of type <I>jtypeN</I> are the distribution atom. If either <I>itypeN</I> and <I>jtypeN</I> represent a range of values via the wild-card asterisk, as in the 5th example above, this means that a g(r) is computed where atoms of any of the range of types represented by <I>itypeN</I> are the central atom, and atoms of any of the range of types represented by <I>jtypeN</I> are the distribution atom. </P> <P>Pairwise distances are generated by looping over a pairwise neighbor list, just as they would be in a <A HREF = "pair_style.html">pair_style</A> computation. The distance between two atoms I and J is included in a specific histogram if the following criteria are met: </P> <UL><LI>atoms I,J are both in the specified compute group <LI>the distance between atoms I,J is less than the maximum force cutoff <LI>the type of the I atom matches itypeN (one or a range of types) <LI>the type of the J atom matches jtypeN (one or a range of types) </UL> <P>It is OK if a particular pairwise distance is included in more than one individual histogram, due to the way the <I>itypeN</I> and <I>jtypeN</I> arguments are specified. </P> <P>The g(r) value for a bin is calculated from the histogram count by scaling it by the idealized number of how many counts there would be if atoms of type <I>jtypeN</I> were uniformly distributed. Thus it involves the count of <I>itypeN</I> atoms, the count of <I>jtypeN</I> atoms, the volume of the entire simulation box, and the volume of the bin's thin shell in 3d (or the area of the bin's thin ring in 2d). </P> <P>A coordination number coord(r) is also calculated, which is the number of atoms of type <I>jtypeN</I> within the current bin or closer, averaged over atoms of type <I>itypeN</I>. This is calculated as the area- or volume-weighted sum of g(r) values over all bins up to and including the current bin, multiplied by the global average volume density of atoms of type jtypeN. </P> <P>The simplest way to output the results of the compute rdf calculation to a file is to use the <A HREF = "fix_ave_time.html">fix ave/time</A> command, for example: </P> <PRE>compute myRDF all rdf 50 fix 1 all ave/time 100 1 100 c_myRDF file tmp.rdf mode vector </PRE> <P><B>Output info:</B> </P> <P>This compute calculates a global array with the number of rows = <I>Nbins</I>, and the number of columns = 1 + 2*Npairs, where Npairs is the number of I,J pairings specified. The first column has the bin coordinate (center of the bin), Each successive set of 2 columns has the g(r) and coord(r) values for a specific set of <I>itypeN</I> versus <I>jtypeN</I> interactions, as described above. These values can be used by any command that uses a global values from a compute as input. See <A HREF = "Section_howto.html#howto_15">Section_howto 15</A> for an overview of LAMMPS output options. </P> <P>The array values calculated by this compute are all "intensive". </P> <P>The first column of array values will be in distance <A HREF = "units.html">units</A>. The g(r) columns of array values are normalized numbers >= 0.0. The coordination number columns of array values are also numbers >= 0.0. </P> <P><B>Restrictions:</B> </P> <P>The RDF is not computed for distances longer than the force cutoff, since processors (in parallel) don't know about atom coordinates for atoms further away than that distance. If you want an RDF for larger distances, you can use the <A HREF = "rerun.html">rerun</A> command to post-process a dump file. The definition of g(r) used by LAMMPS is only appropriate for characterizing atoms that are uniformly distributed throughout the simulation cell. In such cases, the coordination number is still correct and meaningful. As an example, if a large simulation cell contains only one atom of type <I>itypeN</I> and one of <I>jtypeN</I>, then g(r) will register an arbitrarily large spike at whatever distance they happen to be at, and zero everywhere else. coord(r) will show a step change from zero to one at the location of the spike in g(r). </P> <P><B>Related commands:</B> </P> <P><A HREF = "fix_ave_time.html">fix ave/time</A> </P> <P><B>Default:</B> none </P> </HTML>
qipa/lammps
doc/doc2/compute_rdf.html
HTML
gpl-2.0
7,377
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef TITANIC_PHONOGRAPH_EAR_H #define TITANIC_PHONOGRAPH_EAR_H #include "titanic/carry/ear.h" namespace Titanic { class CPhonographEar : public CEar { DECLARE_MESSAGE_MAP; bool CorrectMusicPlayedMsg(CCorrectMusicPlayedMsg *msg); bool PETGainedObjectMsg(CPETGainedObjectMsg *msg); bool TimerMsg(CTimerMsg *msg); private: bool _replacementEar; public: CLASSDEF; CPhonographEar() : CEar(), _replacementEar(true) {} /** * Save the data for the class to file */ virtual void save(SimpleFile *file, int indent); /** * Load the data for the class from file */ virtual void load(SimpleFile *file); }; } // End of namespace Titanic #endif /* TITANIC_PHONOGRAPH_EYE_H */
alexbevi/scummvm
engines/titanic/carry/phonograph_ear.h
C
gpl-2.0
1,639
/* * Copyright (C) 2010-2011 Freescale Semiconductor, Inc. * * Configuration settings for the MX53-LOCO Freescale board. * * 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 */ #ifndef __CONFIG_H #define __CONFIG_H #include <asm/arch/mx53.h> /* High Level Configuration Options */ #define CONFIG_ARMV7 /* This is armv7 Cortex-A8 CPU core */ #define CONFIG_MXC #define CONFIG_MX53 #define CONFIG_MX53_LOCO #define CONFIG_FLASH_HEADER #define CONFIG_FLASH_HEADER_OFFSET 0x400 #define CONFIG_MX53_CLK32 32768 #define CONFIG_SKIP_RELOCATE_UBOOT #define CONFIG_ARCH_CPU_INIT #define CONFIG_ARCH_MMU #define CONFIG_MX53_HCLK_FREQ 24000000 #define CONFIG_SYS_PLL2_FREQ 400 #define CONFIG_SYS_AHB_PODF 2 #define CONFIG_SYS_AXIA_PODF 0 #define CONFIG_SYS_AXIB_PODF 1 #define CONFIG_DISPLAY_CPUINFO #define CONFIG_DISPLAY_BOARDINFO #define CONFIG_SYS_64BIT_VSPRINTF #define BOARD_LATE_INIT /* * Disabled for now due to build problems under Debian and a significant * increase in the final file size: 144260 vs. 109536 Bytes. */ #define CONFIG_CMDLINE_TAG 1 /* enable passing of ATAGs */ #define CONFIG_REVISION_TAG 1 #define CONFIG_SETUP_MEMORY_TAGS 1 #define CONFIG_INITRD_TAG 1 /* * Size of malloc() pool */ #define CONFIG_SYS_MALLOC_LEN (3 * 1024 * 1024) /* size in bytes reserved for initial data */ #define CONFIG_SYS_GBL_DATA_SIZE 128 /* * Hardware drivers */ #define CONFIG_MXC_UART 1 #define CONFIG_UART_BASE_ADDR UART1_BASE_ADDR /* allow to overwrite serial and ethaddr */ #define CONFIG_ENV_OVERWRITE #define CONFIG_CONS_INDEX 1 #define CONFIG_BAUDRATE 115200 #define CONFIG_SYS_BAUDRATE_TABLE {9600, 19200, 38400, 57600, 115200} /*********************************************************** * Command definition ***********************************************************/ #include <config_cmd_default.h> #define CONFIG_CMD_PING #define CONFIG_CMD_DHCP #define CONFIG_CMD_MII #define CONFIG_CMD_NET #define CONFIG_NET_RETRY_COUNT 100 #define CONFIG_NET_MULTI 1 #define CONFIG_BOOTP_SUBNETMASK #define CONFIG_BOOTP_GATEWAY #define CONFIG_BOOTP_DNS #define CONFIG_CMD_MMC #define CONFIG_CMD_ENV #define CONFIG_CMD_IIM #define CONFIG_CMD_CLOCK #define CONFIG_REF_CLK_FREQ CONFIG_MX53_HCLK_FREQ #define CONFIG_CMD_SATA #undef CONFIG_CMD_IMLS #define CONFIG_BOOTDELAY 3 #define CONFIG_PRIME "FEC0" #define CONFIG_LOADADDR 0x70800000 /* loadaddr env var */ #define CONFIG_RD_LOADADDR (CONFIG_LOADADDR + 0x300000) #define CONFIG_EXTRA_ENV_SETTINGS \ "netdev=eth0\0" \ "ethprime=FEC0\0" \ "uboot=u-boot.bin\0" \ "kernel=uImage\0" \ "nfsroot=/opt/eldk/arm\0" \ "bootargs_base=setenv bootargs console=ttymxc0,115200\0"\ "bootargs_nfs=setenv bootargs ${bootargs} root=/dev/nfs "\ "ip=dhcp nfsroot=${serverip}:${nfsroot},v3,tcp\0"\ "bootcmd_net=run bootargs_base bootargs_nfs; " \ "tftpboot ${loadaddr} ${kernel}; bootm\0" \ "bootargs_mmc=setenv bootargs ${bootargs} ip=dhcp " \ "root=/dev/mmcblk0p1 rootwait rw\0" \ "bootcmd_mmc=run bootargs_base bootargs_mmc; " \ "mmc dev 0; " \ "mmc read ${loadaddr} 0x800 0x1800; bootm\0" \ "bootcmd=run bootcmd_mmc\0" \ \ #define CONFIG_ARP_TIMEOUT 200UL /* * Miscellaneous configurable options */ #define CONFIG_SYS_LONGHELP /* undef to save memory */ #define CONFIG_SYS_PROMPT "MX53-LOCO U-Boot > " #define CONFIG_AUTO_COMPLETE #define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */ /* Print Buffer Size */ #define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE + sizeof(CONFIG_SYS_PROMPT) + 16) #define CONFIG_SYS_MAXARGS 16 /* max number of command args */ #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* Boot Argument Buffer Size */ #define CONFIG_SYS_MEMTEST_START 0 /* memtest works on */ #define CONFIG_SYS_MEMTEST_END 0x10000 #undef CONFIG_SYS_CLKS_IN_HZ /* everything, incl board info, in Hz */ #define CONFIG_SYS_LOAD_ADDR CONFIG_LOADADDR #define CONFIG_SYS_HZ 1000 #define CONFIG_CMDLINE_EDITING 1 #define CONFIG_FEC0_IOBASE FEC_BASE_ADDR #define CONFIG_FEC0_PINMUX -1 #define CONFIG_FEC0_PHY_ADDR -1 #define CONFIG_FEC0_MIIBASE -1 #define CONFIG_GET_FEC_MAC_ADDR_FROM_IIM #define CONFIG_IIM_MAC_ADDR_OFFSET 0x24 #define CONFIG_MXC_FEC #define CONFIG_MII #define CONFIG_MII_GASKET #define CONFIG_DISCOVER_PHY /* * FUSE Configs * */ #ifdef CONFIG_CMD_IIM #define CONFIG_IMX_IIM #define IMX_IIM_BASE IIM_BASE_ADDR #define CONFIG_IIM_MAC_BANK 1 #define CONFIG_IIM_MAC_ROW 9 #endif /* * I2C Configs */ #define CONFIG_CMD_I2C 1 #define CONFIG_HARD_I2C 1 #define CONFIG_I2C_MXC 1 #define CONFIG_SYS_I2C_PORT I2C1_BASE_ADDR #define CONFIG_SYS_I2C_SPEED 100000 #define CONFIG_SYS_I2C_SLAVE 0xfe /* * MMC Configs */ #ifdef CONFIG_CMD_MMC #define CONFIG_MMC 1 #define CONFIG_GENERIC_MMC #define CONFIG_IMX_MMC #define CONFIG_SYS_FSL_ESDHC_NUM 2 #define CONFIG_SYS_FSL_ESDHC_ADDR 0 #define CONFIG_SYS_MMC_ENV_DEV 0 #define CONFIG_DOS_PARTITION 1 #define CONFIG_CMD_FAT 1 #define CONFIG_CMD_EXT2 1 /* detect whether ESDHC1 or ESDHC3 is boot device */ #define CONFIG_DYNAMIC_MMC_DEVNO #define CONFIG_EMMC_DDR_PORT_DETECT #define CONFIG_EMMC_DDR_MODE /* port 1 (ESDHC3) is 8 bit */ #define CONFIG_MMC_8BIT_PORTS 0x2 #endif /* * SATA Configs */ #ifdef CONFIG_CMD_SATA #define CONFIG_DWC_AHSATA #define CONFIG_SYS_SATA_MAX_DEVICE 1 #define CONFIG_DWC_AHSATA_PORT_ID 0 #define CONFIG_DWC_AHSATA_BASE_ADDR SATA_BASE_ADDR #define CONFIG_LBA48 #define CONFIG_LIBATA #endif /*----------------------------------------------------------------------- * Stack sizes * * The stack sizes are set up in start.S using the settings below */ #define CONFIG_STACKSIZE (128 * 1024) /* regular stack */ /*----------------------------------------------------------------------- * Physical Memory Map */ #define CONFIG_NR_DRAM_BANKS 2 #define PHYS_SDRAM_1 CSD0_BASE_ADDR #define PHYS_SDRAM_1_SIZE (512 * 1024 * 1024) #define PHYS_SDRAM_2 CSD1_BASE_ADDR #define PHYS_SDRAM_2_SIZE (512 * 1024 * 1024) #define iomem_valid_addr(addr, size) \ ((addr >= PHYS_SDRAM_1 && addr <= (PHYS_SDRAM_1 + PHYS_SDRAM_1_SIZE)) \ || (addr >= PHYS_SDRAM_2 && addr <= (PHYS_SDRAM_2 + PHYS_SDRAM_2_SIZE))) /*----------------------------------------------------------------------- * FLASH and environment organization */ #define CONFIG_SYS_NO_FLASH /* Monitor at beginning of flash */ #define CONFIG_FSL_ENV_IN_MMC /* #define CONFIG_FSL_ENV_IN_SATA */ #define CONFIG_ENV_SECT_SIZE (8 * 1024) #define CONFIG_ENV_SIZE CONFIG_ENV_SECT_SIZE #if defined(CONFIG_FSL_ENV_IN_NAND) #define CONFIG_ENV_IS_IN_NAND 1 #define CONFIG_ENV_OFFSET 0x200000 #elif defined(CONFIG_FSL_ENV_IN_MMC) #define CONFIG_ENV_IS_IN_MMC 1 #define CONFIG_ENV_OFFSET (768 * 1024) #elif defined(CONFIG_FSL_ENV_IN_SATA) #define CONFIG_ENV_IS_IN_SATA 1 #define CONFIG_SATA_ENV_DEV 0 #define CONFIG_ENV_OFFSET (768 * 1024) #elif defined(CONFIG_FSL_ENV_IN_SF) #define CONFIG_ENV_IS_IN_SPI_FLASH 1 #define CONFIG_ENV_SPI_CS 1 #define CONFIG_ENV_OFFSET (768 * 1024) #else #define CONFIG_ENV_IS_NOWHERE 1 #endif #endif /* __CONFIG_H */
fwmiller/Conserver-Freescale-Linux-U-boot
rpm/BUILD/u-boot-2009.08/include/configs/mx53_loco.h
C
gpl-2.0
7,903
/* * linux/mm/vmscan.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds * * Swap reorganised 29.12.95, Stephen Tweedie. * kswapd added: 7.1.96 sct * Removed kswapd_ctl limits, and swap out as many pages as needed * to bring the system back to freepages.high: 2.4.97, Rik van Riel. * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com). * Multiqueue VM started 5.8.00, Rik van Riel. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/mm.h> #include <linux/module.h> #include <linux/gfp.h> #include <linux/kernel_stat.h> #include <linux/swap.h> #include <linux/pagemap.h> #include <linux/init.h> #include <linux/highmem.h> #include <linux/vmpressure.h> #include <linux/vmstat.h> #include <linux/file.h> #include <linux/writeback.h> #include <linux/blkdev.h> #include <linux/buffer_head.h> /* for try_to_release_page(), buffer_heads_over_limit */ #include <linux/mm_inline.h> #include <linux/backing-dev.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/compaction.h> #include <linux/notifier.h> #include <linux/rwsem.h> #include <linux/delay.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/memcontrol.h> #include <linux/delayacct.h> #include <linux/sysctl.h> #include <linux/oom.h> #include <linux/prefetch.h> #include <linux/printk.h> #include <asm/tlbflush.h> #include <asm/div64.h> #include <linux/swapops.h> #include <linux/balloon_compaction.h> #include "internal.h" #define CREATE_TRACE_POINTS #include <trace/events/vmscan.h> struct scan_control { /* How many pages shrink_list() should reclaim */ unsigned long nr_to_reclaim; /* This context's GFP mask */ gfp_t gfp_mask; /* Allocation order */ int order; /* * Nodemask of nodes allowed by the caller. If NULL, all nodes * are scanned. */ nodemask_t *nodemask; /* * The memory cgroup that hit its limit and as a result is the * primary target of this reclaim invocation. */ struct mem_cgroup *target_mem_cgroup; /* Scan (total_size >> priority) pages at once */ int priority; unsigned int may_writepage:1; /* Can mapped pages be reclaimed? */ unsigned int may_unmap:1; /* Can pages be swapped as part of reclaim? */ unsigned int may_swap:1; /* Can cgroups be reclaimed below their normal consumption range? */ unsigned int may_thrash:1; unsigned int hibernation_mode:1; /* One of the zones is ready for compaction */ unsigned int compaction_ready:1; /* Incremented by the number of inactive pages that were scanned */ unsigned long nr_scanned; /* Number of pages freed so far during a call to shrink_zones() */ unsigned long nr_reclaimed; }; #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru)) #ifdef ARCH_HAS_PREFETCH #define prefetch_prev_lru_page(_page, _base, _field) \ do { \ if ((_page)->lru.prev != _base) { \ struct page *prev; \ \ prev = lru_to_page(&(_page->lru)); \ prefetch(&prev->_field); \ } \ } while (0) #else #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0) #endif #ifdef ARCH_HAS_PREFETCHW #define prefetchw_prev_lru_page(_page, _base, _field) \ do { \ if ((_page)->lru.prev != _base) { \ struct page *prev; \ \ prev = lru_to_page(&(_page->lru)); \ prefetchw(&prev->_field); \ } \ } while (0) #else #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0) #endif /* * From 0 .. 100. Higher means more swappy. */ int vm_swappiness = 60; /* * The total number of pages which are beyond the high watermark within all * zones. */ unsigned long vm_total_pages; static LIST_HEAD(shrinker_list); static DECLARE_RWSEM(shrinker_rwsem); #ifdef CONFIG_MEMCG static bool global_reclaim(struct scan_control *sc) { return !sc->target_mem_cgroup; } /** * sane_reclaim - is the usual dirty throttling mechanism operational? * @sc: scan_control in question * * The normal page dirty throttling mechanism in balance_dirty_pages() is * completely broken with the legacy memcg and direct stalling in * shrink_page_list() is used for throttling instead, which lacks all the * niceties such as fairness, adaptive pausing, bandwidth proportional * allocation and configurability. * * This function tests whether the vmscan currently in progress can assume * that the normal dirty throttling mechanism is operational. */ static bool sane_reclaim(struct scan_control *sc) { struct mem_cgroup *memcg = sc->target_mem_cgroup; if (!memcg) return true; #ifdef CONFIG_CGROUP_WRITEBACK if (cgroup_on_dfl(mem_cgroup_css(memcg)->cgroup)) return true; #endif return false; } #else static bool global_reclaim(struct scan_control *sc) { return true; } static bool sane_reclaim(struct scan_control *sc) { return true; } #endif static unsigned long zone_reclaimable_pages(struct zone *zone) { int nr; nr = zone_page_state(zone, NR_ACTIVE_FILE) + zone_page_state(zone, NR_INACTIVE_FILE); if (get_nr_swap_pages() > 0) nr += zone_page_state(zone, NR_ACTIVE_ANON) + zone_page_state(zone, NR_INACTIVE_ANON); return nr; } bool zone_reclaimable(struct zone *zone) { return zone_page_state(zone, NR_PAGES_SCANNED) < zone_reclaimable_pages(zone) * 6; } static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru) { if (!mem_cgroup_disabled()) return mem_cgroup_get_lru_size(lruvec, lru); return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru); } /* * Add a shrinker callback to be called from the vm. */ int register_shrinker(struct shrinker *shrinker) { size_t size = sizeof(*shrinker->nr_deferred); /* * If we only have one possible node in the system anyway, save * ourselves the trouble and disable NUMA aware behavior. This way we * will save memory and some small loop time later. */ if (nr_node_ids == 1) shrinker->flags &= ~SHRINKER_NUMA_AWARE; if (shrinker->flags & SHRINKER_NUMA_AWARE) size *= nr_node_ids; shrinker->nr_deferred = kzalloc(size, GFP_KERNEL); if (!shrinker->nr_deferred) return -ENOMEM; down_write(&shrinker_rwsem); list_add_tail(&shrinker->list, &shrinker_list); up_write(&shrinker_rwsem); return 0; } EXPORT_SYMBOL(register_shrinker); /* * Remove one */ void unregister_shrinker(struct shrinker *shrinker) { down_write(&shrinker_rwsem); list_del(&shrinker->list); up_write(&shrinker_rwsem); kfree(shrinker->nr_deferred); } EXPORT_SYMBOL(unregister_shrinker); #define SHRINK_BATCH 128 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl, struct shrinker *shrinker, unsigned long nr_scanned, unsigned long nr_eligible) { unsigned long freed = 0; unsigned long long delta; long total_scan; long freeable; long nr; long new_nr; int nid = shrinkctl->nid; long batch_size = shrinker->batch ? shrinker->batch : SHRINK_BATCH; freeable = shrinker->count_objects(shrinker, shrinkctl); if (freeable == 0) return 0; /* * copy the current shrinker scan count into a local variable * and zero it so that other concurrent shrinker invocations * don't also do this scanning work. */ nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0); total_scan = nr; delta = (4 * nr_scanned) / shrinker->seeks; delta *= freeable; do_div(delta, nr_eligible + 1); total_scan += delta; if (total_scan < 0) { pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n", shrinker->scan_objects, total_scan); total_scan = freeable; } /* * We need to avoid excessive windup on filesystem shrinkers * due to large numbers of GFP_NOFS allocations causing the * shrinkers to return -1 all the time. This results in a large * nr being built up so when a shrink that can do some work * comes along it empties the entire cache due to nr >>> * freeable. This is bad for sustaining a working set in * memory. * * Hence only allow the shrinker to scan the entire cache when * a large delta change is calculated directly. */ if (delta < freeable / 4) total_scan = min(total_scan, freeable / 2); /* * Avoid risking looping forever due to too large nr value: * never try to free more than twice the estimate number of * freeable entries. */ if (total_scan > freeable * 2) total_scan = freeable * 2; trace_mm_shrink_slab_start(shrinker, shrinkctl, nr, nr_scanned, nr_eligible, freeable, delta, total_scan); /* * Normally, we should not scan less than batch_size objects in one * pass to avoid too frequent shrinker calls, but if the slab has less * than batch_size objects in total and we are really tight on memory, * we will try to reclaim all available objects, otherwise we can end * up failing allocations although there are plenty of reclaimable * objects spread over several slabs with usage less than the * batch_size. * * We detect the "tight on memory" situations by looking at the total * number of objects we want to scan (total_scan). If it is greater * than the total number of objects on slab (freeable), we must be * scanning at high prio and therefore should try to reclaim as much as * possible. */ while (total_scan >= batch_size || total_scan >= freeable) { unsigned long ret; unsigned long nr_to_scan = min(batch_size, total_scan); shrinkctl->nr_to_scan = nr_to_scan; ret = shrinker->scan_objects(shrinker, shrinkctl); if (ret == SHRINK_STOP) break; freed += ret; count_vm_events(SLABS_SCANNED, nr_to_scan); total_scan -= nr_to_scan; cond_resched(); } /* * move the unused scan count back into the shrinker in a * manner that handles concurrent updates. If we exhausted the * scan, there is no need to do an update. */ if (total_scan > 0) new_nr = atomic_long_add_return(total_scan, &shrinker->nr_deferred[nid]); else new_nr = atomic_long_read(&shrinker->nr_deferred[nid]); trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan); return freed; } /** * shrink_slab - shrink slab caches * @gfp_mask: allocation context * @nid: node whose slab caches to target * @memcg: memory cgroup whose slab caches to target * @nr_scanned: pressure numerator * @nr_eligible: pressure denominator * * Call the shrink functions to age shrinkable caches. * * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set, * unaware shrinkers will receive a node id of 0 instead. * * @memcg specifies the memory cgroup to target. If it is not NULL, * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan * objects from the memory cgroup specified. Otherwise all shrinkers * are called, and memcg aware shrinkers are supposed to scan the * global list then. * * @nr_scanned and @nr_eligible form a ratio that indicate how much of * the available objects should be scanned. Page reclaim for example * passes the number of pages scanned and the number of pages on the * LRU lists that it considered on @nid, plus a bias in @nr_scanned * when it encountered mapped pages. The ratio is further biased by * the ->seeks setting of the shrink function, which indicates the * cost to recreate an object relative to that of an LRU page. * * Returns the number of reclaimed slab objects. */ static unsigned long shrink_slab(gfp_t gfp_mask, int nid, struct mem_cgroup *memcg, unsigned long nr_scanned, unsigned long nr_eligible) { struct shrinker *shrinker; unsigned long freed = 0; if (memcg && !memcg_kmem_is_active(memcg)) return 0; if (nr_scanned == 0) nr_scanned = SWAP_CLUSTER_MAX; if (!down_read_trylock(&shrinker_rwsem)) { /* * If we would return 0, our callers would understand that we * have nothing else to shrink and give up trying. By returning * 1 we keep it going and assume we'll be able to shrink next * time. */ freed = 1; goto out; } list_for_each_entry(shrinker, &shrinker_list, list) { struct shrink_control sc = { .gfp_mask = gfp_mask, .nid = nid, .memcg = memcg, }; if (memcg && !(shrinker->flags & SHRINKER_MEMCG_AWARE)) continue; if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) sc.nid = 0; freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible); } up_read(&shrinker_rwsem); out: cond_resched(); return freed; } void drop_slab_node(int nid) { unsigned long freed; do { struct mem_cgroup *memcg = NULL; freed = 0; do { freed += shrink_slab(GFP_KERNEL, nid, memcg, 1000, 1000); } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL); } while (freed > 10); } void drop_slab(void) { int nid; for_each_online_node(nid) drop_slab_node(nid); } static inline int is_page_cache_freeable(struct page *page) { /* * A freeable page cache page is referenced only by the caller * that isolated the page, the page cache radix tree and * optional buffer heads at page->private. */ return page_count(page) - page_has_private(page) == 2; } static int may_write_to_inode(struct inode *inode, struct scan_control *sc) { if (current->flags & PF_SWAPWRITE) return 1; if (!inode_write_congested(inode)) return 1; if (inode_to_bdi(inode) == current->backing_dev_info) return 1; return 0; } /* * We detected a synchronous write error writing a page out. Probably * -ENOSPC. We need to propagate that into the address_space for a subsequent * fsync(), msync() or close(). * * The tricky part is that after writepage we cannot touch the mapping: nothing * prevents it from being freed up. But we have a ref on the page and once * that page is locked, the mapping is pinned. * * We're allowed to run sleeping lock_page() here because we know the caller has * __GFP_FS. */ static void handle_write_error(struct address_space *mapping, struct page *page, int error) { lock_page(page); if (page_mapping(page) == mapping) mapping_set_error(mapping, error); unlock_page(page); } /* possible outcome of pageout() */ typedef enum { /* failed to write page out, page is locked */ PAGE_KEEP, /* move page to the active list, page is locked */ PAGE_ACTIVATE, /* page has been sent to the disk successfully, page is unlocked */ PAGE_SUCCESS, /* page is clean and locked */ PAGE_CLEAN, } pageout_t; /* * pageout is called by shrink_page_list() for each dirty page. * Calls ->writepage(). */ static pageout_t pageout(struct page *page, struct address_space *mapping, struct scan_control *sc) { /* * If the page is dirty, only perform writeback if that write * will be non-blocking. To prevent this allocation from being * stalled by pagecache activity. But note that there may be * stalls if we need to run get_block(). We could test * PagePrivate for that. * * If this process is currently in __generic_file_write_iter() against * this page's queue, we can perform writeback even if that * will block. * * If the page is swapcache, write it back even if that would * block, for some throttling. This happens by accident, because * swap_backing_dev_info is bust: it doesn't reflect the * congestion state of the swapdevs. Easy to fix, if needed. */ if (!is_page_cache_freeable(page)) return PAGE_KEEP; if (!mapping) { /* * Some data journaling orphaned pages can have * page->mapping == NULL while being dirty with clean buffers. */ if (page_has_private(page)) { if (try_to_free_buffers(page)) { ClearPageDirty(page); pr_info("%s: orphaned page\n", __func__); return PAGE_CLEAN; } } return PAGE_KEEP; } if (mapping->a_ops->writepage == NULL) return PAGE_ACTIVATE; if (!may_write_to_inode(mapping->host, sc)) return PAGE_KEEP; if (clear_page_dirty_for_io(page)) { int res; struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = SWAP_CLUSTER_MAX, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1, }; SetPageReclaim(page); res = mapping->a_ops->writepage(page, &wbc); if (res < 0) handle_write_error(mapping, page, res); if (res == AOP_WRITEPAGE_ACTIVATE) { ClearPageReclaim(page); return PAGE_ACTIVATE; } if (!PageWriteback(page)) { /* synchronous write or broken a_ops? */ ClearPageReclaim(page); } trace_mm_vmscan_writepage(page, trace_reclaim_flags(page)); inc_zone_page_state(page, NR_VMSCAN_WRITE); return PAGE_SUCCESS; } return PAGE_CLEAN; } /* * Same as remove_mapping, but if the page is removed from the mapping, it * gets returned with a refcount of 0. */ static int __remove_mapping(struct address_space *mapping, struct page *page, bool reclaimed) { unsigned long flags; struct mem_cgroup *memcg; BUG_ON(!PageLocked(page)); BUG_ON(mapping != page_mapping(page)); memcg = mem_cgroup_begin_page_stat(page); spin_lock_irqsave(&mapping->tree_lock, flags); /* * The non racy check for a busy page. * * Must be careful with the order of the tests. When someone has * a ref to the page, it may be possible that they dirty it then * drop the reference. So if PageDirty is tested before page_count * here, then the following race may occur: * * get_user_pages(&page); * [user mapping goes away] * write_to(page); * !PageDirty(page) [good] * SetPageDirty(page); * put_page(page); * !page_count(page) [good, discard it] * * [oops, our write_to data is lost] * * Reversing the order of the tests ensures such a situation cannot * escape unnoticed. The smp_rmb is needed to ensure the page->flags * load is not satisfied before that of page->_count. * * Note that if SetPageDirty is always performed via set_page_dirty, * and thus under tree_lock, then this ordering is not required. */ if (!page_freeze_refs(page, 2)) goto cannot_free; /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */ if (unlikely(PageDirty(page))) { page_unfreeze_refs(page, 2); goto cannot_free; } if (PageSwapCache(page)) { swp_entry_t swap = { .val = page_private(page) }; mem_cgroup_swapout(page, swap); __delete_from_swap_cache(page); spin_unlock_irqrestore(&mapping->tree_lock, flags); mem_cgroup_end_page_stat(memcg); swapcache_free(swap); } else { void (*freepage)(struct page *); void *shadow = NULL; freepage = mapping->a_ops->freepage; /* * Remember a shadow entry for reclaimed file cache in * order to detect refaults, thus thrashing, later on. * * But don't store shadows in an address space that is * already exiting. This is not just an optizimation, * inode reclaim needs to empty out the radix tree or * the nodes are lost. Don't plant shadows behind its * back. */ if (reclaimed && page_is_file_cache(page) && !mapping_exiting(mapping)) shadow = workingset_eviction(mapping, page); __delete_from_page_cache(page, shadow, memcg); spin_unlock_irqrestore(&mapping->tree_lock, flags); mem_cgroup_end_page_stat(memcg); if (freepage != NULL) freepage(page); } return 1; cannot_free: spin_unlock_irqrestore(&mapping->tree_lock, flags); mem_cgroup_end_page_stat(memcg); return 0; } /* * Attempt to detach a locked page from its ->mapping. If it is dirty or if * someone else has a ref on the page, abort and return 0. If it was * successfully detached, return 1. Assumes the caller has a single ref on * this page. */ int remove_mapping(struct address_space *mapping, struct page *page) { if (__remove_mapping(mapping, page, false)) { /* * Unfreezing the refcount with 1 rather than 2 effectively * drops the pagecache ref for us without requiring another * atomic operation. */ page_unfreeze_refs(page, 1); return 1; } return 0; } /** * putback_lru_page - put previously isolated page onto appropriate LRU list * @page: page to be put back to appropriate lru list * * Add previously isolated @page to appropriate LRU list. * Page may still be unevictable for other reasons. * * lru_lock must not be held, interrupts must be enabled. */ void putback_lru_page(struct page *page) { bool is_unevictable; int was_unevictable = PageUnevictable(page); VM_BUG_ON_PAGE(PageLRU(page), page); redo: ClearPageUnevictable(page); if (page_evictable(page)) { /* * For evictable pages, we can use the cache. * In event of a race, worst case is we end up with an * unevictable page on [in]active list. * We know how to handle that. */ is_unevictable = false; lru_cache_add(page); } else { /* * Put unevictable pages directly on zone's unevictable * list. */ is_unevictable = true; add_page_to_unevictable_list(page); /* * When racing with an mlock or AS_UNEVICTABLE clearing * (page is unlocked) make sure that if the other thread * does not observe our setting of PG_lru and fails * isolation/check_move_unevictable_pages, * we see PG_mlocked/AS_UNEVICTABLE cleared below and move * the page back to the evictable list. * * The other side is TestClearPageMlocked() or shmem_lock(). */ smp_mb(); } /* * page's status can change while we move it among lru. If an evictable * page is on unevictable list, it never be freed. To avoid that, * check after we added it to the list, again. */ if (is_unevictable && page_evictable(page)) { if (!isolate_lru_page(page)) { put_page(page); goto redo; } /* This means someone else dropped this page from LRU * So, it will be freed or putback to LRU again. There is * nothing to do here. */ } if (was_unevictable && !is_unevictable) count_vm_event(UNEVICTABLE_PGRESCUED); else if (!was_unevictable && is_unevictable) count_vm_event(UNEVICTABLE_PGCULLED); put_page(page); /* drop ref from isolate */ } enum page_references { PAGEREF_RECLAIM, PAGEREF_RECLAIM_CLEAN, PAGEREF_KEEP, PAGEREF_ACTIVATE, }; static enum page_references page_check_references(struct page *page, struct scan_control *sc) { int referenced_ptes, referenced_page; unsigned long vm_flags; referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup, &vm_flags); referenced_page = TestClearPageReferenced(page); /* * Mlock lost the isolation race with us. Let try_to_unmap() * move the page to the unevictable list. */ if (vm_flags & VM_LOCKED) return PAGEREF_RECLAIM; if (referenced_ptes) { if (PageSwapBacked(page)) return PAGEREF_ACTIVATE; /* * All mapped pages start out with page table * references from the instantiating fault, so we need * to look twice if a mapped file page is used more * than once. * * Mark it and spare it for another trip around the * inactive list. Another page table reference will * lead to its activation. * * Note: the mark is set for activated pages as well * so that recently deactivated but used pages are * quickly recovered. */ SetPageReferenced(page); if (referenced_page || referenced_ptes > 1) return PAGEREF_ACTIVATE; /* * Activate file-backed executable pages after first usage. */ if (vm_flags & VM_EXEC) return PAGEREF_ACTIVATE; return PAGEREF_KEEP; } /* Reclaim if clean, defer dirty pages to writeback */ if (referenced_page && !PageSwapBacked(page)) return PAGEREF_RECLAIM_CLEAN; return PAGEREF_RECLAIM; } /* Check if a page is dirty or under writeback */ static void page_check_dirty_writeback(struct page *page, bool *dirty, bool *writeback) { struct address_space *mapping; /* * Anonymous pages are not handled by flushers and must be written * from reclaim context. Do not stall reclaim based on them */ if (!page_is_file_cache(page)) { *dirty = false; *writeback = false; return; } /* By default assume that the page flags are accurate */ *dirty = PageDirty(page); *writeback = PageWriteback(page); /* Verify dirty/writeback state if the filesystem supports it */ if (!page_has_private(page)) return; mapping = page_mapping(page); if (mapping && mapping->a_ops->is_dirty_writeback) mapping->a_ops->is_dirty_writeback(page, dirty, writeback); } /* * shrink_page_list() returns the number of reclaimed pages */ static unsigned long shrink_page_list(struct list_head *page_list, struct zone *zone, struct scan_control *sc, enum ttu_flags ttu_flags, unsigned long *ret_nr_dirty, unsigned long *ret_nr_unqueued_dirty, unsigned long *ret_nr_congested, unsigned long *ret_nr_writeback, unsigned long *ret_nr_immediate, bool force_reclaim) { LIST_HEAD(ret_pages); LIST_HEAD(free_pages); int pgactivate = 0; unsigned long nr_unqueued_dirty = 0; unsigned long nr_dirty = 0; unsigned long nr_congested = 0; unsigned long nr_reclaimed = 0; unsigned long nr_writeback = 0; unsigned long nr_immediate = 0; cond_resched(); while (!list_empty(page_list)) { struct address_space *mapping; struct page *page; int may_enter_fs; enum page_references references = PAGEREF_RECLAIM_CLEAN; bool dirty, writeback; cond_resched(); page = lru_to_page(page_list); list_del(&page->lru); if (!trylock_page(page)) goto keep; VM_BUG_ON_PAGE(PageActive(page), page); VM_BUG_ON_PAGE(page_zone(page) != zone, page); sc->nr_scanned++; if (unlikely(!page_evictable(page))) goto cull_mlocked; if (!sc->may_unmap && page_mapped(page)) goto keep_locked; /* Double the slab pressure for mapped and swapcache pages */ if (page_mapped(page) || PageSwapCache(page)) sc->nr_scanned++; may_enter_fs = (sc->gfp_mask & __GFP_FS) || (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO)); /* * The number of dirty pages determines if a zone is marked * reclaim_congested which affects wait_iff_congested. kswapd * will stall and start writing pages if the tail of the LRU * is all dirty unqueued pages. */ page_check_dirty_writeback(page, &dirty, &writeback); if (dirty || writeback) nr_dirty++; if (dirty && !writeback) nr_unqueued_dirty++; /* * Treat this page as congested if the underlying BDI is or if * pages are cycling through the LRU so quickly that the * pages marked for immediate reclaim are making it to the * end of the LRU a second time. */ mapping = page_mapping(page); if (((dirty || writeback) && mapping && inode_write_congested(mapping->host)) || (writeback && PageReclaim(page))) nr_congested++; /* * If a page at the tail of the LRU is under writeback, there * are three cases to consider. * * 1) If reclaim is encountering an excessive number of pages * under writeback and this page is both under writeback and * PageReclaim then it indicates that pages are being queued * for IO but are being recycled through the LRU before the * IO can complete. Waiting on the page itself risks an * indefinite stall if it is impossible to writeback the * page due to IO error or disconnected storage so instead * note that the LRU is being scanned too quickly and the * caller can stall after page list has been processed. * * 2) Global or new memcg reclaim encounters a page that is * not marked for immediate reclaim, or the caller does not * have __GFP_FS (or __GFP_IO if it's simply going to swap, * not to fs). In this case mark the page for immediate * reclaim and continue scanning. * * Require may_enter_fs because we would wait on fs, which * may not have submitted IO yet. And the loop driver might * enter reclaim, and deadlock if it waits on a page for * which it is needed to do the write (loop masks off * __GFP_IO|__GFP_FS for this reason); but more thought * would probably show more reasons. * * 3) Legacy memcg encounters a page that is not already marked * PageReclaim. memcg does not have any dirty pages * throttling so we could easily OOM just because too many * pages are in writeback and there is nothing else to * reclaim. Wait for the writeback to complete. */ if (PageWriteback(page)) { /* Case 1 above */ if (current_is_kswapd() && PageReclaim(page) && test_bit(ZONE_WRITEBACK, &zone->flags)) { nr_immediate++; goto keep_locked; /* Case 2 above */ } else if (sane_reclaim(sc) || !PageReclaim(page) || !may_enter_fs) { /* * This is slightly racy - end_page_writeback() * might have just cleared PageReclaim, then * setting PageReclaim here end up interpreted * as PageReadahead - but that does not matter * enough to care. What we do want is for this * page to have PageReclaim set next time memcg * reclaim reaches the tests above, so it will * then wait_on_page_writeback() to avoid OOM; * and it's also appropriate in global reclaim. */ SetPageReclaim(page); nr_writeback++; goto keep_locked; /* Case 3 above */ } else { wait_on_page_writeback(page); } } if (!force_reclaim) references = page_check_references(page, sc); switch (references) { case PAGEREF_ACTIVATE: goto activate_locked; case PAGEREF_KEEP: goto keep_locked; case PAGEREF_RECLAIM: case PAGEREF_RECLAIM_CLEAN: ; /* try to reclaim the page below */ } /* * Anonymous process memory has backing store? * Try to allocate it some swap space here. */ if (PageAnon(page) && !PageSwapCache(page)) { if (!(sc->gfp_mask & __GFP_IO)) goto keep_locked; if (!add_to_swap(page, page_list)) goto activate_locked; may_enter_fs = 1; /* Adding to swap updated mapping */ mapping = page_mapping(page); } /* * The page is mapped into the page tables of one or more * processes. Try to unmap it here. */ if (page_mapped(page) && mapping) { switch (try_to_unmap(page, ttu_flags)) { case SWAP_FAIL: goto activate_locked; case SWAP_AGAIN: goto keep_locked; case SWAP_MLOCK: goto cull_mlocked; case SWAP_SUCCESS: ; /* try to free the page below */ } } if (PageDirty(page)) { /* * Only kswapd can writeback filesystem pages to * avoid risk of stack overflow but only writeback * if many dirty pages have been encountered. */ if (page_is_file_cache(page) && (!current_is_kswapd() || !test_bit(ZONE_DIRTY, &zone->flags))) { /* * Immediately reclaim when written back. * Similar in principal to deactivate_page() * except we already have the page isolated * and know it's dirty */ inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE); SetPageReclaim(page); goto keep_locked; } if (references == PAGEREF_RECLAIM_CLEAN) goto keep_locked; if (!may_enter_fs) goto keep_locked; if (!sc->may_writepage) goto keep_locked; /* Page is dirty, try to write it out here */ switch (pageout(page, mapping, sc)) { case PAGE_KEEP: goto keep_locked; case PAGE_ACTIVATE: goto activate_locked; case PAGE_SUCCESS: if (PageWriteback(page)) goto keep; if (PageDirty(page)) goto keep; /* * A synchronous write - probably a ramdisk. Go * ahead and try to reclaim the page. */ if (!trylock_page(page)) goto keep; if (PageDirty(page) || PageWriteback(page)) goto keep_locked; mapping = page_mapping(page); case PAGE_CLEAN: ; /* try to free the page below */ } } /* * If the page has buffers, try to free the buffer mappings * associated with this page. If we succeed we try to free * the page as well. * * We do this even if the page is PageDirty(). * try_to_release_page() does not perform I/O, but it is * possible for a page to have PageDirty set, but it is actually * clean (all its buffers are clean). This happens if the * buffers were written out directly, with submit_bh(). ext3 * will do this, as well as the blockdev mapping. * try_to_release_page() will discover that cleanness and will * drop the buffers and mark the page clean - it can be freed. * * Rarely, pages can have buffers and no ->mapping. These are * the pages which were not successfully invalidated in * truncate_complete_page(). We try to drop those buffers here * and if that worked, and the page is no longer mapped into * process address space (page_count == 1) it can be freed. * Otherwise, leave the page on the LRU so it is swappable. */ if (page_has_private(page)) { if (!try_to_release_page(page, sc->gfp_mask)) goto activate_locked; if (!mapping && page_count(page) == 1) { unlock_page(page); if (put_page_testzero(page)) goto free_it; else { /* * rare race with speculative reference. * the speculative reference will free * this page shortly, so we may * increment nr_reclaimed here (and * leave it off the LRU). */ nr_reclaimed++; continue; } } } if (!mapping || !__remove_mapping(mapping, page, true)) goto keep_locked; /* * At this point, we have no other references and there is * no way to pick any more up (removed from LRU, removed * from pagecache). Can use non-atomic bitops now (and * we obviously don't have to worry about waking up a process * waiting on the page lock, because there are no references. */ __clear_page_locked(page); free_it: nr_reclaimed++; /* * Is there need to periodically free_page_list? It would * appear not as the counts should be low */ list_add(&page->lru, &free_pages); continue; cull_mlocked: if (PageSwapCache(page)) try_to_free_swap(page); unlock_page(page); list_add(&page->lru, &ret_pages); continue; activate_locked: /* Not a candidate for swapping, so reclaim swap space. */ if (PageSwapCache(page) && vm_swap_full()) try_to_free_swap(page); VM_BUG_ON_PAGE(PageActive(page), page); SetPageActive(page); pgactivate++; keep_locked: unlock_page(page); keep: list_add(&page->lru, &ret_pages); VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page); } mem_cgroup_uncharge_list(&free_pages); free_hot_cold_page_list(&free_pages, true); list_splice(&ret_pages, page_list); count_vm_events(PGACTIVATE, pgactivate); *ret_nr_dirty += nr_dirty; *ret_nr_congested += nr_congested; *ret_nr_unqueued_dirty += nr_unqueued_dirty; *ret_nr_writeback += nr_writeback; *ret_nr_immediate += nr_immediate; return nr_reclaimed; } unsigned long reclaim_clean_pages_from_list(struct zone *zone, struct list_head *page_list) { struct scan_control sc = { .gfp_mask = GFP_KERNEL, .priority = DEF_PRIORITY, .may_unmap = 1, }; unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5; struct page *page, *next; LIST_HEAD(clean_pages); list_for_each_entry_safe(page, next, page_list, lru) { if (page_is_file_cache(page) && !PageDirty(page) && !isolated_balloon_page(page)) { ClearPageActive(page); list_move(&page->lru, &clean_pages); } } ret = shrink_page_list(&clean_pages, zone, &sc, TTU_UNMAP|TTU_IGNORE_ACCESS, &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true); list_splice(&clean_pages, page_list); mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret); return ret; } /* * Attempt to remove the specified page from its LRU. Only take this page * if it is of the appropriate PageActive status. Pages which are being * freed elsewhere are also ignored. * * page: page to consider * mode: one of the LRU isolation modes defined above * * returns 0 on success, -ve errno on failure. */ int __isolate_lru_page(struct page *page, isolate_mode_t mode) { int ret = -EINVAL; /* Only take pages on the LRU. */ if (!PageLRU(page)) return ret; /* Compaction should not handle unevictable pages but CMA can do so */ if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE)) return ret; ret = -EBUSY; /* * To minimise LRU disruption, the caller can indicate that it only * wants to isolate pages it will be able to operate on without * blocking - clean pages for the most part. * * ISOLATE_CLEAN means that only clean pages should be isolated. This * is used by reclaim when it is cannot write to backing storage * * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages * that it is possible to migrate without blocking */ if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) { /* All the caller can do on PageWriteback is block */ if (PageWriteback(page)) return ret; if (PageDirty(page)) { struct address_space *mapping; /* ISOLATE_CLEAN means only clean pages */ if (mode & ISOLATE_CLEAN) return ret; /* * Only pages without mappings or that have a * ->migratepage callback are possible to migrate * without blocking */ mapping = page_mapping(page); if (mapping && !mapping->a_ops->migratepage) return ret; } } if ((mode & ISOLATE_UNMAPPED) && page_mapped(page)) return ret; if (likely(get_page_unless_zero(page))) { /* * Be careful not to clear PageLRU until after we're * sure the page is not being freed elsewhere -- the * page release code relies on it. */ ClearPageLRU(page); ret = 0; } return ret; } /* * zone->lru_lock is heavily contended. Some of the functions that * shrink the lists perform better by taking out a batch of pages * and working on them outside the LRU lock. * * For pagecache intensive workloads, this function is the hottest * spot in the kernel (apart from copy_*_user functions). * * Appropriate locks must be held before calling this function. * * @nr_to_scan: The number of pages to look through on the list. * @lruvec: The LRU vector to pull pages from. * @dst: The temp list to put pages on to. * @nr_scanned: The number of pages that were scanned. * @sc: The scan_control struct for this reclaim session * @mode: One of the LRU isolation modes * @lru: LRU list id for isolating * * returns how many pages were moved onto *@dst. */ static unsigned long isolate_lru_pages(unsigned long nr_to_scan, struct lruvec *lruvec, struct list_head *dst, unsigned long *nr_scanned, struct scan_control *sc, isolate_mode_t mode, enum lru_list lru) { struct list_head *src = &lruvec->lists[lru]; unsigned long nr_taken = 0; unsigned long scan; for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) { struct page *page; int nr_pages; page = lru_to_page(src); prefetchw_prev_lru_page(page, src, flags); VM_BUG_ON_PAGE(!PageLRU(page), page); switch (__isolate_lru_page(page, mode)) { case 0: nr_pages = hpage_nr_pages(page); mem_cgroup_update_lru_size(lruvec, lru, -nr_pages); list_move(&page->lru, dst); nr_taken += nr_pages; break; case -EBUSY: /* else it is being freed elsewhere */ list_move(&page->lru, src); continue; default: BUG(); } } *nr_scanned = scan; trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan, nr_taken, mode, is_file_lru(lru)); return nr_taken; } /** * isolate_lru_page - tries to isolate a page from its LRU list * @page: page to isolate from its LRU list * * Isolates a @page from an LRU list, clears PageLRU and adjusts the * vmstat statistic corresponding to whatever LRU list the page was on. * * Returns 0 if the page was removed from an LRU list. * Returns -EBUSY if the page was not on an LRU list. * * The returned page will have PageLRU() cleared. If it was found on * the active list, it will have PageActive set. If it was found on * the unevictable list, it will have the PageUnevictable bit set. That flag * may need to be cleared by the caller before letting the page go. * * The vmstat statistic corresponding to the list on which the page was * found will be decremented. * * Restrictions: * (1) Must be called with an elevated refcount on the page. This is a * fundamentnal difference from isolate_lru_pages (which is called * without a stable reference). * (2) the lru_lock must not be held. * (3) interrupts must be enabled. */ int isolate_lru_page(struct page *page) { int ret = -EBUSY; VM_BUG_ON_PAGE(!page_count(page), page); if (PageLRU(page)) { struct zone *zone = page_zone(page); struct lruvec *lruvec; spin_lock_irq(&zone->lru_lock); lruvec = mem_cgroup_page_lruvec(page, zone); if (PageLRU(page)) { int lru = page_lru(page); get_page(page); ClearPageLRU(page); del_page_from_lru_list(page, lruvec, lru); ret = 0; } spin_unlock_irq(&zone->lru_lock); } return ret; } /* * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and * then get resheduled. When there are massive number of tasks doing page * allocation, such sleeping direct reclaimers may keep piling up on each CPU, * the LRU list will go small and be scanned faster than necessary, leading to * unnecessary swapping, thrashing and OOM. */ static int too_many_isolated(struct zone *zone, int file, struct scan_control *sc) { unsigned long inactive, isolated; if (current_is_kswapd()) return 0; if (!sane_reclaim(sc)) return 0; if (file) { inactive = zone_page_state(zone, NR_INACTIVE_FILE); isolated = zone_page_state(zone, NR_ISOLATED_FILE); } else { inactive = zone_page_state(zone, NR_INACTIVE_ANON); isolated = zone_page_state(zone, NR_ISOLATED_ANON); } /* * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they * won't get blocked by normal direct-reclaimers, forming a circular * deadlock. */ if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS) inactive >>= 3; return isolated > inactive; } static noinline_for_stack void putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list) { struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; struct zone *zone = lruvec_zone(lruvec); LIST_HEAD(pages_to_free); /* * Put back any unfreeable pages. */ while (!list_empty(page_list)) { struct page *page = lru_to_page(page_list); int lru; VM_BUG_ON_PAGE(PageLRU(page), page); list_del(&page->lru); if (unlikely(!page_evictable(page))) { spin_unlock_irq(&zone->lru_lock); putback_lru_page(page); spin_lock_irq(&zone->lru_lock); continue; } lruvec = mem_cgroup_page_lruvec(page, zone); SetPageLRU(page); lru = page_lru(page); add_page_to_lru_list(page, lruvec, lru); if (is_active_lru(lru)) { int file = is_file_lru(lru); int numpages = hpage_nr_pages(page); reclaim_stat->recent_rotated[file] += numpages; } if (put_page_testzero(page)) { __ClearPageLRU(page); __ClearPageActive(page); del_page_from_lru_list(page, lruvec, lru); if (unlikely(PageCompound(page))) { spin_unlock_irq(&zone->lru_lock); mem_cgroup_uncharge(page); (*get_compound_page_dtor(page))(page); spin_lock_irq(&zone->lru_lock); } else list_add(&page->lru, &pages_to_free); } } /* * To save our caller's stack, now use input list for pages to free. */ list_splice(&pages_to_free, page_list); } /* * If a kernel thread (such as nfsd for loop-back mounts) services * a backing device by writing to the page cache it sets PF_LESS_THROTTLE. * In that case we should only throttle if the backing device it is * writing to is congested. In other cases it is safe to throttle. */ static int current_may_throttle(void) { return !(current->flags & PF_LESS_THROTTLE) || current->backing_dev_info == NULL || bdi_write_congested(current->backing_dev_info); } /* * shrink_inactive_list() is a helper for shrink_zone(). It returns the number * of reclaimed pages */ static noinline_for_stack unsigned long shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec, struct scan_control *sc, enum lru_list lru) { LIST_HEAD(page_list); unsigned long nr_scanned; unsigned long nr_reclaimed = 0; unsigned long nr_taken; unsigned long nr_dirty = 0; unsigned long nr_congested = 0; unsigned long nr_unqueued_dirty = 0; unsigned long nr_writeback = 0; unsigned long nr_immediate = 0; isolate_mode_t isolate_mode = 0; int file = is_file_lru(lru); struct zone *zone = lruvec_zone(lruvec); struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; while (unlikely(too_many_isolated(zone, file, sc))) { congestion_wait(BLK_RW_ASYNC, HZ/10); /* We are about to die and free our memory. Return now. */ if (fatal_signal_pending(current)) return SWAP_CLUSTER_MAX; } lru_add_drain(); if (!sc->may_unmap) isolate_mode |= ISOLATE_UNMAPPED; if (!sc->may_writepage) isolate_mode |= ISOLATE_CLEAN; spin_lock_irq(&zone->lru_lock); nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list, &nr_scanned, sc, isolate_mode, lru); __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken); __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken); if (global_reclaim(sc)) { __mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned); if (current_is_kswapd()) __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned); else __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned); } spin_unlock_irq(&zone->lru_lock); if (nr_taken == 0) return 0; nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP, &nr_dirty, &nr_unqueued_dirty, &nr_congested, &nr_writeback, &nr_immediate, false); spin_lock_irq(&zone->lru_lock); reclaim_stat->recent_scanned[file] += nr_taken; if (global_reclaim(sc)) { if (current_is_kswapd()) __count_zone_vm_events(PGSTEAL_KSWAPD, zone, nr_reclaimed); else __count_zone_vm_events(PGSTEAL_DIRECT, zone, nr_reclaimed); } putback_inactive_pages(lruvec, &page_list); __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken); spin_unlock_irq(&zone->lru_lock); mem_cgroup_uncharge_list(&page_list); free_hot_cold_page_list(&page_list, true); /* * If reclaim is isolating dirty pages under writeback, it implies * that the long-lived page allocation rate is exceeding the page * laundering rate. Either the global limits are not being effective * at throttling processes due to the page distribution throughout * zones or there is heavy usage of a slow backing device. The * only option is to throttle from reclaim context which is not ideal * as there is no guarantee the dirtying process is throttled in the * same way balance_dirty_pages() manages. * * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number * of pages under pages flagged for immediate reclaim and stall if any * are encountered in the nr_immediate check below. */ if (nr_writeback && nr_writeback == nr_taken) set_bit(ZONE_WRITEBACK, &zone->flags); /* * Legacy memcg will stall in page writeback so avoid forcibly * stalling here. */ if (sane_reclaim(sc)) { /* * Tag a zone as congested if all the dirty pages scanned were * backed by a congested BDI and wait_iff_congested will stall. */ if (nr_dirty && nr_dirty == nr_congested) set_bit(ZONE_CONGESTED, &zone->flags); /* * If dirty pages are scanned that are not queued for IO, it * implies that flushers are not keeping up. In this case, flag * the zone ZONE_DIRTY and kswapd will start writing pages from * reclaim context. */ if (nr_unqueued_dirty == nr_taken) set_bit(ZONE_DIRTY, &zone->flags); /* * If kswapd scans pages marked marked for immediate * reclaim and under writeback (nr_immediate), it implies * that pages are cycling through the LRU faster than * they are written so also forcibly stall. */ if (nr_immediate && current_may_throttle()) congestion_wait(BLK_RW_ASYNC, HZ/10); } /* * Stall direct reclaim for IO completions if underlying BDIs or zone * is congested. Allow kswapd to continue until it starts encountering * unqueued dirty pages or cycling through the LRU too quickly. */ if (!sc->hibernation_mode && !current_is_kswapd() && current_may_throttle()) wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10); trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id, zone_idx(zone), nr_scanned, nr_reclaimed, sc->priority, trace_shrink_flags(file)); return nr_reclaimed; } /* * This moves pages from the active list to the inactive list. * * We move them the other way if the page is referenced by one or more * processes, from rmap. * * If the pages are mostly unmapped, the processing is fast and it is * appropriate to hold zone->lru_lock across the whole operation. But if * the pages are mapped, the processing is slow (page_referenced()) so we * should drop zone->lru_lock around each page. It's impossible to balance * this, so instead we remove the pages from the LRU while processing them. * It is safe to rely on PG_active against the non-LRU pages in here because * nobody will play with that bit on a non-LRU page. * * The downside is that we have to touch page->_count against each page. * But we had to alter page->flags anyway. */ static void move_active_pages_to_lru(struct lruvec *lruvec, struct list_head *list, struct list_head *pages_to_free, enum lru_list lru) { struct zone *zone = lruvec_zone(lruvec); unsigned long pgmoved = 0; struct page *page; int nr_pages; while (!list_empty(list)) { page = lru_to_page(list); lruvec = mem_cgroup_page_lruvec(page, zone); VM_BUG_ON_PAGE(PageLRU(page), page); SetPageLRU(page); nr_pages = hpage_nr_pages(page); mem_cgroup_update_lru_size(lruvec, lru, nr_pages); list_move(&page->lru, &lruvec->lists[lru]); pgmoved += nr_pages; if (put_page_testzero(page)) { __ClearPageLRU(page); __ClearPageActive(page); del_page_from_lru_list(page, lruvec, lru); if (unlikely(PageCompound(page))) { spin_unlock_irq(&zone->lru_lock); mem_cgroup_uncharge(page); (*get_compound_page_dtor(page))(page); spin_lock_irq(&zone->lru_lock); } else list_add(&page->lru, pages_to_free); } } __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved); if (!is_active_lru(lru)) __count_vm_events(PGDEACTIVATE, pgmoved); } static void shrink_active_list(unsigned long nr_to_scan, struct lruvec *lruvec, struct scan_control *sc, enum lru_list lru) { unsigned long nr_taken; unsigned long nr_scanned; unsigned long vm_flags; LIST_HEAD(l_hold); /* The pages which were snipped off */ LIST_HEAD(l_active); LIST_HEAD(l_inactive); struct page *page; struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; unsigned long nr_rotated = 0; isolate_mode_t isolate_mode = 0; int file = is_file_lru(lru); struct zone *zone = lruvec_zone(lruvec); lru_add_drain(); if (!sc->may_unmap) isolate_mode |= ISOLATE_UNMAPPED; if (!sc->may_writepage) isolate_mode |= ISOLATE_CLEAN; spin_lock_irq(&zone->lru_lock); nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold, &nr_scanned, sc, isolate_mode, lru); if (global_reclaim(sc)) __mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned); reclaim_stat->recent_scanned[file] += nr_taken; __count_zone_vm_events(PGREFILL, zone, nr_scanned); __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken); __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken); spin_unlock_irq(&zone->lru_lock); while (!list_empty(&l_hold)) { cond_resched(); page = lru_to_page(&l_hold); list_del(&page->lru); if (unlikely(!page_evictable(page))) { putback_lru_page(page); continue; } if (unlikely(buffer_heads_over_limit)) { if (page_has_private(page) && trylock_page(page)) { if (page_has_private(page)) try_to_release_page(page, 0); unlock_page(page); } } if (page_referenced(page, 0, sc->target_mem_cgroup, &vm_flags)) { nr_rotated += hpage_nr_pages(page); /* * Identify referenced, file-backed active pages and * give them one more trip around the active list. So * that executable code get better chances to stay in * memory under moderate memory pressure. Anon pages * are not likely to be evicted by use-once streaming * IO, plus JVM can create lots of anon VM_EXEC pages, * so we ignore them here. */ if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) { list_add(&page->lru, &l_active); continue; } } ClearPageActive(page); /* we are de-activating */ list_add(&page->lru, &l_inactive); } /* * Move pages back to the lru list. */ spin_lock_irq(&zone->lru_lock); /* * Count referenced pages from currently used mappings as rotated, * even though only some of them are actually re-activated. This * helps balance scan pressure between file and anonymous pages in * get_scan_count. */ reclaim_stat->recent_rotated[file] += nr_rotated; move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru); move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE); __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken); spin_unlock_irq(&zone->lru_lock); mem_cgroup_uncharge_list(&l_hold); free_hot_cold_page_list(&l_hold, true); } #ifdef CONFIG_SWAP static int inactive_anon_is_low_global(struct zone *zone) { unsigned long active, inactive; active = zone_page_state(zone, NR_ACTIVE_ANON); inactive = zone_page_state(zone, NR_INACTIVE_ANON); if (inactive * zone->inactive_ratio < active) return 1; return 0; } /** * inactive_anon_is_low - check if anonymous pages need to be deactivated * @lruvec: LRU vector to check * * Returns true if the zone does not have enough inactive anon pages, * meaning some active anon pages need to be deactivated. */ static int inactive_anon_is_low(struct lruvec *lruvec) { /* * If we don't have swap space, anonymous page deactivation * is pointless. */ if (!total_swap_pages) return 0; if (!mem_cgroup_disabled()) return mem_cgroup_inactive_anon_is_low(lruvec); return inactive_anon_is_low_global(lruvec_zone(lruvec)); } #else static inline int inactive_anon_is_low(struct lruvec *lruvec) { return 0; } #endif /** * inactive_file_is_low - check if file pages need to be deactivated * @lruvec: LRU vector to check * * When the system is doing streaming IO, memory pressure here * ensures that active file pages get deactivated, until more * than half of the file pages are on the inactive list. * * Once we get to that situation, protect the system's working * set from being evicted by disabling active file page aging. * * This uses a different ratio than the anonymous pages, because * the page cache uses a use-once replacement algorithm. */ static int inactive_file_is_low(struct lruvec *lruvec) { unsigned long inactive; unsigned long active; inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE); active = get_lru_size(lruvec, LRU_ACTIVE_FILE); return active > inactive; } static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru) { if (is_file_lru(lru)) return inactive_file_is_low(lruvec); else return inactive_anon_is_low(lruvec); } static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan, struct lruvec *lruvec, struct scan_control *sc) { if (is_active_lru(lru)) { if (inactive_list_is_low(lruvec, lru)) shrink_active_list(nr_to_scan, lruvec, sc, lru); return 0; } return shrink_inactive_list(nr_to_scan, lruvec, sc, lru); } enum scan_balance { SCAN_EQUAL, SCAN_FRACT, SCAN_ANON, SCAN_FILE, }; /* * Determine how aggressively the anon and file LRU lists should be * scanned. The relative value of each set of LRU lists is determined * by looking at the fraction of the pages scanned we did rotate back * onto the active list instead of evict. * * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan */ static void get_scan_count(struct lruvec *lruvec, int swappiness, struct scan_control *sc, unsigned long *nr, unsigned long *lru_pages) { struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat; u64 fraction[2]; u64 denominator = 0; /* gcc */ struct zone *zone = lruvec_zone(lruvec); unsigned long anon_prio, file_prio; enum scan_balance scan_balance; unsigned long anon, file; bool force_scan = false; unsigned long ap, fp; enum lru_list lru; bool some_scanned; int pass; /* * If the zone or memcg is small, nr[l] can be 0. This * results in no scanning on this priority and a potential * priority drop. Global direct reclaim can go to the next * zone and tends to have no problems. Global kswapd is for * zone balancing and it needs to scan a minimum amount. When * reclaiming for a memcg, a priority drop can cause high * latencies, so it's better to scan a minimum amount there as * well. */ if (current_is_kswapd()) { if (!zone_reclaimable(zone)) force_scan = true; if (!mem_cgroup_lruvec_online(lruvec)) force_scan = true; } if (!global_reclaim(sc)) force_scan = true; /* If we have no swap space, do not bother scanning anon pages. */ if (!sc->may_swap || (get_nr_swap_pages() <= 0)) { scan_balance = SCAN_FILE; goto out; } /* * Global reclaim will swap to prevent OOM even with no * swappiness, but memcg users want to use this knob to * disable swapping for individual groups completely when * using the memory controller's swap limit feature would be * too expensive. */ if (!global_reclaim(sc) && !swappiness) { scan_balance = SCAN_FILE; goto out; } /* * Do not apply any pressure balancing cleverness when the * system is close to OOM, scan both anon and file equally * (unless the swappiness setting disagrees with swapping). */ if (!sc->priority && swappiness) { scan_balance = SCAN_EQUAL; goto out; } /* * Prevent the reclaimer from falling into the cache trap: as * cache pages start out inactive, every cache fault will tip * the scan balance towards the file LRU. And as the file LRU * shrinks, so does the window for rotation from references. * This means we have a runaway feedback loop where a tiny * thrashing file LRU becomes infinitely more attractive than * anon pages. Try to detect this based on file LRU size. */ if (global_reclaim(sc)) { unsigned long zonefile; unsigned long zonefree; zonefree = zone_page_state(zone, NR_FREE_PAGES); zonefile = zone_page_state(zone, NR_ACTIVE_FILE) + zone_page_state(zone, NR_INACTIVE_FILE); if (unlikely(zonefile + zonefree <= high_wmark_pages(zone))) { scan_balance = SCAN_ANON; goto out; } } /* * There is enough inactive page cache, do not reclaim * anything from the anonymous working set right now. */ if (!inactive_file_is_low(lruvec)) { scan_balance = SCAN_FILE; goto out; } scan_balance = SCAN_FRACT; /* * With swappiness at 100, anonymous and file have the same priority. * This scanning priority is essentially the inverse of IO cost. */ anon_prio = swappiness; file_prio = 200 - anon_prio; /* * OK, so we have swap space and a fair amount of page cache * pages. We use the recently rotated / recently scanned * ratios to determine how valuable each cache is. * * Because workloads change over time (and to avoid overflow) * we keep these statistics as a floating average, which ends * up weighing recent references more than old ones. * * anon in [0], file in [1] */ anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) + get_lru_size(lruvec, LRU_INACTIVE_ANON); file = get_lru_size(lruvec, LRU_ACTIVE_FILE) + get_lru_size(lruvec, LRU_INACTIVE_FILE); spin_lock_irq(&zone->lru_lock); if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) { reclaim_stat->recent_scanned[0] /= 2; reclaim_stat->recent_rotated[0] /= 2; } if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) { reclaim_stat->recent_scanned[1] /= 2; reclaim_stat->recent_rotated[1] /= 2; } /* * The amount of pressure on anon vs file pages is inversely * proportional to the fraction of recently scanned pages on * each list that were recently referenced and in active use. */ ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1); ap /= reclaim_stat->recent_rotated[0] + 1; fp = file_prio * (reclaim_stat->recent_scanned[1] + 1); fp /= reclaim_stat->recent_rotated[1] + 1; spin_unlock_irq(&zone->lru_lock); fraction[0] = ap; fraction[1] = fp; denominator = ap + fp + 1; out: some_scanned = false; /* Only use force_scan on second pass. */ for (pass = 0; !some_scanned && pass < 2; pass++) { *lru_pages = 0; for_each_evictable_lru(lru) { int file = is_file_lru(lru); unsigned long size; unsigned long scan; size = get_lru_size(lruvec, lru); scan = size >> sc->priority; if (!scan && pass && force_scan) scan = min(size, SWAP_CLUSTER_MAX); switch (scan_balance) { case SCAN_EQUAL: /* Scan lists relative to size */ break; case SCAN_FRACT: /* * Scan types proportional to swappiness and * their relative recent reclaim efficiency. */ scan = div64_u64(scan * fraction[file], denominator); break; case SCAN_FILE: case SCAN_ANON: /* Scan one type exclusively */ if ((scan_balance == SCAN_FILE) != file) { size = 0; scan = 0; } break; default: /* Look ma, no brain */ BUG(); } *lru_pages += size; nr[lru] = scan; /* * Skip the second pass and don't force_scan, * if we found something to scan. */ some_scanned |= !!scan; } } } /* * This is a basic per-zone page freer. Used by both kswapd and direct reclaim. */ static void shrink_lruvec(struct lruvec *lruvec, int swappiness, struct scan_control *sc, unsigned long *lru_pages) { unsigned long nr[NR_LRU_LISTS]; unsigned long targets[NR_LRU_LISTS]; unsigned long nr_to_scan; enum lru_list lru; unsigned long nr_reclaimed = 0; unsigned long nr_to_reclaim = sc->nr_to_reclaim; struct blk_plug plug; bool scan_adjusted; get_scan_count(lruvec, swappiness, sc, nr, lru_pages); /* Record the original scan target for proportional adjustments later */ memcpy(targets, nr, sizeof(nr)); /* * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal * event that can occur when there is little memory pressure e.g. * multiple streaming readers/writers. Hence, we do not abort scanning * when the requested number of pages are reclaimed when scanning at * DEF_PRIORITY on the assumption that the fact we are direct * reclaiming implies that kswapd is not keeping up and it is best to * do a batch of work at once. For memcg reclaim one check is made to * abort proportional reclaim if either the file or anon lru has already * dropped to zero at the first pass. */ scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() && sc->priority == DEF_PRIORITY); blk_start_plug(&plug); while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] || nr[LRU_INACTIVE_FILE]) { unsigned long nr_anon, nr_file, percentage; unsigned long nr_scanned; for_each_evictable_lru(lru) { if (nr[lru]) { nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX); nr[lru] -= nr_to_scan; nr_reclaimed += shrink_list(lru, nr_to_scan, lruvec, sc); } } if (nr_reclaimed < nr_to_reclaim || scan_adjusted) continue; /* * For kswapd and memcg, reclaim at least the number of pages * requested. Ensure that the anon and file LRUs are scanned * proportionally what was requested by get_scan_count(). We * stop reclaiming one LRU and reduce the amount scanning * proportional to the original scan target. */ nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE]; nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON]; /* * It's just vindictive to attack the larger once the smaller * has gone to zero. And given the way we stop scanning the * smaller below, this makes sure that we only make one nudge * towards proportionality once we've got nr_to_reclaim. */ if (!nr_file || !nr_anon) break; if (nr_file > nr_anon) { unsigned long scan_target = targets[LRU_INACTIVE_ANON] + targets[LRU_ACTIVE_ANON] + 1; lru = LRU_BASE; percentage = nr_anon * 100 / scan_target; } else { unsigned long scan_target = targets[LRU_INACTIVE_FILE] + targets[LRU_ACTIVE_FILE] + 1; lru = LRU_FILE; percentage = nr_file * 100 / scan_target; } /* Stop scanning the smaller of the LRU */ nr[lru] = 0; nr[lru + LRU_ACTIVE] = 0; /* * Recalculate the other LRU scan count based on its original * scan target and the percentage scanning already complete */ lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE; nr_scanned = targets[lru] - nr[lru]; nr[lru] = targets[lru] * (100 - percentage) / 100; nr[lru] -= min(nr[lru], nr_scanned); lru += LRU_ACTIVE; nr_scanned = targets[lru] - nr[lru]; nr[lru] = targets[lru] * (100 - percentage) / 100; nr[lru] -= min(nr[lru], nr_scanned); scan_adjusted = true; } blk_finish_plug(&plug); sc->nr_reclaimed += nr_reclaimed; /* * Even if we did not try to evict anon pages at all, we want to * rebalance the anon lru active/inactive ratio. */ if (inactive_anon_is_low(lruvec)) shrink_active_list(SWAP_CLUSTER_MAX, lruvec, sc, LRU_ACTIVE_ANON); throttle_vm_writeout(sc->gfp_mask); } /* Use reclaim/compaction for costly allocs or under memory pressure */ static bool in_reclaim_compaction(struct scan_control *sc) { if (IS_ENABLED(CONFIG_COMPACTION) && sc->order && (sc->order > PAGE_ALLOC_COSTLY_ORDER || sc->priority < DEF_PRIORITY - 2)) return true; return false; } /* * Reclaim/compaction is used for high-order allocation requests. It reclaims * order-0 pages before compacting the zone. should_continue_reclaim() returns * true if more pages should be reclaimed such that when the page allocator * calls try_to_compact_zone() that it will have enough free pages to succeed. * It will give up earlier than that if there is difficulty reclaiming pages. */ static inline bool should_continue_reclaim(struct zone *zone, unsigned long nr_reclaimed, unsigned long nr_scanned, struct scan_control *sc) { unsigned long pages_for_compaction; unsigned long inactive_lru_pages; /* If not in reclaim/compaction mode, stop */ if (!in_reclaim_compaction(sc)) return false; /* Consider stopping depending on scan and reclaim activity */ if (sc->gfp_mask & __GFP_REPEAT) { /* * For __GFP_REPEAT allocations, stop reclaiming if the * full LRU list has been scanned and we are still failing * to reclaim pages. This full LRU scan is potentially * expensive but a __GFP_REPEAT caller really wants to succeed */ if (!nr_reclaimed && !nr_scanned) return false; } else { /* * For non-__GFP_REPEAT allocations which can presumably * fail without consequence, stop if we failed to reclaim * any pages from the last SWAP_CLUSTER_MAX number of * pages that were scanned. This will return to the * caller faster at the risk reclaim/compaction and * the resulting allocation attempt fails */ if (!nr_reclaimed) return false; } /* * If we have not reclaimed enough pages for compaction and the * inactive lists are large enough, continue reclaiming */ pages_for_compaction = (2UL << sc->order); inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE); if (get_nr_swap_pages() > 0) inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON); if (sc->nr_reclaimed < pages_for_compaction && inactive_lru_pages > pages_for_compaction) return true; /* If compaction would go ahead or the allocation would succeed, stop */ switch (compaction_suitable(zone, sc->order, 0, 0)) { case COMPACT_PARTIAL: case COMPACT_CONTINUE: return false; default: return true; } } static bool shrink_zone(struct zone *zone, struct scan_control *sc, bool is_classzone) { struct reclaim_state *reclaim_state = current->reclaim_state; unsigned long nr_reclaimed, nr_scanned; bool reclaimable = false; do { struct mem_cgroup *root = sc->target_mem_cgroup; struct mem_cgroup_reclaim_cookie reclaim = { .zone = zone, .priority = sc->priority, }; unsigned long zone_lru_pages = 0; struct mem_cgroup *memcg; nr_reclaimed = sc->nr_reclaimed; nr_scanned = sc->nr_scanned; memcg = mem_cgroup_iter(root, NULL, &reclaim); do { unsigned long lru_pages; unsigned long scanned; struct lruvec *lruvec; int swappiness; if (mem_cgroup_low(root, memcg)) { if (!sc->may_thrash) continue; mem_cgroup_events(memcg, MEMCG_LOW, 1); } lruvec = mem_cgroup_zone_lruvec(zone, memcg); swappiness = mem_cgroup_swappiness(memcg); scanned = sc->nr_scanned; shrink_lruvec(lruvec, swappiness, sc, &lru_pages); zone_lru_pages += lru_pages; if (memcg && is_classzone) shrink_slab(sc->gfp_mask, zone_to_nid(zone), memcg, sc->nr_scanned - scanned, lru_pages); /* * Direct reclaim and kswapd have to scan all memory * cgroups to fulfill the overall scan target for the * zone. * * Limit reclaim, on the other hand, only cares about * nr_to_reclaim pages to be reclaimed and it will * retry with decreasing priority if one round over the * whole hierarchy is not sufficient. */ if (!global_reclaim(sc) && sc->nr_reclaimed >= sc->nr_to_reclaim) { mem_cgroup_iter_break(root, memcg); break; } } while ((memcg = mem_cgroup_iter(root, memcg, &reclaim))); /* * Shrink the slab caches in the same proportion that * the eligible LRU pages were scanned. */ if (global_reclaim(sc) && is_classzone) shrink_slab(sc->gfp_mask, zone_to_nid(zone), NULL, sc->nr_scanned - nr_scanned, zone_lru_pages); if (reclaim_state) { sc->nr_reclaimed += reclaim_state->reclaimed_slab; reclaim_state->reclaimed_slab = 0; } vmpressure(sc->gfp_mask, sc->target_mem_cgroup, sc->nr_scanned - nr_scanned, sc->nr_reclaimed - nr_reclaimed); if (sc->nr_reclaimed - nr_reclaimed) reclaimable = true; } while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed, sc->nr_scanned - nr_scanned, sc)); return reclaimable; } /* * Returns true if compaction should go ahead for a high-order request, or * the high-order allocation would succeed without compaction. */ static inline bool compaction_ready(struct zone *zone, int order) { unsigned long balance_gap, watermark; bool watermark_ok; /* * Compaction takes time to run and there are potentially other * callers using the pages just freed. Continue reclaiming until * there is a buffer of free pages available to give compaction * a reasonable chance of completing and allocating the page */ balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP( zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO)); watermark = high_wmark_pages(zone) + balance_gap + (2UL << order); watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0); /* * If compaction is deferred, reclaim up to a point where * compaction will have a chance of success when re-enabled */ if (compaction_deferred(zone, order)) return watermark_ok; /* * If compaction is not ready to start and allocation is not likely * to succeed without it, then keep reclaiming. */ if (compaction_suitable(zone, order, 0, 0) == COMPACT_SKIPPED) return false; return watermark_ok; } /* * This is the direct reclaim path, for page-allocating processes. We only * try to reclaim pages from zones which will satisfy the caller's allocation * request. * * We reclaim from a zone even if that zone is over high_wmark_pages(zone). * Because: * a) The caller may be trying to free *extra* pages to satisfy a higher-order * allocation or * b) The target zone may be at high_wmark_pages(zone) but the lower zones * must go *over* high_wmark_pages(zone) to satisfy the `incremental min' * zone defense algorithm. * * If a zone is deemed to be full of pinned pages then just give it a light * scan then give up on it. * * Returns true if a zone was reclaimable. */ static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc) { struct zoneref *z; struct zone *zone; unsigned long nr_soft_reclaimed; unsigned long nr_soft_scanned; gfp_t orig_mask; enum zone_type requested_highidx = gfp_zone(sc->gfp_mask); bool reclaimable = false; /* * If the number of buffer_heads in the machine exceeds the maximum * allowed level, force direct reclaim to scan the highmem zone as * highmem pages could be pinning lowmem pages storing buffer_heads */ orig_mask = sc->gfp_mask; if (buffer_heads_over_limit) sc->gfp_mask |= __GFP_HIGHMEM; for_each_zone_zonelist_nodemask(zone, z, zonelist, requested_highidx, sc->nodemask) { enum zone_type classzone_idx; if (!populated_zone(zone)) continue; classzone_idx = requested_highidx; while (!populated_zone(zone->zone_pgdat->node_zones + classzone_idx)) classzone_idx--; /* * Take care memory controller reclaiming has small influence * to global LRU. */ if (global_reclaim(sc)) { if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL)) continue; if (sc->priority != DEF_PRIORITY && !zone_reclaimable(zone)) continue; /* Let kswapd poll it */ /* * If we already have plenty of memory free for * compaction in this zone, don't free any more. * Even though compaction is invoked for any * non-zero order, only frequent costly order * reclamation is disruptive enough to become a * noticeable problem, like transparent huge * page allocations. */ if (IS_ENABLED(CONFIG_COMPACTION) && sc->order > PAGE_ALLOC_COSTLY_ORDER && zonelist_zone_idx(z) <= requested_highidx && compaction_ready(zone, sc->order)) { sc->compaction_ready = true; continue; } /* * This steals pages from memory cgroups over softlimit * and returns the number of reclaimed pages and * scanned pages. This works for global memory pressure * and balancing, not for a memcg's limit. */ nr_soft_scanned = 0; nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone, sc->order, sc->gfp_mask, &nr_soft_scanned); sc->nr_reclaimed += nr_soft_reclaimed; sc->nr_scanned += nr_soft_scanned; if (nr_soft_reclaimed) reclaimable = true; /* need some check for avoid more shrink_zone() */ } if (shrink_zone(zone, sc, zone_idx(zone) == classzone_idx)) reclaimable = true; if (global_reclaim(sc) && !reclaimable && zone_reclaimable(zone)) reclaimable = true; } /* * Restore to original mask to avoid the impact on the caller if we * promoted it to __GFP_HIGHMEM. */ sc->gfp_mask = orig_mask; return reclaimable; } /* * This is the main entry point to direct page reclaim. * * If a full scan of the inactive list fails to free enough memory then we * are "out of memory" and something needs to be killed. * * If the caller is !__GFP_FS then the probability of a failure is reasonably * high - the zone may be full of dirty or under-writeback pages, which this * caller can't do much about. We kick the writeback threads and take explicit * naps in the hope that some of these pages can be written. But if the * allocating task holds filesystem locks which prevent writeout this might not * work, and the allocation attempt will fail. * * returns: 0, if no pages reclaimed * else, the number of pages reclaimed */ static unsigned long do_try_to_free_pages(struct zonelist *zonelist, struct scan_control *sc) { int initial_priority = sc->priority; unsigned long total_scanned = 0; unsigned long writeback_threshold; bool zones_reclaimable; retry: delayacct_freepages_start(); if (global_reclaim(sc)) count_vm_event(ALLOCSTALL); do { vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup, sc->priority); sc->nr_scanned = 0; zones_reclaimable = shrink_zones(zonelist, sc); total_scanned += sc->nr_scanned; if (sc->nr_reclaimed >= sc->nr_to_reclaim) break; if (sc->compaction_ready) break; /* * If we're getting trouble reclaiming, start doing * writepage even in laptop mode. */ if (sc->priority < DEF_PRIORITY - 2) sc->may_writepage = 1; /* * Try to write back as many pages as we just scanned. This * tends to cause slow streaming writers to write data to the * disk smoothly, at the dirtying rate, which is nice. But * that's undesirable in laptop mode, where we *want* lumpy * writeout. So in laptop mode, write out the whole world. */ writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2; if (total_scanned > writeback_threshold) { wakeup_flusher_threads(laptop_mode ? 0 : total_scanned, WB_REASON_TRY_TO_FREE_PAGES); sc->may_writepage = 1; } } while (--sc->priority >= 0); delayacct_freepages_end(); if (sc->nr_reclaimed) return sc->nr_reclaimed; /* Aborted reclaim to try compaction? don't OOM, then */ if (sc->compaction_ready) return 1; /* Untapped cgroup reserves? Don't OOM, retry. */ if (!sc->may_thrash) { sc->priority = initial_priority; sc->may_thrash = 1; goto retry; } /* Any of the zones still reclaimable? Don't OOM. */ if (zones_reclaimable) return 1; return 0; } static bool pfmemalloc_watermark_ok(pg_data_t *pgdat) { struct zone *zone; unsigned long pfmemalloc_reserve = 0; unsigned long free_pages = 0; int i; bool wmark_ok; for (i = 0; i <= ZONE_NORMAL; i++) { zone = &pgdat->node_zones[i]; if (!populated_zone(zone) || zone_reclaimable_pages(zone) == 0) continue; pfmemalloc_reserve += min_wmark_pages(zone); free_pages += zone_page_state(zone, NR_FREE_PAGES); } /* If there are no reserves (unexpected config) then do not throttle */ if (!pfmemalloc_reserve) return true; wmark_ok = free_pages > pfmemalloc_reserve / 2; /* kswapd must be awake if processes are being throttled */ if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) { pgdat->classzone_idx = min(pgdat->classzone_idx, (enum zone_type)ZONE_NORMAL); wake_up_interruptible(&pgdat->kswapd_wait); } return wmark_ok; } /* * Throttle direct reclaimers if backing storage is backed by the network * and the PFMEMALLOC reserve for the preferred node is getting dangerously * depleted. kswapd will continue to make progress and wake the processes * when the low watermark is reached. * * Returns true if a fatal signal was delivered during throttling. If this * happens, the page allocator should not consider triggering the OOM killer. */ static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist, nodemask_t *nodemask) { struct zoneref *z; struct zone *zone; pg_data_t *pgdat = NULL; /* * Kernel threads should not be throttled as they may be indirectly * responsible for cleaning pages necessary for reclaim to make forward * progress. kjournald for example may enter direct reclaim while * committing a transaction where throttling it could forcing other * processes to block on log_wait_commit(). */ if (current->flags & PF_KTHREAD) goto out; /* * If a fatal signal is pending, this process should not throttle. * It should return quickly so it can exit and free its memory */ if (fatal_signal_pending(current)) goto out; /* * Check if the pfmemalloc reserves are ok by finding the first node * with a usable ZONE_NORMAL or lower zone. The expectation is that * GFP_KERNEL will be required for allocating network buffers when * swapping over the network so ZONE_HIGHMEM is unusable. * * Throttling is based on the first usable node and throttled processes * wait on a queue until kswapd makes progress and wakes them. There * is an affinity then between processes waking up and where reclaim * progress has been made assuming the process wakes on the same node. * More importantly, processes running on remote nodes will not compete * for remote pfmemalloc reserves and processes on different nodes * should make reasonable progress. */ for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nodemask) { if (zone_idx(zone) > ZONE_NORMAL) continue; /* Throttle based on the first usable node */ pgdat = zone->zone_pgdat; if (pfmemalloc_watermark_ok(pgdat)) goto out; break; } /* If no zone was usable by the allocation flags then do not throttle */ if (!pgdat) goto out; /* Account for the throttling */ count_vm_event(PGSCAN_DIRECT_THROTTLE); /* * If the caller cannot enter the filesystem, it's possible that it * is due to the caller holding an FS lock or performing a journal * transaction in the case of a filesystem like ext[3|4]. In this case, * it is not safe to block on pfmemalloc_wait as kswapd could be * blocked waiting on the same lock. Instead, throttle for up to a * second before continuing. */ if (!(gfp_mask & __GFP_FS)) { wait_event_interruptible_timeout(pgdat->pfmemalloc_wait, pfmemalloc_watermark_ok(pgdat), HZ); goto check_pending; } /* Throttle until kswapd wakes the process */ wait_event_killable(zone->zone_pgdat->pfmemalloc_wait, pfmemalloc_watermark_ok(pgdat)); check_pending: if (fatal_signal_pending(current)) return true; out: return false; } unsigned long try_to_free_pages(struct zonelist *zonelist, int order, gfp_t gfp_mask, nodemask_t *nodemask) { unsigned long nr_reclaimed; struct scan_control sc = { .nr_to_reclaim = SWAP_CLUSTER_MAX, .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)), .order = order, .nodemask = nodemask, .priority = DEF_PRIORITY, .may_writepage = !laptop_mode, .may_unmap = 1, .may_swap = 1, }; /* * Do not enter reclaim if fatal signal was delivered while throttled. * 1 is returned so that the page allocator does not OOM kill at this * point. */ if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask)) return 1; trace_mm_vmscan_direct_reclaim_begin(order, sc.may_writepage, gfp_mask); nr_reclaimed = do_try_to_free_pages(zonelist, &sc); trace_mm_vmscan_direct_reclaim_end(nr_reclaimed); return nr_reclaimed; } #ifdef CONFIG_MEMCG unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg, gfp_t gfp_mask, bool noswap, struct zone *zone, unsigned long *nr_scanned) { struct scan_control sc = { .nr_to_reclaim = SWAP_CLUSTER_MAX, .target_mem_cgroup = memcg, .may_writepage = !laptop_mode, .may_unmap = 1, .may_swap = !noswap, }; struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg); int swappiness = mem_cgroup_swappiness(memcg); unsigned long lru_pages; sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK); trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order, sc.may_writepage, sc.gfp_mask); /* * NOTE: Although we can get the priority field, using it * here is not a good idea, since it limits the pages we can scan. * if we don't reclaim here, the shrink_zone from balance_pgdat * will pick up pages from other mem cgroup's as well. We hack * the priority and make it zero. */ shrink_lruvec(lruvec, swappiness, &sc, &lru_pages); trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed); *nr_scanned = sc.nr_scanned; return sc.nr_reclaimed; } unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg, unsigned long nr_pages, gfp_t gfp_mask, bool may_swap) { struct zonelist *zonelist; unsigned long nr_reclaimed; int nid; struct scan_control sc = { .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) | (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK), .target_mem_cgroup = memcg, .priority = DEF_PRIORITY, .may_writepage = !laptop_mode, .may_unmap = 1, .may_swap = may_swap, }; /* * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't * take care of from where we get pages. So the node where we start the * scan does not need to be the current node. */ nid = mem_cgroup_select_victim_node(memcg); zonelist = NODE_DATA(nid)->node_zonelists; trace_mm_vmscan_memcg_reclaim_begin(0, sc.may_writepage, sc.gfp_mask); nr_reclaimed = do_try_to_free_pages(zonelist, &sc); trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed); return nr_reclaimed; } #endif static void age_active_anon(struct zone *zone, struct scan_control *sc) { struct mem_cgroup *memcg; if (!total_swap_pages) return; memcg = mem_cgroup_iter(NULL, NULL, NULL); do { struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg); if (inactive_anon_is_low(lruvec)) shrink_active_list(SWAP_CLUSTER_MAX, lruvec, sc, LRU_ACTIVE_ANON); memcg = mem_cgroup_iter(NULL, memcg, NULL); } while (memcg); } static bool zone_balanced(struct zone *zone, int order, unsigned long balance_gap, int classzone_idx) { if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) + balance_gap, classzone_idx, 0)) return false; if (IS_ENABLED(CONFIG_COMPACTION) && order && compaction_suitable(zone, order, 0, classzone_idx) == COMPACT_SKIPPED) return false; return true; } /* * pgdat_balanced() is used when checking if a node is balanced. * * For order-0, all zones must be balanced! * * For high-order allocations only zones that meet watermarks and are in a * zone allowed by the callers classzone_idx are added to balanced_pages. The * total of balanced pages must be at least 25% of the zones allowed by * classzone_idx for the node to be considered balanced. Forcing all zones to * be balanced for high orders can cause excessive reclaim when there are * imbalanced zones. * The choice of 25% is due to * o a 16M DMA zone that is balanced will not balance a zone on any * reasonable sized machine * o On all other machines, the top zone must be at least a reasonable * percentage of the middle zones. For example, on 32-bit x86, highmem * would need to be at least 256M for it to be balance a whole node. * Similarly, on x86-64 the Normal zone would need to be at least 1G * to balance a node on its own. These seemed like reasonable ratios. */ static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx) { unsigned long managed_pages = 0; unsigned long balanced_pages = 0; int i; /* Check the watermark levels */ for (i = 0; i <= classzone_idx; i++) { struct zone *zone = pgdat->node_zones + i; if (!populated_zone(zone)) continue; managed_pages += zone->managed_pages; /* * A special case here: * * balance_pgdat() skips over all_unreclaimable after * DEF_PRIORITY. Effectively, it considers them balanced so * they must be considered balanced here as well! */ if (!zone_reclaimable(zone)) { balanced_pages += zone->managed_pages; continue; } if (zone_balanced(zone, order, 0, i)) balanced_pages += zone->managed_pages; else if (!order) return false; } if (order) return balanced_pages >= (managed_pages >> 2); else return true; } /* * Prepare kswapd for sleeping. This verifies that there are no processes * waiting in throttle_direct_reclaim() and that watermarks have been met. * * Returns true if kswapd is ready to sleep */ static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining, int classzone_idx) { /* If a direct reclaimer woke kswapd within HZ/10, it's premature */ if (remaining) return false; /* * The throttled processes are normally woken up in balance_pgdat() as * soon as pfmemalloc_watermark_ok() is true. But there is a potential * race between when kswapd checks the watermarks and a process gets * throttled. There is also a potential race if processes get * throttled, kswapd wakes, a large process exits thereby balancing the * zones, which causes kswapd to exit balance_pgdat() before reaching * the wake up checks. If kswapd is going to sleep, no process should * be sleeping on pfmemalloc_wait, so wake them now if necessary. If * the wake up is premature, processes will wake kswapd and get * throttled again. The difference from wake ups in balance_pgdat() is * that here we are under prepare_to_wait(). */ if (waitqueue_active(&pgdat->pfmemalloc_wait)) wake_up_all(&pgdat->pfmemalloc_wait); return pgdat_balanced(pgdat, order, classzone_idx); } /* * kswapd shrinks the zone by the number of pages required to reach * the high watermark. * * Returns true if kswapd scanned at least the requested number of pages to * reclaim or if the lack of progress was due to pages under writeback. * This is used to determine if the scanning priority needs to be raised. */ static bool kswapd_shrink_zone(struct zone *zone, int classzone_idx, struct scan_control *sc, unsigned long *nr_attempted) { int testorder = sc->order; unsigned long balance_gap; bool lowmem_pressure; /* Reclaim above the high watermark. */ sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone)); /* * Kswapd reclaims only single pages with compaction enabled. Trying * too hard to reclaim until contiguous free pages have become * available can hurt performance by evicting too much useful data * from memory. Do not reclaim more than needed for compaction. */ if (IS_ENABLED(CONFIG_COMPACTION) && sc->order && compaction_suitable(zone, sc->order, 0, classzone_idx) != COMPACT_SKIPPED) testorder = 0; /* * We put equal pressure on every zone, unless one zone has way too * many pages free already. The "too many pages" is defined as the * high wmark plus a "gap" where the gap is either the low * watermark or 1% of the zone, whichever is smaller. */ balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP( zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO)); /* * If there is no low memory pressure or the zone is balanced then no * reclaim is necessary */ lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone)); if (!lowmem_pressure && zone_balanced(zone, testorder, balance_gap, classzone_idx)) return true; shrink_zone(zone, sc, zone_idx(zone) == classzone_idx); /* Account for the number of pages attempted to reclaim */ *nr_attempted += sc->nr_to_reclaim; clear_bit(ZONE_WRITEBACK, &zone->flags); /* * If a zone reaches its high watermark, consider it to be no longer * congested. It's possible there are dirty pages backed by congested * BDIs but as pressure is relieved, speculatively avoid congestion * waits. */ if (zone_reclaimable(zone) && zone_balanced(zone, testorder, 0, classzone_idx)) { clear_bit(ZONE_CONGESTED, &zone->flags); clear_bit(ZONE_DIRTY, &zone->flags); } return sc->nr_scanned >= sc->nr_to_reclaim; } /* * For kswapd, balance_pgdat() will work across all this node's zones until * they are all at high_wmark_pages(zone). * * Returns the final order kswapd was reclaiming at * * There is special handling here for zones which are full of pinned pages. * This can happen if the pages are all mlocked, or if they are all used by * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb. * What we do is to detect the case where all pages in the zone have been * scanned twice and there has been zero successful reclaim. Mark the zone as * dead and from now on, only perform a short scan. Basically we're polling * the zone for when the problem goes away. * * kswapd scans the zones in the highmem->normal->dma direction. It skips * zones which have free_pages > high_wmark_pages(zone), but once a zone is * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the * lower zones regardless of the number of free pages in the lower zones. This * interoperates with the page allocator fallback scheme to ensure that aging * of pages is balanced across the zones. */ static unsigned long balance_pgdat(pg_data_t *pgdat, int order, int *classzone_idx) { int i; int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */ unsigned long nr_soft_reclaimed; unsigned long nr_soft_scanned; struct scan_control sc = { .gfp_mask = GFP_KERNEL, .order = order, .priority = DEF_PRIORITY, .may_writepage = !laptop_mode, .may_unmap = 1, .may_swap = 1, }; count_vm_event(PAGEOUTRUN); do { unsigned long nr_attempted = 0; bool raise_priority = true; bool pgdat_needs_compaction = (order > 0); sc.nr_reclaimed = 0; /* * Scan in the highmem->dma direction for the highest * zone which needs scanning */ for (i = pgdat->nr_zones - 1; i >= 0; i--) { struct zone *zone = pgdat->node_zones + i; if (!populated_zone(zone)) continue; if (sc.priority != DEF_PRIORITY && !zone_reclaimable(zone)) continue; /* * Do some background aging of the anon list, to give * pages a chance to be referenced before reclaiming. */ age_active_anon(zone, &sc); /* * If the number of buffer_heads in the machine * exceeds the maximum allowed level and this node * has a highmem zone, force kswapd to reclaim from * it to relieve lowmem pressure. */ if (buffer_heads_over_limit && is_highmem_idx(i)) { end_zone = i; break; } if (!zone_balanced(zone, order, 0, 0)) { end_zone = i; break; } else { /* * If balanced, clear the dirty and congested * flags */ clear_bit(ZONE_CONGESTED, &zone->flags); clear_bit(ZONE_DIRTY, &zone->flags); } } if (i < 0) goto out; for (i = 0; i <= end_zone; i++) { struct zone *zone = pgdat->node_zones + i; if (!populated_zone(zone)) continue; /* * If any zone is currently balanced then kswapd will * not call compaction as it is expected that the * necessary pages are already available. */ if (pgdat_needs_compaction && zone_watermark_ok(zone, order, low_wmark_pages(zone), *classzone_idx, 0)) pgdat_needs_compaction = false; } /* * If we're getting trouble reclaiming, start doing writepage * even in laptop mode. */ if (sc.priority < DEF_PRIORITY - 2) sc.may_writepage = 1; /* * Now scan the zone in the dma->highmem direction, stopping * at the last zone which needs scanning. * * We do this because the page allocator works in the opposite * direction. This prevents the page allocator from allocating * pages behind kswapd's direction of progress, which would * cause too much scanning of the lower zones. */ for (i = 0; i <= end_zone; i++) { struct zone *zone = pgdat->node_zones + i; if (!populated_zone(zone)) continue; if (sc.priority != DEF_PRIORITY && !zone_reclaimable(zone)) continue; sc.nr_scanned = 0; nr_soft_scanned = 0; /* * Call soft limit reclaim before calling shrink_zone. */ nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone, order, sc.gfp_mask, &nr_soft_scanned); sc.nr_reclaimed += nr_soft_reclaimed; /* * There should be no need to raise the scanning * priority if enough pages are already being scanned * that that high watermark would be met at 100% * efficiency. */ if (kswapd_shrink_zone(zone, end_zone, &sc, &nr_attempted)) raise_priority = false; } /* * If the low watermark is met there is no need for processes * to be throttled on pfmemalloc_wait as they should not be * able to safely make forward progress. Wake them */ if (waitqueue_active(&pgdat->pfmemalloc_wait) && pfmemalloc_watermark_ok(pgdat)) wake_up_all(&pgdat->pfmemalloc_wait); /* * Fragmentation may mean that the system cannot be rebalanced * for high-order allocations in all zones. If twice the * allocation size has been reclaimed and the zones are still * not balanced then recheck the watermarks at order-0 to * prevent kswapd reclaiming excessively. Assume that a * process requested a high-order can direct reclaim/compact. */ if (order && sc.nr_reclaimed >= 2UL << order) order = sc.order = 0; /* Check if kswapd should be suspending */ if (try_to_freeze() || kthread_should_stop()) break; /* * Compact if necessary and kswapd is reclaiming at least the * high watermark number of pages as requsted */ if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted) compact_pgdat(pgdat, order); /* * Raise priority if scanning rate is too low or there was no * progress in reclaiming pages */ if (raise_priority || !sc.nr_reclaimed) sc.priority--; } while (sc.priority >= 1 && !pgdat_balanced(pgdat, order, *classzone_idx)); out: /* * Return the order we were reclaiming at so prepare_kswapd_sleep() * makes a decision on the order we were last reclaiming at. However, * if another caller entered the allocator slow path while kswapd * was awake, order will remain at the higher level */ *classzone_idx = end_zone; return order; } static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx) { long remaining = 0; DEFINE_WAIT(wait); if (freezing(current) || kthread_should_stop()) return; prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); /* Try to sleep for a short interval */ if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) { remaining = schedule_timeout(HZ/10); finish_wait(&pgdat->kswapd_wait, &wait); prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE); } /* * After a short sleep, check if it was a premature sleep. If not, then * go fully to sleep until explicitly woken up. */ if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) { trace_mm_vmscan_kswapd_sleep(pgdat->node_id); /* * vmstat counters are not perfectly accurate and the estimated * value for counters such as NR_FREE_PAGES can deviate from the * true value by nr_online_cpus * threshold. To avoid the zone * watermarks being breached while under pressure, we reduce the * per-cpu vmstat threshold while kswapd is awake and restore * them before going back to sleep. */ set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold); /* * Compaction records what page blocks it recently failed to * isolate pages from and skips them in the future scanning. * When kswapd is going to sleep, it is reasonable to assume * that pages and compaction may succeed so reset the cache. */ reset_isolation_suitable(pgdat); if (!kthread_should_stop()) schedule(); set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold); } else { if (remaining) count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY); else count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY); } finish_wait(&pgdat->kswapd_wait, &wait); } /* * The background pageout daemon, started as a kernel thread * from the init process. * * This basically trickles out pages so that we have _some_ * free memory available even if there is no other activity * that frees anything up. This is needed for things like routing * etc, where we otherwise might have all activity going on in * asynchronous contexts that cannot page things out. * * If there are applications that are active memory-allocators * (most normal use), this basically shouldn't matter. */ static int kswapd(void *p) { unsigned long order, new_order; unsigned balanced_order; int classzone_idx, new_classzone_idx; int balanced_classzone_idx; pg_data_t *pgdat = (pg_data_t*)p; struct task_struct *tsk = current; struct reclaim_state reclaim_state = { .reclaimed_slab = 0, }; const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id); lockdep_set_current_reclaim_state(GFP_KERNEL); if (!cpumask_empty(cpumask)) set_cpus_allowed_ptr(tsk, cpumask); current->reclaim_state = &reclaim_state; /* * Tell the memory management that we're a "memory allocator", * and that if we need more memory we should get access to it * regardless (see "__alloc_pages()"). "kswapd" should * never get caught in the normal page freeing logic. * * (Kswapd normally doesn't need memory anyway, but sometimes * you need a small amount of memory in order to be able to * page out something else, and this flag essentially protects * us from recursively trying to free more memory as we're * trying to free the first piece of memory in the first place). */ tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD; set_freezable(); order = new_order = 0; balanced_order = 0; classzone_idx = new_classzone_idx = pgdat->nr_zones - 1; balanced_classzone_idx = classzone_idx; for ( ; ; ) { bool ret; /* * If the last balance_pgdat was unsuccessful it's unlikely a * new request of a similar or harder type will succeed soon * so consider going to sleep on the basis we reclaimed at */ if (balanced_classzone_idx >= new_classzone_idx && balanced_order == new_order) { new_order = pgdat->kswapd_max_order; new_classzone_idx = pgdat->classzone_idx; pgdat->kswapd_max_order = 0; pgdat->classzone_idx = pgdat->nr_zones - 1; } if (order < new_order || classzone_idx > new_classzone_idx) { /* * Don't sleep if someone wants a larger 'order' * allocation or has tigher zone constraints */ order = new_order; classzone_idx = new_classzone_idx; } else { kswapd_try_to_sleep(pgdat, balanced_order, balanced_classzone_idx); order = pgdat->kswapd_max_order; classzone_idx = pgdat->classzone_idx; new_order = order; new_classzone_idx = classzone_idx; pgdat->kswapd_max_order = 0; pgdat->classzone_idx = pgdat->nr_zones - 1; } ret = try_to_freeze(); if (kthread_should_stop()) break; /* * We can speed up thawing tasks if we don't call balance_pgdat * after returning from the refrigerator */ if (!ret) { trace_mm_vmscan_kswapd_wake(pgdat->node_id, order); balanced_classzone_idx = classzone_idx; balanced_order = balance_pgdat(pgdat, order, &balanced_classzone_idx); } } tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD); current->reclaim_state = NULL; lockdep_clear_current_reclaim_state(); return 0; } /* * A zone is low on free memory, so wake its kswapd task to service it. */ void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx) { pg_data_t *pgdat; if (!populated_zone(zone)) return; if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL)) return; pgdat = zone->zone_pgdat; if (pgdat->kswapd_max_order < order) { pgdat->kswapd_max_order = order; pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx); } if (!waitqueue_active(&pgdat->kswapd_wait)) return; if (zone_balanced(zone, order, 0, 0)) return; trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order); wake_up_interruptible(&pgdat->kswapd_wait); } #ifdef CONFIG_HIBERNATION /* * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of * freed pages. * * Rather than trying to age LRUs the aim is to preserve the overall * LRU order by reclaiming preferentially * inactive > active > active referenced > active mapped */ unsigned long shrink_all_memory(unsigned long nr_to_reclaim) { struct reclaim_state reclaim_state; struct scan_control sc = { .nr_to_reclaim = nr_to_reclaim, .gfp_mask = GFP_HIGHUSER_MOVABLE, .priority = DEF_PRIORITY, .may_writepage = 1, .may_unmap = 1, .may_swap = 1, .hibernation_mode = 1, }; struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask); struct task_struct *p = current; unsigned long nr_reclaimed; p->flags |= PF_MEMALLOC; lockdep_set_current_reclaim_state(sc.gfp_mask); reclaim_state.reclaimed_slab = 0; p->reclaim_state = &reclaim_state; nr_reclaimed = do_try_to_free_pages(zonelist, &sc); p->reclaim_state = NULL; lockdep_clear_current_reclaim_state(); p->flags &= ~PF_MEMALLOC; return nr_reclaimed; } #endif /* CONFIG_HIBERNATION */ /* It's optimal to keep kswapds on the same CPUs as their memory, but not required for correctness. So if the last cpu in a node goes away, we get changed to run anywhere: as the first one comes back, restore their cpu bindings. */ static int cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { int nid; if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) { for_each_node_state(nid, N_MEMORY) { pg_data_t *pgdat = NODE_DATA(nid); const struct cpumask *mask; mask = cpumask_of_node(pgdat->node_id); if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids) /* One of our CPUs online: restore mask */ set_cpus_allowed_ptr(pgdat->kswapd, mask); } } return NOTIFY_OK; } /* * This kswapd start function will be called by init and node-hot-add. * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added. */ int kswapd_run(int nid) { pg_data_t *pgdat = NODE_DATA(nid); int ret = 0; if (pgdat->kswapd) return 0; pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid); if (IS_ERR(pgdat->kswapd)) { /* failure at boot is fatal */ BUG_ON(system_state == SYSTEM_BOOTING); pr_err("Failed to start kswapd on node %d\n", nid); ret = PTR_ERR(pgdat->kswapd); pgdat->kswapd = NULL; } return ret; } /* * Called by memory hotplug when all memory in a node is offlined. Caller must * hold mem_hotplug_begin/end(). */ void kswapd_stop(int nid) { struct task_struct *kswapd = NODE_DATA(nid)->kswapd; if (kswapd) { kthread_stop(kswapd); NODE_DATA(nid)->kswapd = NULL; } } static int __init kswapd_init(void) { int nid; swap_setup(); for_each_node_state(nid, N_MEMORY) kswapd_run(nid); hotcpu_notifier(cpu_callback, 0); return 0; } module_init(kswapd_init) #ifdef CONFIG_NUMA /* * Zone reclaim mode * * If non-zero call zone_reclaim when the number of free pages falls below * the watermarks. */ int zone_reclaim_mode __read_mostly; #define RECLAIM_OFF 0 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */ #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */ #define RECLAIM_UNMAP (1<<2) /* Unmap pages during reclaim */ /* * Priority for ZONE_RECLAIM. This determines the fraction of pages * of a node considered for each zone_reclaim. 4 scans 1/16th of * a zone. */ #define ZONE_RECLAIM_PRIORITY 4 /* * Percentage of pages in a zone that must be unmapped for zone_reclaim to * occur. */ int sysctl_min_unmapped_ratio = 1; /* * If the number of slab pages in a zone grows beyond this percentage then * slab reclaim needs to occur. */ int sysctl_min_slab_ratio = 5; static inline unsigned long zone_unmapped_file_pages(struct zone *zone) { unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED); unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) + zone_page_state(zone, NR_ACTIVE_FILE); /* * It's possible for there to be more file mapped pages than * accounted for by the pages on the file LRU lists because * tmpfs pages accounted for as ANON can also be FILE_MAPPED */ return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0; } /* Work out how many page cache pages we can reclaim in this reclaim_mode */ static long zone_pagecache_reclaimable(struct zone *zone) { long nr_pagecache_reclaimable; long delta = 0; /* * If RECLAIM_UNMAP is set, then all file pages are considered * potentially reclaimable. Otherwise, we have to worry about * pages like swapcache and zone_unmapped_file_pages() provides * a better estimate */ if (zone_reclaim_mode & RECLAIM_UNMAP) nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES); else nr_pagecache_reclaimable = zone_unmapped_file_pages(zone); /* If we can't clean pages, remove dirty pages from consideration */ if (!(zone_reclaim_mode & RECLAIM_WRITE)) delta += zone_page_state(zone, NR_FILE_DIRTY); /* Watch for any possible underflows due to delta */ if (unlikely(delta > nr_pagecache_reclaimable)) delta = nr_pagecache_reclaimable; return nr_pagecache_reclaimable - delta; } /* * Try to free up some pages from this zone through reclaim. */ static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) { /* Minimum pages needed in order to stay on node */ const unsigned long nr_pages = 1 << order; struct task_struct *p = current; struct reclaim_state reclaim_state; struct scan_control sc = { .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX), .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)), .order = order, .priority = ZONE_RECLAIM_PRIORITY, .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE), .may_unmap = !!(zone_reclaim_mode & RECLAIM_UNMAP), .may_swap = 1, }; cond_resched(); /* * We need to be able to allocate from the reserves for RECLAIM_UNMAP * and we also need to be able to write out pages for RECLAIM_WRITE * and RECLAIM_UNMAP. */ p->flags |= PF_MEMALLOC | PF_SWAPWRITE; lockdep_set_current_reclaim_state(gfp_mask); reclaim_state.reclaimed_slab = 0; p->reclaim_state = &reclaim_state; if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) { /* * Free memory by calling shrink zone with increasing * priorities until we have enough memory freed. */ do { shrink_zone(zone, &sc, true); } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0); } p->reclaim_state = NULL; current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE); lockdep_clear_current_reclaim_state(); return sc.nr_reclaimed >= nr_pages; } int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order) { int node_id; int ret; /* * Zone reclaim reclaims unmapped file backed pages and * slab pages if we are over the defined limits. * * A small portion of unmapped file backed pages is needed for * file I/O otherwise pages read by file I/O will be immediately * thrown out if the zone is overallocated. So we do not reclaim * if less than a specified percentage of the zone is used by * unmapped file backed pages. */ if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages && zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages) return ZONE_RECLAIM_FULL; if (!zone_reclaimable(zone)) return ZONE_RECLAIM_FULL; /* * Do not scan if the allocation should not be delayed. */ if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC)) return ZONE_RECLAIM_NOSCAN; /* * Only run zone reclaim on the local zone or on zones that do not * have associated processors. This will favor the local processor * over remote processors and spread off node memory allocations * as wide as possible. */ node_id = zone_to_nid(zone); if (node_state(node_id, N_CPU) && node_id != numa_node_id()) return ZONE_RECLAIM_NOSCAN; if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags)) return ZONE_RECLAIM_NOSCAN; ret = __zone_reclaim(zone, gfp_mask, order); clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags); if (!ret) count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED); return ret; } #endif /* * page_evictable - test whether a page is evictable * @page: the page to test * * Test whether page is evictable--i.e., should be placed on active/inactive * lists vs unevictable list. * * Reasons page might not be evictable: * (1) page's mapping marked unevictable * (2) page is part of an mlocked VMA * */ int page_evictable(struct page *page) { return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page); } #ifdef CONFIG_SHMEM /** * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list * @pages: array of pages to check * @nr_pages: number of pages to check * * Checks pages for evictability and moves them to the appropriate lru list. * * This function is only used for SysV IPC SHM_UNLOCK. */ void check_move_unevictable_pages(struct page **pages, int nr_pages) { struct lruvec *lruvec; struct zone *zone = NULL; int pgscanned = 0; int pgrescued = 0; int i; for (i = 0; i < nr_pages; i++) { struct page *page = pages[i]; struct zone *pagezone; pgscanned++; pagezone = page_zone(page); if (pagezone != zone) { if (zone) spin_unlock_irq(&zone->lru_lock); zone = pagezone; spin_lock_irq(&zone->lru_lock); } lruvec = mem_cgroup_page_lruvec(page, zone); if (!PageLRU(page) || !PageUnevictable(page)) continue; if (page_evictable(page)) { enum lru_list lru = page_lru_base_type(page); VM_BUG_ON_PAGE(PageActive(page), page); ClearPageUnevictable(page); del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE); add_page_to_lru_list(page, lruvec, lru); pgrescued++; } } if (zone) { __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued); __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned); spin_unlock_irq(&zone->lru_lock); } } #endif /* CONFIG_SHMEM */
Basler/linux-usb-zerocopy
mm/vmscan.c
C
gpl-2.0
112,737
/* Copyright (C) 2000 MySQL AB 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; version 2 of the License. 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 <my_global.h> #include <m_string.h> #include <stdarg.h> #include <m_ctype.h> #define MAX_ARGS 32 /* max positional args count*/ #define MAX_PRINT_INFO 32 /* max print position count */ #define LENGTH_ARG 1 #define WIDTH_ARG 2 #define PREZERO_ARG 4 #define ESCAPED_ARG 8 typedef struct pos_arg_info ARGS_INFO; typedef struct print_info PRINT_INFO; struct pos_arg_info { char arg_type; /* argument type */ uint have_longlong; /* used from integer values */ char *str_arg; /* string value of the arg */ longlong longlong_arg; /* integer value of the arg */ double double_arg; /* double value of the arg */ }; struct print_info { char arg_type; /* argument type */ size_t arg_idx; /* index of the positional arg */ size_t length; /* print width or arg index */ size_t width; /* print width or arg index */ uint flags; const char *begin; /**/ const char *end; /**/ }; /** Calculates print length or index of positional argument @param fmt processed string @param length print length or index of positional argument @param pre_zero returns flags with PREZERO_ARG set if necessary @retval string position right after length digits */ static const char *get_length(const char *fmt, size_t *length, uint *pre_zero) { for (; my_isdigit(&my_charset_latin1, *fmt); fmt++) { *length= *length * 10 + (uint)(*fmt - '0'); if (!*length) *pre_zero|= PREZERO_ARG; /* first digit was 0 */ } return fmt; } /** Calculates print width or index of positional argument @param fmt processed string @param width print width or index of positional argument @retval string position right after width digits */ static const char *get_width(const char *fmt, size_t *width) { for (; my_isdigit(&my_charset_latin1, *fmt); fmt++) { *width= *width * 10 + (uint)(*fmt - '0'); } return fmt; } /** Calculates print width or index of positional argument @param fmt processed string @param have_longlong TRUE if longlong is required @retval string position right after modifier symbol */ static const char *check_longlong(const char *fmt, uint *have_longlong) { *have_longlong= 0; if (*fmt == 'l') { fmt++; if (*fmt != 'l') *have_longlong= (sizeof(long) == sizeof(longlong)); else { fmt++; *have_longlong= 1; } } else if (*fmt == 'z') { fmt++; *have_longlong= (sizeof(size_t) == sizeof(longlong)); } return fmt; } /** Returns escaped string @param cs string charset @param to buffer where escaped string will be placed @param end end of buffer @param par string to escape @param par_len string length @param quote_char character for quoting @retval position in buffer which points on the end of escaped string */ static char *backtick_string(CHARSET_INFO *cs, char *to, char *end, char *par, size_t par_len, char quote_char) { uint char_len; char *start= to; char *par_end= par + par_len; size_t buff_length= (size_t) (end - to); if (buff_length <= par_len) goto err; *start++= quote_char; for ( ; par < par_end; par+= char_len) { uchar c= *(uchar *) par; if (!(char_len= my_mbcharlen(cs, c))) char_len= 1; if (char_len == 1 && c == (uchar) quote_char ) { if (start + 1 >= end) goto err; *start++= quote_char; } if (start + char_len >= end) goto err; start= strnmov(start, par, char_len); } if (start + 1 >= end) goto err; *start++= quote_char; return start; err: *to='\0'; return to; } /** Prints string argument */ static char *process_str_arg(CHARSET_INFO *cs, char *to, char *end, size_t width, char *par, uint print_type) { int well_formed_error; size_t plen, left_len= (size_t) (end - to) + 1; if (!par) par = (char*) "(null)"; plen= strnlen(par, width); if (left_len <= plen) plen = left_len - 1; plen= cs->cset->well_formed_len(cs, par, par + plen, width, &well_formed_error); if (print_type & ESCAPED_ARG) to= backtick_string(cs, to, end, par, plen, '`'); else to= strnmov(to,par,plen); return to; } /** Prints binary argument */ static char *process_bin_arg(char *to, char *end, size_t width, char *par) { DBUG_ASSERT(to <= end); if (to + width + 1 > end) width= end - to - 1; /* sign doesn't matter */ memmove(to, par, width); to+= width; return to; } /** Prints double or float argument */ static char *process_dbl_arg(char *to, char *end, size_t width, double par, char arg_type) { if (width == SIZE_T_MAX) width= FLT_DIG; /* width not set, use default */ else if (width >= NOT_FIXED_DEC) width= NOT_FIXED_DEC - 1; /* max.precision for my_fcvt() */ width= min(width, (size_t)(end-to) - 1); if (arg_type == 'f') to+= my_fcvt(par, (int)width , to, NULL); else to+= my_gcvt(par, MY_GCVT_ARG_DOUBLE, (int) width , to, NULL); return to; } /** Prints integer argument */ static char *process_int_arg(char *to, char *end, size_t length, longlong par, char arg_type, uint print_type) { size_t res_length, to_length; char *store_start= to, *store_end; char buff[32]; if ((to_length= (size_t) (end-to)) < 16 || length) store_start= buff; if (arg_type == 'd' || arg_type == 'i') store_end= longlong10_to_str(par, store_start, -10); else if (arg_type == 'u') store_end= longlong10_to_str(par, store_start, 10); else if (arg_type == 'p') { store_start[0]= '0'; store_start[1]= 'x'; store_end= ll2str(par, store_start + 2, 16, 0); } else if (arg_type == 'o') { store_end= ll2str(par, store_start, 8, 0); } else { DBUG_ASSERT(arg_type == 'X' || arg_type =='x'); store_end= ll2str(par, store_start, 16, (arg_type == 'X')); } if ((res_length= (size_t) (store_end - store_start)) > to_length) return to; /* num doesn't fit in output */ /* If %#d syntax was used, we have to pre-zero/pre-space the string */ if (store_start == buff) { length= min(length, to_length); if (res_length < length) { size_t diff= (length- res_length); bfill(to, diff, (print_type & PREZERO_ARG) ? '0' : ' '); if (arg_type == 'p' && print_type & PREZERO_ARG) { if (diff > 1) to[1]= 'x'; else store_start[0]= 'x'; store_start[1]= '0'; } to+= diff; } bmove(to, store_start, res_length); } to+= res_length; return to; } /** Procesed positional arguments. @param cs string charset @param to buffer where processed string will be place @param end end of buffer @param par format string @param arg_index arg index of the first occurrence of positional arg @param ap list of parameters @retval end of buffer where processed string is placed */ static char *process_args(CHARSET_INFO *cs, char *to, char *end, const char* fmt, size_t arg_index, va_list ap) { ARGS_INFO args_arr[MAX_ARGS]; PRINT_INFO print_arr[MAX_PRINT_INFO]; uint idx= 0, arg_count= arg_index; start: /* Here we are at the beginning of positional argument, right after $ */ arg_index--; print_arr[idx].flags= 0; if (*fmt == '`') { print_arr[idx].flags|= ESCAPED_ARG; fmt++; } if (*fmt == '-') fmt++; print_arr[idx].length= print_arr[idx].width= 0; /* Get print length */ if (*fmt == '*') { fmt++; fmt= get_length(fmt, &print_arr[idx].length, &print_arr[idx].flags); print_arr[idx].length--; DBUG_ASSERT(*fmt == '$' && print_arr[idx].length < MAX_ARGS); args_arr[print_arr[idx].length].arg_type= 'd'; print_arr[idx].flags|= LENGTH_ARG; arg_count= max(arg_count, print_arr[idx].length + 1); fmt++; } else fmt= get_length(fmt, &print_arr[idx].length, &print_arr[idx].flags); if (*fmt == '.') { fmt++; /* Get print width */ if (*fmt == '*') { fmt++; fmt= get_width(fmt, &print_arr[idx].width); print_arr[idx].width--; DBUG_ASSERT(*fmt == '$' && print_arr[idx].width < MAX_ARGS); args_arr[print_arr[idx].width].arg_type= 'd'; print_arr[idx].flags|= WIDTH_ARG; arg_count= max(arg_count, print_arr[idx].width + 1); fmt++; } else fmt= get_width(fmt, &print_arr[idx].width); } else print_arr[idx].width= SIZE_T_MAX; fmt= check_longlong(fmt, &args_arr[arg_index].have_longlong); if (*fmt == 'p') args_arr[arg_index].have_longlong= (sizeof(void *) == sizeof(longlong)); args_arr[arg_index].arg_type= print_arr[idx].arg_type= *fmt; print_arr[idx].arg_idx= arg_index; print_arr[idx].begin= ++fmt; while (*fmt && *fmt != '%') fmt++; if (!*fmt) /* End of format string */ { uint i; print_arr[idx].end= fmt; /* Obtain parameters from the list */ for (i= 0 ; i < arg_count; i++) { switch (args_arr[i].arg_type) { case 's': case 'b': args_arr[i].str_arg= va_arg(ap, char *); break; case 'f': case 'g': args_arr[i].double_arg= va_arg(ap, double); break; case 'd': case 'i': case 'u': case 'x': case 'X': case 'o': case 'p': if (args_arr[i].have_longlong) args_arr[i].longlong_arg= va_arg(ap,longlong); else if (args_arr[i].arg_type == 'd' || args_arr[i].arg_type == 'i') args_arr[i].longlong_arg= va_arg(ap, int); else args_arr[i].longlong_arg= va_arg(ap, uint); break; case 'c': args_arr[i].longlong_arg= va_arg(ap, int); break; default: DBUG_ASSERT(0); } } /* Print result string */ for (i= 0; i <= idx; i++) { size_t width= 0, length= 0; switch (print_arr[i].arg_type) { case 's': { char *par= args_arr[print_arr[i].arg_idx].str_arg; width= (print_arr[i].flags & WIDTH_ARG) ? (size_t)args_arr[print_arr[i].width].longlong_arg : print_arr[i].width; to= process_str_arg(cs, to, end, width, par, print_arr[i].flags); break; } case 'b': { char *par = args_arr[print_arr[i].arg_idx].str_arg; width= (print_arr[i].flags & WIDTH_ARG) ? (size_t)args_arr[print_arr[i].width].longlong_arg : print_arr[i].width; to= process_bin_arg(to, end, width, par); break; } case 'c': { if (to == end) break; *to++= (char) args_arr[print_arr[i].arg_idx].longlong_arg; break; } case 'f': case 'g': { double d= args_arr[print_arr[i].arg_idx].double_arg; width= (print_arr[i].flags & WIDTH_ARG) ? (uint)args_arr[print_arr[i].width].longlong_arg : print_arr[i].width; to= process_dbl_arg(to, end, width, d, print_arr[i].arg_type); break; } case 'd': case 'i': case 'u': case 'x': case 'X': case 'o': case 'p': { /* Integer parameter */ longlong larg; length= (print_arr[i].flags & LENGTH_ARG) ? (size_t)args_arr[print_arr[i].length].longlong_arg : print_arr[i].length; if (args_arr[print_arr[i].arg_idx].have_longlong) larg = args_arr[print_arr[i].arg_idx].longlong_arg; else if (print_arr[i].arg_type == 'd' || print_arr[i].arg_type == 'i' ) larg = (int) args_arr[print_arr[i].arg_idx].longlong_arg; else larg= (uint) args_arr[print_arr[i].arg_idx].longlong_arg; to= process_int_arg(to, end, length, larg, print_arr[i].arg_type, print_arr[i].flags); break; } default: break; } if (to == end) break; length= min(end - to , print_arr[i].end - print_arr[i].begin); if (to + length < end) length++; to= strnmov(to, print_arr[i].begin, length); } DBUG_ASSERT(to <= end); *to='\0'; /* End of errmessage */ return to; } else { /* Process next positional argument*/ DBUG_ASSERT(*fmt == '%'); print_arr[idx].end= fmt - 1; idx++; fmt++; arg_index= 0; fmt= get_width(fmt, &arg_index); DBUG_ASSERT(*fmt == '$'); fmt++; arg_count= max(arg_count, arg_index); goto start; } return 0; } /** Produces output string according to a format string See the detailed documentation around my_snprintf_service_st @param cs string charset @param to buffer where processed string will be place @param n size of buffer @param par format string @param ap list of parameters @retval length of result string */ size_t my_vsnprintf_ex(CHARSET_INFO *cs, char *to, size_t n, const char* fmt, va_list ap) { char *start=to, *end=to+n-1; size_t length, width; uint print_type, have_longlong; for (; *fmt ; fmt++) { if (*fmt != '%') { if (to == end) /* End of buffer */ break; *to++= *fmt; /* Copy ordinary char */ continue; } fmt++; /* skip '%' */ length= width= 0; print_type= 0; /* Read max fill size (only used with %d and %u) */ if (my_isdigit(&my_charset_latin1, *fmt)) { fmt= get_length(fmt, &length, &print_type); if (*fmt == '$') { to= process_args(cs, to, end, (fmt+1), length, ap); return (size_t) (to - start); } } else { if (*fmt == '`') { print_type|= ESCAPED_ARG; fmt++; } if (*fmt == '-') fmt++; if (*fmt == '*') { fmt++; length= va_arg(ap, int); } else fmt= get_length(fmt, &length, &print_type); } if (*fmt == '.') { fmt++; if (*fmt == '*') { fmt++; width= va_arg(ap, int); } else fmt= get_width(fmt, &width); } else width= SIZE_T_MAX; fmt= check_longlong(fmt, &have_longlong); if (*fmt == 's') /* String parameter */ { reg2 char *par= va_arg(ap, char *); to= process_str_arg(cs, to, end, width, par, print_type); continue; } else if (*fmt == 'b') /* Buffer parameter */ { char *par = va_arg(ap, char *); to= process_bin_arg(to, end, width, par); continue; } else if (*fmt == 'f' || *fmt == 'g') { double d= va_arg(ap, double); to= process_dbl_arg(to, end, width, d, *fmt); continue; } else if (*fmt == 'd' || *fmt == 'i' || *fmt == 'u' || *fmt == 'x' || *fmt == 'X' || *fmt == 'p' || *fmt == 'o') { /* Integer parameter */ longlong larg; if (*fmt == 'p') have_longlong= (sizeof(void *) == sizeof(longlong)); if (have_longlong) larg = va_arg(ap,longlong); else if (*fmt == 'd' || *fmt == 'i') larg = va_arg(ap, int); else larg= va_arg(ap, uint); to= process_int_arg(to, end, length, larg, *fmt, print_type); continue; } else if (*fmt == 'c') /* Character parameter */ { register int larg; if (to == end) break; larg = va_arg(ap, int); *to++= (char) larg; continue; } /* We come here on '%%', unknown code or too long parameter */ if (to == end) break; *to++='%'; /* % used as % or unknown code */ } DBUG_ASSERT(to <= end); *to='\0'; /* End of errmessage */ return (size_t) (to - start); } /* Limited snprintf() implementations exported to plugins as a service, see the detailed documentation around my_snprintf_service_st */ size_t my_vsnprintf(char *to, size_t n, const char* fmt, va_list ap) { return my_vsnprintf_ex(&my_charset_latin1, to, n, fmt, ap); } size_t my_snprintf(char* to, size_t n, const char* fmt, ...) { size_t result; va_list args; va_start(args,fmt); result= my_vsnprintf(to, n, fmt, args); va_end(args); return result; }
drakeos/Dracore
dep/mysqllite/strings/my_vsnprintf.c
C
gpl-2.0
18,158
/* * linux/drivers/video/ti81xx/vpss/dctrl.c * * VPSS display controller driver for TI 81XX * * Copyright (C) 2009 TI * Author: Yihe Hu <yihehu@ti.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. */ #define VPSS_SUBMODULE_NAME "DCTRL" #include <linux/kernel.h> #include <linux/module.h> #include <linux/device.h> #include <linux/interrupt.h> #include <linux/err.h> #include <linux/sysfs.h> #include <linux/kobject.h> #include <linux/dma-mapping.h> #include <linux/slab.h> #include <mach/board-ti816x.h> #include "core.h" #include "system.h" #include "dc.h" static struct vps_dispctrl *disp_ctrl; static void *dc_handle; static struct vps_payload_info *dc_payload_info; /*store the current VENC setting*/ static struct vps_dcvencinfo venc_info = { { {VPS_DC_VENC_HDMI, {FVID2_STD_1080P_60, 1920, 1080, FVID2_SF_PROGRESSIVE,\ 148500, 60, 88, 148, 44, 4, 36, 5}, 3, 0, 0}, {VPS_DC_VENC_DVO2, {FVID2_STD_1080P_60, 1920, 1080, FVID2_SF_PROGRESSIVE,\ 148500, 60, 88, 148, 44, 4, 36, 5}, 3, 0, 0}, {VPS_DC_VENC_SD, {FVID2_STD_NTSC, 720, 480, FVID2_SF_INTERLACED,\ 216000, 60, 12, 68, 64, 5, 41, 5}, 0, 0, 0}, {VPS_DC_VENC_HDCOMP, {FVID2_STD_1080I_60, 1920, 1080, FVID2_SF_PROGRESSIVE,\ 74250, 60, 88, 148, 44, 2, 15, 5}, 2, 0, 0} }, 0, VPS_DC_MAX_VENC, }; /********************************************************** The name in the followig arrays are the value used in the sysfs. **********************************************************/ /*store the current mode info*/ static const struct dc_vencmode_info vmode_info[] = { {"ntsc", FVID2_STD_NTSC, {FVID2_STD_NTSC, 720, 480, FVID2_SF_INTERLACED, 216000, 60, 12, 68, 64, 5, 41, 5} }, {"pal", FVID2_STD_PAL, {FVID2_STD_PAL, 720, 576, FVID2_SF_INTERLACED, 216000, 50, 16, 58, 64, 6, 31, 6} }, {"1080p-60", FVID2_STD_1080P_60, {FVID2_STD_1080P_60, 1920, 1080, FVID2_SF_PROGRESSIVE, 148500, 60, 88, 148, 44, 4, 36, 5} }, {"1920x1080@60", FVID2_STD_1080P_60, {FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_PROGRESSIVE, 148500, 60, 88, 148, 44, 4, 36, 5} }, {"1080p-50", FVID2_STD_1080P_50, {FVID2_STD_1080P_50, 1920, 1080, FVID2_SF_PROGRESSIVE, 148500, 50, 528, 148, 44, 4, 36, 5} }, {"1920x1080@50", FVID2_STD_1080P_50, {FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_PROGRESSIVE, 148500, 50, 528, 148, 44, 4, 36, 5} }, {"1080p-30", FVID2_STD_1080P_30, {FVID2_STD_1080P_30, 1920, 1080, FVID2_SF_PROGRESSIVE, 74250, 30, 88, 148, 44, 4, 36, 5} }, {"1920x1080@30", FVID2_STD_1080P_30, {FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_PROGRESSIVE, 74250, 30, 88, 148, 44, 4, 36, 5} }, {"720p-60", FVID2_STD_720P_60, {FVID2_STD_720P_60, 1280, 720, FVID2_SF_PROGRESSIVE, 74250, 60, 110, 220, 40, 5, 20, 5} }, {"1280x720@60", FVID2_STD_720P_60, {FVID2_STD_CUSTOM, 1280, 720, FVID2_SF_PROGRESSIVE, 74250, 60, 110, 220, 40, 5, 20, 5} }, {"720p-50", FVID2_STD_720P_50, {FVID2_STD_720P_50, 1280, 720, FVID2_SF_PROGRESSIVE, 74250, 50, 440, 220, 40, 5, 20, 5} }, {"1280x720@50", FVID2_STD_720P_50, { FVID2_STD_CUSTOM, 1280, 720, FVID2_SF_PROGRESSIVE, 74250, 50, 440, 220, 40, 5, 20, 5} }, {"1080i-60", FVID2_STD_1080I_60, {FVID2_STD_1080I_60, 1920, 1080, FVID2_SF_INTERLACED, 74250, 60, 88, 148, 44, 2, 15, 5} }, {"1920x1080@60i", FVID2_STD_1080I_60, {FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_INTERLACED, 74250, 60, 88, 148, 44, 2, 15, 5} }, {"1080i-50", FVID2_STD_1080I_50, {FVID2_STD_1080I_50, 1920, 1080, FVID2_SF_INTERLACED, 742500, 50, 528, 148, 44, 2, 15, 5} }, {"1920x1080@50i", FVID2_STD_1080I_50, {FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_INTERLACED, 742500, 50, 528, 148, 44, 2, 15, 5} }, /*VGA*/ {"640x480@60", FVID2_STD_VGA_60, {FVID2_STD_CUSTOM, 640, 480, FVID2_SF_PROGRESSIVE, 25088, 60, 16, 48, 96, 10, 33, 2} }, {"640x480@72", FVID2_STD_VGA_72, {FVID2_STD_CUSTOM, 640, 480, FVID2_SF_PROGRESSIVE, 31488, 72, 24, 128, 40, 9, 29, 2} }, {"640x480@75", FVID2_STD_VGA_75, {FVID2_STD_CUSTOM, 640, 480, FVID2_SF_PROGRESSIVE, 31488, 75, 16, 120, 64, 1, 16, 3} }, {"640x480@85", FVID2_STD_VGA_85, {FVID2_STD_CUSTOM, 640, 480, FVID2_SF_PROGRESSIVE, 35840, 85, 56, 80, 56, 1, 25, 3} }, /*SVGA*/ {"800x600@60", FVID2_STD_SVGA_60, {FVID2_STD_CUSTOM, 800, 600, FVID2_SF_PROGRESSIVE, 39936, 60, 40, 88, 128, 1, 23, 4} }, {"800x600@72", FVID2_STD_SVGA_72, {FVID2_STD_CUSTOM, 800, 600, FVID2_SF_PROGRESSIVE, 49920, 72, 56, 64, 120, 37, 23, 6} }, {"800x600@75", FVID2_STD_SVGA_75, {FVID2_STD_CUSTOM, 800, 600, FVID2_SF_PROGRESSIVE, 49400, 75, 16, 160, 80, 1, 21, 3} }, {"800x600@85", FVID2_STD_SVGA_85, {FVID2_STD_CUSTOM, 800, 600, FVID2_SF_PROGRESSIVE, 56000, 85, 32, 152, 64, 1, 27, 3} }, /*XGA*/ {"1024x768@60", FVID2_STD_XGA_60, {FVID2_STD_XGA_60, 1024, 768, FVID2_SF_PROGRESSIVE, 65000, 60, 24, 160, 136, 3, 29, 6} }, {"1024x768@70", FVID2_STD_XGA_70, {FVID2_STD_CUSTOM, 1024, 768, FVID2_SF_PROGRESSIVE, 74752, 70, 24, 144, 136, 3, 29, 6} }, {"1024x768@75", FVID2_STD_XGA_75, {FVID2_STD_XGA_75, 1024, 768, FVID2_SF_PROGRESSIVE, 78720, 75, 16, 176, 96, 1, 28, 3} }, {"1024x768@85", FVID2_STD_XGA_85, {FVID2_STD_CUSTOM, 1024, 768, FVID2_SF_PROGRESSIVE, 94464, 85, 48, 208, 96, 1, 36, 3} }, /*SXGA*/ {"1280x1024@60", FVID2_STD_SXGA_60, {FVID2_STD_SXGA_60, 1280, 1024, FVID2_SF_PROGRESSIVE, 108000, 60, 48, 248, 112, 1, 38, 3} }, {"1280x1024@75", FVID2_STD_SXGA_75, {FVID2_STD_SXGA_75, 1280, 1024, FVID2_SF_PROGRESSIVE, 135000, 75, 16, 248, 144, 1, 38, 3} }, {"1280x1024@85", FVID2_STD_SXGA_85, {FVID2_STD_CUSTOM, 1280, 1024, FVID2_SF_PROGRESSIVE, 157440, 85, 64, 224, 160, 1, 44, 3} }, /*UXGA*/ {"1600x1200@60", FVID2_STD_UXGA_60, {FVID2_STD_UXGA_60, 1600, 1200, FVID2_SF_PROGRESSIVE, 162000, 60, 64, 304, 192, 1, 46, 3} } }; /*use for the venc name*/ static const struct dc_vencname_info venc_name[VPS_DC_MAX_VENC] = { {"hdmi", VPS_DC_VENC_HDMI, VPS_DC_HDMI_BLEND, HDMI}, {"dvo2", VPS_DC_VENC_DVO2, VPS_DC_DVO2_BLEND, DVO2}, {"sd", VPS_DC_VENC_SD, VPS_DC_SDVENC_BLEND, SDVENC}, {"hdcomp", VPS_DC_VENC_HDCOMP, VPS_DC_HDCOMP_BLEND, HDCOMP} }; /*use for pll sysfs*/ static const struct vps_sname_info pllvenc_name[] = { {"rfclk", VPS_SYSTEM_VPLL_OUTPUT_VENC_RF}, {"dclk", VPS_SYSTEM_VPLL_OUTPUT_VENC_D}, {"aclk", VPS_SYSTEM_VPLL_OUTPUT_VENC_A} }; /*used for clock source sysfs*/ static const struct vps_sname_info vclksrc_name[] = { {"dclk", VPS_DC_CLKSRC_VENCD}, {"dclkdiv2", VPS_DC_CLKSRC_VENCD_DIV2}, {"dclkdiff", VPS_DC_CLKSRC_VENCD_DIV2_DIFF}, {"aclk", VPS_DC_CLKSRC_VENCA}, {"aclkdiv2", VPS_DC_CLKSRC_VENCA_DIV2}, {"aclkdiff", VPS_DC_CLKSRC_VENCA_DIV2_DIFF} }; /*used for output sysfs*/ static const struct vps_sname_info dfmt_name[VPS_DC_DVOFMT_MAX] = { {"single", VPS_DC_DVOFMT_SINGLECHAN}, {"double", VPS_DC_DVOFMT_DOUBLECHAN}, {"triple", VPS_DC_DVOFMT_TRIPLECHAN_EMBSYNC}, {"triplediscrete", VPS_DC_DVOFMT_TRIPLECHAN_DISCSYNC}, {"doublediscrete", VPS_DC_DVOFMT_DOUBLECHAN_DISCSYNC}, }; /*used for output sysfs*/ static const struct vps_sname_info afmt_name[VPS_DC_A_OUTPUT_MAX] = { {"composite", VPS_DC_A_OUTPUT_COMPOSITE}, {"svideo", VPS_DC_A_OUTPUT_SVIDEO}, {"component", VPS_DC_A_OUTPUT_COMPONENT}, }; /*used for output sysfs*/ static const struct vps_sname_info datafmt_name[] = { {"rgb888", FVID2_DF_RGB24_888}, {"yuv444p", FVID2_DF_YUV444P}, {"yuv422spuv", FVID2_DF_YUV422SP_UV}, }; /*used for nodes sysfs*/ static const struct vps_sname_info dc_nodes[] = { {"main", VPS_DC_MAIN_INPUT_PATH}, /*0*/ {"vcompmux", VPS_DC_VCOMP_MUX}, /*1*/ {"hdcompmux", VPS_DC_HDCOMP_MUX}, /*2*/ {"sdmux", VPS_DC_SDVENC_MUX }, /*3*/ {"aux", VPS_DC_AUX_INPUT_PATH}, /*4*/ {"bp0", VPS_DC_BP0_INPUT_PATH}, /*5*/ {"bp1", VPS_DC_BP1_INPUT_PATH}, /*6*/ {"dummy", VPS_DC_MAX_NODE_NUM}, /*7*/ {"dummy", VPS_DC_MAX_NODE_NUM}, /*8*/ {"dummy", VPS_DC_MAX_NODE_NUM}, /*9*/ {"sd", VPS_DC_SEC1_INPUT_PATH}, /*10*/ {"dummy", VPS_DC_MAX_NODE_NUM}, /*11*/ {"dummy", VPS_DC_MAX_NODE_NUM}, /*12*/ {"dummy", VPS_DC_MAX_NODE_NUM}, /*13*/ {"vcomp", VPS_DC_VCOMP}, /*14*/ {"cigcons", VPS_DC_CIG_CONSTRAINED_OUTPUT}, /*15*/ {"cigin", VPS_DC_CIG_PIP_INPUT}, /*16*/ {"cigncons", VPS_DC_CIG_NON_CONSTRAINED_OUTPUT}, /*17*/ {"cigout", VPS_DC_CIG_PIP_OUTPUT}, /*18*/ {"grpx0", VPS_DC_GRPX0_INPUT_PATH}, /*19*/ {"grpx1", VPS_DC_GRPX1_INPUT_PATH}, /*20*/ {"grpx2", VPS_DC_GRPX2_INPUT_PATH}, /*21*/ {"hdmi", VPS_DC_HDMI_BLEND}, /*22*/ #ifdef CONFIG_ARCH_TI816X {"hdcomp", VPS_DC_HDCOMP_BLEND}, /*23*/ {"dvo2", VPS_DC_DVO2_BLEND}, /*24*/ {"sd", VPS_DC_SDVENC_BLEND}, /*25*/ #else {"dvo2", VPS_DC_DVO2_BLEND}, /*23*/ {"sd", VPS_DC_SDVENC_BLEND}, /*24*/ #endif }; /*S***************************private funtions*******************/ static inline void dc_lock(struct vps_dispctrl *dctrl) { mutex_lock(&dctrl->dcmutex); } static inline void dc_unlock(struct vps_dispctrl *dctrl) { mutex_unlock(&dctrl->dcmutex); } static inline bool isdigitalvenc(int vid) { if ((vid == VPS_DC_VENC_HDMI) || (vid == VPS_DC_VENC_DVO2)) return true; return false; } static inline bool isdigitalclk(u32 clk) { if ((clk == VPS_DC_CLKSRC_VENCA) || (clk == VPS_DC_CLKSRC_VENCA_DIV2) || (clk == VPS_DC_CLKSRC_VENCA_DIV2_DIFF)) return false; return true; } static inline bool isvalidclksrc(int vid, enum vps_dcvencclksrcsel clk) { if ((vid == VPS_DC_VENC_HDMI) && (!isdigitalclk(clk))) return false; /*ti814x, DVO2 must be aclk*/ if (cpu_is_ti814x()) { if ((vid == VPS_DC_VENC_DVO2) && (isdigitalclk(clk))) return false; } return true; } static inline bool isvalidmode(int vid, int mid) { switch (vid) { case VPS_DC_VENC_HDMI: if (cpu_is_ti816x()) case VPS_DC_VENC_HDCOMP: case VPS_DC_VENC_DVO2: if ((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL)) return false; break; case VPS_DC_VENC_SD: if (!((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL))) return false; break; } return true; } /*get the clock venc*/ static inline u32 get_plloutputvenc(int bidx) { struct vps_dcvencclksrc clksrc = disp_ctrl->blenders[bidx].clksrc; if (bidx == SDVENC) return VPS_SYSTEM_VPLL_OUTPUT_VENC_RF; if (cpu_is_ti814x()) return VPS_SYSTEM_VPLL_OUTPUT_VENC_D; if (isdigitalclk(clksrc.clksrc)) return VPS_SYSTEM_VPLL_OUTPUT_VENC_D; else return VPS_SYSTEM_VPLL_OUTPUT_VENC_A; } /*get the pixel clock for the standard mode*/ static inline int get_pllclock(u32 mid, u32 *freq) { int i; for (i = 0; i < ARRAY_SIZE(vmode_info); i++) { if (vmode_info[i].standard == mid) { *freq = vmode_info[i].minfo.pixelclock; if ((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL)) { if (cpu_is_ti814x()) *freq = 54000; } return 0; } } return -EINVAL; } /*get the current format based on the mode id*/ static int dc_get_format_from_mid(int mid, u32 *width, u32 *height, u8 *scformat) { int i; for (i = 0; i < ARRAY_SIZE(vmode_info); i++) { if (mid == vmode_info[i].standard) { *width = vmode_info[i].minfo.width; *height = vmode_info[i].minfo.height; *scformat = vmode_info[i].minfo.scanformat; return 0; } } return -EINVAL; } static int dc_get_timing(int mid, struct fvid2_modeinfo *minfo) { int i; for (i = 0; i < ARRAY_SIZE(vmode_info); i++) { if (mid == vmode_info[i].standard) { memcpy(minfo, &vmode_info[i].minfo, sizeof(*minfo)); if ((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL)) { if (cpu_is_ti814x()) minfo->pixelclock = 54000; } return 0; } } return -EINVAL; } /*get the index of the desired venc id in the database*/ static int get_idx_from_vid(int vid, int *idx) { int i; for (i = 0; i < disp_ctrl->numvencs; i++) { if (vid == venc_name[i].vid) { *idx = venc_name[i].idx; return 0; } } return -EINVAL; } /*get the venc id based on the name*/ static int dc_get_vencid(char *vname, int *vid) { int i; for (i = 0; i < disp_ctrl->numvencs; i++) { const struct dc_vencname_info *vnid = &venc_name[i]; if (sysfs_streq(vname, vnid->name)) { *vid = vnid->vid; return 0; } } return -1; } /*get the blender id from the indx */ static int get_bid_from_idx(int idx, int *bid) { int i; for (i = 0; i < disp_ctrl->numvencs; i++) { const struct dc_vencname_info *vnid = &venc_name[i]; if (vnid->idx == idx) { *bid = vnid->bid; return 0; } } return -1; } /*get the mode id based on the mode name*/ static int dc_get_modeid(char *mname, int *mid) { int i; for (i = 0; i < ARRAY_SIZE(vmode_info); i++) { const struct dc_vencmode_info *vinfo = &vmode_info[i]; if (sysfs_streq(mname, vinfo->name)) { *mid = vinfo->standard; return 0; } } return -1; } /*get the node id based on the name*/ static int dc_get_nodeid(char *name, int *nid) { int i; if (sysfs_streq(name, "dummy")) return -EINVAL; for (i = 0; i < ARRAY_SIZE(dc_nodes); i++) { const struct vps_sname_info *ninfo = &dc_nodes[i]; if (sysfs_streq(name, ninfo->name)) { *nid = ninfo->value; return 0; } } return -EINVAL; } /*get the venc information from M3*/ static int dc_get_vencinfo(struct vps_dcvencinfo *vinfo) { int r = 0; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; memcpy(disp_ctrl->vinfo, vinfo, sizeof(struct vps_dcvencinfo)); r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_VENC_MODE, (void *)disp_ctrl->vinfo_phy, NULL); if (r) VPSSERR("failed to get venc info.\n"); else memcpy(vinfo, disp_ctrl->vinfo, sizeof(struct vps_dcvencinfo)); return r; } /*is venc running*/ static int dc_isvencrunning(int vid) { struct vps_dcvencinfo vinfo; int r = 0; vinfo.numvencs = 1; vinfo.modeinfo[0].vencid = vid; r = dc_get_vencinfo(&vinfo); if (!r) return vinfo.modeinfo[0].isvencrunning; return r; } /*Get the current VENC output info*/ static int dc_get_output(struct vps_dcoutputinfo *oinfo) { int r = 0; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; /*get the venc output info*/ disp_ctrl->opinfo->vencnodenum = oinfo->vencnodenum; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_VENC_OUTPUT, (void *)disp_ctrl->opinfo_phy, NULL); if (r) VPSSERR("failed to get venc output info\n"); else memcpy(oinfo, disp_ctrl->opinfo, sizeof(struct vps_dcoutputinfo)); return r; } /*Set the VENC outputs*/ static int dc_set_output(struct vps_dcoutputinfo *oinfo) { int r; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; memcpy(disp_ctrl->opinfo, oinfo, sizeof(struct vps_dcoutputinfo)); r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_SET_VENC_OUTPUT, (void *)disp_ctrl->opinfo_phy, NULL); if (r) VPSSERR("failed to set venc output\n"); return r; } /*set up the pll clock*/ static int dc_set_pllclock(int bidx, u32 clock) { struct vps_systemvpllclk pll; int r = 0; /*FIXME: call function of HDMI driver to set HDMI for ti814x*/ if (cpu_is_ti814x() && (bidx == HDMI)) return r; pll.outputvenc = (enum vps_vplloutputclk)get_plloutputvenc(bidx); pll.outputclk = clock; r = vps_system_setpll(&pll); return r; } static int dc_set_pll_by_mid(int bidx, int mid) { int r = 0; u32 clock; r = get_pllclock(mid, &clock); if (r) { VPSSERR("nonexit mode %d\n", mid); return r; } r = dc_set_pllclock(bidx, clock); return r; } /*get the clock source*/ static int dc_get_clksrc(struct vps_dcvencclksrc *clksrc) { int r = 0; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; disp_ctrl->clksrc->venc = clksrc->venc; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_VENC_CLK_SRC, (void *)disp_ctrl->clksrc_phy, NULL); if (r) VPSSERR("get clock source failed\n"); else clksrc->clksrc = disp_ctrl->clksrc->clksrc; return r; } /*set the clock source*/ static int dc_set_clksrc(struct vps_dcvencclksrc *clksrc) { int r = 0; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; if (!isvalidclksrc(clksrc->venc, clksrc->clksrc)) { VPSSERR("invalid clock source\n"); return -EINVAL; } disp_ctrl->clksrc->venc = clksrc->venc; disp_ctrl->clksrc->clksrc = clksrc->clksrc; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_SET_VENC_CLK_SRC, (void *)disp_ctrl->clksrc_phy, NULL); if (r) VPSSERR("set clock source failed\n"); return r; } /*get the format based on the venc id*/ static int dc_get_format_from_vid(int vid, u32 *width, u32 *height, u8 *scformat) { int r = 0; struct vps_dcvencinfo vinfo; vinfo.numvencs = 1; vinfo.modeinfo[0].vencid = vid; r = dc_get_vencinfo(&vinfo); if (r) return -EINVAL; if (vinfo.modeinfo[0].minfo.standard == FVID2_STD_CUSTOM) { *width = vinfo.modeinfo[0].minfo.width; *height = vinfo.modeinfo[0].minfo.height; *scformat = vinfo.modeinfo[0].minfo.scanformat; } else { r = dc_get_format_from_mid(vinfo.modeinfo[0].minfo.standard, width, height, scformat); } return 0; } /*get the format based on the blender id*/ static int dc_get_format_from_bid(int bid, u32 *width, u32 *height, u8 *scformat) { int i; int r = -EINVAL; for (i = 0; i < disp_ctrl->numvencs; i++) { if (bid == venc_name[i].bid) { r = dc_get_format_from_vid(venc_name[i].vid, width, height, scformat); break; } } return r; } /*disable the desired vencs*/ static int dc_venc_disable(int vid) { int i = 0; int r = 0; struct vps_dcvencinfo vinfo; int venc_ids = vid; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; if (vid == 0) return 0; if (vid & (~disp_ctrl->vencmask)) { VPSSERR("wrong venc id.\n"); return -EINVAL; } VPSSDBG("enter venc disable\n"); vinfo.numvencs = 0; /*get the id of each venc to be disabled*/ while (venc_ids >> i) { if ((venc_ids >> i++) & 1) vinfo.modeinfo[vinfo.numvencs++].vencid = 1 << (i - 1); } r = dc_get_vencinfo(&vinfo); if (r) { VPSSERR("faild to get venc info.\n"); return r; } venc_ids = vid; for (i = 0; i < vinfo.numvencs; i++) { if (vinfo.modeinfo[i].isvencrunning == 0) { VPSSERR("venc %d already stop\n", vinfo.modeinfo[i].vencid); venc_ids &= ~vinfo.modeinfo[i].vencid; } } if (venc_ids && !r) { *disp_ctrl->dis_vencs = venc_ids; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_DISABLE_VENC, (void *)disp_ctrl->dis_vencsphy, NULL); if (r == 0) { disp_ctrl->enabled_venc_ids &= ~venc_ids; if (disp_ctrl->tiedvenc) { disp_ctrl->tiedvenc &= ~venc_ids; venc_ids = 0; i = 0; /*calculate how vencs left in tied list*/ while (disp_ctrl->tiedvenc >> i) { if ((disp_ctrl->tiedvenc >> i++) & 1) venc_ids++; } /*if one venc left,set tiedvenc to zero*/ if (venc_ids == 1) disp_ctrl->tiedvenc = 0; } } else VPSSERR("failed to disable the venc.\n"); } return r; } /*set the mode for desired vencs*/ static int dc_set_vencmode(struct vps_dcvencinfo *vinfo) { int i, r = 0; int vencs = 0; struct vps_dcvencinfo vi; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; /*get the current setting based on the app inputs*/ for (i = 0; i < vinfo->numvencs; i++) vi.modeinfo[i].vencid = vinfo->modeinfo[i].vencid; vi.numvencs = vinfo->numvencs; r = dc_get_vencinfo(&vi); if (r) { VPSSERR("failed to get venc info.\n"); goto exit; } /*make sure current venc status is matching */ disp_ctrl->vinfo->numvencs = 0; disp_ctrl->vinfo->tiedvencs = 0; for (i = 0; i < vinfo->numvencs; i++) { if (vi.modeinfo[i].isvencrunning) { if (vi.modeinfo[i].minfo.standard != vinfo->modeinfo[i].minfo.standard) { r = -EINVAL; VPSSERR("venc %d already running with \ different mode\n", vi.modeinfo[i].vencid); goto exit; } else VPSSDBG("venc %d already running\n", vi.modeinfo[i].vencid); } else { memcpy(&disp_ctrl->vinfo->modeinfo \ [disp_ctrl->vinfo->numvencs++], &vinfo->modeinfo[i], sizeof(struct vps_dcmodeinfo)); vencs |= vinfo->modeinfo[i].vencid; } } if (vinfo->tiedvencs) { if ((vencs & vinfo->tiedvencs) != vinfo->tiedvencs) { r = -EINVAL; VPSSERR("can not tied venc\n"); goto exit; } else disp_ctrl->vinfo->tiedvencs = vinfo->tiedvencs; } if (disp_ctrl->vinfo->numvencs) { /*set the VENC Mode*/ r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_SET_VENC_MODE, (void *)disp_ctrl->vinfo_phy, NULL); if (r) { VPSSERR("failed to set venc mdoe.\n"); goto exit; } disp_ctrl->enabled_venc_ids |= vencs; } exit: return r; } static int dc_enum_node_input(struct vps_dispctrl *dctrl, struct vps_dcenumnodeinput *eninput) { int r = 0; if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL)) return -EINVAL; *dctrl->dceninput = *eninput; r = vps_fvid2_control(dctrl->fvid2_handle, IOCTL_VPS_DCTRL_ENUM_NODE_INPUTS, (void *)dctrl->dceninput_phy, NULL); if (!r) *eninput = *dctrl->dceninput; return r; } static int dc_get_node_status(struct vps_dispctrl *dctrl, struct vps_dcnodeinput *ninput) { int r = 0; if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL)) return -EINVAL; *dctrl->nodeinfo = *ninput; r = vps_fvid2_control(dctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_NODE_INPUT_STATUS, (void *)dctrl->ninfo_phy, NULL); if (r) VPSSERR("failed to get node status\n"); else *ninput = *dctrl->nodeinfo; return r; } static int dc_get_comp_rtconfig(struct vps_dispctrl *dctrl, struct vps_dccomprtconfig *compcfg) { int r = 0; if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL)) return -EINVAL; dctrl->comprtcfg->nodeid = compcfg->nodeid; r = vps_fvid2_control(dctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_COMP_RTCONFIG, (void *)dctrl->comprtcfg_phy, NULL); if (r) VPSSERR("Get compositor RT config failed\n"); else *compcfg = *dctrl->comprtcfg; return r; } static int dc_set_comp_rtconfig(struct vps_dispctrl *dctrl, struct vps_dccomprtconfig *compcfg) { int r = 0; if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL)) return -EINVAL; *dctrl->comprtcfg = *compcfg; r = vps_fvid2_control(dctrl->fvid2_handle, IOCTL_VPS_DCTRL_SET_COMP_RTCONFIG, (void *)dctrl->comprtcfg_phy, NULL); if (r) VPSSERR("Set compositor RT config failed\n"); return r; } /*E******************************** private functions *********************/ /*S******************************* public functions *********************/ /*get the id(venc,blender,mode) based on the name*/ int vps_dc_get_id(char *name, int *id, enum dc_idtype type) { int r = -EINVAL; switch (type) { case DC_BLEND_ID: case DC_NODE_ID: r = dc_get_nodeid(name, id); break; case DC_VENC_ID: r = dc_get_vencid(name, id); break; case DC_MODE_ID: r = dc_get_modeid(name, id); break; } return r; } /*get the tied venc information*/ int vps_dc_get_tiedvenc(u8 *tiedvenc) { *tiedvenc = disp_ctrl->tiedvenc; return 0; } /*set the streaming on the blender, not used*/ void vps_dc_set_actnodes(u8 setflag, u8 bidx) { struct dc_blender_info *binfo = &disp_ctrl->blenders[bidx]; if (setflag) binfo->actnodes++; else if (binfo->actnodes != 0) binfo->actnodes--; } /*get the venc infor for the desired vencs*/ int vps_dc_get_vencinfo(struct vps_dcvencinfo *vinfo) { int r; dc_lock(disp_ctrl); r = dc_get_vencinfo(vinfo); dc_unlock(disp_ctrl); return r; } /*get the node name based on the id*/ int vps_dc_get_node_name(int id, char *name) { int i; for (i = 0; i < ARRAY_SIZE(dc_nodes); i++) { const struct vps_sname_info *ninfo = &dc_nodes[i]; if (id == ninfo->value) { strcpy(name, (char *)ninfo->name); return 0; } } return -EINVAL; } /*set dc config not used now*/ int vps_dc_set_config(struct vps_dcconfig *usercfg, int setflag) { int r = 0; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; if (usercfg->vencinfo.numvencs > disp_ctrl->numvencs) { VPSSERR("num vens (%d) over max\n", usercfg->vencinfo.numvencs); return -EINVAL; } if (usercfg->vencinfo.tiedvencs & (~disp_ctrl->tiedvenc)) { VPSSERR("tied venc not match.\n"); return -EINVAL; } VPSSDBG("enter set config\n"); dc_lock(disp_ctrl); memcpy(disp_ctrl->dccfg, usercfg, sizeof(struct vps_dcconfig)); if (setflag) { r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_SET_CONFIG, (void *)disp_ctrl->dccfg_phy, NULL); if (r) VPSSDBG("faield to set the DC config.\n"); } else { r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_CLEAR_CONFIG, (void *)disp_ctrl->dccfg_phy, NULL); if (r) VPSSDBG("faield to clear the DC config.\n"); } dc_unlock(disp_ctrl); return r; } /*get current venc output format*/ int vps_dc_get_outpfmt(int id, u32 *width, u32 *height, u8 *scformat, enum dc_idtype type) { int r; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; VPSSDBG("enter get output format\n"); dc_lock(disp_ctrl); if (type == DC_VENC_ID) r = dc_get_format_from_vid(id, width, height, scformat); else if (type == DC_BLEND_ID) r = dc_get_format_from_bid(id, width, height, scformat); else if (type == DC_MODE_ID) r = dc_get_format_from_mid(id, width, height, scformat); else r = -EINVAL; dc_unlock(disp_ctrl); return r; } /* set/clear the node path/edge */ int vps_dc_set_node(u8 nodeid, u8 inputid, u8 enable) { int r = 0; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL)) return -EINVAL; VPSSDBG("enter set node\n"); dc_lock(disp_ctrl); disp_ctrl->nodeinfo->nodeid = nodeid; disp_ctrl->nodeinfo->inputid = inputid; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_NODE_INPUT_STATUS, (void *)disp_ctrl->ninfo_phy, NULL); if (r) { VPSSERR("failed to get node input status\n"); goto exit; } if (disp_ctrl->nodeinfo->isenable == enable) { if (enable) VPSSDBG("node already connected\n"); else VPSSDBG("node already disconnected\n"); goto exit; } /*call ioctl to set/clear the node */ disp_ctrl->nodeinfo->isenable = enable; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_NODE_INPUT, (void *)disp_ctrl->ninfo_phy, NULL); if (r) VPSSERR("failed to enable node.\n"); exit: dc_unlock(disp_ctrl); return r; } int vps_dc_set_color(struct vps_dccigrtconfig *cigconfig) { int r; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL) || (cigconfig == NULL)) return -EINVAL; VPSSDBG("set color\n"); dc_lock(disp_ctrl); memcpy(disp_ctrl->cigcfg, cigconfig, sizeof(*cigconfig)); r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_SET_CIG_RTCONFIG, (void *)disp_ctrl->cigcfg_phy, NULL); if (r) VPSSERR("failed to set CIG color\n"); dc_unlock(disp_ctrl); return r; } int vps_dc_get_color(struct vps_dccigrtconfig *cigconfig) { int r; if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL) || (cigconfig == NULL)) return -EINVAL; VPSSDBG("get color\n"); dc_lock(disp_ctrl); disp_ctrl->cigcfg->nodeid = cigconfig->nodeid; r = vps_fvid2_control(disp_ctrl->fvid2_handle, IOCTL_VPS_DCTRL_GET_CIG_RTCONFIG, (void *)disp_ctrl->cigcfg_phy, NULL); if (!r) memcpy(cigconfig, disp_ctrl->cigcfg, sizeof(*cigconfig)); else VPSSERR("failed to get cig color\n"); dc_unlock(disp_ctrl); return r; } int vps_dc_enum_node_input(struct vps_dcenumnodeinput *eninput) { int r = 0; VPSSDBG("enum node input\n"); dc_lock(disp_ctrl); r = dc_enum_node_input(disp_ctrl, eninput); dc_unlock(disp_ctrl); return r; } int vps_dc_get_node_status(struct vps_dcnodeinput *ninput) { int r = 0; VPSSDBG("get node status\n"); dc_lock(disp_ctrl); r = dc_get_node_status(disp_ctrl, ninput); dc_unlock(disp_ctrl); return r; } int vps_dc_get_timing(u32 bid, struct fvid2_modeinfo *tinfo) { int i; for (i = 0; i < disp_ctrl->numvencs; i++) { if (bid == venc_name[i].bid) { *tinfo = venc_info.modeinfo[i].minfo; if ((tinfo->standard == FVID2_STD_NTSC) || (tinfo->standard == FVID2_STD_PAL)) { if (cpu_is_ti814x()) tinfo->pixelclock = 54000; } return 0; } } return -EINVAL; } /*E********************************* public functions *****************/ /*sysfs function for blender starting from here*/ static ssize_t blender_mode_show(struct dc_blender_info *binfo, char *buf) { int i; u32 idx = binfo->idx; int l = 0; for (i = 0; i < ARRAY_SIZE(vmode_info); i++) { u32 standard = venc_info.modeinfo[idx].minfo.standard; if (standard == FVID2_STD_CUSTOM) { if (venc_info.modeinfo[idx].minfo.scanformat == FVID2_SF_INTERLACED) l = snprintf(buf, PAGE_SIZE, "%ux%u@%ui\n", venc_info.modeinfo[idx].minfo.width, venc_info.modeinfo[idx].minfo.height, venc_info.modeinfo[idx].minfo.fps); else l = snprintf(buf, PAGE_SIZE, "%ux%u@%u\n", venc_info.modeinfo[idx].minfo.width, venc_info.modeinfo[idx].minfo.height, venc_info.modeinfo[idx].minfo.fps); } else if (vmode_info[i].standard == standard) { l = snprintf(buf, PAGE_SIZE, "%s\n", vmode_info[i].name); break; } } return l; } static ssize_t blender_mode_store(struct dc_blender_info *binfo, const char *buf, size_t size) { int r = 0; u32 idx = binfo->idx; u32 mid; dc_lock(binfo->dctrl); /*venc should be stop before changes*/ if (dc_isvencrunning(venc_info.modeinfo[idx].vencid)) { VPSSERR("stop venc before changing mode\n"); r = -EINVAL; goto exit; } if (dc_get_modeid((char *)buf, &mid)) { VPSSERR("failed to get the mode %s.", buf); r = -EINVAL; goto exit; } /*make sure the mode is supported by the venc*/ if (!isvalidmode(venc_info.modeinfo[idx].vencid, mid)) goto exit; /*only set the PLL if it is auto mode*/ if (binfo->dctrl->automode) { r = dc_set_pll_by_mid(binfo->idx, mid); if (r) goto exit; } venc_info.modeinfo[idx].minfo.standard = mid; dc_get_timing(mid, &venc_info.modeinfo[idx].minfo); #ifdef CONFIG_ARCH_TI816X if (cpu_is_ti816x()) { if ((binfo->idx == HDCOMP) && (binfo->isdeviceon == true)) { if ((mid == FVID2_STD_1080P_60) || (mid == FVID2_STD_1080P_50)) r = pcf8575_ths7360_hd_enable( TI816X_THS7360_SF_TRUE_HD_MODE); else r = pcf8575_ths7360_hd_enable( TI816X_THS7360_SF_HD_MODE); if (r < 0) { VPSSERR("failed to set THS filter\n"); goto exit; } } } #endif r = size; exit: dc_unlock(binfo->dctrl); return r; } static ssize_t blender_timings_show(struct dc_blender_info *binfo, char *buf) { int r; struct fvid2_modeinfo *t; t = &venc_info.modeinfo[binfo->idx].minfo; r = snprintf(buf, PAGE_SIZE, "%u,%u/%u/%u/%u,%u/%u/%u/%u,%u\n", t->pixelclock, t->width, t->hfrontporch, t->hbackporch, t->hsynclen, t->height, t->vfrontporch, t->vbackporch, t->vsynclen, t->scanformat); return r; } static ssize_t blender_timings_store(struct dc_blender_info *binfo, const char *buf, size_t size) { int r = 0; struct fvid2_modeinfo t; u32 num; u32 vmode; if (binfo->idx == SDVENC) return -EINVAL; dc_lock(binfo->dctrl); /*venc should be stop before changes*/ if (dc_isvencrunning(venc_info.modeinfo[binfo->idx].vencid)) { VPSSERR("stop venc before changing timing\n"); r = -EINVAL; goto exit; } num = sscanf(buf, "%u,%u/%u/%u/%u,%u/%u/%u/%u,%u/%u", &t.pixelclock, &t.width, &t.hfrontporch, &t.hbackporch, &t.hsynclen, &t.height, &t.vfrontporch, &t.vbackporch, &t.vsynclen, &t.scanformat, &vmode); if (!((num == 11) || (num == 10))) { r = -EINVAL; VPSSERR("wrong timing input %d\n", num); goto exit; } /*if use did not assign mode, than we fix it to 1*/ if (num == 10) vmode = 1; memcpy(&venc_info.modeinfo[binfo->idx].minfo, &t, sizeof(t)); venc_info.modeinfo[binfo->idx].minfo.standard = FVID2_STD_CUSTOM; venc_info.modeinfo[binfo->idx].mode = vmode; /*calculate the refresh rate*/ venc_info.modeinfo[binfo->idx].minfo.fps = (t.pixelclock * 1000) / ((t.width + t.hfrontporch + t.hbackporch + t.hsynclen) * (t.height + t.vfrontporch + t.vbackporch + t.vsynclen)); if (t.scanformat == 0) venc_info.modeinfo[binfo->idx].minfo.fps *= 2; r = dc_set_pllclock(binfo->idx, t.pixelclock); if (r) { VPSSERR("failed to set %dKHz clock\n", t.pixelclock); r = -EINVAL; goto exit; } r = size; exit: dc_unlock(binfo->dctrl); return r; } static ssize_t blender_enabled_show(struct dc_blender_info *binfo, char *buf) { int r; struct vps_dcvencinfo vinfo; dc_lock(binfo->dctrl); vinfo.numvencs = 1; vinfo.modeinfo[0].vencid = venc_name[binfo->idx].vid; r = dc_get_vencinfo(&vinfo); if (r) { VPSSERR(" Failed to get venc infor\n"); r = -EINVAL; goto exit; } r = snprintf(buf, PAGE_SIZE, "%d\n", vinfo.modeinfo[0].isvencrunning); exit: dc_unlock(binfo->dctrl); return r; } static ssize_t blender_enabled_store(struct dc_blender_info *binfo, const char *buf, size_t size) { int enabled; int vid; int r = 0; enabled = simple_strtoul(buf, NULL, 10); dc_lock(disp_ctrl); /*get vid id*/ vid = venc_name[binfo->idx].vid; if (enabled == 0) { r = dc_venc_disable(vid); if (r) { VPSSERR("failed to disable %s venc\n", binfo->name); r = -EINVAL; goto exit; } } else { int idx; struct vps_dcvencinfo vinfo; get_idx_from_vid(vid, &idx); memcpy(&vinfo.modeinfo[0], &venc_info.modeinfo[idx], sizeof(struct vps_dcvencinfo)); vinfo.numvencs = 1; vinfo.tiedvencs = 0; r = dc_set_vencmode(&vinfo); if (r) { VPSSERR("failed to enable venc %s\n", binfo->name); r = -EINVAL; goto exit; } } r = size; exit: dc_unlock(disp_ctrl); return r; } static ssize_t blender_clksrc_show(struct dc_blender_info *binfo, char *buf) { int r = 0; struct vps_dcvencclksrc *clksrc = &binfo->clksrc; if (binfo->idx == SDVENC) { VPSSERR("no clock soure for SD VENC\n"); return -EINVAL; } dc_lock(binfo->dctrl); clksrc->venc = venc_name[binfo->idx].vid; r = dc_get_clksrc(clksrc); dc_unlock(binfo->dctrl); if (r) return r; else return snprintf(buf, PAGE_SIZE, "%s\n", vclksrc_name[clksrc->clksrc].name); } static ssize_t blender_clksrc_store(struct dc_blender_info *binfo, const char *buf, size_t size) { int r = 0, i; struct vps_dcvencclksrc clksrc; bool found = false; if (binfo->idx == SDVENC) { VPSSERR("no clock soure for SD VENC\n"); return -EINVAL; } dc_lock(binfo->dctrl); clksrc.venc = venc_name[binfo->idx].vid; if (dc_isvencrunning(clksrc.venc)) { VPSSERR("please stop venc before changing clock source\n"); r = -EINVAL; goto exit; } /*found the matching clock source*/ for (i = 0; i < ARRAY_SIZE(vclksrc_name); i++) { if (sysfs_streq(buf, vclksrc_name[i].name)) { clksrc.clksrc = vclksrc_name[i].value; found = true; break; } } /*set the clock source*/ if (found == true) { r = dc_set_clksrc(&clksrc); if (!r) { r = size; /*store back*/ binfo->clksrc.clksrc = clksrc.clksrc; } } else { r = -EINVAL; VPSSERR("invalid clock source input\n"); } exit: dc_unlock(binfo->dctrl); return r; } static ssize_t blender_output_show(struct dc_blender_info *binfo, char *buf) { struct vps_dcoutputinfo oinfo; int r = 0; int l = 0, i; oinfo.vencnodenum = venc_name[binfo->idx].vid; dc_lock(binfo->dctrl); r = dc_get_output(&oinfo); dc_unlock(binfo->dctrl); if (r) return -EINVAL; if (isdigitalvenc(oinfo.vencnodenum)) l += snprintf(buf + l, PAGE_SIZE - l, "%s", dfmt_name[oinfo.dvofmt].name); else l += snprintf(buf + l, PAGE_SIZE - l, "%s", afmt_name[oinfo.afmt].name); for (i = 0 ; i < ARRAY_SIZE(datafmt_name); i++) { if (datafmt_name[i].value == oinfo.dataformat) l += snprintf(buf + l, PAGE_SIZE - l, ",%s\n", datafmt_name[i].name); } return l; } static ssize_t blender_output_store(struct dc_blender_info *binfo, const char *buf, size_t size) { struct vps_dcoutputinfo oinfo; int r = 0; char *input = (char *)buf; char *ptr; enum vps_dcdigitalfmt dfmt = VPS_DC_DVOFMT_MAX; enum vps_dcanalogfmt afmt = VPS_DC_A_OUTPUT_MAX; enum fvid2_dataformat fmt = FVID2_DF_MAX; oinfo.vencnodenum = venc_name[binfo->idx].vid; dc_lock(binfo->dctrl); /*venc should be off before changed output*/ if (dc_isvencrunning(oinfo.vencnodenum)) { VPSSERR("please disable VENC before changing output\n"); r = -EINVAL; goto exit; } dc_get_output(&oinfo); /*process the input buf*/ while ((ptr = strsep(&input, ",")) != NULL) { int i; bool found; found = false; /*check data format first*/ for (i = 0; i < ARRAY_SIZE(datafmt_name); i++) { if (sysfs_streq(ptr, datafmt_name[i].name)) { fmt = datafmt_name[i].value; found = true; } } /*check digital format or analog format based on current venc*/ if (!found) { if (isdigitalvenc(oinfo.vencnodenum)) { for (i = 0; i < VPS_DC_DVOFMT_MAX; i++) if (sysfs_streq(ptr, dfmt_name[i].name)) { dfmt = dfmt_name[i].value; found = true; break; } } else { for (i = 0; i < VPS_DC_A_OUTPUT_MAX; i++) if (sysfs_streq(ptr, afmt_name[i].name)) { afmt = afmt_name[i].value; found = true; break; } } if (found == false) { VPSSERR("invalid output value %s\n", ptr); r = -EINVAL; goto exit; } } if (input == NULL) break; } /*make sure the input is right before send out to M3*/ if (isdigitalvenc(oinfo.vencnodenum)) { if ((dfmt == VPS_DC_DVOFMT_MAX) && (fmt == FVID2_DF_MAX)) { VPSSERR("no valid digital output settings\n"); r = -EINVAL; goto exit; } if (dfmt != VPS_DC_DVOFMT_MAX) oinfo.dvofmt = dfmt; } else { if ((afmt == VPS_DC_A_OUTPUT_MAX) && (fmt == FVID2_DF_MAX)) { VPSSERR("no valid analog output settings\n"); r = -EINVAL; goto exit; } if ((binfo->idx == SDVENC) && (afmt == VPS_DC_A_OUTPUT_COMPONENT)) { VPSSERR("component out not supported on sdvenc\n"); r = -EINVAL; goto exit; } if (afmt != VPS_DC_A_OUTPUT_MAX) oinfo.afmt = afmt; } if (fmt != FVID2_DF_MAX) oinfo.dataformat = fmt; r = dc_set_output(&oinfo); if (!r) r = size; exit: dc_unlock(binfo->dctrl); return r; } static ssize_t blender_order_show(struct dc_blender_info *binfo, char *buf) { int r; int l; struct vps_dccomprtconfig comprtcfg; r = get_bid_from_idx(binfo->idx, &comprtcfg.nodeid); if (r) return r; dc_lock(binfo->dctrl); r = dc_get_comp_rtconfig(binfo->dctrl, &comprtcfg); dc_unlock(binfo->dctrl); if (r) return r; if (comprtcfg.isglobalreorderenable) l = snprintf(buf, PAGE_SIZE, "%u,%u/%u/%u/%u\n", comprtcfg.isglobalreorderenable, comprtcfg.displayorder[0], comprtcfg.displayorder[1], comprtcfg.displayorder[2], comprtcfg.displayorder[3]); else l = snprintf(buf, PAGE_SIZE, "%u,%u\n", comprtcfg.isglobalreorderenable, comprtcfg.displayorder[0]); return l; } static ssize_t blender_order_store(struct dc_blender_info *binfo, const char *buf, size_t size) { int r; int num; struct vps_dccomprtconfig comprtcfg; r = get_bid_from_idx(binfo->idx, &comprtcfg.nodeid); if (r) return r; num = sscanf(buf, "%u,%u/%u/%u/%u", &comprtcfg.isglobalreorderenable, &comprtcfg.displayorder[0], &comprtcfg.displayorder[1], &comprtcfg.displayorder[2], &comprtcfg.displayorder[3]); /*error check*/ if (comprtcfg.isglobalreorderenable == 1) { if (num != 5) { VPSSERR("Wrong display re-order format\n"); return -EINVAL; } } else { if (num < 2) { VPSSERR("Wrong display re-order format\n"); return -EINVAL; } } dc_lock(binfo->dctrl); r = dc_set_comp_rtconfig(binfo->dctrl, &comprtcfg); if (!r) r = size; dc_unlock(binfo->dctrl); return r; } static ssize_t blender_name_show(struct dc_blender_info *binfo, char *buf) { return snprintf(buf, PAGE_SIZE, "%s\n", venc_name[binfo->idx].name); } struct blender_attribute { struct attribute attr; ssize_t (*show)(struct dc_blender_info *, char *); ssize_t (*store)(struct dc_blender_info *, const char *, size_t); }; #define BLENDER_ATTR(_name, _mode, _show, _store) \ struct blender_attribute blender_attr_##_name = \ __ATTR(_name, _mode, _show, _store) static BLENDER_ATTR(name, S_IRUGO, blender_name_show, NULL); static BLENDER_ATTR(mode, S_IRUGO | S_IWUSR, blender_mode_show, blender_mode_store); static BLENDER_ATTR(timings, S_IRUGO | S_IWUSR, blender_timings_show, blender_timings_store); static BLENDER_ATTR(enabled, S_IRUGO | S_IWUSR, blender_enabled_show, blender_enabled_store); static BLENDER_ATTR(output, S_IRUGO | S_IWUSR, blender_output_show, blender_output_store); static BLENDER_ATTR(clksrc, S_IRUGO | S_IWUSR, blender_clksrc_show, blender_clksrc_store); static BLENDER_ATTR(order, S_IRUGO | S_IWUSR, blender_order_show, blender_order_store); static struct attribute *blender_sysfs_attrs[] = { &blender_attr_mode.attr, &blender_attr_timings.attr, &blender_attr_enabled.attr, &blender_attr_output.attr, &blender_attr_clksrc.attr, &blender_attr_order.attr, &blender_attr_name.attr, NULL }; static ssize_t blender_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct dc_blender_info *binfo = NULL; struct blender_attribute *blend_attr = NULL; binfo = container_of(kobj, struct dc_blender_info, kobj); blend_attr = container_of(attr, struct blender_attribute, attr); if (!blend_attr->show) return -ENOENT; return blend_attr->show(binfo, buf); } static ssize_t blender_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t size) { struct dc_blender_info *blend; struct blender_attribute *blend_attr; blend = container_of(kobj, struct dc_blender_info, kobj); blend_attr = container_of(attr, struct blender_attribute, attr); if (!blend_attr->store) return -ENOENT; return blend_attr->store(blend, buf, size); } static const struct sysfs_ops blender_sysfs_ops = { .show = blender_attr_show, .store = blender_attr_store, }; static struct kobj_type blender_ktype = { .sysfs_ops = &blender_sysfs_ops, .default_attrs = blender_sysfs_attrs, }; /*sysfs for the display controller*/ static ssize_t dctrl_pllclks_show(struct vps_dispctrl *dctrl, char *buf) { int r = 0, l = 0, i; struct vps_systemvpllclk pllclk; for (i = 0; i < VPS_SYSTEM_VPLL_OUTPUT_MAX_VENC; i++) { pllclk.outputvenc = (enum vps_vplloutputclk)i; /*no need for APLL for TI814X*/ if ((pllclk.outputvenc == VPS_SYSTEM_VPLL_OUTPUT_VENC_A) && cpu_is_ti814x()) continue; r = vps_system_getpll(&pllclk); if (r) return -EINVAL; if (i == 0) l += snprintf(buf + l, PAGE_SIZE - l, "%s:%d", pllvenc_name[i].name, pllclk.outputclk); else l += snprintf(buf + l, PAGE_SIZE - l, ",%s:%d", pllvenc_name[i].name, pllclk.outputclk); } l += snprintf(buf + l, PAGE_SIZE - l, "\n"); return l; } static ssize_t dctrl_pllclks_store(struct vps_dispctrl *dctrl, const char *buf, size_t size) { struct vps_systemvpllclk pllclk; char *input = (char *)buf, *this_opt; int r = 0; if (dctrl->automode) { VPSSERR("please turn off automode first\n"); return -EINVAL; } dc_lock(dctrl); while (!r && (this_opt = strsep(&input, ",")) != NULL) { char *p, *venc_str, *clk_str; int i; p = strchr(this_opt, ':'); if (!p) break; *p = 0; venc_str = this_opt; clk_str = p + 1; pllclk.outputvenc = VPS_SYSTEM_VPLL_OUTPUT_MAX_VENC; pllclk.outputclk = 0xFFFFFFFF; /*get the output venc*/ for (i = 0; i < VPS_SYSTEM_VPLL_OUTPUT_MAX_VENC; i++) { if (sysfs_streq(venc_str, pllvenc_name[i].name)) { pllclk.outputvenc = pllvenc_name[i].value; break; } } if (i == VPS_SYSTEM_VPLL_OUTPUT_MAX_VENC) { VPSSERR("wrong venc %s\n", venc_str); r = -EINVAL; goto exit; } if ((pllclk.outputvenc == VPS_SYSTEM_VPLL_OUTPUT_VENC_A) && cpu_is_ti814x()) { VPSSERR("Invalid VENCA PLL\n"); r = -EINVAL; goto exit; } /*get the pll clk*/ pllclk.outputclk = simple_strtoul((const char *)clk_str, NULL, 10); r = vps_system_setpll(&pllclk); if (r) VPSSERR("set freq %s for %s failed\n", clk_str, venc_str); if (input == NULL) break; } if (!r) r = size; exit: dc_unlock(dctrl); return r; } static ssize_t dctrl_automode_show(struct vps_dispctrl *dctrl, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", dctrl->automode); } static ssize_t dctrl_automode_store(struct vps_dispctrl *dctrl, const char *buf, size_t size) { int enabled; enabled = simple_strtoul(buf, NULL, 10); dctrl->automode = (bool)enabled; return size; } static ssize_t dctrl_tiedvencs_show(struct vps_dispctrl *dctrl, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", disp_ctrl->tiedvenc); } static ssize_t dctrl_tiedvencs_store(struct vps_dispctrl *dctrl, const char *buf, size_t size) { int r = 0; int vencs = 0; int i = 0; struct vps_dcvencinfo vinfo; dc_lock(disp_ctrl); vencs = simple_strtoul(buf, NULL, 10); if (vencs & ~disp_ctrl->vencmask) { r = -EINVAL; VPSSERR("vencs %d over limit\n", vencs); goto exit; } if ((vencs == 0) || (disp_ctrl->tiedvenc == vencs)) { r = size; goto exit; } vinfo.numvencs = 0; vinfo.tiedvencs = vencs; /*assemble the structure based on the venc id*/ while (vencs >> i) { /*get id of each venc to be tied*/ if ((vencs >> i++) & 1) { int idx; int vid = 1 << (i - 1); get_idx_from_vid(vid, &idx); memcpy(&vinfo.modeinfo[vinfo.numvencs++], &venc_info.modeinfo[idx], sizeof(struct vps_dcmodeinfo)); } } if (vinfo.numvencs < 2) { VPSSERR("at least 2 vencs to tied.\n"); r = -EINVAL; goto exit; } /*set the tied venc mode*/ r = dc_set_vencmode(&vinfo); if (r) { VPSSERR("failed to set tied venc\n"); r = -EINVAL; goto exit; } disp_ctrl->tiedvenc = vinfo.tiedvencs; r = size; exit: dc_unlock(disp_ctrl); return r; } struct dctrl_attribute { struct attribute attr; ssize_t (*show)(struct vps_dispctrl *, char *); ssize_t (*store)(struct vps_dispctrl *, const char *, size_t); }; #define DCTRL_ATTR(_name, _mode, _show, _store) \ struct dctrl_attribute dctrl_attr_##_name = \ __ATTR(_name, _mode, _show, _store) static DCTRL_ATTR(tiedvencs, S_IRUGO | S_IWUSR, dctrl_tiedvencs_show, dctrl_tiedvencs_store); static DCTRL_ATTR(pllclks, S_IRUGO | S_IWUSR, dctrl_pllclks_show, dctrl_pllclks_store); static DCTRL_ATTR(automode, S_IRUGO | S_IWUSR, dctrl_automode_show, dctrl_automode_store); static struct attribute *dctrl_sysfs_attrs[] = { &dctrl_attr_tiedvencs.attr, &dctrl_attr_pllclks.attr, &dctrl_attr_automode.attr, NULL }; static ssize_t dctrl_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct vps_dispctrl *dctrl = NULL; struct dctrl_attribute *dctrl_attr = NULL; dctrl = container_of(kobj, struct vps_dispctrl, kobj); dctrl_attr = container_of(attr, struct dctrl_attribute, attr); if (!dctrl_attr->show) return -ENOENT; return dctrl_attr->show(dctrl, buf); } static ssize_t dctrl_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t size) { struct vps_dispctrl *dctrl; struct dctrl_attribute *dctrl_attr; dctrl = container_of(kobj, struct vps_dispctrl, kobj); dctrl_attr = container_of(attr, struct dctrl_attribute, attr); if (!dctrl_attr->store) return -ENOENT; return dctrl_attr->store(dctrl, buf, size); } static const struct sysfs_ops dctrl_sysfs_ops = { .show = dctrl_attr_show, .store = dctrl_attr_store, }; static struct kobj_type dctrl_ktype = { .sysfs_ops = &dctrl_sysfs_ops, .default_attrs = dctrl_sysfs_attrs, }; /*end of sysfs function for display controller*/ static int parse_def_clksrc(const char *clksrc) { int r = 0, i; char *str, *options, *this_opt; if (clksrc == NULL) return 0; str = kmalloc(strlen(clksrc) + 1, GFP_KERNEL); strcpy(str, clksrc); options = str; VPSSDBG("clksrc %s\n", clksrc); while (!r && (this_opt = strsep(&options, ",")) != NULL) { char *p, *venc, *csrc; int vid, idx; struct dc_blender_info *binfo; p = strchr(this_opt, ':'); if (!p) break; *p = 0; venc = this_opt; csrc = p + 1; /*parse the clock source for each possible venc input*/ for (i = 0; i < ARRAY_SIZE(vclksrc_name); i++) { if (sysfs_streq(csrc, vclksrc_name[i].name)) { if (dc_get_vencid(venc, &vid)) { VPSSERR("wrong venc\n"); break; } /* no clock for SD VENC*/ if (vid == VPS_DC_VENC_SD) break; get_idx_from_vid(vid, &idx); binfo = &disp_ctrl->blenders[idx]; /*is valid clock source*/ if (isvalidclksrc(vid, vclksrc_name[i].value)) { binfo->clksrc.clksrc = vclksrc_name[i].value; } else VPSSERR("wrong clock source\n"); break; } } if (i == ARRAY_SIZE(vclksrc_name)) VPSSERR("wrong clock source\n"); if (options == NULL) break; } kfree(str); return r; } static int parse_def_modes(const char *mode) { char *str, *options, *this_opt; int r = 0; struct vps_dcvencinfo *vinfo = &venc_info; if (mode == NULL) return 0; str = kmalloc(strlen(mode) + 1, GFP_KERNEL); strcpy(str, mode); options = str; VPSSDBG("mode %s\n", mode); while (!r && (this_opt = strsep(&options, ",")) != NULL) { char *p, *display_str, *mode_str; int vid, mid; int idx; p = strchr(this_opt, ':'); if (!p) { r = -EINVAL; break; } *p = 0; display_str = this_opt; mode_str = p + 1; if (dc_get_vencid(display_str, &vid)) { VPSSERR("venc name(%s) not existing.\n", display_str); continue; } if (dc_get_modeid(mode_str, &mid)) { VPSSERR("venc mode(%s) is not supported.\n", mode_str); continue; } if (!isvalidmode(vid, mid)) continue; get_idx_from_vid(vid, &idx); vinfo->modeinfo[idx].vencid = vid; vinfo->modeinfo[idx].minfo.standard = mid; dc_get_timing(mid, &vinfo->modeinfo[idx].minfo); if (options == NULL) break; } kfree(str); return r; } void __init vps_dc_ctrl_init(struct vps_dispctrl *dctrl) { struct vps_dcedeconfig *edecfg = dctrl->dcedecfg; dctrl->dccreatecfg->edeconfig = (struct vps_dcedeconfig *)dctrl->dcede_phy; /*setup default ede values*/ edecfg->ltienable = 0; edecfg->horzpeaking = 0; edecfg->ctienable = 0; edecfg->transadjustenable = 0; edecfg->lumapeaking = 0; edecfg->chromapeaking = 0; edecfg->minclipluma = 0; edecfg->maxclipluma = 1023; edecfg->minclipchroma = 0; edecfg->maxclipchroma = 1023; edecfg->bypass = 0; } static inline int get_payload_size(void) { int size = 0; size = sizeof(struct vps_dccreateconfig); size += sizeof(struct vps_dcedeconfig); size += sizeof(u32); size += sizeof(struct vps_dcconfig); size += sizeof(struct vps_dcvencinfo); size += sizeof(struct vps_dcnodeinput); size += sizeof(struct vps_dcmodeinfo); size += sizeof(struct vps_dcoutputinfo); size += sizeof(struct vps_dcvencclksrc); size += sizeof(struct vps_dccigrtconfig); size += sizeof(struct vps_dcenumnodeinput); size += sizeof(struct vps_dccomprtconfig); size += sizeof(u32); /*this is for the disable venc command*/ /*FIXME add more here*/ return size; } static inline void assign_payload_addr(struct vps_dispctrl *dctrl, struct vps_payload_info *pinfo, u32 *buf_offset) { int offset = *buf_offset; /*dc create config*/ dctrl->dccreatecfg = (struct vps_dccreateconfig *)setaddr(pinfo, &offset, &dctrl->dccreate_phy, sizeof(struct vps_dccreateconfig)); /*ede config*/ dctrl->dcedecfg = (struct vps_dcedeconfig *)setaddr(pinfo, &offset, &dctrl->dcede_phy, sizeof(struct vps_dcedeconfig)); /*return status*/ dctrl->dcrtstatus = (u32 *)setaddr(pinfo, &offset, &dctrl->dcrtst_phy, sizeof(u32)); /*dc config */ dctrl->dccfg = (struct vps_dcconfig *)setaddr(pinfo, &offset, &dctrl->dccfg_phy, sizeof(struct vps_dcconfig)); /* venc info*/ dctrl->vinfo = (struct vps_dcvencinfo *)setaddr(pinfo, &offset, &dctrl->vinfo_phy, sizeof(struct vps_dcvencinfo)); /*node input*/ dctrl->nodeinfo = (struct vps_dcnodeinput *)setaddr( pinfo, &offset, &dctrl->ninfo_phy, sizeof(struct vps_dcnodeinput)); /*venc disable*/ dctrl->dis_vencs = (u32 *)setaddr(pinfo, &offset, &dctrl->dis_vencsphy, sizeof(u32)); /*venc output infor*/ dctrl->opinfo = (struct vps_dcoutputinfo *)setaddr( pinfo, &offset, &dctrl->opinfo_phy, sizeof(struct vps_dcoutputinfo)); /*venc clock source*/ dctrl->clksrc = (struct vps_dcvencclksrc *)setaddr( pinfo, &offset, &dctrl->clksrc_phy, sizeof(struct vps_dcvencclksrc)); /*CIG runtime configuration*/ dctrl->cigcfg = (struct vps_dccigrtconfig *)setaddr( pinfo, &offset, &dctrl->cigcfg_phy, sizeof(struct vps_dccigrtconfig)); /*DC enum node input*/ dctrl->dceninput = (struct vps_dcenumnodeinput *)setaddr( pinfo, &offset, &dctrl->dceninput_phy, sizeof(struct vps_dcenumnodeinput)); /*COMP RT Config*/ dctrl->comprtcfg = (struct vps_dccomprtconfig *) setaddr( pinfo, &offset, &dctrl->comprtcfg_phy, sizeof(struct vps_dccomprtconfig)); *buf_offset = offset; } int __init vps_dc_init(struct platform_device *pdev, const char *mode, int tied_vencs, const char *clksrc) { int r = 0; int i; int size = 0, offset = 0; VPSSDBG("dctrl init\n"); dc_payload_info = kzalloc(sizeof(struct vps_payload_info), GFP_KERNEL); if (!dc_payload_info) { VPSSERR("allocated payload info failed.\n"); return -ENOMEM; } /*allocate non-cacheable memory*/ size = get_payload_size(); dc_payload_info->vaddr = vps_sbuf_alloc(size, &dc_payload_info->paddr); if (dc_payload_info->vaddr == NULL) { VPSSERR("alloc dctrl dma buffer failed\n"); dc_payload_info->paddr = 0u; r = -ENOMEM; goto cleanup; } dc_payload_info->size = PAGE_ALIGN(size); memset(dc_payload_info->vaddr, 0, dc_payload_info->size); /*allocate display_control memory*/ disp_ctrl = kzalloc(sizeof(struct vps_dispctrl), GFP_KERNEL); if (disp_ctrl == NULL) { r = -ENOMEM; goto cleanup; } disp_ctrl->automode = true; disp_ctrl->numvencs = vps_get_numvencs(); venc_info.numvencs = disp_ctrl->numvencs; disp_ctrl->vencmask = (1 << VPS_DC_MAX_VENC) - 1; if (cpu_is_ti814x()) disp_ctrl->vencmask -= VPS_DC_VENC_HDCOMP; assign_payload_addr(disp_ctrl, dc_payload_info, &offset); vps_dc_ctrl_init(disp_ctrl); /*get dc handle*/ dc_handle = vps_fvid2_create(FVID2_VPS_DCTRL_DRV, VPS_DCTRL_INST_0, (void *)disp_ctrl->dccreate_phy, (void *)dc_payload_info->paddr, NULL); if (dc_handle == NULL) { VPSSDBG("Create FVID2 DC handle status 0x%08x.\n", *(u32 *)dc_payload_info->vaddr); r = -EINVAL; goto cleanup; } disp_ctrl->fvid2_handle = dc_handle; mutex_init(&disp_ctrl->dcmutex); r = kobject_init_and_add( &disp_ctrl->kobj, &dctrl_ktype, &pdev->dev.kobj, "system"); if (r) VPSSERR("failed to create dctrl sysfs file.\n"); /*create sysfs*/ for (i = 0; i < disp_ctrl->numvencs; i++) { struct dc_blender_info *blend = &disp_ctrl->blenders[i];; blend->idx = i; blend->actnodes = 0; blend->name = (char *)venc_name[i].name; blend->dctrl = disp_ctrl; blend->isdeviceon = true; r = kobject_init_and_add( &blend->kobj, &blender_ktype, &pdev->dev.kobj, "display%d", i); if (r) { VPSSERR("failed to create blender \ %d sysfs file.\n", i); continue; } } disp_ctrl->tiedvenc = tied_vencs; venc_info.tiedvencs = disp_ctrl->tiedvenc; /*parse the mode*/ r = parse_def_modes(mode); if (r) { VPSSERR("failed to parse mode.\n"); goto cleanup; } /*set up the default clksrc and output format*/ for (i = 0; i < disp_ctrl->numvencs; i++) { struct vps_dcvencclksrc *clksrcp = &disp_ctrl->blenders[i].clksrc; struct vps_dcoutputinfo opinfo; clksrcp->venc = venc_name[i].vid; /*set the venc output*/ opinfo.dvofidpolarity = VPS_DC_POLARITY_ACT_HIGH; opinfo.dvohspolarity = VPS_DC_POLARITY_ACT_HIGH; opinfo.dvovspolarity = VPS_DC_POLARITY_ACT_HIGH; opinfo.dvoactvidpolarity = VPS_DC_POLARITY_ACT_HIGH; switch (i) { case HDMI: opinfo.vencnodenum = VPS_DC_VENC_HDMI; opinfo.dvofmt = VPS_DC_DVOFMT_TRIPLECHAN_DISCSYNC; opinfo.dataformat = FVID2_DF_RGB24_888; if (cpu_is_ti816x() && (VPS_PLATFORM_CPU_REV_1_0 == vps_system_getcpurev())) clksrcp->clksrc = VPS_DC_CLKSRC_VENCD_DIV2; else clksrcp->clksrc = VPS_DC_CLKSRC_VENCD; break; case DVO2: opinfo.vencnodenum = VPS_DC_VENC_DVO2; opinfo.dvofmt = VPS_DC_DVOFMT_DOUBLECHAN; opinfo.dataformat = FVID2_DF_YUV422SP_UV; if (cpu_is_ti816x()) { if (VPS_PLATFORM_CPU_REV_1_0 == vps_system_getcpurev()) clksrcp->clksrc = VPS_DC_CLKSRC_VENCD_DIV2; else clksrcp->clksrc = VPS_DC_CLKSRC_VENCD; } else clksrcp->clksrc = VPS_DC_CLKSRC_VENCA; break; case SDVENC: opinfo.vencnodenum = VPS_DC_VENC_SD; if (cpu_is_ti816x()) opinfo.afmt = VPS_DC_A_OUTPUT_COMPOSITE; else opinfo.afmt = VPS_DC_A_OUTPUT_SVIDEO; opinfo.dataformat = FVID2_DF_RGB24_888; break; if (cpu_is_ti816x()) { case HDCOMP: opinfo.vencnodenum = VPS_DC_VENC_HDCOMP; opinfo.afmt = VPS_DC_A_OUTPUT_COMPONENT; opinfo.dataformat = FVID2_DF_YUV422SP_UV; clksrcp->clksrc = VPS_DC_CLKSRC_VENCA; break; } } r = dc_set_output(&opinfo); if (r) { VPSSERR("failed to set venc output\n"); goto cleanup; } } /*parse command line clksrc*/ r = parse_def_clksrc(clksrc); if (r) { VPSSERR("failed to parse clock source\n"); goto cleanup; } /*set the clock source*/ for (i = 0; i < venc_info.numvencs; i++) { if (disp_ctrl->blenders[i].idx != SDVENC) { r = dc_set_clksrc( &disp_ctrl->blenders[i].clksrc); if (r) { VPSSERR("failed to set clock resource"); goto cleanup; } } } /*config the PLL*/ for (i = 0; i < venc_info.numvencs; i++) { r = dc_set_pll_by_mid(i, venc_info.modeinfo[i].minfo.standard); if (r) { VPSSERR("failed to set pll"); goto cleanup; } } /*set the venc mode*/ r = dc_set_vencmode(&venc_info); if (r) { VPSSERR("Failed to set venc mode.\n"); goto cleanup; } /*set the the THS filter, device is still registered even if setup is failed*/ #ifdef CONFIG_ARCH_TI816X if (cpu_is_ti816x()) { r = pcf8575_ths7375_enable(TI816X_THSFILTER_ENABLE_MODULE); if ((venc_info.modeinfo[HDCOMP].minfo.standard == FVID2_STD_1080P_60) || (venc_info.modeinfo[HDCOMP].minfo.standard == FVID2_STD_1080P_50)) r |= pcf8575_ths7360_hd_enable( TI816X_THS7360_SF_TRUE_HD_MODE); else r |= pcf8575_ths7360_hd_enable( TI816X_THS7360_SF_HD_MODE); if (r < 0) { VPSSERR("setup 7375 filter failed\n"); disp_ctrl->blenders[HDCOMP].isdeviceon = false; } r = pcf8575_ths7360_sd_enable(TI816X_THSFILTER_ENABLE_MODULE); if (r < 0) { VPSSERR("setup 7360 filter failed.\n"); disp_ctrl->blenders[SDVENC].isdeviceon = false; } } #endif return 0; cleanup: vps_dc_deinit(pdev); return r; } int __exit vps_dc_deinit(struct platform_device *pdev) { int r = 0; int i; VPSSDBG("dctrl deinit\n"); if (disp_ctrl) { /*disable vencs*/ if (disp_ctrl->enabled_venc_ids != 0) { r = dc_venc_disable(disp_ctrl->vencmask); if (r) { VPSSERR("Failed to disable vencs.\n"); return r; } } kobject_del(&disp_ctrl->kobj); kobject_put(&disp_ctrl->kobj); for (i = 0; i < disp_ctrl->numvencs; i++) { kobject_del(&disp_ctrl->blenders[i].kobj); kobject_put(&disp_ctrl->blenders[i].kobj); } kfree(disp_ctrl); disp_ctrl = NULL; } if (dc_payload_info) { /*free memory*/ if (dc_payload_info->vaddr) vps_sbuf_free(dc_payload_info->paddr, dc_payload_info->vaddr, dc_payload_info->size); kfree(dc_payload_info); dc_payload_info = NULL; } if (dc_handle) { r = vps_fvid2_delete(dc_handle, NULL); if (r) { VPSSERR("failed to delete DC fvid2 handle.\n"); return r; } dc_handle = NULL; } return r; }
nazgee/igep-kernel
drivers/video/ti81xx/vpss/dctrl.c
C
gpl-2.0
61,473
.vct_frameless_orange { /** Toggle/FAQ **/ /** Tabs **/ /** Tour **/ /* Accordion */ /* Call to Action box **/ /* Separator */ /* Message box */ /* Bar Graph */ /* Button */ /** Colors */ /* Google maps */ } .vct_frameless_orange .clearfix { *zoom: 1; } .vct_frameless_orange .clearfix:before, .vct_frameless_orange .clearfix:after { display: table; content: ""; } .vct_frameless_orange .clearfix:after { clear: both; } .vct_frameless_orange .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .vct_frameless_orange .input-block-level { display: block; width: 100%; min-height: 5px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; } .vct_frameless_orange #content h4.wpb_toggle, .vct_frameless_orange h4.wpb_toggle { position: relative; padding: 7px 15px 7px 35px; border: 1px solid #f3f3f3; border-left: 0; border-right: 0; margin: 0 0 10px 0; font-weight: normal; background: none; -webkit-transition: color 0.3s ease-out; -moz-transition: color 0.3s ease-out; -ms-transition: color 0.3s ease-out; -o-transition: color 0.3s ease-out; transition: color 0.3s ease-out; } .vct_frameless_orange #content h4.wpb_toggle:hover, .vct_frameless_orange h4.wpb_toggle:hover { cursor: pointer; } .vct_frameless_orange #content h4.wpb_toggle:hover, .vct_frameless_orange h4.wpb_toggle:hover { color: #ffac14; } .vct_frameless_orange #content h4.wpb_toggle.wpb_toggle_title_active, .vct_frameless_orange h4.wpb_toggle.wpb_toggle_title_active { color: #ffac14; border-top: 3px solid #ffac14; padding-top: 5px; } .vct_frameless_orange h4.wpb_toggle { color: #333333; } .vct_frameless_orange h4.wpb_toggle:before { content: ''; display: block; position: absolute; left: 0px; top: 0px; width: 35px; height: 100%; font-weight: normal; font-size: 15px; line-height: 37px; text-align: center; background: url(../../images/toggle_open.png) no-repeat center center; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -ms-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; transition: all 0.3s ease-out; } .vct_frameless_orange h4.wpb_toggle_title_active:before { background-image: url(../../images/toggle_close.png); } .vct_frameless_orange .wpb_toggle_content { position: relative; padding: 0px 15px 20px; margin: 0; } .vct_frameless_orange .wpb_content_element .wpb_tour_tabs_wrapper .wpb_tab { padding: 0; background: none; } .vct_frameless_orange .wpb_tour_tabs_wrapper .wpb_tabs_nav { padding: 0; border-bottom: 1px solid #f3f3f3; margin-bottom: 15px !important; } .vct_frameless_orange .wpb_tour_tabs_wrapper .wpb_tabs_nav li { list-style: none; margin: 0 15px 0 0; float: left; background: none; } .vct_frameless_orange .wpb_tour_tabs_wrapper .wpb_tabs_nav li a { font-weight: normal; margin: 0; display: block; padding: 8px 5px; color: #ffac14; opacity: 0.7; filter: alpha(opacity=70); -webkit-transition: color 0.3s ease-out; -moz-transition: color 0.3s ease-out; -ms-transition: color 0.3s ease-out; -o-transition: color 0.3s ease-out; transition: color 0.3s ease-out; -webkit-transition: opacity 0.3s ease-out; -moz-transition: opacity 0.3s ease-out; -ms-transition: opacity 0.3s ease-out; -o-transition: opacity 0.3s ease-out; transition: opacity 0.3s ease-out; } .vct_frameless_orange .wpb_tour_tabs_wrapper .wpb_tabs_nav li.ui-state-active a { color: #ffac14; border-bottom: 3px solid #ffac14; opacity: 1; filter: alpha(opacity=100); } .vct_frameless_orange .wpb_tour_tabs_wrapper .wpb_tabs_nav li:hover a { opacity: 1; filter: alpha(opacity=100); } .vct_frameless_orange .wpb_content_element.wpb_tour .wpb_tour_tabs_wrapper .wpb_tab { padding: 0 0px 0 22px; } .vct_frameless_orange .wpb_tour .wpb_tour_tabs_wrapper .wpb_tour_next_prev_nav a { color: #ffac14; border-color: #f3f3f3; } .vct_frameless_orange .wpb_tour .wpb_tour_tabs_wrapper .wpb_tabs_nav { border-bottom: none; border-top: 1px solid #f3f3f3; } .vct_frameless_orange .wpb_tour .wpb_tour_tabs_wrapper .wpb_tabs_nav li { float: none; margin: 0 0 1px 0; } .vct_frameless_orange .wpb_tour .wpb_tour_tabs_wrapper .wpb_tabs_nav li a { border-bottom: 1px solid #f3f3f3; } .vct_frameless_orange .wpb_tour .wpb_tour_tabs_wrapper .wpb_tabs_nav li.ui-state-active a { color: #ffac14; border-bottom: 3px solid #ffac14; opacity: 1; filter: alpha(opacity=100); padding: 8px 5px 6px 5px; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_content { padding: 0 15px 15px 15px; background: #ffffff; color: #333333; } .vct_frameless_orange .wpb_accordion_section { margin-top: -2px; position: relative; top: 2px; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header { color: #333333; border: 1px solid #f3f3f3; border-left: 0; border-right: 0; padding: 8px 15px; background: none; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header:after { content: ""; display: block; position: absolute; top: 0px; right: 0px; color: #f3f3f3; background: #ffffff url(../../images/toggle_open.png) no-repeat center center; width: 35px; height: 100%; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header.ui-state-active { border-bottom-color: transparent; border-top: 3px solid #ffac14; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header.ui-state-active:after { background-image: url(../../images/toggle_close.png); } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header.ui-state-active:after, .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header.ui-state-hover:after { color: #ffac14; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header a:hover, .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header.ui-state-active a { color: #ffac14; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header a { padding: 0; color: inherit; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -ms-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; transition: all 0.3s ease-out; } .vct_frameless_orange .wpb_content_element .wpb_accordion_wrapper .wpb_accordion_header > span { display: none; } .vct_frameless_orange .wpb_call_to_action { background: none; border: 1px solid #f3f3f3; border-left: 0; border-right: 0; padding: 30px 25px; position: relative; } .vct_frameless_orange .wpb_call_to_action:before { content: ""; display: block; position: absolute; bottom: -7px; left: 0; width: 100%; height: 1px; border-bottom: 3px solid #f3f3f3; } .vct_frameless_orange .wpb_call_to_action .wpb_call_text { font-weight: normal; color: #ffac14; } .vct_frameless_orange .wpb_separator, .vct_frameless_orange .vc_text_separator { position: relative; border-bottom: 1px solid #f3f3f3; } .vct_frameless_orange .wpb_separator:after, .vct_frameless_orange .vc_text_separator:after { content: ""; position: absolute; top: 4px; left: 0; width: 100%; height: 1px; border-bottom: 3px solid #f3f3f3; } .vct_frameless_orange .vc_text_separator div { top: -9px; color: #ffac14; background: #ffffff; position: relative; z-index: 1; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .vct_frameless_orange .wpb_alert .messagebox_text { padding-left: 40px; } .vct_frameless_orange .wpb_alert { color: #aa8a02; border: 1px solid #fdda48; text-shadow: none; padding: 15px 25px; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; } .vct_frameless_orange .wpb_alert-success { border: 1px solid #6ab165; } .vct_frameless_orange .wpb_alert-success p { color: #2d532a; } .vct_frameless_orange .wpb_alert-error { border: 1px solid #d95757; } .vct_frameless_orange .wpb_alert-error p { color: #7b1c1c; } .vct_frameless_orange .wpb_alert-info { border: 1px solid #686b72; } .vct_frameless_orange .wpb_alert-info p { color: #1f2022; } .vct_frameless_orange .vc_progress_bar .vc_single_bar { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; border: 1px solid #f3f3f3; background: none; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; } .vct_frameless_orange .vc_progress_bar .vc_single_bar .vc_bar { -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; } .vct_frameless_orange .vc_progress_bar .bar_grey .vc_label { color: #ffffff; } .vct_frameless_orange .vc_progress_bar .bar_grey .vc_bar { background: #ffac14; } .vct_frameless_orange .wpb_button { border: 0; padding: 6px 10px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -ms-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; transition: all 0.3s ease-out; text-shadow: none; } .vct_frameless_orange .wpb_btn-mini { padding: 3px 7px 4px 7px; font-size: 85%; line-height: 110%; } .vct_frameless_orange .wpb_btn-small { padding: 5px 10px 5px; font-size: 85%; line-height: 110%; } .vct_frameless_orange .wpb_regularsize { padding: 8px 20px; } .vct_frameless_orange .wpb_btn-large { padding: 10px 25px; font-size: 120%; } .vct_frameless_orange .wpb_wpb_button { background: #ffac14; color: #ffffff; } .vct_frameless_orange .wpb_wpb_button:hover { background: #404040; } .vct_frameless_orange .wpb_btn-inverse { background: #414141; } .vct_frameless_orange .wpb_btn-inverse:hover { background: #272727; } .vct_frameless_orange .wpb_btn-danger { background: #DA4F49; } .vct_frameless_orange .wpb_btn-danger:hover { background: #c72f29; } .vct_frameless_orange .wpb_btn-success { background: #5BB75B; } .vct_frameless_orange .wpb_btn-success:hover { background: #449b44; } .vct_frameless_orange .wpb_btn-warning { background: #FAA732; } .vct_frameless_orange .wpb_btn-warning:hover { background: #f39106; } .vct_frameless_orange .wpb_gmaps_widget .wpb_map_wraper { padding: 5px; border: 1px solid #f3f3f3; background-color: #f8f8f8; background-image: -moz-linear-gradient(top, #f3f3f3, #ffffff); background-image: -ms-linear-gradient(top, #f3f3f3, #ffffff); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f3f3f3), to(#ffffff)); background-image: -webkit-linear-gradient(top, #f3f3f3, #ffffff); background-image: -o-linear-gradient(top, #f3f3f3, #ffffff); background-image: linear-gradient(top, #f3f3f3, #ffffff); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f3f3f3', endColorstr='#ffffff', GradientType=0); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }
jfbelisle/magexpress
wp-content/themes/magexpress/wpbakery/templatera/assets/css/themes/frameless_orange.css
CSS
gpl-2.0
11,166
/*------------------------------------------------------------------------- _fsreturnval.c - Floating point library in optimized assembly for 8051 Copyright (c) 2004, Paul Stoffregen, paul@pjrc.com This library 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this library; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, if you link this library with other files, some of which are compiled with SDCC, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. -------------------------------------------------------------------------*/ #define __SDCC_FLOAT_LIB #include <float.h> #ifdef FLOAT_ASM_MCS51 static void dummy(void) __naked { __asm .globl fs_round_and_return fs_round_and_return: #ifdef FLOAT_FULL_ACCURACY // discard the extra 8 bits of precision we kept around in r1 cjne r1, #128, 00001$ mov a, r2 rrc a cpl c 00001$: jc fs_zerocheck_return mov a, r2 add a, #1 mov r2, a clr a addc a, r3 mov r3, a clr a addc a, r4 mov r4, a jnc fs_zerocheck_return mov r4, #0x80 inc exp_a #endif .globl fs_zerocheck_return fs_zerocheck_return: // zero output is a special case cjne r4, #0, fs_direct_return cjne r3, #0, fs_direct_return cjne r2, #0, fs_direct_return .globl fs_return_zero fs_return_zero: clr a mov b, a mov dph, a mov dpl, a ret .globl fs_direct_return fs_direct_return: // collect all pieces and return mov c, sign_a mov a, exp_a rrc a mov b, r4 mov b.7, c mov dph, r3 mov dpl, r2 ret .globl fs_return_inf fs_return_inf: clr a mov dph, a mov dpl, a mov b, #0x80 cpl a mov c, sign_a rrc a ret .globl fs_return_nan fs_return_nan: clr a mov dph, a mov dpl, a mov b, #0xC0 mov a, #0x7F ret __endasm; } #endif
PinguinoIDE/pinguino-compilers
windows64/p8/share/sdcc/lib/src/_fsreturnval.c
C
gpl-2.0
2,557
// SPDX-License-Identifier: GPL-2.0-only /* * e750-wm9705.c -- SoC audio for e750 * * Copyright 2007 (c) Ian Molton <spyro@f2s.com> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/gpio.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <mach/audio.h> #include <mach/eseries-gpio.h> #include <asm/mach-types.h> static int e750_spk_amp_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { if (event & SND_SOC_DAPM_PRE_PMU) gpio_set_value(GPIO_E750_SPK_AMP_OFF, 0); else if (event & SND_SOC_DAPM_POST_PMD) gpio_set_value(GPIO_E750_SPK_AMP_OFF, 1); return 0; } static int e750_hp_amp_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { if (event & SND_SOC_DAPM_PRE_PMU) gpio_set_value(GPIO_E750_HP_AMP_OFF, 0); else if (event & SND_SOC_DAPM_POST_PMD) gpio_set_value(GPIO_E750_HP_AMP_OFF, 1); return 0; } static const struct snd_soc_dapm_widget e750_dapm_widgets[] = { SND_SOC_DAPM_HP("Headphone Jack", NULL), SND_SOC_DAPM_SPK("Speaker", NULL), SND_SOC_DAPM_MIC("Mic (Internal)", NULL), SND_SOC_DAPM_PGA_E("Headphone Amp", SND_SOC_NOPM, 0, 0, NULL, 0, e750_hp_amp_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("Speaker Amp", SND_SOC_NOPM, 0, 0, NULL, 0, e750_spk_amp_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), }; static const struct snd_soc_dapm_route audio_map[] = { {"Headphone Amp", NULL, "HPOUTL"}, {"Headphone Amp", NULL, "HPOUTR"}, {"Headphone Jack", NULL, "Headphone Amp"}, {"Speaker Amp", NULL, "MONOOUT"}, {"Speaker", NULL, "Speaker Amp"}, {"MIC1", NULL, "Mic (Internal)"}, }; static struct snd_soc_dai_link e750_dai[] = { { .name = "AC97", .stream_name = "AC97 HiFi", .cpu_dai_name = "pxa2xx-ac97", .codec_dai_name = "wm9705-hifi", .platform_name = "pxa-pcm-audio", .codec_name = "wm9705-codec", /* use ops to check startup state */ }, { .name = "AC97 Aux", .stream_name = "AC97 Aux", .cpu_dai_name = "pxa2xx-ac97-aux", .codec_dai_name = "wm9705-aux", .platform_name = "pxa-pcm-audio", .codec_name = "wm9705-codec", }, }; static struct snd_soc_card e750 = { .name = "Toshiba e750", .owner = THIS_MODULE, .dai_link = e750_dai, .num_links = ARRAY_SIZE(e750_dai), .dapm_widgets = e750_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(e750_dapm_widgets), .dapm_routes = audio_map, .num_dapm_routes = ARRAY_SIZE(audio_map), .fully_routed = true, }; static struct gpio e750_audio_gpios[] = { { GPIO_E750_HP_AMP_OFF, GPIOF_OUT_INIT_HIGH, "Headphone amp" }, { GPIO_E750_SPK_AMP_OFF, GPIOF_OUT_INIT_HIGH, "Speaker amp" }, }; static int e750_probe(struct platform_device *pdev) { struct snd_soc_card *card = &e750; int ret; ret = gpio_request_array(e750_audio_gpios, ARRAY_SIZE(e750_audio_gpios)); if (ret) return ret; card->dev = &pdev->dev; ret = devm_snd_soc_register_card(&pdev->dev, card); if (ret) { dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n", ret); gpio_free_array(e750_audio_gpios, ARRAY_SIZE(e750_audio_gpios)); } return ret; } static int e750_remove(struct platform_device *pdev) { gpio_free_array(e750_audio_gpios, ARRAY_SIZE(e750_audio_gpios)); return 0; } static struct platform_driver e750_driver = { .driver = { .name = "e750-audio", .pm = &snd_soc_pm_ops, }, .probe = e750_probe, .remove = e750_remove, }; module_platform_driver(e750_driver); /* Module information */ MODULE_AUTHOR("Ian Molton <spyro@f2s.com>"); MODULE_DESCRIPTION("ALSA SoC driver for e750"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:e750-audio");
koct9i/linux
sound/soc/pxa/e750_wm9705.c
C
gpl-2.0
3,657
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. 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. COPYRIGHT NOTICE: TokuDB, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: 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. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2011-2013 Tokutek Inc. All rights reserved." // generate a tree with a single leaf node containing duplicate keys // check that brt verify finds them #include <ft-cachetable-wrappers.h> #include "test.h" static FTNODE make_node(FT_HANDLE brt, int height) { FTNODE node = NULL; int n_children = (height == 0) ? 1 : 0; toku_create_new_ftnode(brt, &node, height, n_children); if (n_children) BP_STATE(node,0) = PT_AVAIL; return node; } static void append_leaf(FTNODE leafnode, void *key, size_t keylen, void *val, size_t vallen) { assert(leafnode->height == 0); DBT thekey; toku_fill_dbt(&thekey, key, keylen); DBT theval; toku_fill_dbt(&theval, val, vallen); // get an index that we can use to create a new leaf entry uint32_t idx = toku_omt_size(BLB_BUFFER(leafnode, 0)); // apply an insert to the leaf node MSN msn = next_dummymsn(); FT_MSG_S cmd = { FT_INSERT, msn, xids_get_root_xids(), .u={.id = { &thekey, &theval }} }; toku_ft_bn_apply_cmd_once(BLB(leafnode, 0), &cmd, idx, NULL, TXNID_NONE, make_gc_info(false), NULL, NULL); // dont forget to dirty the node leafnode->dirty = 1; } static void populate_leaf(FTNODE leafnode, int k, int v) { append_leaf(leafnode, &k, sizeof k, &v, sizeof v); } static void test_dup_in_leaf(int do_verify) { int r; // cleanup const char *fname = TOKU_TEST_FILENAME; r = unlink(fname); assert(r == 0 || (r == -1 && errno == ENOENT)); // create a cachetable CACHETABLE ct = NULL; toku_cachetable_create(&ct, 0, ZERO_LSN, NULL_LOGGER); // create the brt TOKUTXN null_txn = NULL; FT_HANDLE brt = NULL; r = toku_open_ft_handle(fname, 1, &brt, 1024, 256, TOKU_DEFAULT_COMPRESSION_METHOD, ct, null_txn, toku_builtin_compare_fun); assert(r == 0); // discard the old root block FTNODE newroot = make_node(brt, 0); populate_leaf(newroot, htonl(2), 1); populate_leaf(newroot, htonl(2), 2); // set the new root to point to the new tree toku_ft_set_new_root_blocknum(brt->ft, newroot->thisnodename); // unpin the new root toku_unpin_ftnode(brt->ft, newroot); if (do_verify) { r = toku_verify_ft(brt); assert(r != 0); } // flush to the file system r = toku_close_ft_handle_nolsn(brt, 0); assert(r == 0); // shutdown the cachetable toku_cachetable_close(&ct); } static int usage(void) { return 1; } int test_main (int argc , const char *argv[]) { int do_verify = 1; initialize_dummymsn(); for (int i = 1; i < argc; i++) { const char *arg = argv[i]; if (strcmp(arg, "-v") == 0) { verbose++; continue; } if (strcmp(arg, "-q") == 0) { verbose = 0; continue; } if (strcmp(arg, "--verify") == 0 && i+1 < argc) { do_verify = atoi(argv[++i]); continue; } return usage(); } test_dup_in_leaf(do_verify); return 0; }
YannNayn/mariadb-galera-msvc
storage/tokudb/ft-index/ft/tests/verify-dup-in-leaf.cc
C++
gpl-2.0
6,838
/* Copyright (c) 2011, Code Aurora Forum. 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 version 2 and * only 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. * */ /* * Toshiba MIPI-DSI-to-LVDS Bridge driver. * Device Model TC358764XBG/65XBG. * Reference document: TC358764XBG_65XBG_V119.pdf * * The Host sends a DSI Generic Long Write packet (Data ID = 0x29) over the * DSI link for each write access transaction to the chip configuration * registers. * Payload of this packet is 16-bit register address and 32-bit data. * Multiple data values are allowed for sequential addresses. * * The Host sends a DSI Generic Read packet (Data ID = 0x24) over the DSI * link for each read request transaction to the chip configuration * registers. Payload of this packet is further defined as follows: * 16-bit address followed by a 32-bit value (Generic Long Read Response * packet). * * The bridge supports 5 GPIO lines controlled via the GPC register. * * The bridge support I2C Master/Slave. * The I2C slave can be used for read/write to the bridge register instead of * using the DSI interface. * I2C slave address is 0x0F (read/write 0x1F/0x1E). * The I2C Master can be used for communication with the panel if * it has an I2C slave. * * NOTE: The I2C interface is not used in this driver. * Only the DSI interface is used for read/write the bridge registers. * * Pixel data can be transmitted in non-burst or burst fashion. * Non-burst refers to pixel data packet transmission time on DSI link * being roughly the same (to account for packet overhead time) * as active video line time on LVDS output (i.e. DE = 1). * And burst refers to pixel data packet transmission time on DSI link * being less than the active video line time on LVDS output. * Video mode transmission is further differentiated by the types of * timing events being transmitted. * Video pulse mode refers to the case where both sync start and sync end * events (for frame and line) are transmitted. * Video event mode refers to the case where only sync start events * are transmitted. * This is configured via register bit VPCTRL.EVTMODE. * */ /* #define DEBUG 1 */ /** * Use the I2C master to control the panel. */ /* #define TC358764_USE_I2C_MASTER */ #define DRV_NAME "mipi_tc358764" #include <linux/i2c.h> #include <linux/delay.h> #include <linux/pwm.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include "msm_fb.h" #include "mipi_dsi.h" #include "mipi_tc358764_dsi2lvds.h" /* Registers definition */ /* DSI D-PHY Layer Registers */ #define D0W_DPHYCONTTX 0x0004 /* Data Lane 0 DPHY Tx Control */ #define CLW_DPHYCONTRX 0x0020 /* Clock Lane DPHY Rx Control */ #define D0W_DPHYCONTRX 0x0024 /* Data Lane 0 DPHY Rx Control */ #define D1W_DPHYCONTRX 0x0028 /* Data Lane 1 DPHY Rx Control */ #define D2W_DPHYCONTRX 0x002C /* Data Lane 2 DPHY Rx Control */ #define D3W_DPHYCONTRX 0x0030 /* Data Lane 3 DPHY Rx Control */ #define COM_DPHYCONTRX 0x0038 /* DPHY Rx Common Control */ #define CLW_CNTRL 0x0040 /* Clock Lane Control */ #define D0W_CNTRL 0x0044 /* Data Lane 0 Control */ #define D1W_CNTRL 0x0048 /* Data Lane 1 Control */ #define D2W_CNTRL 0x004C /* Data Lane 2 Control */ #define D3W_CNTRL 0x0050 /* Data Lane 3 Control */ #define DFTMODE_CNTRL 0x0054 /* DFT Mode Control */ /* DSI PPI Layer Registers */ #define PPI_STARTPPI 0x0104 /* START control bit of PPI-TX function. */ #define PPI_BUSYPPI 0x0108 #define PPI_LINEINITCNT 0x0110 /* Line Initialization Wait Counter */ #define PPI_LPTXTIMECNT 0x0114 #define PPI_LANEENABLE 0x0134 /* Enables each lane at the PPI layer. */ #define PPI_TX_RX_TA 0x013C /* DSI Bus Turn Around timing parameters */ /* Analog timer function enable */ #define PPI_CLS_ATMR 0x0140 /* Delay for Clock Lane in LPRX */ #define PPI_D0S_ATMR 0x0144 /* Delay for Data Lane 0 in LPRX */ #define PPI_D1S_ATMR 0x0148 /* Delay for Data Lane 1 in LPRX */ #define PPI_D2S_ATMR 0x014C /* Delay for Data Lane 2 in LPRX */ #define PPI_D3S_ATMR 0x0150 /* Delay for Data Lane 3 in LPRX */ #define PPI_D0S_CLRSIPOCOUNT 0x0164 #define PPI_D1S_CLRSIPOCOUNT 0x0168 /* For lane 1 */ #define PPI_D2S_CLRSIPOCOUNT 0x016C /* For lane 2 */ #define PPI_D3S_CLRSIPOCOUNT 0x0170 /* For lane 3 */ #define CLS_PRE 0x0180 /* Digital Counter inside of PHY IO */ #define D0S_PRE 0x0184 /* Digital Counter inside of PHY IO */ #define D1S_PRE 0x0188 /* Digital Counter inside of PHY IO */ #define D2S_PRE 0x018C /* Digital Counter inside of PHY IO */ #define D3S_PRE 0x0190 /* Digital Counter inside of PHY IO */ #define CLS_PREP 0x01A0 /* Digital Counter inside of PHY IO */ #define D0S_PREP 0x01A4 /* Digital Counter inside of PHY IO */ #define D1S_PREP 0x01A8 /* Digital Counter inside of PHY IO */ #define D2S_PREP 0x01AC /* Digital Counter inside of PHY IO */ #define D3S_PREP 0x01B0 /* Digital Counter inside of PHY IO */ #define CLS_ZERO 0x01C0 /* Digital Counter inside of PHY IO */ #define D0S_ZERO 0x01C4 /* Digital Counter inside of PHY IO */ #define D1S_ZERO 0x01C8 /* Digital Counter inside of PHY IO */ #define D2S_ZERO 0x01CC /* Digital Counter inside of PHY IO */ #define D3S_ZERO 0x01D0 /* Digital Counter inside of PHY IO */ #define PPI_CLRFLG 0x01E0 /* PRE Counters has reached set values */ #define PPI_CLRSIPO 0x01E4 /* Clear SIPO values, Slave mode use only. */ #define HSTIMEOUT 0x01F0 /* HS Rx Time Out Counter */ #define HSTIMEOUTENABLE 0x01F4 /* Enable HS Rx Time Out Counter */ #define DSI_STARTDSI 0x0204 /* START control bit of DSI-TX function */ #define DSI_BUSYDSI 0x0208 #define DSI_LANEENABLE 0x0210 /* Enables each lane at the Protocol layer. */ #define DSI_LANESTATUS0 0x0214 /* Displays lane is in HS RX mode. */ #define DSI_LANESTATUS1 0x0218 /* Displays lane is in ULPS or STOP state */ #define DSI_INTSTATUS 0x0220 /* Interrupt Status */ #define DSI_INTMASK 0x0224 /* Interrupt Mask */ #define DSI_INTCLR 0x0228 /* Interrupt Clear */ #define DSI_LPTXTO 0x0230 /* Low Power Tx Time Out Counter */ #define DSIERRCNT 0x0300 /* DSI Error Count */ #define APLCTRL 0x0400 /* Application Layer Control */ #define RDPKTLN 0x0404 /* Command Read Packet Length */ #define VPCTRL 0x0450 /* Video Path Control */ #define HTIM1 0x0454 /* Horizontal Timing Control 1 */ #define HTIM2 0x0458 /* Horizontal Timing Control 2 */ #define VTIM1 0x045C /* Vertical Timing Control 1 */ #define VTIM2 0x0460 /* Vertical Timing Control 2 */ #define VFUEN 0x0464 /* Video Frame Timing Update Enable */ /* Mux Input Select for LVDS LINK Input */ #define LVMX0003 0x0480 /* Bit 0 to 3 */ #define LVMX0407 0x0484 /* Bit 4 to 7 */ #define LVMX0811 0x0488 /* Bit 8 to 11 */ #define LVMX1215 0x048C /* Bit 12 to 15 */ #define LVMX1619 0x0490 /* Bit 16 to 19 */ #define LVMX2023 0x0494 /* Bit 20 to 23 */ #define LVMX2427 0x0498 /* Bit 24 to 27 */ #define LVCFG 0x049C /* LVDS Configuration */ #define LVPHY0 0x04A0 /* LVDS PHY 0 */ #define LVPHY1 0x04A4 /* LVDS PHY 1 */ #define SYSSTAT 0x0500 /* System Status */ #define SYSRST 0x0504 /* System Reset */ /* GPIO Registers */ #define GPIOC 0x0520 /* GPIO Control */ #define GPIOO 0x0524 /* GPIO Output */ #define GPIOI 0x0528 /* GPIO Input */ /* I2C Registers */ #define I2CTIMCTRL 0x0540 /* I2C IF Timing and Enable Control */ #define I2CMADDR 0x0544 /* I2C Master Addressing */ #define WDATAQ 0x0548 /* Write Data Queue */ #define RDATAQ 0x054C /* Read Data Queue */ /* Chip ID and Revision ID Register */ #define IDREG 0x0580 #define TC358764XBG_ID 0x00006500 /* Debug Registers */ #define DEBUG00 0x05A0 /* Debug */ #define DEBUG01 0x05A4 /* LVDS Data */ /* PWM */ #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT_PANEL) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT_PANEL) #define PWM_FREQ_HZ (5*1000) /* 33 KHZ */ #define PWM_LEVEL 200 #else #define PWM_FREQ_HZ (66*1000) /* 66 KHZ */ #define PWM_LEVEL 15 #endif #define PWM_PERIOD_USEC (USEC_PER_SEC / PWM_FREQ_HZ) #define PWM_DUTY_LEVEL (PWM_PERIOD_USEC / PWM_LEVEL) #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT_PANEL) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT_PANEL) #define PWM_DUTY_MAX PWM_DUTY_LEVEL #define DUTY_DIM 5 #define DUTY_MIN 8 #define DUTY_25 20 #define DUTY_DEFAULT 70 #define DUTY_MAX 189 /* Backlight levels */ #define BRIGHTNESS_OFF 0 #define BRIGHTNESS_DIM 20 #define BRIGHTNESS_MIN 30 #define BRIGHTNESS_25 86 #define BRIGHTNESS_DEFAULT 140 #define BRIGHTNESS_MAX 255 #endif #define CMD_DELAY 100 #define DSI_MAX_LANES 4 #define KHZ 1000 #define MHZ (1000*1000) /** * Command payload for DTYPE_GEN_LWRITE (0x29) / DTYPE_GEN_READ2 (0x24). */ struct wr_cmd_payload { u16 addr; u32 data; } __packed; /* * Driver state. */ static struct msm_panel_common_pdata *d2l_common_pdata; struct msm_fb_data_type *d2l_mfd; static struct dsi_buf d2l_tx_buf; static struct dsi_buf d2l_rx_buf; static int led_pwm; static struct pwm_device *bl_pwm; static int initial_powerseq; static int bl_level; #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT) static struct delayed_work det_work; #endif static u32 d2l_gpio_out_mask; static u32 d2l_gpio_out_val; static int mipi_d2l_init(void); /** * Read a bridge register * * @param mfd * * @return register data value */ static u32 mipi_d2l_read_reg(struct msm_fb_data_type *mfd, u16 reg) { u32 data; int len = 4; struct dsi_cmd_desc cmd_read_reg = { DTYPE_GEN_READ2, 1, 0, 1, 0, /* cmd 0x24 */ sizeof(reg), (char *) &reg}; mipi_dsi_buf_init(&d2l_tx_buf); mipi_dsi_buf_init(&d2l_rx_buf); /* mutex had been acquried at dsi_on */ len = mipi_dsi_cmds_rx(mfd, &d2l_tx_buf, &d2l_rx_buf, &cmd_read_reg, len); data = *(u32 *)d2l_rx_buf.data; if (len != 4) pr_err("%s: invalid rlen=%d, expecting 4.\n", __func__, len); pr_debug("%s: reg=0x%x.data=0x%08x.\n", __func__, reg, data); return data; } /** * Write a bridge register * * @param mfd * * @return register data value */ static u32 mipi_d2l_write_reg(struct msm_fb_data_type *mfd, u16 reg, u32 data) { struct wr_cmd_payload payload; struct dsi_cmd_desc cmd_write_reg = { DTYPE_GEN_LWRITE, 1, 0, 0, 0, sizeof(payload), (char *)&payload}; payload.addr = reg; payload.data = data; /* mutex had been acquried at dsi_on */ mipi_dsi_cmds_tx(mfd, &d2l_tx_buf, &cmd_write_reg, 1); pr_debug("%s: reg=0x%x. data=0x%x.\n", __func__, reg, data); return data; } /* * Init the D2L bridge via the DSI interface for Video. * * Register Addr Value * =================================================== * PPI_TX_RX_TA 0x013C 0x00040004 * PPI_LPTXTIMECNT 0x0114 0x00000004 * PPI_D0S_CLRSIPOCOUNT 0x0164 0x00000003 * PPI_D1S_CLRSIPOCOUNT 0x0168 0x00000003 * PPI_D2S_CLRSIPOCOUNT 0x016C 0x00000003 * PPI_D3S_CLRSIPOCOUNT 0x0170 0x00000003 * PPI_LANEENABLE 0x0134 0x0000001F * DSI_LANEENABLE 0x0210 0x0000001F * PPI_STARTPPI 0x0104 0x00000001 * DSI_STARTDSI 0x0204 0x00000001 * VPCTRL 0x0450 0x01000120 * HTIM1 0x0454 0x002C0028 * VTIM1 0x045C 0x001E0008 * VFUEN 0x0464 0x00000001 * LVCFG 0x049C 0x00000001 * * VPCTRL.EVTMODE (0x20) configuration bit is needed to determine whether * video timing information is delivered in pulse mode or event mode. * In pulse mode, both Sync Start and End packets are required. * In event mode, only Sync Start packets are required. * * @param mfd * * @return register data value */ static int mipi_d2l_dsi_init_sequence(struct msm_fb_data_type *mfd) { struct mipi_panel_info *mipi = &mfd->panel_info.mipi; u32 lanes_enable; u32 vpctrl; u32 htime1 = 0x002C0028; u32 vtime1 = 0x001E0008; lanes_enable = 0x01; /* clock-lane enable */ lanes_enable |= (mipi->data_lane0 << 1); lanes_enable |= (mipi->data_lane1 << 2); lanes_enable |= (mipi->data_lane2 << 3); lanes_enable |= (mipi->data_lane3 << 4); if (mipi->traffic_mode == DSI_NON_BURST_SYNCH_EVENT) vpctrl = 0x01000120; else if (mipi->traffic_mode == DSI_NON_BURST_SYNCH_PULSE) vpctrl = 0x01000100; else { pr_err("%s.unsupported traffic_mode %d.\n", __func__, mipi->traffic_mode); return -EINVAL; } pr_debug("%s.htime1=0x%x.\n", __func__, htime1); pr_debug("%s.vtime1=0x%x.\n", __func__, vtime1); pr_debug("%s.vpctrl=0x%x.\n", __func__, vpctrl); pr_debug("%s.lanes_enable=0x%x.\n", __func__, lanes_enable); #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT) /* VESA format instead of JEIDA format for RGB888 */ mipi_d2l_write_reg(mfd, LVMX0003, 0x03020100); mipi_d2l_write_reg(mfd, LVMX0407, 0x08050704); mipi_d2l_write_reg(mfd, LVMX0811, 0x0F0E0A09); mipi_d2l_write_reg(mfd, LVMX1215, 0x100D0C0B); mipi_d2l_write_reg(mfd, LVMX1619, 0x12111716); mipi_d2l_write_reg(mfd, LVMX2023, 0x1B151413); mipi_d2l_write_reg(mfd, LVMX2427, 0x061A1918); mipi_d2l_write_reg(mfd, PPI_TX_RX_TA, 0x00030005); /* BTA */ mipi_d2l_write_reg(mfd, PPI_LPTXTIMECNT, 0x00000003); mipi_d2l_write_reg(mfd, PPI_D0S_CLRSIPOCOUNT, 0x00000002); mipi_d2l_write_reg(mfd, PPI_D1S_CLRSIPOCOUNT, 0x00000002); mipi_d2l_write_reg(mfd, PPI_D2S_CLRSIPOCOUNT, 0x00000002); mipi_d2l_write_reg(mfd, PPI_D3S_CLRSIPOCOUNT, 0x00000002); mipi_d2l_write_reg(mfd, PPI_LANEENABLE, 0x0000001F); mipi_d2l_write_reg(mfd, DSI_LANEENABLE, 0x0000001F); mipi_d2l_write_reg(mfd, PPI_STARTPPI, 0x00000001); mipi_d2l_write_reg(mfd, DSI_STARTDSI, 0x00000001); mipi_d2l_write_reg(mfd, VPCTRL, 0x03F00121); /* RGB888 + Event mode */ mipi_d2l_write_reg(mfd, HTIM1, 0x00140114); mipi_d2l_write_reg(mfd, HTIM2, 0x00340400); mipi_d2l_write_reg(mfd, VTIM1, 0x0022000A); mipi_d2l_write_reg(mfd, VTIM1, 0x00150258); mipi_d2l_write_reg(mfd, VFUEN, 0x00000001); mipi_d2l_write_reg(mfd, LVPHY0, 0x0044802D); udelay(20); mipi_d2l_write_reg(mfd, LVPHY0, 0x0004802D); mipi_d2l_write_reg(mfd, LVCFG, 0x00000101); #else mipi_d2l_write_reg(mfd, SYSRST, 0xFF); msleep(30); /* VESA format instead of JEIDA format for RGB888 */ mipi_d2l_write_reg(mfd, LVMX0003, 0x03020100); mipi_d2l_write_reg(mfd, LVMX0407, 0x08050704); mipi_d2l_write_reg(mfd, LVMX0811, 0x0F0E0A09); mipi_d2l_write_reg(mfd, LVMX1215, 0x100D0C0B); mipi_d2l_write_reg(mfd, LVMX1619, 0x12111716); mipi_d2l_write_reg(mfd, LVMX2023, 0x1B151413); mipi_d2l_write_reg(mfd, LVMX2427, 0x061A1918); mipi_d2l_write_reg(mfd, PPI_TX_RX_TA, 0x00040004); /* BTA */ mipi_d2l_write_reg(mfd, PPI_LPTXTIMECNT, 0x00000004); mipi_d2l_write_reg(mfd, PPI_D0S_CLRSIPOCOUNT, 0x00000003); mipi_d2l_write_reg(mfd, PPI_D1S_CLRSIPOCOUNT, 0x00000003); mipi_d2l_write_reg(mfd, PPI_D2S_CLRSIPOCOUNT, 0x00000003); mipi_d2l_write_reg(mfd, PPI_D3S_CLRSIPOCOUNT, 0x00000003); mipi_d2l_write_reg(mfd, PPI_LANEENABLE, lanes_enable); mipi_d2l_write_reg(mfd, DSI_LANEENABLE, lanes_enable); mipi_d2l_write_reg(mfd, PPI_STARTPPI, 0x00000001); mipi_d2l_write_reg(mfd, DSI_STARTDSI, 0x00000001); mipi_d2l_write_reg(mfd, VPCTRL, vpctrl); /* RGB888 + Event mode */ mipi_d2l_write_reg(mfd, HTIM1, htime1); mipi_d2l_write_reg(mfd, VTIM1, vtime1); mipi_d2l_write_reg(mfd, VFUEN, 0x00000001); mipi_d2l_write_reg(mfd, LVCFG, 0x00000001); /* Enables LVDS tx */ #endif /* CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT */ return 0; } #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT_PANEL) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT_PANEL) static int scale_pwm_dutycycle(int level) { int scaled_level = 0; if (level == BRIGHTNESS_OFF) scaled_level = BRIGHTNESS_OFF; else if (level <= BRIGHTNESS_DIM) scaled_level = PWM_DUTY_MAX*DUTY_DIM; else if (level <= BRIGHTNESS_MIN) scaled_level = (level - BRIGHTNESS_DIM) * (PWM_DUTY_MAX * DUTY_MIN - PWM_DUTY_MAX * DUTY_DIM) / (BRIGHTNESS_MIN - BRIGHTNESS_DIM) + PWM_DUTY_MAX * DUTY_DIM; else if (level <= BRIGHTNESS_25) scaled_level = (level - BRIGHTNESS_MIN) * (PWM_DUTY_MAX * DUTY_25 - PWM_DUTY_MAX * DUTY_MIN) / (BRIGHTNESS_25 - BRIGHTNESS_MIN) + PWM_DUTY_MAX * DUTY_MIN; else if (level <= BRIGHTNESS_DEFAULT) scaled_level = (level - BRIGHTNESS_25) * (PWM_DUTY_MAX * DUTY_DEFAULT - PWM_DUTY_MAX * DUTY_25) / (BRIGHTNESS_DEFAULT - BRIGHTNESS_25) + PWM_DUTY_MAX * DUTY_25; else if (level <= BRIGHTNESS_MAX) scaled_level = (level - BRIGHTNESS_DEFAULT) * (PWM_DUTY_MAX * DUTY_MAX - PWM_DUTY_MAX * DUTY_DEFAULT) / (BRIGHTNESS_MAX - BRIGHTNESS_DEFAULT) + PWM_DUTY_MAX * DUTY_DEFAULT; return scaled_level; } #endif /** * Set Backlight level. * * @param pwm * @param level * * @return int */ static int mipi_d2l_set_backlight_level(struct pwm_device *pwm, int level) { int ret = 0; pr_debug("%s: level=%d.\n", __func__, level); #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT_PANEL) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT_PANEL) if ((pwm == NULL) || (level > BRIGHTNESS_MAX) || (level < 0)) { pr_err("%s.pwm=NULL.\n", __func__); return -EINVAL; } level = scale_pwm_dutycycle(level); #else if ((pwm == NULL) || (level > PWM_LEVEL) || (level < 0)) { pr_err("%s.pwm=NULL.\n", __func__); return -EINVAL; } #endif ret = pwm_config(pwm, PWM_DUTY_LEVEL * level, PWM_PERIOD_USEC); if (ret) { pr_err("%s: pwm_config() failed err=%d.\n", __func__, ret); return ret; } ret = pwm_enable(pwm); if (ret) { pr_err("%s: pwm_enable() failed err=%d\n", __func__, ret); return ret; } return 0; } #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT) static void blenable_work_func(struct work_struct *work) { int ret = 0; /* Set backlight via PWM */ if (bl_pwm) { ret = mipi_d2l_set_backlight_level(bl_pwm, bl_level); if (ret) pr_err("%s.mipi_d2l_set_backlight_level.ret=%d", __func__, ret); } } #endif /** * LCD ON. * * Set LCD On via MIPI interface or I2C-Slave interface. * Set Backlight on. * * @param pdev * * @return int */ static int mipi_d2l_lcd_on(struct platform_device *pdev) { int ret = 0; u32 chip_id; struct msm_fb_data_type *mfd; pr_info("%s.\n", __func__); /* wait for valid clock before sending data over DSI or I2C. */ msleep(30); mfd = platform_get_drvdata(pdev); d2l_mfd = mfd; if (!mfd) return -ENODEV; if (mfd->key != MFD_KEY) return -EINVAL; chip_id = mipi_d2l_read_reg(mfd, IDREG); if (chip_id != TC358764XBG_ID) { pr_err("%s: invalid chip_id=0x%x", __func__, chip_id); return -ENODEV; } ret = mipi_d2l_dsi_init_sequence(mfd); if (ret) return ret; mipi_d2l_write_reg(mfd, GPIOC, d2l_gpio_out_mask); /* Set GPIOs: gpio#4=U/D=0 , gpio#3=L/R=1 , gpio#2,1=CABC=0. */ mipi_d2l_write_reg(mfd, GPIOO, d2l_gpio_out_val); #if defined(CONFIG_FB_MSM_MIPI_BOEOT_TFT_VIDEO_WSVGA_PT_PANEL) \ || defined(CONFIG_FB_MSM_MIPI_SAMSUNG_TFT_VIDEO_WXGA_PT_PANEL) if ((bl_level == 0) && (!initial_powerseq)) { bl_level = BRIGHTNESS_DEFAULT ; /* Default ON value */ INIT_DELAYED_WORK(&det_work, blenable_work_func); schedule_delayed_work(&det_work, msecs_to_jiffies(250)); } #else if ((bl_level == 0) && (!initial_powerseq)) bl_level = PWM_LEVEL * 2 / 3 ; /* Default ON value */ /* Set backlight via PWM */ if (bl_pwm) { ret = mipi_d2l_set_backlight_level(bl_pwm, bl_level); if (ret) pr_err("%s.mipi_d2l_set_backlight_level.ret=%d", __func__, ret); } #endif pr_info("%s.ret=%d.\n", __func__, ret); /* Set power on flag */ initial_powerseq = 1; return ret; } /** * LCD OFF. * * @param pdev * * @return int */ static int mipi_d2l_lcd_off(struct platform_device *pdev) { int ret; struct msm_fb_data_type *mfd; pr_info("%s.\n", __func__); mfd = platform_get_drvdata(pdev); if (!mfd) return -ENODEV; if (mfd->key != MFD_KEY) return -EINVAL; ret = mipi_d2l_set_backlight_level(bl_pwm, 0); pr_info("%s.ret=%d.\n", __func__, ret); return ret; } static void mipi_d2l_set_backlight(struct msm_fb_data_type *mfd) { int level = mfd->bl_level; pr_debug("%s.lvl=%d.\n", __func__, level); mipi_d2l_set_backlight_level(bl_pwm, level); bl_level = level; } static struct msm_fb_panel_data d2l_panel_data = { .on = mipi_d2l_lcd_on, .off = mipi_d2l_lcd_off, .set_backlight = mipi_d2l_set_backlight, }; /** * Probe for device. * * Both the "target" and "panel" device use the same probe function. * "Target" device has id=0, "Panel" devic has non-zero id. * Target device should register first, passing msm_panel_common_pdata. * Panel device passing msm_panel_info. * * @param pdev * * @return int */ static int __devinit mipi_d2l_probe(struct platform_device *pdev) { int ret = 0; struct msm_panel_info *pinfo = NULL; pr_debug("%s.id=%d.\n", __func__, pdev->id); if (pdev->id == 0) { /* d2l_common_pdata = platform_get_drvdata(pdev); */ d2l_common_pdata = pdev->dev.platform_data; if (d2l_common_pdata == NULL) { pr_err("%s: no PWM gpio specified.\n", __func__); return 0; } led_pwm = d2l_common_pdata->gpio_num[0]; d2l_gpio_out_mask = d2l_common_pdata->gpio_num[1] >> 8; d2l_gpio_out_val = d2l_common_pdata->gpio_num[1] & 0xFF; mipi_dsi_buf_alloc(&d2l_tx_buf, DSI_BUF_SIZE); mipi_dsi_buf_alloc(&d2l_rx_buf, DSI_BUF_SIZE); return 0; } if (d2l_common_pdata == NULL) { pr_err("%s: d2l_common_pdata is NULL.\n", __func__); return -ENODEV; } bl_pwm = NULL; if (led_pwm >= 0) { bl_pwm = pwm_request(led_pwm, "lcd-backlight"); if (bl_pwm == NULL || IS_ERR(bl_pwm)) { pr_err("%s pwm_request() failed.id=%d.bl_pwm=%d.\n", __func__, led_pwm, (int) bl_pwm); bl_pwm = NULL; return -EIO; } else { pr_debug("%s.pwm_request() ok.pwm-id=%d.\n", __func__, led_pwm); } } else { pr_info("%s. led_pwm is invalid.\n", __func__); } /* pinfo = platform_get_drvdata(pdev); */ pinfo = pdev->dev.platform_data; if (pinfo == NULL) { pr_err("%s: pinfo is NULL.\n", __func__); return -ENODEV; } d2l_panel_data.panel_info = *pinfo; pdev->dev.platform_data = &d2l_panel_data; msm_fb_add_device(pdev); return ret; } /** * Device removal notification handler. * * @param pdev * * @return int */ static int __devexit mipi_d2l_remove(struct platform_device *pdev) { /* Note: There are no APIs to remove fb device and free DSI buf. */ pr_debug("%s.\n", __func__); if (bl_pwm) { pwm_free(bl_pwm); bl_pwm = NULL; } return 0; } /** * Register the panel device. * * @param pinfo * @param channel_id * @param panel_id * * @return int */ int mipi_tc358764_dsi2lvds_register(struct msm_panel_info *pinfo, u32 channel_id, u32 panel_id) { struct platform_device *pdev = NULL; int ret; /* Use DSI-to-LVDS bridge */ const char driver_name[] = "mipi_tc358764"; pr_debug("%s.\n", __func__); ret = mipi_d2l_init(); if (ret) { pr_err("mipi_d2l_init() failed with ret %u\n", ret); return ret; } /* Note: the device id should be non-zero */ pdev = platform_device_alloc(driver_name, (panel_id << 8)|channel_id); if (pdev == NULL) return -ENOMEM; pdev->dev.platform_data = pinfo; ret = platform_device_add(pdev); if (ret) { pr_err("%s: platform_device_register failed!\n", __func__); goto err_device_put; } return 0; err_device_put: platform_device_put(pdev); return ret; } static struct platform_driver d2l_driver = { .probe = mipi_d2l_probe, .remove = __devexit_p(mipi_d2l_remove), .driver = { .name = DRV_NAME, }, }; /** * Module Init * * @return int */ static int mipi_d2l_init(void) { pr_debug("%s.\n", __func__); return platform_driver_register(&d2l_driver); } MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Toshiba MIPI-DSI-to-LVDS bridge driver"); MODULE_AUTHOR("Amir Samuelov <amirs@codeaurora.org>");
sgs3/SGH-T999V_Kernel
drivers/video/msm/mipi_tc358764_dsi2lvds.c
C
gpl-2.0
24,068
<?php // see : http://wordpress.org/support/topic/plugin-nextgen-gallery-ngg-and-featured-image-issue?replies=14 /** * nggPostThumbnail - Class for adding the post thumbnail feature * * @package NextGEN Gallery * @author Alex Rabe * * @version 1.0.2 * @access internal */ class nggPostThumbnail { /** * PHP4 compatibility layer for calling the PHP5 constructor. * */ function nggPostThumbnail() { return $this->__construct(); } /** * Main constructor - Add filter and action hooks * */ function __construct() { add_filter( 'admin_post_thumbnail_html', array( $this, 'admin_post_thumbnail'), 10, 2 ); add_action( 'wp_ajax_ngg_set_post_thumbnail', array( $this, 'ajax_set_post_thumbnail') ); // Adding filter for the new post_thumbnail add_filter( 'post_thumbnail_html', array( $this, 'ngg_post_thumbnail'), 10, 5 ); return; } /** * Filter for the post meta box. look for a NGG image if the ID is "ngg-<imageID>" * * @param string $content * @return string html output */ function admin_post_thumbnail( $content, $post_id = null ) { if ($post_id == null) { global $post; if ( !is_object($post) ) return $content; $post_id = $post->ID; } $thumbnail_id = get_post_meta($post_id, '_thumbnail_id', true); // in the case it's a ngg image it return ngg-<imageID> if ( strpos($thumbnail_id, 'ngg-') === false) { global $wp_version; if (version_compare($wp_version, '3.5', '>=') && $thumbnail_id <= 0) { $iframe_src = get_upload_iframe_src('image'); $iframe_src = remove_query_arg('TB_iframe', $iframe_src); $iframe_src = add_query_arg('tab', 'nextgen', $iframe_src); $iframe_src = add_query_arg('chromeless', '1', $iframe_src); $iframe_src = add_query_arg('TB_iframe', '1', $iframe_src); $set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set NextGEN featured image' ) . '" href="' . nextgen_esc_url( $iframe_src ) . '" id="set-ngg-post-thumbnail" class="thickbox">%s</a></p>'; $content .= sprintf($set_thumbnail_link, esc_html__( 'Set NextGEN featured image' )); } return $content; } // cut off the 'ngg-' $thumbnail_id = substr( $thumbnail_id, 4); return $this->_wp_post_thumbnail_html( $thumbnail_id ); } /** * Filter for the post content * * @param string $html * @param int $post_id * @param int $post_thumbnail_id * @param string|array $size Optional. Image size. Defaults to 'thumbnail'. * @param string|array $attr Optional. Query string or array of attributes. * @return string html output */ function ngg_post_thumbnail( $html, $post_id, $post_thumbnail_id, $size = 'post-thumbnail', $attr = '' ) { global $post, $_wp_additional_image_sizes; // in the case it's a ngg image it return ngg-<imageID> if ( strpos($post_thumbnail_id, 'ngg-') === false) return $html; // cut off the 'ngg-' $post_thumbnail_id = substr( $post_thumbnail_id, 4); // get the options $ngg_options = nggGallery::get_option('ngg_options'); // get the image data $image = nggdb::find_image($post_thumbnail_id); if (!$image) return $html; $img_src = false; $class = 'wp-post-image ngg-image-' . $image->pid . ' '; if (is_array($size) || is_array($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes[$size])) { $class .= isset($attr['class']) ? esc_attr($attr['class']) : ''; if( is_array($size)){ //the parameters is given as an array rather than a predfined image $width = absint( $size[0] ); $height = absint( $size[1] ); if(isset($size[2]) && $size[2] === true) { $mode = 'crop'; } else if(isset($size[2])){ $mode = $size[2]; } else { $mode = ''; } } else { $width = absint( $_wp_additional_image_sizes[$size]['width'] ); $height = absint( $_wp_additional_image_sizes[$size]['height'] ); $mode = ($_wp_additional_image_sizes[$size]['crop']) ? 'crop' : ''; } // check fo cached picture if ( $post->post_status == 'publish' ) $img_src = $image->cached_singlepic_file( $width, $height, $mode ); // if we didn't use a cached image then we take the on-the-fly mode if ($img_src == false) $img_src = trailingslashit( home_url() ) . 'index.php?callback=image&amp;pid=' . $image->pid . '&amp;width=' . $width . '&amp;height=' . $height . '&amp;mode=crop'; } else { $img_src = $image->thumbURL; } $alttext = isset($attr['alt']) ? $attr['alt'] : $image->alttext; $titletext = isset($attr['title']) ? $attr['title'] : $image->title; $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alttext) . '" title="' . esc_attr($titletext) .'" class="'.$class.'" />'; return $html; } /** * nggPostThumbnail::ajax_set_post_thumbnail() * * @return void */ function ajax_set_post_thumbnail() { global $post_ID; // check for correct capability if ( !is_user_logged_in() ) die( '-1' ); // get the post id as global variable, otherwise the ajax_nonce failed later $post_ID = intval( $_POST['post_id'] ); if ( !current_user_can( 'edit_post', $post_ID ) ) die( '-1' ); $thumbnail_id = intval( $_POST['thumbnail_id'] ); // delete the image if ( $thumbnail_id == '-1' ) { delete_post_meta( $post_ID, '_thumbnail_id' ); die('0'); } if ($thumbnail_id != null) { $registry = C_Component_Registry::get_instance(); $imap = $registry->get_utility('I_Image_Mapper'); $storage = $registry->get_utility('I_Gallery_Storage'); $image = $imap->find($thumbnail_id); // for NGG we look for the image id if ($image) { $image_id = $thumbnail_id; $args = array( 'post_type' => 'attachment', 'meta_key' => '_ngg_image_id', 'meta_compare' => '==', 'meta_value' => $image_id ); $upload_dir = wp_upload_dir(); $basedir = $upload_dir['basedir']; $thumbs_dir = path_join($basedir, 'ngg_featured'); $gallery_abspath = $storage->get_gallery_abspath($image->galleryid); $image_abspath = $storage->get_full_abspath($image); $target_path = null; $posts = get_posts($args); $attachment_id = null; if ($posts != null) { $attachment_id = $posts[0]->ID; } else { $url = $storage->get_full_url($image); $target_relpath = null; $target_basename = basename($image_abspath); if (strpos($image_abspath, $gallery_abspath) === 0) { $target_relpath = substr($image_abspath, strlen($gallery_abspath)); } else if ($image->galleryid) { $target_relpath = path_join(strval($image->galleryid), $target_basename); } else { $target_relpath = $target_basename; } $target_relpath = trim($target_relpath, '\\/'); $target_path = path_join($thumbs_dir, $target_relpath); $max_count = 100; $count = 0; while (file_exists($target_path) && $count <= $max_count) { $count++; $pathinfo = pathinfo($target_path); $dirname = $pathinfo['dirname']; $filename = $pathinfo['filename']; $extension = $pathinfo['extension']; $rand = mt_rand(1, 9999); $basename = $filename . '_' . sprintf('%04d', $rand) . '.' . $extension; $target_path = path_join($dirname, $basename); } if (file_exists($target_path)) { // XXX handle very rare case in which $max_count wasn't enough? } $target_dir = dirname($target_path); wp_mkdir_p($target_dir); if (@copy($image_abspath, $target_path)) { $size = @getimagesize($target_path); $image_type = ($size) ? $size['mime'] : 'image/jpeg'; $title = sanitize_file_name($image->alttext); $caption = sanitize_file_name($image->description); $attachment = array( 'post_title' => $title, 'post_content' => $caption, 'post_status' => 'attachment', 'post_parent' => 0, 'post_mime_type' => $image_type, 'guid' => $url ); // Save the data $attachment_id = wp_insert_attachment($attachment, $target_path); if ($attachment_id) { wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $target_path)); update_post_meta($attachment_id, '_ngg_image_id', $image_id); } } } if ($attachment_id) { //$attachment = get_post($attachment_id); //$attachment_meta = wp_get_attachment_metadata($attachment_id); $attachment_file = get_attached_file($attachment_id); $target_path = $attachment_file; if (filemtime($image_abspath) > filemtime($target_path)) { if (@copy($image_abspath, $target_path)) { wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $target_path)); } } die(strval($attachment_id)); } } } die('0'); } /** * Output HTML for the post thumbnail meta-box. * * @see wp-admin\includes\post.php * @param int $thumbnail_id ID of the image used for thumbnail * @return string html output */ function _wp_post_thumbnail_html( $thumbnail_id = NULL ) { global $_wp_additional_image_sizes, $post_ID; $set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="' . nextgen_esc_url( get_upload_iframe_src('image') ) . '" id="set-post-thumbnail" class="thickbox">%s</a></p>'; $content = sprintf($set_thumbnail_link, esc_html__( 'Set featured image' )); $image = nggdb::find_image($thumbnail_id); $img_src = false; // get the options $ngg_options = nggGallery::get_option('ngg_options'); if ( $image ) { if ( is_array($_wp_additional_image_sizes) && isset($_wp_additional_image_sizes['post-thumbnail']) ){ // Use post thumbnail settings if defined $width = absint( $_wp_additional_image_sizes['post-thumbnail']['width'] ); $height = absint( $_wp_additional_image_sizes['post-thumbnail']['height'] ); $mode = $_wp_additional_image_sizes['post-thumbnail']['crop'] ? 'crop' : ''; // check fo cached picture $img_src = $image->cached_singlepic_file( $width, $height, $mode ); } // if we didn't use a cached image then we take the on-the-fly mode if ( $img_src == false ) $img_src = trailingslashit( home_url() ) . 'index.php?callback=image&amp;pid=' . $image->pid . '&amp;width=' . $width . '&amp;height=' . $height . '&amp;mode=crop'; $thumbnail_html = '<img width="266" src="'. $img_src . '" alt="'.$image->alttext.'" title="'.$image->alttext.'" />'; if ( !empty( $thumbnail_html ) ) { $ajax_nonce = wp_create_nonce( "set_post_thumbnail-$post_ID" ); $content = sprintf($set_thumbnail_link, $thumbnail_html); $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail" onclick="WPRemoveThumbnail(\'' . $ajax_nonce . '\');return false;">' . esc_html__( 'Remove featured image' ) . '</a></p>'; } } return $content; } } $nggPostThumbnail = new nggPostThumbnail();
rakeybulhasan/IAPP
wp-content/plugins/nextgen-gallery/products/photocrati_nextgen/modules/ngglegacy/lib/post-thumbnail.php
PHP
gpl-2.0
11,431
#!/bin/sh ./test_document `find $srcdir/test/testdata -name *.xml`
Bytewerk/uClinux-ipcam
user/wsc_upnp/libupnp-1.4.6/ixml/test/test_document.sh
Shell
gpl-2.0
69
<?php /** * @package AkeebaBackup * @copyright Copyright (c)2009-2014 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later * * @since 1.3 */ // Protect from unauthorized access defined('_JEXEC') or die(); /** * MVC View for Log * */ class AkeebaViewLog extends FOFViewHtml { public function onBrowse($tpl = null) { // Add live help AkeebaHelperIncludes::addHelp('log'); // Get a list of log names $model = $this->getModel(); $this->logs = $model->getLogList(); $tag = $model->getState('tag'); if(empty($tag)) $tag = null; $this->tag = $tag; // Get profile ID $profileid = AEPlatform::getInstance()->get_active_profile(); $this->profileid = $profileid; // Get profile name $pmodel = FOFModel::getAnInstance('Profiles', 'AkeebaModel'); $pmodel->setId($profileid); $profile_data = $pmodel->getItem(); $this->profilename = $profile_data->description; return true; } public function onIframe($tpl = null) { $model = $this->getModel(); $tag = $model->getState('tag'); if(empty($tag)) $tag = null; $this->tag = $tag; return true; } }
apachish/tariin
log/administrator/components/com_akeeba/views/log/view.html.php
PHP
gpl-2.0
1,128
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types"; export const definition: IconDefinition; export const faGrinHearts: IconDefinition; export const prefix: IconPrefix; export const iconName: IconName; export const width: number; export const height: number; export const ligatures: string[]; export const unicode: string; export const svgPathData: string;
cstrassburg/smarthome
modules/http/webif/gstatic/fontawesome/advanced-options/use-with-node-js/free-solid-svg-icons/faGrinHearts.d.ts
TypeScript
gpl-3.0
399
<?php class Avada_Helper { /** * Return the value of an echo. * example: Avada_Helper::get_echo( 'function' ); */ public static function get_echo( $function, $args = '' ) { // Early exit if function does not exist if ( ! function_exists( $function ) ) { return; } ob_start(); $function( $args ); $get_echo = ob_get_clean(); return $get_echo; } public static function slider_name( $name ) { $type = ''; switch( $name ) { case 'layer': $type = 'slider'; break; case 'flex': $type = 'wooslider'; break; case 'rev': $type = 'revslider'; break; case 'elastic': $type = 'elasticslider'; break; } return $type; } public static function get_slider_type( $post_id ) { return get_post_meta( $post_id, 'pyre_slider_type', true ); } } // Omit closing PHP tag to avoid "Headers already sent" issues.
Skyrant/escortmissions.net
wp-content/themes/pereira/includes/class-avada-helper.php
PHP
gpl-3.0
929
--------------------------------------------------------------------------------------------------- -- func: animatenpc -- desc: Changes the animation of the given npc. (For testing purposes.) --------------------------------------------------------------------------------------------------- require("scripts/globals/status"); cmdprops = { permission = 1, parameters = "ss" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!animatenpc {npcID} <animationID>"); end; function onTrigger(player, arg1, arg2) local targ; local animationId; if (arg2 == nil) then -- player did not provide npcId. Shift arguments by one. targ = player:getCursorTarget(); animationId = arg1; else -- player provided npcId and animationId. targ = GetNPCByID(tonumber(arg1)); animationId = arg2; end -- validate target if (targ == nil) then error(player,"You must either enter a valid npcID or target an NPC."); return; end if (not targ:isNPC()) then error(player,"Targeted entity is not an NPC."); return; end -- validate animationID if (animationId ~= nil) then animationId = tonumber(animationId) or dsp.anim[string.upper(animationId)]; end if (animationId == nil) then error(player,"Invalid animationID."); return; end local oldAnimation = targ:getAnimation(); targ:setAnimation( animationId ); player:PrintToPlayer(string.format("NPC ID: %i - %s | Old animation: %i | New animation: %i\n", targ:getID(), targ:getName(), oldAnimation, animationId)); end
zynjec/darkstar
scripts/commands/animatenpc.lua
Lua
gpl-3.0
1,668
using System.Collections.Generic; using Nancy.Metadata.Module; using Nancy.Swagger; using OmniSharp.Common; namespace OmniSharp.CurrentFileMembers.Metadata { public class CurrentFileMembersAsFlatMetadataModule : MetadataModule<SwaggerRouteData> { public CurrentFileMembersAsFlatMetadataModule() { Describe["CurrentFileMembersAsFlat"] = desc => desc.AsSwagger(builder => builder .ResourcePath("/currentfilemembersasflat") .BodyParam<CurrentFileMembersRequest>() .Response(200) .Model<IEnumerable<QuickFix>>()); } } }
alexrao/YouCompleteMe
third_party/ycmd/third_party/OmniSharpServer/OmniSharp/CurrentFileMembers/Metadata/CurrentFileMembersAsFlatMetadataModule.cs
C#
gpl-3.0
632
Proj4js.defs["EPSG:32666"] = "+proj=tmerc +lat_0=0 +lon_0=-87 +k=0.9996 +x_0=500000.001016002 +y_0=0 +ellps=WGS84 +datum=WGS84 +to_meter=0.3048006096012192 +no_defs";
MaxiReglisse/georchestra
mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG32666.js
JavaScript
gpl-3.0
166
# # Copyright (C) 2011 - 2015 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # class Oauth2ProviderController < ApplicationController protect_from_forgery :except => [:token, :destroy] before_filter :run_login_hooks, :only => [:token] skip_before_filter :require_reacceptance_of_terms def auth if params[:code] || params[:error] # hopefully the user never sees this, since it's an oob response and the # browser should be closed automatically. but we'll at least display # something basic. return render() end scopes = params.fetch(:scopes, '').split(',') provider = Canvas::Oauth::Provider.new(params[:client_id], params[:redirect_uri], scopes, params[:purpose]) return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key? return render(:status => 400, :json => { :message => "invalid redirect_uri" }) unless provider.has_valid_redirect? session[:oauth2] = provider.session_hash session[:oauth2][:state] = params[:state] if params.key?(:state) if @current_pseudonym && !params[:force_login] redirect_to Canvas::Oauth::Provider.confirmation_redirect(self, provider, @current_user) else redirect_to login_url(params.slice(:canvas_login, :pseudonym_session, :force_login, :authentication_provider)) end end def confirm if session[:oauth2] @provider = Canvas::Oauth::Provider.new(session[:oauth2][:client_id], session[:oauth2][:redirect_uri], session[:oauth2][:scopes], session[:oauth2][:purpose]) if mobile_device? js_env :GOOGLE_ANALYTICS_KEY => Setting.get('google_analytics_key', nil) render :layout => 'mobile_auth', :action => 'confirm_mobile' end else flash[:error] = t("Must submit new OAuth2 request") redirect_to login_url end end def accept redirect_params = Canvas::Oauth::Provider.final_redirect_params(session[:oauth2], @current_user, remember_access: params[:remember_access]) redirect_to Canvas::Oauth::Provider.final_redirect(self, redirect_params) end def deny redirect_to Canvas::Oauth::Provider.final_redirect(self, :error => "access_denied") end def token basic_user, basic_pass = ActionController::HttpAuthentication::Basic.user_name_and_password(request) if request.authorization client_id = params[:client_id].presence || basic_user secret = params[:client_secret].presence || basic_pass provider = Canvas::Oauth::Provider.new(client_id) return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key? return render(:status => 400, :json => { :message => "invalid client_secret" }) unless provider.is_authorized_by?(secret) token = provider.token_for(params[:code]) return render(:status => 400, :json => { :message => "invalid code" }) unless token.is_for_valid_code? token.create_access_token_if_needed(value_to_boolean(params[:replace_tokens])) Canvas::Oauth::Token.expire_code(params[:code]) render :json => token end def destroy logout_current_user if params[:expire_sessions] return render :json => { :message => "can't delete OAuth access token when not using an OAuth access token" }, :status => 400 unless @access_token @access_token.destroy render :json => {} end end
Rvor/canvas-lms
app/controllers/oauth2_provider_controller.rb
Ruby
agpl-3.0
3,946
/* * jQuery UI Effects Explode 1.8.7 * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Explode * * Depends: * jquery.effects.core.js */ (function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++)for(var f= 0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+ e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery);
ieb/Shahnama
static/jquery-ui/development-bundle/ui/minified/jquery.effects.explode.min.js
JavaScript
agpl-3.0
1,643
/** * Shopware 4.0 * Copyright © 2012 shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @package Login * @subpackage Model * @copyright Copyright (c) 2012, shopware AG (http://www.shopware.de) * @version $Id$ * @author shopware AG */ /** * Shopware Backend - ErrorReporter Main Model * * todo@all: Documentation */ Ext.define('Shopware.apps.UserManager.model.Locale', { extend: 'Ext.data.Model', fields: [ 'id', 'name' ] });
OliverZachau/shopware-4
templates/_default/backend/user_manager/model/locale.js
JavaScript
agpl-3.0
1,318
#ifndef IVE_MATERIAL #define IVE_MATERIAL 1 #include <osg/Material> #include "ReadWrite.h" namespace ive{ class Material : public osg::Material { public: void write(DataOutputStream* out); void read(DataInputStream* in); }; } #endif
artoolkit/osg
src/osgPlugins/ive/Material.h
C
lgpl-2.1
238
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Captcha * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /* @var $installer Mage_Core_Model_Resource_Setup */ $installer = $this; $installer->startSetup(); $table = $installer->getConnection() ->newTable($installer->getTable('captcha/log')) ->addColumn('type', Varien_Db_Ddl_Table::TYPE_TEXT, 32, array( 'nullable' => false, 'primary' => true, ), 'Type') ->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, 32, array( 'nullable' => false, 'unsigned' => true, 'primary' => true, ), 'Value') ->addColumn('count', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array( 'unsigned' => true, 'nullable' => false, 'default' => '0', ), 'Count') ->addColumn('updated_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(), 'Update Time') ->setComment('Count Login Attempts'); $installer->getConnection()->createTable($table); $installer->endSetup();
dbashyal/MagentoStarterBase
trunk/app/code/core/Mage/Captcha/sql/captcha_setup/install-1.7.0.0.0.php
PHP
lgpl-3.0
1,868
/**************************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/
an4967/TizenRT
external/include/libcxx/support/xlocale/xlocale.h
C
apache-2.0
776
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function try: import ConfigParser except ImportError: import configparser as ConfigParser import logging import mock import os import subprocess from helpers import unittest import warnings from luigi import six import luigi from luigi.mock import MockTarget class SomeTask(luigi.Task): n = luigi.IntParameter() def output(self): return MockTarget('/tmp/test_%d' % self.n) def run(self): f = self.output().open('w') f.write('done') f.close() class AmbiguousClass(luigi.Task): pass class AmbiguousClass(luigi.Task): pass class TaskWithSameName(luigi.Task): def run(self): self.x = 42 class TaskWithSameName(luigi.Task): # there should be no ambiguity def run(self): self.x = 43 class WriteToFile(luigi.Task): filename = luigi.Parameter() def output(self): return luigi.LocalTarget(self.filename) def run(self): f = self.output().open('w') print('foo', file=f) f.close() class FooBaseClass(luigi.Task): x = luigi.Parameter(default='foo_base_default') class FooSubClass(FooBaseClass): pass class CmdlineTest(unittest.TestCase): def setUp(self): MockTarget.fs.clear() @mock.patch("logging.getLogger") def test_cmdline_main_task_cls(self, logger): luigi.run(['--local-scheduler', '--no-lock', '--n', '100'], main_task_cls=SomeTask) self.assertEqual(dict(MockTarget.fs.get_all_data()), {'/tmp/test_100': b'done'}) @mock.patch("logging.getLogger") def test_cmdline_local_scheduler(self, logger): luigi.run(['SomeTask', '--no-lock', '--n', '101'], local_scheduler=True) self.assertEqual(dict(MockTarget.fs.get_all_data()), {'/tmp/test_101': b'done'}) @mock.patch("logging.getLogger") def test_cmdline_other_task(self, logger): luigi.run(['--local-scheduler', '--no-lock', 'SomeTask', '--n', '1000']) self.assertEqual(dict(MockTarget.fs.get_all_data()), {'/tmp/test_1000': b'done'}) @mock.patch("logging.getLogger") def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("logging.StreamHandler") def test_setup_interface_logging(self, handler, logger): handler.return_value = mock.Mock(name="stream_handler") with mock.patch("luigi.interface.setup_interface_logging.has_run", new=False): luigi.interface.setup_interface_logging() self.assertEqual([mock.call(handler.return_value)], logger.return_value.addHandler.call_args_list) with mock.patch("luigi.interface.setup_interface_logging.has_run", new=False): if six.PY2: error = ConfigParser.NoSectionError else: error = KeyError self.assertRaises(error, luigi.interface.setup_interface_logging, '/blah') @mock.patch("warnings.warn") @mock.patch("luigi.interface.setup_interface_logging") def test_cmdline_logger(self, setup_mock, warn): with mock.patch("luigi.interface.core") as env_params: env_params.return_value.logging_conf_file = None luigi.run(['SomeTask', '--n', '7', '--local-scheduler', '--no-lock']) self.assertEqual([mock.call(None)], setup_mock.call_args_list) with mock.patch("luigi.configuration.get_config") as getconf: getconf.return_value.get.side_effect = ConfigParser.NoOptionError(section='foo', option='bar') getconf.return_value.getint.return_value = 0 luigi.interface.setup_interface_logging.call_args_list = [] luigi.run(['SomeTask', '--n', '42', '--local-scheduler', '--no-lock']) self.assertEqual([], setup_mock.call_args_list) @mock.patch('argparse.ArgumentParser.print_usage') def test_non_existent_class(self, print_usage): self.assertRaises(luigi.task_register.TaskClassNotFoundException, luigi.run, ['--local-scheduler', '--no-lock', 'XYZ']) @mock.patch('argparse.ArgumentParser.print_usage') def test_no_task(self, print_usage): self.assertRaises(SystemExit, luigi.run, ['--local-scheduler', '--no-lock']) class InvokeOverCmdlineTest(unittest.TestCase): def _run_cmdline(self, args): env = os.environ.copy() env['PYTHONPATH'] = env.get('PYTHONPATH', '') + ':.:test' p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) stdout, stderr = p.communicate() # Unfortunately subprocess.check_output is 2.7+ return p.returncode, stdout, stderr def test_bin_luigi(self): t = luigi.LocalTarget(is_tmp=True) args = ['./bin/luigi', '--module', 'cmdline_test', 'WriteToFile', '--filename', t.path, '--local-scheduler', '--no-lock'] self._run_cmdline(args) self.assertTrue(t.exists()) def test_direct_python(self): t = luigi.LocalTarget(is_tmp=True) args = ['python', 'test/cmdline_test.py', 'WriteToFile', '--filename', t.path, '--local-scheduler', '--no-lock'] self._run_cmdline(args) self.assertTrue(t.exists()) def test_direct_python_help(self): returncode, stdout, stderr = self._run_cmdline(['python', 'test/cmdline_test.py', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertFalse(stdout.find(b'--x') != -1) def test_direct_python_help_class(self): returncode, stdout, stderr = self._run_cmdline(['python', 'test/cmdline_test.py', 'FooBaseClass', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertTrue(stdout.find(b'--x') != -1) def test_bin_luigi_help(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--module', 'cmdline_test', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertFalse(stdout.find(b'--x') != -1) def test_bin_luigi_help_no_module(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--help']) self.assertTrue(stdout.find(b'usage:') != -1) def test_bin_luigi_no_parameters(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi']) self.assertTrue(stderr.find(b'No task specified') != -1) def test_bin_luigi_help_class(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--module', 'cmdline_test', 'FooBaseClass', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertTrue(stdout.find(b'--x') != -1) class NewStyleParameters822Test(unittest.TestCase): # See https://github.com/spotify/luigi/issues/822 def test_subclasses(self): ap = luigi.interface.ArgParseInterface() task, = ap.parse(['--local-scheduler', '--no-lock', 'FooSubClass', '--x', 'xyz', '--FooBaseClass-x', 'xyz']) self.assertEquals(task.x, 'xyz') # This won't work because --FooSubClass-x doesn't exist self.assertRaises(BaseException, ap.parse, (['--local-scheduler', '--no-lock', 'FooBaseClass', '--x', 'xyz', '--FooSubClass-x', 'xyz'])) def test_subclasses_2(self): ap = luigi.interface.ArgParseInterface() # https://github.com/spotify/luigi/issues/822#issuecomment-77782714 task, = ap.parse(['--local-scheduler', '--no-lock', 'FooBaseClass', '--FooBaseClass-x', 'xyz']) self.assertEquals(task.x, 'xyz') if __name__ == '__main__': # Needed for one of the tests luigi.run()
percyfal/luigi
test/cmdline_test.py
Python
apache-2.0
8,267
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.operators.hash; import org.apache.flink.api.common.typeutils.GenericPairComparator; import org.apache.flink.api.common.typeutils.TypeComparator; import org.apache.flink.api.common.typeutils.TypePairComparator; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.common.typeutils.base.ByteValueSerializer; import org.apache.flink.api.common.typeutils.base.LongComparator; import org.apache.flink.api.common.typeutils.base.LongSerializer; import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArrayComparator; import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.runtime.TupleComparator; import org.apache.flink.api.java.typeutils.runtime.TupleSerializer; import org.apache.flink.api.java.typeutils.runtime.ValueComparator; import org.apache.flink.core.memory.MemorySegment; import org.apache.flink.core.memory.MemorySegmentFactory; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync; import org.apache.flink.types.ByteValue; import org.apache.flink.util.MutableObjectIterator; import org.junit.Test; import org.junit.Assert; import org.mockito.Mockito; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class HashTableTest { private final TypeSerializer<Tuple2<Long, byte[]>> buildSerializer; private final TypeSerializer<Long> probeSerializer; private final TypeComparator<Tuple2<Long, byte[]>> buildComparator; private final TypeComparator<Long> probeComparator; private final TypePairComparator<Long, Tuple2<Long, byte[]>> pairComparator; public HashTableTest() { TypeSerializer<?>[] fieldSerializers = { LongSerializer.INSTANCE, BytePrimitiveArraySerializer.INSTANCE }; @SuppressWarnings("unchecked") Class<Tuple2<Long, byte[]>> clazz = (Class<Tuple2<Long, byte[]>>) (Class<?>) Tuple2.class; this.buildSerializer = new TupleSerializer<Tuple2<Long, byte[]>>(clazz, fieldSerializers); this.probeSerializer = LongSerializer.INSTANCE; TypeComparator<?>[] comparators = { new LongComparator(true) }; TypeSerializer<?>[] comparatorSerializers = { LongSerializer.INSTANCE }; this.buildComparator = new TupleComparator<Tuple2<Long, byte[]>>(new int[] {0}, comparators, comparatorSerializers); this.probeComparator = new LongComparator(true); this.pairComparator = new TypePairComparator<Long, Tuple2<Long, byte[]>>() { private long ref; @Override public void setReference(Long reference) { ref = reference; } @Override public boolean equalToReference(Tuple2<Long, byte[]> candidate) { //noinspection UnnecessaryUnboxing return candidate.f0.longValue() == ref; } @Override public int compareToReference(Tuple2<Long, byte[]> candidate) { long x = ref; long y = candidate.f0; return (x < y) ? -1 : ((x == y) ? 0 : 1); } }; } // ------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------ /** * This tests a combination of values that lead to a corner case situation where memory * was missing and the computation deadlocked. */ @Test public void testBufferMissingForProbing() { final IOManager ioMan = new IOManagerAsync(); try { final int pageSize = 32*1024; final int numSegments = 34; final int numRecords = 3400; final int recordLen = 270; final byte[] payload = new byte[recordLen - 8 - 4]; List<MemorySegment> memory = getMemory(numSegments, pageSize); MutableHashTable<Tuple2<Long, byte[]>, Long> table = new MutableHashTable<>( buildSerializer, probeSerializer, buildComparator, probeComparator, pairComparator, memory, ioMan, 16, false); table.open(new TupleBytesIterator(payload, numRecords), new LongIterator(10000)); try { while (table.nextRecord()) { MutableObjectIterator<Tuple2<Long, byte[]>> matches = table.getBuildSideIterator(); while (matches.next() != null); } } catch (RuntimeException e) { if (!e.getMessage().contains("exceeded maximum number of recursions")) { e.printStackTrace(); fail("Test failed with unexpected exception"); } } finally { table.close(); } checkNoTempFilesRemain(ioMan); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { ioMan.shutdown(); } } /** * This tests the case where no additional partition buffers are used at the point when spilling * is triggered, testing that overflow bucket buffers are taken into account when deciding which * partition to spill. */ @Test public void testSpillingFreesOnlyOverflowSegments() { final IOManager ioMan = new IOManagerAsync(); final TypeSerializer<ByteValue> serializer = ByteValueSerializer.INSTANCE; final TypeComparator<ByteValue> buildComparator = new ValueComparator<>(true, ByteValue.class); final TypeComparator<ByteValue> probeComparator = new ValueComparator<>(true, ByteValue.class); @SuppressWarnings("unchecked") final TypePairComparator<ByteValue, ByteValue> pairComparator = Mockito.mock(TypePairComparator.class); try { final int pageSize = 32*1024; final int numSegments = 34; List<MemorySegment> memory = getMemory(numSegments, pageSize); MutableHashTable<ByteValue, ByteValue> table = new MutableHashTable<>( serializer, serializer, buildComparator, probeComparator, pairComparator, memory, ioMan, 1, false); table.open(new ByteValueIterator(100000000), new ByteValueIterator(1)); table.close(); checkNoTempFilesRemain(ioMan); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { ioMan.shutdown(); } } /** * Tests that the MutableHashTable spills its partitions when creating the initial table * without overflow segments in the partitions. This means that the records are large. */ @Test public void testSpillingWhenBuildingTableWithoutOverflow() throws Exception { final IOManager ioMan = new IOManagerAsync(); final TypeSerializer<byte[]> serializer = BytePrimitiveArraySerializer.INSTANCE; final TypeComparator<byte[]> buildComparator = new BytePrimitiveArrayComparator(true); final TypeComparator<byte[]> probeComparator = new BytePrimitiveArrayComparator(true); @SuppressWarnings("unchecked") final TypePairComparator<byte[], byte[]> pairComparator = new GenericPairComparator<>( new BytePrimitiveArrayComparator(true), new BytePrimitiveArrayComparator(true)); final int pageSize = 128; final int numSegments = 33; List<MemorySegment> memory = getMemory(numSegments, pageSize); MutableHashTable<byte[], byte[]> table = new MutableHashTable<byte[], byte[]>( serializer, serializer, buildComparator, probeComparator, pairComparator, memory, ioMan, 1, false); int numElements = 9; table.open( new CombiningIterator<byte[]>( new ByteArrayIterator(numElements, 128,(byte) 0), new ByteArrayIterator(numElements, 128,(byte) 1)), new CombiningIterator<byte[]>( new ByteArrayIterator(1, 128,(byte) 0), new ByteArrayIterator(1, 128,(byte) 1))); while(table.nextRecord()) { MutableObjectIterator<byte[]> iterator = table.getBuildSideIterator(); int counter = 0; while(iterator.next() != null) { counter++; } // check that we retrieve all our elements Assert.assertEquals(numElements, counter); } table.close(); } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ private static List<MemorySegment> getMemory(int numSegments, int segmentSize) { ArrayList<MemorySegment> list = new ArrayList<MemorySegment>(numSegments); for (int i = 0; i < numSegments; i++) { list.add(MemorySegmentFactory.allocateUnpooledSegment(segmentSize)); } return list; } private static void checkNoTempFilesRemain(IOManager ioManager) { for (File dir : ioManager.getSpillingDirectories()) { for (String file : dir.list()) { if (file != null && !(file.equals(".") || file.equals(".."))) { fail("hash table did not clean up temp files. remaining file: " + file); } } } } private static class TupleBytesIterator implements MutableObjectIterator<Tuple2<Long, byte[]>> { private final byte[] payload; private final int numRecords; private int count = 0; TupleBytesIterator(byte[] payload, int numRecords) { this.payload = payload; this.numRecords = numRecords; } @Override public Tuple2<Long, byte[]> next(Tuple2<Long, byte[]> reuse) { return next(); } @Override public Tuple2<Long, byte[]> next() { if (count++ < numRecords) { return new Tuple2<>(42L, payload); } else { return null; } } } private static class ByteArrayIterator implements MutableObjectIterator<byte[]> { private final long numRecords; private long counter = 0; private final byte[] arrayValue; ByteArrayIterator(long numRecords, int length, byte value) { this.numRecords = numRecords; arrayValue = new byte[length]; Arrays.fill(arrayValue, value); } @Override public byte[] next(byte[] array) { return next(); } @Override public byte[] next() { if (counter++ < numRecords) { return arrayValue; } else { return null; } } } private static class LongIterator implements MutableObjectIterator<Long> { private final long numRecords; private long value = 0; LongIterator(long numRecords) { this.numRecords = numRecords; } @Override public Long next(Long aLong) { return next(); } @Override public Long next() { if (value < numRecords) { return value++; } else { return null; } } } private static class ByteValueIterator implements MutableObjectIterator<ByteValue> { private final long numRecords; private long value = 0; ByteValueIterator(long numRecords) { this.numRecords = numRecords; } @Override public ByteValue next(ByteValue aLong) { return next(); } @Override public ByteValue next() { if (value++ < numRecords) { return new ByteValue((byte) 0); } else { return null; } } } private static class CombiningIterator<T> implements MutableObjectIterator<T> { private final MutableObjectIterator<T> left; private final MutableObjectIterator<T> right; public CombiningIterator(MutableObjectIterator<T> left, MutableObjectIterator<T> right) { this.left = left; this.right = right; } @Override public T next(T reuse) throws IOException { T value = left.next(reuse); if (value == null) { return right.next(reuse); } else { return value; } } @Override public T next() throws IOException { T value = left.next(); if (value == null) { return right.next(); } else { return value; } } } }
hongyuhong/flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/hash/HashTableTest.java
Java
apache-2.0
12,009
package com.avast.android.dialogs.core; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; /** * Internal base builder that holds common values for all dialog fragment builders. * * @author Tomas Vondracek */ public abstract class BaseDialogBuilder<T extends BaseDialogBuilder<T>> { public final static String ARG_REQUEST_CODE = "request_code"; public final static String ARG_CANCELABLE_ON_TOUCH_OUTSIDE = "cancelable_oto"; public final static String DEFAULT_TAG = "simple_dialog"; private String mTag = DEFAULT_TAG; public final static int DEFAULT_REQUEST_CODE = -42; private int mRequestCode = DEFAULT_REQUEST_CODE; public static String ARG_USE_DARK_THEME = "usedarktheme"; public static String ARG_USE_LIGHT_THEME = "uselighttheme"; protected final Context mContext; protected final FragmentManager mFragmentManager; protected final Class<? extends BaseDialogFragment> mClass; private Fragment mTargetFragment; private boolean mCancelable = true; private boolean mCancelableOnTouchOutside = true; private boolean mUseDarkTheme = false; private boolean mUseLightTheme = false; public BaseDialogBuilder(Context context, FragmentManager fragmentManager, Class<? extends BaseDialogFragment> clazz) { mFragmentManager = fragmentManager; mContext = context.getApplicationContext(); mClass = clazz; } protected abstract T self(); protected abstract Bundle prepareArguments(); public T setCancelable(boolean cancelable) { mCancelable = cancelable; return self(); } public T setCancelableOnTouchOutside(boolean cancelable) { mCancelableOnTouchOutside = cancelable; if (cancelable) { mCancelable = cancelable; } return self(); } public T setTargetFragment(Fragment fragment, int requestCode) { mTargetFragment = fragment; mRequestCode = requestCode; return self(); } public T setRequestCode(int requestCode) { mRequestCode = requestCode; return self(); } public T setTag(String tag) { mTag = tag; return self(); } public T useDarkTheme() { mUseDarkTheme = true; return self(); } public T useLightTheme() { mUseLightTheme = true; return self(); } private BaseDialogFragment create() { final Bundle args = prepareArguments(); final BaseDialogFragment fragment = (BaseDialogFragment) Fragment.instantiate(mContext, mClass.getName(), args); args.putBoolean(ARG_CANCELABLE_ON_TOUCH_OUTSIDE, mCancelableOnTouchOutside); args.putBoolean(ARG_USE_DARK_THEME, mUseDarkTheme); args.putBoolean(ARG_USE_LIGHT_THEME, mUseLightTheme); if (mTargetFragment != null) { fragment.setTargetFragment(mTargetFragment, mRequestCode); } else { args.putInt(ARG_REQUEST_CODE, mRequestCode); } fragment.setCancelable(mCancelable); return fragment; } public DialogFragment show() { BaseDialogFragment fragment = create(); fragment.show(mFragmentManager, mTag); return fragment; } /** * Like show() but allows the commit to be executed after an activity's state is saved. This * is dangerous because the commit can be lost if the activity needs to later be restored from * its state, so this should only be used for cases where it is okay for the UI state to change * unexpectedly on the user. */ public DialogFragment showAllowingStateLoss() { BaseDialogFragment fragment = create(); fragment.showAllowingStateLoss(mFragmentManager, mTag); return fragment; } }
jaohoang/android-styled-dialogs
library/src/main/java/com/avast/android/dialogs/core/BaseDialogBuilder.java
Java
apache-2.0
3,904
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kafka.javaapi import kafka.common.TopicAndPartition class OffsetResponse(private val underlying: kafka.api.OffsetResponse) { def hasError = underlying.hasError def error(topic: String, partition: Int) = underlying.partitionErrorAndOffsets(TopicAndPartition(topic, partition)).error def errorCode(topic: String, partition: Int) = error(topic, partition).code def offsets(topic: String, partition: Int) = underlying.partitionErrorAndOffsets(TopicAndPartition(topic, partition)).offsets.toArray override def equals(obj: Any): Boolean = { obj match { case null => false case other: OffsetResponse => this.underlying.equals(other.underlying) case _ => false } } override def hashCode = underlying.hashCode override def toString = underlying.toString }
wangcy6/storm_app
frame/kafka-0.11.0/kafka-0.11.0.1-src/core/src/main/scala/kafka/javaapi/OffsetResponse.scala
Scala
apache-2.0
1,617
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.graph; import com.google.common.base.Preconditions; public class DefaultDirectedAcyclicGraph<T> extends DefaultTraversableGraph<T> implements DirectedAcyclicGraph<T> { public DefaultDirectedAcyclicGraph(MutableDirectedGraph<T> graph) { super(graph); Preconditions.checkArgument(super.isAcyclic()); } }
janicduplessis/buck
src/com/facebook/buck/graph/DefaultDirectedAcyclicGraph.java
Java
apache-2.0
954
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * 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 */ package proguard.gui.splash; import java.awt.*; /** * This interface describes objects that can paint themselves, possibly varying * as a function of time. * * @author Eric Lafortune */ public interface Sprite { /** * Paints the object. * * @param graphics the Graphics to paint on. * @param time the time since the start of the animation, expressed in * milliseconds. */ public void paint(Graphics graphics, long time); }
damienmg/bazel
third_party/java/proguard/proguard5.3.3/src/proguard/gui/splash/Sprite.java
Java
apache-2.0
1,374
/**************************************************************************** Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) Microsoft Open Technologies, Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ #ifndef __EXPORT_COMMON__ #define __EXPORT_COMMON__ #if defined(SHP) #include <FBaseConfig.h> #define EXPORT_DLL _EXPORT_ #elif defined(_WIN32) || defined(_WINRT) || defined(_WP8) #if defined(_EXPORT_DLL_) #define EXPORT_DLL __declspec(dllexport) #elif defined(IGNORE_EXPORT) #define EXPORT_DLL #else /* use a DLL library */ #define EXPORT_DLL __declspec(dllimport) #endif #else #if defined(_SHARED_) #define EXPORT_DLL __attribute__((visibility("default"))) #elif defined(IGNORE_EXPORT) #define EXPORT_DLL #else #define EXPORT_DLL #endif #endif #endif // end of __EXPORT_COMMON__
zjfandroid/TurboSnail
jni/CocosDenshion/include/Export.h
C
apache-2.0
1,965
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine { internal sealed class Vbc : VisualBasicCompiler { internal Vbc(string responseFile, BuildPaths buildPaths, string[] args, IAnalyzerAssemblyLoader analyzerLoader) : base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths.ClientDirectory, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, Environment.GetEnvironmentVariable("LIB"), analyzerLoader) { } internal static int Run(string[] args, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader) { FatalError.Handler = FailFast.OnFatalException; var responseFile = Path.Combine(buildPaths.ClientDirectory, VisualBasicCompiler.ResponseFileName); var compiler = new Vbc(responseFile, buildPaths, args, analyzerLoader); return ConsoleUtil.RunWithUtf8Output(compiler.Arguments.Utf8Output, textWriter, tw => compiler.Run(tw)); } protected override uint GetSqmAppID() { return SqmServiceProvider.CSHARP_APPID; } protected override void CompilerSpecificSqm(IVsSqmMulti sqm, uint sqmSession) { sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_COMPILERTYPE, (uint)SqmServiceProvider.CompilerType.Compiler); sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_LANGUAGEVERSION, (uint)Arguments.ParseOptions.LanguageVersion); sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNINGLEVEL, (uint)Arguments.CompilationOptions.WarningLevel); //Project complexity # of source files, # of references sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_SOURCES, (uint)Arguments.SourceFiles.Count()); sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_REFERENCES, (uint)Arguments.ReferencePaths.Count()); } } }
ericfe-ms/roslyn
src/Compilers/Shared/Vbc.cs
C#
apache-2.0
2,289
class Tinyumbrella < Cask version '7.04' sha256 '2ce5ea70bbdf216aaff9fc30c1a33a58a6fc19a5ad5e4f0029aafae61c622db1' url 'http://cache.firmwareumbrella.com/downloads/TinyUmbrella-7.04.00.app.zip' homepage 'http://blog.firmwareumbrella.com/' link 'TinyUmbrella.app' end
flesch/homebrew-cask
Casks/tinyumbrella.rb
Ruby
bsd-2-clause
279
W3C CSS Test Suite Repository ----------------------------- This repository contains top level directories for all of CSS specs for which we currently have tests. Place tests in the appropriate directory based on the first rel="help" link in the test. If you are writing tests for a spec and it doesn't yet have a directory here, feel free to create it. There are a few directories that do not map to specifications: support/ contains common image files to which many of the tests link in this location tools/ is random scripts that may be useful when administering tests. vendor-imports/ is where third parties may import their tests that originate and are maintained in an external repo. Files in this directory should never be modified in this repo, but should go through the vendor's process to be imported here. work-in-progress/ is a legacy directory that contains all the work that was once submitted to the repo, but was not yet ready for review. Since the CSSWG has adopted the GitHub pull request process, no new files should be landed here. The subdirectories here are named by test author or contributing organization. Linking Your Tests to Specifications ----------------------------------- In addition to placing your tests in the appropriate directory in this repository, you must also include at least one specification link in the test metadata, following [these guidelines][speclinks]. For CSS tests, you must also be sure you’re linking to a specific level of the spec, generally the first level where the feature being tested is defined. Where possible, it’s preferable to link to the official version of the spec, which will start with http://www.w3.org/TR/. This can usually be found as the ‘Latest version’ link in the spec itself and will include the level of the spec in the URL. For example, the proper link to level 1 of the CSS Flexbox spec is: http://www.w3.org/TR/css-flexbox-1/#RELEVANT_SECTION When testing features not yet available in an official draft, link to the appropriate Editor’s Draft found at http://dev.w3.org/csswg/. Be sure to include the level of the specification in the link. For example, the proper link to the CSS Flexbox Level 1 Editor’s Draft is: http://dev.w3.org/csswg/css-flexbox-1/#RELEVANT_SECTION Contributing ------------- Absolutely everyone is welcome (and even encouraged) to contribute to test development, so long as you fulfill the contribution requirements detailed in the [Contributing Guidelines][contributing]. No test is too small or too simple, especially if it corresponds to something for which you've noted an interoperability bug in a browser. Write Access ------------ This section only applies if you have cloned the repository from Mercurial. If you've cloned it from GitHub, which is a mirror of the canonical Mercurial repo, you can submit your tests via a [pull request][github101]. To gain write access to this Mercurial repository, sign up for an account on the CSS Test Suite Manager (aka Shepherd) at: https://test.csswg.org/shepherd/register and then submit a request on the Repository Access page at: https://test.csswg.org/shepherd/account/access/ You will be notified by email when your request is processed. Please note that although we will grant write access directly to the Mercurial repo, it is strongly advised to use GitHub for test submissions to enable reviewers to use its built-in review tools. Direct submissions to Mercurial should be limited to administrative or housekeeping tasks, very minor changes that don't require a review, or from advanced users of the system. [contributing]: https://github.com/rhauck/csswg-test/blob/master/CONTRIBUTING.md [github101]: http://testthewebforward.org/docs/github-101.html [speclinks]: http://testthewebforward.org/docs/test-templates.html#specification-links
modulexcite/blink
LayoutTests/imported/csswg-test/README.md
Markdown
bsd-3-clause
3,837
//===-- RuntimeDyldCOFF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Implementation of COFF support for the MC-JIT runtime dynamic linker. // //===----------------------------------------------------------------------===// #include "RuntimeDyldCOFF.h" #include "Targets/RuntimeDyldCOFFAArch64.h" #include "Targets/RuntimeDyldCOFFI386.h" #include "Targets/RuntimeDyldCOFFThumb.h" #include "Targets/RuntimeDyldCOFFX86_64.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Triple.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/FormatVariadic.h" using namespace llvm; using namespace llvm::object; #define DEBUG_TYPE "dyld" namespace { class LoadedCOFFObjectInfo final : public LoadedObjectInfoHelper<LoadedCOFFObjectInfo, RuntimeDyld::LoadedObjectInfo> { public: LoadedCOFFObjectInfo( RuntimeDyldImpl &RTDyld, RuntimeDyld::LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap) : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {} OwningBinary<ObjectFile> getObjectForDebug(const ObjectFile &Obj) const override { return OwningBinary<ObjectFile>(); } }; } namespace llvm { std::unique_ptr<RuntimeDyldCOFF> llvm::RuntimeDyldCOFF::create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver) { switch (Arch) { default: llvm_unreachable("Unsupported target for RuntimeDyldCOFF."); case Triple::x86: return std::make_unique<RuntimeDyldCOFFI386>(MemMgr, Resolver); case Triple::thumb: return std::make_unique<RuntimeDyldCOFFThumb>(MemMgr, Resolver); case Triple::x86_64: return std::make_unique<RuntimeDyldCOFFX86_64>(MemMgr, Resolver); case Triple::aarch64: return std::make_unique<RuntimeDyldCOFFAArch64>(MemMgr, Resolver); } } std::unique_ptr<RuntimeDyld::LoadedObjectInfo> RuntimeDyldCOFF::loadObject(const object::ObjectFile &O) { if (auto ObjSectionToIDOrErr = loadObjectImpl(O)) { return std::make_unique<LoadedCOFFObjectInfo>(*this, *ObjSectionToIDOrErr); } else { HasError = true; raw_string_ostream ErrStream(ErrorStr); logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream); return nullptr; } } uint64_t RuntimeDyldCOFF::getSymbolOffset(const SymbolRef &Sym) { // The value in a relocatable COFF object is the offset. return cantFail(Sym.getValue()); } uint64_t RuntimeDyldCOFF::getDLLImportOffset(unsigned SectionID, StubMap &Stubs, StringRef Name, bool SetSectionIDMinus1) { LLVM_DEBUG(dbgs() << "Getting DLLImport entry for " << Name << "... "); assert(Name.startswith(getImportSymbolPrefix()) && "Not a DLLImport symbol?"); RelocationValueRef Reloc; Reloc.SymbolName = Name.data(); auto I = Stubs.find(Reloc); if (I != Stubs.end()) { LLVM_DEBUG(dbgs() << format("{0:x8}", I->second) << "\n"); return I->second; } assert(SectionID < Sections.size() && "SectionID out of range"); auto &Sec = Sections[SectionID]; auto EntryOffset = alignTo(Sec.getStubOffset(), PointerSize); Sec.advanceStubOffset(EntryOffset + PointerSize - Sec.getStubOffset()); Stubs[Reloc] = EntryOffset; RelocationEntry RE(SectionID, EntryOffset, PointerReloc, 0, false, Log2_64(PointerSize)); // Hack to tell I386/Thumb resolveRelocation that this isn't section relative. if (SetSectionIDMinus1) RE.Sections.SectionA = -1; addRelocationForSymbol(RE, Name.drop_front(getImportSymbolPrefix().size())); LLVM_DEBUG({ dbgs() << "Creating entry at " << formatv("{0:x16} + {1:x8} ( {2:x16} )", Sec.getLoadAddress(), EntryOffset, Sec.getLoadAddress() + EntryOffset) << "\n"; }); return EntryOffset; } bool RuntimeDyldCOFF::isCompatibleFile(const object::ObjectFile &Obj) const { return Obj.isCOFF(); } } // namespace llvm
endlessm/chromium-browser
third_party/llvm/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldCOFF.cpp
C++
bsd-3-clause
4,282
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "sync/api/attachments/attachment_metadata.h" namespace syncer { AttachmentMetadata::AttachmentMetadata(const AttachmentId& id, size_t size) : id_(id), size_(size) { } AttachmentMetadata::~AttachmentMetadata() { } const AttachmentId& AttachmentMetadata::GetId() const { return id_; } size_t AttachmentMetadata::GetSize() const { return size_; } } // namespace syncer
js0701/chromium-crosswalk
sync/api/attachments/attachment_metadata.cc
C++
bsd-3-clause
577
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/browser/fileapi/obfuscated_file_util.h" #include <queue> #include <string> #include <vector> #include "base/file_util.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "url/gurl.h" #include "webkit/browser/fileapi/file_observers.h" #include "webkit/browser/fileapi/file_system_context.h" #include "webkit/browser/fileapi/file_system_operation_context.h" #include "webkit/browser/fileapi/file_system_url.h" #include "webkit/browser/fileapi/native_file_util.h" #include "webkit/browser/fileapi/sandbox_file_system_backend.h" #include "webkit/browser/fileapi/sandbox_isolated_origin_database.h" #include "webkit/browser/fileapi/sandbox_origin_database.h" #include "webkit/browser/fileapi/sandbox_prioritized_origin_database.h" #include "webkit/browser/fileapi/timed_task_helper.h" #include "webkit/browser/quota/quota_manager.h" #include "webkit/common/database/database_identifier.h" #include "webkit/common/fileapi/file_system_util.h" // Example of various paths: // void ObfuscatedFileUtil::DoSomething(const FileSystemURL& url) { // base::FilePath virtual_path = url.path(); // base::FilePath local_path = GetLocalFilePath(url); // // NativeFileUtil::DoSomething(local_path); // file_util::DoAnother(local_path); // } namespace fileapi { namespace { typedef SandboxDirectoryDatabase::FileId FileId; typedef SandboxDirectoryDatabase::FileInfo FileInfo; void InitFileInfo( SandboxDirectoryDatabase::FileInfo* file_info, SandboxDirectoryDatabase::FileId parent_id, const base::FilePath::StringType& file_name) { DCHECK(file_info); file_info->parent_id = parent_id; file_info->name = file_name; } // Costs computed as per crbug.com/86114, based on the LevelDB implementation of // path storage under Linux. It's not clear if that will differ on Windows, on // which base::FilePath uses wide chars [since they're converted to UTF-8 for // storage anyway], but as long as the cost is high enough that one can't cheat // on quota by storing data in paths, it doesn't need to be all that accurate. const int64 kPathCreationQuotaCost = 146; // Bytes per inode, basically. const int64 kPathByteQuotaCost = 2; // Bytes per byte of path length in UTF-8. int64 UsageForPath(size_t length) { return kPathCreationQuotaCost + static_cast<int64>(length) * kPathByteQuotaCost; } bool AllocateQuota(FileSystemOperationContext* context, int64 growth) { if (context->allowed_bytes_growth() == quota::QuotaManager::kNoLimit) return true; int64 new_quota = context->allowed_bytes_growth() - growth; if (growth > 0 && new_quota < 0) return false; context->set_allowed_bytes_growth(new_quota); return true; } void UpdateUsage( FileSystemOperationContext* context, const FileSystemURL& url, int64 growth) { context->update_observers()->Notify( &FileUpdateObserver::OnUpdate, MakeTuple(url, growth)); } void TouchDirectory(SandboxDirectoryDatabase* db, FileId dir_id) { DCHECK(db); if (!db->UpdateModificationTime(dir_id, base::Time::Now())) NOTREACHED(); } enum IsolatedOriginStatus { kIsolatedOriginMatch, kIsolatedOriginDontMatch, kIsolatedOriginStatusMax, }; } // namespace class ObfuscatedFileEnumerator : public FileSystemFileUtil::AbstractFileEnumerator { public: ObfuscatedFileEnumerator( SandboxDirectoryDatabase* db, FileSystemOperationContext* context, ObfuscatedFileUtil* obfuscated_file_util, const FileSystemURL& root_url, bool recursive) : db_(db), context_(context), obfuscated_file_util_(obfuscated_file_util), root_url_(root_url), recursive_(recursive), current_file_id_(0) { base::FilePath root_virtual_path = root_url.path(); FileId file_id; if (!db_->GetFileWithPath(root_virtual_path, &file_id)) return; FileRecord record = { file_id, root_virtual_path }; recurse_queue_.push(record); } virtual ~ObfuscatedFileEnumerator() {} virtual base::FilePath Next() OVERRIDE { ProcessRecurseQueue(); if (display_stack_.empty()) return base::FilePath(); current_file_id_ = display_stack_.back(); display_stack_.pop_back(); FileInfo file_info; base::FilePath platform_file_path; base::File::Error error = obfuscated_file_util_->GetFileInfoInternal( db_, context_, root_url_, current_file_id_, &file_info, &current_platform_file_info_, &platform_file_path); if (error != base::File::FILE_OK) return Next(); base::FilePath virtual_path = current_parent_virtual_path_.Append(file_info.name); if (recursive_ && file_info.is_directory()) { FileRecord record = { current_file_id_, virtual_path }; recurse_queue_.push(record); } return virtual_path; } virtual int64 Size() OVERRIDE { return current_platform_file_info_.size; } virtual base::Time LastModifiedTime() OVERRIDE { return current_platform_file_info_.last_modified; } virtual bool IsDirectory() OVERRIDE { return current_platform_file_info_.is_directory; } private: typedef SandboxDirectoryDatabase::FileId FileId; typedef SandboxDirectoryDatabase::FileInfo FileInfo; struct FileRecord { FileId file_id; base::FilePath virtual_path; }; void ProcessRecurseQueue() { while (display_stack_.empty() && !recurse_queue_.empty()) { FileRecord entry = recurse_queue_.front(); recurse_queue_.pop(); if (!db_->ListChildren(entry.file_id, &display_stack_)) { display_stack_.clear(); return; } current_parent_virtual_path_ = entry.virtual_path; } } SandboxDirectoryDatabase* db_; FileSystemOperationContext* context_; ObfuscatedFileUtil* obfuscated_file_util_; FileSystemURL root_url_; bool recursive_; std::queue<FileRecord> recurse_queue_; std::vector<FileId> display_stack_; base::FilePath current_parent_virtual_path_; FileId current_file_id_; base::File::Info current_platform_file_info_; }; class ObfuscatedOriginEnumerator : public ObfuscatedFileUtil::AbstractOriginEnumerator { public: typedef SandboxOriginDatabase::OriginRecord OriginRecord; ObfuscatedOriginEnumerator( SandboxOriginDatabaseInterface* origin_database, const base::FilePath& base_file_path) : base_file_path_(base_file_path) { if (origin_database) origin_database->ListAllOrigins(&origins_); } virtual ~ObfuscatedOriginEnumerator() {} // Returns the next origin. Returns empty if there are no more origins. virtual GURL Next() OVERRIDE { OriginRecord record; if (!origins_.empty()) { record = origins_.back(); origins_.pop_back(); } current_ = record; return webkit_database::GetOriginFromIdentifier(record.origin); } // Returns the current origin's information. virtual bool HasTypeDirectory(const std::string& type_string) const OVERRIDE { if (current_.path.empty()) return false; if (type_string.empty()) { NOTREACHED(); return false; } base::FilePath path = base_file_path_.Append(current_.path).AppendASCII(type_string); return base::DirectoryExists(path); } private: std::vector<OriginRecord> origins_; OriginRecord current_; base::FilePath base_file_path_; }; ObfuscatedFileUtil::ObfuscatedFileUtil( quota::SpecialStoragePolicy* special_storage_policy, const base::FilePath& file_system_directory, leveldb::Env* env_override, base::SequencedTaskRunner* file_task_runner, const GetTypeStringForURLCallback& get_type_string_for_url, const std::set<std::string>& known_type_strings, SandboxFileSystemBackendDelegate* sandbox_delegate) : special_storage_policy_(special_storage_policy), file_system_directory_(file_system_directory), env_override_(env_override), db_flush_delay_seconds_(10 * 60), // 10 mins. file_task_runner_(file_task_runner), get_type_string_for_url_(get_type_string_for_url), known_type_strings_(known_type_strings), sandbox_delegate_(sandbox_delegate) { } ObfuscatedFileUtil::~ObfuscatedFileUtil() { DropDatabases(); } base::File ObfuscatedFileUtil::CreateOrOpen( FileSystemOperationContext* context, const FileSystemURL& url, int file_flags) { base::File file = CreateOrOpenInternal(context, url, file_flags); if (file.IsValid() && file_flags & base::File::FLAG_WRITE && context->quota_limit_type() == quota::kQuotaLimitTypeUnlimited && sandbox_delegate_) { sandbox_delegate_->StickyInvalidateUsageCache(url.origin(), url.type()); } return file.Pass(); } base::File::Error ObfuscatedFileUtil::EnsureFileExists( FileSystemOperationContext* context, const FileSystemURL& url, bool* created) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true); if (!db) return base::File::FILE_ERROR_FAILED; FileId file_id; if (db->GetFileWithPath(url.path(), &file_id)) { FileInfo file_info; if (!db->GetFileInfo(file_id, &file_info)) { NOTREACHED(); return base::File::FILE_ERROR_FAILED; } if (file_info.is_directory()) return base::File::FILE_ERROR_NOT_A_FILE; if (created) *created = false; return base::File::FILE_OK; } FileId parent_id; if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo file_info; InitFileInfo(&file_info, parent_id, VirtualPath::BaseName(url.path()).value()); int64 growth = UsageForPath(file_info.name.size()); if (!AllocateQuota(context, growth)) return base::File::FILE_ERROR_NO_SPACE; base::File::Error error = CreateFile(context, base::FilePath(), url, &file_info); if (created && base::File::FILE_OK == error) { *created = true; UpdateUsage(context, url, growth); context->change_observers()->Notify( &FileChangeObserver::OnCreateFile, MakeTuple(url)); } return error; } base::File::Error ObfuscatedFileUtil::CreateDirectory( FileSystemOperationContext* context, const FileSystemURL& url, bool exclusive, bool recursive) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true); if (!db) return base::File::FILE_ERROR_FAILED; FileId file_id; if (db->GetFileWithPath(url.path(), &file_id)) { FileInfo file_info; if (exclusive) return base::File::FILE_ERROR_EXISTS; if (!db->GetFileInfo(file_id, &file_info)) { NOTREACHED(); return base::File::FILE_ERROR_FAILED; } if (!file_info.is_directory()) return base::File::FILE_ERROR_NOT_A_DIRECTORY; return base::File::FILE_OK; } std::vector<base::FilePath::StringType> components; VirtualPath::GetComponents(url.path(), &components); FileId parent_id = 0; size_t index; for (index = 0; index < components.size(); ++index) { base::FilePath::StringType name = components[index]; if (name == FILE_PATH_LITERAL("/")) continue; if (!db->GetChildWithName(parent_id, name, &parent_id)) break; } if (!db->IsDirectory(parent_id)) return base::File::FILE_ERROR_NOT_A_DIRECTORY; if (!recursive && components.size() - index > 1) return base::File::FILE_ERROR_NOT_FOUND; bool first = true; for (; index < components.size(); ++index) { FileInfo file_info; file_info.name = components[index]; if (file_info.name == FILE_PATH_LITERAL("/")) continue; file_info.modification_time = base::Time::Now(); file_info.parent_id = parent_id; int64 growth = UsageForPath(file_info.name.size()); if (!AllocateQuota(context, growth)) return base::File::FILE_ERROR_NO_SPACE; base::File::Error error = db->AddFileInfo(file_info, &parent_id); if (error != base::File::FILE_OK) return error; UpdateUsage(context, url, growth); context->change_observers()->Notify( &FileChangeObserver::OnCreateDirectory, MakeTuple(url)); if (first) { first = false; TouchDirectory(db, file_info.parent_id); } } return base::File::FILE_OK; } base::File::Error ObfuscatedFileUtil::GetFileInfo( FileSystemOperationContext* context, const FileSystemURL& url, base::File::Info* file_info, base::FilePath* platform_file_path) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false); if (!db) return base::File::FILE_ERROR_NOT_FOUND; FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo local_info; return GetFileInfoInternal(db, context, url, file_id, &local_info, file_info, platform_file_path); } scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> ObfuscatedFileUtil::CreateFileEnumerator( FileSystemOperationContext* context, const FileSystemURL& root_url) { return CreateFileEnumerator(context, root_url, false /* recursive */); } base::File::Error ObfuscatedFileUtil::GetLocalFilePath( FileSystemOperationContext* context, const FileSystemURL& url, base::FilePath* local_path) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false); if (!db) return base::File::FILE_ERROR_NOT_FOUND; FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo file_info; if (!db->GetFileInfo(file_id, &file_info) || file_info.is_directory()) { NOTREACHED(); // Directories have no local file path. return base::File::FILE_ERROR_NOT_FOUND; } *local_path = DataPathToLocalPath(url, file_info.data_path); if (local_path->empty()) return base::File::FILE_ERROR_NOT_FOUND; return base::File::FILE_OK; } base::File::Error ObfuscatedFileUtil::Touch( FileSystemOperationContext* context, const FileSystemURL& url, const base::Time& last_access_time, const base::Time& last_modified_time) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false); if (!db) return base::File::FILE_ERROR_NOT_FOUND; FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo file_info; if (!db->GetFileInfo(file_id, &file_info)) { NOTREACHED(); return base::File::FILE_ERROR_FAILED; } if (file_info.is_directory()) { if (!db->UpdateModificationTime(file_id, last_modified_time)) return base::File::FILE_ERROR_FAILED; return base::File::FILE_OK; } return NativeFileUtil::Touch( DataPathToLocalPath(url, file_info.data_path), last_access_time, last_modified_time); } base::File::Error ObfuscatedFileUtil::Truncate( FileSystemOperationContext* context, const FileSystemURL& url, int64 length) { base::File::Info file_info; base::FilePath local_path; base::File::Error error = GetFileInfo(context, url, &file_info, &local_path); if (error != base::File::FILE_OK) return error; int64 growth = length - file_info.size; if (!AllocateQuota(context, growth)) return base::File::FILE_ERROR_NO_SPACE; error = NativeFileUtil::Truncate(local_path, length); if (error == base::File::FILE_OK) { UpdateUsage(context, url, growth); context->change_observers()->Notify( &FileChangeObserver::OnModifyFile, MakeTuple(url)); } return error; } base::File::Error ObfuscatedFileUtil::CopyOrMoveFile( FileSystemOperationContext* context, const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, bool copy) { // Cross-filesystem copies and moves should be handled via CopyInForeignFile. DCHECK(src_url.origin() == dest_url.origin()); DCHECK(src_url.type() == dest_url.type()); SandboxDirectoryDatabase* db = GetDirectoryDatabase(src_url, true); if (!db) return base::File::FILE_ERROR_FAILED; FileId src_file_id; if (!db->GetFileWithPath(src_url.path(), &src_file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileId dest_file_id; bool overwrite = db->GetFileWithPath(dest_url.path(), &dest_file_id); FileInfo src_file_info; base::File::Info src_platform_file_info; base::FilePath src_local_path; base::File::Error error = GetFileInfoInternal( db, context, src_url, src_file_id, &src_file_info, &src_platform_file_info, &src_local_path); if (error != base::File::FILE_OK) return error; if (src_file_info.is_directory()) return base::File::FILE_ERROR_NOT_A_FILE; FileInfo dest_file_info; base::File::Info dest_platform_file_info; // overwrite case only base::FilePath dest_local_path; // overwrite case only if (overwrite) { base::File::Error error = GetFileInfoInternal( db, context, dest_url, dest_file_id, &dest_file_info, &dest_platform_file_info, &dest_local_path); if (error == base::File::FILE_ERROR_NOT_FOUND) overwrite = false; // fallback to non-overwrite case else if (error != base::File::FILE_OK) return error; else if (dest_file_info.is_directory()) return base::File::FILE_ERROR_INVALID_OPERATION; } if (!overwrite) { FileId dest_parent_id; if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()), &dest_parent_id)) { return base::File::FILE_ERROR_NOT_FOUND; } dest_file_info = src_file_info; dest_file_info.parent_id = dest_parent_id; dest_file_info.name = VirtualPath::BaseName(dest_url.path()).value(); } int64 growth = 0; if (copy) growth += src_platform_file_info.size; else growth -= UsageForPath(src_file_info.name.size()); if (overwrite) growth -= dest_platform_file_info.size; else growth += UsageForPath(dest_file_info.name.size()); if (!AllocateQuota(context, growth)) return base::File::FILE_ERROR_NO_SPACE; /* * Copy-with-overwrite * Just overwrite data file * Copy-without-overwrite * Copy backing file * Create new metadata pointing to new backing file. * Move-with-overwrite * transaction: * Remove source entry. * Point target entry to source entry's backing file. * Delete target entry's old backing file * Move-without-overwrite * Just update metadata */ error = base::File::FILE_ERROR_FAILED; if (copy) { if (overwrite) { error = NativeFileUtil::CopyOrMoveFile( src_local_path, dest_local_path, option, fileapi::NativeFileUtil::CopyOrMoveModeForDestination( dest_url, true /* copy */)); } else { // non-overwrite error = CreateFile(context, src_local_path, dest_url, &dest_file_info); } } else { if (overwrite) { if (db->OverwritingMoveFile(src_file_id, dest_file_id)) { if (base::File::FILE_OK != NativeFileUtil::DeleteFile(dest_local_path)) LOG(WARNING) << "Leaked a backing file."; error = base::File::FILE_OK; } else { error = base::File::FILE_ERROR_FAILED; } } else { // non-overwrite if (db->UpdateFileInfo(src_file_id, dest_file_info)) error = base::File::FILE_OK; else error = base::File::FILE_ERROR_FAILED; } } if (error != base::File::FILE_OK) return error; if (overwrite) { context->change_observers()->Notify( &FileChangeObserver::OnModifyFile, MakeTuple(dest_url)); } else { context->change_observers()->Notify( &FileChangeObserver::OnCreateFileFrom, MakeTuple(dest_url, src_url)); } if (!copy) { context->change_observers()->Notify( &FileChangeObserver::OnRemoveFile, MakeTuple(src_url)); TouchDirectory(db, src_file_info.parent_id); } TouchDirectory(db, dest_file_info.parent_id); UpdateUsage(context, dest_url, growth); return error; } base::File::Error ObfuscatedFileUtil::CopyInForeignFile( FileSystemOperationContext* context, const base::FilePath& src_file_path, const FileSystemURL& dest_url) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true); if (!db) return base::File::FILE_ERROR_FAILED; base::File::Info src_platform_file_info; if (!base::GetFileInfo(src_file_path, &src_platform_file_info)) return base::File::FILE_ERROR_NOT_FOUND; FileId dest_file_id; bool overwrite = db->GetFileWithPath(dest_url.path(), &dest_file_id); FileInfo dest_file_info; base::File::Info dest_platform_file_info; // overwrite case only if (overwrite) { base::FilePath dest_local_path; base::File::Error error = GetFileInfoInternal( db, context, dest_url, dest_file_id, &dest_file_info, &dest_platform_file_info, &dest_local_path); if (error == base::File::FILE_ERROR_NOT_FOUND) overwrite = false; // fallback to non-overwrite case else if (error != base::File::FILE_OK) return error; else if (dest_file_info.is_directory()) return base::File::FILE_ERROR_INVALID_OPERATION; } if (!overwrite) { FileId dest_parent_id; if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()), &dest_parent_id)) { return base::File::FILE_ERROR_NOT_FOUND; } if (!dest_file_info.is_directory()) return base::File::FILE_ERROR_FAILED; InitFileInfo(&dest_file_info, dest_parent_id, VirtualPath::BaseName(dest_url.path()).value()); } int64 growth = src_platform_file_info.size; if (overwrite) growth -= dest_platform_file_info.size; else growth += UsageForPath(dest_file_info.name.size()); if (!AllocateQuota(context, growth)) return base::File::FILE_ERROR_NO_SPACE; base::File::Error error; if (overwrite) { base::FilePath dest_local_path = DataPathToLocalPath(dest_url, dest_file_info.data_path); error = NativeFileUtil::CopyOrMoveFile( src_file_path, dest_local_path, FileSystemOperation::OPTION_NONE, fileapi::NativeFileUtil::CopyOrMoveModeForDestination(dest_url, true /* copy */)); } else { error = CreateFile(context, src_file_path, dest_url, &dest_file_info); } if (error != base::File::FILE_OK) return error; if (overwrite) { context->change_observers()->Notify( &FileChangeObserver::OnModifyFile, MakeTuple(dest_url)); } else { context->change_observers()->Notify( &FileChangeObserver::OnCreateFile, MakeTuple(dest_url)); } UpdateUsage(context, dest_url, growth); TouchDirectory(db, dest_file_info.parent_id); return base::File::FILE_OK; } base::File::Error ObfuscatedFileUtil::DeleteFile( FileSystemOperationContext* context, const FileSystemURL& url) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true); if (!db) return base::File::FILE_ERROR_FAILED; FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo file_info; base::File::Info platform_file_info; base::FilePath local_path; base::File::Error error = GetFileInfoInternal( db, context, url, file_id, &file_info, &platform_file_info, &local_path); if (error != base::File::FILE_ERROR_NOT_FOUND && error != base::File::FILE_OK) return error; if (file_info.is_directory()) return base::File::FILE_ERROR_NOT_A_FILE; int64 growth = -UsageForPath(file_info.name.size()) - platform_file_info.size; AllocateQuota(context, growth); if (!db->RemoveFileInfo(file_id)) { NOTREACHED(); return base::File::FILE_ERROR_FAILED; } UpdateUsage(context, url, growth); TouchDirectory(db, file_info.parent_id); context->change_observers()->Notify( &FileChangeObserver::OnRemoveFile, MakeTuple(url)); if (error == base::File::FILE_ERROR_NOT_FOUND) return base::File::FILE_OK; error = NativeFileUtil::DeleteFile(local_path); if (base::File::FILE_OK != error) LOG(WARNING) << "Leaked a backing file."; return base::File::FILE_OK; } base::File::Error ObfuscatedFileUtil::DeleteDirectory( FileSystemOperationContext* context, const FileSystemURL& url) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true); if (!db) return base::File::FILE_ERROR_FAILED; FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) return base::File::FILE_ERROR_NOT_FOUND; FileInfo file_info; if (!db->GetFileInfo(file_id, &file_info)) { NOTREACHED(); return base::File::FILE_ERROR_FAILED; } if (!file_info.is_directory()) return base::File::FILE_ERROR_NOT_A_DIRECTORY; if (!db->RemoveFileInfo(file_id)) return base::File::FILE_ERROR_NOT_EMPTY; int64 growth = -UsageForPath(file_info.name.size()); AllocateQuota(context, growth); UpdateUsage(context, url, growth); TouchDirectory(db, file_info.parent_id); context->change_observers()->Notify( &FileChangeObserver::OnRemoveDirectory, MakeTuple(url)); return base::File::FILE_OK; } webkit_blob::ScopedFile ObfuscatedFileUtil::CreateSnapshotFile( FileSystemOperationContext* context, const FileSystemURL& url, base::File::Error* error, base::File::Info* file_info, base::FilePath* platform_path) { // We're just returning the local file information. *error = GetFileInfo(context, url, file_info, platform_path); if (*error == base::File::FILE_OK && file_info->is_directory) { *file_info = base::File::Info(); *error = base::File::FILE_ERROR_NOT_A_FILE; } return webkit_blob::ScopedFile(); } scoped_ptr<FileSystemFileUtil::AbstractFileEnumerator> ObfuscatedFileUtil::CreateFileEnumerator( FileSystemOperationContext* context, const FileSystemURL& root_url, bool recursive) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(root_url, false); if (!db) { return scoped_ptr<AbstractFileEnumerator>(new EmptyFileEnumerator()); } return scoped_ptr<AbstractFileEnumerator>( new ObfuscatedFileEnumerator(db, context, this, root_url, recursive)); } bool ObfuscatedFileUtil::IsDirectoryEmpty( FileSystemOperationContext* context, const FileSystemURL& url) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, false); if (!db) return true; // Not a great answer, but it's what others do. FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) return true; // Ditto. FileInfo file_info; if (!db->GetFileInfo(file_id, &file_info)) { DCHECK(!file_id); // It's the root directory and the database hasn't been initialized yet. return true; } if (!file_info.is_directory()) return true; std::vector<FileId> children; // TODO(ericu): This could easily be made faster with help from the database. if (!db->ListChildren(file_id, &children)) return true; return children.empty(); } base::FilePath ObfuscatedFileUtil::GetDirectoryForOriginAndType( const GURL& origin, const std::string& type_string, bool create, base::File::Error* error_code) { base::FilePath origin_dir = GetDirectoryForOrigin(origin, create, error_code); if (origin_dir.empty()) return base::FilePath(); if (type_string.empty()) return origin_dir; base::FilePath path = origin_dir.AppendASCII(type_string); base::File::Error error = base::File::FILE_OK; if (!base::DirectoryExists(path) && (!create || !base::CreateDirectory(path))) { error = create ? base::File::FILE_ERROR_FAILED : base::File::FILE_ERROR_NOT_FOUND; } if (error_code) *error_code = error; return path; } bool ObfuscatedFileUtil::DeleteDirectoryForOriginAndType( const GURL& origin, const std::string& type_string) { base::File::Error error = base::File::FILE_OK; base::FilePath origin_type_path = GetDirectoryForOriginAndType( origin, type_string, false, &error); if (origin_type_path.empty()) return true; if (error != base::File::FILE_ERROR_NOT_FOUND) { // TODO(dmikurube): Consider the return value of DestroyDirectoryDatabase. // We ignore its error now since 1) it doesn't matter the final result, and // 2) it always returns false in Windows because of LevelDB's // implementation. // Information about failure would be useful for debugging. if (!type_string.empty()) DestroyDirectoryDatabase(origin, type_string); if (!base::DeleteFile(origin_type_path, true /* recursive */)) return false; } base::FilePath origin_path = VirtualPath::DirName(origin_type_path); DCHECK_EQ(origin_path.value(), GetDirectoryForOrigin(origin, false, NULL).value()); if (!type_string.empty()) { // At this point we are sure we had successfully deleted the origin/type // directory (i.e. we're ready to just return true). // See if we have other directories in this origin directory. for (std::set<std::string>::iterator iter = known_type_strings_.begin(); iter != known_type_strings_.end(); ++iter) { if (*iter == type_string) continue; if (base::DirectoryExists(origin_path.AppendASCII(*iter))) { // Other type's directory exists; just return true here. return true; } } } // No other directories seem exist. Try deleting the entire origin directory. InitOriginDatabase(origin, false); if (origin_database_) { origin_database_->RemovePathForOrigin( webkit_database::GetIdentifierFromOrigin(origin)); } if (!base::DeleteFile(origin_path, true /* recursive */)) return false; return true; } ObfuscatedFileUtil::AbstractOriginEnumerator* ObfuscatedFileUtil::CreateOriginEnumerator() { std::vector<SandboxOriginDatabase::OriginRecord> origins; InitOriginDatabase(GURL(), false); return new ObfuscatedOriginEnumerator( origin_database_.get(), file_system_directory_); } bool ObfuscatedFileUtil::DestroyDirectoryDatabase( const GURL& origin, const std::string& type_string) { std::string key = GetDirectoryDatabaseKey(origin, type_string); if (key.empty()) return true; DirectoryMap::iterator iter = directories_.find(key); if (iter != directories_.end()) { SandboxDirectoryDatabase* database = iter->second; directories_.erase(iter); delete database; } base::File::Error error = base::File::FILE_OK; base::FilePath path = GetDirectoryForOriginAndType( origin, type_string, false, &error); if (path.empty() || error == base::File::FILE_ERROR_NOT_FOUND) return true; return SandboxDirectoryDatabase::DestroyDatabase(path, env_override_); } // static int64 ObfuscatedFileUtil::ComputeFilePathCost(const base::FilePath& path) { return UsageForPath(VirtualPath::BaseName(path).value().size()); } void ObfuscatedFileUtil::MaybePrepopulateDatabase( const std::vector<std::string>& type_strings_to_prepopulate) { SandboxPrioritizedOriginDatabase database(file_system_directory_, env_override_); std::string origin_string = database.GetPrimaryOrigin(); if (origin_string.empty() || !database.HasOriginPath(origin_string)) return; const GURL origin = webkit_database::GetOriginFromIdentifier(origin_string); // Prepopulate the directory database(s) if and only if this instance // has primary origin and the directory database is already there. for (size_t i = 0; i < type_strings_to_prepopulate.size(); ++i) { const std::string type_string = type_strings_to_prepopulate[i]; // Only handles known types. if (!ContainsKey(known_type_strings_, type_string)) continue; base::File::Error error = base::File::FILE_ERROR_FAILED; base::FilePath path = GetDirectoryForOriginAndType( origin, type_string, false, &error); if (error != base::File::FILE_OK) continue; scoped_ptr<SandboxDirectoryDatabase> db( new SandboxDirectoryDatabase(path, env_override_)); if (db->Init(SandboxDirectoryDatabase::FAIL_ON_CORRUPTION)) { directories_[GetDirectoryDatabaseKey(origin, type_string)] = db.release(); MarkUsed(); // Don't populate more than one database, as it may rather hurt // performance. break; } } } base::FilePath ObfuscatedFileUtil::GetDirectoryForURL( const FileSystemURL& url, bool create, base::File::Error* error_code) { return GetDirectoryForOriginAndType( url.origin(), CallGetTypeStringForURL(url), create, error_code); } std::string ObfuscatedFileUtil::CallGetTypeStringForURL( const FileSystemURL& url) { DCHECK(!get_type_string_for_url_.is_null()); return get_type_string_for_url_.Run(url); } base::File::Error ObfuscatedFileUtil::GetFileInfoInternal( SandboxDirectoryDatabase* db, FileSystemOperationContext* context, const FileSystemURL& url, FileId file_id, FileInfo* local_info, base::File::Info* file_info, base::FilePath* platform_file_path) { DCHECK(db); DCHECK(context); DCHECK(file_info); DCHECK(platform_file_path); if (!db->GetFileInfo(file_id, local_info)) { NOTREACHED(); return base::File::FILE_ERROR_FAILED; } if (local_info->is_directory()) { file_info->size = 0; file_info->is_directory = true; file_info->is_symbolic_link = false; file_info->last_modified = local_info->modification_time; *platform_file_path = base::FilePath(); // We don't fill in ctime or atime. return base::File::FILE_OK; } if (local_info->data_path.empty()) return base::File::FILE_ERROR_INVALID_OPERATION; base::FilePath local_path = DataPathToLocalPath(url, local_info->data_path); base::File::Error error = NativeFileUtil::GetFileInfo( local_path, file_info); // We should not follow symbolic links in sandboxed file system. if (base::IsLink(local_path)) { LOG(WARNING) << "Found a symbolic file."; error = base::File::FILE_ERROR_NOT_FOUND; } if (error == base::File::FILE_OK) { *platform_file_path = local_path; } else if (error == base::File::FILE_ERROR_NOT_FOUND) { LOG(WARNING) << "Lost a backing file."; InvalidateUsageCache(context, url.origin(), url.type()); if (!db->RemoveFileInfo(file_id)) return base::File::FILE_ERROR_FAILED; } return error; } base::File ObfuscatedFileUtil::CreateAndOpenFile( FileSystemOperationContext* context, const FileSystemURL& dest_url, FileInfo* dest_file_info, int file_flags) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true); base::FilePath root, dest_local_path; base::File::Error error = GenerateNewLocalPath(db, context, dest_url, &root, &dest_local_path); if (error != base::File::FILE_OK) return base::File(error); if (base::PathExists(dest_local_path)) { if (!base::DeleteFile(dest_local_path, true /* recursive */)) return base::File(base::File::FILE_ERROR_FAILED); LOG(WARNING) << "A stray file detected"; InvalidateUsageCache(context, dest_url.origin(), dest_url.type()); } base::File file = NativeFileUtil::CreateOrOpen(dest_local_path, file_flags); if (!file.IsValid()) return file.Pass(); if (!file.created()) { file.Close(); base::DeleteFile(dest_local_path, false /* recursive */); return base::File(base::File::FILE_ERROR_FAILED); } error = CommitCreateFile(root, dest_local_path, db, dest_file_info); if (error != base::File::FILE_OK) { file.Close(); base::DeleteFile(dest_local_path, false /* recursive */); return base::File(error); } return file.Pass(); } base::File::Error ObfuscatedFileUtil::CreateFile( FileSystemOperationContext* context, const base::FilePath& src_file_path, const FileSystemURL& dest_url, FileInfo* dest_file_info) { SandboxDirectoryDatabase* db = GetDirectoryDatabase(dest_url, true); base::FilePath root, dest_local_path; base::File::Error error = GenerateNewLocalPath(db, context, dest_url, &root, &dest_local_path); if (error != base::File::FILE_OK) return error; bool created = false; if (src_file_path.empty()) { if (base::PathExists(dest_local_path)) { if (!base::DeleteFile(dest_local_path, true /* recursive */)) return base::File::FILE_ERROR_FAILED; LOG(WARNING) << "A stray file detected"; InvalidateUsageCache(context, dest_url.origin(), dest_url.type()); } error = NativeFileUtil::EnsureFileExists(dest_local_path, &created); } else { error = NativeFileUtil::CopyOrMoveFile( src_file_path, dest_local_path, FileSystemOperation::OPTION_NONE, fileapi::NativeFileUtil::CopyOrMoveModeForDestination(dest_url, true /* copy */)); created = true; } if (error != base::File::FILE_OK) return error; if (!created) return base::File::FILE_ERROR_FAILED; return CommitCreateFile(root, dest_local_path, db, dest_file_info); } base::File::Error ObfuscatedFileUtil::CommitCreateFile( const base::FilePath& root, const base::FilePath& local_path, SandboxDirectoryDatabase* db, FileInfo* dest_file_info) { // This removes the root, including the trailing slash, leaving a relative // path. dest_file_info->data_path = base::FilePath( local_path.value().substr(root.value().length() + 1)); FileId file_id; base::File::Error error = db->AddFileInfo(*dest_file_info, &file_id); if (error != base::File::FILE_OK) return error; TouchDirectory(db, dest_file_info->parent_id); return base::File::FILE_OK; } base::FilePath ObfuscatedFileUtil::DataPathToLocalPath( const FileSystemURL& url, const base::FilePath& data_path) { base::File::Error error = base::File::FILE_OK; base::FilePath root = GetDirectoryForURL(url, false, &error); if (error != base::File::FILE_OK) return base::FilePath(); return root.Append(data_path); } std::string ObfuscatedFileUtil::GetDirectoryDatabaseKey( const GURL& origin, const std::string& type_string) { if (type_string.empty()) { LOG(WARNING) << "Unknown filesystem type requested:" << type_string; return std::string(); } // For isolated origin we just use a type string as a key. return webkit_database::GetIdentifierFromOrigin(origin) + type_string; } // TODO(ericu): How to do the whole validation-without-creation thing? // We may not have quota even to create the database. // Ah, in that case don't even get here? // Still doesn't answer the quota issue, though. SandboxDirectoryDatabase* ObfuscatedFileUtil::GetDirectoryDatabase( const FileSystemURL& url, bool create) { std::string key = GetDirectoryDatabaseKey( url.origin(), CallGetTypeStringForURL(url)); if (key.empty()) return NULL; DirectoryMap::iterator iter = directories_.find(key); if (iter != directories_.end()) { MarkUsed(); return iter->second; } base::File::Error error = base::File::FILE_OK; base::FilePath path = GetDirectoryForURL(url, create, &error); if (error != base::File::FILE_OK) { LOG(WARNING) << "Failed to get origin+type directory: " << url.DebugString() << " error:" << error; return NULL; } MarkUsed(); SandboxDirectoryDatabase* database = new SandboxDirectoryDatabase(path, env_override_); directories_[key] = database; return database; } base::FilePath ObfuscatedFileUtil::GetDirectoryForOrigin( const GURL& origin, bool create, base::File::Error* error_code) { if (!InitOriginDatabase(origin, create)) { if (error_code) { *error_code = create ? base::File::FILE_ERROR_FAILED : base::File::FILE_ERROR_NOT_FOUND; } return base::FilePath(); } base::FilePath directory_name; std::string id = webkit_database::GetIdentifierFromOrigin(origin); bool exists_in_db = origin_database_->HasOriginPath(id); if (!exists_in_db && !create) { if (error_code) *error_code = base::File::FILE_ERROR_NOT_FOUND; return base::FilePath(); } if (!origin_database_->GetPathForOrigin(id, &directory_name)) { if (error_code) *error_code = base::File::FILE_ERROR_FAILED; return base::FilePath(); } base::FilePath path = file_system_directory_.Append(directory_name); bool exists_in_fs = base::DirectoryExists(path); if (!exists_in_db && exists_in_fs) { if (!base::DeleteFile(path, true)) { if (error_code) *error_code = base::File::FILE_ERROR_FAILED; return base::FilePath(); } exists_in_fs = false; } if (!exists_in_fs) { if (!create || !base::CreateDirectory(path)) { if (error_code) *error_code = create ? base::File::FILE_ERROR_FAILED : base::File::FILE_ERROR_NOT_FOUND; return base::FilePath(); } } if (error_code) *error_code = base::File::FILE_OK; return path; } void ObfuscatedFileUtil::InvalidateUsageCache( FileSystemOperationContext* context, const GURL& origin, FileSystemType type) { if (sandbox_delegate_) sandbox_delegate_->InvalidateUsageCache(origin, type); } void ObfuscatedFileUtil::MarkUsed() { if (!timer_) timer_.reset(new TimedTaskHelper(file_task_runner_.get())); if (timer_->IsRunning()) { timer_->Reset(); } else { timer_->Start(FROM_HERE, base::TimeDelta::FromSeconds(db_flush_delay_seconds_), base::Bind(&ObfuscatedFileUtil::DropDatabases, base::Unretained(this))); } } void ObfuscatedFileUtil::DropDatabases() { origin_database_.reset(); STLDeleteContainerPairSecondPointers( directories_.begin(), directories_.end()); directories_.clear(); timer_.reset(); } bool ObfuscatedFileUtil::InitOriginDatabase(const GURL& origin_hint, bool create) { if (origin_database_) return true; if (!create && !base::DirectoryExists(file_system_directory_)) return false; if (!base::CreateDirectory(file_system_directory_)) { LOG(WARNING) << "Failed to create FileSystem directory: " << file_system_directory_.value(); return false; } SandboxPrioritizedOriginDatabase* prioritized_origin_database = new SandboxPrioritizedOriginDatabase(file_system_directory_, env_override_); origin_database_.reset(prioritized_origin_database); if (origin_hint.is_empty() || !HasIsolatedStorage(origin_hint)) return true; const std::string isolated_origin_string = webkit_database::GetIdentifierFromOrigin(origin_hint); // TODO(kinuko): Deprecate this after a few release cycles, e.g. around M33. base::FilePath isolated_origin_dir = file_system_directory_.Append( SandboxIsolatedOriginDatabase::kObsoleteOriginDirectory); if (base::DirectoryExists(isolated_origin_dir) && prioritized_origin_database->GetSandboxOriginDatabase()) { SandboxIsolatedOriginDatabase::MigrateBackFromObsoleteOriginDatabase( isolated_origin_string, file_system_directory_, prioritized_origin_database->GetSandboxOriginDatabase()); } prioritized_origin_database->InitializePrimaryOrigin( isolated_origin_string); return true; } base::File::Error ObfuscatedFileUtil::GenerateNewLocalPath( SandboxDirectoryDatabase* db, FileSystemOperationContext* context, const FileSystemURL& url, base::FilePath* root, base::FilePath* local_path) { DCHECK(local_path); int64 number; if (!db || !db->GetNextInteger(&number)) return base::File::FILE_ERROR_FAILED; base::File::Error error = base::File::FILE_OK; *root = GetDirectoryForURL(url, false, &error); if (error != base::File::FILE_OK) return error; // We use the third- and fourth-to-last digits as the directory. int64 directory_number = number % 10000 / 100; base::FilePath new_local_path = root->AppendASCII( base::StringPrintf("%02" PRId64, directory_number)); error = NativeFileUtil::CreateDirectory( new_local_path, false /* exclusive */, false /* recursive */); if (error != base::File::FILE_OK) return error; *local_path = new_local_path.AppendASCII(base::StringPrintf("%08" PRId64, number)); return base::File::FILE_OK; } base::File ObfuscatedFileUtil::CreateOrOpenInternal( FileSystemOperationContext* context, const FileSystemURL& url, int file_flags) { DCHECK(!(file_flags & (base::File::FLAG_DELETE_ON_CLOSE | base::File::FLAG_HIDDEN | base::File::FLAG_EXCLUSIVE_READ | base::File::FLAG_EXCLUSIVE_WRITE))); SandboxDirectoryDatabase* db = GetDirectoryDatabase(url, true); if (!db) return base::File(base::File::FILE_ERROR_FAILED); FileId file_id; if (!db->GetFileWithPath(url.path(), &file_id)) { // The file doesn't exist. if (!(file_flags & (base::File::FLAG_CREATE | base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_ALWAYS))) { return base::File(base::File::FILE_ERROR_NOT_FOUND); } FileId parent_id; if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id)) return base::File(base::File::FILE_ERROR_NOT_FOUND); FileInfo file_info; InitFileInfo(&file_info, parent_id, VirtualPath::BaseName(url.path()).value()); int64 growth = UsageForPath(file_info.name.size()); if (!AllocateQuota(context, growth)) return base::File(base::File::FILE_ERROR_NO_SPACE); base::File file = CreateAndOpenFile(context, url, &file_info, file_flags); if (file.IsValid()) { UpdateUsage(context, url, growth); context->change_observers()->Notify( &FileChangeObserver::OnCreateFile, MakeTuple(url)); } return file.Pass(); } if (file_flags & base::File::FLAG_CREATE) return base::File(base::File::FILE_ERROR_EXISTS); base::File::Info platform_file_info; base::FilePath local_path; FileInfo file_info; base::File::Error error = GetFileInfoInternal( db, context, url, file_id, &file_info, &platform_file_info, &local_path); if (error != base::File::FILE_OK) return base::File(error); if (file_info.is_directory()) return base::File(base::File::FILE_ERROR_NOT_A_FILE); int64 delta = 0; if (file_flags & (base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_TRUNCATED)) { // The file exists and we're truncating. delta = -platform_file_info.size; AllocateQuota(context, delta); } base::File file = NativeFileUtil::CreateOrOpen(local_path, file_flags); if (!file.IsValid()) { error = file.error_details(); if (error == base::File::FILE_ERROR_NOT_FOUND) { // TODO(tzik): Also invalidate on-memory usage cache in UsageTracker. // TODO(tzik): Delete database entry after ensuring the file lost. InvalidateUsageCache(context, url.origin(), url.type()); LOG(WARNING) << "Lost a backing file."; return base::File(base::File::FILE_ERROR_FAILED); } return file.Pass(); } // If truncating we need to update the usage. if (delta) { UpdateUsage(context, url, delta); context->change_observers()->Notify( &FileChangeObserver::OnModifyFile, MakeTuple(url)); } return file.Pass(); } bool ObfuscatedFileUtil::HasIsolatedStorage(const GURL& origin) { return special_storage_policy_.get() && special_storage_policy_->HasIsolatedStorage(origin); } } // namespace fileapi
TeamEOS/external_chromium_org
webkit/browser/fileapi/obfuscated_file_util.cc
C++
bsd-3-clause
47,936
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export enum TagContentType { RAW_TEXT, ESCAPABLE_RAW_TEXT, PARSABLE_DATA } export interface TagDefinition { closedByParent: boolean; implicitNamespacePrefix: string|null; contentType: TagContentType; isVoid: boolean; ignoreFirstLf: boolean; canSelfClose: boolean; isClosedByChild(name: string): boolean; } export function splitNsName(elementName: string): [string | null, string] { if (elementName[0] != ':') { return [null, elementName]; } const colonIndex = elementName.indexOf(':', 1); if (colonIndex == -1) { throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`); } return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)]; } // `<ng-container>` tags work the same regardless the namespace export function isNgContainer(tagName: string): boolean { return splitNsName(tagName)[1] === 'ng-container'; } // `<ng-content>` tags work the same regardless the namespace export function isNgContent(tagName: string): boolean { return splitNsName(tagName)[1] === 'ng-content'; } // `<ng-template>` tags work the same regardless the namespace export function isNgTemplate(tagName: string): boolean { return splitNsName(tagName)[1] === 'ng-template'; } export function getNsPrefix(fullName: string): string; export function getNsPrefix(fullName: null): null; export function getNsPrefix(fullName: string | null): string|null { return fullName === null ? null : splitNsName(fullName)[0]; } export function mergeNsAndName(prefix: string, localName: string): string { return prefix ? `:${prefix}:${localName}` : localName; } // see http://www.w3.org/TR/html51/syntax.html#named-character-references // see https://html.spec.whatwg.org/multipage/entities.json // This list is not exhaustive to keep the compiler footprint low. // The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not // exist. export const NAMED_ENTITIES: {[k: string]: string} = { 'Aacute': '\u00C1', 'aacute': '\u00E1', 'Acirc': '\u00C2', 'acirc': '\u00E2', 'acute': '\u00B4', 'AElig': '\u00C6', 'aelig': '\u00E6', 'Agrave': '\u00C0', 'agrave': '\u00E0', 'alefsym': '\u2135', 'Alpha': '\u0391', 'alpha': '\u03B1', 'amp': '&', 'and': '\u2227', 'ang': '\u2220', 'apos': '\u0027', 'Aring': '\u00C5', 'aring': '\u00E5', 'asymp': '\u2248', 'Atilde': '\u00C3', 'atilde': '\u00E3', 'Auml': '\u00C4', 'auml': '\u00E4', 'bdquo': '\u201E', 'Beta': '\u0392', 'beta': '\u03B2', 'brvbar': '\u00A6', 'bull': '\u2022', 'cap': '\u2229', 'Ccedil': '\u00C7', 'ccedil': '\u00E7', 'cedil': '\u00B8', 'cent': '\u00A2', 'Chi': '\u03A7', 'chi': '\u03C7', 'circ': '\u02C6', 'clubs': '\u2663', 'cong': '\u2245', 'copy': '\u00A9', 'crarr': '\u21B5', 'cup': '\u222A', 'curren': '\u00A4', 'dagger': '\u2020', 'Dagger': '\u2021', 'darr': '\u2193', 'dArr': '\u21D3', 'deg': '\u00B0', 'Delta': '\u0394', 'delta': '\u03B4', 'diams': '\u2666', 'divide': '\u00F7', 'Eacute': '\u00C9', 'eacute': '\u00E9', 'Ecirc': '\u00CA', 'ecirc': '\u00EA', 'Egrave': '\u00C8', 'egrave': '\u00E8', 'empty': '\u2205', 'emsp': '\u2003', 'ensp': '\u2002', 'Epsilon': '\u0395', 'epsilon': '\u03B5', 'equiv': '\u2261', 'Eta': '\u0397', 'eta': '\u03B7', 'ETH': '\u00D0', 'eth': '\u00F0', 'Euml': '\u00CB', 'euml': '\u00EB', 'euro': '\u20AC', 'exist': '\u2203', 'fnof': '\u0192', 'forall': '\u2200', 'frac12': '\u00BD', 'frac14': '\u00BC', 'frac34': '\u00BE', 'frasl': '\u2044', 'Gamma': '\u0393', 'gamma': '\u03B3', 'ge': '\u2265', 'gt': '>', 'harr': '\u2194', 'hArr': '\u21D4', 'hearts': '\u2665', 'hellip': '\u2026', 'Iacute': '\u00CD', 'iacute': '\u00ED', 'Icirc': '\u00CE', 'icirc': '\u00EE', 'iexcl': '\u00A1', 'Igrave': '\u00CC', 'igrave': '\u00EC', 'image': '\u2111', 'infin': '\u221E', 'int': '\u222B', 'Iota': '\u0399', 'iota': '\u03B9', 'iquest': '\u00BF', 'isin': '\u2208', 'Iuml': '\u00CF', 'iuml': '\u00EF', 'Kappa': '\u039A', 'kappa': '\u03BA', 'Lambda': '\u039B', 'lambda': '\u03BB', 'lang': '\u27E8', 'laquo': '\u00AB', 'larr': '\u2190', 'lArr': '\u21D0', 'lceil': '\u2308', 'ldquo': '\u201C', 'le': '\u2264', 'lfloor': '\u230A', 'lowast': '\u2217', 'loz': '\u25CA', 'lrm': '\u200E', 'lsaquo': '\u2039', 'lsquo': '\u2018', 'lt': '<', 'macr': '\u00AF', 'mdash': '\u2014', 'micro': '\u00B5', 'middot': '\u00B7', 'minus': '\u2212', 'Mu': '\u039C', 'mu': '\u03BC', 'nabla': '\u2207', 'nbsp': '\u00A0', 'ndash': '\u2013', 'ne': '\u2260', 'ni': '\u220B', 'not': '\u00AC', 'notin': '\u2209', 'nsub': '\u2284', 'Ntilde': '\u00D1', 'ntilde': '\u00F1', 'Nu': '\u039D', 'nu': '\u03BD', 'Oacute': '\u00D3', 'oacute': '\u00F3', 'Ocirc': '\u00D4', 'ocirc': '\u00F4', 'OElig': '\u0152', 'oelig': '\u0153', 'Ograve': '\u00D2', 'ograve': '\u00F2', 'oline': '\u203E', 'Omega': '\u03A9', 'omega': '\u03C9', 'Omicron': '\u039F', 'omicron': '\u03BF', 'oplus': '\u2295', 'or': '\u2228', 'ordf': '\u00AA', 'ordm': '\u00BA', 'Oslash': '\u00D8', 'oslash': '\u00F8', 'Otilde': '\u00D5', 'otilde': '\u00F5', 'otimes': '\u2297', 'Ouml': '\u00D6', 'ouml': '\u00F6', 'para': '\u00B6', 'permil': '\u2030', 'perp': '\u22A5', 'Phi': '\u03A6', 'phi': '\u03C6', 'Pi': '\u03A0', 'pi': '\u03C0', 'piv': '\u03D6', 'plusmn': '\u00B1', 'pound': '\u00A3', 'prime': '\u2032', 'Prime': '\u2033', 'prod': '\u220F', 'prop': '\u221D', 'Psi': '\u03A8', 'psi': '\u03C8', 'quot': '\u0022', 'radic': '\u221A', 'rang': '\u27E9', 'raquo': '\u00BB', 'rarr': '\u2192', 'rArr': '\u21D2', 'rceil': '\u2309', 'rdquo': '\u201D', 'real': '\u211C', 'reg': '\u00AE', 'rfloor': '\u230B', 'Rho': '\u03A1', 'rho': '\u03C1', 'rlm': '\u200F', 'rsaquo': '\u203A', 'rsquo': '\u2019', 'sbquo': '\u201A', 'Scaron': '\u0160', 'scaron': '\u0161', 'sdot': '\u22C5', 'sect': '\u00A7', 'shy': '\u00AD', 'Sigma': '\u03A3', 'sigma': '\u03C3', 'sigmaf': '\u03C2', 'sim': '\u223C', 'spades': '\u2660', 'sub': '\u2282', 'sube': '\u2286', 'sum': '\u2211', 'sup': '\u2283', 'sup1': '\u00B9', 'sup2': '\u00B2', 'sup3': '\u00B3', 'supe': '\u2287', 'szlig': '\u00DF', 'Tau': '\u03A4', 'tau': '\u03C4', 'there4': '\u2234', 'Theta': '\u0398', 'theta': '\u03B8', 'thetasym': '\u03D1', 'thinsp': '\u2009', 'THORN': '\u00DE', 'thorn': '\u00FE', 'tilde': '\u02DC', 'times': '\u00D7', 'trade': '\u2122', 'Uacute': '\u00DA', 'uacute': '\u00FA', 'uarr': '\u2191', 'uArr': '\u21D1', 'Ucirc': '\u00DB', 'ucirc': '\u00FB', 'Ugrave': '\u00D9', 'ugrave': '\u00F9', 'uml': '\u00A8', 'upsih': '\u03D2', 'Upsilon': '\u03A5', 'upsilon': '\u03C5', 'Uuml': '\u00DC', 'uuml': '\u00FC', 'weierp': '\u2118', 'Xi': '\u039E', 'xi': '\u03BE', 'Yacute': '\u00DD', 'yacute': '\u00FD', 'yen': '\u00A5', 'yuml': '\u00FF', 'Yuml': '\u0178', 'Zeta': '\u0396', 'zeta': '\u03B6', 'zwj': '\u200D', 'zwnj': '\u200C', }; // The &ngsp; pseudo-entity is denoting a space. see: // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart export const NGSP_UNICODE = '\uE500'; NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
Toxicable/angular
packages/compiler/src/ml_parser/tags.ts
TypeScript
mit
7,644
// // AKMixedFFT.h // AudioKit // // Created by Aurelius Prochazka on 7/22/12. // Copyright (c) 2012 Aurelius Prochazka. All rights reserved. // #import "AKParameter+Operation.h" #import "AKFSignal.h" /** Mix 'seamlessly' two pv signals. This opcode combines the most prominent components of two pvoc streams into a single mixed stream. */ NS_ASSUME_NONNULL_BEGIN @interface AKMixedFFT : AKFSignal /// Create a mixture of two f-signal. /// @param signal1 The first f-signal. /// @param signal2 The second f-signal. - (instancetype)initWithSignal1:(AKFSignal *)signal1 signal2:(AKFSignal *)signal2; @end NS_ASSUME_NONNULL_END
dclelland/HOWL
Pods/AudioKit/AudioKit/Operations/FFT/AKMixedFFT.h
C
mit
660
# coding: utf-8 # In[ ]: #练习一:文本加密解密(先看有关ASCII码的相关知识以及码表,查维基百科或百度百科) #输入:一个txt文件(假设全是字母的英文词,每个单词之间用单个空格隔开,假设单词最长为10个字母) #加密:得到每个单词的长度 n ,随机生成一个9位的数字,将 n-1 与这个9位的数字连接,形成一个10位的数字, #作为密匙 key 。依照 key 中各个数字对单词中每一个对应位置的字母进行向后移位(例:如过 key 中某数字为 2 , #对应该位置的字母为 a ,加密则应移位成 c ,如果超过 z ,则回到 A 处继续移位),对长度不到10的单词,移位后, #将移位后的单词利用随机字母补全到10个,最终形成以10个字母为一个单词,并以单个空格分割的加密文本,存入文件。 #解密:给定该文本文件并给定key(10位数字),恢复原来的文本。 #(提示,利用 ord() 及 chr() 函数, ord(x) 是取得字符 x 的ASCII码, chr(n) 是取得整数n(代表ASCII码)对应的字符。 #例: ord(a) 的值为 97 , chr(97) 的值为 'a' ,因字母 a 的ASCII码值为 97 。) fh = open(r'd:\temp\words.txt') text = fh.read() fh.close() print(len(text)) print(text)
ZMMzhangmingming/liupengyuan.github.io
chapter2/homework/computer/5-10/201611680890-5.10.py
Python
mit
1,296
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2016, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Rene Rahn <rene.rahn@fu-berlin.de> // ========================================================================== // The adaption of the meta profile and the setup for the banded chain // alignment. // ========================================================================== #ifndef INCLUDE_SEQAN_SEEDS_BANDED_CHAIN_ALIGNMENT_META_INFO_H_ #define INCLUDE_SEQAN_SEEDS_BANDED_CHAIN_ALIGNMENT_META_INFO_H_ namespace seqan { // ============================================================================ // Forwards // ============================================================================ // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // Tag BandedChainInitialDPMatrix // ---------------------------------------------------------------------------- // Specifies the first dp matrix that is computed. struct BandedChainInitialDPMatrix_; typedef Tag<BandedChainInitialDPMatrix_> BandedChainInitialDPMatrix; // ---------------------------------------------------------------------------- // Tag BandedChainInnerDPMatrix // ---------------------------------------------------------------------------- // Specifies the inner dp matrix that is computed. struct BandedChainInnerDPMatrix_; typedef Tag<BandedChainInnerDPMatrix_> BandedChainInnerDPMatrix; // ---------------------------------------------------------------------------- // Tag BandedChainLastDPMatrix // ---------------------------------------------------------------------------- // Specifies the lasr dp matrix that is computed. struct BandedChainFinalDPMatrix_; typedef Tag<BandedChainFinalDPMatrix_> BandedChainFinalDPMatrix; // ---------------------------------------------------------------------------- // Struct BandedChainAlignment // ---------------------------------------------------------------------------- // Algorithm tag for the banded chain alignments. The first type determines the // free end-gaps and the second one which dp matrix is currently considered (initial, inner, final) template <typename TSpec = FreeEndGaps_<>, typename TDPMatrixLocation = BandedChainInnerDPMatrix> struct BandedChainAlignment_{}; // ---------------------------------------------------------------------------- // Class DPMetaColumn [FullColumn] // ---------------------------------------------------------------------------- template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType> struct DPMetaColumn_<DPProfile_<BandedChainAlignment_<TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>, MetaColumnDescriptor<TColumnType, FullColumn> > { // If InitialColumn -> replaced, replaced, replaced // If InnerColumn -> replaced, All, All // If FinalColumn -> replaced, All, All typedef RecursionDirectionZero TRecursionTypeFirstCell_; typedef RecursionDirectionAll TRecursionTypeInnerCell_; typedef RecursionDirectionAll TRecursionTypeLastCell_; typedef DPMetaCell_<TRecursionTypeFirstCell_, True> TFirstCell_; typedef DPMetaCell_<TRecursionTypeInnerCell_, True> TInnerCell_; typedef DPMetaCell_<TRecursionTypeLastCell_, True> TLastCell_; }; // ---------------------------------------------------------------------------- // Class DPMetaColumn [PartialColumnTop] // ---------------------------------------------------------------------------- template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType> struct DPMetaColumn_<DPProfile_<BandedChainAlignment_<TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>, MetaColumnDescriptor<TColumnType, PartialColumnTop> > { // If InitialColumn -> replaced, replaced, replaced // If InnerColumn -> replaced, All, LowerBand // If FinalColumn -> replaced, All, LowerBand typedef RecursionDirectionZero TRecursionTypeFirstCell_; typedef RecursionDirectionAll TRecursionTypeInnerCell_; typedef RecursionDirectionLowerDiagonal TRecursionTypeLastCell_; typedef DPMetaCell_<TRecursionTypeFirstCell_, True> TFirstCell_; typedef DPMetaCell_<TRecursionTypeInnerCell_, True> TInnerCell_; typedef DPMetaCell_<TRecursionTypeLastCell_, True> TLastCell_; }; // ---------------------------------------------------------------------------- // Class DPMetaColumn [PartialColumnMiddle] // ---------------------------------------------------------------------------- template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType> struct DPMetaColumn_<DPProfile_<BandedChainAlignment_<TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>, MetaColumnDescriptor<TColumnType, PartialColumnMiddle> > { // If InitialColumn -> replaced, replaced, replaced // If InnerColumn -> UpperDiagonal, All, LowerDiagonal // If FinalColumn -> UpperDiagonal, All, LowerDiagonal typedef RecursionDirectionUpperDiagonal TRecursionTypeFirstCell_; typedef RecursionDirectionAll TRecursionTypeInnerCell_; typedef RecursionDirectionLowerDiagonal TRecursionTypeLastCell_; typedef DPMetaCell_<TRecursionTypeFirstCell_, True> TFirstCell_; typedef DPMetaCell_<TRecursionTypeInnerCell_, True> TInnerCell_; typedef DPMetaCell_<TRecursionTypeLastCell_, True> TLastCell_; }; // ---------------------------------------------------------------------------- // Class DPMetaColumn [PartialColumnBottom] // ---------------------------------------------------------------------------- template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType> struct DPMetaColumn_<DPProfile_<BandedChainAlignment_<TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>, MetaColumnDescriptor<TColumnType, PartialColumnBottom> > { // If InitialColumn -> replaced, replaced, replaced // If InnerColumn -> UpperDiagonal, All, All // If FinalColumn -> UpperDiagonal, All, All typedef RecursionDirectionUpperDiagonal TRecursionTypeFirstCell_; typedef RecursionDirectionAll TRecursionTypeInnerCell_; typedef RecursionDirectionAll TRecursionTypeLastCell_; typedef DPMetaCell_<TRecursionTypeFirstCell_, True> TFirstCell_; typedef DPMetaCell_<TRecursionTypeInnerCell_, True> TInnerCell_; typedef DPMetaCell_<TRecursionTypeLastCell_, True> TLastCell_; }; // ============================================================================ // Metafunctions // ============================================================================ // ---------------------------------------------------------------------------- // Metafunction IsGlobalAlignment_ // ---------------------------------------------------------------------------- template <typename TSpec, typename TDPMatrixLocation> struct IsGlobalAlignment_<BandedChainAlignment_<TSpec, TDPMatrixLocation> > : False{}; // ---------------------------------------------------------------------------- // Metafunction IsFreeEndGap_ // ---------------------------------------------------------------------------- template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TDPSide> struct IsFreeEndGap_<BandedChainAlignment_<TFreeEndGaps, TDPMatrixLocation>, TDPSide> : IsFreeEndGap_<TFreeEndGaps, TDPSide> {}; template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TDPSide> struct IsFreeEndGap_<BandedChainAlignment_<TFreeEndGaps, TDPMatrixLocation> const, TDPSide> : IsFreeEndGap_<TFreeEndGaps const, TDPSide> {}; // ---------------------------------------------------------------------------- // Metafunction SetupBandedChainAlignmentProfile_ // ---------------------------------------------------------------------------- // Profile for BandedChainAlignment algorithm template <typename TAlignConfig, typename TGapCosts, typename TGapsPlacement> struct SetupBandedChainAlignmentProfile_ { typedef typename SubstituteAlignConfig_<TAlignConfig>::Type TFreeEndGaps_; typedef DPProfile_<BandedChainAlignment_<TFreeEndGaps_, BandedChainInnerDPMatrix>, TGapCosts, TracebackOn<TracebackConfig_<CompleteTrace,TGapsPlacement> > > Type; }; // ============================================================================ // Functions // ============================================================================ // ---------------------------------------------------------------------------- // Function _setupAndRunBandedChainAlignment() // ---------------------------------------------------------------------------- template <typename TTraceSegment, typename TStringSetSpec, typename TSeeds, typename TSequenceH, typename TSequenceV, typename TScoreValue, typename TScoreSpecAnchor, typename TScoreSpecGap, bool TFirstRow, bool TFirstColumn, bool TLastColumn, bool TLastRow, typename TACSpec, typename TGapsPlacement> inline TScoreValue _setupAndRunBandedChainAlignment(StringSet<String<TTraceSegment>, TStringSetSpec> & globalTraceSet, TSeeds const & seedSet, TSequenceH const & seqH, TSequenceV const & seqV, Score<TScoreValue, TScoreSpecAnchor> const & scoringSchemeAnchor, Score<TScoreValue, TScoreSpecGap> const & scoringSchemeGap, AlignConfig<TFirstRow, TFirstColumn, TLastColumn, TLastRow, TACSpec> const &, unsigned bandExtension, TGapsPlacement const &) { //typedef typename Position<TSequenceH const>::Type TPosH; //typedef typename Position<TSequenceV const>::Type TPosV; typedef AlignConfig<TFirstRow, TFirstColumn, TLastColumn, TLastRow, TACSpec> TAlignConfig; typedef Score<TScoreValue, TScoreSpecAnchor> TScoringSchemeAnchor; typedef Score<TScoreValue, TScoreSpecGap> TScoringSchemeGap; typedef typename SequenceEntryForScore<TScoringSchemeAnchor, TSequenceH>::Type TSequenceHEntryAnchor; typedef typename SequenceEntryForScore<TScoringSchemeAnchor, TSequenceV>::Type TSequenceVEntryAnchor; typedef typename SequenceEntryForScore<TScoringSchemeGap, TSequenceH>::Type TSequenceHEntryGap; typedef typename SequenceEntryForScore<TScoringSchemeGap, TSequenceV>::Type TSequenceVEntryGap; TSequenceHEntryAnchor seqHEntryAnchor = sequenceEntryForScore(scoringSchemeAnchor, seqH, 0); TSequenceVEntryAnchor seqVEntryAnchor = sequenceEntryForScore(scoringSchemeAnchor, seqV, 0); TSequenceHEntryGap seqHEntryGap = sequenceEntryForScore(scoringSchemeGap, seqH, 0); TSequenceVEntryGap seqVEntryGap = sequenceEntryForScore(scoringSchemeGap, seqV, 0); if (scoreGapExtendHorizontal(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) != scoreGapOpenHorizontal(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) || scoreGapExtendVertical(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) != scoreGapOpenVertical(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) || scoreGapExtendHorizontal(scoringSchemeGap, seqHEntryGap, seqVEntryGap) != scoreGapOpenHorizontal(scoringSchemeGap, seqHEntryGap, seqVEntryGap) || scoreGapExtendVertical(scoringSchemeGap, seqHEntryGap, seqVEntryGap) != scoreGapOpenVertical(scoringSchemeGap, seqHEntryGap, seqVEntryGap)) { typedef typename SetupBandedChainAlignmentProfile_<TAlignConfig, AffineGaps, TGapsPlacement>::Type TDPProfile; return _computeAlignment(globalTraceSet, seedSet, seqH, seqV, scoringSchemeAnchor, scoringSchemeGap, bandExtension, TDPProfile()); } else { typedef typename SetupBandedChainAlignmentProfile_<TAlignConfig, LinearGaps, TGapsPlacement>::Type TDPProfile; return _computeAlignment(globalTraceSet, seedSet, seqH, seqV, scoringSchemeAnchor, scoringSchemeGap, bandExtension, TDPProfile()); } } } // namespace seqan #endif // #ifndef INCLUDE_SEQAN_SEEDS_BANDED_CHAIN_ALIGNMENT_META_INFO_H_
AbeelLab/phasm
vendor/seqan/seeds/banded_chain_alignment_profile.h
C
mit
14,414
var Model; module("Ember.FilteredRecordArray", { setup: function() { Model = Ember.Model.extend({ id: Ember.attr(), name: Ember.attr() }); Model.adapter = Ember.FixtureAdapter.create(); Model.FIXTURES = [ {id: 1, name: 'Erik'}, {id: 2, name: 'Stefan'}, {id: 'abc', name: 'Charles'} ]; }, teardown: function() { } }); test("must be created with a modelClass property", function() { throws(function() { Ember.FilteredRecordArray.create(); }, /FilteredRecordArrays must be created with a modelClass/); }); test("must be created with a filterFunction property", function() { throws(function() { Ember.FilteredRecordArray.create({modelClass: Model}); }, /FilteredRecordArrays must be created with a filterFunction/); }); test("must be created with a filterProperties property", function() { throws(function() { Ember.FilteredRecordArray.create({modelClass: Model, filterFunction: Ember.K}); }, /FilteredRecordArrays must be created with filterProperties/); }); test("with a noop filter will return all the loaded records", function() { expect(1); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: Ember.K, filterProperties: [] }); equal(recordArray.get('length'), 3, "There are 3 records"); }); stop(); }); test("with a filter will return only the relevant loaded records", function() { expect(2); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name') === 'Erik'; }, filterProperties: ['name'] }); equal(recordArray.get('length'), 1, "There is 1 record"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); }); stop(); }); test("loading a record that doesn't match the filter after creating a FilteredRecordArray shouldn't change the content", function() { expect(2); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name') === 'Erik'; }, filterProperties: ['name'] }); Model.create({id: 3, name: 'Kris'}).save().then(function(record) { start(); equal(recordArray.get('length'), 1, "There is still 1 record"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); }); stop(); }); stop(); }); test("loading a record that matches the filter after creating a FilteredRecordArray should update the content of it", function() { expect(3); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name') === 'Erik' || record.get('name') === 'Kris'; }, filterProperties: ['name'] }); Model.create({id: 3, name: 'Kris'}).save().then(function(record) { start(); equal(recordArray.get('length'), 2, "There are 2 records"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); equal(recordArray.get('lastObject.name'), 'Kris', "The record data matches"); }); stop(); }); stop(); }); test("changing a property that matches the filter should update the FilteredRecordArray to include it", function() { expect(5); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name').match(/^E/); }, filterProperties: ['name'] }); equal(recordArray.get('length'), 1, "There is 1 record initially"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); Model.fetch(2).then(function(record) { start(); record.set('name', 'Estefan'); equal(recordArray.get('length'), 2, "There are 2 records after changing the name"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); equal(recordArray.get('lastObject.name'), 'Estefan', "The record data matches"); }); stop(); }); stop(); }); test("adding a new record and changing a property that matches the filter should update the FilteredRecordArray to include it", function() { expect(8); Model.fetch().then(function() { start(); var recordArray = Ember.FilteredRecordArray.create({ modelClass: Model, filterFunction: function(record) { return record.get('name').match(/^E/); }, filterProperties: ['name'] }); equal(recordArray.get('length'), 1, "There is 1 record initially"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); Model.create({id: 3, name: 'Kris'}).save().then(function(record) { start(); record.set('name', 'Ekris'); equal(recordArray.get('length'), 2, "There are 2 records after changing the name"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches"); equal(recordArray.get('lastObject.name'), 'Ekris', "The record data matches"); record.set('name', 'Eskil'); equal(recordArray.get('length'), 2, "There are still 2 records after changing the name again"); equal(recordArray.get('firstObject.name'), 'Erik', "The record data still matches"); equal(recordArray.get('lastObject.name'), 'Eskil', "The record data still matches"); }); stop(); }); stop(); });
hypexr/grunt-version-copy-bower-components
test/fixtures/bower_components/ember-model/packages/ember-model/tests/filtered_record_array_test.js
JavaScript
mit
5,733
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=../../libc/enum.fpos64_t.html"> </head> <body> <p>Redirecting to <a href="../../libc/enum.fpos64_t.html">../../libc/enum.fpos64_t.html</a>...</p> <script>location.replace("../../libc/enum.fpos64_t.html" + location.search + location.hash);</script> </body> </html>
ssgrn/Rust-Matrix-Computations
target/doc/libc/unix/enum.fpos64_t.html
HTML
mit
357
#ifndef NGX_HTTP_HEADERS_MORE_FILTER_MODULE_H #define NGX_HTTP_HEADERS_MORE_FILTER_MODULE_H #include <ngx_core.h> #include <ngx_http.h> typedef enum { ngx_http_headers_more_opcode_set, ngx_http_headers_more_opcode_clear } ngx_http_headers_more_opcode_t; typedef struct { ngx_array_t *types; /* of ngx_str_t */ ngx_array_t *statuses; /* of ngx_uint_t */ ngx_array_t *headers; /* of ngx_http_header_val_t */ ngx_flag_t is_input; } ngx_http_headers_more_cmd_t; typedef struct { ngx_array_t *cmds; /* of ngx_http_headers_more_cmd_t */ } ngx_http_headers_more_loc_conf_t; typedef struct { unsigned postponed_to_phase_end; } ngx_http_headers_more_main_conf_t; typedef struct ngx_http_headers_more_header_val_s ngx_http_headers_more_header_val_t; typedef ngx_int_t (*ngx_http_headers_more_set_header_pt)(ngx_http_request_t *r, ngx_http_headers_more_header_val_t *hv, ngx_str_t *value); typedef struct { ngx_str_t name; ngx_uint_t offset; ngx_http_headers_more_set_header_pt handler; } ngx_http_headers_more_set_header_t; struct ngx_http_headers_more_header_val_s { ngx_http_complex_value_t value; ngx_uint_t hash; ngx_str_t key; ngx_http_headers_more_set_header_pt handler; ngx_uint_t offset; ngx_flag_t replace; ngx_flag_t wildcard; }; extern ngx_module_t ngx_http_headers_more_filter_module; extern unsigned ngx_http_headers_more_handler_used; extern unsigned ngx_http_headers_more_filter_used; #ifndef ngx_str_set #define ngx_str_set(str, text) \ (str)->len = sizeof(text) - 1; (str)->data = (u_char *) text #endif #endif /* NGX_HTTP_HEADERS_MORE_FILTER_MODULE_H */
ober/pinky-server
vendor/projects/ngx_openresty-1.2.7.6/bundle/headers-more-nginx-module-0.19/src/ngx_http_headers_more_filter_module.h
C
mit
2,066
// Package binary implements sintax-sugar functions on top of the standard // library binary package package binary import ( "bufio" "encoding/binary" "io" "gopkg.in/src-d/go-git.v4/plumbing" ) // Read reads structured binary data from r into data. Bytes are read and // decoded in BigEndian order // https://golang.org/pkg/encoding/binary/#Read func Read(r io.Reader, data ...interface{}) error { for _, v := range data { if err := binary.Read(r, binary.BigEndian, v); err != nil { return err } } return nil } // ReadUntil reads from r untin delim is found func ReadUntil(r io.Reader, delim byte) ([]byte, error) { var buf [1]byte value := make([]byte, 0, 16) for { if _, err := io.ReadFull(r, buf[:]); err != nil { if err == io.EOF { return nil, err } return nil, err } if buf[0] == delim { return value, nil } value = append(value, buf[0]) } } // ReadVariableWidthInt reads and returns an int in Git VLQ special format: // // Ordinary VLQ has some redundancies, example: the number 358 can be // encoded as the 2-octet VLQ 0x8166 or the 3-octet VLQ 0x808166 or the // 4-octet VLQ 0x80808166 and so forth. // // To avoid these redundancies, the VLQ format used in Git removes this // prepending redundancy and extends the representable range of shorter // VLQs by adding an offset to VLQs of 2 or more octets in such a way // that the lowest possible value for such an (N+1)-octet VLQ becomes // exactly one more than the maximum possible value for an N-octet VLQ. // In particular, since a 1-octet VLQ can store a maximum value of 127, // the minimum 2-octet VLQ (0x8000) is assigned the value 128 instead of // 0. Conversely, the maximum value of such a 2-octet VLQ (0xff7f) is // 16511 instead of just 16383. Similarly, the minimum 3-octet VLQ // (0x808000) has a value of 16512 instead of zero, which means // that the maximum 3-octet VLQ (0xffff7f) is 2113663 instead of // just 2097151. And so forth. // // This is how the offset is saved in C: // // dheader[pos] = ofs & 127; // while (ofs >>= 7) // dheader[--pos] = 128 | (--ofs & 127); // func ReadVariableWidthInt(r io.Reader) (int64, error) { var c byte if err := Read(r, &c); err != nil { return 0, err } var v = int64(c & maskLength) for c&maskContinue > 0 { v++ if err := Read(r, &c); err != nil { return 0, err } v = (v << lengthBits) + int64(c&maskLength) } return v, nil } const ( maskContinue = uint8(128) // 1000 000 maskLength = uint8(127) // 0111 1111 lengthBits = uint8(7) // subsequent bytes has 7 bits to store the length ) // ReadUint64 reads 8 bytes and returns them as a BigEndian uint32 func ReadUint64(r io.Reader) (uint64, error) { var v uint64 if err := binary.Read(r, binary.BigEndian, &v); err != nil { return 0, err } return v, nil } // ReadUint32 reads 4 bytes and returns them as a BigEndian uint32 func ReadUint32(r io.Reader) (uint32, error) { var v uint32 if err := binary.Read(r, binary.BigEndian, &v); err != nil { return 0, err } return v, nil } // ReadUint16 reads 2 bytes and returns them as a BigEndian uint16 func ReadUint16(r io.Reader) (uint16, error) { var v uint16 if err := binary.Read(r, binary.BigEndian, &v); err != nil { return 0, err } return v, nil } // ReadHash reads a plumbing.Hash from r func ReadHash(r io.Reader) (plumbing.Hash, error) { var h plumbing.Hash if err := binary.Read(r, binary.BigEndian, h[:]); err != nil { return plumbing.ZeroHash, err } return h, nil } const sniffLen = 8000 // IsBinary detects if data is a binary value based on: // http://git.kernel.org/cgit/git/git.git/tree/xdiff-interface.c?id=HEAD#n198 func IsBinary(r io.Reader) (bool, error) { reader := bufio.NewReader(r) c := 0 for { if c == sniffLen { break } b, err := reader.ReadByte() if err == io.EOF { break } if err != nil { return false, err } if b == byte(0) { return true, nil } c++ } return false, nil }
kettle11/wabi
wabi/vendor/gopkg.in/src-d/go-git.v4/utils/binary/read.go
GO
mit
3,985
// // MLAnonymousUtils.h // MaxLeap // #ifdef EXTENSION_IOS #import <MaxLeapExt/MLConstants.h> #else #import <MaxLeap/MLConstants.h> #endif /*! Methods for working with Anonymously logged-in users. Anonymous users have some unique characteristics: <ul> <li>Anonymous users don't need a user name or password.</li> <li>Once logged out, an anonymous user cannot be recovered.</li> <li>When the current user is anonymous, the following methods can be used to switch to a different user or convert the anonymous user into a regular one: <ul> <li>signUp converts an anonymous user to a standard user with the given username and password. Data associated with the anonymous user is retained.</li> <li>logIn switches users without converting the anonymous user. Data associated with the anonymous user will be lost.</li> <li>Service logIn (e.g. Facebook, Twitter) will attempt to convert the anonymous user into a standard user by linking it to the service. If a user already exists that is linked to the service, it will instead switch to the existing user.</li> <li>Service linking (e.g. Facebook, Twitter) will convert the anonymous user into a standard user by linking it to the service.</li> </ul> </ul> */ @interface MLAnonymousUtils : NSObject /*! @name Creating an Anonymous User */ /*! Creates an anonymous user. @param block The block to execute when anonymous user creation is complete. The block should have the following argument signature: (MLUser *user, NSError *error) */ + (void)logInWithBlock:(nullable MLUserResultBlock)block; /*! @name Determining Whether a MLUseris Anonymous */ /*! Whether the user is logged in anonymously. @param user User to check for anonymity. The user must be logged in on this device. @return True if the user is anonymous. False if the user is not the current user or is not anonymous. */ + (BOOL)isLinkedWithUser:(nullable MLUser *)user; @end
LeapCloud/Sample-Todo-iOS
Frameworks/MaxLeap.framework/Headers/MLAnonymousUtils.h
C
cc0-1.0
1,931
var dude = "Dude"; var dude2 = new { Name = "Dude", Age = 30, }; var dude3 = new { Name = "Dude", Age = 30, Kids = new { Name = "LittleDude" } }; var dude4 = new { Name = "Dude", Age = 30, Kids = new[] { "LittleDude" } }; var dude5 = new { Name = "Dude", Age = 30, Kids = new[] { new { Name = "LittleDude" } } }; Action y = () => { }; Func<int, float, bool> z = (a, b) => { var z = new { a, b }; return(z == null); };
bengardner/uncrustify
tests/output/cs/10140-remove_semi.cs
C#
gpl-2.0
532
#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "William.A.Walters@colorado.edu" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order)
ssorgatem/qiime
qiime/truncate_fasta_qual_files.py
Python
gpl-2.0
6,323
/* * Copyright (c) 2011-2015 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ /** ------------------------------------------------------------------------- * ------------------------------------------------------------------------- * \file csrApiScan.c Implementation for the Common Scan interfaces. ========================================================================== */ #include "aniGlobal.h" #include "palApi.h" #include "csrInsideApi.h" #include "smeInside.h" #include "smsDebug.h" #include "csrSupport.h" #include "wlan_qct_tl.h" #include "vos_diag_core_log.h" #include "vos_diag_core_event.h" #include "vos_nvitem.h" #include "vos_memory.h" #include "wlan_qct_wda.h" #include "vos_utils.h" #define MIN_CHN_TIME_TO_FIND_GO 100 #define MAX_CHN_TIME_TO_FIND_GO 100 #define DIRECT_SSID_LEN 7 /* * Purpose of HIDDEN_TIMER * When we remove hidden ssid from the profile i.e., forget the SSID via GUI * that SSID shouldn't see in the profile for above requirement we used timer * limit, logic is explained below timer value is initialized to current time * when it receives corresponding probe response of hidden SSID * (The probe request is received regularly till SSID in the profile. * Once it is removed from profile probe request is not sent.) when we receive * probe response for broadcast probe request, during update SSID with saved * SSID we will diff current time with saved SSID time if it is greater than * 1 min then we are not updating with old one. */ #define HIDDEN_TIMER (1*60*1000) /* Must be less than 100, represent the percentage of new RSSI */ #define CSR_SCAN_RESULT_RSSI_WEIGHT 80 #define MAX_ACTIVE_SCAN_FOR_ONE_CHANNEL 140 #define MIN_ACTIVE_SCAN_FOR_ONE_CHANNEL 120 #define MAX_ACTIVE_SCAN_FOR_ONE_CHANNEL_FASTREASSOC 30 #define MIN_ACTIVE_SCAN_FOR_ONE_CHANNEL_FASTREASSOC 20 #define CSR_SCAN_IS_OVER_BSS_LIMIT(pMac) \ ( (pMac)->scan.nBssLimit <= (csrLLCount(&(pMac)->scan.scanResultList)) ) //*** This is temporary work around. It need to call CCM api to get to CFG later /// Get string parameter value extern tSirRetStatus wlan_cfgGetStr(tpAniSirGlobal, tANI_U16, tANI_U8*, tANI_U32*); void csrScanGetResultTimerHandler(void *); static void csrScanResultCfgAgingTimerHandler(void *pv); void csrScanIdleScanTimerHandler(void *); static void csrSetDefaultScanTiming( tpAniSirGlobal pMac, tSirScanType scanType, tCsrScanRequest *pScanRequest); #ifdef WLAN_AP_STA_CONCURRENCY static void csrStaApConcTimerHandler(void *); #endif tANI_BOOLEAN csrIsSupportedChannel(tpAniSirGlobal pMac, tANI_U8 channelId); eHalStatus csrScanChannels( tpAniSirGlobal pMac, tSmeCmd *pCommand ); void csrSetCfgValidChannelList( tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 NumChannels ); void csrSaveTxPowerToCfg( tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U32 cfgId ); void csrSetCfgCountryCode( tpAniSirGlobal pMac, tANI_U8 *countryCode ); void csrPurgeChannelPower( tpAniSirGlobal pMac, tDblLinkList *pChannelList ); //if bgPeriod is 0, background scan is disabled. It is in millisecond units eHalStatus csrSetCfgBackgroundScanPeriod(tpAniSirGlobal pMac, tANI_U32 bgPeriod); eHalStatus csrProcessSetBGScanParam(tpAniSirGlobal pMac, tSmeCmd *pCommand); void csrReleaseScanCommand(tpAniSirGlobal pMac, tSmeCmd *pCommand, eCsrScanStatus scanStatus); static tANI_BOOLEAN csrScanValidateScanResult( tpAniSirGlobal pMac, tANI_U8 *pChannels, tANI_U8 numChn, tSirBssDescription *pBssDesc, tDot11fBeaconIEs **ppIes ); eHalStatus csrSetBGScanChannelList( tpAniSirGlobal pMac, tANI_U8 *pAdjustChannels, tANI_U8 NumAdjustChannels); void csrReleaseCmdSingle(tpAniSirGlobal pMac, tSmeCmd *pCommand); tANI_BOOLEAN csrRoamIsValidChannel( tpAniSirGlobal pMac, tANI_U8 channel ); void csrPruneChannelListForMode( tpAniSirGlobal pMac, tCsrChannel *pChannelList ); #define CSR_IS_SOCIAL_CHANNEL(channel) (((channel) == 1) || ((channel) == 6) || ((channel) == 11) ) static void csrReleaseScanCmdPendingList(tpAniSirGlobal pMac) { tListElem *pEntry; tSmeCmd *pCommand; while((pEntry = csrLLRemoveHead( &pMac->scan.scanCmdPendingList, LL_ACCESS_LOCK)) != NULL) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); if ( eSmeCsrCommandMask & pCommand->command ) { csrAbortCommand( pMac, pCommand, eANI_BOOLEAN_TRUE ); } else { smsLog(pMac, LOGE, FL("Error: Received command : %d"),pCommand->command); } } } //pResult is invalid calling this function. void csrFreeScanResultEntry( tpAniSirGlobal pMac, tCsrScanResult *pResult ) { if( NULL != pResult->Result.pvIes ) { vos_mem_free(pResult->Result.pvIes); } vos_mem_free(pResult); } static eHalStatus csrLLScanPurgeResult(tpAniSirGlobal pMac, tDblLinkList *pList) { eHalStatus status = eHAL_STATUS_SUCCESS; tListElem *pEntry; tCsrScanResult *pBssDesc; csrLLLock(pList); while((pEntry = csrLLRemoveHead(pList, LL_ACCESS_NOLOCK)) != NULL) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); csrFreeScanResultEntry( pMac, pBssDesc ); } csrLLUnlock(pList); return (status); } eHalStatus csrScanOpen( tpAniSirGlobal pMac ) { eHalStatus status; do { csrLLOpen(pMac->hHdd, &pMac->scan.scanResultList); csrLLOpen(pMac->hHdd, &pMac->scan.tempScanResults); csrLLOpen(pMac->hHdd, &pMac->scan.channelPowerInfoList24); csrLLOpen(pMac->hHdd, &pMac->scan.channelPowerInfoList5G); #ifdef WLAN_AP_STA_CONCURRENCY csrLLOpen(pMac->hHdd, &pMac->scan.scanCmdPendingList); #endif pMac->scan.fFullScanIssued = eANI_BOOLEAN_FALSE; pMac->scan.nBssLimit = CSR_MAX_BSS_SUPPORT; status = vos_timer_init(&pMac->scan.hTimerGetResult, VOS_TIMER_TYPE_SW, csrScanGetResultTimerHandler, pMac); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("cannot allocate memory for getResult timer")); break; } #ifdef WLAN_AP_STA_CONCURRENCY status = vos_timer_init(&pMac->scan.hTimerStaApConcTimer, VOS_TIMER_TYPE_SW, csrStaApConcTimerHandler, pMac); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("cannot allocate memory for hTimerStaApConcTimer timer")); break; } #endif status = vos_timer_init(&pMac->scan.hTimerIdleScan, VOS_TIMER_TYPE_SW, csrScanIdleScanTimerHandler, pMac); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("cannot allocate memory for idleScan timer")); break; } status = vos_timer_init(&pMac->scan.hTimerResultCfgAging, VOS_TIMER_TYPE_SW, csrScanResultCfgAgingTimerHandler, pMac); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("cannot allocate memory for CFG ResultAging timer")); break; } }while(0); return (status); } eHalStatus csrScanClose( tpAniSirGlobal pMac ) { csrLLScanPurgeResult(pMac, &pMac->scan.tempScanResults); csrLLScanPurgeResult(pMac, &pMac->scan.scanResultList); #ifdef WLAN_AP_STA_CONCURRENCY csrReleaseScanCmdPendingList(pMac); #endif csrLLClose(&pMac->scan.scanResultList); csrLLClose(&pMac->scan.tempScanResults); #ifdef WLAN_AP_STA_CONCURRENCY csrLLClose(&pMac->scan.scanCmdPendingList); #endif csrPurgeChannelPower(pMac, &pMac->scan.channelPowerInfoList24); csrPurgeChannelPower(pMac, &pMac->scan.channelPowerInfoList5G); csrLLClose(&pMac->scan.channelPowerInfoList24); csrLLClose(&pMac->scan.channelPowerInfoList5G); csrScanDisable(pMac); vos_timer_destroy(&pMac->scan.hTimerResultCfgAging); vos_timer_destroy(&pMac->scan.hTimerGetResult); #ifdef WLAN_AP_STA_CONCURRENCY vos_timer_destroy(&pMac->scan.hTimerStaApConcTimer); #endif vos_timer_destroy(&pMac->scan.hTimerIdleScan); return eHAL_STATUS_SUCCESS; } eHalStatus csrScanEnable( tpAniSirGlobal pMac ) { pMac->scan.fScanEnable = eANI_BOOLEAN_TRUE; pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; return eHAL_STATUS_SUCCESS; } eHalStatus csrScanDisable( tpAniSirGlobal pMac ) { csrScanStopTimers(pMac); pMac->scan.fScanEnable = eANI_BOOLEAN_FALSE; return eHAL_STATUS_SUCCESS; } //Set scan timing parameters according to state of other driver sessions //No validation of the parameters is performed. static void csrSetDefaultScanTiming( tpAniSirGlobal pMac, tSirScanType scanType, tCsrScanRequest *pScanRequest) { #ifdef WLAN_AP_STA_CONCURRENCY if(csrIsAnySessionConnected(pMac)) { /* Reset passive scan time as per ini parameter. */ ccmCfgSetInt(pMac, WNI_CFG_PASSIVE_MAXIMUM_CHANNEL_TIME, pMac->roam.configParam.nPassiveMaxChnTimeConc, NULL, false); //If multi-session, use the appropriate default scan times if(scanType == eSIR_ACTIVE_SCAN) { pScanRequest->maxChnTime = pMac->roam.configParam.nActiveMaxChnTimeConc; pScanRequest->minChnTime = pMac->roam.configParam.nActiveMinChnTimeConc; } else { pScanRequest->maxChnTime = pMac->roam.configParam.nPassiveMaxChnTimeConc; pScanRequest->minChnTime = pMac->roam.configParam.nPassiveMinChnTimeConc; } pScanRequest->maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pScanRequest->minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; pScanRequest->restTime = pMac->roam.configParam.nRestTimeConc; pScanRequest->min_rest_time = pMac->roam.configParam.min_rest_time_conc; pScanRequest->idle_time = pMac->roam.configParam.idle_time_conc; //Return so that fields set above will not be overwritten. return; } #endif //This portion of the code executed if multi-session not supported //(WLAN_AP_STA_CONCURRENCY not defined) or no multi-session. //Use the "regular" (non-concurrency) default scan timing. ccmCfgSetInt(pMac, WNI_CFG_PASSIVE_MAXIMUM_CHANNEL_TIME, pMac->roam.configParam.nPassiveMaxChnTime, NULL,eANI_BOOLEAN_FALSE); if(pScanRequest->scanType == eSIR_ACTIVE_SCAN) { pScanRequest->maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; pScanRequest->minChnTime = pMac->roam.configParam.nActiveMinChnTime; } else { pScanRequest->maxChnTime = pMac->roam.configParam.nPassiveMaxChnTime; pScanRequest->minChnTime = pMac->roam.configParam.nPassiveMinChnTime; } pScanRequest->maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pScanRequest->minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; #ifdef WLAN_AP_STA_CONCURRENCY /* No rest time/Idle time if no sessions are connected. */ pScanRequest->restTime = 0; pScanRequest->min_rest_time = 0; pScanRequest->idle_time = 0; #endif } #ifdef WLAN_AP_STA_CONCURRENCY //Return SUCCESS is the command is queued, else returns eHAL_STATUS_FAILURE eHalStatus csrQueueScanRequest(tpAniSirGlobal pMac, tANI_U8 sessionId, tSmeCmd *pScanCmd) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_BOOLEAN fNoCmdPending; tSmeCmd *pQueueScanCmd=NULL; tSmeCmd *pSendScanCmd=NULL; tANI_U8 nNumChanCombinedConc = 0; if (NULL == pScanCmd) { smsLog (pMac, LOGE, FL("Scan Req cmd is NULL")); return eHAL_STATUS_FAILURE; } /* split scan if any one of the following: * - STA session is connected and the scan is not a P2P search * - any P2P session is connected * Do not split scans if no concurrent infra connections are * active and if the scan is a BG scan triggered by LFR (OR) * any scan if LFR is in the middle of a BG scan. Splitting * the scan is delaying the time it takes for LFR to find * candidates and resulting in disconnects. */ if(csrIsStaSessionConnected(pMac) && !csrIsP2pSessionConnected(pMac)) { nNumChanCombinedConc = pMac->roam.configParam.nNumStaChanCombinedConc; } else if(csrIsP2pSessionConnected(pMac)) { nNumChanCombinedConc = pMac->roam.configParam.nNumP2PChanCombinedConc; } if ( (csrIsStaSessionConnected(pMac) && #ifdef FEATURE_WLAN_LFR (csrIsConcurrentInfraConnected(pMac) || ((pScanCmd->u.scanCmd.reason != eCsrScanBgScan) && (pMac->roam.neighborRoamInfo[sessionId].neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN))) && #endif (pScanCmd->u.scanCmd.u.scanRequest.p2pSearch != 1)) || (csrIsP2pSessionConnected(pMac)) ) { tCsrScanRequest scanReq; tANI_U8 numChn = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels; tCsrChannelInfo *pChnInfo = &scanReq.ChannelInfo; tANI_U8 channelToScan[WNI_CFG_VALID_CHANNEL_LIST_LEN]; tANI_BOOLEAN bMemAlloc = eANI_BOOLEAN_FALSE; if (numChn == 0) { numChn = pMac->scan.baseChannels.numChannels; pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(numChn); if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList ) { smsLog( pMac, LOGE, FL(" Failed to get memory for channel list ") ); return eHAL_STATUS_FAILURE; } bMemAlloc = eANI_BOOLEAN_TRUE; vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList, pMac->scan.baseChannels.channelList, numChn); status = eHAL_STATUS_SUCCESS; if( !HAL_STATUS_SUCCESS( status ) ) { vos_mem_free(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList); pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL; smsLog( pMac, LOGE, FL(" Failed to copy memory to channel list ") ); return eHAL_STATUS_FAILURE; } pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = numChn; } //Whenever we get a scan request with multiple channels we break it up into 2 requests //First request for first channel to scan and second request to scan remaining channels if ( numChn > nNumChanCombinedConc) { vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0); pQueueScanCmd = csrGetCommandBuffer(pMac); //optimize this to use 2 command buffer only if (!pQueueScanCmd) { if (bMemAlloc) { vos_mem_free(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList); pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL; } smsLog( pMac, LOGE, FL(" Failed to get Queue command buffer") ); return eHAL_STATUS_FAILURE; } pQueueScanCmd->command = pScanCmd->command; pQueueScanCmd->sessionId = pScanCmd->sessionId; pQueueScanCmd->u.scanCmd.callback = pScanCmd->u.scanCmd.callback; pQueueScanCmd->u.scanCmd.pContext = pScanCmd->u.scanCmd.pContext; pQueueScanCmd->u.scanCmd.reason = pScanCmd->u.scanCmd.reason; pQueueScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around /* First copy all the parameters to local variable of scan request */ csrScanCopyRequest(pMac, &scanReq, &pScanCmd->u.scanCmd.u.scanRequest); /* Now modify the elements of local var scan request required to be modified for split scan */ if(scanReq.ChannelInfo.ChannelList != NULL) { vos_mem_free(scanReq.ChannelInfo.ChannelList); scanReq.ChannelInfo.ChannelList = NULL; } pChnInfo->numOfChannels = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels - nNumChanCombinedConc; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_WARN, FL(" &channelToScan %p pScanCmd(%p) pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList(%p)numChn(%d)"), &channelToScan[0], pScanCmd, pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList, numChn); vos_mem_copy(&channelToScan[0], &pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[ nNumChanCombinedConc], pChnInfo->numOfChannels * sizeof(tANI_U8)); pChnInfo->ChannelList = &channelToScan[0]; scanReq.BSSType = eCSR_BSS_TYPE_ANY; //Use concurrency values for min/maxChnTime. //We know csrIsAnySessionConnected(pMac) returns TRUE here csrSetDefaultScanTiming(pMac, scanReq.scanType, &scanReq); status = csrScanCopyRequest(pMac, &pQueueScanCmd->u.scanCmd.u.scanRequest, &scanReq); if(!HAL_STATUS_SUCCESS(status)) { if (bMemAlloc) { vos_mem_free(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList); pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL; } if( scanReq.pIEField != NULL) { vos_mem_free(scanReq.pIEField); scanReq.pIEField = NULL; } smsLog( pMac, LOGE, FL(" Failed to get copy csrScanRequest = %d"), status ); return eHAL_STATUS_FAILURE; } /* Clean the local scan variable */ scanReq.ChannelInfo.ChannelList = NULL; scanReq.ChannelInfo.numOfChannels = 0; csrScanFreeRequest(pMac, &scanReq); /* setup the command to scan 2 channels */ pSendScanCmd = pScanCmd; pSendScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = nNumChanCombinedConc; pSendScanCmd->u.scanCmd.u.scanRequest.BSSType = eCSR_BSS_TYPE_ANY; //Use concurrency values for min/maxChnTime. //We know csrIsAnySessionConnected(pMac) returns TRUE here csrSetDefaultScanTiming(pMac, pSendScanCmd->u.scanCmd.u.scanRequest.scanType, &pSendScanCmd->u.scanCmd.u.scanRequest); pSendScanCmd->u.scanCmd.callback = NULL; } else { pSendScanCmd = pScanCmd; pSendScanCmd->u.scanCmd.u.scanRequest.BSSType = eCSR_BSS_TYPE_ANY; //Use concurrency values for min/maxChnTime. //We know csrIsAnySessionConnected(pMac) returns TRUE here csrSetDefaultScanTiming(pMac, pSendScanCmd->u.scanCmd.u.scanRequest.scanType, &pSendScanCmd->u.scanCmd.u.scanRequest); } fNoCmdPending = csrLLIsListEmpty( &pMac->scan.scanCmdPendingList, LL_ACCESS_LOCK ); //Logic Below is as follows // If the scanCmdPendingList is empty then we directly send that command // to smeCommandQueue else we buffer it in our scanCmdPendingList Queue if( fNoCmdPending ) { if (pQueueScanCmd != NULL) { csrLLInsertTail( &pMac->scan.scanCmdPendingList, &pQueueScanCmd->Link, LL_ACCESS_LOCK ); } if (pSendScanCmd != NULL) { return csrQueueSmeCommand(pMac, pSendScanCmd, eANI_BOOLEAN_FALSE); } } else { if (pSendScanCmd != NULL) { csrLLInsertTail( &pMac->scan.scanCmdPendingList, &pSendScanCmd->Link, LL_ACCESS_LOCK ); } if (pQueueScanCmd != NULL) { csrLLInsertTail( &pMac->scan.scanCmdPendingList, &pQueueScanCmd->Link, LL_ACCESS_LOCK ); } } } else { //No concurrency case smsLog( pMac, LOG2, FL("Queuing scan command (reason=%d, roamState=%d" " numOfChannels=%d)"), pScanCmd->u.scanCmd.reason, pMac->roam.neighborRoamInfo[sessionId].neighborRoamState, pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels); return csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); } return ( status ); } #endif /** * csrScan2GOnyRequest() - This function will update the scan request with * only 2.4GHz valid channel list. * @mac_ctx: Pointer to Global MAC structure * @scan_cmd scan cmd * @scan_req scan req * * This function will update the scan request with only 2.4GHz valid channel * list. * * @Return: status of operation */ static eHalStatus csrScan2GOnyRequest(tpAniSirGlobal mac_ctx, tSmeCmd *scan_cmd, tCsrScanRequest *scan_req) { uint8_t idx, lst_sz = 0; VOS_ASSERT(scan_cmd && scan_req); /* To silence the KW tool null check is added */ if ((scan_cmd == NULL) || (scan_req == NULL)) { smsLog(mac_ctx, LOGE, FL(" Scan Cmd or Scan Request is NULL ")); return eHAL_STATUS_INVALID_PARAMETER; } if (eCSR_SCAN_REQUEST_FULL_SCAN != scan_req->requestType) return eHAL_STATUS_SUCCESS; smsLog(mac_ctx, LOG1, FL("Scanning only 2G Channels during first scan")); /* Contsruct valid Supported 2.4 GHz Channel List */ if (NULL == scan_req->ChannelInfo.ChannelList) { scan_req->ChannelInfo.ChannelList = vos_mem_malloc(NUM_2_4GHZ_CHANNELS); if (NULL == scan_req->ChannelInfo.ChannelList) { smsLog(mac_ctx, LOGE, FL("Memory allocation failed.")); return eHAL_STATUS_FAILED_ALLOC; } for (idx = 1; idx <= NUM_2_4GHZ_CHANNELS; idx++) { if (csrIsSupportedChannel(mac_ctx, idx)) { scan_req->ChannelInfo.ChannelList[lst_sz] = idx; lst_sz++; } } } else { for (idx = 0; idx < scan_req->ChannelInfo.numOfChannels; idx++) { if (scan_req->ChannelInfo.ChannelList[idx] <= VOS_24_GHZ_CHANNEL_14 && csrIsSupportedChannel(mac_ctx, scan_req->ChannelInfo.ChannelList[idx])) { scan_req->ChannelInfo.ChannelList[lst_sz] = scan_req->ChannelInfo.ChannelList[idx]; lst_sz++; } } } scan_req->ChannelInfo.numOfChannels = lst_sz; return eHAL_STATUS_SUCCESS; } eHalStatus csrScanRequest(tpAniSirGlobal pMac, tANI_U16 sessionId, tCsrScanRequest *pScanRequest, tANI_U32 *pScanRequestID, csrScanCompleteCallback callback, void *pContext) { eHalStatus status = eHAL_STATUS_FAILURE; tSmeCmd *pScanCmd = NULL; eCsrConnectState ConnectState; if(pScanRequest == NULL) { smsLog( pMac, LOGE, FL(" pScanRequest is NULL")); VOS_ASSERT(0); return status; } /* During group formation, the P2P client scans for GO with the specific SSID. * There will be chances of GO switching to other channels because of scan or * to STA channel in case of STA+GO MCC scenario. So to increase the possibility * of client to find the GO, the dwell time of scan is increased to 100ms. */ if(pScanRequest->p2pSearch) { if ((pScanRequest->SSIDs.numOfSSIDs) && (NULL != pScanRequest->SSIDs.SSIDList)) { //If the scan request is for specific SSId the length of SSID will be //greater than 7 as SSID for p2p search contains "DIRECT-") if(pScanRequest->SSIDs.SSIDList->SSID.length > DIRECT_SSID_LEN) { smsLog( pMac, LOG1, FL("P2P: Increasing the min and max Dwell" " time to %d for specific SSID scan %.*s"), MAX_CHN_TIME_TO_FIND_GO, pScanRequest->SSIDs.SSIDList->SSID.length, pScanRequest->SSIDs.SSIDList->SSID.ssId); pScanRequest->maxChnTime = MAX_CHN_TIME_TO_FIND_GO; pScanRequest->minChnTime = MIN_CHN_TIME_TO_FIND_GO; } } } do { if(pMac->scan.fScanEnable) { pScanCmd = csrGetCommandBuffer(pMac); if(pScanCmd) { vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0); pScanCmd->command = eSmeCommandScan; pScanCmd->sessionId = sessionId; if (pScanCmd->sessionId >= CSR_ROAM_SESSION_MAX) smsLog( pMac, LOGE, FL("Invalid Sme Session ID = %d"), sessionId); pScanCmd->u.scanCmd.callback = callback; pScanCmd->u.scanCmd.pContext = pContext; if(eCSR_SCAN_REQUEST_11D_SCAN == pScanRequest->requestType) { pScanCmd->u.scanCmd.reason = eCsrScan11d1; } else if((eCSR_SCAN_REQUEST_FULL_SCAN == pScanRequest->requestType) || (eCSR_SCAN_P2P_DISCOVERY == pScanRequest->requestType) #ifdef SOFTAP_CHANNEL_RANGE ||(eCSR_SCAN_SOFTAP_CHANNEL_RANGE == pScanRequest->requestType) #endif ) { pScanCmd->u.scanCmd.reason = eCsrScanUserRequest; } else if(eCSR_SCAN_HO_BG_SCAN == pScanRequest->requestType) { pScanCmd->u.scanCmd.reason = eCsrScanBgScan; } else if(eCSR_SCAN_HO_PROBE_SCAN == pScanRequest->requestType) { pScanCmd->u.scanCmd.reason = eCsrScanProbeBss; } else if(eCSR_SCAN_P2P_FIND_PEER == pScanRequest->requestType) { pScanCmd->u.scanCmd.reason = eCsrScanP2PFindPeer; } else { pScanCmd->u.scanCmd.reason = eCsrScanIdleScan; } if(pScanRequest->minChnTime == 0 && pScanRequest->maxChnTime == 0) { //The caller doesn't set the time correctly. Set it here csrSetDefaultScanTiming(pMac, pScanRequest->scanType, pScanRequest); smsLog(pMac, LOG1, FL("Setting default min %d and max %d" " ChnTime"), pScanRequest->minChnTime, pScanRequest->maxChnTime); } #ifdef WLAN_AP_STA_CONCURRENCY if(pScanRequest->restTime == 0) { /* Need to set restTime/min_Ret_time/idle_time only * if at least one session is connected */ if(csrIsAnySessionConnected(pMac)) { pScanRequest->restTime = pMac->roam.configParam.nRestTimeConc; pScanRequest->min_rest_time = pMac->roam.configParam.min_rest_time_conc; pScanRequest->idle_time = pMac->roam.configParam.idle_time_conc; if(pScanRequest->scanType == eSIR_ACTIVE_SCAN) { pScanRequest->maxChnTime = pMac->roam.configParam.nActiveMaxChnTimeConc; pScanRequest->minChnTime = pMac->roam.configParam.nActiveMinChnTimeConc; } else { pScanRequest->maxChnTime = pMac->roam.configParam.nPassiveMaxChnTimeConc; pScanRequest->minChnTime = pMac->roam.configParam.nPassiveMinChnTimeConc; } } } #endif /* Increase dwell time in case P2P Search and Miracast is not present*/ if(pScanRequest->p2pSearch && pScanRequest->ChannelInfo.numOfChannels == P2P_SOCIAL_CHANNELS && (!(pMac->sme.miracast_value))) { pScanRequest->maxChnTime += P2P_SEARCH_DWELL_TIME_INCREASE; } /*For Standalone wlan : channel time will remain the same. For BTC with A2DP up: Channel time = Channel time * 2, if station is not already associated. This has been done to provide a larger scan window for faster connection during btc.Else Scan is seen to take a long time. For BTC with A2DP up: Channel time will not be doubled, if station is already associated. */ status = csrRoamGetConnectState(pMac,sessionId,&ConnectState); if (HAL_STATUS_SUCCESS(status) && pMac->btc.fA2DPUp && (eCSR_ASSOC_STATE_TYPE_INFRA_ASSOCIATED != ConnectState) && (eCSR_ASSOC_STATE_TYPE_IBSS_CONNECTED != ConnectState)) { pScanRequest->maxChnTime = pScanRequest->maxChnTime << 1; pScanRequest->minChnTime = pScanRequest->minChnTime << 1; smsLog( pMac, LOG1, FL("BTC A2DP up, doubling max and min" " ChnTime (Max=%d Min=%d)"), pScanRequest->maxChnTime, pScanRequest->minChnTime); } pScanRequest->maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pScanRequest->minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; //Need to make the following atomic pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around if(pScanRequestID) { *pScanRequestID = pScanCmd->u.scanCmd.scanID; } // If it is the first scan request from HDD, CSR checks if it is for 11d. // If it is not, CSR will save the scan request in the pending cmd queue // & issue an 11d scan request to PE. if (((false == pMac->first_scan_done) && (eCSR_SCAN_REQUEST_11D_SCAN != pScanRequest->requestType)) #ifdef SOFTAP_CHANNEL_RANGE && (eCSR_SCAN_SOFTAP_CHANNEL_RANGE != pScanRequest->requestType) #endif && (eANI_BOOLEAN_FALSE == pMac->scan.fEnableBypass11d) ) { tSmeCmd *p11dScanCmd; tCsrScanRequest scanReq; tCsrChannelInfo *pChnInfo = &scanReq.ChannelInfo; vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0); p11dScanCmd = csrGetCommandBuffer(pMac); if (p11dScanCmd) { tANI_U32 numChn = pMac->scan.baseChannels.numChannels; vos_mem_set(&p11dScanCmd->u.scanCmd, sizeof(tScanCmd), 0); pChnInfo->ChannelList = vos_mem_malloc(numChn); if ( NULL == pChnInfo->ChannelList ) { smsLog(pMac, LOGE, FL("Failed to allocate memory")); status = eHAL_STATUS_FAILURE; break; } vos_mem_copy(pChnInfo->ChannelList, pMac->scan.baseChannels.channelList, numChn); pChnInfo->numOfChannels = (tANI_U8)numChn; p11dScanCmd->command = eSmeCommandScan; p11dScanCmd->u.scanCmd.callback = pMac->scan.callback11dScanDone; p11dScanCmd->u.scanCmd.pContext = NULL; p11dScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; scanReq.BSSType = eCSR_BSS_TYPE_ANY; if ( csrIs11dSupported(pMac) ) { scanReq.scanType = eSIR_PASSIVE_SCAN; scanReq.requestType = eCSR_SCAN_REQUEST_11D_SCAN; p11dScanCmd->u.scanCmd.reason = eCsrScan11d1; scanReq.maxChnTime = pMac->roam.configParam.nPassiveMaxChnTime; scanReq.minChnTime = pMac->roam.configParam.nPassiveMinChnTime; } else { scanReq.scanType = pScanRequest->scanType; scanReq.requestType = eCSR_SCAN_IDLE_MODE_SCAN; p11dScanCmd->u.scanCmd.reason = eCsrScanIdleScan; scanReq.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; scanReq.minChnTime = pMac->roam.configParam.nActiveMinChnTime; scanReq.maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; scanReq.minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; } if (pMac->roam.configParam.nInitialDwellTime) { scanReq.maxChnTime = pMac->roam.configParam.nInitialDwellTime; smsLog(pMac, LOG1, FL("11d scan, updating" "dwell time for first scan %u"), scanReq.maxChnTime); } status = csrScanCopyRequest(pMac, &p11dScanCmd->u.scanCmd.u.scanRequest, &scanReq); //Free the channel list vos_mem_free(pChnInfo->ChannelList); pChnInfo->ChannelList = NULL; if (HAL_STATUS_SUCCESS(status)) { pMac->scan.scanProfile.numOfChannels = p11dScanCmd->u.scanCmd.u.scanRequest. ChannelInfo.numOfChannels; //Start process the command #ifdef WLAN_AP_STA_CONCURRENCY if (!pMac->fScanOffload) status = csrQueueScanRequest(pMac, sessionId, p11dScanCmd); else status = csrQueueSmeCommand(pMac, p11dScanCmd, eANI_BOOLEAN_FALSE); #else status = csrQueueSmeCommand(pMac, p11dScanCmd, eANI_BOOLEAN_FALSE); #endif if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" Failed to send message" " status = %d"), status); break; } } else { smsLog(pMac, LOGE, FL("csrScanCopyRequest failed")); break; } } else { //error smsLog( pMac, LOGE, FL("p11dScanCmd failed") ); break; } } //Scan only 2G Channels if set in ini file //This is mainly to reduce the First Scan duration //Once we turn on Wifi if(pMac->scan.fFirstScanOnly2GChnl && false == pMac->first_scan_done) { status = csrScan2GOnyRequest(pMac, pScanCmd, pScanRequest); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("csrScan2GOnyRequest failed.")); break; } } pMac->first_scan_done = true; if (pMac->roam.configParam.nInitialDwellTime) { pScanRequest->maxChnTime = pMac->roam.configParam.nInitialDwellTime; pMac->roam.configParam.nInitialDwellTime = 0; smsLog(pMac, LOG1, FL("updating dwell time for first scan %u"), pScanRequest->maxChnTime); } status = csrScanCopyRequest(pMac, &pScanCmd->u.scanCmd.u.scanRequest, pScanRequest); /* * Reset the variable after the first scan is queued after * loading the driver. The purpose of this parameter is that * DFS channels are skipped during the first scan after loading * the driver. The above API builds the target scan request in * which this variable is used. */ pMac->roam.configParam.initial_scan_no_dfs_chnl = 0; if(HAL_STATUS_SUCCESS(status)) { tCsrScanRequest *pTempScanReq = &pScanCmd->u.scanCmd.u.scanRequest; pMac->scan.scanProfile.numOfChannels = pTempScanReq->ChannelInfo.numOfChannels; smsLog(pMac, LOG1, FL(" SId=%d scanId=%d" " Scan reason=%u numSSIDs=%d" " numChan=%d P2P search=%d minCT=%d maxCT=%d" " minCBtc=%d maxCBtx=%d uIEFieldLen=%d"), sessionId, pScanCmd->u.scanCmd.scanID, pScanCmd->u.scanCmd.reason, pTempScanReq->SSIDs.numOfSSIDs, pTempScanReq->ChannelInfo.numOfChannels, pTempScanReq->p2pSearch, pTempScanReq->minChnTime, pTempScanReq->maxChnTime, pTempScanReq->minChnTimeBtc, pTempScanReq->maxChnTimeBtc, pTempScanReq->uIEFieldLen); //Start process the command #ifdef WLAN_AP_STA_CONCURRENCY if (!pMac->fScanOffload) status = csrQueueScanRequest(pMac, sessionId, pScanCmd); else status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); #else status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); #endif if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); break; } } else { smsLog( pMac, LOGE, FL(" fail to copy request status = %d"), status ); break; } } else { smsLog( pMac, LOGE, FL(" pScanCmd is NULL")); break; } } else { smsLog( pMac, LOGE, FL("SId: %d Scanning not enabled" " Scan type=%u, numOfSSIDs=%d P2P search=%d"), sessionId, pScanRequest->requestType, pScanRequest->SSIDs.numOfSSIDs, pScanRequest->p2pSearch ); } } while(0); if(!HAL_STATUS_SUCCESS(status) && pScanCmd) { if( eCsrScanIdleScan == pScanCmd->u.scanCmd.reason ) { //Set the flag back for restarting idle scan pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; } smsLog( pMac, LOGE, FL(" SId: %d Failed with status=%d" " Scan reason=%u numOfSSIDs=%d" " P2P search=%d scanId=%d"), sessionId, status, pScanCmd->u.scanCmd.reason, pScanRequest->SSIDs.numOfSSIDs, pScanRequest->p2pSearch, pScanCmd->u.scanCmd.scanID ); csrReleaseCommandScan(pMac, pScanCmd); } return (status); } eHalStatus csrScanRequestResult(tpAniSirGlobal pMac) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pScanCmd; if(pMac->scan.fScanEnable) { pScanCmd = csrGetCommandBuffer(pMac); if(pScanCmd) { pScanCmd->command = eSmeCommandScan; vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0); pScanCmd->u.scanCmd.callback = NULL; pScanCmd->u.scanCmd.pContext = NULL; pScanCmd->u.scanCmd.reason = eCsrScanGetResult; //Need to make the following atomic pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID; //let it wrap around status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); csrReleaseCommandScan(pMac, pScanCmd); } } else { //log error smsLog(pMac, LOGE, FL("can not obtain a common buffer")); status = eHAL_STATUS_RESOURCES; } } return (status); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD eHalStatus csrScanRequestLfrResult(tpAniSirGlobal pMac, tANI_U32 sessionId, csrScanCompleteCallback callback, void *pContext) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pScanCmd; if (pMac->scan.fScanEnable) { pScanCmd = csrGetCommandBuffer(pMac); if (pScanCmd) { pScanCmd->command = eSmeCommandScan; pScanCmd->sessionId = sessionId; vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0); pScanCmd->u.scanCmd.callback = callback; pScanCmd->u.scanCmd.pContext = pContext; pScanCmd->u.scanCmd.reason = eCsrScanGetLfrResult; //Need to make the following atomic pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID; //let it wrap around status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_TRUE); if ( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d\n"), status ); csrReleaseCommandScan(pMac, pScanCmd); } } else { //log error smsLog(pMac, LOGE, FL("can not obtain a common buffer\n")); status = eHAL_STATUS_RESOURCES; } } return (status); } #endif //WLAN_FEATURE_ROAM_SCAN_OFFLOAD eHalStatus csrScanAllChannels(tpAniSirGlobal pMac, eCsrRequestType reqType) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U32 scanId; tCsrScanRequest scanReq; vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0); scanReq.BSSType = eCSR_BSS_TYPE_ANY; scanReq.scanType = eSIR_ACTIVE_SCAN; scanReq.requestType = reqType; scanReq.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; scanReq.minChnTime = pMac->roam.configParam.nActiveMinChnTime; scanReq.maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; scanReq.minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; //Scan with invalid sessionId. //This results in SME using the first available session to scan. status = csrScanRequest(pMac, CSR_SESSION_ID_INVALID, &scanReq, &scanId, NULL, NULL); return (status); } eHalStatus csrIssueRoamAfterLostlinkScan(tpAniSirGlobal pMac, tANI_U32 sessionId, eCsrRoamReason reason) { eHalStatus status = eHAL_STATUS_FAILURE; tScanResultHandle hBSSList = NULL; tCsrScanResultFilter *pScanFilter = NULL; tANI_U32 roamId = 0; tCsrRoamProfile *pProfile = NULL; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } do { smsLog(pMac, LOG1, " csrIssueRoamAfterLostlinkScan called"); if(pSession->fCancelRoaming) { smsLog(pMac, LOGW, " lost link roaming is canceled"); csrScanStartIdleScan(pMac); status = eHAL_STATUS_SUCCESS; break; } //Here is the profile we need to connect to pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) break; vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); if(NULL == pSession->pCurRoamProfile) { pScanFilter->EncryptionType.numEntries = 1; pScanFilter->EncryptionType.encryptionType[0] = eCSR_ENCRYPT_TYPE_NONE; } else { //We have to make a copy of pCurRoamProfile because it will be free inside csrRoamIssueConnect pProfile = vos_mem_malloc(sizeof(tCsrRoamProfile)); if ( NULL == pProfile ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) break; vos_mem_set(pProfile, sizeof(tCsrRoamProfile), 0); status = csrRoamCopyProfile(pMac, pProfile, pSession->pCurRoamProfile); if(!HAL_STATUS_SUCCESS(status)) break; status = csrRoamPrepareFilterFromProfile(pMac, pProfile, pScanFilter); }//We have a profile roamId = GET_NEXT_ROAM_ID(&pMac->roam); if(HAL_STATUS_SUCCESS(status)) { status = csrScanGetResult(pMac, pScanFilter, &hBSSList); if(HAL_STATUS_SUCCESS(status)) { if(eCsrLostLink1 == reason) { //we want to put the last connected BSS to the very beginning, if possible csrMoveBssToHeadFromBSSID(pMac, &pSession->connectedProfile.bssid, hBSSList); } status = csrRoamIssueConnect(pMac, sessionId, pProfile, hBSSList, reason, roamId, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); if(!HAL_STATUS_SUCCESS(status)) { csrScanResultPurge(pMac, hBSSList); } }//Have scan result } }while(0); if(pScanFilter) { //we need to free memory for filter if profile exists csrFreeScanFilter(pMac, pScanFilter); vos_mem_free(pScanFilter); } if(NULL != pProfile) { csrReleaseProfile(pMac, pProfile); vos_mem_free(pProfile); } return (status); } eHalStatus csrScanGetScanChnInfo(tpAniSirGlobal pMac, tANI_U8 sessionId, void *pContext, void *callback, tANI_U32 scanID) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pScanCmd; if(pMac->scan.fScanEnable) { pScanCmd = csrGetCommandBuffer(pMac); if(pScanCmd) { pScanCmd->command = eSmeCommandScan; vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0); pScanCmd->u.scanCmd.callback = callback; pScanCmd->u.scanCmd.pContext = pContext; pScanCmd->u.scanCmd.reason = eCsrScanGetScanChnInfo; if (callback) { //use same scanID as maintained in pAdapter pScanCmd->u.scanCmd.scanID = scanID; } else { //Need to make the following atomic pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around } pScanCmd->sessionId = sessionId; status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); csrReleaseCommandScan(pMac, pScanCmd); } } else { //log error smsLog(pMac, LOGE, FL("can not obtain a common buffer")); status = eHAL_STATUS_RESOURCES; } } return (status); } eHalStatus csrScanHandleFailedLostlink1(tpAniSirGlobal pMac, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, "Lost link scan 1 failed"); if(pSession->fCancelRoaming) { csrScanStartIdleScan(pMac); } else if(pSession->pCurRoamProfile) { //We fail lostlink1 but there may be other BSS in the cached result fit the profile. Give it a try first if(pSession->pCurRoamProfile->SSIDs.numOfSSIDs == 0 || pSession->pCurRoamProfile->SSIDs.numOfSSIDs > 1) { /* Try lost link scan2 */ status = csrScanRequestLostLink2(pMac, sessionId); } else if(!pSession->pCurRoamProfile->ChannelInfo.ChannelList || pSession->pCurRoamProfile->ChannelInfo.ChannelList[0] == 0) { /* Go straight to lost link scan3 */ status = csrScanRequestLostLink3(pMac, sessionId); } else { /* We are done with lost link */ if(csrRoamCompleteRoaming(pMac, sessionId, eANI_BOOLEAN_FALSE, eCSR_ROAM_RESULT_FAILURE)) { csrScanStartIdleScan(pMac); } status = eHAL_STATUS_SUCCESS; } } else { status = csrScanRequestLostLink3(pMac, sessionId); } return (status); } eHalStatus csrScanHandleFailedLostlink2(tpAniSirGlobal pMac, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, "Lost link scan 2 failed"); if(pSession->fCancelRoaming) { csrScanStartIdleScan(pMac); } else if(!pSession->pCurRoamProfile || !pSession->pCurRoamProfile->ChannelInfo.ChannelList || pSession->pCurRoamProfile->ChannelInfo.ChannelList[0] == 0) { /* Try lost link scan3 */ status = csrScanRequestLostLink3(pMac, sessionId); } else { /* We are done with lost link */ if(csrRoamCompleteRoaming(pMac, sessionId, eANI_BOOLEAN_FALSE, eCSR_ROAM_RESULT_FAILURE)) { csrScanStartIdleScan(pMac); } } return (status); } eHalStatus csrScanHandleFailedLostlink3(tpAniSirGlobal pMac, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_SUCCESS; smsLog(pMac, LOGW, "Lost link scan 3 failed"); if(eANI_BOOLEAN_TRUE == csrRoamCompleteRoaming(pMac, sessionId, eANI_BOOLEAN_FALSE, eCSR_ROAM_RESULT_FAILURE)) { /* We are done with lost link */ csrScanStartIdleScan(pMac); } return (status); } //Lostlink1 scan is to actively scan the last connected profile's SSID on all matched BSS channels. //If no roam profile (it should not), it is like lostlinkscan3 eHalStatus csrScanRequestLostLink1( tpAniSirGlobal pMac, tANI_U32 sessionId ) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pCommand = NULL; tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; tCsrScanResultFilter *pScanFilter = NULL; tScanResultHandle hBSSList = NULL; tCsrScanResultInfo *pScanResult = NULL; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, FL(" called")); do { pCommand = csrGetCommandBuffer(pMac); if(!pCommand) { status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); pCommand->command = eSmeCommandScan; pCommand->sessionId = (tANI_U8)sessionId; pCommand->u.scanCmd.reason = eCsrScanLostLink1; pCommand->u.scanCmd.callback = NULL; pCommand->u.scanCmd.pContext = NULL; pCommand->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; pCommand->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime; pCommand->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pCommand->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN; if(pSession->connectedProfile.SSID.length) { pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList = vos_mem_malloc(sizeof(tCsrSSIDInfo)); if ( NULL == pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if(!HAL_STATUS_SUCCESS(status)) { break; } pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs = 1; vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID, &pSession->connectedProfile.SSID, sizeof(tSirMacSSid)); } else { pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs = 0; } if(pSession->pCurRoamProfile) { pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if(!HAL_STATUS_SUCCESS(status)) { break; } vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); status = csrRoamPrepareFilterFromProfile(pMac, pSession->pCurRoamProfile, pScanFilter); if(!HAL_STATUS_SUCCESS(status)) { break; } //Don't change variable status here because whether we can get result or not, the command goes to PE. //The status is also used to indicate whether the command is queued. Not success meaning not queue if(HAL_STATUS_SUCCESS((csrScanGetResult(pMac, pScanFilter, &hBSSList))) && hBSSList) { tANI_U8 i, nChn = 0; pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(WNI_CFG_VALID_CHANNEL_LIST_LEN); if ( NULL == pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if(!HAL_STATUS_SUCCESS(status)) { break; } while(((pScanResult = csrScanResultGetNext(pMac, hBSSList)) != NULL) && nChn < WNI_CFG_VALID_CHANNEL_LIST_LEN) { for(i = 0; i < nChn; i++) { if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] == pScanResult->BssDescriptor.channelId) { break; } } if(i == nChn) { pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[nChn++] = pScanResult->BssDescriptor.channelId; } } //Include the last connected BSS' channel if(csrRoamIsChannelValid(pMac, pSession->connectedProfile.operationChannel)) { for(i = 0; i < nChn; i++) { if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] == pSession->connectedProfile.operationChannel) { break; } } if(i == nChn) { pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[nChn++] = pSession->connectedProfile.operationChannel; } } pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = nChn; } else { if(csrRoamIsChannelValid(pMac, pSession->connectedProfile.operationChannel)) { pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(1); if ( NULL == pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; //just try the last connected channel if(HAL_STATUS_SUCCESS(status)) { pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[0] = pSession->connectedProfile.operationChannel; pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = 1; } else { break; } } } } vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.bssid, bAddr, sizeof(tCsrBssid)); status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); break; } } while( 0 ); if(!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGW, " csrScanRequestLostLink1 failed with status %d", status); if(pCommand) { csrReleaseCommandScan(pMac, pCommand); } status = csrScanHandleFailedLostlink1( pMac, sessionId ); } if(pScanFilter) { csrFreeScanFilter(pMac, pScanFilter); vos_mem_free(pScanFilter); } if(hBSSList) { csrScanResultPurge(pMac, hBSSList); } return( status ); } //Lostlink2 scan is to actively scan the all SSIDs of the last roaming profile's on all matched BSS channels. //Since MAC doesn't support multiple SSID, we scan all SSIDs and filter them afterwards eHalStatus csrScanRequestLostLink2( tpAniSirGlobal pMac, tANI_U32 sessionId ) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; tCsrScanResultFilter *pScanFilter = NULL; tScanResultHandle hBSSList = NULL; tCsrScanResultInfo *pScanResult = NULL; tSmeCmd *pCommand = NULL; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, FL(" called")); do { pCommand = csrGetCommandBuffer(pMac); if(!pCommand) { status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); pCommand->command = eSmeCommandScan; pCommand->sessionId = (tANI_U8)sessionId; pCommand->u.scanCmd.reason = eCsrScanLostLink2; pCommand->u.scanCmd.callback = NULL; pCommand->u.scanCmd.pContext = NULL; pCommand->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; pCommand->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime; pCommand->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pCommand->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN; if(pSession->pCurRoamProfile) { pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) { break; } vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); status = csrRoamPrepareFilterFromProfile(pMac, pSession->pCurRoamProfile, pScanFilter); if(!HAL_STATUS_SUCCESS(status)) { break; } status = csrScanGetResult(pMac, pScanFilter, &hBSSList); if(!HAL_STATUS_SUCCESS(status)) { break; } if(hBSSList) { tANI_U8 i, nChn = 0; pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(WNI_CFG_VALID_CHANNEL_LIST_LEN); if ( NULL == pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) { break; } while(((pScanResult = csrScanResultGetNext(pMac, hBSSList)) != NULL) && nChn < WNI_CFG_VALID_CHANNEL_LIST_LEN) { for(i = 0; i < nChn; i++) { if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] == pScanResult->BssDescriptor.channelId) { break; } } if(i == nChn) { pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[nChn++] = pScanResult->BssDescriptor.channelId; } } pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = nChn; } } vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.bssid, bAddr, sizeof(tCsrBssid)); //Put to the head in pending queue status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_TRUE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); break; } } while( 0 ); if(!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGW, " csrScanRequestLostLink2 failed with status %d", status); if(pCommand) { csrReleaseCommandScan(pMac, pCommand); } status = csrScanHandleFailedLostlink2( pMac, sessionId ); } if(pScanFilter) { csrFreeScanFilter(pMac, pScanFilter); vos_mem_free(pScanFilter); } if(hBSSList) { csrScanResultPurge(pMac, hBSSList); } return( status ); } //To actively scan all valid channels eHalStatus csrScanRequestLostLink3( tpAniSirGlobal pMac, tANI_U32 sessionId ) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pCommand; tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; smsLog(pMac, LOGW, FL(" called")); do { pCommand = csrGetCommandBuffer(pMac); if(!pCommand) { status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); pCommand->command = eSmeCommandScan; pCommand->sessionId = (tANI_U8)sessionId; pCommand->u.scanCmd.reason = eCsrScanLostLink3; pCommand->u.scanCmd.callback = NULL; pCommand->u.scanCmd.pContext = NULL; pCommand->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; pCommand->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime; pCommand->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pCommand->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN; vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.bssid, bAddr, sizeof(tCsrBssid)); //Put to the head of pending queue status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_TRUE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); break; } } while( 0 ); if(!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGW, " csrScanRequestLostLink3 failed with status %d", status); if(csrRoamCompleteRoaming(pMac, sessionId, eANI_BOOLEAN_FALSE, eCSR_ROAM_RESULT_FAILURE)) { csrScanStartIdleScan(pMac); } if(pCommand) { csrReleaseCommandScan(pMac, pCommand); } } return( status ); } eHalStatus csrScanHandleSearchForSSID(tpAniSirGlobal pMac, tSmeCmd *pCommand) { eHalStatus status = eHAL_STATUS_FAILURE; tScanResultHandle hBSSList = CSR_INVALID_SCANRESULT_HANDLE; tCsrScanResultFilter *pScanFilter = NULL; tCsrRoamProfile *pProfile = pCommand->u.scanCmd.pToRoamProfile; tANI_U32 sessionId = pCommand->sessionId; do { #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD /* If this scan is for LFR */ if (pMac->roam.neighborRoamInfo[sessionId].uOsRequestedHandoff) { /* Notify LFR state m/c */ if (eHAL_STATUS_SUCCESS != csrNeighborRoamSssidScanDone(pMac, sessionId, eHAL_STATUS_SUCCESS)) { csrNeighborRoamStartLfrScan(pMac, sessionId); } status = eHAL_STATUS_SUCCESS; break; } #endif //If there is roam command waiting, ignore this roam because the newer roam command is the one to execute if(csrIsRoamCommandWaitingForSession(pMac, sessionId)) { smsLog(pMac, LOGW, FL(" aborts because roam command waiting")); break; } if(pProfile == NULL) break; pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) break; vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); status = csrRoamPrepareFilterFromProfile(pMac, pProfile, pScanFilter); if(!HAL_STATUS_SUCCESS(status)) break; status = csrScanGetResult(pMac, pScanFilter, &hBSSList); if(!HAL_STATUS_SUCCESS(status)) break; if (pMac->roam.roamSession[sessionId].connectState == eCSR_ASSOC_STATE_TYPE_INFRA_DISCONNECTING) { smsLog(pMac, LOGE, FL("upper layer issued disconnetion")); status = eHAL_STATUS_FAILURE; break; } status = csrRoamIssueConnect(pMac, sessionId, pProfile, hBSSList, eCsrHddIssued, pCommand->u.scanCmd.roamId, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); if(!HAL_STATUS_SUCCESS(status)) { break; } }while(0); if(!HAL_STATUS_SUCCESS(status)) { if(CSR_INVALID_SCANRESULT_HANDLE != hBSSList) { csrScanResultPurge(pMac, hBSSList); } //We haven't done anything to this profile csrRoamCallCallback(pMac, sessionId, NULL, pCommand->u.scanCmd.roamId, eCSR_ROAM_ASSOCIATION_FAILURE, eCSR_ROAM_RESULT_FAILURE); //In case we have nothing else to do, restart idle scan if(csrIsConnStateDisconnected(pMac, sessionId) && !csrIsRoamCommandWaiting(pMac)) { status = csrScanStartIdleScan(pMac); } } if (pScanFilter) { csrFreeScanFilter(pMac, pScanFilter); vos_mem_free(pScanFilter); } return (status); } eHalStatus csrScanHandleSearchForSSIDFailure(tpAniSirGlobal pMac, tSmeCmd *pCommand) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U32 sessionId = pCommand->sessionId; tCsrRoamProfile *pProfile = pCommand->u.scanCmd.pToRoamProfile; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if (!pSession) { smsLog(pMac, LOGE, FL("Session %d not found"), sessionId); return eHAL_STATUS_FAILURE; } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD /* If this scan is for LFR */ if (pMac->roam.neighborRoamInfo[sessionId].uOsRequestedHandoff) { /* Notify LFR state m/c */ if (eHAL_STATUS_SUCCESS != csrNeighborRoamSssidScanDone(pMac, sessionId, eHAL_STATUS_FAILURE)) { csrNeighborRoamStartLfrScan(pMac, sessionId); } return eHAL_STATUS_SUCCESS; } #endif #if defined(WLAN_DEBUG) if(pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs == 1) { char str[36]; vos_mem_copy(str, pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID.ssId, pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID.length); str[pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID.length] = 0; smsLog(pMac, LOGW, FL(" SSID = %s"), str); } #endif //Check whether it is for start ibss. No need to do anything if it is a JOIN request if(pProfile && CSR_IS_START_IBSS(pProfile)) { status = csrRoamIssueConnect(pMac, sessionId, pProfile, NULL, eCsrHddIssued, pCommand->u.scanCmd.roamId, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); if(!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("failed to issue startIBSS command with status = 0x%08X"), status); csrRoamCallCallback(pMac, sessionId, NULL, pCommand->u.scanCmd.roamId, eCSR_ROAM_FAILED, eCSR_ROAM_RESULT_FAILURE); } } else { eCsrRoamResult roamResult = eCSR_ROAM_RESULT_FAILURE; if(csrIsConnStateDisconnected(pMac, sessionId) && !csrIsRoamCommandWaitingForSession(pMac, sessionId)) { status = csrScanStartIdleScan(pMac); } if((NULL == pProfile) || !csrIsBssTypeIBSS(pProfile->BSSType)) { //Only indicate assoc_completion if we indicate assoc_start. if(pSession->bRefAssocStartCnt > 0) { tCsrRoamInfo *pRoamInfo = NULL, roamInfo; vos_mem_set(&roamInfo, sizeof(tCsrRoamInfo), 0); pRoamInfo = &roamInfo; if(pCommand->u.roamCmd.pRoamBssEntry) { tCsrScanResult *pScanResult = GET_BASE_ADDR(pCommand->u.roamCmd.pRoamBssEntry, tCsrScanResult, Link); roamInfo.pBssDesc = &pScanResult->Result.BssDescriptor; } roamInfo.statusCode = pSession->joinFailStatusCode.statusCode; roamInfo.reasonCode = pSession->joinFailStatusCode.reasonCode; pSession->bRefAssocStartCnt--; csrRoamCallCallback(pMac, sessionId, pRoamInfo, pCommand->u.scanCmd.roamId, eCSR_ROAM_ASSOCIATION_COMPLETION, eCSR_ROAM_RESULT_FAILURE); } else { csrRoamCallCallback(pMac, sessionId, NULL, pCommand->u.scanCmd.roamId, eCSR_ROAM_ASSOCIATION_FAILURE, eCSR_ROAM_RESULT_FAILURE); } } else { roamResult = eCSR_ROAM_RESULT_IBSS_START_FAILED; } csrRoamCompletion(pMac, sessionId, NULL, pCommand, roamResult, eANI_BOOLEAN_FALSE); } return (status); } //After scan for cap changes, issue a roaming command to either reconnect to the AP or pick another one to connect eHalStatus csrScanHandleCapChangeScanComplete(tpAniSirGlobal pMac, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tScanResultHandle hBSSList = NULL; tCsrScanResultFilter *pScanFilter = NULL; tANI_U32 roamId = 0; tCsrRoamProfile *pProfile = NULL; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); do { //Here is the profile we need to connect to pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) break; vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); if (NULL == pSession) break; if (NULL == pSession->pCurRoamProfile) { pScanFilter->EncryptionType.numEntries = 1; pScanFilter->EncryptionType.encryptionType[0] = eCSR_ENCRYPT_TYPE_NONE; } else { //We have to make a copy of pCurRoamProfile because it will be free inside csrRoamIssueConnect pProfile = vos_mem_malloc(sizeof(tCsrRoamProfile)); if ( NULL == pProfile ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if(!HAL_STATUS_SUCCESS(status)) break; status = csrRoamCopyProfile(pMac, pProfile, pSession->pCurRoamProfile); if(!HAL_STATUS_SUCCESS(status)) break; status = csrRoamPrepareFilterFromProfile(pMac, pProfile, pScanFilter); }//We have a profile roamId = GET_NEXT_ROAM_ID(&pMac->roam); if(HAL_STATUS_SUCCESS(status)) { status = csrScanGetResult(pMac, pScanFilter, &hBSSList); if(HAL_STATUS_SUCCESS(status)) { //we want to put the last connected BSS to the very beginning, if possible csrMoveBssToHeadFromBSSID(pMac, &pSession->connectedProfile.bssid, hBSSList); status = csrRoamIssueConnect(pMac, sessionId, pProfile, hBSSList, eCsrCapsChange, 0, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); if(!HAL_STATUS_SUCCESS(status)) { csrScanResultPurge(pMac, hBSSList); } }//Have scan result else { smsLog(pMac, LOGW, FL("cannot find matching BSS of " MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pSession->connectedProfile.bssid)); //Disconnect csrRoamDisconnectInternal(pMac, sessionId, eCSR_DISCONNECT_REASON_UNSPECIFIED); } } }while(0); if(pScanFilter) { csrFreeScanFilter(pMac, pScanFilter); vos_mem_free(pScanFilter); } if(NULL != pProfile) { csrReleaseProfile(pMac, pProfile); vos_mem_free(pProfile); } return (status); } eHalStatus csrScanResultPurge(tpAniSirGlobal pMac, tScanResultHandle hScanList) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; tScanResultList *pScanList = (tScanResultList *)hScanList; if(pScanList) { status = csrLLScanPurgeResult(pMac, &pScanList->List); csrLLClose(&pScanList->List); vos_mem_free(pScanList); } return (status); } /** * csr_get_altered_rssi() - Artificially increase/decrease RSSI * @mac_ctx: Global MAC Context pointer. * @rssi: Actual RSSI of the AP. * @channel_id: Channel on which the AP is parked. * @bssid: BSSID of the AP to connect to. * * This routine will apply the boost and penalty parameters * if the channel_id is of 5G band and it will also apply * the preferred bssid score if there is a match between * the bssid and the global preferred bssid list. * * Return: The modified RSSI Value */ static int csr_get_altered_rssi(tpAniSirGlobal mac_ctx, int rssi, uint8_t channel_id, tCsrBssid *bssid) { int modified_rssi; int boost_factor; int penalty_factor; int i; struct roam_ext_params *roam_params; tCsrBssid local_bssid; modified_rssi = rssi; vos_mem_set(&local_bssid, 0, VOS_MAC_ADDR_SIZE); if (bssid) vos_mem_copy(&local_bssid, bssid, VOS_MAC_ADDR_SIZE); roam_params = &mac_ctx->roam.configParam.roam_params; /* * If the 5G pref feature is enabled, apply the roaming * parameters to boost or penalize the rssi. * Boost Factor = boost_factor * (Actual RSSI - boost Threshold) * Penalty Factor = penalty factor * (penalty threshold - Actual RSSI) */ if (CSR_IS_SELECT_5G_PREFERRED(mac_ctx) && CSR_IS_CHANNEL_5GHZ(channel_id)) { if (rssi > roam_params->raise_rssi_thresh_5g) { /* Check and boost the threshold*/ boost_factor = roam_params->raise_factor_5g * (rssi - roam_params->raise_rssi_thresh_5g); /* Check and penalize the threshold */ modified_rssi += CSR_MIN(roam_params->max_raise_rssi_5g, boost_factor); } else if(rssi < roam_params->drop_rssi_thresh_5g) { penalty_factor = roam_params->drop_factor_5g * (roam_params->drop_rssi_thresh_5g - rssi); modified_rssi -= CSR_MAX(roam_params->max_drop_rssi_5g, penalty_factor); } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, FL("5G BSSID("MAC_ADDRESS_STR") AR:%d, MR:%d, ch=%d"), MAC_ADDR_ARRAY(local_bssid), rssi, modified_rssi, channel_id); } /* * Check if there are preferred bssid and then apply the * preferred score */ if (roam_params->num_bssid_favored) { for (i=0; i<roam_params->num_bssid_favored; i++) { if (!csrIsMacAddressEqual(mac_ctx, &roam_params->bssid_favored[i], bssid)) continue; modified_rssi += roam_params->bssid_favored_factor[i]; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, FL("Pref: ("MAC_ADDRESS_STR") AR:%d, MR:%d, ch=%d"), MAC_ADDR_ARRAY(local_bssid), rssi, modified_rssi, channel_id); } } return modified_rssi; } /** * csrGetBssPreferValue() - Get BSS Preference Value * @pMac: Global MAC Context pointer. * @rssi: Actual RSSI of the AP. * @bssid: BSSID of the AP to connect to. * @channel_id: Channel on which the AP is parked. * * * This routine helps in determining the preference value * of a particular BSS in the scan result which is further * used in the sorting logic of the final candidate AP's. * * Return: The preference Value for a BSS. */ static tANI_U32 csrGetBssPreferValue(tpAniSirGlobal pMac, int rssi, tCsrBssid *bssid, int channel_id) { tANI_U32 ret = 0; int i, modified_rssi; /* * The RSSI does not get modified in case the 5G * preference or preferred BSSID is not applicable */ modified_rssi = csr_get_altered_rssi(pMac, rssi, channel_id, bssid); i = CSR_NUM_RSSI_CAT - 1; while(i >= 0) { if(modified_rssi >= pMac->roam.configParam.RSSICat[i]) { ret = pMac->roam.configParam.BssPreferValue[i]; break; } i--; }; return (ret); } //Return a CapValue base on the capabilities of a BSS static tANI_U32 csrGetBssCapValue(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes) { tANI_U32 ret = CSR_BSS_CAP_VALUE_NONE; #if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_ESE) || defined(FEATURE_WLAN_LFR) if(CSR_IS_ROAM_PREFER_5GHZ(pMac) || CSR_IS_SELECT_5G_PREFERRED(pMac)) { if((pBssDesc) && CSR_IS_CHANNEL_5GHZ(pBssDesc->channelId)) { ret += CSR_BSS_CAP_VALUE_5GHZ; } } #endif /* if strict select 5GHz is non-zero then ignore the capability checking */ if (pIes && !CSR_IS_SELECT_5GHZ_MARGIN(pMac)) { //We only care about 11N capability if (pIes->VHTCaps.present) ret += CSR_BSS_CAP_VALUE_VHT; else if (pIes->HTCaps.present) ret += CSR_BSS_CAP_VALUE_HT; if(CSR_IS_QOS_BSS(pIes)) { ret += CSR_BSS_CAP_VALUE_WMM; //Give advantage to UAPSD if(CSR_IS_UAPSD_BSS(pIes)) { ret += CSR_BSS_CAP_VALUE_UAPSD; } } } return (ret); } /** * csr_is_better_rssi() - Is bss1 better than bss2 * @mac_ctx: Global MAC Context pointer. * @bss1: Pointer to the first BSS. * @bss2: Pointer to the second BSS. * * * This routine helps in determining the preference value * of a particular BSS in the scan result which is further * used in the sorting logic of the final candidate AP's. * * Return: true, if bss1 is better than bss2 * false, if bss2 is better than bss1. */ static bool csr_is_better_rssi(tpAniSirGlobal mac_ctx, tCsrScanResult *bss1, tCsrScanResult *bss2) { bool ret; int rssi1, rssi2; rssi1 = bss1->Result.BssDescriptor.rssi; rssi2 = bss2->Result.BssDescriptor.rssi; /* * Apply the boost and penlty logic and check * which is the best RSSI */ rssi1 = csr_get_altered_rssi(mac_ctx, rssi1, bss1->Result.BssDescriptor.channelId, &bss1->Result.BssDescriptor.bssId); rssi2 = csr_get_altered_rssi(mac_ctx, rssi2, bss2->Result.BssDescriptor.channelId, &bss2->Result.BssDescriptor.bssId); if (CSR_IS_BETTER_RSSI(rssi1, rssi2)) ret = true; else ret = false; return ret; } /* To check whether pBss1 is better than pBss2 */ static tANI_BOOLEAN csrIsBetterBss(tpAniSirGlobal mac_ctx, tCsrScanResult *pBss1, tCsrScanResult *pBss2) { tANI_BOOLEAN ret; if(CSR_IS_BETTER_PREFER_VALUE(pBss1->preferValue, pBss2->preferValue)) ret = eANI_BOOLEAN_TRUE; else if(CSR_IS_EQUAL_PREFER_VALUE (pBss1->preferValue, pBss2->preferValue)) { if(CSR_IS_BETTER_CAP_VALUE(pBss1->capValue, pBss2->capValue)) ret = eANI_BOOLEAN_TRUE; else if (CSR_IS_EQUAL_CAP_VALUE (pBss1->capValue, pBss2->capValue)) { if (csr_is_better_rssi(mac_ctx, pBss1, pBss2)) ret = eANI_BOOLEAN_TRUE; else ret = eANI_BOOLEAN_FALSE; } else ret = eANI_BOOLEAN_FALSE; } else ret = eANI_BOOLEAN_FALSE; return (ret); } #ifdef FEATURE_WLAN_LFR //Add the channel to the occupiedChannels array static void csrScanAddToOccupiedChannels( tpAniSirGlobal pMac, tCsrScanResult *pResult, tANI_U8 sessionId, tCsrChannel *pOccupiedChannels, tDot11fBeaconIEs *pIes) { eHalStatus status; tANI_U8 channel; tANI_U8 numOccupiedChannels = pOccupiedChannels->numChannels; tANI_U8 *pOccupiedChannelList = pOccupiedChannels->channelList; channel = pResult->Result.BssDescriptor.channelId; if (!csrIsChannelPresentInList(pOccupiedChannelList, numOccupiedChannels, channel) && csrNeighborRoamConnectedProfileMatch(pMac, sessionId, pResult, pIes)) { status = csrAddToChannelListFront(pOccupiedChannelList, numOccupiedChannels, channel); if(HAL_STATUS_SUCCESS(status)) { pOccupiedChannels->numChannels++; smsLog(pMac, LOG2, FL("Added channel %d to the list (count=%d)"), channel, pOccupiedChannels->numChannels); if (pOccupiedChannels->numChannels > CSR_BG_SCAN_OCCUPIED_CHANNEL_LIST_LEN) pOccupiedChannels->numChannels = CSR_BG_SCAN_OCCUPIED_CHANNEL_LIST_LEN; } } } #endif //Put the BSS into the scan result list //pIes can not be NULL static void csrScanAddResult(tpAniSirGlobal pMac, tCsrScanResult *pResult, tDot11fBeaconIEs *pIes, tANI_U32 sessionId) { #ifdef FEATURE_WLAN_LFR tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo[sessionId]; #endif tCsrBssid *bssid = &pResult->Result.BssDescriptor.bssId; uint8_t channel_id = pResult->Result.BssDescriptor.channelId; pResult->preferValue = csrGetBssPreferValue(pMac, (int)pResult->Result.BssDescriptor.rssi, bssid, channel_id); pResult->capValue = csrGetBssCapValue(pMac, &pResult->Result.BssDescriptor, pIes); csrLLInsertTail( &pMac->scan.scanResultList, &pResult->Link, LL_ACCESS_LOCK ); #ifdef FEATURE_WLAN_LFR if(0 == pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels) { /* Build the occupied channel list, only if "gNeighborScanChannelList" is NOT set in the cfg.ini file */ csrScanAddToOccupiedChannels(pMac, pResult, sessionId, &pMac->scan.occupiedChannels[sessionId], pIes); } #endif } eHalStatus csrScanGetResult(tpAniSirGlobal pMac, tCsrScanResultFilter *pFilter, tScanResultHandle *phResult) { eHalStatus status; tScanResultList *pRetList; tCsrScanResult *pResult, *pBssDesc; tANI_U32 count = 0; tListElem *pEntry; tANI_U32 bssLen, allocLen; eCsrEncryptionType uc = eCSR_ENCRYPT_TYPE_NONE, mc = eCSR_ENCRYPT_TYPE_NONE; eCsrAuthType auth = eCSR_AUTH_TYPE_OPEN_SYSTEM; tDot11fBeaconIEs *pIes, *pNewIes; tANI_BOOLEAN fMatch; tANI_U16 i = 0; struct roam_ext_params *roam_params = NULL; if(phResult) { *phResult = CSR_INVALID_SCANRESULT_HANDLE; } if (pMac->roam.configParam.nSelect5GHzMargin || CSR_IS_SELECT_5G_PREFERRED(pMac)) { pMac->scan.inScanResultBestAPRssi = -128; roam_params = &pMac->roam.configParam.roam_params; #ifdef WLAN_DEBUG_ROAM_OFFLOAD VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("nSelect5GHzMargin")); #endif csrLLLock(&pMac->scan.scanResultList); /* For 5G preference feature, there is no * need to check the filter match and also re-program the * RSSI bucket categories, since we use the RSSI values * while setting the preference value for the BSS. * There is no need to check the match for roaming since * it is already done.*/ if(!CSR_IS_SELECT_5G_PREFERRED(pMac)) { /* Find out the best AP Rssi going thru the scan results */ pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK); while ( NULL != pEntry) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); fMatch = FALSE; if (pFilter) for(i = 0; i < pFilter->SSIDs.numOfSSIDs; i++) { fMatch = csrIsSsidMatch( pMac, pFilter->SSIDs.SSIDList[i].SSID.ssId, pFilter->SSIDs.SSIDList[i].SSID.length, pBssDesc->Result.ssId.ssId, pBssDesc->Result.ssId.length, eANI_BOOLEAN_TRUE ); if (fMatch) { pIes = (tDot11fBeaconIEs *)( pBssDesc->Result.pvIes ); //At this time, pBssDescription->Result.pvIes may be NULL if( !pIes && (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, &pBssDesc->Result.BssDescriptor, &pIes))) ) { continue; } smsLog(pMac, LOG1, FL("SSID Matched")); if ( pFilter->bOSENAssociation ) { fMatch = TRUE; } else { #ifdef WLAN_FEATURE_11W fMatch = csrIsSecurityMatch(pMac, &pFilter->authType, &pFilter->EncryptionType, &pFilter->mcEncryptionType, &pFilter->MFPEnabled, &pFilter->MFPRequired, &pFilter->MFPCapable, &pBssDesc->Result.BssDescriptor, pIes, NULL, NULL, NULL ); #else fMatch = csrIsSecurityMatch(pMac, &pFilter->authType, &pFilter->EncryptionType, &pFilter->mcEncryptionType, NULL, NULL, NULL, &pBssDesc->Result.BssDescriptor, pIes, NULL, NULL, NULL ); #endif } if ((pBssDesc->Result.pvIes == NULL) && pIes) vos_mem_free(pIes); if (fMatch) smsLog(pMac, LOG1, FL(" Security Matched")); } } if (fMatch && (pBssDesc->Result.BssDescriptor.rssi > pMac->scan.inScanResultBestAPRssi)) { smsLog(pMac, LOG1, FL("Best AP Rssi changed from %d to %d"), pMac->scan.inScanResultBestAPRssi, pBssDesc->Result.BssDescriptor.rssi); pMac->scan.inScanResultBestAPRssi = pBssDesc->Result.BssDescriptor.rssi; } pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); } } if ((-128 != pMac->scan.inScanResultBestAPRssi) || CSR_IS_SELECT_5G_PREFERRED(pMac)) { smsLog(pMac, LOG1, FL("Best AP Rssi is %d"), pMac->scan.inScanResultBestAPRssi); /* Modify Rssi category based on best AP Rssi */ if (-128 != pMac->scan.inScanResultBestAPRssi) csrAssignRssiForCategory(pMac, pMac->scan.inScanResultBestAPRssi, pMac->roam.configParam.bCatRssiOffset); pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK); while ( NULL != pEntry) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); /* re-assign preference value based on (modified rssi bucket (or) * prefer 5G feature.*/ pBssDesc->preferValue = csrGetBssPreferValue(pMac, (int)pBssDesc->Result.BssDescriptor.rssi, &pBssDesc->Result.BssDescriptor.bssId, pBssDesc->Result.BssDescriptor.channelId); smsLog(pMac, LOG2, FL("BSSID("MAC_ADDRESS_STR ") Rssi(%d) Chnl(%d) PrefVal(%u) SSID=%.*s"), MAC_ADDR_ARRAY(pBssDesc->Result.BssDescriptor.bssId), pBssDesc->Result.BssDescriptor.rssi, pBssDesc->Result.BssDescriptor.channelId, pBssDesc->preferValue, pBssDesc->Result.ssId.length, pBssDesc->Result.ssId.ssId); pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); } } csrLLUnlock(&pMac->scan.scanResultList); } pRetList = vos_mem_malloc(sizeof(tScanResultList)); if ( NULL == pRetList ) status = eHAL_STATUS_FAILURE; else { status = eHAL_STATUS_SUCCESS; vos_mem_set(pRetList, sizeof(tScanResultList), 0); csrLLOpen(pMac->hHdd, &pRetList->List); pRetList->pCurEntry = NULL; csrLLLock(&pMac->scan.scanResultList); pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_NOLOCK ); while( pEntry ) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); pIes = (tDot11fBeaconIEs *)( pBssDesc->Result.pvIes ); /* * If pBssDesc->Result.pvIes is NULL, we need to free any memory * allocated by csrMatchBSS for any error condition, otherwise, * it will be freed later. */ fMatch = eANI_BOOLEAN_FALSE; pNewIes = NULL; if(pFilter) { fMatch = csrMatchBSS(pMac, &pBssDesc->Result.BssDescriptor, pFilter, &auth, &uc, &mc, &pIes); #ifdef WLAN_DEBUG_ROAM_OFFLOAD VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, FL("csrMatchBSS fmatch %d"), fMatch); #endif if( NULL != pIes ) { //Only save it when matching if(fMatch) { if( !pBssDesc->Result.pvIes ) { //csrMatchBSS allocates the memory. Simply pass it and it is freed later pNewIes = pIes; } else { //The pIes is allocated by someone else. make a copy //Only to save parsed IEs if caller provides a filter. Most likely the caller //is using to for association, hence save the parsed IEs pNewIes = vos_mem_malloc(sizeof(tDot11fBeaconIEs)); if ( NULL == pNewIes ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if ( HAL_STATUS_SUCCESS( status ) ) { vos_mem_copy(pNewIes, pIes, sizeof( tDot11fBeaconIEs )); } else { smsLog(pMac, LOGE, FL(" fail to allocate memory for IEs")); //Need to free memory allocated by csrMatchBSS if( !pBssDesc->Result.pvIes ) { vos_mem_free(pIes); } break; } } }//fMatch else if( !pBssDesc->Result.pvIes ) { vos_mem_free(pIes); } } } if(NULL == pFilter || fMatch) { bssLen = pBssDesc->Result.BssDescriptor.length + sizeof(pBssDesc->Result.BssDescriptor.length); allocLen = sizeof( tCsrScanResult ) + bssLen; pResult = vos_mem_malloc(allocLen); if ( NULL == pResult ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if(!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL(" fail to allocate memory for scan result, len=%d"), allocLen); if(pNewIes) { vos_mem_free(pNewIes); } break; } vos_mem_set(pResult, allocLen, 0); pResult->capValue = pBssDesc->capValue; pResult->preferValue = pBssDesc->preferValue; pResult->ucEncryptionType = uc; pResult->mcEncryptionType = mc; pResult->authType = auth; pResult->Result.ssId = pBssDesc->Result.ssId; pResult->Result.timer = pBssDesc->Result.timer; //save the pIes for later use pResult->Result.pvIes = pNewIes; //save bss description vos_mem_copy(&pResult->Result.BssDescriptor, &pBssDesc->Result.BssDescriptor, bssLen); //No need to lock pRetList because it is locally allocated and no outside can access it at this time if(csrLLIsListEmpty(&pRetList->List, LL_ACCESS_NOLOCK)) { csrLLInsertTail(&pRetList->List, &pResult->Link, LL_ACCESS_NOLOCK); } else { //To sort the list tListElem *pTmpEntry; tCsrScanResult *pTmpResult; pTmpEntry = csrLLPeekHead(&pRetList->List, LL_ACCESS_NOLOCK); while(pTmpEntry) { pTmpResult = GET_BASE_ADDR( pTmpEntry, tCsrScanResult, Link ); if(csrIsBetterBss(pMac, pResult, pTmpResult)) { csrLLInsertEntry(&pRetList->List, pTmpEntry, &pResult->Link, LL_ACCESS_NOLOCK); //To indicate we are done pResult = NULL; break; } pTmpEntry = csrLLNext(&pRetList->List, pTmpEntry, LL_ACCESS_NOLOCK); } if(pResult != NULL) { /* This one is'nt better than anyone or the first one */ csrLLInsertTail(&pRetList->List, &pResult->Link, LL_ACCESS_NOLOCK); } } count++; } pEntry = csrLLNext( &pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK ); }//while csrLLUnlock(&pMac->scan.scanResultList); smsLog(pMac, LOG2, FL("return %d BSS"), csrLLCount(&pRetList->List)); if( !HAL_STATUS_SUCCESS(status) || (phResult == NULL) ) { //Fail or No one wants the result. csrScanResultPurge(pMac, (tScanResultHandle)pRetList); } else { if(0 == count) { //We are here meaning the there is no match csrLLClose(&pRetList->List); vos_mem_free(pRetList); status = eHAL_STATUS_E_NULL_VALUE; } else if(phResult) { *phResult = pRetList; } } }//Allocated pRetList return (status); } /* * NOTE: This routine is being added to make * sure that scan results are not being flushed * while roaming. If the scan results are flushed, * we are unable to recover from * csrRoamRoamingStateDisassocRspProcessor. * If it is needed to remove this routine, * first ensure that we recover gracefully from * csrRoamRoamingStateDisassocRspProcessor if * csrScanGetResult returns with a failure because * of not being able to find the roaming BSS. */ tANI_U8 csrScanFlushDenied(tpAniSirGlobal pMac, tANI_U8 sessionId) { switch(pMac->roam.neighborRoamInfo[sessionId].neighborRoamState) { case eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN: case eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING: case eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE: case eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING: return (pMac->roam.neighborRoamInfo[sessionId].neighborRoamState); default: return 0; } } eHalStatus csrScanFlushResult(tpAniSirGlobal pMac, tANI_U8 sessionId) { tANI_U8 isFlushDenied = csrScanFlushDenied(pMac, sessionId); eHalStatus status = eHAL_STATUS_SUCCESS; tSirMbMsg *pMsg; tANI_U16 msgLen; if (isFlushDenied) { smsLog(pMac, LOGW, "%s: scan flush denied in roam state %d", __func__, isFlushDenied); return eHAL_STATUS_FAILURE; } /* prepare and send clear cached scan results msg to lim */ msgLen = (tANI_U16)(sizeof( tSirMbMsg )); pMsg = vos_mem_malloc(msgLen); if ( NULL != pMsg ) { vos_mem_set((void *)pMsg, msgLen, 0); pMsg->type = pal_cpu_to_be16((tANI_U16)eWNI_SME_CLEAR_LIM_SCAN_CACHE); pMsg->msgLen = pal_cpu_to_be16(msgLen); palSendMBMessage(pMac->hHdd, pMsg); } else { status = eHAL_STATUS_FAILED_ALLOC; } csrLLScanPurgeResult( pMac, &pMac->scan.tempScanResults ); csrLLScanPurgeResult( pMac, &pMac->scan.scanResultList ); return( status ); } eHalStatus csrScanFlushSelectiveResult(tpAniSirGlobal pMac, v_BOOL_t flushP2P) { eHalStatus status = eHAL_STATUS_SUCCESS; tListElem *pEntry,*pFreeElem; tCsrScanResult *pBssDesc; tDblLinkList *pList = &pMac->scan.scanResultList; csrLLLock(pList); pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK ); while( pEntry != NULL) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); if( flushP2P == vos_mem_compare( pBssDesc->Result.ssId.ssId, "DIRECT-", 7) ) { pFreeElem = pEntry; pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); csrLLRemoveEntry(pList, pFreeElem, LL_ACCESS_NOLOCK); csrFreeScanResultEntry( pMac, pBssDesc ); continue; } pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); } csrLLUnlock(pList); return (status); } void csrScanFlushBssEntry(tpAniSirGlobal pMac, tpSmeCsaOffloadInd pCsaOffloadInd) { tListElem *pEntry,*pFreeElem; tCsrScanResult *pBssDesc; tDblLinkList *pList = &pMac->scan.scanResultList; csrLLLock(pList); pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK ); while( pEntry != NULL) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); if( vos_mem_compare(pBssDesc->Result.BssDescriptor.bssId, pCsaOffloadInd->bssId, sizeof(tSirMacAddr)) ) { pFreeElem = pEntry; pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); csrLLRemoveEntry(pList, pFreeElem, LL_ACCESS_NOLOCK); csrFreeScanResultEntry( pMac, pBssDesc ); smsLog( pMac, LOG1, FL("Removed BSS entry:%pM"), pCsaOffloadInd->bssId); continue; } pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); } csrLLUnlock(pList); } /** * csrCheck11dChannel * *FUNCTION: * This function is called from csrScanFilterResults function and * compare channel number with given channel list. * *LOGIC: * Check Scan result channel number with CFG channel list * *ASSUMPTIONS: * * *NOTE: * * @param channelId channel number * @param pChannelList Pointer to channel list * @param numChannels Number of channel in channel list * * @return Status */ eHalStatus csrCheck11dChannel(tANI_U8 channelId, tANI_U8 *pChannelList, tANI_U32 numChannels) { eHalStatus status = eHAL_STATUS_FAILURE; tANI_U8 i = 0; for (i = 0; i < numChannels; i++) { if(pChannelList[ i ] == channelId) { status = eHAL_STATUS_SUCCESS; break; } } return status; } /** * csrScanFilterResults * *FUNCTION: * This function is called from csrApplyCountryInformation function and * filter scan result based on valid channel list number. * *LOGIC: * Get scan result from scan list and Check Scan result channel number * with 11d channel list if channel number is found in 11d channel list * then do not remove scan result entry from scan list * *ASSUMPTIONS: * * *NOTE: * * @param pMac Pointer to Global MAC structure * * @return Status */ eHalStatus csrScanFilterResults(tpAniSirGlobal pMac) { eHalStatus status = eHAL_STATUS_SUCCESS; tListElem *pEntry,*pTempEntry; tCsrScanResult *pBssDesc; tANI_U32 len = sizeof(pMac->roam.validChannelList); /* Get valid channels list from CFG */ if (!HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac, pMac->roam.validChannelList, &len))) { smsLog( pMac, LOGE, "Failed to get Channel list from CFG"); } csrLLLock(&pMac->scan.scanResultList); pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK); while( pEntry ) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); pTempEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); if(csrCheck11dChannel(pBssDesc->Result.BssDescriptor.channelId, pMac->roam.validChannelList, len)) { /* Remove Scan result which does not have 11d channel */ if( csrLLRemoveEntry(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK)) { csrFreeScanResultEntry( pMac, pBssDesc ); } } else { smsLog( pMac, LOG1, FL("%d is a Valid channel"), pBssDesc->Result.BssDescriptor.channelId); } pEntry = pTempEntry; } csrLLUnlock(&pMac->scan.scanResultList); csrLLLock(&pMac->scan.tempScanResults); pEntry = csrLLPeekHead(&pMac->scan.tempScanResults, LL_ACCESS_NOLOCK); while( pEntry ) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); pTempEntry = csrLLNext(&pMac->scan.tempScanResults, pEntry, LL_ACCESS_NOLOCK); if(csrCheck11dChannel(pBssDesc->Result.BssDescriptor.channelId, pMac->roam.validChannelList, len)) { /* Remove Scan result which does not have 11d channel */ if(csrLLRemoveEntry(&pMac->scan.tempScanResults, pEntry, LL_ACCESS_NOLOCK)) { csrFreeScanResultEntry( pMac, pBssDesc ); } } else { smsLog( pMac, LOG1, FL("%d is a Valid channel"), pBssDesc->Result.BssDescriptor.channelId); } pEntry = pTempEntry; } csrLLUnlock(&pMac->scan.tempScanResults); return status; } eHalStatus csrScanCopyResultList(tpAniSirGlobal pMac, tScanResultHandle hIn, tScanResultHandle *phResult) { eHalStatus status = eHAL_STATUS_SUCCESS; tScanResultList *pRetList, *pInList = (tScanResultList *)hIn; tCsrScanResult *pResult, *pScanResult; tANI_U32 count = 0; tListElem *pEntry; tANI_U32 bssLen, allocLen; if(phResult) { *phResult = CSR_INVALID_SCANRESULT_HANDLE; } pRetList = vos_mem_malloc(sizeof(tScanResultList)); if ( NULL == pRetList ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pRetList, sizeof(tScanResultList), 0); csrLLOpen(pMac->hHdd, &pRetList->List); pRetList->pCurEntry = NULL; csrLLLock(&pMac->scan.scanResultList); csrLLLock(&pInList->List); pEntry = csrLLPeekHead( &pInList->List, LL_ACCESS_NOLOCK ); while( pEntry ) { pScanResult = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); bssLen = pScanResult->Result.BssDescriptor.length + sizeof(pScanResult->Result.BssDescriptor.length); allocLen = sizeof( tCsrScanResult ) + bssLen; pResult = vos_mem_malloc(allocLen); if ( NULL == pResult ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) { csrScanResultPurge(pMac, (tScanResultHandle *)pRetList); count = 0; break; } vos_mem_set(pResult, allocLen , 0); vos_mem_copy(&pResult->Result.BssDescriptor, &pScanResult->Result.BssDescriptor, bssLen); if( pScanResult->Result.pvIes ) { pResult->Result.pvIes = vos_mem_malloc(sizeof( tDot11fBeaconIEs )); if ( NULL == pResult->Result.pvIes ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (!HAL_STATUS_SUCCESS(status)) { //Free the memory we allocate above first vos_mem_free(pResult); csrScanResultPurge(pMac, (tScanResultHandle *)pRetList); count = 0; break; } vos_mem_copy(pResult->Result.pvIes, pScanResult->Result.pvIes, sizeof( tDot11fBeaconIEs )); } csrLLInsertTail(&pRetList->List, &pResult->Link, LL_ACCESS_LOCK); count++; pEntry = csrLLNext( &pInList->List, pEntry, LL_ACCESS_NOLOCK ); }//while csrLLUnlock(&pInList->List); csrLLUnlock(&pMac->scan.scanResultList); if(HAL_STATUS_SUCCESS(status)) { if(0 == count) { csrLLClose(&pRetList->List); vos_mem_free(pRetList); status = eHAL_STATUS_E_NULL_VALUE; } else if(phResult) { *phResult = pRetList; } } }//Allocated pRetList return (status); } eHalStatus csrScanningStateMsgProcessor( tpAniSirGlobal pMac, void *pMsgBuf ) { eHalStatus status = eHAL_STATUS_SUCCESS; tSirMbMsg *pMsg = (tSirMbMsg *)pMsgBuf; if((eWNI_SME_SCAN_RSP == pMsg->type) || (eWNI_SME_GET_SCANNED_CHANNEL_RSP == pMsg->type)) { status = csrScanSmeScanResponse( pMac, pMsgBuf ); } else { if(pMsg->type == eWNI_SME_UPPER_LAYER_ASSOC_CNF) { tCsrRoamSession *pSession; tSirSmeAssocIndToUpperLayerCnf *pUpperLayerAssocCnf; tCsrRoamInfo roamInfo; tCsrRoamInfo *pRoamInfo = NULL; tANI_U32 sessionId; eHalStatus status; smsLog( pMac, LOG1, FL("Scanning : ASSOCIATION confirmation can be given to upper layer ")); vos_mem_set(&roamInfo, sizeof(tCsrRoamInfo), 0); pRoamInfo = &roamInfo; pUpperLayerAssocCnf = (tSirSmeAssocIndToUpperLayerCnf *)pMsgBuf; status = csrRoamGetSessionIdFromBSSID( pMac, (tCsrBssid *)pUpperLayerAssocCnf->bssId, &sessionId ); pSession = CSR_GET_SESSION(pMac, sessionId); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } pRoamInfo->statusCode = eSIR_SME_SUCCESS; //send the status code as Success pRoamInfo->u.pConnectedProfile = &pSession->connectedProfile; pRoamInfo->staId = (tANI_U8)pUpperLayerAssocCnf->aid; pRoamInfo->rsnIELen = (tANI_U8)pUpperLayerAssocCnf->rsnIE.length; pRoamInfo->prsnIE = pUpperLayerAssocCnf->rsnIE.rsnIEdata; pRoamInfo->addIELen = (tANI_U8)pUpperLayerAssocCnf->addIE.length; pRoamInfo->paddIE = pUpperLayerAssocCnf->addIE.addIEdata; vos_mem_copy(pRoamInfo->peerMac, pUpperLayerAssocCnf->peerMacAddr, sizeof(tSirMacAddr)); vos_mem_copy(&pRoamInfo->bssid, pUpperLayerAssocCnf->bssId, sizeof(tCsrBssid)); pRoamInfo->wmmEnabledSta = pUpperLayerAssocCnf->wmmEnabledSta; if(CSR_IS_INFRA_AP(pRoamInfo->u.pConnectedProfile) ) { pMac->roam.roamSession[sessionId].connectState = eCSR_ASSOC_STATE_TYPE_INFRA_CONNECTED; pRoamInfo->fReassocReq = pUpperLayerAssocCnf->reassocReq; status = csrRoamCallCallback(pMac, sessionId, pRoamInfo, 0, eCSR_ROAM_INFRA_IND, eCSR_ROAM_RESULT_INFRA_ASSOCIATION_CNF); } if(CSR_IS_WDS_AP( pRoamInfo->u.pConnectedProfile)) { vos_sleep( 100 ); pMac->roam.roamSession[sessionId].connectState = eCSR_ASSOC_STATE_TYPE_WDS_CONNECTED;//Sta status = csrRoamCallCallback(pMac, sessionId, pRoamInfo, 0, eCSR_ROAM_WDS_IND, eCSR_ROAM_RESULT_WDS_ASSOCIATION_IND);//Sta } } else { if( csrIsAnySessionInConnectState( pMac ) ) { //In case of we are connected, we need to check whether connect status changes //because scan may also run while connected. csrRoamCheckForLinkStatusChange( pMac, ( tSirSmeRsp * )pMsgBuf ); } else { smsLog( pMac, LOGW, "Message [0x%04x] received in state, when expecting Scan Response", pMsg->type ); } } } return (status); } void csrCheckNSaveWscIe(tpAniSirGlobal pMac, tSirBssDescription *pNewBssDescr, tSirBssDescription *pOldBssDescr) { int idx, len; tANI_U8 *pbIe; //If failed to remove, assuming someone else got it. if((pNewBssDescr->fProbeRsp != pOldBssDescr->fProbeRsp) && (0 == pNewBssDescr->WscIeLen)) { idx = 0; len = pOldBssDescr->length - sizeof(tSirBssDescription) + sizeof(tANI_U16) + sizeof(tANI_U32) - DOT11F_IE_WSCPROBERES_MIN_LEN - 2; pbIe = (tANI_U8 *)pOldBssDescr->ieFields; //Save WPS IE if it exists pNewBssDescr->WscIeLen = 0; while(idx < len) { if((DOT11F_EID_WSCPROBERES == pbIe[0]) && (0x00 == pbIe[2]) && (0x50 == pbIe[3]) && (0xf2 == pbIe[4]) && (0x04 == pbIe[5])) { /* Found it */ if((DOT11F_IE_WSCPROBERES_MAX_LEN - 2) >= pbIe[1]) { vos_mem_copy(pNewBssDescr->WscIeProbeRsp, pbIe, pbIe[1] + 2); pNewBssDescr->WscIeLen = pbIe[1] + 2; } break; } idx += pbIe[1] + 2; pbIe += pbIe[1] + 2; } } } //pIes may be NULL tANI_BOOLEAN csrRemoveDupBssDescription( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDescr, tDot11fBeaconIEs *pIes, tAniSSID *pSsid, v_TIME_t *timer, tANI_BOOLEAN fForced ) { tListElem *pEntry; tCsrScanResult *pBssDesc; tANI_BOOLEAN fRC = FALSE; // Walk through all the chained BssDescriptions. If we find a chained BssDescription that // matches the BssID of the BssDescription passed in, then these must be duplicate scan // results for this Bss. In that case, remove the 'old' Bss description from the linked list. csrLLLock(&pMac->scan.scanResultList); pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK); while( pEntry ) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); // we have a duplicate scan results only when BSSID, SSID, Channel and NetworkType // matches if ( csrIsDuplicateBssDescription( pMac, &pBssDesc->Result.BssDescriptor, pSirBssDescr, pIes, fForced ) ) { int32_t rssi_new, rssi_old; rssi_new = (int32_t) pSirBssDescr->rssi; rssi_old = (int32_t) pBssDesc->Result.BssDescriptor.rssi; rssi_new = ((rssi_new * CSR_SCAN_RESULT_RSSI_WEIGHT) + rssi_old * (100 - CSR_SCAN_RESULT_RSSI_WEIGHT)) / 100; pSirBssDescr->rssi = (tANI_S8) rssi_new; rssi_new = (int32_t) pSirBssDescr->rssi_raw; rssi_old = (int32_t) pBssDesc->Result.BssDescriptor.rssi_raw; rssi_new = ((rssi_new * CSR_SCAN_RESULT_RSSI_WEIGHT) + rssi_old * (100 - CSR_SCAN_RESULT_RSSI_WEIGHT)) / 100; pSirBssDescr->rssi_raw = (tANI_S8) rssi_new; // Remove the 'old' entry from the list.... if(csrLLRemoveEntry(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK)) { // !we need to free the memory associated with this node //If failed to remove, assuming someone else got it. *pSsid = pBssDesc->Result.ssId; *timer = pBssDesc->Result.timer; csrCheckNSaveWscIe(pMac, pSirBssDescr, &pBssDesc->Result.BssDescriptor); csrFreeScanResultEntry( pMac, pBssDesc ); } else { smsLog( pMac, LOGW, FL( " fail to remove entry" ) ); } fRC = TRUE; // If we found a match, we can stop looking through the list. break; } pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); } csrLLUnlock(&pMac->scan.scanResultList); return fRC; } eHalStatus csrAddPMKIDCandidateList( tpAniSirGlobal pMac, tANI_U32 sessionId, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes ) { eHalStatus status = eHAL_STATUS_FAILURE; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, "csrAddPMKIDCandidateList called pMac->scan.NumPmkidCandidate = %d", pSession->NumPmkidCandidate); if( pIes ) { // check if this is a RSN BSS if( pIes->RSN.present ) { // Check if the BSS is capable of doing pre-authentication if( pSession->NumPmkidCandidate < CSR_MAX_PMKID_ALLOWED ) { #ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR { WLAN_VOS_DIAG_EVENT_DEF(secEvent, vos_event_wlan_security_payload_type); vos_mem_set(&secEvent, sizeof(vos_event_wlan_security_payload_type), 0); secEvent.eventId = WLAN_SECURITY_EVENT_PMKID_CANDIDATE_FOUND; secEvent.encryptionModeMulticast = (v_U8_t)diagEncTypeFromCSRType(pSession->connectedProfile.mcEncryptionType); secEvent.encryptionModeUnicast = (v_U8_t)diagEncTypeFromCSRType(pSession->connectedProfile.EncryptionType); vos_mem_copy(secEvent.bssid, pSession->connectedProfile.bssid, 6); secEvent.authMode = (v_U8_t)diagAuthTypeFromCSRType(pSession->connectedProfile.AuthType); WLAN_VOS_DIAG_EVENT_REPORT(&secEvent, EVENT_WLAN_SECURITY); } #endif//#ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR // if yes, then add to PMKIDCandidateList vos_mem_copy(pSession->PmkidCandidateInfo[pSession->NumPmkidCandidate].BSSID, pBssDesc->bssId, VOS_MAC_ADDR_SIZE); /* Bit 0 of first byte - PreAuthentication Capability */ if ( (pIes->RSN.RSN_Cap[0] >> 0) & 0x1 ) { pSession->PmkidCandidateInfo[pSession->NumPmkidCandidate].preAuthSupported = eANI_BOOLEAN_TRUE; } else { pSession->PmkidCandidateInfo[pSession->NumPmkidCandidate].preAuthSupported = eANI_BOOLEAN_FALSE; } pSession->NumPmkidCandidate++; } else { status = eHAL_STATUS_FAILURE; } } } return (status); } //This function checks whether new AP is found for the current connected profile //If it is found, it return the sessionId, else it return invalid sessionID eHalStatus csrProcessBSSDescForPMKIDList(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes, tANI_U8 sessionId) { tCsrRoamSession *pSession; tDot11fBeaconIEs *pIesLocal = pIes; eHalStatus status = eHAL_STATUS_FAILURE; if (pIesLocal || HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs( pMac, pBssDesc, &pIesLocal))) { if (CSR_IS_SESSION_VALID(pMac, sessionId)) { pSession = CSR_GET_SESSION(pMac, sessionId); if (csrIsConnStateConnectedInfra(pMac, sessionId) && (eCSR_AUTH_TYPE_RSN == pSession->connectedProfile.AuthType)) { if (csrMatchBSSToConnectProfile(pMac, &pSession->connectedProfile, pBssDesc, pIesLocal)) { /* This new BSS fits the current profile connected */ if (!HAL_STATUS_SUCCESS(csrAddPMKIDCandidateList(pMac, sessionId, pBssDesc, pIesLocal))) { smsLog(pMac, LOGE, FL("csrAddPMKIDCandidateList failed")); } else { status = eHAL_STATUS_SUCCESS; } } } } if (!pIes) { vos_mem_free(pIesLocal); } } return status; } #ifdef FEATURE_WLAN_WAPI eHalStatus csrAddBKIDCandidateList( tpAniSirGlobal pMac, tANI_U32 sessionId, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes ) { eHalStatus status = eHAL_STATUS_FAILURE; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, "csrAddBKIDCandidateList called pMac->scan.NumBkidCandidate = %d", pSession->NumBkidCandidate); if( pIes ) { // check if this is a WAPI BSS if( pIes->WAPI.present ) { // Check if the BSS is capable of doing pre-authentication if( pSession->NumBkidCandidate < CSR_MAX_BKID_ALLOWED ) { // if yes, then add to BKIDCandidateList vos_mem_copy(pSession->BkidCandidateInfo[pSession->NumBkidCandidate].BSSID, pBssDesc->bssId, VOS_MAC_ADDR_SIZE); if ( pIes->WAPI.preauth ) { pSession->BkidCandidateInfo[pSession->NumBkidCandidate].preAuthSupported = eANI_BOOLEAN_TRUE; } else { pSession->BkidCandidateInfo[pSession->NumBkidCandidate].preAuthSupported = eANI_BOOLEAN_FALSE; } pSession->NumBkidCandidate++; } else { status = eHAL_STATUS_FAILURE; } } } return (status); } //This function checks whether new AP is found for the current connected profile //if so add to BKIDCandidateList tANI_BOOLEAN csrProcessBSSDescForBKIDList(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes) { tANI_BOOLEAN fRC = FALSE; tDot11fBeaconIEs *pIesLocal = pIes; tANI_U32 sessionId; tCsrRoamSession *pSession; if( pIesLocal || HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pBssDesc, &pIesLocal)) ) { for( sessionId = 0; sessionId < CSR_ROAM_SESSION_MAX; sessionId++ ) { if( CSR_IS_SESSION_VALID( pMac, sessionId) ) { pSession = CSR_GET_SESSION( pMac, sessionId ); if( csrIsConnStateConnectedInfra( pMac, sessionId ) && eCSR_AUTH_TYPE_WAPI_WAI_CERTIFICATE == pSession->connectedProfile.AuthType) { if(csrMatchBSSToConnectProfile(pMac, &pSession->connectedProfile,pBssDesc, pIesLocal)) { //this new BSS fits the current profile connected if(HAL_STATUS_SUCCESS(csrAddBKIDCandidateList(pMac, sessionId, pBssDesc, pIesLocal))) { fRC = TRUE; } } } } } if(!pIes) { vos_mem_free(pIesLocal); } } return fRC; } #endif static void csrMoveTempScanResultsToMainList(tpAniSirGlobal pMac, tANI_U8 reason, tANI_U8 sessionId) { tListElem *pEntry; tCsrScanResult *pBssDescription; tANI_BOOLEAN fDupBss; #ifdef FEATURE_WLAN_WAPI tANI_BOOLEAN fNewWapiBSSForCurConnection = eANI_BOOLEAN_FALSE; #endif /* FEATURE_WLAN_WAPI */ tDot11fBeaconIEs *pIesLocal = NULL; tAniSSID tmpSsid; v_TIME_t timer=0; tmpSsid.length = 0; // remove the BSS descriptions from temporary list while ((pEntry = csrLLRemoveTail(&pMac->scan.tempScanResults, LL_ACCESS_LOCK)) != NULL) { pBssDescription = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); smsLog( pMac, LOG2, "...Bssid= "MAC_ADDRESS_STR" chan= %d, rssi = -%d", MAC_ADDR_ARRAY(pBssDescription->Result.BssDescriptor.bssId), pBssDescription->Result.BssDescriptor.channelId, pBssDescription->Result.BssDescriptor.rssi * (-1) ); //At this time, pBssDescription->Result.pvIes may be NULL pIesLocal = (tDot11fBeaconIEs *)( pBssDescription->Result.pvIes ); if( !pIesLocal && (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, &pBssDescription->Result.BssDescriptor, &pIesLocal))) ) { smsLog(pMac, LOGE, FL(" Cannot pared IEs")); csrFreeScanResultEntry(pMac, pBssDescription); continue; } fDupBss = csrRemoveDupBssDescription( pMac, &pBssDescription->Result.BssDescriptor, pIesLocal, &tmpSsid, &timer, FALSE ); //Check whether we have reach out limit, but don't lose the LFR candidates came from FW if( CSR_SCAN_IS_OVER_BSS_LIMIT(pMac) #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD && !( eCsrScanGetLfrResult == reason ) #endif ) { //Limit reach smsLog(pMac, LOGW, FL(" BSS limit reached")); //Free the resources if( (pBssDescription->Result.pvIes == NULL) && pIesLocal ) { vos_mem_free(pIesLocal); } csrFreeScanResultEntry(pMac, pBssDescription); //Continue because there may be duplicated BSS continue; } // check for duplicate scan results if ( !fDupBss ) { if (HAL_STATUS_SUCCESS(csrProcessBSSDescForPMKIDList(pMac, &pBssDescription->Result.BssDescriptor, pIesLocal, sessionId))) { /* Found a new BSS */ csrRoamCallCallback(pMac, sessionId, NULL, 0, eCSR_ROAM_SCAN_FOUND_NEW_BSS, eCSR_ROAM_RESULT_NONE); } } else { //Check if the new one has SSID it it, if not, use the older SSID if it exists. if( (0 == pBssDescription->Result.ssId.length) && tmpSsid.length ) { //New BSS has a hidden SSID and old one has the SSID. Keep the SSID only //if diff of saved SSID time and current time is less than 1 min to avoid //side effect of saving SSID with old one is that if AP changes its SSID while remain //hidden, we may never see it and also to address the requirement of //When we remove hidden ssid from the profile i.e., forget the SSID via // GUI that SSID shouldn't see in the profile if( (vos_timer_get_system_time() - timer) <= HIDDEN_TIMER) { pBssDescription->Result.timer = timer; pBssDescription->Result.ssId = tmpSsid; } } } //Find a good AP for 11d info if ( csrIs11dSupported( pMac ) ) { // check if country information element is present if (pIesLocal->Country.present) { csrAddVoteForCountryInfo(pMac, pIesLocal->Country.country); smsLog(pMac, LOGW, FL("11d AP Bssid " MAC_ADDRESS_STR " chan= %d, rssi = -%d, countryCode %c%c"), MAC_ADDR_ARRAY( pBssDescription->Result.BssDescriptor.bssId), pBssDescription->Result.BssDescriptor.channelId, pBssDescription->Result.BssDescriptor.rssi * (-1), pIesLocal->Country.country[0],pIesLocal->Country.country[1] ); } } // append to main list csrScanAddResult(pMac, pBssDescription, pIesLocal, sessionId); if ( (pBssDescription->Result.pvIes == NULL) && pIesLocal ) { vos_mem_free(pIesLocal); } } pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_LOCK ); if (pEntry && 0 != pMac->scan.scanResultCfgAgingTime) csrScanStartResultCfgAgingTimer(pMac); /* We don't need to update CC while connected to an AP which is advertising CC already */ if (csrIs11dSupported(pMac)) { tCsrRoamSession *pSession; tANI_U32 i; for (i = 0; i < CSR_ROAM_SESSION_MAX; i++ ) { if (CSR_IS_SESSION_VALID( pMac, i ) ) { pSession = CSR_GET_SESSION( pMac, i ); if (csrIsConnStateConnected(pMac, i)) { smsLog(pMac, LOGW, FL("No need for updating CC in" "connected state")); goto end; } } } csrElectedCountryInfo(pMac); csrLearnCountryInformation( pMac, NULL, NULL, eANI_BOOLEAN_TRUE ); } end: //If we can find the current 11d info in any of the scan results, or // a good enough AP with the 11d info from the scan results then no need to // get into ambiguous state if(pMac->scan.fAmbiguous11dInfoFound) { if((pMac->scan.fCurrent11dInfoMatch)) { pMac->scan.fAmbiguous11dInfoFound = eANI_BOOLEAN_FALSE; } } #ifdef FEATURE_WLAN_WAPI if(fNewWapiBSSForCurConnection) { //remember it first csrRoamCallCallback(pMac, sessionId, NULL, 0, eCSR_ROAM_SCAN_FOUND_NEW_BSS, eCSR_ROAM_RESULT_NEW_WAPI_BSS); } #endif /* FEATURE_WLAN_WAPI */ return; } static tCsrScanResult * csrScanSaveBssDescription(tpAniSirGlobal pMac, tSirBssDescription *pBSSDescription, tDot11fBeaconIEs *pIes, tANI_U8 sessionId) { tCsrScanResult *pCsrBssDescription = NULL; tANI_U32 cbBSSDesc; tANI_U32 cbAllocated; tListElem *pEntry; // figure out how big the BSS description is (the BSSDesc->length does NOT // include the size of the length field itself). cbBSSDesc = pBSSDescription->length + sizeof( pBSSDescription->length ); cbAllocated = sizeof( tCsrScanResult ) + cbBSSDesc; pCsrBssDescription = vos_mem_malloc(cbAllocated); if ( NULL != pCsrBssDescription ) { vos_mem_set(pCsrBssDescription, cbAllocated, 0); pCsrBssDescription->AgingCount = (tANI_S32)pMac->roam.configParam.agingCount; smsLog(pMac, LOGW, FL(" Set Aging Count = %d for BSS "MAC_ADDRESS_STR" "), pCsrBssDescription->AgingCount, MAC_ADDR_ARRAY(pCsrBssDescription->Result.BssDescriptor.bssId)); vos_mem_copy(&pCsrBssDescription->Result.BssDescriptor, pBSSDescription, cbBSSDesc); #if defined(VOSS_ENSBALED) if ( NULL != pCsrBssDescription->Result.pvIes) { VOS_ASSERT( pCsrBssDescription->Result.pvIes == NULL ); return NULL; } #endif csrScanAddResult(pMac, pCsrBssDescription, pIes, sessionId); pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_LOCK ); if (pEntry && 0 != pMac->scan.scanResultCfgAgingTime) csrScanStartResultCfgAgingTimer(pMac); } return( pCsrBssDescription ); } // Append a Bss Description... tCsrScanResult * csrScanAppendBssDescription(tpAniSirGlobal pMac, tSirBssDescription *pSirBssDescription, tDot11fBeaconIEs *pIes, tANI_BOOLEAN fForced, tANI_U8 sessionId) { tCsrScanResult *pCsrBssDescription = NULL; tAniSSID tmpSsid; v_TIME_t timer = 0; int result; tmpSsid.length = 0; result = csrRemoveDupBssDescription( pMac, pSirBssDescription, pIes, &tmpSsid, &timer, fForced ); pCsrBssDescription = csrScanSaveBssDescription(pMac, pSirBssDescription, pIes, sessionId); if (result && (pCsrBssDescription != NULL)) { //Check if the new one has SSID it it, if not, use the older SSID if it exists. if( (0 == pCsrBssDescription->Result.ssId.length) && tmpSsid.length ) { //New BSS has a hidden SSID and old one has the SSID. Keep the SSID only //if diff of saved SSID time and current time is less than 1 min to avoid //side effect of saving SSID with old one is that if AP changes its SSID while remain //hidden, we may never see it and also to address the requirement of //When we remove hidden ssid from the profile i.e., forget the SSID via // GUI that SSID shouldn't see in the profile if((vos_timer_get_system_time()-timer) <= HIDDEN_TIMER) { pCsrBssDescription->Result.ssId = tmpSsid; pCsrBssDescription->Result.timer = timer; } } } return( pCsrBssDescription ); } void csrPurgeChannelPower( tpAniSirGlobal pMac, tDblLinkList *pChannelList ) { tCsrChannelPowerInfo *pChannelSet; tListElem *pEntry; csrLLLock(pChannelList); // Remove the channel sets from the learned list and put them in the free list while( ( pEntry = csrLLRemoveHead( pChannelList, LL_ACCESS_NOLOCK ) ) != NULL) { pChannelSet = GET_BASE_ADDR( pEntry, tCsrChannelPowerInfo, link ); if( pChannelSet ) { vos_mem_free(pChannelSet); } } csrLLUnlock(pChannelList); return; } /* * Save the channelList into the ultimate storage as the final stage of channel * Input: pCountryInfo -- the country code (e.g. "USI"), channel list, and power limit are all stored inside this data structure */ eHalStatus csrSaveToChannelPower2G_5G( tpAniSirGlobal pMac, tANI_U32 tableSize, tSirMacChanInfo *channelTable ) { tANI_U32 i = tableSize / sizeof( tSirMacChanInfo ); tSirMacChanInfo *pChannelInfo; tCsrChannelPowerInfo *pChannelSet; tANI_BOOLEAN f2GHzInfoFound = FALSE; tANI_BOOLEAN f2GListPurged = FALSE, f5GListPurged = FALSE; pChannelInfo = channelTable; /* At-least 3 bytes have to be remaining -- from "countryString" */ while ( i-- ) { pChannelSet = vos_mem_malloc(sizeof(tCsrChannelPowerInfo)); if ( NULL != pChannelSet ) { vos_mem_set(pChannelSet, sizeof(tCsrChannelPowerInfo), 0); pChannelSet->firstChannel = pChannelInfo->firstChanNum; pChannelSet->numChannels = pChannelInfo->numChannels; // Now set the inter-channel offset based on the frequency band the channel set lies in if( (CSR_IS_CHANNEL_24GHZ(pChannelSet->firstChannel)) && ((pChannelSet->firstChannel + (pChannelSet->numChannels - 1)) <= CSR_MAX_24GHz_CHANNEL_NUMBER) ) { pChannelSet->interChannelOffset = 1; f2GHzInfoFound = TRUE; } else if ( (CSR_IS_CHANNEL_5GHZ(pChannelSet->firstChannel)) && ((pChannelSet->firstChannel + ((pChannelSet->numChannels - 1) * 4)) <= CSR_MAX_5GHz_CHANNEL_NUMBER) ) { pChannelSet->interChannelOffset = 4; f2GHzInfoFound = FALSE; } else { smsLog( pMac, LOGW, FL("Invalid Channel %d Present in Country IE"), pChannelSet->firstChannel); vos_mem_free(pChannelSet); return eHAL_STATUS_FAILURE; } pChannelSet->txPower = CSR_ROAM_MIN( pChannelInfo->maxTxPower, pMac->roam.configParam.nTxPowerCap ); if( f2GHzInfoFound ) { if( !f2GListPurged ) { // purge previous results if found new csrPurgeChannelPower( pMac, &pMac->scan.channelPowerInfoList24 ); f2GListPurged = TRUE; } if(CSR_IS_OPERATING_BG_BAND(pMac)) { // add to the list of 2.4 GHz channel sets csrLLInsertTail( &pMac->scan.channelPowerInfoList24, &pChannelSet->link, LL_ACCESS_LOCK ); } else { smsLog( pMac, LOGW, FL("Adding 11B/G channels in 11A mode -- First Channel is %d"), pChannelSet->firstChannel); vos_mem_free(pChannelSet); } } else { // 5GHz info found if( !f5GListPurged ) { // purge previous results if found new csrPurgeChannelPower( pMac, &pMac->scan.channelPowerInfoList5G ); f5GListPurged = TRUE; } if(CSR_IS_OPERATING_A_BAND(pMac)) { // add to the list of 5GHz channel sets csrLLInsertTail( &pMac->scan.channelPowerInfoList5G, &pChannelSet->link, LL_ACCESS_LOCK ); } else { smsLog( pMac, LOGW, FL("Adding 11A channels in B/G mode -- First Channel is %d"), pChannelSet->firstChannel); vos_mem_free(pChannelSet); } } } pChannelInfo++; // move to next entry } return eHAL_STATUS_SUCCESS; } static void csrClearDfsChannelList( tpAniSirGlobal pMac ) { tSirMbMsg *pMsg; tANI_U16 msgLen; msgLen = (tANI_U16)(sizeof( tSirMbMsg )); pMsg = vos_mem_malloc(msgLen); if ( NULL != pMsg ) { vos_mem_set((void *)pMsg, msgLen, 0); pMsg->type = pal_cpu_to_be16((tANI_U16)eWNI_SME_CLEAR_DFS_CHANNEL_LIST); pMsg->msgLen = pal_cpu_to_be16(msgLen); palSendMBMessage(pMac->hHdd, pMsg); } } void csrApplyPower2Current( tpAniSirGlobal pMac ) { smsLog( pMac, LOG3, FL(" Updating Cfg with power settings")); csrSaveTxPowerToCfg( pMac, &pMac->scan.channelPowerInfoList24, WNI_CFG_MAX_TX_POWER_2_4 ); csrSaveTxPowerToCfg( pMac, &pMac->scan.channelPowerInfoList5G, WNI_CFG_MAX_TX_POWER_5 ); } void csrApplyChannelPowerCountryInfo( tpAniSirGlobal pMac, tCsrChannel *pChannelList, tANI_U8 *countryCode, tANI_BOOLEAN updateRiva) { int i; tANI_U8 numChannels = 0; tANI_U8 tempNumChannels = 0; tCsrChannel ChannelList; if (pChannelList->numChannels) { tempNumChannels = CSR_MIN(pChannelList->numChannels, WNI_CFG_VALID_CHANNEL_LIST_LEN); for (i = 0; i < tempNumChannels; i++) { ChannelList.channelList[numChannels] = pChannelList->channelList[i]; numChannels++; } ChannelList.numChannels = numChannels; /* Store the channel + power info in the global place: Cfg */ csrApplyPower2Current(pMac); csrSetCfgValidChannelList(pMac, ChannelList.channelList, ChannelList.numChannels); // extend scan capability // build a scan list based on the channel list : channel# + active/passive scan csrSetCfgScanControlList(pMac, countryCode, &ChannelList); /*Send msg to Lim to clear DFS channel list */ csrClearDfsChannelList(pMac); #ifdef FEATURE_WLAN_SCAN_PNO if (updateRiva) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL(" Sending 11d PNO info to Riva")); // Send HAL UpdateScanParams message pmcUpdateScanParams(pMac, &(pMac->roam.configParam), &ChannelList, TRUE); } #endif // FEATURE_WLAN_SCAN_PNO } else { smsLog( pMac, LOGE, FL(" 11D channel list is empty")); } csrSetCfgCountryCode(pMac, countryCode); } void csrResetCountryInformation( tpAniSirGlobal pMac, tANI_BOOLEAN fForce, tANI_BOOLEAN updateRiva ) { if( fForce || (csrIs11dSupported( pMac ) && (!pMac->scan.f11dInfoReset))) { #ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR { vos_log_802_11d_pkt_type *p11dLog; int Index; WLAN_VOS_DIAG_LOG_ALLOC(p11dLog, vos_log_802_11d_pkt_type, LOG_WLAN_80211D_C); if(p11dLog) { p11dLog->eventId = WLAN_80211D_EVENT_RESET; vos_mem_copy(p11dLog->countryCode, pMac->scan.countryCodeCurrent, 3); p11dLog->numChannel = pMac->scan.base20MHzChannels.numChannels; if(p11dLog->numChannel <= VOS_LOG_MAX_NUM_CHANNEL) { vos_mem_copy(p11dLog->Channels, pMac->scan.base20MHzChannels.channelList, p11dLog->numChannel); for (Index=0; Index < pMac->scan.base20MHzChannels.numChannels; Index++) { p11dLog->TxPwr[Index] = CSR_ROAM_MIN( pMac->scan.defaultPowerTable[Index].pwr, pMac->roam.configParam.nTxPowerCap ); } } if(!pMac->roam.configParam.Is11dSupportEnabled) { p11dLog->supportMultipleDomain = WLAN_80211D_DISABLED; } else if(pMac->roam.configParam.fEnforceDefaultDomain) { p11dLog->supportMultipleDomain = WLAN_80211D_NOT_SUPPORT_MULTI_DOMAIN; } else { p11dLog->supportMultipleDomain = WLAN_80211D_SUPPORT_MULTI_DOMAIN; } WLAN_VOS_DIAG_LOG_REPORT(p11dLog); } } #endif //#ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR csrPruneChannelListForMode(pMac, &pMac->scan.baseChannels); csrPruneChannelListForMode(pMac, &pMac->scan.base20MHzChannels); csrSaveChannelPowerForBand(pMac, eANI_BOOLEAN_FALSE); csrSaveChannelPowerForBand(pMac, eANI_BOOLEAN_TRUE); // ... and apply the channel list, power settings, and the country code. csrApplyChannelPowerCountryInfo( pMac, &pMac->scan.base20MHzChannels, pMac->scan.countryCodeCurrent, updateRiva ); // clear the 11d channel list vos_mem_set(&pMac->scan.channels11d, sizeof(pMac->scan.channels11d), 0); pMac->scan.f11dInfoReset = eANI_BOOLEAN_TRUE; pMac->scan.f11dInfoApplied = eANI_BOOLEAN_FALSE; } return; } eHalStatus csrResetCountryCodeInformation(tpAniSirGlobal pMac, tANI_BOOLEAN *pfRestartNeeded) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_BOOLEAN fRestart = eANI_BOOLEAN_FALSE; //Use the Country code and domain from EEPROM vos_mem_copy(pMac->scan.countryCodeCurrent, pMac->scan.countryCodeDefault, WNI_CFG_COUNTRY_CODE_LEN); csrSetRegulatoryDomain(pMac, pMac->scan.domainIdCurrent, &fRestart); if( ((eANI_BOOLEAN_FALSE == fRestart) || (pfRestartNeeded == NULL) ) && !csrIsInfraConnected(pMac)) { //Only reset the country info if we don't need to restart csrResetCountryInformation(pMac, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); } if(pfRestartNeeded) { *pfRestartNeeded = fRestart; } return (status); } void csrClearVotesForCountryInfo(tpAniSirGlobal pMac) { pMac->scan.countryCodeCount = 0; vos_mem_set(pMac->scan.votes11d, sizeof(tCsrVotes11d) * CSR_MAX_NUM_COUNTRY_CODE, 0); } void csrAddVoteForCountryInfo(tpAniSirGlobal pMac, tANI_U8 *pCountryCode) { tANI_BOOLEAN match = FALSE; tANI_U8 i; /* convert to UPPER here so we are assured * the strings are always in upper case. */ for( i = 0; i < 3; i++ ) { pCountryCode[ i ] = (tANI_U8)csrToUpper( pCountryCode[ i ] ); } /* Some of the 'old' Cisco 350 series AP's advertise NA as the * country code (for North America ??). NA is not a valid country code * or domain so let's allow this by changing it to the proper * country code (which is US). We've also seen some NETGEAR AP's * that have "XX " as the country code with valid 2.4 GHz US channel * information. If we cannot find the country code advertised in the * 11d information element, let's default to US. */ if ( !HAL_STATUS_SUCCESS(csrGetRegulatoryDomainForCountry( pMac, pCountryCode, NULL,COUNTRY_QUERY ) ) ) { pCountryCode[ 0 ] = '0'; pCountryCode[ 1 ] = '0'; } /* We've seen some of the AP's improperly put a 0 for the * third character of the country code. spec says valid charcters are * 'O' (for outdoor), 'I' for Indoor, or ' ' (space; for either). * if we see a 0 in this third character, let's change it to a ' '. */ if ( 0 == pCountryCode[ 2 ] ) { pCountryCode[ 2 ] = ' '; } for (i = 0; i < pMac->scan.countryCodeCount; i++) { match = (vos_mem_compare(pMac->scan.votes11d[i].countryCode, pCountryCode, 2)); if(match) { break; } } if (match) { pMac->scan.votes11d[i].votes++; } else { vos_mem_copy( pMac->scan.votes11d[pMac->scan.countryCodeCount].countryCode, pCountryCode, 3 ); pMac->scan.votes11d[pMac->scan.countryCodeCount].votes = 1; pMac->scan.countryCodeCount++; } return; } tANI_BOOLEAN csrElectedCountryInfo(tpAniSirGlobal pMac) { tANI_BOOLEAN fRet = FALSE; tANI_U8 maxVotes = 0; tANI_U8 i, j=0; if (!pMac->scan.countryCodeCount) { return fRet; } maxVotes = pMac->scan.votes11d[0].votes; fRet = TRUE; for(i = 1; i < pMac->scan.countryCodeCount; i++) { /* If we have a tie for max votes for 2 different country codes, * pick random.we can put some more intelligence - TBD */ if (maxVotes < pMac->scan.votes11d[i].votes) { VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, " Votes for Country %c%c : %d\n", pMac->scan.votes11d[i].countryCode[0], pMac->scan.votes11d[i].countryCode[1], pMac->scan.votes11d[i].votes); maxVotes = pMac->scan.votes11d[i].votes; j = i; fRet = TRUE; } } if (fRet) { vos_mem_copy(pMac->scan.countryCodeElected, pMac->scan.votes11d[j].countryCode, WNI_CFG_COUNTRY_CODE_LEN); vos_mem_copy(pMac->scan.countryCode11d, pMac->scan.votes11d[j].countryCode, WNI_CFG_COUNTRY_CODE_LEN); VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "Selected Country is %c%c With count %d\n", pMac->scan.votes11d[j].countryCode[0], pMac->scan.votes11d[j].countryCode[1], pMac->scan.votes11d[j].votes); } return fRet; } eHalStatus csrSetCountryCode(tpAniSirGlobal pMac, tANI_U8 *pCountry, tANI_BOOLEAN *pfRestartNeeded) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; v_REGDOMAIN_t domainId; if(pCountry) { status = csrGetRegulatoryDomainForCountry(pMac, pCountry, &domainId, COUNTRY_USER); if(HAL_STATUS_SUCCESS(status)) { status = csrSetRegulatoryDomain(pMac, domainId, pfRestartNeeded); if(HAL_STATUS_SUCCESS(status)) { //We don't need to check the pMac->roam.configParam.fEnforceDefaultDomain flag here, //csrSetRegulatoryDomain will fail if the country doesn't fit our domain criteria. vos_mem_copy(pMac->scan.countryCodeCurrent, pCountry, WNI_CFG_COUNTRY_CODE_LEN); if((pfRestartNeeded == NULL) || !(*pfRestartNeeded)) { //Simply set it to cfg. If we need to restart, restart will apply it to the CFG csrSetCfgCountryCode(pMac, pCountry); } } } } return (status); } //caller allocated memory for pNumChn and pChnPowerInfo //As input, *pNumChn has the size of the array of pChnPowerInfo //Upon return, *pNumChn has the number of channels assigned. void csrGetChannelPowerInfo( tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U32 *pNumChn, tChannelListWithPower *pChnPowerInfo) { tListElem *pEntry; tANI_U32 chnIdx = 0, idx; tCsrChannelPowerInfo *pChannelSet; //Get 2.4Ghz first pEntry = csrLLPeekHead( pList, LL_ACCESS_LOCK ); while( pEntry && (chnIdx < *pNumChn) ) { pChannelSet = GET_BASE_ADDR( pEntry, tCsrChannelPowerInfo, link ); if ( 1 != pChannelSet->interChannelOffset ) { for( idx = 0; (idx < pChannelSet->numChannels) && (chnIdx < *pNumChn); idx++ ) { pChnPowerInfo[chnIdx].chanId = (tANI_U8)(pChannelSet->firstChannel + ( idx * pChannelSet->interChannelOffset )); pChnPowerInfo[chnIdx++].pwr = pChannelSet->txPower; } } else { for( idx = 0; (idx < pChannelSet->numChannels) && (chnIdx < *pNumChn); idx++ ) { pChnPowerInfo[chnIdx].chanId = (tANI_U8)(pChannelSet->firstChannel + idx); pChnPowerInfo[chnIdx++].pwr = pChannelSet->txPower; } } pEntry = csrLLNext( pList, pEntry, LL_ACCESS_LOCK ); } *pNumChn = chnIdx; return ; } void csrApplyCountryInformation( tpAniSirGlobal pMac, tANI_BOOLEAN fForce ) { v_REGDOMAIN_t domainId; eHalStatus status = eHAL_STATUS_SUCCESS; do { if( !csrIs11dSupported( pMac ) || 0 == pMac->scan.channelOf11dInfo) break; if( pMac->scan.fAmbiguous11dInfoFound ) { /* Ambiguous info found; Restore the default domain as well */ if(HAL_STATUS_SUCCESS(csrGetRegulatoryDomainForCountry( pMac, pMac->scan.countryCodeCurrent, &domainId, COUNTRY_QUERY))) { pMac->scan.domainIdCurrent = domainId; } else { smsLog(pMac, LOGE, FL(" failed to get domain from currentCountryCode %02X%02X"), pMac->scan.countryCodeCurrent[0], pMac->scan.countryCodeCurrent[1]); } csrResetCountryInformation( pMac, eANI_BOOLEAN_FALSE, eANI_BOOLEAN_TRUE ); break; } if ( pMac->scan.f11dInfoApplied && !fForce ) break; if(HAL_STATUS_SUCCESS(csrGetRegulatoryDomainForCountry( pMac, pMac->scan.countryCode11d, &domainId, COUNTRY_QUERY))) { //Check whether we need to enforce default domain if( ( !pMac->roam.configParam.fEnforceDefaultDomain ) || (pMac->scan.domainIdCurrent == domainId) ) { #ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR { vos_log_802_11d_pkt_type *p11dLog; tChannelListWithPower chnPwrInfo[WNI_CFG_VALID_CHANNEL_LIST_LEN]; tANI_U32 nChnInfo = WNI_CFG_VALID_CHANNEL_LIST_LEN, nTmp; WLAN_VOS_DIAG_LOG_ALLOC(p11dLog, vos_log_802_11d_pkt_type, LOG_WLAN_80211D_C); if(p11dLog) { p11dLog->eventId = WLAN_80211D_EVENT_COUNTRY_SET; vos_mem_copy(p11dLog->countryCode, pMac->scan.countryCode11d, 3); p11dLog->numChannel = pMac->scan.channels11d.numChannels; if(p11dLog->numChannel <= VOS_LOG_MAX_NUM_CHANNEL) { vos_mem_copy(p11dLog->Channels, pMac->scan.channels11d.channelList, p11dLog->numChannel); csrGetChannelPowerInfo(pMac, &pMac->scan.channelPowerInfoList24, &nChnInfo, chnPwrInfo); nTmp = nChnInfo; nChnInfo = WNI_CFG_VALID_CHANNEL_LIST_LEN - nTmp; csrGetChannelPowerInfo(pMac, &pMac->scan.channelPowerInfoList5G, &nChnInfo, &chnPwrInfo[nTmp]); for(nTmp = 0; nTmp < p11dLog->numChannel; nTmp++) { for(nChnInfo = 0; nChnInfo < WNI_CFG_VALID_CHANNEL_LIST_LEN; nChnInfo++) { if(p11dLog->Channels[nTmp] == chnPwrInfo[nChnInfo].chanId) { p11dLog->TxPwr[nTmp] = chnPwrInfo[nChnInfo].pwr; break; } } } } if(!pMac->roam.configParam.Is11dSupportEnabled) { p11dLog->supportMultipleDomain = WLAN_80211D_DISABLED; } else if(pMac->roam.configParam.fEnforceDefaultDomain) { p11dLog->supportMultipleDomain = WLAN_80211D_NOT_SUPPORT_MULTI_DOMAIN; } else { p11dLog->supportMultipleDomain = WLAN_80211D_SUPPORT_MULTI_DOMAIN; } WLAN_VOS_DIAG_LOG_REPORT(p11dLog); } } #endif //#ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR if(pMac->scan.domainIdCurrent != domainId) { smsLog(pMac, LOGW, FL("Domain Changed Old %d, new %d"), pMac->scan.domainIdCurrent, domainId); status = WDA_SetRegDomain(pMac, domainId, eSIR_TRUE); } if (status != eHAL_STATUS_SUCCESS) { smsLog( pMac, LOGE, FL(" fail to set regId %d"), domainId ); } pMac->scan.domainIdCurrent = domainId; // switch to active scans using this new channel list pMac->scan.curScanType = eSIR_ACTIVE_SCAN; pMac->scan.f11dInfoApplied = eANI_BOOLEAN_TRUE; pMac->scan.f11dInfoReset = eANI_BOOLEAN_FALSE; } } } while( 0 ); return; } tANI_BOOLEAN csrSave11dCountryString( tpAniSirGlobal pMac, tANI_U8 *pCountryCode, tANI_BOOLEAN fForce) { tANI_BOOLEAN fCountryStringChanged = FALSE, fUnknownCountryCode = FALSE; tANI_U32 i; v_REGDOMAIN_t regd; tANI_BOOLEAN fCountryNotPresentInDriver = FALSE; // convert to UPPER here so we are assured the strings are always in upper case. for( i = 0; i < 3; i++ ) { pCountryCode[ i ] = (tANI_U8)csrToUpper( pCountryCode[ i ] ); } // Some of the 'old' Cisco 350 series AP's advertise NA as the country code (for North America ??). // NA is not a valid country code or domain so let's allow this by changing it to the proper // country code (which is US). We've also seen some NETGEAR AP's that have "XX " as the country code // with valid 2.4 GHz US channel information. If we cannot find the country code advertised in the // 11d information element, let's default to US. if ( !HAL_STATUS_SUCCESS(csrGetRegulatoryDomainForCountry(pMac, pCountryCode, &regd, COUNTRY_QUERY) ) ) { // Check the enforcement first if( pMac->roam.configParam.fEnforceDefaultDomain || pMac->roam.configParam.fEnforceCountryCodeMatch ) { fUnknownCountryCode = TRUE; } else { fCountryNotPresentInDriver = TRUE; } } //right now, even if we don't find the CC in driver we set to world. Making //sure countryCode11d doesn't get updated with the invalid CC, instead //reflect the world CC else if (REGDOMAIN_WORLD == regd) { fCountryNotPresentInDriver = TRUE; } /* * We've seen some of the AP's improperly put a 0 for the third character * of the country code. Spec says valid characters are 'O' (for outdoor), * 'I' for Indoor, or ' ' (space; for either). * if we see a 0 in this third character, let's change it to a ' '. */ if ( 0 == pCountryCode[ 2 ] ) { pCountryCode[ 2 ] = ' '; } if( !fUnknownCountryCode ) { fCountryStringChanged = (!vos_mem_compare(pMac->scan.countryCode11d, pCountryCode, 2)); if(( 0 == pMac->scan.countryCode11d[ 0 ] && 0 == pMac->scan.countryCode11d[ 1 ] ) || (fForce)) { if (!fCountryNotPresentInDriver) { // this is the first .11d information vos_mem_copy(pMac->scan.countryCode11d, pCountryCode, sizeof( pMac->scan.countryCode11d )); } else { pMac->scan.countryCode11d[0] = '0'; pMac->scan.countryCode11d[1] = '0'; } } } return( fCountryStringChanged ); } void csrSaveChannelPowerForBand( tpAniSirGlobal pMac, tANI_BOOLEAN fPopulate5GBand ) { tANI_U32 Index, count=0; tSirMacChanInfo *pChanInfo; tSirMacChanInfo *pChanInfoStart; tANI_S32 maxChannelIndex; maxChannelIndex = ( pMac->scan.base20MHzChannels.numChannels < WNI_CFG_VALID_CHANNEL_LIST_LEN ) ? pMac->scan.base20MHzChannels.numChannels : WNI_CFG_VALID_CHANNEL_LIST_LEN ; pChanInfo = vos_mem_malloc(sizeof(tSirMacChanInfo) * WNI_CFG_VALID_CHANNEL_LIST_LEN); if ( NULL != pChanInfo ) { vos_mem_set(pChanInfo, sizeof(tSirMacChanInfo) * WNI_CFG_VALID_CHANNEL_LIST_LEN, 0); pChanInfoStart = pChanInfo; for (Index=0; Index < maxChannelIndex; Index++) { if ((fPopulate5GBand && (CSR_IS_CHANNEL_5GHZ(pMac->scan.defaultPowerTable[Index].chanId))) || (!fPopulate5GBand && (CSR_IS_CHANNEL_24GHZ(pMac->scan.defaultPowerTable[Index].chanId))) ) { if(count >= WNI_CFG_VALID_CHANNEL_LIST_LEN) { smsLog( pMac, LOGW, FL(" csrSaveChannelPowerForBand, count exceeded, count = %d"), count); break; } pChanInfo->firstChanNum = pMac->scan.defaultPowerTable[Index].chanId; pChanInfo->numChannels = 1; pChanInfo->maxTxPower = CSR_ROAM_MIN( pMac->scan.defaultPowerTable[Index].pwr, pMac->roam.configParam.nTxPowerCap ); pChanInfo++; count++; } } if(count) { csrSaveToChannelPower2G_5G( pMac, count * sizeof(tSirMacChanInfo), pChanInfoStart ); } vos_mem_free(pChanInfoStart); } } void csrSetOppositeBandChannelInfo( tpAniSirGlobal pMac ) { tANI_BOOLEAN fPopulate5GBand = FALSE; do { // if this is not a dual band product, then we don't need to set the opposite // band info. We only work in one band so no need to look in the other band. if ( !CSR_IS_OPEARTING_DUAL_BAND( pMac ) ) break; // if we found channel info on the 5.0 band and... if ( CSR_IS_CHANNEL_5GHZ( pMac->scan.channelOf11dInfo ) ) { // and the 2.4 band is empty, then populate the 2.4 channel info if ( !csrLLIsListEmpty( &pMac->scan.channelPowerInfoList24, LL_ACCESS_LOCK ) ) break; fPopulate5GBand = FALSE; } else { // else, we found channel info in the 2.4 GHz band. If the 5.0 band is empty // set the 5.0 band info from the 2.4 country code. if ( !csrLLIsListEmpty( &pMac->scan.channelPowerInfoList5G, LL_ACCESS_LOCK ) ) break; fPopulate5GBand = TRUE; } csrSaveChannelPowerForBand( pMac, fPopulate5GBand ); } while( 0 ); } tANI_BOOLEAN csrIsSupportedChannel(tpAniSirGlobal pMac, tANI_U8 channelId) { tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE; tANI_U32 i; //Make sure it is a channel that is in our supported list. for ( i = 0; i < pMac->scan.baseChannels.numChannels; i++ ) { if ( channelId == pMac->scan.baseChannels.channelList[i] ) { fRet = eANI_BOOLEAN_TRUE; break; } } //If it is configured to limit a set of the channels if( fRet && pMac->roam.configParam.fEnforce11dChannels ) { fRet = eANI_BOOLEAN_FALSE; for ( i = 0; i < pMac->scan.base20MHzChannels.numChannels; i++ ) { if ( channelId == pMac->scan.base20MHzChannels.channelList[i] ) { fRet = eANI_BOOLEAN_TRUE; break; } } } return (fRet); } //bSize specify the buffer size of pChannelList tANI_U8 csrGetChannelListFromChannelSet( tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 bSize, tCsrChannelPowerInfo *pChannelSet ) { tANI_U8 i, j = 0, chnId; bSize = CSR_MIN(bSize, pChannelSet->numChannels); for( i = 0; i < bSize; i++ ) { chnId = (tANI_U8)(pChannelSet->firstChannel + ( i * pChannelSet->interChannelOffset )); if ( csrIsSupportedChannel( pMac, chnId ) ) { pChannelList[j++] = chnId; } } return (j); } //bSize -- specify the buffer size of pChannelList void csrConstructCurrentValidChannelList( tpAniSirGlobal pMac, tDblLinkList *pChannelSetList, tANI_U8 *pChannelList, tANI_U8 bSize, tANI_U8 *pNumChannels ) { tListElem *pEntry; tCsrChannelPowerInfo *pChannelSet; tANI_U8 numChannels; tANI_U8 *pChannels; if( pChannelSetList && pChannelList && pNumChannels ) { pChannels = pChannelList; *pNumChannels = 0; pEntry = csrLLPeekHead( pChannelSetList, LL_ACCESS_LOCK ); while( pEntry ) { pChannelSet = GET_BASE_ADDR( pEntry, tCsrChannelPowerInfo, link ); numChannels = csrGetChannelListFromChannelSet( pMac, pChannels, bSize, pChannelSet ); pChannels += numChannels; *pNumChannels += numChannels; pEntry = csrLLNext( pChannelSetList, pEntry, LL_ACCESS_LOCK ); } } } /* * 802.11D only: Gather 11d IE via beacon or Probe response and store them in pAdapter->channels11d */ tANI_BOOLEAN csrLearnCountryInformation( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDesc, tDot11fBeaconIEs *pIes, tANI_BOOLEAN fForce) { eHalStatus status; tANI_U8 *pCountryCodeSelected; tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE; v_REGDOMAIN_t domainId; tDot11fBeaconIEs *pIesLocal = pIes; tANI_BOOLEAN useVoting = eANI_BOOLEAN_FALSE; if (VOS_STA_SAP_MODE == vos_get_conparam ()) return eHAL_STATUS_SUCCESS; if ((NULL == pSirBssDesc) && (NULL == pIes)) useVoting = eANI_BOOLEAN_TRUE; do { // check if .11d support is enabled if( !csrIs11dSupported( pMac ) ) break; if (eANI_BOOLEAN_FALSE == useVoting) { if( !pIesLocal && (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSirBssDesc, &pIesLocal)))) { break; } // check if country information element is present if(!pIesLocal->Country.present) { //No country info break; } if( HAL_STATUS_SUCCESS(csrGetRegulatoryDomainForCountry (pMac, pIesLocal->Country.country, &domainId, COUNTRY_QUERY)) && ( domainId == REGDOMAIN_WORLD)) { break; } } //useVoting == eANI_BOOLEAN_FALSE if (eANI_BOOLEAN_FALSE == useVoting) pCountryCodeSelected = pIesLocal->Country.country; else pCountryCodeSelected = pMac->scan.countryCodeElected; status = csrGetRegulatoryDomainForCountry(pMac, pCountryCodeSelected, &domainId, COUNTRY_IE); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to get regId %d"), domainId ); fRet = eANI_BOOLEAN_FALSE; break; } /* updating 11d Country Code with Country code selected. */ vos_mem_copy(pMac->scan.countryCode11d, pCountryCodeSelected, WNI_CFG_COUNTRY_CODE_LEN); #ifndef CONFIG_ENABLE_LINUX_REG // Checking for Domain Id change if ( domainId != pMac->scan.domainIdCurrent ) { vos_mem_copy(pMac->scan.countryCode11d, pCountryCodeSelected, sizeof( pMac->scan.countryCode11d ) ); /* Set Current Country code and Current Regulatory domain */ status = csrSetRegulatoryDomain(pMac, domainId, NULL); if (eHAL_STATUS_SUCCESS != status) { smsLog(pMac, LOGE, "Set Reg Domain Fail %d", status); fRet = eANI_BOOLEAN_FALSE; break; } //csrSetRegulatoryDomain will fail if the country doesn't fit our domain criteria. vos_mem_copy(pMac->scan.countryCodeCurrent, pCountryCodeSelected, WNI_CFG_COUNTRY_CODE_LEN); //Simply set it to cfg. csrSetCfgCountryCode(pMac, pCountryCodeSelected); /* overwrite the defualt country code */ vos_mem_copy(pMac->scan.countryCodeDefault, pMac->scan.countryCodeCurrent, WNI_CFG_COUNTRY_CODE_LEN); /* Set Current RegDomain */ status = WDA_SetRegDomain(pMac, domainId, eSIR_TRUE); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to Set regId %d"), domainId ); fRet = eANI_BOOLEAN_FALSE; break; } /* set to default domain ID */ pMac->scan.domainIdCurrent = domainId; /* get the channels based on new cc */ status = csrInitGetChannels( pMac ); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to get Channels ")); fRet = eANI_BOOLEAN_FALSE; break; } } #endif fRet = eANI_BOOLEAN_TRUE; } while( 0 ); if( !pIes && pIesLocal ) { //locally allocated vos_mem_free(pIesLocal); } return( fRet ); } static void csrSaveScanResults(tpAniSirGlobal pMac, tANI_U8 reason, tANI_U8 sessionId) { // initialize this to FALSE. profMoveInterimScanResultsToMainList() routine // will set this to the channel where an .11d beacon is seen pMac->scan.channelOf11dInfo = 0; // if we get any ambiguous .11d information then this will be set to TRUE pMac->scan.fAmbiguous11dInfoFound = eANI_BOOLEAN_FALSE; //Tush // if we get any ambiguous .11d information, then this will be set to TRUE // only if the applied 11d info could be found in one of the scan results pMac->scan.fCurrent11dInfoMatch = eANI_BOOLEAN_FALSE; // move the scan results from interim list to the main scan list csrMoveTempScanResultsToMainList(pMac, reason, sessionId); // Now check if we gathered any domain/country specific information // If so, we should update channel list and apply Tx power settings if( csrIs11dSupported(pMac) ) { csrApplyCountryInformation( pMac, FALSE ); } } void csrReinitScanCmd(tpAniSirGlobal pMac, tSmeCmd *pCommand) { switch (pCommand->u.scanCmd.reason) { case eCsrScanSetBGScanParam: case eCsrScanAbortBgScan: if(pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList) { vos_mem_free(pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList); pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList = NULL; } break; case eCsrScanBGScanAbort: case eCsrScanBGScanEnable: case eCsrScanGetScanChnInfo: break; case eCsrScanAbortNormalScan: default: csrScanFreeRequest(pMac, &pCommand->u.scanCmd.u.scanRequest); break; } if(pCommand->u.scanCmd.pToRoamProfile) { csrReleaseProfile(pMac, pCommand->u.scanCmd.pToRoamProfile); vos_mem_free(pCommand->u.scanCmd.pToRoamProfile); } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); } tANI_BOOLEAN csrGetRemainingChannelsFor11dScan( tpAniSirGlobal pMac, tANI_U8 *pChannels, tANI_U8 *pcChannels ) { tANI_U32 index11dChannels, index; tANI_U32 indexCurrentChannels; tANI_BOOLEAN fChannelAlreadyScanned; tANI_U32 len = sizeof(pMac->roam.validChannelList); *pcChannels = 0; if ( CSR_IS_11D_INFO_FOUND(pMac) && csrRoamIsChannelValid(pMac, pMac->scan.channelOf11dInfo) ) { if (HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac, (tANI_U8 *)pMac->roam.validChannelList, &len))) { //Find the channel index where we found the 11d info for(index = 0; index < len; index++) { if(pMac->scan.channelOf11dInfo == pMac->roam.validChannelList[index]) break; } //check whether we found the channel index if(index < len) { // Now, look through the 11d channel list and create a list of all channels in the 11d list that are // NOT in the current channel list. This gives us a list of the new channels that have not been // scanned. We'll scan this new list so we have a complete set of scan results on all of the domain channels // initially. for ( index11dChannels = 0; index11dChannels < pMac->scan.channels11d.numChannels; index11dChannels++ ) { fChannelAlreadyScanned = eANI_BOOLEAN_FALSE; for( indexCurrentChannels = 0; indexCurrentChannels < index; indexCurrentChannels++ ) { if ( pMac->roam.validChannelList[ indexCurrentChannels ] == pMac->scan.channels11d.channelList[ index11dChannels ] ) { fChannelAlreadyScanned = eANI_BOOLEAN_TRUE; break; } } if ( !fChannelAlreadyScanned ) { pChannels[ *pcChannels ] = pMac->scan.channels11d.channelList[ index11dChannels ]; ( *pcChannels )++; } } } }//GetCFG } return( *pcChannels ); } eCsrScanCompleteNextCommand csrScanGetNextCommandState( tpAniSirGlobal pMac, tSmeCmd *pCommand, tANI_BOOLEAN fSuccess ) { eCsrScanCompleteNextCommand NextCommand = eCsrNextScanNothing; switch( pCommand->u.scanCmd.reason ) { case eCsrScan11d1: NextCommand = (fSuccess) ? eCsrNext11dScan1Success : eCsrNext11dScan1Failure; break; case eCsrScan11d2: NextCommand = (fSuccess) ? eCsrNext11dScan2Success : eCsrNext11dScan2Failure; break; case eCsrScan11dDone: NextCommand = eCsrNext11dScanComplete; break; case eCsrScanLostLink1: NextCommand = (fSuccess) ? eCsrNextLostLinkScan1Success : eCsrNextLostLinkScan1Failed; break; case eCsrScanLostLink2: NextCommand = (fSuccess) ? eCsrNextLostLinkScan2Success : eCsrNextLostLinkScan2Failed; break; case eCsrScanLostLink3: NextCommand = (fSuccess) ? eCsrNextLostLinkScan3Success : eCsrNextLostLinkScan3Failed; break; case eCsrScanForSsid: NextCommand = (fSuccess) ? eCsrNexteScanForSsidSuccess : eCsrNexteScanForSsidFailure; break; case eCsrScanForCapsChange: NextCommand = eCsrNextCapChangeScanComplete; //don't care success or not break; case eCsrScanIdleScan: NextCommand = eCsrNextIdleScanComplete; break; default: NextCommand = eCsrNextScanNothing; break; } return( NextCommand ); } //Return whether the pCommand is finished. tANI_BOOLEAN csrHandleScan11d1Failure(tpAniSirGlobal pMac, tSmeCmd *pCommand) { tANI_BOOLEAN fRet = eANI_BOOLEAN_TRUE; //Apply back the default setting and passively scan one more time. csrResetCountryInformation(pMac, eANI_BOOLEAN_FALSE, eANI_BOOLEAN_TRUE); pCommand->u.scanCmd.reason = eCsrScan11d2; if(HAL_STATUS_SUCCESS(csrScanChannels(pMac, pCommand))) { fRet = eANI_BOOLEAN_FALSE; } return (fRet); } tANI_BOOLEAN csrHandleScan11dSuccess(tpAniSirGlobal pMac, tSmeCmd *pCommand) { tANI_BOOLEAN fRet = eANI_BOOLEAN_TRUE; tANI_U8 *pChannels; tANI_U8 cChannels; pChannels = vos_mem_malloc(WNI_CFG_VALID_CHANNEL_LIST_LEN); if ( NULL != pChannels ) { vos_mem_set(pChannels, WNI_CFG_VALID_CHANNEL_LIST_LEN, 0); if ( csrGetRemainingChannelsFor11dScan( pMac, pChannels, &cChannels ) ) { pCommand->u.scanCmd.reason = eCsrScan11dDone; if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList) { vos_mem_free(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList); pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL; } pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(cChannels); if ( NULL != pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList ) { vos_mem_copy(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList, pChannels, cChannels); pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = cChannels; pCommand->u.scanCmd.u.scanRequest.requestType = eCSR_SCAN_REQUEST_FULL_SCAN; pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN; if(HAL_STATUS_SUCCESS(csrScanChannels(pMac, pCommand))) { //Reuse the same command buffer fRet = eANI_BOOLEAN_FALSE; } } } vos_mem_free(pChannels); } return (fRet); } //Return whether the command should be removed tANI_BOOLEAN csrScanComplete( tpAniSirGlobal pMac, tSirSmeScanRsp *pScanRsp ) { eCsrScanCompleteNextCommand NextCommand = eCsrNextScanNothing; tListElem *pEntry; tSmeCmd *pCommand; tANI_BOOLEAN fRemoveCommand = eANI_BOOLEAN_TRUE; tANI_BOOLEAN fSuccess; if (pMac->fScanOffload) pEntry = csrLLPeekHead(&pMac->sme.smeScanCmdActiveList, LL_ACCESS_LOCK); else pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK); if ( pEntry ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); // If the head of the queue is Active and it is a SCAN command, remove // and put this on the Free queue. if ( eSmeCommandScan == pCommand->command ) { tANI_U32 sessionId = pCommand->sessionId; if(eSIR_SME_SUCCESS != pScanRsp->statusCode) { fSuccess = eANI_BOOLEAN_FALSE; } else { //pMac->scan.tempScanResults is not empty meaning the scan found something //This check only valid here because csrSaveScanresults is not yet called fSuccess = (!csrLLIsListEmpty(&pMac->scan.tempScanResults, LL_ACCESS_LOCK)); } if (pCommand->u.scanCmd.abortScanDueToBandChange) { /* * Scan aborted due to band change * The scan results need to be flushed */ if (pCommand->u.scanCmd.callback != pMac->scan.callback11dScanDone) { smsLog(pMac, LOG1, FL("Filtering the scan results as the " "results may belong to wrong band")); csrScanFilterResults(pMac); } else { smsLog(pMac, LOG1, FL("11d_scan_done will flush the scan" " results")); } pCommand->u.scanCmd.abortScanDueToBandChange = eANI_BOOLEAN_FALSE; } csrSaveScanResults(pMac, pCommand->u.scanCmd.reason, sessionId); #ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR { vos_log_scan_pkt_type *pScanLog = NULL; tScanResultHandle hScanResult; tCsrScanResultInfo *pScanResult; tDot11fBeaconIEs *pIes; int n = 0, c = 0; WLAN_VOS_DIAG_LOG_ALLOC(pScanLog, vos_log_scan_pkt_type, LOG_WLAN_SCAN_C); if(pScanLog) { if(eCsrScanBgScan == pCommand->u.scanCmd.reason || eCsrScanProbeBss == pCommand->u.scanCmd.reason || eCsrScanSetBGScanParam == pCommand->u.scanCmd.reason) { pScanLog->eventId = WLAN_SCAN_EVENT_HO_SCAN_RSP; } else { if( eSIR_PASSIVE_SCAN != pMac->scan.curScanType ) { pScanLog->eventId = WLAN_SCAN_EVENT_ACTIVE_SCAN_RSP; } else { pScanLog->eventId = WLAN_SCAN_EVENT_PASSIVE_SCAN_RSP; } } if(eSIR_SME_SUCCESS == pScanRsp->statusCode) { if(HAL_STATUS_SUCCESS(csrScanGetResult(pMac, NULL, &hScanResult))) { while(((pScanResult = csrScanResultGetNext(pMac, hScanResult)) != NULL)) { if( n < VOS_LOG_MAX_NUM_BSSID ) { if(!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, &pScanResult->BssDescriptor, &pIes))) { smsLog(pMac, LOGE, FL(" fail to parse IEs")); break; } vos_mem_copy(pScanLog->bssid[n], pScanResult->BssDescriptor.bssId, 6); if(pIes && pIes->SSID.present && VOS_LOG_MAX_SSID_SIZE >= pIes->SSID.num_ssid) { vos_mem_copy(pScanLog->ssid[n], pIes->SSID.ssid, pIes->SSID.num_ssid); } vos_mem_free(pIes); n++; } c++; } pScanLog->numSsid = (v_U8_t)n; pScanLog->totalSsid = (v_U8_t)c; csrScanResultPurge(pMac, hScanResult); } } else { pScanLog->status = WLAN_SCAN_STATUS_FAILURE; } WLAN_VOS_DIAG_LOG_REPORT(pScanLog); } } #endif //#ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR NextCommand = csrScanGetNextCommandState(pMac, pCommand, fSuccess); //We reuse the command here instead reissue a new command switch(NextCommand) { case eCsrNext11dScan1Success: case eCsrNext11dScan2Success: smsLog( pMac, LOG2, FL("11dScan1/3 produced results. Reissue Active scan...")); // if we found country information, no need to continue scanning further, bail out fRemoveCommand = eANI_BOOLEAN_TRUE; NextCommand = eCsrNext11dScanComplete; break; case eCsrNext11dScan1Failure: //We are not done yet. 11d scan fail once. We will try to reset anything and do it over again //The only meaningful thing for this retry is that we cannot find 11d information after a reset so //we clear the "old" 11d info and give it once more chance fRemoveCommand = csrHandleScan11d1Failure(pMac, pCommand); if(fRemoveCommand) { NextCommand = eCsrNext11dScanComplete; } break; case eCsrNextLostLinkScan1Success: if(!HAL_STATUS_SUCCESS(csrIssueRoamAfterLostlinkScan(pMac, sessionId, eCsrLostLink1))) { csrScanHandleFailedLostlink1(pMac, sessionId); } break; case eCsrNextLostLinkScan2Success: if(!HAL_STATUS_SUCCESS(csrIssueRoamAfterLostlinkScan(pMac, sessionId, eCsrLostLink2))) { csrScanHandleFailedLostlink2(pMac, sessionId); } break; case eCsrNextLostLinkScan3Success: if(!HAL_STATUS_SUCCESS(csrIssueRoamAfterLostlinkScan(pMac, sessionId, eCsrLostLink3))) { csrScanHandleFailedLostlink3(pMac, sessionId); } break; case eCsrNextLostLinkScan1Failed: csrScanHandleFailedLostlink1(pMac, sessionId); break; case eCsrNextLostLinkScan2Failed: csrScanHandleFailedLostlink2(pMac, sessionId); break; case eCsrNextLostLinkScan3Failed: csrScanHandleFailedLostlink3(pMac, sessionId); break; case eCsrNexteScanForSsidSuccess: csrScanHandleSearchForSSID(pMac, pCommand); break; case eCsrNexteScanForSsidFailure: csrScanHandleSearchForSSIDFailure(pMac, pCommand); break; case eCsrNextIdleScanComplete: pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; break; case eCsrNextCapChangeScanComplete: csrScanHandleCapChangeScanComplete(pMac, sessionId); break; default: break; } } else { smsLog( pMac, LOGW, FL("Scan Completion called but SCAN command is not ACTIVE ...")); fRemoveCommand = eANI_BOOLEAN_FALSE; } } else { smsLog( pMac, LOGW, FL("Scan Completion called but NO commands are ACTIVE ...")); fRemoveCommand = eANI_BOOLEAN_FALSE; } return( fRemoveCommand ); } static void csrScanRemoveDupBssDescriptionFromInterimList( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDescr, tDot11fBeaconIEs *pIes) { tListElem *pEntry; tCsrScanResult *pCsrBssDescription; csrLLLock(&pMac->scan.tempScanResults); // Walk through all the chained BssDescriptions. If we find a chained BssDescription that // matches the BssID of the BssDescription passed in, then these must be duplicate scan // results for this Bss. In that case, remove the 'old' Bss description from the linked list. pEntry = csrLLPeekHead(&pMac->scan.tempScanResults, LL_ACCESS_NOLOCK); while( pEntry ) { pCsrBssDescription = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); // we have a duplicate scan results only when BSSID, SSID, Channel and NetworkType // matches if ( csrIsDuplicateBssDescription( pMac, &pCsrBssDescription->Result.BssDescriptor, pSirBssDescr, pIes, FALSE ) ) { pSirBssDescr->rssi = (tANI_S8)( (((tANI_S32)pSirBssDescr->rssi * CSR_SCAN_RESULT_RSSI_WEIGHT ) + ((tANI_S32)pCsrBssDescription->Result.BssDescriptor.rssi * (100 - CSR_SCAN_RESULT_RSSI_WEIGHT) )) / 100 ); // Remove the 'old' entry from the list.... if(csrLLRemoveEntry(&pMac->scan.tempScanResults, pEntry, LL_ACCESS_NOLOCK)) { csrCheckNSaveWscIe(pMac, pSirBssDescr, &pCsrBssDescription->Result.BssDescriptor); // we need to free the memory associated with this node csrFreeScanResultEntry( pMac, pCsrBssDescription ); } // If we found a match, we can stop looking through the list. break; } pEntry = csrLLNext(&pMac->scan.tempScanResults, pEntry, LL_ACCESS_NOLOCK); } csrLLUnlock(&pMac->scan.tempScanResults); } //Caller allocated memory pfNewBssForConn to return whether new candidate for //current connection is found. Cannot be NULL tCsrScanResult *csrScanSaveBssDescriptionToInterimList( tpAniSirGlobal pMac, tSirBssDescription *pBSSDescription, tDot11fBeaconIEs *pIes) { tCsrScanResult *pCsrBssDescription = NULL; tANI_U32 cbBSSDesc; tANI_U32 cbAllocated; // figure out how big the BSS description is (the BSSDesc->length does NOT // include the size of the length field itself). cbBSSDesc = pBSSDescription->length + sizeof( pBSSDescription->length ); cbAllocated = sizeof( tCsrScanResult ) + cbBSSDesc; pCsrBssDescription = vos_mem_malloc(cbAllocated); if ( NULL != pCsrBssDescription ) { vos_mem_set(pCsrBssDescription, cbAllocated, 0); pCsrBssDescription->AgingCount = (tANI_S32)pMac->roam.configParam.agingCount; smsLog(pMac, LOGW, FL(" Set Aging Count = %d for BSS "MAC_ADDRESS_STR" "), pCsrBssDescription->AgingCount, MAC_ADDR_ARRAY(pBSSDescription->bssId)); vos_mem_copy(&pCsrBssDescription->Result.BssDescriptor, pBSSDescription, cbBSSDesc ); //Save SSID separately for later use if( pIes->SSID.present && !csrIsNULLSSID(pIes->SSID.ssid, pIes->SSID.num_ssid) ) { //SSID not hidden tANI_U32 len = pIes->SSID.num_ssid; if (len > SIR_MAC_MAX_SSID_LENGTH) { // truncate to fit in our struct len = SIR_MAC_MAX_SSID_LENGTH; } pCsrBssDescription->Result.ssId.length = len; pCsrBssDescription->Result.timer = vos_timer_get_system_time(); vos_mem_copy(pCsrBssDescription->Result.ssId.ssId, pIes->SSID.ssid, len); } csrLLInsertTail( &pMac->scan.tempScanResults, &pCsrBssDescription->Link, LL_ACCESS_LOCK ); } return( pCsrBssDescription ); } tANI_BOOLEAN csrIsDuplicateBssDescription( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDesc1, tSirBssDescription *pSirBssDesc2, tDot11fBeaconIEs *pIes2, tANI_BOOLEAN fForced ) { tANI_BOOLEAN fMatch = FALSE; tSirMacCapabilityInfo *pCap1, *pCap2; tDot11fBeaconIEs *pIes1 = NULL; tDot11fBeaconIEs *pIesTemp = pIes2; pCap1 = (tSirMacCapabilityInfo *)&pSirBssDesc1->capabilityInfo; pCap2 = (tSirMacCapabilityInfo *)&pSirBssDesc2->capabilityInfo; if(pCap1->ess == pCap2->ess) { if (pCap1->ess && csrIsMacAddressEqual( pMac, (tCsrBssid *)pSirBssDesc1->bssId, (tCsrBssid *)pSirBssDesc2->bssId)&& (fForced || (vos_chan_to_band(pSirBssDesc1->channelId) == vos_chan_to_band((pSirBssDesc2->channelId))))) { fMatch = TRUE; // Check for SSID match, if exists do { if(!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSirBssDesc1, &pIes1))) { break; } if( NULL == pIesTemp ) { if(!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSirBssDesc2, &pIesTemp))) { break; } } if(pIes1->SSID.present && pIesTemp->SSID.present) { fMatch = csrIsSsidMatch(pMac, pIes1->SSID.ssid, pIes1->SSID.num_ssid, pIesTemp->SSID.ssid, pIesTemp->SSID.num_ssid, eANI_BOOLEAN_TRUE); } }while(0); } else if (pCap1->ibss && (pSirBssDesc1->channelId == pSirBssDesc2->channelId)) { do { if(!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSirBssDesc1, &pIes1))) { break; } if( NULL == pIesTemp ) { if(!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSirBssDesc2, &pIesTemp))) { break; } } //Same channel cannot have same SSID for different IBSS if(pIes1->SSID.present && pIesTemp->SSID.present) { fMatch = csrIsSsidMatch(pMac, pIes1->SSID.ssid, pIes1->SSID.num_ssid, pIesTemp->SSID.ssid, pIesTemp->SSID.num_ssid, eANI_BOOLEAN_TRUE); } }while(0); } /* In case of P2P devices, ess and ibss will be set to zero */ else if (!pCap1->ess && csrIsMacAddressEqual( pMac, (tCsrBssid *)pSirBssDesc1->bssId, (tCsrBssid *)pSirBssDesc2->bssId)) { fMatch = TRUE; } } if(pIes1) { vos_mem_free(pIes1); } if( (NULL == pIes2) && pIesTemp ) { //locally allocated vos_mem_free(pIesTemp); } return( fMatch ); } tANI_BOOLEAN csrIsNetworkTypeEqual( tSirBssDescription *pSirBssDesc1, tSirBssDescription *pSirBssDesc2 ) { return( pSirBssDesc1->nwType == pSirBssDesc2->nwType ); } //to check whether the BSS matches the dot11Mode static tANI_BOOLEAN csrScanIsBssAllowed(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes) { tANI_BOOLEAN fAllowed = eANI_BOOLEAN_FALSE; eCsrPhyMode phyMode; if(HAL_STATUS_SUCCESS(csrGetPhyModeFromBss(pMac, pBssDesc, &phyMode, pIes))) { switch(pMac->roam.configParam.phyMode) { case eCSR_DOT11_MODE_11b: fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11a != phyMode); break; case eCSR_DOT11_MODE_11g: fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11a != phyMode); break; case eCSR_DOT11_MODE_11g_ONLY: fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11g == phyMode); break; case eCSR_DOT11_MODE_11a: fAllowed = (tANI_BOOLEAN)((eCSR_DOT11_MODE_11b != phyMode) && (eCSR_DOT11_MODE_11g != phyMode)); break; case eCSR_DOT11_MODE_11n_ONLY: fAllowed = (tANI_BOOLEAN)((eCSR_DOT11_MODE_11n == phyMode)); break; #ifdef WLAN_FEATURE_11AC case eCSR_DOT11_MODE_11ac_ONLY: fAllowed = (tANI_BOOLEAN)((eCSR_DOT11_MODE_11ac == phyMode)); break; #endif case eCSR_DOT11_MODE_11b_ONLY: fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11b == phyMode); break; case eCSR_DOT11_MODE_11n: #ifdef WLAN_FEATURE_11AC case eCSR_DOT11_MODE_11ac: #endif default: fAllowed = eANI_BOOLEAN_TRUE; break; } } return (fAllowed); } //Return pIes to caller for future use when returning TRUE. static tANI_BOOLEAN csrScanValidateScanResult( tpAniSirGlobal pMac, tANI_U8 *pChannels, tANI_U8 numChn, tSirBssDescription *pBssDesc, tDot11fBeaconIEs **ppIes ) { tANI_BOOLEAN fValidChannel = FALSE; tDot11fBeaconIEs *pIes = NULL; tANI_U8 index; for( index = 0; index < numChn; index++ ) { /* * This check relies on the fact that a single BSS description is * returned in each ScanRsp call, which is the way LIM implemented * the scan req/rsp functions. We changed to this model when we ran * with a large number of APs. If this were to change, then this check * would have to mess with removing the bssDescription from somewhere * in an arbitrary index in the bssDescription array. */ if ( pChannels[ index ] == pBssDesc->channelId ) { fValidChannel = TRUE; break; } } *ppIes = NULL; if(fValidChannel) { if( HAL_STATUS_SUCCESS( csrGetParsedBssDescriptionIEs(pMac, pBssDesc, &pIes) ) ) { fValidChannel = csrScanIsBssAllowed(pMac, pBssDesc, pIes); if( fValidChannel ) { *ppIes = pIes; } else { vos_mem_free(pIes); } } else { fValidChannel = FALSE; } } return( fValidChannel ); } //Return whether last scan result is received static tANI_BOOLEAN csrScanProcessScanResults( tpAniSirGlobal pMac, tSmeCmd *pCommand, tSirSmeScanRsp *pScanRsp, tANI_BOOLEAN *pfRemoveCommand ) { tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE, fRemoveCommand = eANI_BOOLEAN_FALSE; tDot11fBeaconIEs *pIes = NULL; tANI_U32 cbParsed; tSirBssDescription *pSirBssDescription; tANI_U32 cbBssDesc; tANI_U32 cbScanResult = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription ) + sizeof(tSirBssDescription); //We need at least one CB tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo[pScanRsp->sessionId]; /* * Don't consider the scan rsp to be valid if the status code is Scan * Failure. Scan Failure is returned when the scan could not find anything. * So if we get scan failure return that the scan response is invalid. * Also check the length in the scan result for valid scan BssDescriptions. */ do { if ( ( cbScanResult <= pScanRsp->length ) && (( eSIR_SME_SUCCESS == pScanRsp->statusCode ) || ( eSIR_SME_MORE_SCAN_RESULTS_FOLLOW == pScanRsp->statusCode ) ) ) { tANI_U8 *pChannelList = NULL; tANI_U8 cChannels = 0; //Different scan type can reach this point, we need to distinguish it #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if( eCsrScanGetLfrResult == pCommand->u.scanCmd.reason ) { pChannelList = NULL; cChannels = 0; } else #endif if( eCsrScanSetBGScanParam == pCommand->u.scanCmd.reason ) { //eCsrScanSetBGScanParam uses different structure tCsrBGScanRequest *pBgScanReq = &pCommand->u.scanCmd.u.bgScanRequest; cChannels = pBgScanReq->ChannelInfo.numOfChannels; pChannelList = pBgScanReq->ChannelInfo.ChannelList; } else { //the rest use generic scan request cChannels = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels; pChannelList = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList; } // if the scan result is not on one of the channels in the Valid channel list, then it // must have come from an AP on an overlapping channel (in the 2.4GHz band). In this case, // let's drop the scan result. // // The other situation is where the scan request is for a scan on a particular channel set // and the scan result is from a // if the NumChannels is 0, then we are supposed to be scanning all channels. Use the full channel // list as the 'valid' channel list. Otherwise, use the specific channel list in the scan parms // as the valid channels. if ( 0 == cChannels ) { tANI_U32 len = sizeof(pMac->roam.validChannelList); if (HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac, (tANI_U8 *)pMac->roam.validChannelList, &len))) { pChannelList = pMac->roam.validChannelList; cChannels = (tANI_U8)len; } else { //Cannot continue smsLog( pMac, LOGE, "CSR: Processing internal SCAN results...csrGetCfgValidChannels failed" ); break; } } smsLog( pMac, LOG2, "CSR: Processing internal SCAN results..." ); cbParsed = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription ); pSirBssDescription = pScanRsp->bssDescription; while( cbParsed < pScanRsp->length ) { if ( csrScanValidateScanResult( pMac, pChannelList, cChannels, pSirBssDescription, &pIes ) ) { csrScanRemoveDupBssDescriptionFromInterimList(pMac, pSirBssDescription, pIes); csrScanSaveBssDescriptionToInterimList( pMac, pSirBssDescription, pIes ); if( eSIR_PASSIVE_SCAN == pMac->scan.curScanType ) { if( csrIs11dSupported( pMac) ) { //Check whether the BSS is acceptable base on 11d info and our configs. if( csrMatchCountryCode( pMac, NULL, pIes ) ) { //Double check whether the channel is acceptable by us. if( csrIsSupportedChannel( pMac, pSirBssDescription->channelId ) ) { pMac->scan.curScanType = eSIR_ACTIVE_SCAN; } } } else { pMac->scan.curScanType = eSIR_ACTIVE_SCAN; } } //Free the resource vos_mem_free(pIes); } // skip over the BSS description to the next one... cbBssDesc = pSirBssDescription->length + sizeof( pSirBssDescription->length ); cbParsed += cbBssDesc; pSirBssDescription = (tSirBssDescription *)((tANI_U8 *)pSirBssDescription + cbBssDesc ); } //while } else { smsLog( pMac, LOGW, " Scanrsp fail (0x%08X), length = %d (expected %d)", pScanRsp->statusCode, pScanRsp->length, cbScanResult); //HO bg scan/probe failed no need to try autonomously if(eCsrScanBgScan == pCommand->u.scanCmd.reason || eCsrScanProbeBss == pCommand->u.scanCmd.reason || #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD eCsrScanGetLfrResult == pCommand->u.scanCmd.reason || #endif eCsrScanSetBGScanParam == pCommand->u.scanCmd.reason) { fRemoveCommand = eANI_BOOLEAN_TRUE; } } }while(0); if ( eSIR_SME_MORE_SCAN_RESULTS_FOLLOW != pScanRsp->statusCode ) { smsLog(pMac, LOGE, "Found %d BSS, statusCode %d", csrLLCount(&pMac->scan.tempScanResults), pScanRsp->statusCode); smsLog(pMac, LOG1, "scan reason is %d", pCommand->u.scanCmd.reason); #ifdef FEATURE_WLAN_DIAG_SUPPORT csr_diag_event_report(pMac, eCSR_EVENT_SCAN_COMPLETE, eSIR_SUCCESS, eSIR_SUCCESS); if (csrLLCount(&pMac->scan.tempScanResults) > 0) csr_diag_event_report(pMac, eCSR_EVENT_SCAN_RES_FOUND, eSIR_SUCCESS, eSIR_SUCCESS); #endif fRemoveCommand = csrScanComplete( pMac, pScanRsp ); fRet = eANI_BOOLEAN_TRUE; }//if ( eSIR_SME_MORE_SCAN_RESULTS_FOLLOW != pScanRsp->statusCode ) if(pfRemoveCommand) { *pfRemoveCommand = fRemoveCommand; } #ifdef WLAN_AP_STA_CONCURRENCY if (pMac->fScanOffload) return fRet; if (!csrLLIsListEmpty( &pMac->scan.scanCmdPendingList, LL_ACCESS_LOCK )) { /* Pending scan commands in the list because the previous scan command * was split into a scan command on one channel + a scan command for all * remaining channels. * * Start timer to trigger processing of the next scan command. * NOTE for LFR: * Do not split scans if no concurrent infra connections are * active and if the scan is a BG scan triggered by LFR (OR) * any scan if LFR is in the middle of a BG scan. Splitting * the scan is delaying the time it takes for LFR to find * candidates and resulting in disconnects. */ if ((csrIsStaSessionConnected(pMac) && #ifdef FEATURE_WLAN_LFR (csrIsConcurrentInfraConnected(pMac) || ((pCommand->u.scanCmd.reason != eCsrScanBgScan) && (pNeighborRoamInfo->neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN))) && #endif (pCommand->u.scanCmd.u.scanRequest.p2pSearch != 1)) || (csrIsP2pSessionConnected(pMac))) { /* if active connected sessions present then continue to split scan * with specified interval between consecutive scans */ csrSetDefaultScanTiming(pMac, pCommand->u.scanCmd.u.scanRequest.scanType, &(pCommand->u.scanCmd.u.scanRequest)); vos_timer_start(&pMac->scan.hTimerStaApConcTimer, pCommand->u.scanCmd.u.scanRequest.restTime); } else { /* if no connected sessions present then initiate next scan command immediately */ /* minimum timer granularity is 10ms */ vos_timer_start(&pMac->scan.hTimerStaApConcTimer, 10); } } #endif return (fRet); } tANI_BOOLEAN csrScanIsWildCardScan( tpAniSirGlobal pMac, tSmeCmd *pCommand ) { tANI_U8 bssid[VOS_MAC_ADDR_SIZE] = {0, 0, 0, 0, 0, 0}; tANI_BOOLEAN f = vos_mem_compare(pCommand->u.scanCmd.u.scanRequest.bssid, bssid, sizeof(tCsrBssid)); //It is not a wild card scan if the bssid is not broadcast and the number of SSID is 1. return ((tANI_BOOLEAN)( (f || (0xff == pCommand->u.scanCmd.u.scanRequest.bssid[0])) && (pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs != 1) )); } #ifdef FEATURE_WLAN_SCAN_PNO eHalStatus csrSavePnoScanResults(tpAniSirGlobal pMac, tSirSmeScanRsp *pScanRsp, tANI_U8 sessionId) { tSirBssDescription *pSirBssDescription; tANI_U32 cbScanResult = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription ) + sizeof(tSirBssDescription); //We need at least one CB tCsrScanResult *pScanResult = NULL; tAniSSID tmpSsid; v_TIME_t timer; tANI_U32 cbParsed; tANI_U32 cbBssDesc; tANI_U16 ieLen; if ((cbScanResult > pScanRsp->length ) || (( eSIR_SME_SUCCESS != pScanRsp->statusCode ) && ( eSIR_SME_MORE_SCAN_RESULTS_FOLLOW != pScanRsp->statusCode ) ) ) return eHAL_STATUS_FAILURE; cbParsed = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription ); pSirBssDescription = pScanRsp->bssDescription; while( cbParsed < pScanRsp->length ) { // Check whether we have reach out limit if ( CSR_SCAN_IS_OVER_BSS_LIMIT(pMac) ) { smsLog( pMac, LOGW, FL( "BSS limit reached")); return eHAL_STATUS_RESOURCES; } ieLen = (pSirBssDescription->length + sizeof( pSirBssDescription->length ) - GET_FIELD_OFFSET( tSirBssDescription, ieFields )); pScanResult = vos_mem_malloc(sizeof(tCsrScanResult) + ieLen); if (NULL == pScanResult) { smsLog(pMac, LOGE, FL(" Fail to allocate memory for frame")); return eHAL_STATUS_RESOURCES; } vos_mem_set(pScanResult, sizeof(tCsrScanResult) + ieLen, 0); if (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSirBssDescription, (tDot11fBeaconIEs **)&pScanResult->Result.pvIes))) { smsLog(pMac, LOGE, FL(" Cannot parse IEs")); csrFreeScanResultEntry(pMac, pScanResult); return eHAL_STATUS_RESOURCES; } cbBssDesc = pSirBssDescription->length + sizeof( pSirBssDescription->length ); vos_mem_copy(&pScanResult->Result.BssDescriptor, pSirBssDescription, cbBssDesc); // Remove duplicate entry csrRemoveDupBssDescription( pMac, &pScanResult->Result.BssDescriptor, (tDot11fBeaconIEs *)pScanResult->Result.pvIes, &tmpSsid , &timer, FALSE ); //Add to scan cache csrScanAddResult(pMac, pScanResult, (tDot11fBeaconIEs *)pScanResult->Result.pvIes, sessionId); // skip over the BSS description to the next one... cbParsed += cbBssDesc; pSirBssDescription = (tSirBssDescription *)((tANI_U8 *)pSirBssDescription + cbBssDesc ); } return eHAL_STATUS_SUCCESS; } #endif eHalStatus csrScanSmeScanResponse( tpAniSirGlobal pMac, void *pMsgBuf ) { eHalStatus status = eHAL_STATUS_SUCCESS; tListElem *pEntry; tSmeCmd *pCommand; eCsrScanStatus scanStatus; tSirSmeScanRsp *pScanRsp = (tSirSmeScanRsp *)pMsgBuf; tSmeGetScanChnRsp *pScanChnInfo; tANI_BOOLEAN fRemoveCommand = eANI_BOOLEAN_TRUE; eCsrScanReason reason = eCsrScanOther; if (pMac->fScanOffload) pEntry = csrLLPeekHead(&pMac->sme.smeScanCmdActiveList, LL_ACCESS_LOCK); else pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK); if ( pEntry ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); if ( eSmeCommandScan == pCommand->command ) { scanStatus = (eSIR_SME_SUCCESS == pScanRsp->statusCode) ? eCSR_SCAN_SUCCESS : eCSR_SCAN_FAILURE; reason = pCommand->u.scanCmd.reason; switch(pCommand->u.scanCmd.reason) { case eCsrScanAbortBgScan: case eCsrScanAbortNormalScan: case eCsrScanBGScanAbort: case eCsrScanBGScanEnable: break; case eCsrScanGetScanChnInfo: pScanChnInfo = (tSmeGetScanChnRsp *)pMsgBuf; /* * status code not available in tSmeGetScanChnRsp, so * by default considering it to be success */ scanStatus = eSIR_SME_SUCCESS; csrScanAgeResults(pMac, pScanChnInfo); break; case eCsrScanForCapsChange: csrScanProcessScanResults( pMac, pCommand, pScanRsp, &fRemoveCommand ); break; case eCsrScanP2PFindPeer: scanStatus = ((eSIR_SME_SUCCESS == pScanRsp->statusCode) && (pScanRsp->length > 50)) ? eCSR_SCAN_FOUND_PEER : eCSR_SCAN_FAILURE; csrScanProcessScanResults( pMac, pCommand, pScanRsp, NULL ); break; case eCsrScanSetBGScanParam: default: if(csrScanProcessScanResults( pMac, pCommand, pScanRsp, &fRemoveCommand )) { /* * Not to get channel info if the scan is not a * wild card scan because it may cause scan results got * aged out incorrectly. */ if( csrScanIsWildCardScan( pMac, pCommand ) && (!pCommand->u.scanCmd.u.scanRequest.p2pSearch) #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD && (pCommand->u.scanCmd.reason != eCsrScanGetLfrResult) #endif ) { //Get the list of channels scanned if( pCommand->u.scanCmd.reason != eCsrScanUserRequest) { csrScanGetScanChnInfo(pMac, pCommand->sessionId, NULL, NULL, pCommand->u.scanCmd.scanID); } else { csrScanGetScanChnInfo(pMac, pCommand->sessionId, pCommand->u.scanCmd.pContext, pCommand->u.scanCmd.callback, pCommand->u.scanCmd.scanID); pCommand->u.scanCmd.callback = NULL; } } } break; }//switch if(fRemoveCommand) { csrReleaseScanCommand(pMac, pCommand, scanStatus); } smeProcessPendingQueue( pMac ); } #ifdef FEATURE_WLAN_SCAN_PNO else if (pMac->pnoOffload && !HAL_STATUS_SUCCESS(csrSavePnoScanResults(pMac, pScanRsp, pScanRsp->sessionId))) { smsLog( pMac, LOGE, "CSR: Unable to store scan results for PNO" ); status = eHAL_STATUS_FAILURE; } #endif else { smsLog( pMac, LOGE, "CSR: Scan Completion called but SCAN command is not ACTIVE ..." ); status = eHAL_STATUS_FAILURE; } } #ifdef FEATURE_WLAN_SCAN_PNO else if (pMac->pnoOffload && !HAL_STATUS_SUCCESS(csrSavePnoScanResults(pMac, pScanRsp, pScanRsp->sessionId))) { smsLog( pMac, LOGE, "CSR: Unable to store scan results for PNO" ); status = eHAL_STATUS_FAILURE; } #endif else if (pMac->pnoOffload == FALSE) { smsLog( pMac, LOGE, "CSR: Scan Completion called but NO commands are ACTIVE ..." ); status = eHAL_STATUS_FAILURE; } return (status); } tCsrScanResultInfo *csrScanResultGetFirst(tpAniSirGlobal pMac, tScanResultHandle hScanResult) { tListElem *pEntry; tCsrScanResult *pResult; tCsrScanResultInfo *pRet = NULL; tScanResultList *pResultList = (tScanResultList *)hScanResult; if(pResultList) { csrLLLock(&pResultList->List); pEntry = csrLLPeekHead(&pResultList->List, LL_ACCESS_NOLOCK); if(pEntry) { pResult = GET_BASE_ADDR(pEntry, tCsrScanResult, Link); pRet = &pResult->Result; } pResultList->pCurEntry = pEntry; csrLLUnlock(&pResultList->List); } return pRet; } tCsrScanResultInfo *csrScanResultGetNext(tpAniSirGlobal pMac, tScanResultHandle hScanResult) { tListElem *pEntry = NULL; tCsrScanResult *pResult = NULL; tCsrScanResultInfo *pRet = NULL; tScanResultList *pResultList = (tScanResultList *)hScanResult; if(pResultList) { csrLLLock(&pResultList->List); if(NULL == pResultList->pCurEntry) { pEntry = csrLLPeekHead(&pResultList->List, LL_ACCESS_NOLOCK); } else { pEntry = csrLLNext(&pResultList->List, pResultList->pCurEntry, LL_ACCESS_NOLOCK); } if(pEntry) { pResult = GET_BASE_ADDR(pEntry, tCsrScanResult, Link); pRet = &pResult->Result; } pResultList->pCurEntry = pEntry; csrLLUnlock(&pResultList->List); } return pRet; } //This function moves the first BSS that matches the bssid to the head of the result eHalStatus csrMoveBssToHeadFromBSSID(tpAniSirGlobal pMac, tCsrBssid *bssid, tScanResultHandle hScanResult) { eHalStatus status = eHAL_STATUS_FAILURE; tScanResultList *pResultList = (tScanResultList *)hScanResult; tCsrScanResult *pResult = NULL; tListElem *pEntry = NULL; if(pResultList && bssid) { csrLLLock(&pResultList->List); pEntry = csrLLPeekHead(&pResultList->List, LL_ACCESS_NOLOCK); while(pEntry) { pResult = GET_BASE_ADDR(pEntry, tCsrScanResult, Link); if (vos_mem_compare(bssid, pResult->Result.BssDescriptor.bssId, sizeof(tCsrBssid))) { status = eHAL_STATUS_SUCCESS; csrLLRemoveEntry(&pResultList->List, pEntry, LL_ACCESS_NOLOCK); csrLLInsertHead(&pResultList->List, pEntry, LL_ACCESS_NOLOCK); break; } pEntry = csrLLNext(&pResultList->List, pResultList->pCurEntry, LL_ACCESS_NOLOCK); } csrLLUnlock(&pResultList->List); } return (status); } //Remove the BSS if possible. //Return -- TRUE == the BSS is remove. False == Fail to remove it //This function is called when list lock is held. Be caution what functions it can call. tANI_BOOLEAN csrScanAgeOutBss(tpAniSirGlobal pMac, tCsrScanResult *pResult) { tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE; tANI_U32 i; tCsrRoamSession *pSession; tANI_BOOLEAN isConnBssfound = eANI_BOOLEAN_FALSE; for( i = 0; i < CSR_ROAM_SESSION_MAX; i++ ) { if( CSR_IS_SESSION_VALID( pMac, i ) ) { pSession = CSR_GET_SESSION( pMac, i ); //Not to remove the BSS we are connected to. if(csrIsConnStateConnectedInfra(pMac, i) && (NULL != pSession->pConnectBssDesc) && (csrIsDuplicateBssDescription(pMac, &pResult->Result.BssDescriptor, pSession->pConnectBssDesc, NULL, FALSE)) ) { isConnBssfound = eANI_BOOLEAN_TRUE; break; } } } if( isConnBssfound ) { /* Reset the counter so that aging out of connected BSS won't happen too soon */ pResult->AgingCount = (tANI_S32)pMac->roam.configParam.agingCount; smsLog(pMac, LOGW, FL(" Connected BSS, Set Aging Count=%d for BSS "MAC_ADDRESS_STR" "), pResult->AgingCount, MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId)); pResult->Result.BssDescriptor.nReceivedTime = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd); return (fRet); } else { smsLog(pMac, LOGW, "Aging out BSS "MAC_ADDRESS_STR" Channel %d", MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId), pResult->Result.BssDescriptor.channelId); //No need to hold the spin lock because caller should hold the lock for pMac->scan.scanResultList if(csrLLRemoveEntry(&pMac->scan.scanResultList, &pResult->Link, LL_ACCESS_NOLOCK)) { if (csrIsMacAddressEqual(pMac, (tCsrBssid *) pResult->Result.BssDescriptor.bssId, (tCsrBssid *) pMac->scan.currentCountryBssid)) { smsLog(pMac, LOGW, "Aging out 11d BSS "MAC_ADDRESS_STR, MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId)); pMac->scan.currentCountryRSSI = -128; } csrFreeScanResultEntry(pMac, pResult); fRet = eANI_BOOLEAN_TRUE; } } return (fRet); } eHalStatus csrScanAgeResults(tpAniSirGlobal pMac, tSmeGetScanChnRsp *pScanChnInfo) { eHalStatus status = eHAL_STATUS_SUCCESS; tListElem *pEntry, *tmpEntry; tCsrScanResult *pResult; tLimScanChn *pChnInfo; tANI_U8 i; csrLLLock(&pMac->scan.scanResultList); for(i = 0; i < pScanChnInfo->numChn; i++) { pChnInfo = &pScanChnInfo->scanChn[i]; pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK); while( pEntry ) { tmpEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); pResult = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); if(pResult->Result.BssDescriptor.channelId == pChnInfo->channelId) { if(pResult->AgingCount <= 0) { smsLog(pMac, LOGW, " age out due to ref count"); csrScanAgeOutBss(pMac, pResult); } else { pResult->AgingCount--; smsLog(pMac, LOGW, FL("Decremented AgingCount=%d for BSS "MAC_ADDRESS_STR""), pResult->AgingCount, MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId)); } } pEntry = tmpEntry; } } csrLLUnlock(&pMac->scan.scanResultList); return (status); } eHalStatus csrSendMBScanReq( tpAniSirGlobal pMac, tANI_U16 sessionId, tCsrScanRequest *pScanReq, tScanReqParam *pScanReqParam ) { eHalStatus status = eHAL_STATUS_SUCCESS; tSirSmeScanReq *pMsg; tANI_U16 msgLen; tANI_U8 bssid[VOS_MAC_ADDR_SIZE] = {0, 0, 0, 0, 0, 0}; tSirScanType scanType = pScanReq->scanType; tANI_U32 minChnTime; //in units of milliseconds tANI_U32 maxChnTime; //in units of milliseconds tANI_U32 i; tANI_U8 selfMacAddr[VOS_MAC_ADDR_SIZE]; tANI_U8 *pSelfMac = NULL; msgLen = (tANI_U16)(sizeof( tSirSmeScanReq ) - sizeof( pMsg->channelList.channelNumber ) + ( sizeof( pMsg->channelList.channelNumber ) * pScanReq->ChannelInfo.numOfChannels )) + ( pScanReq->uIEFieldLen ) ; pMsg = vos_mem_malloc(msgLen); if ( NULL == pMsg ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (HAL_STATUS_SUCCESS(status)) { do { vos_mem_set(pMsg, msgLen, 0); pMsg->messageType = pal_cpu_to_be16((tANI_U16)eWNI_SME_SCAN_REQ); pMsg->length = pal_cpu_to_be16(msgLen); //ToDO: Fill in session info when we need to do scan base on session. if ((pMac->fScanOffload) && (sessionId != CSR_SESSION_ID_INVALID)) { pMsg->sessionId = sessionId; } else { /* if sessionId == CSR_SESSION_ID_INVALID, then send the scan request on first available session */ pMsg->sessionId = 0; } if (pMsg->sessionId >= CSR_ROAM_SESSION_MAX) smsLog( pMac, LOGE, FL(" Invalid Sme Session ID = %d"), pMsg->sessionId ); pMsg->transactionId = 0; pMsg->dot11mode = (tANI_U8) csrTranslateToWNICfgDot11Mode(pMac, csrFindBestPhyMode( pMac, pMac->roam.configParam.phyMode )); pMsg->bssType = pal_cpu_to_be32(csrTranslateBsstypeToMacType(pScanReq->BSSType)); if ( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { pSelfMac = (tANI_U8 *)&pMac->roam.roamSession[sessionId].selfMacAddr; } else { // Since we don't have session for the scanning, we find a valid session. In case we fail to // do so, get the WNI_CFG_STA_ID for( i = 0; i < CSR_ROAM_SESSION_MAX; i++ ) { if( CSR_IS_SESSION_VALID( pMac, i ) ) { pSelfMac = (tANI_U8 *)&pMac->roam.roamSession[i].selfMacAddr; break; } } if( CSR_ROAM_SESSION_MAX == i ) { tANI_U32 len = VOS_MAC_ADDR_SIZE; pSelfMac = selfMacAddr; status = ccmCfgGetStr( pMac, WNI_CFG_STA_ID, pSelfMac, &len ); if( !HAL_STATUS_SUCCESS( status ) || ( len < VOS_MAC_ADDR_SIZE ) ) { smsLog( pMac, LOGE, FL(" Can not get self MAC address from CFG status = %d"), status ); //Force failed status status = eHAL_STATUS_FAILURE; break; } } } vos_mem_copy((tANI_U8 *)pMsg->selfMacAddr, pSelfMac, sizeof(tSirMacAddr)); //sirCopyMacAddr vos_mem_copy((tANI_U8 *)pMsg->bssId, (tANI_U8 *)&pScanReq->bssid, sizeof(tSirMacAddr)); if ( vos_mem_compare(pScanReq->bssid, bssid, sizeof(tCsrBssid))) { vos_mem_set(pMsg->bssId, sizeof(tSirMacAddr), 0xff); } else { vos_mem_copy(pMsg->bssId, pScanReq->bssid, VOS_MAC_ADDR_SIZE); } minChnTime = pScanReq->minChnTime; maxChnTime = pScanReq->maxChnTime; //Verify the scan type first, if the scan is active scan, we need to make sure we //are allowed to do so. /* if 11d is enabled & we don't see any beacon around, scan type falls back to passive. But in BT AMP STA mode we need to send out a directed probe*/ if( (eSIR_PASSIVE_SCAN != scanType) && (eCSR_SCAN_P2P_DISCOVERY != pScanReq->requestType) && (eCSR_BSS_TYPE_WDS_STA != pScanReq->BSSType) && (eANI_BOOLEAN_FALSE == pMac->scan.fEnableBypass11d)) { scanType = pMac->scan.curScanType; if(eSIR_PASSIVE_SCAN == pMac->scan.curScanType) { if(minChnTime < pMac->roam.configParam.nPassiveMinChnTime) { minChnTime = pMac->roam.configParam.nPassiveMinChnTime; } if(maxChnTime < pMac->roam.configParam.nPassiveMaxChnTime) { maxChnTime = pMac->roam.configParam.nPassiveMaxChnTime; } } } pMsg->scanType = pal_cpu_to_be32(scanType); pMsg->numSsid = (pScanReq->SSIDs.numOfSSIDs < SIR_SCAN_MAX_NUM_SSID) ? pScanReq->SSIDs.numOfSSIDs : SIR_SCAN_MAX_NUM_SSID; if((pScanReq->SSIDs.numOfSSIDs != 0) && ( eSIR_PASSIVE_SCAN != scanType )) { for (i = 0; i < pMsg->numSsid; i++) { vos_mem_copy(&pMsg->ssId[i], &pScanReq->SSIDs.SSIDList[i].SSID, sizeof(tSirMacSSid)); } } else { //Otherwise we scan all SSID and let the result filter later for (i = 0; i < SIR_SCAN_MAX_NUM_SSID; i++) { pMsg->ssId[i].length = 0; } } pMsg->minChannelTime = pal_cpu_to_be32(minChnTime); pMsg->maxChannelTime = pal_cpu_to_be32(maxChnTime); pMsg->minChannelTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; pMsg->maxChannelTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; //hidden SSID option pMsg->hiddenSsid = pScanReqParam->hiddenSsid; /* maximum rest time */ pMsg->restTime = pScanReq->restTime; /* Minimum rest time */ pMsg->min_rest_time = pScanReq->min_rest_time; /* Idle time */ pMsg->idle_time = pScanReq->idle_time; pMsg->returnAfterFirstMatch = pScanReqParam->bReturnAfter1stMatch; // All the scan results caching will be done by Roaming // We do not want LIM to do any caching of scan results, // so delete the LIM cache on all scan requests pMsg->returnFreshResults = pScanReqParam->freshScan; //Always ask for unique result pMsg->returnUniqueResults = pScanReqParam->fUniqueResult; pMsg->channelList.numChannels = (tANI_U8)pScanReq->ChannelInfo.numOfChannels; if(pScanReq->ChannelInfo.numOfChannels) { //Assuming the channelNumber is tANI_U8 (1 byte) vos_mem_copy(pMsg->channelList.channelNumber, pScanReq->ChannelInfo.ChannelList, pScanReq->ChannelInfo.numOfChannels); } pMsg->uIEFieldLen = (tANI_U16) pScanReq->uIEFieldLen; pMsg->uIEFieldOffset = (tANI_U16)(sizeof( tSirSmeScanReq ) - sizeof( pMsg->channelList.channelNumber ) + ( sizeof( pMsg->channelList.channelNumber ) * pScanReq->ChannelInfo.numOfChannels )) ; if(pScanReq->uIEFieldLen != 0) { vos_mem_copy((tANI_U8 *)pMsg+pMsg->uIEFieldOffset, pScanReq->pIEField, pScanReq->uIEFieldLen); } pMsg->p2pSearch = pScanReq->p2pSearch; if (pScanReq->requestType == eCSR_SCAN_HO_BG_SCAN) { pMsg->backgroundScanMode = eSIR_ROAMING_SCAN; } }while(0); smsLog(pMac, LOG1, FL("domainIdCurrent %s (%d) scanType %s (%d)" "bssType %s (%d), requestType %s(%d)" "numChannels %d"), voss_DomainIdtoString(pMac->scan.domainIdCurrent), pMac->scan.domainIdCurrent, lim_ScanTypetoString(pMsg->scanType), pMsg->scanType, lim_BssTypetoString(pMsg->bssType), pMsg->bssType, sme_requestTypetoString(pScanReq->requestType), pScanReq->requestType, pMsg->channelList.numChannels); for(i = 0; i < pMsg->channelList.numChannels; i++) { smsLog(pMac, LOG1, FL("channelNumber[%d]= %d"), i, pMsg->channelList.channelNumber[i]); } if(HAL_STATUS_SUCCESS(status)) { status = palSendMBMessage(pMac->hHdd, pMsg); } else { smsLog( pMac, LOGE, FL(" failed to send down scan req with status = %d"), status ); vos_mem_free(pMsg); } }//Success allocated memory else { smsLog( pMac, LOGE, FL(" memory allocation failure")); } if(!HAL_STATUS_SUCCESS(status)) { smsLog( pMac, LOG1, FL("Failed: SId: %d FirstMatch = %d" " UniqueResult = %d freshScan = %d hiddenSsid = %d"), sessionId, pScanReqParam->bReturnAfter1stMatch, pScanReqParam->fUniqueResult, pScanReqParam->freshScan, pScanReqParam->hiddenSsid ); smsLog( pMac, LOG1, FL("scanType = %s (%d) BSSType = %s (%d) " "numOfSSIDs = %d numOfChannels = %d requestType = %s (%d)" " p2pSearch = %d\n"), lim_ScanTypetoString(pScanReq->scanType), pScanReq->scanType, lim_BssTypetoString(pScanReq->BSSType), pScanReq->BSSType, pScanReq->SSIDs.numOfSSIDs, pScanReq->ChannelInfo.numOfChannels, sme_requestTypetoString(pScanReq->requestType), pScanReq->requestType, pScanReq->p2pSearch ); } return( status ); } eHalStatus csrSendMBScanResultReq( tpAniSirGlobal pMac, tANI_U32 sessionId, tScanReqParam *pScanReqParam ) { eHalStatus status = eHAL_STATUS_SUCCESS; tSirSmeScanReq *pMsg; tANI_U16 msgLen; msgLen = (tANI_U16)(sizeof( tSirSmeScanReq )); pMsg = vos_mem_malloc(msgLen); if ( NULL == pMsg ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pMsg, msgLen, 0); pMsg->messageType = pal_cpu_to_be16((tANI_U16)eWNI_SME_SCAN_REQ); pMsg->length = pal_cpu_to_be16(msgLen); pMsg->sessionId = sessionId; pMsg->transactionId = 0; pMsg->returnFreshResults = pScanReqParam->freshScan; //Always ask for unique result pMsg->returnUniqueResults = pScanReqParam->fUniqueResult; pMsg->returnAfterFirstMatch = pScanReqParam->bReturnAfter1stMatch; status = palSendMBMessage(pMac->hHdd, pMsg); if (!HAL_STATUS_SUCCESS(status)) { smsLog( pMac, LOGE, FL(" failed to send down scan req with status = %d\n"), status ); } } return( status ); } eHalStatus csrScanChannels( tpAniSirGlobal pMac, tSmeCmd *pCommand ) { eHalStatus status = eHAL_STATUS_FAILURE; tScanReqParam scanReq; do { /* * Don't delete cached results. Rome rssi based scan candidates * may land up in scan cache instead of LFR cache. * They will be deleted upon query. */ scanReq.freshScan = SIR_BG_SCAN_RETURN_FRESH_RESULTS; scanReq.fUniqueResult = TRUE; scanReq.hiddenSsid = SIR_SCAN_NO_HIDDEN_SSID; if(eCsrScanForSsid == pCommand->u.scanCmd.reason) { scanReq.bReturnAfter1stMatch = CSR_SCAN_RETURN_AFTER_FIRST_MATCH; } else { // Basically do scan on all channels even for 11D 1st scan case. scanReq.bReturnAfter1stMatch = CSR_SCAN_RETURN_AFTER_ALL_CHANNELS; } if((eCsrScanBgScan == pCommand->u.scanCmd.reason)|| (eCsrScanProbeBss == pCommand->u.scanCmd.reason)) { scanReq.hiddenSsid = SIR_SCAN_HIDDEN_SSID_PE_DECISION; } #ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR { vos_log_scan_pkt_type *pScanLog = NULL; WLAN_VOS_DIAG_LOG_ALLOC(pScanLog, vos_log_scan_pkt_type, LOG_WLAN_SCAN_C); if(pScanLog) { if(eCsrScanBgScan == pCommand->u.scanCmd.reason || eCsrScanProbeBss == pCommand->u.scanCmd.reason) { pScanLog->eventId = WLAN_SCAN_EVENT_HO_SCAN_REQ; } else { if( (eSIR_PASSIVE_SCAN != pCommand->u.scanCmd.u.scanRequest.scanType) && (eSIR_PASSIVE_SCAN != pMac->scan.curScanType) ) { pScanLog->eventId = WLAN_SCAN_EVENT_ACTIVE_SCAN_REQ; } else { pScanLog->eventId = WLAN_SCAN_EVENT_PASSIVE_SCAN_REQ; } } pScanLog->minChnTime = (v_U8_t)pCommand->u.scanCmd.u.scanRequest.minChnTime; pScanLog->maxChnTime = (v_U8_t)pCommand->u.scanCmd.u.scanRequest.maxChnTime; pScanLog->numChannel = (v_U8_t)pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels; if(pScanLog->numChannel && (pScanLog->numChannel < VOS_LOG_MAX_NUM_CHANNEL)) { vos_mem_copy(pScanLog->channels, pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList, pScanLog->numChannel); } WLAN_VOS_DIAG_LOG_REPORT(pScanLog); } } #endif //#ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR csrClearVotesForCountryInfo(pMac); status = csrSendMBScanReq(pMac, pCommand->sessionId, &pCommand->u.scanCmd.u.scanRequest, &scanReq); }while(0); return( status ); } eHalStatus csrScanRetrieveResult(tpAniSirGlobal pMac, tSmeCmd *pCommand) { eHalStatus status = eHAL_STATUS_FAILURE; tScanReqParam scanReq; do { #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (eCsrScanGetLfrResult == pCommand->u.scanCmd.reason) { //to get the LFR candidates from PE cache scanReq.freshScan = SIR_BG_SCAN_RETURN_LFR_CACHED_RESULTS|SIR_BG_SCAN_PURGE_LFR_RESULTS; scanReq.fUniqueResult = TRUE; scanReq.bReturnAfter1stMatch = CSR_SCAN_RETURN_AFTER_ALL_CHANNELS; } else #endif { //not a fresh scan scanReq.freshScan = SIR_BG_SCAN_PURGE_RESUTLS; scanReq.fUniqueResult = TRUE; scanReq.bReturnAfter1stMatch = CSR_SCAN_RETURN_AFTER_ALL_CHANNELS; } status = csrSendMBScanResultReq(pMac, pCommand->sessionId, &scanReq); }while(0); return (status); } eHalStatus csrProcessScanCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand ) { eHalStatus status = eHAL_STATUS_SUCCESS; tCsrChannelInfo newChannelInfo = {0, NULL}; int i, j; tANI_U8 *pChannel = NULL; tANI_U32 len = 0; // Transition to Scanning state... if (!pMac->fScanOffload) { for( i = 0; i < CSR_ROAM_SESSION_MAX; i++ ) { pCommand->u.scanCmd.lastRoamState[i] = csrRoamStateChange( pMac, eCSR_ROAMING_STATE_SCANNING, i); smsLog( pMac, LOG3, "starting SCAN command from %d state...." " reason is %d", pCommand->u.scanCmd.lastRoamState[i], pCommand->u.scanCmd.reason ); } } else { pCommand->u.scanCmd.lastRoamState[pCommand->sessionId] = csrRoamStateChange(pMac, eCSR_ROAMING_STATE_SCANNING, pCommand->sessionId); smsLog( pMac, LOG3, "starting SCAN command from %d state.... reason is %d", pCommand->u.scanCmd.lastRoamState[pCommand->sessionId], pCommand->u.scanCmd.reason ); } switch(pCommand->u.scanCmd.reason) { #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD case eCsrScanGetLfrResult: #endif case eCsrScanGetResult: case eCsrScanForCapsChange: //For cap change, LIM already save BSS description status = csrScanRetrieveResult(pMac, pCommand); break; case eCsrScanSetBGScanParam: status = csrProcessSetBGScanParam(pMac, pCommand); break; case eCsrScanBGScanAbort: status = csrSetCfgBackgroundScanPeriod(pMac, 0); break; case eCsrScanBGScanEnable: status = csrSetCfgBackgroundScanPeriod(pMac, pMac->roam.configParam.bgScanInterval); break; case eCsrScanGetScanChnInfo: status = csrScanGetScanChannelInfo(pMac, pCommand->sessionId); break; case eCsrScanUserRequest: if(pMac->roam.configParam.fScanTwice) { //We scan 2.4 channel twice if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels && (NULL != pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList)) { len = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels; /* Allocate twice the channel */ newChannelInfo.ChannelList = vos_mem_malloc(len * 2); pChannel = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList; } else { //get the valid channel list to scan all. len = sizeof(pMac->roam.validChannelList); if (HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac, (tANI_U8 *)pMac->roam.validChannelList, &len))) { //allocate twice the channel newChannelInfo.ChannelList = (tANI_U8 *)vos_mem_malloc(len * 2); pChannel = pMac->roam.validChannelList; } } if(NULL == newChannelInfo.ChannelList) { newChannelInfo.numOfChannels = 0; } else { j = 0; for(i = 0; i < len; i++) { newChannelInfo.ChannelList[j++] = pChannel[i]; if(CSR_MAX_24GHz_CHANNEL_NUMBER >= pChannel[i]) { newChannelInfo.ChannelList[j++] = pChannel[i]; } } if(NULL != pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList) { //pChannel points to the channellist from the command, free it. vos_mem_free(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList); pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL; } pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = j; pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = newChannelInfo.ChannelList; } } //if(pMac->roam.configParam.fScanTwice) status = csrScanChannels(pMac, pCommand); break; default: status = csrScanChannels(pMac, pCommand); break; } if(!HAL_STATUS_SUCCESS(status)) { csrReleaseScanCommand(pMac, pCommand, eCSR_SCAN_FAILURE); } return (status); } eHalStatus csrScanSetBGScanparams(tpAniSirGlobal pMac, tCsrBGScanRequest *pScanReq) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pCommand = NULL; if(pScanReq) { do { pCommand = csrGetCommandBuffer(pMac); if(!pCommand) { status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); pCommand->command = eSmeCommandScan; pCommand->u.scanCmd.reason = eCsrScanSetBGScanParam; pCommand->u.scanCmd.callback = NULL; pCommand->u.scanCmd.pContext = NULL; vos_mem_copy(&pCommand->u.scanCmd.u.bgScanRequest, pScanReq, sizeof(tCsrBGScanRequest)); //we have to do the follow if(pScanReq->ChannelInfo.numOfChannels == 0) { pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList = NULL; } else { pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList = vos_mem_malloc(pScanReq->ChannelInfo.numOfChannels); if ( NULL != pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList ) { vos_mem_copy(pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList, pScanReq->ChannelInfo.ChannelList, pScanReq->ChannelInfo.numOfChannels); } else { smsLog(pMac, LOGE, FL("ran out of memory")); csrReleaseCommandScan(pMac, pCommand); return eHAL_STATUS_FAILURE; } } //scan req for SSID if(pScanReq->SSID.length) { vos_mem_copy(pCommand->u.scanCmd.u.bgScanRequest.SSID.ssId, pScanReq->SSID.ssId, pScanReq->SSID.length); pCommand->u.scanCmd.u.bgScanRequest.SSID.length = pScanReq->SSID.length; } pCommand->u.scanCmd.u.bgScanRequest.maxChnTime= pScanReq->maxChnTime; pCommand->u.scanCmd.u.bgScanRequest.minChnTime = pScanReq->minChnTime; pCommand->u.scanCmd.u.bgScanRequest.scanInterval = pScanReq->scanInterval; status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); csrReleaseCommandScan( pMac, pCommand ); break; } }while(0); } return (status); } eHalStatus csrScanBGScanAbort( tpAniSirGlobal pMac ) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pCommand = NULL; do { pCommand = csrGetCommandBuffer(pMac); if(!pCommand) { status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); pCommand->command = eSmeCommandScan; pCommand->u.scanCmd.reason = eCsrScanBGScanAbort; pCommand->u.scanCmd.callback = NULL; pCommand->u.scanCmd.pContext = NULL; status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); csrReleaseCommandScan( pMac, pCommand ); break; } }while(0); return (status); } //This will enable the background scan with the non-zero interval eHalStatus csrScanBGScanEnable(tpAniSirGlobal pMac) { eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pCommand = NULL; if(pMac->roam.configParam.bgScanInterval) { do { pCommand = csrGetCommandBuffer(pMac); if(!pCommand) { status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0); pCommand->command = eSmeCommandScan; pCommand->u.scanCmd.reason = eCsrScanBGScanEnable; pCommand->u.scanCmd.callback = NULL; pCommand->u.scanCmd.pContext = NULL; status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); csrReleaseCommandScan( pMac, pCommand ); break; } }while(0); } else { smsLog(pMac, LOGE, FL("cannot continue because the bgscan interval is 0")); status = eHAL_STATUS_INVALID_PARAMETER; } return (status); } eHalStatus csrScanCopyRequest(tpAniSirGlobal pMac, tCsrScanRequest *pDstReq, tCsrScanRequest *pSrcReq) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U32 len = sizeof(pMac->roam.validChannelList); tANI_U32 index = 0; tANI_U32 new_index = 0; eNVChannelEnabledType NVchannel_state; bool skip_dfs_chnl = pMac->roam.configParam.initial_scan_no_dfs_chnl || !pMac->scan.fEnableDFSChnlScan; do { status = csrScanFreeRequest(pMac, pDstReq); if(HAL_STATUS_SUCCESS(status)) { vos_mem_copy(pDstReq, pSrcReq, sizeof(tCsrScanRequest)); /* Re-initialize the pointers to NULL since we did a copy */ pDstReq->pIEField = NULL; pDstReq->ChannelInfo.ChannelList = NULL; pDstReq->SSIDs.SSIDList = NULL; if(pSrcReq->uIEFieldLen == 0) { pDstReq->pIEField = NULL; } else { pDstReq->pIEField = vos_mem_malloc(pSrcReq->uIEFieldLen); if ( NULL == pDstReq->pIEField ) { status = eHAL_STATUS_FAILURE; smsLog(pMac, LOGE, FL("No memory for scanning IE fields")); break; } else { status = eHAL_STATUS_SUCCESS; vos_mem_copy(pDstReq->pIEField, pSrcReq->pIEField, pSrcReq->uIEFieldLen); pDstReq->uIEFieldLen = pSrcReq->uIEFieldLen; } }//Allocate memory for IE field { if(pSrcReq->ChannelInfo.numOfChannels == 0) { pDstReq->ChannelInfo.ChannelList = NULL; pDstReq->ChannelInfo.numOfChannels = 0; } else { pDstReq->ChannelInfo.ChannelList = vos_mem_malloc( pSrcReq->ChannelInfo.numOfChannels * sizeof(*pDstReq->ChannelInfo.ChannelList)); if ( NULL == pDstReq->ChannelInfo.ChannelList ) { status = eHAL_STATUS_FAILURE; pDstReq->ChannelInfo.numOfChannels = 0; smsLog(pMac, LOGE, FL("No memory for scanning Channel" " List")); break; } if((pSrcReq->scanType == eSIR_PASSIVE_SCAN) && (pSrcReq->requestType == eCSR_SCAN_REQUEST_11D_SCAN)) { for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels ; index++ ) { NVchannel_state = vos_nv_getChannelEnabledState( pSrcReq->ChannelInfo.ChannelList[index]); if (pSrcReq->ChannelInfo.ChannelList[index] < MIN_11P_CHANNEL && ((NV_CHANNEL_ENABLE == NVchannel_state) || ((NV_CHANNEL_DFS == NVchannel_state) && !skip_dfs_chnl))) { pDstReq->ChannelInfo.ChannelList[new_index] = pSrcReq->ChannelInfo.ChannelList[index]; new_index++; } } pDstReq->ChannelInfo.numOfChannels = new_index; } else if(HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac, pMac->roam.validChannelList, &len))) { new_index = 0; pMac->roam.numValidChannels = len; for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels ; index++ ) { /* Allow scan on valid channels only. * If it is p2p scan and valid channel list doesnt contain * social channels, enforce scan on social channels because * that is the only way to find p2p peers. * This can happen only if band is set to 5Ghz mode. */ if(pSrcReq->ChannelInfo.ChannelList[index] < MIN_11P_CHANNEL && ((csrRoamIsValidChannel(pMac, pSrcReq->ChannelInfo.ChannelList[index])) || ((eCSR_SCAN_P2P_DISCOVERY == pSrcReq->requestType) && CSR_IS_SOCIAL_CHANNEL(pSrcReq->ChannelInfo.ChannelList[index])))) { if( ((pSrcReq->skipDfsChnlInP2pSearch || skip_dfs_chnl) && (NV_CHANNEL_DFS == vos_nv_getChannelEnabledState(pSrcReq->ChannelInfo.ChannelList[index])) ) #ifdef FEATURE_WLAN_LFR /* * If LFR is requesting a contiguous scan * (i.e. numOfChannels > 1), then ignore * DFS channels. * TODO: vos_nv_getChannelEnabledState is returning * 120, 124 and 128 as non-DFS channels. Hence, the * use of direct check for channels below. */ || ((eCSR_SCAN_HO_BG_SCAN == pSrcReq->requestType) && (pSrcReq->ChannelInfo.numOfChannels > 1) && (CSR_IS_CHANNEL_DFS(pSrcReq->ChannelInfo.ChannelList[index])) && !pMac->roam.configParam.allowDFSChannelRoam ) #endif ) { #ifdef FEATURE_WLAN_LFR smsLog(pMac, LOG2, FL(" reqType= %s (%d), numOfChannels=%d," " ignoring DFS channel %d"), sme_requestTypetoString(pSrcReq->requestType), pSrcReq->requestType, pSrcReq->ChannelInfo.numOfChannels, pSrcReq->ChannelInfo.ChannelList[index]); #endif continue; } pDstReq->ChannelInfo.ChannelList[new_index] = pSrcReq->ChannelInfo.ChannelList[index]; new_index++; } } pDstReq->ChannelInfo.numOfChannels = new_index; #ifdef FEATURE_WLAN_LFR if ((eCSR_SCAN_HO_BG_SCAN == pSrcReq->requestType) && (0 == pDstReq->ChannelInfo.numOfChannels)) { /* * No valid channels found in the request. * Only perform scan on the channels passed * pSrcReq if it is a eCSR_SCAN_HO_BG_SCAN. * Passing 0 to LIM will trigger a scan on * all valid channels which is not desirable. */ smsLog(pMac, LOGE, FL(" no valid channels found" " (request=%d)"), pSrcReq->requestType); for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels ; index++ ) { smsLog(pMac, LOGE, FL("pSrcReq index=%d" " channel=%d"), index, pSrcReq->ChannelInfo.ChannelList[index]); } status = eHAL_STATUS_FAILURE; break; } #endif } else { smsLog(pMac, LOGE, FL("Couldn't get the valid Channel" " List, keeping requester's list")); new_index = 0; for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels; index++ ) { if (pSrcReq->ChannelInfo.ChannelList[index] < MIN_11P_CHANNEL) { pDstReq->ChannelInfo.ChannelList[new_index] = pSrcReq->ChannelInfo.ChannelList[index]; new_index++; } } pDstReq->ChannelInfo.numOfChannels = new_index; } }//Allocate memory for Channel List } if(pSrcReq->SSIDs.numOfSSIDs == 0) { pDstReq->SSIDs.numOfSSIDs = 0; pDstReq->SSIDs.SSIDList = NULL; } else { pDstReq->SSIDs.SSIDList = vos_mem_malloc( pSrcReq->SSIDs.numOfSSIDs * sizeof(*pDstReq->SSIDs.SSIDList)); if ( NULL == pDstReq->SSIDs.SSIDList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (HAL_STATUS_SUCCESS(status)) { pDstReq->SSIDs.numOfSSIDs = pSrcReq->SSIDs.numOfSSIDs; vos_mem_copy(pDstReq->SSIDs.SSIDList, pSrcReq->SSIDs.SSIDList, pSrcReq->SSIDs.numOfSSIDs * sizeof(*pDstReq->SSIDs.SSIDList)); } else { pDstReq->SSIDs.numOfSSIDs = 0; smsLog(pMac, LOGE, FL("No memory for scanning SSID List")); break; } }//Allocate memory for SSID List pDstReq->p2pSearch = pSrcReq->p2pSearch; pDstReq->skipDfsChnlInP2pSearch = pSrcReq->skipDfsChnlInP2pSearch; } }while(0); if(!HAL_STATUS_SUCCESS(status)) { csrScanFreeRequest(pMac, pDstReq); } return (status); } eHalStatus csrScanFreeRequest(tpAniSirGlobal pMac, tCsrScanRequest *pReq) { if(pReq->ChannelInfo.ChannelList) { vos_mem_free(pReq->ChannelInfo.ChannelList); pReq->ChannelInfo.ChannelList = NULL; } pReq->ChannelInfo.numOfChannels = 0; if(pReq->pIEField) { vos_mem_free(pReq->pIEField); pReq->pIEField = NULL; } pReq->uIEFieldLen = 0; if(pReq->SSIDs.SSIDList) { vos_mem_free(pReq->SSIDs.SSIDList); pReq->SSIDs.SSIDList = NULL; } pReq->SSIDs.numOfSSIDs = 0; return eHAL_STATUS_SUCCESS; } void csrScanCallCallback(tpAniSirGlobal pMac, tSmeCmd *pCommand, eCsrScanStatus scanStatus) { if(pCommand->u.scanCmd.callback) { pCommand->u.scanCmd.callback(pMac, pCommand->u.scanCmd.pContext, pCommand->sessionId, pCommand->u.scanCmd.scanID, scanStatus); } else { smsLog( pMac, LOG2, "%s:%d - Callback NULL!!!", __func__, __LINE__); } } void csrScanStopTimers(tpAniSirGlobal pMac) { csrScanStopIdleScanTimer(pMac); csrScanStopGetResultTimer(pMac); if(0 != pMac->scan.scanResultCfgAgingTime ) { csrScanStopResultCfgAgingTimer(pMac); } } eHalStatus csrScanStartGetResultTimer(tpAniSirGlobal pMac) { eHalStatus status; if(pMac->scan.fScanEnable) { status = vos_timer_start(&pMac->scan.hTimerGetResult, CSR_SCAN_GET_RESULT_INTERVAL/VOS_TIMER_TO_MS_UNIT); } else { status = eHAL_STATUS_FAILURE; } return (status); } eHalStatus csrScanStopGetResultTimer(tpAniSirGlobal pMac) { return (vos_timer_stop(&pMac->scan.hTimerGetResult)); } void csrScanGetResultTimerHandler(void *pv) { tpAniSirGlobal pMac = PMAC_STRUCT( pv ); csrScanRequestResult(pMac); vos_timer_start(&pMac->scan.hTimerGetResult, CSR_SCAN_GET_RESULT_INTERVAL/VOS_TIMER_TO_MS_UNIT); } #ifdef WLAN_AP_STA_CONCURRENCY static void csrStaApConcTimerHandler(void *pv) { tpAniSirGlobal pMac = PMAC_STRUCT( pv ); tListElem *pEntry; tSmeCmd *pScanCmd; tANI_U32 sessionId = CSR_SESSION_ID_INVALID; csrLLLock(&pMac->scan.scanCmdPendingList); if ( NULL != ( pEntry = csrLLPeekHead( &pMac->scan.scanCmdPendingList, LL_ACCESS_NOLOCK) ) ) { tCsrScanRequest scanReq; tSmeCmd *pSendScanCmd = NULL; tANI_U8 numChn = 0; tANI_U8 nNumChanCombinedConc = 0; tANI_U8 i, j; tCsrChannelInfo *pChnInfo = &scanReq.ChannelInfo; tANI_U8 channelToScan[WNI_CFG_VALID_CHANNEL_LIST_LEN]; eHalStatus status; pScanCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); numChn = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels; sessionId = pScanCmd->sessionId; /* if any session is connected and the number of channels to scan is * greater than 1 then split the scan into multiple scan operations * on each individual channel else continue to perform scan on all * specified channels */ /* split scan if number of channels to scan is greater than 1 and * any one of the following: * - STA session is connected and the scan is not a P2P search * - any P2P session is connected * Do not split scans if no concurrent infra connections are * active and if the scan is a BG scan triggered by LFR (OR) * any scan if LFR is in the middle of a BG scan. Splitting * the scan is delaying the time it takes for LFR to find * candidates and resulting in disconnects. */ if((csrIsStaSessionConnected(pMac) && !csrIsP2pSessionConnected(pMac))) { nNumChanCombinedConc = pMac->roam.configParam.nNumStaChanCombinedConc; } else if(csrIsP2pSessionConnected(pMac)) { nNumChanCombinedConc = pMac->roam.configParam.nNumP2PChanCombinedConc; } if ( (numChn > nNumChanCombinedConc) && ((csrIsStaSessionConnected(pMac) && #ifdef FEATURE_WLAN_LFR (csrIsConcurrentInfraConnected(pMac) || ((pScanCmd->u.scanCmd.reason != eCsrScanBgScan) && (pMac->roam.neighborRoamInfo[sessionId].neighborRoamState != eCSR_NEIGHBOR_ROAM_STATE_CFG_CHAN_LIST_SCAN))) && #endif (pScanCmd->u.scanCmd.u.scanRequest.p2pSearch != 1)) || (csrIsP2pSessionConnected(pMac)))) { vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0); pSendScanCmd = csrGetCommandBuffer(pMac); //optimize this to use 2 command buffer only if (!pSendScanCmd) { smsLog( pMac, LOGE, FL(" Failed to get Queue command buffer") ); csrLLUnlock(&pMac->scan.scanCmdPendingList); return; } pSendScanCmd->command = pScanCmd->command; pSendScanCmd->sessionId = pScanCmd->sessionId; pSendScanCmd->u.scanCmd.callback = NULL; pSendScanCmd->u.scanCmd.pContext = pScanCmd->u.scanCmd.pContext; pSendScanCmd->u.scanCmd.reason = pScanCmd->u.scanCmd.reason; pSendScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around /* First copy all the parameters to local variable of scan request */ csrScanCopyRequest(pMac, &scanReq, &pScanCmd->u.scanCmd.u.scanRequest); /* Now modify the elements of local var scan request required to be modified for split scan */ if(scanReq.ChannelInfo.ChannelList != NULL) { vos_mem_free(scanReq.ChannelInfo.ChannelList); scanReq.ChannelInfo.ChannelList = NULL; } pChnInfo->numOfChannels = nNumChanCombinedConc; vos_mem_copy(&channelToScan[0], &pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[0], pChnInfo->numOfChannels * sizeof(tANI_U8));//just send one channel pChnInfo->ChannelList = &channelToScan[0]; for (i = 0, j = nNumChanCombinedConc; i < (numChn-nNumChanCombinedConc); i++, j++) { pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[j]; //Move all the channels one step } pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = numChn - nNumChanCombinedConc; //reduce outstanding # of channels to be scanned scanReq.BSSType = eCSR_BSS_TYPE_ANY; //Use concurrency values for min/maxChnTime. csrSetDefaultScanTiming(pMac, scanReq.scanType, &scanReq); status = csrScanCopyRequest(pMac, &pSendScanCmd->u.scanCmd.u.scanRequest, &scanReq); if(!HAL_STATUS_SUCCESS(status)) { smsLog( pMac, LOGE, FL(" Failed to get copy csrScanRequest = %d"), status ); csrLLUnlock(&pMac->scan.scanCmdPendingList); return; } /* Clean the local scan variable */ scanReq.ChannelInfo.ChannelList = NULL; scanReq.ChannelInfo.numOfChannels = 0; csrScanFreeRequest(pMac, &scanReq); } else { /* no active connected session present or numChn == 1 * scan all remaining channels */ pSendScanCmd = pScanCmd; //remove this command from pending list if (csrLLRemoveHead( &pMac->scan.scanCmdPendingList, LL_ACCESS_NOLOCK) == NULL) { //In case between PeekHead and here, the entry got removed by another thread. smsLog( pMac, LOGE, FL(" Failed to remove entry from scanCmdPendingList")); } } csrQueueSmeCommand(pMac, pSendScanCmd, eANI_BOOLEAN_FALSE); } csrLLUnlock(&pMac->scan.scanCmdPendingList); } #endif eHalStatus csrScanStartResultCfgAgingTimer(tpAniSirGlobal pMac) { eHalStatus status = eHAL_STATUS_FAILURE; if(pMac->scan.fScanEnable) { status = vos_timer_start(&pMac->scan.hTimerResultCfgAging, CSR_SCAN_RESULT_CFG_AGING_INTERVAL/VOS_TIMER_TO_MS_UNIT); } return (status); } eHalStatus csrScanStopResultCfgAgingTimer(tpAniSirGlobal pMac) { return (vos_timer_stop(&pMac->scan.hTimerResultCfgAging)); } static void csrScanResultCfgAgingTimerHandler(void *pv) { tpAniSirGlobal pMac = PMAC_STRUCT( pv ); tListElem *pEntry, *tmpEntry; tCsrScanResult *pResult; tANI_TIMESTAMP ageOutTime = pMac->scan.scanResultCfgAgingTime * PAL_TICKS_PER_SECOND; tANI_TIMESTAMP curTime = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd); csrLLLock(&pMac->scan.scanResultList); pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_NOLOCK ); while( pEntry ) { tmpEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); pResult = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); if((curTime - pResult->Result.BssDescriptor.nReceivedTime) > ageOutTime) { smsLog(pMac, LOGW, " age out due to time out"); csrScanAgeOutBss(pMac, pResult); } pEntry = tmpEntry; } csrLLUnlock(&pMac->scan.scanResultList); if (pEntry) vos_timer_start(&pMac->scan.hTimerResultCfgAging, CSR_SCAN_RESULT_CFG_AGING_INTERVAL/VOS_TIMER_TO_MS_UNIT); } eHalStatus csrScanStartIdleScanTimer(tpAniSirGlobal pMac, tANI_U32 interval) { eHalStatus status; smsLog(pMac, LOG1, " csrScanStartIdleScanTimer"); if((pMac->scan.fScanEnable) && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) && interval) { pMac->scan.nIdleScanTimeGap += interval; vos_timer_stop(&pMac->scan.hTimerIdleScan); status = vos_timer_start(&pMac->scan.hTimerIdleScan, interval/VOS_TIMER_TO_MS_UNIT); if( !HAL_STATUS_SUCCESS(status) ) { smsLog(pMac, LOGE, " Fail to start Idle scan timer. status = %d interval = %d", status, interval); //This should not happen but set the flag to restart when ready pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; } } else { if( pMac->scan.fScanEnable && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) ) { pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; } status = eHAL_STATUS_FAILURE; } return (status); } eHalStatus csrScanStopIdleScanTimer(tpAniSirGlobal pMac) { return (vos_timer_stop(&pMac->scan.hTimerIdleScan)); } //Stop CSR from asking for IMPS, This function doesn't disable IMPS from CSR void csrScanSuspendIMPS( tpAniSirGlobal pMac ) { csrScanCancelIdleScan(pMac); } //Start CSR from asking for IMPS. This function doesn't trigger CSR to request entering IMPS //because IMPS maybe disabled. void csrScanResumeIMPS( tpAniSirGlobal pMac ) { csrScanStartIdleScan( pMac ); } void csrScanIMPSCallback(void *callbackContext, eHalStatus status) { tpAniSirGlobal pMac = PMAC_STRUCT( callbackContext ); if(eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) { if(pMac->roam.configParam.IsIdleScanEnabled) { if(HAL_STATUS_SUCCESS(status)) { if(csrIsAllSessionDisconnected(pMac) && !csrIsRoamCommandWaiting(pMac)) { smsLog(pMac, LOGW, FL("starts idle mode full scan")); csrScanAllChannels(pMac, eCSR_SCAN_IDLE_MODE_SCAN); } else { smsLog(pMac, LOGW, FL("cannot start idle mode full scan")); //even though we are in timer handle, calling stop timer will make sure the timer //doesn't get to restart. csrScanStopIdleScanTimer(pMac); } } else { smsLog(pMac, LOGE, FL("sees not success status (%d)"), status); } } else {//we might need another flag to check if CSR needs to request imps at all tANI_U32 nTime = 0; pMac->scan.fRestartIdleScan = eANI_BOOLEAN_FALSE; if(!HAL_STATUS_SUCCESS(csrScanTriggerIdleScan(pMac, &nTime))) { csrScanStartIdleScanTimer(pMac, nTime); } } } } /* * Param: pTimeInterval -- Caller allocated memory in return, if failed, * to specify the next time interval for idle scan timer interval * Return: Not success -- meaning it cannot start IMPS, caller needs to * start a timer for idle scan */ eHalStatus csrScanTriggerIdleScan(tpAniSirGlobal pMac, tANI_U32 *pTimeInterval) { eHalStatus status = eHAL_STATUS_CSR_WRONG_STATE; //Do not trigger IMPS in case of concurrency if (vos_concurrent_open_sessions_running() && csrIsAnySessionInConnectState(pMac)) { smsLog( pMac, LOG1, FL("Cannot request IMPS because Concurrent Sessions Running") ); return (status); } if(pTimeInterval) { *pTimeInterval = 0; } smsLog(pMac, LOG3, FL("called")); if( smeCommandPending( pMac ) ) { smsLog( pMac, LOG1, FL(" Cannot request IMPS because command pending") ); //Not to enter IMPS because more work to do if(pTimeInterval) { *pTimeInterval = 0; } //restart when ready pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; return (status); } if (IsPmcImpsReqFailed (pMac)) { if(pTimeInterval) { *pTimeInterval = 1000000; //usec } //restart when ready pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; return status; } if((pMac->scan.fScanEnable) && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan)) { //Stop get result timer because idle scan gets scan result out of PE csrScanStopGetResultTimer(pMac); if(pTimeInterval) { *pTimeInterval = pMac->roam.configParam.impsSleepTime; } //pmcRequestImps take a period in millisecond unit. status = pmcRequestImps(pMac, pMac->roam.configParam.impsSleepTime / VOS_TIMER_TO_MS_UNIT, csrScanIMPSCallback, pMac); if(!HAL_STATUS_SUCCESS(status)) { if(eHAL_STATUS_PMC_ALREADY_IN_IMPS != status) { //Do restart the timer if CSR thinks it cannot do IMPS if( !csrCheckPSReady( pMac ) ) { if(pTimeInterval) { *pTimeInterval = 0; } //Set the restart flag to true because that idle scan //can be restarted even though the timer will not be running pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; } else { //For not now, we do a quicker retry if(pTimeInterval) { *pTimeInterval = CSR_IDLE_SCAN_WAIT_TIME; } } smsLog(pMac, LOGW, FL("call pmcRequestImps and it returns status code (%d)"), status); } else { smsLog(pMac, LOGW, FL("already in IMPS")); //Since CSR is the only module to request for IMPS. If it is already in IMPS, CSR assumes //the callback will be called in the future. Should not happen though. status = eHAL_STATUS_SUCCESS; pMac->scan.nIdleScanTimeGap = 0; } } else { //requested so let's reset the value pMac->scan.nIdleScanTimeGap = 0; } } return (status); } eHalStatus csrScanStartIdleScan(tpAniSirGlobal pMac) { eHalStatus status = eHAL_STATUS_CSR_WRONG_STATE; tANI_U32 nTime = 0; smsLog(pMac, LOGW, FL("called")); /* * Idle Scan not supported with Power Save Offload * Enabled */ if(pMac->psOffloadEnabled) { return eHAL_STATUS_SUCCESS; } if(pMac->roam.configParam.IsIdleScanEnabled) { //stop bg scan first csrScanBGScanAbort(pMac); //Stop get result timer because idle scan gets scan result out of PE csrScanStopGetResultTimer(pMac); } pMac->scan.fCancelIdleScan = eANI_BOOLEAN_FALSE; status = csrScanTriggerIdleScan(pMac, &nTime); if(!HAL_STATUS_SUCCESS(status)) { csrScanStartIdleScanTimer(pMac, nTime); } return (status); } void csrScanCancelIdleScan(tpAniSirGlobal pMac) { /* * Idle Scan not supported with Power Save Offload * Enabled */ if(pMac->psOffloadEnabled) { return; } if(eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) { if (vos_concurrent_open_sessions_running()) { return; } smsLog(pMac, LOG1, " csrScanCancelIdleScan"); pMac->scan.fCancelIdleScan = eANI_BOOLEAN_TRUE; /* Set the restart flag in case later on it is uncanceled */ pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; csrScanStopIdleScanTimer(pMac); csrScanRemoveNotRoamingScanCommand(pMac); } } void csrScanIdleScanTimerHandler(void *pv) { tpAniSirGlobal pMac = PMAC_STRUCT( pv ); eHalStatus status; tANI_U32 nTime = 0; smsLog(pMac, LOGW, " csrScanIdleScanTimerHandler called "); pmcResetImpsFailStatus (pMac); status = csrScanTriggerIdleScan(pMac, &nTime); if(!HAL_STATUS_SUCCESS(status) && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan)) { //Check whether it is time to actually do an idle scan if(pMac->scan.nIdleScanTimeGap >= pMac->roam.configParam.impsSleepTime) { pMac->scan.nIdleScanTimeGap = 0; csrScanIMPSCallback(pMac, eHAL_STATUS_SUCCESS); } else { csrScanStartIdleScanTimer(pMac, nTime); } } } tANI_BOOLEAN csrScanRemoveNotRoamingScanCommand(tpAniSirGlobal pMac) { tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE; tListElem *pEntry, *pEntryTmp; tSmeCmd *pCommand; tDblLinkList localList; tDblLinkList *pCmdList; vos_mem_zero(&localList, sizeof(tDblLinkList)); if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList))) { smsLog(pMac, LOGE, FL(" failed to open list")); return fRet; } if (!pMac->fScanOffload) pCmdList = &pMac->sme.smeCmdPendingList; else pCmdList = &pMac->sme.smeScanCmdPendingList; csrLLLock(pCmdList); pEntry = csrLLPeekHead(pCmdList, LL_ACCESS_NOLOCK); while(pEntry) { pEntryTmp = csrLLNext(pCmdList, pEntry, LL_ACCESS_NOLOCK); pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link); if( eSmeCommandScan == pCommand->command ) { switch( pCommand->u.scanCmd.reason ) { case eCsrScanIdleScan: if( csrLLRemoveEntry(pCmdList, pEntry, LL_ACCESS_NOLOCK) ) { csrLLInsertTail(&localList, pEntry, LL_ACCESS_NOLOCK); } fRet = eANI_BOOLEAN_TRUE; break; default: break; } //switch } pEntry = pEntryTmp; } csrLLUnlock(pCmdList); while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) ) { pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link); csrReleaseCommandScan( pMac, pCommand ); } csrLLClose(&localList); return (fRet); } tANI_BOOLEAN csrScanRemoveFreshScanCommand(tpAniSirGlobal pMac, tANI_U8 sessionId) { tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE; tListElem *pEntry, *pEntryTmp; tSmeCmd *pCommand; tDblLinkList localList; tDblLinkList *pCmdList; vos_mem_zero(&localList, sizeof(tDblLinkList)); if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList))) { smsLog(pMac, LOGE, FL(" failed to open list")); return fRet; } if (!pMac->fScanOffload) pCmdList = &pMac->sme.smeCmdPendingList; else pCmdList = &pMac->sme.smeScanCmdPendingList; csrLLLock(pCmdList); pEntry = csrLLPeekHead(pCmdList, LL_ACCESS_NOLOCK); while(pEntry) { pEntryTmp = csrLLNext(pCmdList, pEntry, LL_ACCESS_NOLOCK); pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link); if( (eSmeCommandScan == pCommand->command) && (sessionId == pCommand->sessionId) ) { switch(pCommand->u.scanCmd.reason) { #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD case eCsrScanGetLfrResult: #endif case eCsrScanGetResult: case eCsrScanSetBGScanParam: case eCsrScanBGScanAbort: case eCsrScanBGScanEnable: case eCsrScanGetScanChnInfo: break; default: smsLog (pMac, LOGW, "%s: -------- abort scan command reason = %d", __func__, pCommand->u.scanCmd.reason); //The rest are fresh scan requests if( csrLLRemoveEntry(pCmdList, pEntry, LL_ACCESS_NOLOCK) ) { csrLLInsertTail(&localList, pEntry, LL_ACCESS_NOLOCK); } fRet = eANI_BOOLEAN_TRUE; break; } } pEntry = pEntryTmp; } csrLLUnlock(pCmdList); while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) ) { pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link); if (pCommand->u.scanCmd.callback) { /* User scan request is pending, * send response with status eCSR_SCAN_ABORT*/ pCommand->u.scanCmd.callback(pMac, pCommand->u.scanCmd.pContext, sessionId, pCommand->u.scanCmd.scanID, eCSR_SCAN_ABORT); } csrReleaseCommandScan( pMac, pCommand ); } csrLLClose(&localList); return (fRet); } void csrReleaseScanCommand(tpAniSirGlobal pMac, tSmeCmd *pCommand, eCsrScanStatus scanStatus) { eCsrScanReason reason = pCommand->u.scanCmd.reason; tANI_BOOLEAN status; if (!pMac->fScanOffload) { tANI_U32 i; for(i = 0; i < CSR_ROAM_SESSION_MAX; i++) csrRoamStateChange(pMac, pCommand->u.scanCmd.lastRoamState[i], i); } else { csrRoamStateChange(pMac, pCommand->u.scanCmd.lastRoamState[pCommand->sessionId], pCommand->sessionId); } csrScanCallCallback(pMac, pCommand, scanStatus); smsLog(pMac, LOG3, " Remove Scan command reason = %d", reason); if (pMac->fScanOffload) { status = csrLLRemoveEntry(&pMac->sme.smeScanCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK); } else { status = csrLLRemoveEntry(&pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK); } if(status) { csrReleaseCommandScan( pMac, pCommand ); } else { smsLog(pMac, LOGE, " ********csrReleaseScanCommand cannot release command reason %d", pCommand->u.scanCmd.reason ); } } eHalStatus csrScanGetPMKIDCandidateList(tpAniSirGlobal pMac, tANI_U32 sessionId, tPmkidCandidateInfo *pPmkidList, tANI_U32 *pNumItems ) { eHalStatus status = eHAL_STATUS_SUCCESS; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, " pMac->scan.NumPmkidCandidate = %d", pSession->NumPmkidCandidate); csrResetPMKIDCandidateList(pMac, sessionId); if(csrIsConnStateConnected(pMac, sessionId) && pSession->pCurRoamProfile) { tCsrScanResultFilter *pScanFilter; tCsrScanResultInfo *pScanResult; tScanResultHandle hBSSList; tANI_U32 nItems = *pNumItems; *pNumItems = 0; pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); //Here is the profile we need to connect to status = csrRoamPrepareFilterFromProfile(pMac, pSession->pCurRoamProfile, pScanFilter); if(HAL_STATUS_SUCCESS(status)) { status = csrScanGetResult(pMac, pScanFilter, &hBSSList); if(HAL_STATUS_SUCCESS(status)) { while(((pScanResult = csrScanResultGetNext(pMac, hBSSList)) != NULL) && ( pSession->NumPmkidCandidate < nItems)) { //NumPmkidCandidate adds up here csrProcessBSSDescForPMKIDList(pMac, &pScanResult->BssDescriptor, (tDot11fBeaconIEs *)(pScanResult->pvIes), sessionId); } if(pSession->NumPmkidCandidate) { *pNumItems = pSession->NumPmkidCandidate; vos_mem_copy(pPmkidList, pSession->PmkidCandidateInfo, pSession->NumPmkidCandidate * sizeof(tPmkidCandidateInfo)); } csrScanResultPurge(pMac, hBSSList); }//Have scan result csrFreeScanFilter(pMac, pScanFilter); } vos_mem_free(pScanFilter); } } return (status); } #ifdef FEATURE_WLAN_WAPI eHalStatus csrScanGetBKIDCandidateList(tpAniSirGlobal pMac, tANI_U32 sessionId, tBkidCandidateInfo *pBkidList, tANI_U32 *pNumItems ) { eHalStatus status = eHAL_STATUS_SUCCESS; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); return eHAL_STATUS_FAILURE; } smsLog(pMac, LOGW, " pMac->scan.NumBkidCandidate = %d", pSession->NumBkidCandidate); csrResetBKIDCandidateList(pMac, sessionId); if(csrIsConnStateConnected(pMac, sessionId) && pSession->pCurRoamProfile) { tCsrScanResultFilter *pScanFilter; tCsrScanResultInfo *pScanResult; tScanResultHandle hBSSList; tANI_U32 nItems = *pNumItems; *pNumItems = 0; pScanFilter = vos_mem_malloc(sizeof(tCsrScanResultFilter)); if ( NULL == pScanFilter ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pScanFilter, sizeof(tCsrScanResultFilter), 0); //Here is the profile we need to connect to status = csrRoamPrepareFilterFromProfile(pMac, pSession->pCurRoamProfile, pScanFilter); if(HAL_STATUS_SUCCESS(status)) { status = csrScanGetResult(pMac, pScanFilter, &hBSSList); if(HAL_STATUS_SUCCESS(status)) { while(((pScanResult = csrScanResultGetNext(pMac, hBSSList)) != NULL) && ( pSession->NumBkidCandidate < nItems)) { //pMac->scan.NumBkidCandidate adds up here csrProcessBSSDescForBKIDList(pMac, &pScanResult->BssDescriptor, (tDot11fBeaconIEs *)( pScanResult->pvIes )); } if(pSession->NumBkidCandidate) { *pNumItems = pSession->NumBkidCandidate; vos_mem_copy(pBkidList, pSession->BkidCandidateInfo, pSession->NumBkidCandidate * sizeof(tBkidCandidateInfo)); } csrScanResultPurge(pMac, hBSSList); }//Have scan result } vos_mem_free(pScanFilter); } } return (status); } #endif /* FEATURE_WLAN_WAPI */ //This function is usually used for BSSs that suppresses SSID so the profile //shall have one and only one SSID eHalStatus csrScanForSSID(tpAniSirGlobal pMac, tANI_U32 sessionId, tCsrRoamProfile *pProfile, tANI_U32 roamId, tANI_BOOLEAN notify) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; tSmeCmd *pScanCmd = NULL; tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; tANI_U8 index = 0; tANI_U32 numSsid = pProfile->SSIDs.numOfSSIDs; tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo[sessionId]; smsLog(pMac, LOG2, FL("called")); //For WDS, we use the index 0. There must be at least one in there if( CSR_IS_WDS_STA( pProfile ) && numSsid ) { numSsid = 1; } if(pMac->scan.fScanEnable && ( numSsid == 1 ) ) { do { pScanCmd = csrGetCommandBuffer(pMac); if(!pScanCmd) { smsLog(pMac, LOGE, FL("failed to allocate command buffer")); break; } vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0); pScanCmd->u.scanCmd.pToRoamProfile = vos_mem_malloc(sizeof(tCsrRoamProfile)); if ( NULL == pScanCmd->u.scanCmd.pToRoamProfile ) { status = eHAL_STATUS_FAILURE; } else { status = csrRoamCopyProfile(pMac, pScanCmd->u.scanCmd.pToRoamProfile, pProfile); } if(!HAL_STATUS_SUCCESS(status)) break; pScanCmd->u.scanCmd.roamId = roamId; pScanCmd->command = eSmeCommandScan; pScanCmd->sessionId = (tANI_U8)sessionId; pScanCmd->u.scanCmd.callback = NULL; pScanCmd->u.scanCmd.pContext = NULL; pScanCmd->u.scanCmd.reason = eCsrScanForSsid;//Need to check: might need a new reason for SSID scan for LFR during multisession with p2p pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around vos_mem_set(&pScanCmd->u.scanCmd.u.scanRequest, sizeof(tCsrScanRequest), 0); pScanCmd->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN; pScanCmd->u.scanCmd.u.scanRequest.BSSType = pProfile->BSSType; // To avoid 11b rate in probe request Set p2pSearch flag as 1 for P2P Client Mode if(VOS_P2P_CLIENT_MODE == pProfile->csrPersona) { pScanCmd->u.scanCmd.u.scanRequest.p2pSearch = 1; } if(pProfile->pAddIEScan) { pScanCmd->u.scanCmd.u.scanRequest.pIEField = vos_mem_malloc( pProfile->nAddIEScanLength); if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.pIEField ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; vos_mem_set(pScanCmd->u.scanCmd.u.scanRequest.pIEField, pProfile->nAddIEScanLength, 0); if (HAL_STATUS_SUCCESS(status)) { vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.pIEField, pProfile->pAddIEScan, pProfile->nAddIEScanLength); pScanCmd->u.scanCmd.u.scanRequest.uIEFieldLen = pProfile->nAddIEScanLength; } else { smsLog(pMac, LOGE, "No memory for scanning IE fields"); } } //Allocate memory for IE field else { pScanCmd->u.scanCmd.u.scanRequest.uIEFieldLen = 0; } /* For one channel be good enough time to receive beacon at-least */ if( 1 == pProfile->ChannelInfo.numOfChannels ) { #if defined (WLAN_FEATURE_ROAM_SCAN_OFFLOAD) if (pNeighborRoamInfo->handoffReqInfo.src == FASTREASSOC) { pScanCmd->u.scanCmd.u.scanRequest.maxChnTime = MAX_ACTIVE_SCAN_FOR_ONE_CHANNEL_FASTREASSOC; pScanCmd->u.scanCmd.u.scanRequest.minChnTime = MIN_ACTIVE_SCAN_FOR_ONE_CHANNEL_FASTREASSOC; /* Reset this value */ pNeighborRoamInfo->handoffReqInfo.src = 0; } else #endif { pScanCmd->u.scanCmd.u.scanRequest.maxChnTime = MAX_ACTIVE_SCAN_FOR_ONE_CHANNEL; pScanCmd->u.scanCmd.u.scanRequest.minChnTime = MIN_ACTIVE_SCAN_FOR_ONE_CHANNEL; } } else { pScanCmd->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime; pScanCmd->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime; } pScanCmd->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.nActiveMaxChnTimeBtc; pScanCmd->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.nActiveMinChnTimeBtc; if(pProfile->BSSIDs.numOfBSSIDs == 1) { vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.bssid, pProfile->BSSIDs.bssid, sizeof(tCsrBssid)); } else { vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.bssid, bAddr, 6); } if(pProfile->ChannelInfo.numOfChannels) { pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc( sizeof(*pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList) * pProfile->ChannelInfo.numOfChannels); if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = 0; if(HAL_STATUS_SUCCESS(status)) { csrRoamIsChannelValid(pMac, pProfile->ChannelInfo.ChannelList[0]); for(index = 0; index < pProfile->ChannelInfo.numOfChannels; index++) { if(csrRoamIsValidChannel(pMac, pProfile->ChannelInfo.ChannelList[index])) { pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels] = pProfile->ChannelInfo.ChannelList[index]; pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels++; } else { smsLog(pMac, LOGW, FL("process a channel (%d) that is invalid"), pProfile->ChannelInfo.ChannelList[index]); } } } else { break; } } else { pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = 0; } if(pProfile->SSIDs.numOfSSIDs) { pScanCmd->u.scanCmd.u.scanRequest.SSIDs.SSIDList = vos_mem_malloc( pProfile->SSIDs.numOfSSIDs * sizeof(tCsrSSIDInfo)); if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.SSIDs.SSIDList ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if(!HAL_STATUS_SUCCESS(status)) { break; } pScanCmd->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs = 1; vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.SSIDs.SSIDList, pProfile->SSIDs.SSIDList, sizeof(tCsrSSIDInfo)); } //Start process the command status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); break; } }while(0); if(!HAL_STATUS_SUCCESS(status)) { if(pScanCmd) { csrReleaseCommandScan(pMac, pScanCmd); //TODO:free the memory that is allocated in this function } if(notify) { csrRoamCallCallback(pMac, sessionId, NULL, roamId, eCSR_ROAM_FAILED, eCSR_ROAM_RESULT_FAILURE); } } }//valid else { smsLog(pMac, LOGE, FL("cannot scan because scanEnable (%d) or numSSID (%d) is invalid"), pMac->scan.fScanEnable, pProfile->SSIDs.numOfSSIDs); } return (status); } /* * Issue a scan based on the new capability information * This should only happen when the associated AP changes its capability. * After this scan is done, CSR re-roams based on the new scan results */ eHalStatus csrScanForCapabilityChange(tpAniSirGlobal pMac, tSirSmeApNewCaps *pNewCaps) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; tSmeCmd *pScanCmd = NULL; if(pNewCaps) { do { pScanCmd = csrGetCommandBuffer(pMac); if(!pScanCmd) { smsLog(pMac, LOGE, FL("failed to allocate command buffer")); status = eHAL_STATUS_RESOURCES; break; } vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0); status = eHAL_STATUS_SUCCESS; pScanCmd->u.scanCmd.roamId = 0; pScanCmd->command = eSmeCommandScan; pScanCmd->u.scanCmd.callback = NULL; pScanCmd->u.scanCmd.pContext = NULL; pScanCmd->u.scanCmd.reason = eCsrScanForCapsChange; pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE); if( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status ); break; } }while(0); if(!HAL_STATUS_SUCCESS(status)) { if(pScanCmd) { csrReleaseCommandScan(pMac, pScanCmd); } } } return (status); } void csrInitBGScanChannelList(tpAniSirGlobal pMac) { tANI_U32 len = CSR_MIN(sizeof(pMac->roam.validChannelList), sizeof(pMac->scan.bgScanChannelList)); vos_mem_set(pMac->scan.bgScanChannelList, len, 0); pMac->scan.numBGScanChannel = 0; if(HAL_STATUS_SUCCESS(csrGetCfgValidChannels(pMac, pMac->roam.validChannelList, &len))) { pMac->roam.numValidChannels = len; pMac->scan.numBGScanChannel = (tANI_U8)CSR_MIN(len, WNI_CFG_BG_SCAN_CHANNEL_LIST_LEN); vos_mem_copy(pMac->scan.bgScanChannelList, pMac->roam.validChannelList, pMac->scan.numBGScanChannel); csrSetBGScanChannelList(pMac, pMac->scan.bgScanChannelList, pMac->scan.numBGScanChannel); } } //This function return TRUE if background scan channel list is adjusted. //this function will only shrink the background scan channel list tANI_BOOLEAN csrAdjustBGScanChannelList(tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 NumChannels, tANI_U8 *pAdjustChannels, tANI_U8 *pNumAdjustChannels) { tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE; tANI_U8 i, j, count = *pNumAdjustChannels; i = 0; while(i < count) { for(j = 0; j < NumChannels; j++) { if(pChannelList[j] == pAdjustChannels[i]) break; } if(j == NumChannels) { //This channel is not in the list, remove it fRet = eANI_BOOLEAN_TRUE; count--; if(count - i) { vos_mem_copy(&pAdjustChannels[i], &pAdjustChannels[i+1], count - i); } else { //already remove the last one. Done. break; } } else { i++; } }//while(i<count) *pNumAdjustChannels = count; return (fRet); } //Get the list of the base channels to scan for passively 11d info eHalStatus csrScanGetSupportedChannels( tpAniSirGlobal pMac ) { eHalStatus status = eHAL_STATUS_SUCCESS; int n = WNI_CFG_VALID_CHANNEL_LIST_LEN; status = vos_nv_getSupportedChannels( pMac->scan.baseChannels.channelList, &n, NULL, NULL ); if( HAL_STATUS_SUCCESS(status) ) { pMac->scan.baseChannels.numChannels = (tANI_U8)n; } else { smsLog( pMac, LOGE, FL(" failed") ); pMac->scan.baseChannels.numChannels = 0; } return ( status ); } //This function use the input pChannelList to validate the current saved channel list eHalStatus csrSetBGScanChannelList( tpAniSirGlobal pMac, tANI_U8 *pAdjustChannels, tANI_U8 NumAdjustChannels) { tANI_U32 dataLen = sizeof( tANI_U8 ) * NumAdjustChannels; return (ccmCfgSetStr(pMac, WNI_CFG_BG_SCAN_CHANNEL_LIST, pAdjustChannels, dataLen, NULL, eANI_BOOLEAN_FALSE)); } void csrSetCfgValidChannelList( tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 NumChannels ) { tANI_U32 dataLen = sizeof( tANI_U8 ) * NumChannels; eHalStatus status; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: dump valid channel list(NumChannels(%d))", __func__,NumChannels); VOS_TRACE_HEX_DUMP(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, pChannelList, NumChannels); ccmCfgSetStr(pMac, WNI_CFG_VALID_CHANNEL_LIST, pChannelList, dataLen, NULL, eANI_BOOLEAN_FALSE); if (pMac->fScanOffload) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "Scan offload is enabled, update default chan list"); /* * disable fcc constraint since new country code * is being set */ pMac->scan.fcc_constraint = false; status = csrUpdateChannelList(pMac); if (eHAL_STATUS_SUCCESS != status) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "failed to update the supported channel list"); } } return; } /* * The Tx power limits are saved in the cfg for future usage. */ void csrSaveTxPowerToCfg( tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U32 cfgId ) { tListElem *pEntry; tANI_U32 cbLen = 0, dataLen; tCsrChannelPowerInfo *pChannelSet; tANI_U32 idx; tSirMacChanInfo *pChannelPowerSet; tANI_U8 *pBuf = NULL; //allocate maximum space for all channels dataLen = WNI_CFG_VALID_CHANNEL_LIST_LEN * sizeof(tSirMacChanInfo); if ( (pBuf = vos_mem_malloc(dataLen)) != NULL ) { vos_mem_set(pBuf, dataLen, 0); pChannelPowerSet = (tSirMacChanInfo *)(pBuf); pEntry = csrLLPeekHead( pList, LL_ACCESS_LOCK ); // write the tuples (startChan, numChan, txPower) for each channel found in the channel power list. while( pEntry ) { pChannelSet = GET_BASE_ADDR( pEntry, tCsrChannelPowerInfo, link ); if ( 1 != pChannelSet->interChannelOffset ) { /* * we keep the 5G channel sets internally with an inter channel * offset of 4. Expand these to the right format. * (inter channel offset of 1 is the only option for the * triplets that 11d advertises. */ if ((cbLen + (pChannelSet->numChannels * sizeof(tSirMacChanInfo))) >= dataLen) { // expanding this entry will overflow our allocation smsLog(pMac, LOGE, "%s: Buffer overflow, start %d, num %d, offset %d", __func__, pChannelSet->firstChannel, pChannelSet->numChannels, pChannelSet->interChannelOffset); break; } for( idx = 0; idx < pChannelSet->numChannels; idx++ ) { pChannelPowerSet->firstChanNum = (tSirMacChanNum)(pChannelSet->firstChannel + ( idx * pChannelSet->interChannelOffset )); smsLog(pMac, LOG3, " Setting Channel Number %d", pChannelPowerSet->firstChanNum); pChannelPowerSet->numChannels = 1; pChannelPowerSet->maxTxPower = CSR_ROAM_MIN( pChannelSet->txPower, pMac->roam.configParam.nTxPowerCap ); smsLog(pMac, LOG3, " Setting Max Transmit Power %d", pChannelPowerSet->maxTxPower); cbLen += sizeof( tSirMacChanInfo ); pChannelPowerSet++; } } else { if (cbLen >= dataLen) { // this entry will overflow our allocation smsLog(pMac, LOGE, "%s: Buffer overflow, start %d, num %d, offset %d", __func__, pChannelSet->firstChannel, pChannelSet->numChannels, pChannelSet->interChannelOffset); break; } pChannelPowerSet->firstChanNum = pChannelSet->firstChannel; smsLog(pMac, LOG3, " Setting Channel Number %d", pChannelPowerSet->firstChanNum); pChannelPowerSet->numChannels = pChannelSet->numChannels; pChannelPowerSet->maxTxPower = CSR_ROAM_MIN( pChannelSet->txPower, pMac->roam.configParam.nTxPowerCap ); smsLog(pMac, LOG3, " Setting Max Transmit Power %d, nTxPower %d", pChannelPowerSet->maxTxPower,pMac->roam.configParam.nTxPowerCap ); cbLen += sizeof( tSirMacChanInfo ); pChannelPowerSet++; } pEntry = csrLLNext( pList, pEntry, LL_ACCESS_LOCK ); } if(cbLen) { ccmCfgSetStr(pMac, cfgId, (tANI_U8 *)pBuf, cbLen, NULL, eANI_BOOLEAN_FALSE); } vos_mem_free(pBuf); }//Allocate memory } void csrSetCfgCountryCode( tpAniSirGlobal pMac, tANI_U8 *countryCode ) { tANI_U8 cc[WNI_CFG_COUNTRY_CODE_LEN]; ///v_REGDOMAIN_t DomainId; smsLog( pMac, LOG3, "Setting Country Code in Cfg from csrSetCfgCountryCode %s",countryCode ); vos_mem_copy(cc, countryCode, WNI_CFG_COUNTRY_CODE_LEN); // don't program the bogus country codes that we created for Korea in the MAC. if we see // the bogus country codes, program the MAC with the right country code. if ( ( 'K' == countryCode[ 0 ] && '1' == countryCode[ 1 ] ) || ( 'K' == countryCode[ 0 ] && '2' == countryCode[ 1 ] ) || ( 'K' == countryCode[ 0 ] && '3' == countryCode[ 1 ] ) || ( 'K' == countryCode[ 0 ] && '4' == countryCode[ 1 ] ) ) { // replace the alternate Korea country codes, 'K1', 'K2', .. with 'KR' for Korea cc[ 1 ] = 'R'; } ccmCfgSetStr(pMac, WNI_CFG_COUNTRY_CODE, cc, WNI_CFG_COUNTRY_CODE_LEN, NULL, eANI_BOOLEAN_FALSE); //Need to let HALPHY know about the current domain so it can apply some //domain-specific settings (TX filter...) /*if(HAL_STATUS_SUCCESS(csrGetRegulatoryDomainForCountry(pMac, cc, &DomainId))) { halPhySetRegDomain(pMac, DomainId); }*/ } eHalStatus csrGetCountryCode(tpAniSirGlobal pMac, tANI_U8 *pBuf, tANI_U8 *pbLen) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; tANI_U32 len; if(pBuf && pbLen && (*pbLen >= WNI_CFG_COUNTRY_CODE_LEN)) { len = *pbLen; status = ccmCfgGetStr(pMac, WNI_CFG_COUNTRY_CODE, pBuf, &len); if(HAL_STATUS_SUCCESS(status)) { *pbLen = (tANI_U8)len; } } return (status); } void csrSetCfgScanControlList( tpAniSirGlobal pMac, tANI_U8 *countryCode, tCsrChannel *pChannelList ) { tANI_U8 i, j; tANI_BOOLEAN found=FALSE; tANI_U8 *pControlList = NULL; tANI_U32 len = WNI_CFG_SCAN_CONTROL_LIST_LEN; if ( (pControlList = vos_mem_malloc(WNI_CFG_SCAN_CONTROL_LIST_LEN)) != NULL ) { vos_mem_set((void *)pControlList, WNI_CFG_SCAN_CONTROL_LIST_LEN, 0); if(HAL_STATUS_SUCCESS(ccmCfgGetStr(pMac, WNI_CFG_SCAN_CONTROL_LIST, pControlList, &len))) { for (i = 0; i < pChannelList->numChannels; i++) { for (j = 0; j < len; j += 2) { if (pControlList[j] == pChannelList->channelList[i]) { found = TRUE; break; } } if (found) // insert a pair(channel#, flag) { pControlList[j+1] = csrGetScanType(pMac, pControlList[j]); found = FALSE; // reset the flag } } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: dump scan control list",__func__); VOS_TRACE_HEX_DUMP(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, pControlList, len); ccmCfgSetStr(pMac, WNI_CFG_SCAN_CONTROL_LIST, pControlList, len, NULL, eANI_BOOLEAN_FALSE); }//Successfully getting scan control list vos_mem_free(pControlList); }//AllocateMemory } //if bgPeriod is 0, background scan is disabled. It is in millisecond units eHalStatus csrSetCfgBackgroundScanPeriod(tpAniSirGlobal pMac, tANI_U32 bgPeriod) { return (ccmCfgSetInt(pMac, WNI_CFG_BACKGROUND_SCAN_PERIOD, bgPeriod, (tCcmCfgSetCallback) csrScanCcmCfgSetCallback, eANI_BOOLEAN_FALSE)); } void csrScanCcmCfgSetCallback(tHalHandle hHal, tANI_S32 result) { tListElem *pEntry = NULL; tSmeCmd *pCommand = NULL; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tDblLinkList *pCmdList ; if (!pMac->fScanOffload) pCmdList = &pMac->sme.smeCmdActiveList; else pCmdList = &pMac->sme.smeScanCmdActiveList; pEntry = csrLLPeekHead( pCmdList, LL_ACCESS_LOCK ); if ( pEntry ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); if ( eSmeCommandScan == pCommand->command ) { eCsrScanStatus scanStatus = (CCM_IS_RESULT_SUCCESS(result)) ? eCSR_SCAN_SUCCESS : eCSR_SCAN_FAILURE; csrReleaseScanCommand(pMac, pCommand, scanStatus); } else { smsLog( pMac, LOGW, "CSR: Scan Completion called but SCAN command is not ACTIVE ..." ); } } smeProcessPendingQueue( pMac ); } eHalStatus csrProcessSetBGScanParam(tpAniSirGlobal pMac, tSmeCmd *pCommand) { eHalStatus status; tCsrBGScanRequest *pScanReq = &pCommand->u.scanCmd.u.bgScanRequest; tANI_U32 dataLen = sizeof( tANI_U8 ) * pScanReq->ChannelInfo.numOfChannels; //***setcfg for background scan channel list status = ccmCfgSetInt(pMac, WNI_CFG_ACTIVE_MINIMUM_CHANNEL_TIME, pScanReq->minChnTime, NULL, eANI_BOOLEAN_FALSE); status = ccmCfgSetInt(pMac, WNI_CFG_ACTIVE_MAXIMUM_CHANNEL_TIME, pScanReq->maxChnTime, NULL, eANI_BOOLEAN_FALSE); //Not set the background scan interval if not connected because bd scan should not be run if not connected if(!csrIsAllSessionDisconnected(pMac)) { #ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR { vos_log_scan_pkt_type *pScanLog = NULL; WLAN_VOS_DIAG_LOG_ALLOC(pScanLog, vos_log_scan_pkt_type, LOG_WLAN_SCAN_C); if(pScanLog) { pScanLog->eventId = WLAN_SCAN_EVENT_HO_SCAN_REQ; pScanLog->minChnTime = (v_U8_t)pScanReq->minChnTime; pScanLog->maxChnTime = (v_U8_t)pScanReq->maxChnTime; pScanLog->timeBetweenBgScan = (v_U8_t)pScanReq->scanInterval; pScanLog->numChannel = pScanReq->ChannelInfo.numOfChannels; if(pScanLog->numChannel && (pScanLog->numChannel < VOS_LOG_MAX_NUM_CHANNEL)) { vos_mem_copy(pScanLog->channels, pScanReq->ChannelInfo.ChannelList, pScanLog->numChannel); } WLAN_VOS_DIAG_LOG_REPORT(pScanLog); } } #endif //#ifdef FEATURE_WLAN_DIAG_SUPPORT_CSR status = ccmCfgSetInt(pMac, WNI_CFG_BACKGROUND_SCAN_PERIOD, pScanReq->scanInterval, NULL, eANI_BOOLEAN_FALSE); } else { //No need to stop aging because IDLE scan is still running status = ccmCfgSetInt(pMac, WNI_CFG_BACKGROUND_SCAN_PERIOD, 0, NULL, eANI_BOOLEAN_FALSE); } if(pScanReq->SSID.length > WNI_CFG_SSID_LEN) { pScanReq->SSID.length = WNI_CFG_SSID_LEN; } status = ccmCfgSetStr(pMac, WNI_CFG_BG_SCAN_CHANNEL_LIST, pScanReq->ChannelInfo.ChannelList, dataLen, NULL, eANI_BOOLEAN_FALSE); status = ccmCfgSetStr(pMac, WNI_CFG_SSID, (tANI_U8 *)pScanReq->SSID.ssId, pScanReq->SSID.length, NULL, eANI_BOOLEAN_FALSE); return (status); } eHalStatus csrScanAbortMacScan(tpAniSirGlobal pMac, tANI_U8 sessionId, eCsrAbortReason reason) { eHalStatus status = eHAL_STATUS_FAILURE; tSirSmeScanAbortReq *pMsg; tANI_U16 msgLen; tListElem *pEntry; tSmeCmd *pCommand; if (!pMac->fScanOffload) { #ifdef WLAN_AP_STA_CONCURRENCY csrLLLock(&pMac->scan.scanCmdPendingList); while(NULL != (pEntry = csrLLRemoveHead(&pMac->scan.scanCmdPendingList, LL_ACCESS_NOLOCK))) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); csrAbortCommand( pMac, pCommand, eANI_BOOLEAN_FALSE); } csrLLUnlock(&pMac->scan.scanCmdPendingList); #endif pMac->scan.fDropScanCmd = eANI_BOOLEAN_TRUE; csrRemoveCmdFromPendingList( pMac, &pMac->roam.roamCmdPendingList, eSmeCommandScan); csrRemoveCmdFromPendingList( pMac, &pMac->sme.smeCmdPendingList, eSmeCommandScan); pMac->scan.fDropScanCmd = eANI_BOOLEAN_FALSE; pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK); } else { pMac->scan.fDropScanCmd = eANI_BOOLEAN_TRUE; csrRemoveCmdWithSessionIdFromPendingList(pMac, sessionId, &pMac->sme.smeScanCmdPendingList, eSmeCommandScan); pMac->scan.fDropScanCmd = eANI_BOOLEAN_FALSE; pEntry = csrLLPeekHead(&pMac->sme.smeScanCmdActiveList, LL_ACCESS_LOCK); } //We need to abort scan only if we are scanning if(NULL != pEntry) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); if(eSmeCommandScan == pCommand->command && pCommand->sessionId == sessionId) { msgLen = (tANI_U16)(sizeof(tSirSmeScanAbortReq)); pMsg = vos_mem_malloc(msgLen); if ( NULL == pMsg ) { status = eHAL_STATUS_FAILURE; smsLog(pMac, LOGE, FL("Failed to allocate memory for SmeScanAbortReq")); } else { if(reason == eCSR_SCAN_ABORT_DUE_TO_BAND_CHANGE) { pCommand->u.scanCmd.abortScanDueToBandChange = eANI_BOOLEAN_TRUE; } vos_mem_set((void *)pMsg, msgLen, 0); pMsg->type = pal_cpu_to_be16((tANI_U16)eWNI_SME_SCAN_ABORT_IND); pMsg->msgLen = pal_cpu_to_be16(msgLen); pMsg->sessionId = sessionId; status = palSendMBMessage(pMac->hHdd, pMsg); } } } return(status); } void csrRemoveCmdWithSessionIdFromPendingList(tpAniSirGlobal pMac, tANI_U8 sessionId, tDblLinkList *pList, eSmeCommandType commandType) { tDblLinkList localList; tListElem *pEntry; tSmeCmd *pCommand; tListElem *pEntryToRemove; vos_mem_zero(&localList, sizeof(tDblLinkList)); if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList))) { smsLog(pMac, LOGE, FL(" failed to open list")); return; } csrLLLock(pList); if ((pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK))) { /* Have to make sure we don't loop back to the head of the list, * which will happen if the entry is NOT on the list */ while (pEntry) { pEntryToRemove = pEntry; pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); pCommand = GET_BASE_ADDR( pEntryToRemove, tSmeCmd, Link ); if ((pCommand->command == commandType) && (pCommand->sessionId == sessionId)) { /* Remove that entry only */ if (csrLLRemoveEntry( pList, pEntryToRemove, LL_ACCESS_NOLOCK)) { csrLLInsertTail(&localList, pEntryToRemove, LL_ACCESS_NOLOCK); } } } } csrLLUnlock(pList); while ((pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK))) { pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link); csrAbortCommand(pMac, pCommand, eANI_BOOLEAN_FALSE); } csrLLClose(&localList); } void csrRemoveCmdFromPendingList(tpAniSirGlobal pMac, tDblLinkList *pList, eSmeCommandType commandType ) { tDblLinkList localList; tListElem *pEntry; tSmeCmd *pCommand; tListElem *pEntryToRemove; vos_mem_zero(&localList, sizeof(tDblLinkList)); if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList))) { smsLog(pMac, LOGE, FL(" failed to open list")); return; } csrLLLock(pList); if( !csrLLIsListEmpty( pList, LL_ACCESS_NOLOCK ) ) { pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK); // Have to make sure we don't loop back to the head of the list, which will // happen if the entry is NOT on the list... while( pEntry ) { pEntryToRemove = pEntry; pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); pCommand = GET_BASE_ADDR( pEntryToRemove, tSmeCmd, Link ); if ( pCommand->command == commandType ) { // Remove that entry only if(csrLLRemoveEntry( pList, pEntryToRemove, LL_ACCESS_NOLOCK)) { csrLLInsertTail(&localList, pEntryToRemove, LL_ACCESS_NOLOCK); } } } } csrLLUnlock(pList); while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); csrAbortCommand( pMac, pCommand, eANI_BOOLEAN_FALSE); } csrLLClose(&localList); } eHalStatus csrScanAbortScanForSSID(tpAniSirGlobal pMac, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_SUCCESS; tSirSmeScanAbortReq *pMsg; tANI_U16 msgLen; tListElem *pEntry; tSmeCmd *pCommand; if (!pMac->fScanOffload) { pMac->scan.fDropScanCmd = eANI_BOOLEAN_TRUE; #ifdef WLAN_AP_STA_CONCURRENCY csrRemoveScanForSSIDFromPendingList( pMac, &pMac->scan.scanCmdPendingList, sessionId); #endif csrRemoveScanForSSIDFromPendingList( pMac, &pMac->roam.roamCmdPendingList, sessionId); csrRemoveScanForSSIDFromPendingList( pMac, &pMac->sme.smeCmdPendingList, sessionId); pMac->scan.fDropScanCmd = eANI_BOOLEAN_FALSE; pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK); } else { pMac->scan.fDropScanCmd = eANI_BOOLEAN_TRUE; csrRemoveScanForSSIDFromPendingList( pMac, &pMac->sme.smeScanCmdPendingList, sessionId); pMac->scan.fDropScanCmd = eANI_BOOLEAN_FALSE; pEntry = csrLLPeekHead(&pMac->sme.smeScanCmdActiveList, LL_ACCESS_LOCK); } if(NULL != pEntry) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); if ( (eSmeCommandScan == pCommand->command ) && (sessionId == pCommand->sessionId)) { if ( eCsrScanForSsid == pCommand->u.scanCmd.reason) { msgLen = (tANI_U16)(sizeof( tSirSmeScanAbortReq )); pMsg = vos_mem_malloc(msgLen); if ( NULL == pMsg ) { status = eHAL_STATUS_FAILURE; smsLog(pMac, LOGE, FL("Failed to allocate memory for SmeScanAbortReq")); } else { vos_mem_zero((void *)pMsg, msgLen); pMsg->type = pal_cpu_to_be16((tANI_U16)eWNI_SME_SCAN_ABORT_IND); pMsg->msgLen = pal_cpu_to_be16(msgLen); pMsg->sessionId = sessionId; status = palSendMBMessage(pMac->hHdd, pMsg); } } } } return( status ); } void csrRemoveScanForSSIDFromPendingList(tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U32 sessionId) { tDblLinkList localList; tListElem *pEntry; tSmeCmd *pCommand; tListElem *pEntryToRemove; vos_mem_zero(&localList, sizeof(tDblLinkList)); if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList))) { smsLog(pMac, LOGE, FL(" failed to open list")); return; } csrLLLock(pList); if( !csrLLIsListEmpty( pList, LL_ACCESS_NOLOCK ) ) { pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK); // Have to make sure we don't loop back to the head of the list, which will // happen if the entry is NOT on the list... while( pEntry ) { pEntryToRemove = pEntry; pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); pCommand = GET_BASE_ADDR( pEntryToRemove, tSmeCmd, Link ); if ( (eSmeCommandScan == pCommand->command ) && (sessionId == pCommand->sessionId) ) { if ( eCsrScanForSsid == pCommand->u.scanCmd.reason) { // Remove that entry only if ( csrLLRemoveEntry( pList, pEntryToRemove, LL_ACCESS_NOLOCK)) { csrLLInsertTail(&localList, pEntryToRemove, LL_ACCESS_NOLOCK); } } } } } csrLLUnlock(pList); while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); csrAbortCommand( pMac, pCommand, eANI_BOOLEAN_FALSE); } csrLLClose(&localList); } eHalStatus csrScanAbortMacScanNotForConnect(tpAniSirGlobal pMac, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_SUCCESS; if( !csrIsScanForRoamCommandActive( pMac ) ) { //Only abort the scan if it is not used for other roam/connect purpose status = csrScanAbortMacScan(pMac, sessionId, eCSR_SCAN_ABORT_DEFAULT); } return (status); } eHalStatus csrScanGetScanChannelInfo(tpAniSirGlobal pMac, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_SUCCESS; tSirMbMsg *pMsg; tANI_U16 msgLen; if (pMac->fScanOffload) msgLen = (tANI_U16)(sizeof(tSirSmeGetScanChanReq)); else msgLen = (tANI_U16)(sizeof(tSirMbMsg)); pMsg = vos_mem_malloc(msgLen); if ( NULL == pMsg ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pMsg, msgLen, 0); pMsg->type = eWNI_SME_GET_SCANNED_CHANNEL_REQ; pMsg->msgLen = msgLen; if (pMac->fScanOffload) ((tSirSmeGetScanChanReq *)pMsg)->sessionId = sessionId; status = palSendMBMessage(pMac->hHdd, pMsg); } return( status ); } tANI_BOOLEAN csrRoamIsValidChannel( tpAniSirGlobal pMac, tANI_U8 channel ) { tANI_BOOLEAN fValid = FALSE; tANI_U32 idxValidChannels; tANI_U32 len = pMac->roam.numValidChannels; for ( idxValidChannels = 0; ( idxValidChannels < len ); idxValidChannels++ ) { if ( channel == pMac->roam.validChannelList[ idxValidChannels ] ) { fValid = TRUE; break; } } return fValid; } #ifdef FEATURE_WLAN_SCAN_PNO eHalStatus csrScanSavePreferredNetworkFound(tpAniSirGlobal pMac, tSirPrefNetworkFoundInd *pPrefNetworkFoundInd) { v_U32_t uLen = 0; tpSirProbeRespBeacon pParsedFrame; tCsrScanResult *pScanResult = NULL; tSirBssDescription *pBssDescr = NULL; tANI_BOOLEAN fDupBss; tDot11fBeaconIEs *pIesLocal = NULL; tAniSSID tmpSsid; v_TIME_t timer=0; tpSirMacMgmtHdr macHeader = (tpSirMacMgmtHdr)pPrefNetworkFoundInd->data; tListElem *pEntry; pParsedFrame = (tpSirProbeRespBeacon)vos_mem_malloc(sizeof(tSirProbeRespBeacon)); if (NULL == pParsedFrame) { smsLog(pMac, LOGE, FL(" fail to allocate memory for frame")); return eHAL_STATUS_RESOURCES; } if ( pPrefNetworkFoundInd->frameLength <= SIR_MAC_HDR_LEN_3A ) { smsLog(pMac, LOGE, FL("Not enough bytes in PNO indication probe resp frame! length=%d"), pPrefNetworkFoundInd->frameLength); vos_mem_free(pParsedFrame); return eHAL_STATUS_FAILURE; } if (sirConvertProbeFrame2Struct(pMac, &pPrefNetworkFoundInd->data[SIR_MAC_HDR_LEN_3A], pPrefNetworkFoundInd->frameLength - SIR_MAC_HDR_LEN_3A, pParsedFrame) != eSIR_SUCCESS || !pParsedFrame->ssidPresent) { smsLog(pMac, LOGE, FL("Parse error ProbeResponse, length=%d"), pPrefNetworkFoundInd->frameLength); vos_mem_free(pParsedFrame); return eHAL_STATUS_FAILURE; } //24 byte MAC header and 12 byte to ssid IE if (pPrefNetworkFoundInd->frameLength > (SIR_MAC_HDR_LEN_3A + SIR_MAC_B_PR_SSID_OFFSET)) { uLen = pPrefNetworkFoundInd->frameLength - (SIR_MAC_HDR_LEN_3A + SIR_MAC_B_PR_SSID_OFFSET); } pScanResult = vos_mem_malloc(sizeof(tCsrScanResult) + uLen); if ( NULL == pScanResult ) { smsLog(pMac, LOGE, FL(" fail to allocate memory for frame")); vos_mem_free(pParsedFrame); return eHAL_STATUS_RESOURCES; } vos_mem_set(pScanResult, sizeof(tCsrScanResult) + uLen, 0); pBssDescr = &pScanResult->Result.BssDescriptor; /* * Length of BSS description is without length of length itself and length * of pointer that holds the next BSS description */ pBssDescr->length = (tANI_U16)( sizeof(tSirBssDescription) - sizeof(tANI_U16) - sizeof(tANI_U32) + uLen); if (pParsedFrame->dsParamsPresent) { pBssDescr->channelId = pParsedFrame->channelNumber; } else if (pParsedFrame->HTInfo.present) { pBssDescr->channelId = pParsedFrame->HTInfo.primaryChannel; } else { pBssDescr->channelId = pParsedFrame->channelNumber; } if ((pBssDescr->channelId > 0) && (pBssDescr->channelId < 15)) { int i; // 11b or 11g packet // 11g iff extended Rate IE is present or // if there is an A rate in suppRate IE for (i = 0; i < pParsedFrame->supportedRates.numRates; i++) { if (sirIsArate(pParsedFrame->supportedRates.rate[i] & 0x7f)) { pBssDescr->nwType = eSIR_11G_NW_TYPE; break; } } if (pParsedFrame->extendedRatesPresent) { pBssDescr->nwType = eSIR_11G_NW_TYPE; } } else { // 11a packet pBssDescr->nwType = eSIR_11A_NW_TYPE; } pBssDescr->sinr = 0; pBssDescr->rssi = -1 * pPrefNetworkFoundInd->rssi; pBssDescr->beaconInterval = pParsedFrame->beaconInterval; if (!pBssDescr->beaconInterval) { smsLog(pMac, LOGW, FL("Bcn Interval is Zero , default to 100" MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pBssDescr->bssId) ); pBssDescr->beaconInterval = 100; } pBssDescr->timeStamp[0] = pParsedFrame->timeStamp[0]; pBssDescr->timeStamp[1] = pParsedFrame->timeStamp[1]; pBssDescr->capabilityInfo = *((tANI_U16 *)&pParsedFrame->capabilityInfo); vos_mem_copy((tANI_U8 *) &pBssDescr->bssId, (tANI_U8 *) macHeader->bssId, sizeof(tSirMacAddr)); pBssDescr->nReceivedTime = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd); smsLog( pMac, LOG2, "(%s):Bssid= "MAC_ADDRESS_STR " chan= %d, rssi = %d", __func__, MAC_ADDR_ARRAY(pBssDescr->bssId), pBssDescr->channelId, pBssDescr->rssi ); //IEs if (uLen) { vos_mem_copy(&pBssDescr->ieFields, pPrefNetworkFoundInd->data + (SIR_MAC_HDR_LEN_3A + SIR_MAC_B_PR_SSID_OFFSET), uLen); } pIesLocal = (tDot11fBeaconIEs *)( pScanResult->Result.pvIes ); if ( !pIesLocal && (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, &pScanResult->Result.BssDescriptor, &pIesLocal))) ) { smsLog(pMac, LOGE, FL(" Cannot parse IEs")); csrFreeScanResultEntry(pMac, pScanResult); vos_mem_free(pParsedFrame); return eHAL_STATUS_RESOURCES; } fDupBss = csrRemoveDupBssDescription( pMac, &pScanResult->Result.BssDescriptor, pIesLocal, &tmpSsid, &timer, FALSE); //Check whether we have reach out limit if ( CSR_SCAN_IS_OVER_BSS_LIMIT(pMac) ) { //Limit reach smsLog(pMac, LOGE, FL(" BSS limit reached")); //Free the resources if( (pScanResult->Result.pvIes == NULL) && pIesLocal ) { vos_mem_free(pIesLocal); } csrFreeScanResultEntry(pMac, pScanResult); vos_mem_free(pParsedFrame); return eHAL_STATUS_RESOURCES; } if ((macHeader->fc.type == SIR_MAC_MGMT_FRAME) && (macHeader->fc.subType == SIR_MAC_MGMT_PROBE_RSP)) { pScanResult->Result.BssDescriptor.fProbeRsp = 1; } //Add to scan cache csrScanAddResult(pMac, pScanResult, pIesLocal, pPrefNetworkFoundInd->sessionId); pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_LOCK ); if (pEntry && 0 != pMac->scan.scanResultCfgAgingTime) csrScanStartResultCfgAgingTimer(pMac); if( (pScanResult->Result.pvIes == NULL) && pIesLocal ) { vos_mem_free(pIesLocal); } vos_mem_free(pParsedFrame); return eHAL_STATUS_SUCCESS; } #endif //FEATURE_WLAN_SCAN_PNO #ifdef FEATURE_WLAN_LFR void csrInitOccupiedChannelsList(tpAniSirGlobal pMac, tANI_U8 sessionId) { tListElem *pEntry = NULL; tCsrScanResult *pBssDesc = NULL; tDot11fBeaconIEs *pIes = NULL; tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo[sessionId]; if (0 != pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels) { smsLog(pMac, LOG1, FL("Ini file contains neighbor scan channel list, " "hence NO need to build occupied channel list (numChannels = %d)"), pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels); return; } if (!csrNeighborRoamIsNewConnectedProfile(pMac, sessionId)) { smsLog(pMac, LOG2, FL("donot flush occupied list since current roam " "profile matches previous (numChannels = %d)"), pMac->scan.occupiedChannels[sessionId].numChannels); return; } /* Empty occupied channels here */ pMac->scan.occupiedChannels[sessionId].numChannels = 0; csrLLLock(&pMac->scan.scanResultList); pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK); while( pEntry ) { pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link ); pIes = (tDot11fBeaconIEs *)( pBssDesc->Result.pvIes ); //At this time, pBssDescription->Result.pvIes may be NULL if( !pIes && (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, &pBssDesc->Result.BssDescriptor, &pIes))) ) { continue; } csrScanAddToOccupiedChannels(pMac, pBssDesc, sessionId, &pMac->scan.occupiedChannels[sessionId], pIes); /* * Free the memory allocated for pIes in csrGetParsedBssDescriptionIEs */ if( (pBssDesc->Result.pvIes == NULL) && pIes ) { vos_mem_free(pIes); } pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK); }//while csrLLUnlock(&pMac->scan.scanResultList); } #endif eHalStatus csrScanCreateEntryInScanCache(tpAniSirGlobal pMac, tANI_U32 sessionId, tCsrBssid bssid, tANI_U8 channel) { eHalStatus status = eHAL_STATUS_SUCCESS; tDot11fBeaconIEs *pNewIes = NULL; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); tSirBssDescription *pNewBssDescriptor = NULL; tANI_U32 size = 0; if(NULL == pSession) { status = eHAL_STATUS_FAILURE; return status; } smsLog(pMac, LOG2, FL("csrScanCreateEntryInScanCache: Current bssid::" MAC_ADDRESS_STR), MAC_ADDR_ARRAY(pSession->pConnectBssDesc->bssId)); smsLog(pMac, LOG2, FL("csrScanCreateEntryInScanCache: My bssid::" MAC_ADDRESS_STR" channel %d"), MAC_ADDR_ARRAY(bssid), channel); do { if(!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, pSession->pConnectBssDesc, &pNewIes))) { smsLog(pMac, LOGE, FL("%s: Failed to parse IEs"), __func__); status = eHAL_STATUS_FAILURE; break; } size = pSession->pConnectBssDesc->length + sizeof(pSession->pConnectBssDesc->length); if (size) { pNewBssDescriptor = vos_mem_malloc(size); if ( NULL == pNewBssDescriptor ) status = eHAL_STATUS_FAILURE; else status = eHAL_STATUS_SUCCESS; if (HAL_STATUS_SUCCESS(status)) { vos_mem_copy(pNewBssDescriptor, pSession->pConnectBssDesc, size); } else { smsLog(pMac, LOGE, FL("%s: memory allocation failed"), __func__); status = eHAL_STATUS_FAILURE; break; } //change the BSSID & channel as passed vos_mem_copy(pNewBssDescriptor->bssId, bssid, sizeof(tSirMacAddr)); pNewBssDescriptor->channelId = channel; if (NULL == csrScanAppendBssDescription(pMac, pNewBssDescriptor, pNewIes, TRUE, sessionId)) { smsLog(pMac, LOGE, FL("csrScanAppendBssDescription failed")); status = eHAL_STATUS_FAILURE; break; } } else { smsLog(pMac, LOGE, FL("%s: length of bss descriptor is 0"), __func__); status = eHAL_STATUS_FAILURE; break; } smsLog(pMac, LOGE, FL("%s: entry successfully added in scan cache"), __func__); }while(0); if(pNewIes) { vos_mem_free(pNewIes); } if(pNewBssDescriptor) { vos_mem_free(pNewBssDescriptor); } return status; } #ifdef FEATURE_WLAN_ESE // Update the TSF with the difference in system time void UpdateCCKMTSF(tANI_U32 *timeStamp0, tANI_U32 *timeStamp1, tANI_U32 *incr) { tANI_U64 timeStamp64 = ((tANI_U64)*timeStamp1 << 32) | (*timeStamp0); timeStamp64 = (tANI_U64)(timeStamp64 + (tANI_U64)*incr); *timeStamp0 = (tANI_U32)(timeStamp64 & 0xffffffff); *timeStamp1 = (tANI_U32)((timeStamp64 >> 32) & 0xffffffff); } #endif /** * csrScanSaveRoamOffloadApToScanCache * This function parses the received beacon/probe response * from the firmware as part of the roam synch indication. * The beacon or the probe response is parsed and is also * saved into the scan cache * * @param pMac Pointer to Global Mac * @param pRoamOffloadSynchInd Roam Synch Indication from * firmware which also contains the beacon/probe * response * @return Status */ #ifdef WLAN_FEATURE_ROAM_OFFLOAD eHalStatus csrScanSaveRoamOffloadApToScanCache(tpAniSirGlobal pMac, tSirRoamOffloadSynchInd *pRoamOffloadSynchInd) { v_U32_t uLen = 0; tANI_BOOLEAN fDupBss; tDot11fBeaconIEs *pIesLocal = NULL; tAniSSID tmpSsid; v_TIME_t timer=0; tCsrScanResult *pScanResult = NULL; tANI_U8 sessionId = pRoamOffloadSynchInd->roamedVdevId; uLen = pRoamOffloadSynchInd->beaconProbeRespLength - (SIR_MAC_HDR_LEN_3A + SIR_MAC_B_PR_SSID_OFFSET); pScanResult = vos_mem_malloc(sizeof(tCsrScanResult) + uLen); if ( pScanResult == NULL ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, " fail to allocate memory for frame"); return eHAL_STATUS_RESOURCES; } vos_mem_zero(pScanResult, sizeof(tCsrScanResult) + uLen ); vos_mem_copy(&pScanResult->Result.BssDescriptor, pRoamOffloadSynchInd->pbssDescription, (sizeof(tSirBssDescription) + uLen)); pIesLocal = (tDot11fBeaconIEs *)( pScanResult->Result.pvIes ); if ( !pIesLocal && (!HAL_STATUS_SUCCESS(csrGetParsedBssDescriptionIEs(pMac, &pScanResult->Result.BssDescriptor, &pIesLocal))) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:Cannot Parse IEs", __func__); csrFreeScanResultEntry(pMac, pScanResult); return eHAL_STATUS_RESOURCES; } fDupBss = csrRemoveDupBssDescription(pMac, &pScanResult->Result.BssDescriptor, pIesLocal, &tmpSsid, &timer, TRUE); if ( CSR_SCAN_IS_OVER_BSS_LIMIT(pMac) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:BSS Limit Exceed", __func__); if( (pScanResult->Result.pvIes == NULL) && pIesLocal ) { vos_mem_free(pIesLocal); } csrFreeScanResultEntry(pMac, pScanResult); return eHAL_STATUS_RESOURCES; } csrScanAddResult(pMac, pScanResult, pIesLocal, sessionId); return eHAL_STATUS_SUCCESS; } #endif /** * csr_get_bssdescr_from_scan_handle() - This function to extract * first bss description from scan handle * @result_handle: an object for the result. * * This function is written to extract first bss from scan handle. * * Return: first bss descriptor from the scan handle. */ tSirBssDescription* csr_get_bssdescr_from_scan_handle(tScanResultHandle result_handle, tSirBssDescription *bss_descr) { tListElem *first_element = NULL; tCsrScanResult *scan_result = NULL; tScanResultList *bss_list = (tScanResultList *)result_handle; if (NULL == bss_list) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Empty bss_list")); return NULL; } if (csrLLIsListEmpty(&bss_list->List, LL_ACCESS_NOLOCK)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("bss_list->List is empty")); vos_mem_free(bss_list); return NULL; } first_element = csrLLPeekHead(&bss_list->List, LL_ACCESS_NOLOCK); if (first_element) { scan_result = GET_BASE_ADDR(first_element, tCsrScanResult, Link); vos_mem_copy(bss_descr, &scan_result->Result.BssDescriptor, sizeof(tSirBssDescription)); } return bss_descr; }
LeEco-MSM8996-Development/android_kernel_leeco_msm8996
drivers/staging/qcacld-2.0/CORE/SME/src/csr/csrApiScan.c
C
gpl-2.0
337,521
/* * * COPYRIGHT (c) 1989-1999. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.org/license/LICENSE. */ #ifndef _MC68681_P_H_ #define _MC68681_P_H_ #ifdef __cplusplus extern "C" { #endif /* * Define MC68681_STATIC to nothing while debugging so the entry points * will show up in the symbol table. */ #define MC68681_STATIC /* #define MC68681_STATIC static */ /* * mc68681 register offsets Read/Write Addresses */ #define MC68681_MODE_REG_1A 0 /* MR1A-MR Prior to Read */ #define MC68681_MODE_REG_2A 0 /* MR2A-MR After Read */ #define MC68681_COUNT_MODE_CURRENT_MSB 6 /* CTU */ #define MC68681_COUNTER_TIMER_UPPER_REG 6 /* CTU */ #define MC68681_COUNT_MODE_CURRENT_LSB 7 /* CTL */ #define MC68681_COUNTER_TIMER_LOWER_REG 7 /* CTL */ #define MC68681_INTERRUPT_VECTOR_REG 12 /* IVR */ #define MC68681_MODE_REG_1B 8 /* MR1B-MR Prior to Read */ #define MC68681_MODE_REG_2B 8 /* MR2BA-MR After Read */ /* * mc68681 register offsets Read Only Addresses */ #define MC68681_STATUS_REG_A 1 /* SRA */ #define MC68681_MASK_ISR_REG 2 /* MISR */ #define MC68681_RECEIVE_BUFFER_A 3 /* RHRA */ #define MC68681_INPUT_PORT_CHANGE_REG 4 /* IPCR */ #define MC68681_INTERRUPT_STATUS_REG 5 /* ISR */ #define MC68681_STATUS_REG_B 9 /* SRB */ #define MC68681_RECEIVE_BUFFER_B 11 /* RHRB */ #define MC68681_INPUT_PORT 13 /* IP */ #define MC68681_START_COUNT_CMD 14 /* SCC */ #define MC68681_STOP_COUNT_CMD 15 /* STC */ /* * mc68681 register offsets Write Only Addresses */ #define MC68681_CLOCK_SELECT_REG_A 1 /* CSRA */ #define MC68681_COMMAND_REG_A 2 /* CRA */ #define MC68681_TRANSMIT_BUFFER_A 3 /* THRA */ #define MC68681_AUX_CTRL_REG 4 /* ACR */ #define MC68681_INTERRUPT_MASK_REG 5 /* IMR */ #define MC68681_CLOCK_SELECT_REG_B 9 /* CSRB */ #define MC68681_COMMAND_REG_B 10 /* CRB */ #define MC68681_TRANSMIT_BUFFER_B 11 /* THRB */ #define MC68681_OUTPUT_PORT_CONFIG_REG 13 /* OPCR */ #define MC68681_OUTPUT_PORT_SET_REG 14 /* SOPBC */ #define MC68681_OUTPUT_PORT_RESET_BITS 15 /* COPBC */ /* * DUART Command Register Definitions: * * MC68681_COMMAND_REG_A,MC68681_COMMAND_REG_B */ #define MC68681_MODE_REG_ENABLE_RX 0x01 #define MC68681_MODE_REG_DISABLE_RX 0x02 #define MC68681_MODE_REG_ENABLE_TX 0x04 #define MC68681_MODE_REG_DISABLE_TX 0x08 #define MC68681_MODE_REG_RESET_MR_PTR 0x10 #define MC68681_MODE_REG_RESET_RX 0x20 #define MC68681_MODE_REG_RESET_TX 0x30 #define MC68681_MODE_REG_RESET_ERROR 0x40 #define MC68681_MODE_REG_RESET_BREAK 0x50 #define MC68681_MODE_REG_START_BREAK 0x60 #define MC68681_MODE_REG_STOP_BREAK 0x70 #define MC68681_MODE_REG_SET_RX_BRG 0x80 #define MC68681_MODE_REG_CLEAR_RX_BRG 0x90 #define MC68681_MODE_REG_SET_TX_BRG 0xa0 #define MC68681_MODE_REG_CLEAR_TX_BRG 0xb0 #define MC68681_MODE_REG_SET_STANDBY 0xc0 #define MC68681_MODE_REG_SET_ACTIVE 0xd0 /* * Mode Register Definitions * * MC68681_MODE_REG_1A * MC68681_MODE_REG_1B */ #define MC68681_5BIT_CHARS 0x00 #define MC68681_6BIT_CHARS 0x01 #define MC68681_7BIT_CHARS 0x02 #define MC68681_8BIT_CHARS 0x03 #define MC68681_ODD_PARITY 0x00 #define MC68681_EVEN_PARITY 0x04 #define MC68681_WITH_PARITY 0x00 #define MC68681_FORCE_PARITY 0x08 #define MC68681_NO_PARITY 0x10 #define MC68681_MULTI_DROP 0x18 #define MC68681_ERR_MODE_CHAR 0x00 #define MC68681_ERR_MODE_BLOCK 0x20 #define MC68681_RX_INTR_RX_READY 0x00 #define MC68681_RX_INTR_FFULL 0x40 #define MC68681_NO_RX_RTS_CTL 0x00 #define MC68681_RX_RTS_CTRL 0x80 /* * Mode Register Definitions * * MC68681_MODE_REG_2A * MC68681_MODE_REG_2B */ #define MC68681_STOP_BIT_LENGTH__563 0x00 #define MC68681_STOP_BIT_LENGTH__625 0x01 #define MC68681_STOP_BIT_LENGTH__688 0x02 #define MC68681_STOP_BIT_LENGTH__75 0x03 #define MC68681_STOP_BIT_LENGTH__813 0x04 #define MC68681_STOP_BIT_LENGTH__875 0x05 #define MC68681_STOP_BIT_LENGTH__938 0x06 #define MC68681_STOP_BIT_LENGTH_1 0x07 #define MC68681_STOP_BIT_LENGTH_1_563 0x08 #define MC68681_STOP_BIT_LENGTH_1_625 0x09 #define MC68681_STOP_BIT_LENGTH_1_688 0x0a #define MC68681_STOP_BIT_LENGTH_1_75 0x0b #define MC68681_STOP_BIT_LENGTH_1_813 0x0c #define MC68681_STOP_BIT_LENGTH_1_875 0x0d #define MC68681_STOP_BIT_LENGTH_1_938 0x0e #define MC68681_STOP_BIT_LENGTH_2 0x0f #define MC68681_CTS_ENABLE_TX 0x10 #define MC68681_TX_RTS_CTRL 0x20 #define MC68681_CHANNEL_MODE_NORMAL 0x00 #define MC68681_CHANNEL_MODE_ECHO 0x40 #define MC68681_CHANNEL_MODE_LOCAL_LOOP 0x80 #define MC68681_CHANNEL_MODE_REMOTE_LOOP 0xc0 /* * Status Register Definitions * * MC68681_STATUS_REG_A, MC68681_STATUS_REG_B */ #define MC68681_RX_READY 0x01 #define MC68681_FFULL 0x02 #define MC68681_TX_READY 0x04 #define MC68681_TX_EMPTY 0x08 #define MC68681_OVERRUN_ERROR 0x10 #define MC68681_PARITY_ERROR 0x20 #define MC68681_FRAMING_ERROR 0x40 #define MC68681_RECEIVED_BREAK 0x80 #define MC68681_RX_ERRORS \ (MC68681_OVERRUN_ERROR|MC68681_PARITY_ERROR| \ MC68681_FRAMING_ERROR|MC68681_RECEIVED_BREAK) /* * Interupt Status Register Definitions. * * MC68681_INTERRUPT_STATUS_REG */ /* * Interupt Mask Register Definitions * * MC68681_INTERRUPT_MASK_REG */ /* These are passed to mc68681_build_imr */ #define MC68681_IR_TX_READY 0x01 #define MC68681_IR_RX_READY 0x02 #define MC68681_IR_BREAK 0x04 #define MC68681_IMR_ENABLE_ALL 0x07 #define MC68681_IMR_DISABLE_ALL 0x00 #define MC68681_IMR_ENABLE_ALL_EXCEPT_TX 0x06 #define MC68681_IR_TX_READY_A 0x01 #define MC68681_IR_RX_READY_A 0x02 #define MC68681_IR_BREAK_A 0x04 #define MC68681_IR_COUNTER_READY 0x08 #define MC68681_IR_TX_READY_B 0x10 #define MC68681_IR_RX_READY_B 0x20 #define MC68681_IR_BREAK_B 0x40 #define MC68681_IR_INPUT_PORT_CHANGE 0x80 /* * Status Register Definitions. * * MC68681_STATUS_REG_A,MC68681_STATUS_REG_B */ #define MC68681_STATUS_RXRDY 0x01 #define MC68681_STATUS_FFULL 0x02 #define MC68681_STATUS_TXRDY 0x04 #define MC68681_STATUS_TXEMT 0x08 #define MC68681_STATUS_OVERRUN_ERROR 0x10 #define MC68681_STATUS_PARITY_ERROR 0x20 #define MC68681_STATUS_FRAMING_ERROR 0x40 #define MC68681_STATUS_RECEIVED_BREAK 0x80 /* * Definitions for the Interrupt Vector Register: * * MC68681_INTERRUPT_VECTOR_REG */ #define MC68681_INTERRUPT_VECTOR_INIT 0x0f /* * Definitions for the Auxiliary Control Register * * MC68681_AUX_CTRL_REG */ #define MC68681_AUX_BRG_SET1 0x00 #define MC68681_AUX_BRG_SET2 0x80 /* * Per chip context control */ typedef struct _mc68681_context { int mate; unsigned char imr; } mc68681_context; /* * Driver functions */ MC68681_STATIC void mc68681_initialize_context( int minor, mc68681_context *pmc68681Context ); MC68681_STATIC bool mc68681_probe(int minor); MC68681_STATIC int mc68681_set_attributes( int minor, const struct termios *t ); MC68681_STATIC void mc68681_init(int minor); MC68681_STATIC int mc68681_open( int major, int minor, void * arg ); MC68681_STATIC int mc68681_close( int major, int minor, void * arg ); MC68681_STATIC void mc68681_write_polled( int minor, char cChar ); MC68681_STATIC void mc68681_initialize_interrupts(int minor); MC68681_STATIC ssize_t mc68681_write_support_int( int minor, const char *buf, size_t len ); MC68681_STATIC ssize_t mc68681_write_support_polled( int minor, const char *buf, size_t len ); MC68681_STATIC int mc68681_inbyte_nonblocking_polled( int minor ); MC68681_STATIC unsigned int mc68681_build_imr( int minor, int enable_flag ); MC68681_STATIC void mc68681_process( int minor ); MC68681_STATIC void mc68681_enable_interrupts( int minor, int imr_mask ); MC68681_STATIC rtems_isr mc68681_isr( rtems_vector_number vector ); #ifdef __cplusplus } #endif #endif /* _MC68681_P_H_ */
heshamelmatary/rtems-rumpkernel
c/src/libchip/serial/mc68681_p.h
C
gpl-2.0
10,575
#ifndef __DE_CLOCK_H__ #define __DE_CLOCK_H__ #include "ebios_de.h" typedef enum { CLK_NONE = 0, SYS_CLK_PLL3 = 1, SYS_CLK_PLL7 = 2, SYS_CLK_PLL9 = 3, SYS_CLK_PLL10 = 4, SYS_CLK_PLL3X2 = 5, SYS_CLK_PLL6 = 6, SYS_CLK_PLL6x2 = 7, SYS_CLK_PLL7X2 = 8, SYS_CLK_MIPIPLL = 9, MOD_CLK_DEBE0 = 16, MOD_CLK_DEBE1 = 17, MOD_CLK_DEFE0 = 18, MOD_CLK_DEFE1 = 19, MOD_CLK_LCD0CH0 = 20, MOD_CLK_LCD0CH1 = 21, MOD_CLK_LCD1CH0 = 22, MOD_CLK_LCD1CH1 = 23, MOD_CLK_HDMI = 24, MOD_CLK_HDMI_DDC = 25, MOD_CLK_MIPIDSIS = 26, MOD_CLK_MIPIDSIP = 27, MOD_CLK_IEPDRC0 = 28, MOD_CLK_IEPDRC1 = 29, MOD_CLK_IEPDEU0 = 30, MOD_CLK_IEPDEU1 = 31, MOD_CLK_LVDS = 32, MOD_CLK_EDP = 33, MOD_CLK_DEBE2 = 34, MOD_CLK_DEFE2 = 35, MOD_CLK_SAT0 = 36, MOD_CLK_SAT1 = 37, MOD_CLK_SAT2 = 38, MOD_CLK_MERGE = 39, }__disp_clk_id_t; typedef struct { __disp_clk_id_t id; /* clock id */ char *name; /* clock name */ char *src_name; u32 freq; struct clk *hdl; }__disp_clk_t; extern __disp_clk_t disp_clk_pll_tbl[3]; extern __disp_clk_t disp_clk_mod_tbl[8]; #endif //__DE_CLOCK_H__
willemwouters/orangepi_kernel
drivers/video/sunxi/disp/de/lowlevel_sun8iw5/de_clock.h
C
gpl-2.0
1,114
-- DB Table update ALTER TABLE `holiday_dates` CHANGE `holiday_duration` `holiday_duration` INT(10) UNSIGNED DEFAULT 0 NOT NULL; -- Darkmoon Faire UPDATE `game_event` SET `start_time`= '2020-01-05 00:01:00', `end_time`= '2030-01-01 06:00:00' WHERE `eventEntry`= 3; -- Lunar Festival. Holiday ID: 327. UPDATE `game_event` SET `start_time`='2020-01-24 00:01:00', `occurence`='525600', `length`='30240' WHERE `eventEntry`=7; SET @HOLIDAYID := 327; SET @DATEID := 14; DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5); INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE. (@HOLIDAYID, @DATEID, 335921152), -- 2020-01-24. (@HOLIDAYID, @DATEID+1, 352681984), -- 2021-01-23. (@HOLIDAYID, @DATEID+2, 369459200), -- 2022-01-23. (@HOLIDAYID, @DATEID+3, 386236416), -- 2023-01-23. (@HOLIDAYID, @DATEID+4, 403013632), -- 2024-01-23. (@HOLIDAYID, @DATEID+5, 419774464); -- 2025-01-22. UPDATE `holiday_dates` SET `holiday_duration`= 360 WHERE `id`= 327; -- Love is in the air. Holiday ID: 423. UPDATE `game_event` SET `start_time`='2020-02-08 00:01:00', `occurence`='525600', `length`='20160' WHERE `eventEntry`=8; SET @HOLIDAYID := 423; SET @DATEID := 10; DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5); INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE. (@HOLIDAYID, @DATEID, 336707584), -- 2020-02-08. (@HOLIDAYID, @DATEID+1, 353468416), -- 2021-02-07. (@HOLIDAYID, @DATEID+2, 370245632), -- 2022-02-07. (@HOLIDAYID, @DATEID+3, 387022848), -- 2023-02-07. (@HOLIDAYID, @DATEID+4, 403800064), -- 2024-02-07. (@HOLIDAYID, @DATEID+5, 420560896); -- 2025-02-06. -- Pilgrim's Bounty. Holiday ID: 404. UPDATE `game_event` SET `start_time`='2020-11-23 01:00:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=26; SET @HOLIDAYID := 404; SET @DATEID := 11; DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5); INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE. (@HOLIDAYID, @DATEID, 346390592), -- 2020-11-23. (@HOLIDAYID, @DATEID+1, 363167808), -- 2021-11-23. (@HOLIDAYID, @DATEID+2, 379945024), -- 2022-11-23. (@HOLIDAYID, @DATEID+3, 396722240), -- 2023-11-23. (@HOLIDAYID, @DATEID+4, 413483072), -- 2024-11-22. (@HOLIDAYID, @DATEID+5, 430260288); -- 2025-11-22. -- Children's Week. Holiday ID: 201. UPDATE `game_event` SET `start_time`='2020-05-01 00:01:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=10; SET @HOLIDAYID := 201; SET @DATEID := 16; DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5); INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE. (@HOLIDAYID, @DATEID, 339738624), -- 2020-05-01. (@HOLIDAYID, @DATEID+1, 356515840), -- 2021-05-01. (@HOLIDAYID, @DATEID+2, 373293056), -- 2022-05-01. (@HOLIDAYID, @DATEID+3, 390070272), -- 2023-05-01. (@HOLIDAYID, @DATEID+4, 406274048), -- 2024-04-30. (@HOLIDAYID, @DATEID+5, 423051264); -- 2025-04-30. -- Noblegarden. Holiday ID: 181. UPDATE `game_event` SET `start_time`='2020-04-13 00:01:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=9; SET @HOLIDAYID := 181; SET @DATEID := 13; DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5); INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE. (@HOLIDAYID, @DATEID, 338886656), -- 2020-04-13. (@HOLIDAYID, @DATEID+1, 355663872), -- 2021-04-13. (@HOLIDAYID, @DATEID+2, 372441088), -- 2022-04-13. (@HOLIDAYID, @DATEID+3, 389218304), -- 2023-04-13. (@HOLIDAYID, @DATEID+4, 405979136), -- 2024-04-12. (@HOLIDAYID, @DATEID+5, 422756352); -- 2025-04-12. -- Harvest Festival. Holiday ID: 321. UPDATE `game_event` SET `start_time`='2020-09-29 00:01:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=11; SET @HOLIDAYID := 321; SET @DATEID := 14; DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5); INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE. (@HOLIDAYID, @DATEID, 344391680), -- 2020-09-29. (@HOLIDAYID, @DATEID+1, 361168896), -- 2021-09-29. (@HOLIDAYID, @DATEID+2, 377946112), -- 2022-09-29. (@HOLIDAYID, @DATEID+3, 394723328), -- 2023-09-29. (@HOLIDAYID, @DATEID+4, 411484160), -- 2024-09-28. (@HOLIDAYID, @DATEID+5, 428261376); -- 2025-09-28.
pete318/TrinityCore
sql/old/3.3.5a/world/20011_2020_02_15/2020_01_15_02_world_335.sql
SQL
gpl-2.0
4,630
Ext.define('Ext.rtl.scroll.Indicator', { override: 'Ext.scroll.Indicator', privates: { translateX: function(value) { if (this.getScroller().getRtl()) { value = -value; } this.callParent([value]); } } });
sqlwang/my_wpblog
wp-content/themes/extjs/ext/classic/classic/src/rtl/scroll/Indicator.js
JavaScript
gpl-2.0
297
/* Copyright (c) 1990-2003 Info-ZIP. All rights reserved. See the accompanying file LICENSE, version 2000-Apr-09 or later (the contents of which are also included in unzip.h) for terms of use. If, for some reason, all these files are missing, the Info-ZIP license also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html */ #ifndef __windll_h /* prevent multiple inclusions */ #define __windll_h #include <windows.h> #include <assert.h> /* required for all Windows applications */ #include <setjmp.h> #include "../unzip.h" #include "../windll/structs.h" #include "../windll/decs.h" /* Allow compilation under Borland C++ also */ #ifndef __based # define __based(A) #endif #ifdef UNZIP_INTERNAL extern jmp_buf dll_error_return; extern HANDLE hInst; /* current instance */ int win_fprintf(zvoid *pG, FILE *file, unsigned int, char far *); #endif #endif /* __windll_h */
HippoRemote/WinHippoVNC
zipunzip_src/unzip/windll/windll.h
C
gpl-2.0
915
/* Copyright (c) 2015, Oracle and/or its affiliates. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "abstract_crawler.h" #include "this_thread.h" #include <boost/date_time.hpp> using namespace Mysql::Tools::Dump; my_boost::atomic_uint64_t Abstract_crawler::next_chain_id; Abstract_crawler::Abstract_crawler( Mysql::I_callable<bool, const Mysql::Tools::Base::Message_data&>* message_handler, Simple_id_generator* object_id_generator) : Abstract_chain_element(message_handler, object_id_generator) {} void Abstract_crawler::register_chain_maker(I_chain_maker* new_chain_maker) { m_chain_makers.push_back(new_chain_maker); } void Abstract_crawler::process_dump_task(I_dump_task* new_dump_task) { m_dump_tasks_created.push_back(new_dump_task); Item_processing_data* main_item_processing_data= this->new_task_created(new_dump_task); this->object_processing_starts(main_item_processing_data); for (std::vector<I_chain_maker*>::iterator it= m_chain_makers.begin(); it != m_chain_makers.end(); ++it) { uint64 new_chain_id= next_chain_id++; Chain_data* chain_data= new Chain_data(new_chain_id); I_object_reader* chain= (*it)->create_chain(chain_data, new_dump_task); if (chain != NULL) { main_item_processing_data->set_chain(chain_data); chain->read_object( this->new_chain_created( chain_data, main_item_processing_data, chain)); } else { delete chain_data; } } this->object_processing_ends(main_item_processing_data); } void Abstract_crawler::wait_for_tasks_completion() { for (std::vector<I_dump_task*>::iterator it= m_dump_tasks_created.begin(); it != m_dump_tasks_created.end(); ++it) { while ((*it)->is_completed() == false) my_boost::this_thread::sleep(boost::posix_time::milliseconds(1)); } } bool Abstract_crawler::need_callbacks_in_child() { return true; }
myblockchain/myblockchain
client/dump/abstract_crawler.cc
C++
gpl-2.0
2,532
int f_test (int x) { char arr[SIZE]; return arr[x]; }
Gurgel100/gcc
gcc/testsuite/gcc.target/aarch64/stack-check-prologue.h
C
gpl-2.0
58
<?php /** * @file * Contains \Drupal\quickedit\Plugin\InPlaceEditorInterface. */ namespace Drupal\quickedit\Plugin; use Drupal\Component\Plugin\PluginInspectionInterface; use Drupal\Core\Field\FieldItemListInterface; /** * Defines an interface for in-place editors plugins. */ interface InPlaceEditorInterface extends PluginInspectionInterface { /** * Checks whether this in-place editor is compatible with a given field. * * @param \Drupal\Core\Field\FieldItemListInterface $items * The field values to be in-place edited. * * @return bool * TRUE if it is compatible, FALSE otherwise. */ public function isCompatible(FieldItemListInterface $items); /** * Generates metadata that is needed specifically for this editor. * * Will only be called by \Drupal\quickedit\MetadataGeneratorInterface::generate() * when the passed in field instance & item values will use this editor. * * @param \Drupal\Core\Field\FieldItemListInterface $items * The field values to be in-place edited. * * @return array * A keyed array with metadata. Each key should be prefixed with the plugin * ID of the editor. */ public function getMetadata(FieldItemListInterface $items); /** * Returns the attachments for this editor. * * @return array * An array of attachments, for use with #attached. * * @see drupal_process_attached() */ public function getAttachments(); }
drupaals/demo.com
d8/core/modules/quickedit/src/Plugin/InPlaceEditorInterface.php
PHP
gpl-2.0
1,462
using MixERP.Net.i18n.Resources; using MixERP.Net.WebControls.StockAdjustmentFactory.Helpers; using System.Web.UI.HtmlControls; namespace MixERP.Net.WebControls.StockAdjustmentFactory { public partial class FormView { private void AddErrorLabelBottom() { using (HtmlGenericControl errorLabel = new HtmlGenericControl()) { errorLabel.TagName = "div"; errorLabel.ID = "ErrorLabel"; errorLabel.Attributes.Add("class", "big error vpad16"); this.container.Controls.Add(errorLabel); } } private void AddSaveButton(HtmlGenericControl div) { using (HtmlInputButton button = new HtmlInputButton()) { button.ID = "SaveButton"; button.Value = Titles.Save; button.Attributes.Add("class", "ui small blue button"); div.Controls.Add(button); } } private void AddStatementReferenceTextArea(HtmlGenericControl fields) { using (HtmlGenericControl field = FormHelper.GetField()) { using (HtmlGenericControl label = new HtmlGenericControl()) { label.TagName = "label"; label.Attributes.Add("for", "StatementReferenceTextArea"); label.InnerText = Titles.StatementReference; field.Controls.Add(label); } using (HtmlTextArea statementReferenceTextArea = new HtmlTextArea()) { statementReferenceTextArea.ID = "StatementReferenceTextArea"; statementReferenceTextArea.Rows = 4; field.Controls.Add(statementReferenceTextArea); } fields.Controls.Add(field); } } private void AddSourceStoreSelect(HtmlGenericControl fields) { if (!this.DisplaySourceStore) { return; } using (HtmlGenericControl field = FormHelper.GetField()) { using (HtmlGenericControl label = new HtmlGenericControl()) { label.TagName = "label"; label.Attributes.Add("for", "SourceStoreSelect"); label.InnerText = Titles.DeliverFrom; field.Controls.Add(label); } using (HtmlSelect sourceStoreSelect = new HtmlSelect()) { sourceStoreSelect.ID = "SourceStoreSelect"; field.Controls.Add(sourceStoreSelect); } fields.Controls.Add(field); } } private void AddShippingCompanySelect(HtmlGenericControl fields) { if (!this.DisplayShipper) { return; } using (HtmlGenericControl field = FormHelper.GetField()) { using (HtmlGenericControl label = new HtmlGenericControl()) { label.TagName = "label"; label.Attributes.Add("for", "ShippingCompanySelect"); label.InnerText = Titles.ShippingCompany; field.Controls.Add(label); } using (HtmlSelect shippingCompanySelect = new HtmlSelect()) { shippingCompanySelect.ID = "ShippingCompanySelect"; field.Controls.Add(shippingCompanySelect); } fields.Controls.Add(field); } } private void CreateBottomPanel() { using (HtmlGenericControl fields = FormHelper.GetFields()) { fields.TagName = "div"; fields.Attributes.Add("class", "ui form"); fields.Attributes.Add("style", "width:290px;"); this.AddSourceStoreSelect(fields); this.AddShippingCompanySelect(fields); this.AddStatementReferenceTextArea(fields); this.AddSaveButton(fields); this.container.Controls.Add(fields); } } } }
mixerp6/mixerp
src/Libraries/Server Controls/Project/MixERP.Net.WebControls.StockAdjustmentFactory/FormView/BottomPanel.cs
C#
gpl-2.0
4,315
<?php /** * @file getlocations_box.tpl.php * @author Bob Hutchinson http://drupal.org/user/52366 * @copyright GNU GPL * * Template file for colorbox implementation * available variables: * $box_width $box_height contain the getlocations_search defaults set in the config */ ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>"> <!-- getlocations_box --> <head> <title><?php print $head_title; ?></title> <?php print $head; ?> <?php print $styles; ?> <?php print $scripts; ?> <style> /* adjust these to match your colorbox and map size */ body { width: 500px; margin: 0; } #page { min-width: 500px; width: 500px; margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; } #content-area { } </style> </head> <body class="<?php print $body_classes; ?>"> <div id="page"><div id="page-inner"> <div id="main"><div id="main-inner" class="clear-block"> <div id="content"><div id="content-inner"> <?php if ($title): ?> <h2 class="title"><?php print $title; ?></h2> <?php endif; ?> <div id="content-area"> <?php print $content; ?> </div> </div></div> </div></div> </div></div> <?php print $closure; ?> </body> </html>
paulcherrypipka/vcat
sites/all/modules/getlocations/modules/getlocations_search/getlocations_search_box.tpl.php
PHP
gpl-2.0
1,370
/* GStreamer base utils library missing plugins support * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:gstpbutilsmissingplugins * @short_description: Create, recognise and parse missing-plugins messages * * <refsect2> * <para> * Functions to create, recognise and parse missing-plugins messages for * applications and elements. * </para> * <para> * Missing-plugin messages are posted on the bus by elements like decodebin * or playbin if they can't find an appropriate source element or decoder * element. The application can use these messages for two things: * <itemizedlist> * <listitem><para> * concise error/problem reporting to the user mentioning what exactly * is missing, see gst_missing_plugin_message_get_description() * </para></listitem> * <listitem><para> * initiate installation of missing plugins, see * gst_missing_plugin_message_get_installer_detail() and * gst_install_plugins_async() * </para></listitem> * </itemizedlist> * </para> * <para> * Applications may also create missing-plugin messages themselves to install * required elements that are missing, using the install mechanism mentioned * above. * </para> * </refsect2> */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> /* getpid on UNIX */ #endif #ifdef HAVE_PROCESS_H # include <process.h> /* getpid on win32 */ #endif #include "gst/gst-i18n-plugin.h" #include "pbutils.h" #include "pbutils-private.h" #include <string.h> #define GST_DETAIL_STRING_MARKER "gstreamer" typedef enum { GST_MISSING_TYPE_UNKNOWN = 0, GST_MISSING_TYPE_URISOURCE, GST_MISSING_TYPE_URISINK, GST_MISSING_TYPE_ELEMENT, GST_MISSING_TYPE_DECODER, GST_MISSING_TYPE_ENCODER } GstMissingType; static const struct { GstMissingType type; const gchar type_string[12]; } missing_type_mapping[] = { { GST_MISSING_TYPE_URISOURCE, "urisource"}, { GST_MISSING_TYPE_URISINK, "urisink"}, { GST_MISSING_TYPE_ELEMENT, "element"}, { GST_MISSING_TYPE_DECODER, "decoder"}, { GST_MISSING_TYPE_ENCODER, "encoder"} }; static GstMissingType missing_structure_get_type (const GstStructure * s) { const gchar *type; guint i; type = gst_structure_get_string (s, "type"); g_return_val_if_fail (type != NULL, GST_MISSING_TYPE_UNKNOWN); for (i = 0; i < G_N_ELEMENTS (missing_type_mapping); ++i) { if (strcmp (missing_type_mapping[i].type_string, type) == 0) return missing_type_mapping[i].type; } return GST_MISSING_TYPE_UNKNOWN; } GstCaps * copy_and_clean_caps (const GstCaps * caps) { GstStructure *s; GstCaps *ret; ret = gst_caps_copy (caps); /* make caps easier to interpret, remove common fields that are likely * to be irrelevant for determining the right plugin (ie. mostly fields * where template caps usually have the standard MIN - MAX range as value) */ s = gst_caps_get_structure (ret, 0); gst_structure_remove_field (s, "codec_data"); gst_structure_remove_field (s, "palette_data"); gst_structure_remove_field (s, "pixel-aspect-ratio"); gst_structure_remove_field (s, "framerate"); gst_structure_remove_field (s, "leaf_size"); gst_structure_remove_field (s, "packet_size"); gst_structure_remove_field (s, "block_align"); gst_structure_remove_field (s, "metadata-interval"); /* icy caps */ /* decoders/encoders almost always handle the usual width/height/channel/rate * range (and if we don't remove this then the app will have a much harder * time blacklisting formats it has unsuccessfully tried to install before) */ gst_structure_remove_field (s, "width"); gst_structure_remove_field (s, "depth"); gst_structure_remove_field (s, "height"); gst_structure_remove_field (s, "channels"); gst_structure_remove_field (s, "rate"); /* rtp fields */ gst_structure_remove_field (s, "config"); gst_structure_remove_field (s, "clock-rate"); gst_structure_remove_field (s, "clock-base"); gst_structure_remove_field (s, "maxps"); gst_structure_remove_field (s, "seqnum-base"); gst_structure_remove_field (s, "npt-start"); gst_structure_remove_field (s, "npt-stop"); gst_structure_remove_field (s, "play-speed"); gst_structure_remove_field (s, "play-scale"); gst_structure_remove_field (s, "dynamic_range"); return ret; } /** * gst_missing_uri_source_message_new: * @element: the #GstElement posting the message * @protocol: the URI protocol the missing source needs to implement, * e.g. "http" or "mms" * * Creates a missing-plugin message for @element to notify the application * that a source element for a particular URI protocol is missing. This * function is mainly for use in plugins. * * Returns: (transfer full): a new #GstMessage, or NULL on error */ GstMessage * gst_missing_uri_source_message_new (GstElement * element, const gchar * protocol) { GstStructure *s; gchar *description; g_return_val_if_fail (element != NULL, NULL); g_return_val_if_fail (GST_IS_ELEMENT (element), NULL); g_return_val_if_fail (protocol != NULL, NULL); description = gst_pb_utils_get_source_description (protocol); s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING, "urisource", "detail", G_TYPE_STRING, protocol, "name", G_TYPE_STRING, description, NULL); g_free (description); return gst_message_new_element (GST_OBJECT_CAST (element), s); } /** * gst_missing_uri_sink_message_new: * @element: the #GstElement posting the message * @protocol: the URI protocol the missing sink needs to implement, * e.g. "http" or "smb" * * Creates a missing-plugin message for @element to notify the application * that a sink element for a particular URI protocol is missing. This * function is mainly for use in plugins. * * Returns: (transfer full): a new #GstMessage, or NULL on error */ GstMessage * gst_missing_uri_sink_message_new (GstElement * element, const gchar * protocol) { GstStructure *s; gchar *description; g_return_val_if_fail (element != NULL, NULL); g_return_val_if_fail (GST_IS_ELEMENT (element), NULL); g_return_val_if_fail (protocol != NULL, NULL); description = gst_pb_utils_get_sink_description (protocol); s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING, "urisink", "detail", G_TYPE_STRING, protocol, "name", G_TYPE_STRING, description, NULL); g_free (description); return gst_message_new_element (GST_OBJECT_CAST (element), s); } /** * gst_missing_element_message_new: * @element: the #GstElement posting the message * @factory_name: the name of the missing element (element factory), * e.g. "videoscale" or "cdparanoiasrc" * * Creates a missing-plugin message for @element to notify the application * that a certain required element is missing. This function is mainly for * use in plugins. * * Returns: (transfer full): a new #GstMessage, or NULL on error */ GstMessage * gst_missing_element_message_new (GstElement * element, const gchar * factory_name) { GstStructure *s; gchar *description; g_return_val_if_fail (element != NULL, NULL); g_return_val_if_fail (GST_IS_ELEMENT (element), NULL); g_return_val_if_fail (factory_name != NULL, NULL); description = gst_pb_utils_get_element_description (factory_name); s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING, "element", "detail", G_TYPE_STRING, factory_name, "name", G_TYPE_STRING, description, NULL); g_free (description); return gst_message_new_element (GST_OBJECT_CAST (element), s); } /** * gst_missing_decoder_message_new: * @element: the #GstElement posting the message * @decode_caps: the (fixed) caps for which a decoder element is needed * * Creates a missing-plugin message for @element to notify the application * that a decoder element for a particular set of (fixed) caps is missing. * This function is mainly for use in plugins. * * Returns: (transfer full): a new #GstMessage, or NULL on error */ GstMessage * gst_missing_decoder_message_new (GstElement * element, const GstCaps * decode_caps) { GstStructure *s; GstCaps *caps; gchar *description; g_return_val_if_fail (element != NULL, NULL); g_return_val_if_fail (GST_IS_ELEMENT (element), NULL); g_return_val_if_fail (decode_caps != NULL, NULL); g_return_val_if_fail (GST_IS_CAPS (decode_caps), NULL); g_return_val_if_fail (!gst_caps_is_any (decode_caps), NULL); g_return_val_if_fail (!gst_caps_is_empty (decode_caps), NULL); g_return_val_if_fail (gst_caps_is_fixed (decode_caps), NULL); description = gst_pb_utils_get_decoder_description (decode_caps); caps = copy_and_clean_caps (decode_caps); s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING, "decoder", "detail", GST_TYPE_CAPS, caps, "name", G_TYPE_STRING, description, NULL); gst_caps_unref (caps); g_free (description); return gst_message_new_element (GST_OBJECT_CAST (element), s); } /** * gst_missing_encoder_message_new: * @element: the #GstElement posting the message * @encode_caps: the (fixed) caps for which an encoder element is needed * * Creates a missing-plugin message for @element to notify the application * that an encoder element for a particular set of (fixed) caps is missing. * This function is mainly for use in plugins. * * Returns: (transfer full): a new #GstMessage, or NULL on error */ GstMessage * gst_missing_encoder_message_new (GstElement * element, const GstCaps * encode_caps) { GstStructure *s; GstCaps *caps; gchar *description; g_return_val_if_fail (element != NULL, NULL); g_return_val_if_fail (GST_IS_ELEMENT (element), NULL); g_return_val_if_fail (encode_caps != NULL, NULL); g_return_val_if_fail (GST_IS_CAPS (encode_caps), NULL); g_return_val_if_fail (!gst_caps_is_any (encode_caps), NULL); g_return_val_if_fail (!gst_caps_is_empty (encode_caps), NULL); g_return_val_if_fail (gst_caps_is_fixed (encode_caps), NULL); description = gst_pb_utils_get_encoder_description (encode_caps); caps = copy_and_clean_caps (encode_caps); s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING, "encoder", "detail", GST_TYPE_CAPS, caps, "name", G_TYPE_STRING, description, NULL); gst_caps_unref (caps); g_free (description); return gst_message_new_element (GST_OBJECT_CAST (element), s); } static gboolean missing_structure_get_string_detail (const GstStructure * s, gchar ** p_detail) { const gchar *detail; GType detail_type; *p_detail = NULL; detail_type = gst_structure_get_field_type (s, "detail"); if (!g_type_is_a (detail_type, G_TYPE_STRING)) { GST_WARNING ("expected 'detail' field to be of G_TYPE_STRING"); return FALSE; } detail = gst_structure_get_string (s, "detail"); if (detail == NULL || *detail == '\0') { GST_WARNING ("empty 'detail' field"); return FALSE; } *p_detail = g_strdup (detail); return TRUE; } static gboolean missing_structure_get_caps_detail (const GstStructure * s, GstCaps ** p_caps) { const GstCaps *caps; const GValue *val; GType detail_type; *p_caps = NULL; detail_type = gst_structure_get_field_type (s, "detail"); if (!g_type_is_a (detail_type, GST_TYPE_CAPS)) { GST_WARNING ("expected 'detail' field to be of GST_TYPE_CAPS"); return FALSE; } val = gst_structure_get_value (s, "detail"); caps = gst_value_get_caps (val); if (gst_caps_is_empty (caps) || gst_caps_is_any (caps)) { GST_WARNING ("EMPTY or ANY caps not allowed"); return FALSE; } *p_caps = gst_caps_copy (caps); return TRUE; } /** * gst_missing_plugin_message_get_installer_detail: * @msg: a missing-plugin #GstMessage of type #GST_MESSAGE_ELEMENT * * Returns an opaque string containing all the details about the missing * element to be passed to an external installer called via * gst_install_plugins_async() or gst_install_plugins_sync(). * * This function is mainly for applications that call external plugin * installation mechanisms using one of the two above-mentioned functions. * * Returns: a newly-allocated detail string, or NULL on error. Free string * with g_free() when not needed any longer. */ gchar * gst_missing_plugin_message_get_installer_detail (GstMessage * msg) { GstMissingType missing_type; const gchar *progname; const gchar *type; GString *str = NULL; gchar *detail = NULL; gchar *desc; g_return_val_if_fail (gst_is_missing_plugin_message (msg), NULL); GST_LOG ("Parsing missing-plugin message: %" GST_PTR_FORMAT, msg->structure); missing_type = missing_structure_get_type (msg->structure); if (missing_type == GST_MISSING_TYPE_UNKNOWN) { GST_WARNING ("couldn't parse 'type' field"); goto error; } type = gst_structure_get_string (msg->structure, "type"); g_assert (type != NULL); /* validity already checked above */ /* FIXME: use gst_installer_detail_new() here too */ str = g_string_new (GST_DETAIL_STRING_MARKER "|"); g_string_append_printf (str, "%u.%u|", GST_VERSION_MAJOR, GST_VERSION_MINOR); progname = (const gchar *) g_get_prgname (); if (progname) { g_string_append_printf (str, "%s|", progname); } else { g_string_append_printf (str, "pid/%lu|", (gulong) getpid ()); } desc = gst_missing_plugin_message_get_description (msg); if (desc) { g_strdelimit (desc, "|", '#'); g_string_append_printf (str, "%s|", desc); g_free (desc); } else { g_string_append (str, "|"); } switch (missing_type) { case GST_MISSING_TYPE_URISOURCE: case GST_MISSING_TYPE_URISINK: case GST_MISSING_TYPE_ELEMENT: if (!missing_structure_get_string_detail (msg->structure, &detail)) goto error; break; case GST_MISSING_TYPE_DECODER: case GST_MISSING_TYPE_ENCODER:{ GstCaps *caps = NULL; if (!missing_structure_get_caps_detail (msg->structure, &caps)) goto error; detail = gst_caps_to_string (caps); gst_caps_unref (caps); break; } default: g_return_val_if_reached (NULL); } g_string_append_printf (str, "%s-%s", type, detail); g_free (detail); return g_string_free (str, FALSE); /* ERRORS */ error: { GST_WARNING ("Failed to parse missing-plugin msg: %" GST_PTR_FORMAT, msg); if (str) g_string_free (str, TRUE); return NULL; } } /** * gst_missing_plugin_message_get_description: * @msg: a missing-plugin #GstMessage of type #GST_MESSAGE_ELEMENT * * Returns a localised string describing the missing feature, for use in * error dialogs and the like. Should never return NULL unless @msg is not * a valid missing-plugin message. * * This function is mainly for applications that need a human-readable string * describing a missing plugin, given a previously collected missing-plugin * message * * Returns: a newly-allocated description string, or NULL on error. Free * string with g_free() when not needed any longer. */ gchar * gst_missing_plugin_message_get_description (GstMessage * msg) { GstMissingType missing_type; const gchar *desc; gchar *ret = NULL; g_return_val_if_fail (gst_is_missing_plugin_message (msg), NULL); GST_LOG ("Parsing missing-plugin message: %" GST_PTR_FORMAT, msg->structure); desc = gst_structure_get_string (msg->structure, "name"); if (desc != NULL && *desc != '\0') { ret = g_strdup (desc); goto done; } /* fallback #1 */ missing_type = missing_structure_get_type (msg->structure); switch (missing_type) { case GST_MISSING_TYPE_URISOURCE: case GST_MISSING_TYPE_URISINK: case GST_MISSING_TYPE_ELEMENT:{ gchar *detail = NULL; if (missing_structure_get_string_detail (msg->structure, &detail)) { if (missing_type == GST_MISSING_TYPE_URISOURCE) ret = gst_pb_utils_get_source_description (detail); else if (missing_type == GST_MISSING_TYPE_URISINK) ret = gst_pb_utils_get_sink_description (detail); else ret = gst_pb_utils_get_sink_description (detail); g_free (detail); } break; } case GST_MISSING_TYPE_DECODER: case GST_MISSING_TYPE_ENCODER:{ GstCaps *caps = NULL; if (missing_structure_get_caps_detail (msg->structure, &caps)) { if (missing_type == GST_MISSING_TYPE_DECODER) ret = gst_pb_utils_get_decoder_description (caps); else ret = gst_pb_utils_get_encoder_description (caps); gst_caps_unref (caps); } break; } default: break; } if (ret) goto done; /* fallback #2 */ switch (missing_type) { case GST_MISSING_TYPE_URISOURCE: desc = _("Unknown source element"); break; case GST_MISSING_TYPE_URISINK: desc = _("Unknown sink element"); break; case GST_MISSING_TYPE_ELEMENT: desc = _("Unknown element"); break; case GST_MISSING_TYPE_DECODER: desc = _("Unknown decoder element"); break; case GST_MISSING_TYPE_ENCODER: desc = _("Unknown encoder element"); break; default: /* we should really never get here, but we better still return * something if we do */ desc = _("Plugin or element of unknown type"); break; } ret = g_strdup (desc); done: GST_LOG ("returning '%s'", ret); return ret; } /** * gst_is_missing_plugin_message: * @msg: a #GstMessage * * Checks whether @msg is a missing plugins message. * * Returns: %TRUE if @msg is a missing-plugins message, otherwise %FALSE. */ gboolean gst_is_missing_plugin_message (GstMessage * msg) { g_return_val_if_fail (msg != NULL, FALSE); g_return_val_if_fail (GST_IS_MESSAGE (msg), FALSE); if (GST_MESSAGE_TYPE (msg) != GST_MESSAGE_ELEMENT || msg->structure == NULL) return FALSE; return gst_structure_has_name (msg->structure, "missing-plugin"); } /* takes ownership of the description */ static gchar * gst_installer_detail_new (gchar * description, const gchar * type, const gchar * detail) { const gchar *progname; GString *s; s = g_string_new (GST_DETAIL_STRING_MARKER "|"); g_string_append_printf (s, "%u.%u|", GST_VERSION_MAJOR, GST_VERSION_MINOR); progname = (const gchar *) g_get_prgname (); if (progname) { g_string_append_printf (s, "%s|", progname); } else { g_string_append_printf (s, "pid/%lu|", (gulong) getpid ()); } if (description) { g_strdelimit (description, "|", '#'); g_string_append_printf (s, "%s|", description); g_free (description); } else { g_string_append (s, "|"); } g_string_append_printf (s, "%s-%s", type, detail); return g_string_free (s, FALSE); } /** * gst_missing_uri_source_installer_detail_new: * @protocol: the URI protocol the missing source needs to implement, * e.g. "http" or "mms" * * Returns an opaque string containing all the details about the missing * element to be passed to an external installer called via * gst_install_plugins_async() or gst_install_plugins_sync(). * * This function is mainly for applications that call external plugin * installation mechanisms using one of the two above-mentioned functions in * the case where the application knows exactly what kind of plugin it is * missing. * * Returns: a newly-allocated detail string, or NULL on error. Free string * with g_free() when not needed any longer. * * Since: 0.10.15 */ gchar * gst_missing_uri_source_installer_detail_new (const gchar * protocol) { gchar *desc; g_return_val_if_fail (protocol != NULL, NULL); desc = gst_pb_utils_get_source_description (protocol); return gst_installer_detail_new (desc, "urisource", protocol); } /** * gst_missing_uri_sink_installer_detail_new: * @protocol: the URI protocol the missing source needs to implement, * e.g. "http" or "mms" * * Returns an opaque string containing all the details about the missing * element to be passed to an external installer called via * gst_install_plugins_async() or gst_install_plugins_sync(). * * This function is mainly for applications that call external plugin * installation mechanisms using one of the two above-mentioned functions in * the case where the application knows exactly what kind of plugin it is * missing. * * Returns: a newly-allocated detail string, or NULL on error. Free string * with g_free() when not needed any longer. * * Since: 0.10.15 */ gchar * gst_missing_uri_sink_installer_detail_new (const gchar * protocol) { gchar *desc; g_return_val_if_fail (protocol != NULL, NULL); desc = gst_pb_utils_get_sink_description (protocol); return gst_installer_detail_new (desc, "urisink", protocol); } /** * gst_missing_element_installer_detail_new: * @factory_name: the name of the missing element (element factory), * e.g. "videoscale" or "cdparanoiasrc" * * Returns an opaque string containing all the details about the missing * element to be passed to an external installer called via * gst_install_plugins_async() or gst_install_plugins_sync(). * * This function is mainly for applications that call external plugin * installation mechanisms using one of the two above-mentioned functions in * the case where the application knows exactly what kind of plugin it is * missing. * * Returns: a newly-allocated detail string, or NULL on error. Free string * with g_free() when not needed any longer. * * Since: 0.10.15 */ gchar * gst_missing_element_installer_detail_new (const gchar * factory_name) { gchar *desc; g_return_val_if_fail (factory_name != NULL, NULL); desc = gst_pb_utils_get_element_description (factory_name); return gst_installer_detail_new (desc, "element", factory_name); } /** * gst_missing_decoder_installer_detail_new: * @decode_caps: the (fixed) caps for which a decoder element is needed * * Returns an opaque string containing all the details about the missing * element to be passed to an external installer called via * gst_install_plugins_async() or gst_install_plugins_sync(). * * This function is mainly for applications that call external plugin * installation mechanisms using one of the two above-mentioned functions in * the case where the application knows exactly what kind of plugin it is * missing. * * Returns: a newly-allocated detail string, or NULL on error. Free string * with g_free() when not needed any longer. * * Since: 0.10.15 */ gchar * gst_missing_decoder_installer_detail_new (const GstCaps * decode_caps) { GstCaps *caps; gchar *detail_str, *caps_str, *desc; g_return_val_if_fail (decode_caps != NULL, NULL); g_return_val_if_fail (GST_IS_CAPS (decode_caps), NULL); g_return_val_if_fail (!gst_caps_is_any (decode_caps), NULL); g_return_val_if_fail (!gst_caps_is_empty (decode_caps), NULL); g_return_val_if_fail (gst_caps_is_fixed (decode_caps), NULL); desc = gst_pb_utils_get_decoder_description (decode_caps); caps = copy_and_clean_caps (decode_caps); caps_str = gst_caps_to_string (caps); detail_str = gst_installer_detail_new (desc, "decoder", caps_str); g_free (caps_str); gst_caps_unref (caps); return detail_str; } /** * gst_missing_encoder_installer_detail_new: * @encode_caps: the (fixed) caps for which an encoder element is needed * * Returns an opaque string containing all the details about the missing * element to be passed to an external installer called via * gst_install_plugins_async() or gst_install_plugins_sync(). * * This function is mainly for applications that call external plugin * installation mechanisms using one of the two above-mentioned functions in * the case where the application knows exactly what kind of plugin it is * missing. * * Returns: a newly-allocated detail string, or NULL on error. Free string * with g_free() when not needed any longer. * * Since: 0.10.15 */ gchar * gst_missing_encoder_installer_detail_new (const GstCaps * encode_caps) { GstCaps *caps; gchar *detail_str, *caps_str, *desc; g_return_val_if_fail (encode_caps != NULL, NULL); g_return_val_if_fail (GST_IS_CAPS (encode_caps), NULL); g_return_val_if_fail (!gst_caps_is_any (encode_caps), NULL); g_return_val_if_fail (!gst_caps_is_empty (encode_caps), NULL); g_return_val_if_fail (gst_caps_is_fixed (encode_caps), NULL); desc = gst_pb_utils_get_encoder_description (encode_caps); caps = copy_and_clean_caps (encode_caps); caps_str = gst_caps_to_string (caps); detail_str = gst_installer_detail_new (desc, "encoder", caps_str); g_free (caps_str); gst_caps_unref (caps); return detail_str; }
166MMX/openjdk.java.net-openjfx-8u40-rt
modules/media/src/main/native/gstreamer/gstreamer-lite/gst-plugins-base/gst-libs/gst/pbutils/missing-plugins.c
C
gpl-2.0
25,421
/******************************************************************************/ /* Copyright (c) Crackerjack Project., 2007 */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See */ /* the GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software Foundation, */ /* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* */ /* History: Porting from Crackerjack to LTP is done by */ /* Manas Kumar Nayak maknayak@in.ibm.com> */ /******************************************************************************/ /******************************************************************************/ /* Description: This tests the rt_sigaction() syscall */ /* rt_sigaction Expected EFAULT error check */ /******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <sys/syscall.h> #include <string.h> #include "test.h" #include "linux_syscall_numbers.h" #include "lapi/rt_sigaction.h" char *TCID = "rt_sigaction02"; static int testno; int TST_TOTAL = 1; void cleanup(void) { tst_rmdir(); tst_exit(); } void setup(void) { TEST_PAUSE; tst_tmpdir(); } static int test_flags[] = { SA_RESETHAND | SA_SIGINFO, SA_RESETHAND, SA_RESETHAND | SA_SIGINFO, SA_RESETHAND | SA_SIGINFO, SA_NOMASK }; char *test_flags_list[] = { "SA_RESETHAND|SA_SIGINFO", "SA_RESETHAND", "SA_RESETHAND|SA_SIGINFO", "SA_RESETHAND|SA_SIGINFO", "SA_NOMASK" }; static struct test_case_t { int exp_errno; char *errdesc; } test_cases[] = { { EFAULT, "EFAULT"} }; int main(int ac, char **av) { unsigned int flag; int signal; int lc; tst_parse_opts(ac, av, NULL, NULL); setup(); for (lc = 0; TEST_LOOPING(lc); ++lc) { tst_count = 0; for (testno = 0; testno < TST_TOTAL; ++testno) { for (signal = SIGRTMIN; signal <= SIGRTMAX; signal++) { tst_resm(TINFO, "Signal %d", signal); for (flag = 0; flag < ARRAY_SIZE(test_flags); flag++) { /* * * long sys_rt_sigaction (int sig, const struct sigaction *act, * * truct sigaction *oact, size_t sigsetsize); * * EFAULT: * * An invalid act or oact value was specified * */ TEST(ltp_rt_sigaction(signal, INVAL_SA_PTR, NULL, SIGSETSIZE)); if ((TEST_RETURN == -1) && (TEST_ERRNO == test_cases[0].exp_errno)) { tst_resm(TINFO, "sa.sa_flags = %s ", test_flags_list[flag]); tst_resm(TPASS, "%s failure with sig: %d as expected errno = %s : %s", TCID, signal, test_cases[0].errdesc, strerror(TEST_ERRNO)); } else { tst_resm(TFAIL, "rt_sigaction call succeeded: result = %ld got error %d:but expected %d", TEST_RETURN, TEST_ERRNO, test_cases[0]. exp_errno); tst_resm(TINFO, "sa.sa_flags = %s ", test_flags_list[flag]); } } } } } cleanup(); tst_exit(); }
itnihao/ltp
testcases/kernel/syscalls/rt_sigaction/rt_sigaction02.c
C
gpl-2.0
4,240
/* * zsmalloc memory allocator * * Copyright (C) 2011 Nitin Gupta * Copyright (C) 2012, 2013 Minchan Kim * * This code is released using a dual license strategy: BSD/GPL * You can choose the license that better fits your requirements. * * Released under the terms of 3-clause BSD License * Released under the terms of GNU General Public License Version 2.0 */ /* * Following is how we use various fields and flags of underlying * struct page(s) to form a zspage. * * Usage of struct page fields: * page->first_page: points to the first component (0-order) page * page->index (union with page->freelist): offset of the first object * starting in this page. For the first page, this is * always 0, so we use this field (aka freelist) to point * to the first free object in zspage. * page->lru: links together all component pages (except the first page) * of a zspage * * For _first_ page only: * * page->private (union with page->first_page): refers to the * component page after the first page * If the page is first_page for huge object, it stores handle. * Look at size_class->huge. * page->freelist: points to the first free object in zspage. * Free objects are linked together using in-place * metadata. * page->objects: maximum number of objects we can store in this * zspage (class->zspage_order * PAGE_SIZE / class->size) * page->lru: links together first pages of various zspages. * Basically forming list of zspages in a fullness group. * page->mapping: class index and fullness group of the zspage * * Usage of struct page flags: * PG_private: identifies the first component page * PG_private2: identifies the last component page * */ #ifdef CONFIG_ZSMALLOC_DEBUG #define DEBUG #endif #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/bitops.h> #include <linux/errno.h> #include <linux/highmem.h> #include <linux/string.h> #include <linux/slab.h> #include <asm/tlbflush.h> #include <asm/pgtable.h> #include <linux/cpumask.h> #include <linux/cpu.h> #include <linux/vmalloc.h> #include <linux/hardirq.h> #include <linux/spinlock.h> #include <linux/types.h> #include <linux/debugfs.h> #include <linux/zsmalloc.h> #include <linux/zpool.h> /* * This must be power of 2 and greater than of equal to sizeof(link_free). * These two conditions ensure that any 'struct link_free' itself doesn't * span more than 1 page which avoids complex case of mapping 2 pages simply * to restore link_free pointer values. */ #define ZS_ALIGN 8 /* * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single) * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N. */ #define ZS_MAX_ZSPAGE_ORDER 2 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER) #define ZS_HANDLE_SIZE (sizeof(unsigned long)) /* * Object location (<PFN>, <obj_idx>) is encoded as * as single (unsigned long) handle value. * * Note that object index <obj_idx> is relative to system * page <PFN> it is stored in, so for each sub-page belonging * to a zspage, obj_idx starts with 0. * * This is made more complicated by various memory models and PAE. */ #ifndef MAX_PHYSMEM_BITS #ifdef CONFIG_HIGHMEM64G #define MAX_PHYSMEM_BITS 36 #else /* !CONFIG_HIGHMEM64G */ /* * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just * be PAGE_SHIFT */ #define MAX_PHYSMEM_BITS BITS_PER_LONG #endif #endif #define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT) /* * Memory for allocating for handle keeps object position by * encoding <page, obj_idx> and the encoded value has a room * in least bit(ie, look at obj_to_location). * We use the bit to synchronize between object access by * user and migration. */ #define HANDLE_PIN_BIT 0 /* * Head in allocated object should have OBJ_ALLOCATED_TAG * to identify the object was allocated or not. * It's okay to add the status bit in the least bit because * header keeps handle which is 4byte-aligned address so we * have room for two bit at least. */ #define OBJ_ALLOCATED_TAG 1 #define OBJ_TAG_BITS 1 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS) #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1) #define MAX(a, b) ((a) >= (b) ? (a) : (b)) /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */ #define ZS_MIN_ALLOC_SIZE \ MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS)) /* each chunk includes extra space to keep handle */ #define ZS_MAX_ALLOC_SIZE PAGE_SIZE /* * On systems with 4K page size, this gives 255 size classes! There is a * trader-off here: * - Large number of size classes is potentially wasteful as free page are * spread across these classes * - Small number of size classes causes large internal fragmentation * - Probably its better to use specific size classes (empirically * determined). NOTE: all those class sizes must be set as multiple of * ZS_ALIGN to make sure link_free itself never has to span 2 pages. * * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN * (reason above) */ #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> 8) /* * We do not maintain any list for completely empty or full pages */ enum fullness_group { ZS_ALMOST_FULL, ZS_ALMOST_EMPTY, _ZS_NR_FULLNESS_GROUPS, ZS_EMPTY, ZS_FULL }; enum zs_stat_type { OBJ_ALLOCATED, OBJ_USED, CLASS_ALMOST_FULL, CLASS_ALMOST_EMPTY, NR_ZS_STAT_TYPE, }; #ifdef CONFIG_ZSMALLOC_STAT static struct dentry *zs_stat_root; struct zs_size_stat { unsigned long objs[NR_ZS_STAT_TYPE]; }; #endif /* * number of size_classes */ static int zs_size_classes; /* * We assign a page to ZS_ALMOST_EMPTY fullness group when: * n <= N / f, where * n = number of allocated objects * N = total number of objects zspage can store * f = fullness_threshold_frac * * Similarly, we assign zspage to: * ZS_ALMOST_FULL when n > N / f * ZS_EMPTY when n == 0 * ZS_FULL when n == N * * (see: fix_fullness_group()) */ static const int fullness_threshold_frac = 4; struct size_class { /* * Size of objects stored in this class. Must be multiple * of ZS_ALIGN. */ int size; unsigned int index; /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */ int pages_per_zspage; /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */ bool huge; #ifdef CONFIG_ZSMALLOC_STAT struct zs_size_stat stats; #endif spinlock_t lock; struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS]; }; /* * Placed within free objects to form a singly linked list. * For every zspage, first_page->freelist gives head of this list. * * This must be power of 2 and less than or equal to ZS_ALIGN */ struct link_free { union { /* * Position of next free chunk (encodes <PFN, obj_idx>) * It's valid for non-allocated object */ void *next; /* * Handle of allocated object. */ unsigned long handle; }; }; struct zs_pool { char *name; struct size_class **size_class; struct kmem_cache *handle_cachep; gfp_t flags; /* allocation flags used when growing pool */ atomic_long_t pages_allocated; #ifdef CONFIG_ZSMALLOC_STAT struct dentry *stat_dentry; #endif }; /* * A zspage's class index and fullness group * are encoded in its (first)page->mapping */ #define CLASS_IDX_BITS 28 #define FULLNESS_BITS 4 #define CLASS_IDX_MASK ((1 << CLASS_IDX_BITS) - 1) #define FULLNESS_MASK ((1 << FULLNESS_BITS) - 1) struct mapping_area { #ifdef CONFIG_PGTABLE_MAPPING struct vm_struct *vm; /* vm area for mapping object that span pages */ #else char *vm_buf; /* copy buffer for objects that span pages */ #endif char *vm_addr; /* address of kmap_atomic()'ed pages */ enum zs_mapmode vm_mm; /* mapping mode */ bool huge; }; static int create_handle_cache(struct zs_pool *pool) { pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE, 0, 0, NULL); return pool->handle_cachep ? 0 : 1; } static void destroy_handle_cache(struct zs_pool *pool) { if (pool->handle_cachep) kmem_cache_destroy(pool->handle_cachep); } static unsigned long alloc_handle(struct zs_pool *pool) { return (unsigned long)kmem_cache_alloc(pool->handle_cachep, pool->flags & ~__GFP_HIGHMEM); } static void free_handle(struct zs_pool *pool, unsigned long handle) { kmem_cache_free(pool->handle_cachep, (void *)handle); } static void record_obj(unsigned long handle, unsigned long obj) { /* * lsb of @obj represents handle lock while other bits * represent object value the handle is pointing so * updating shouldn't do store tearing. */ WRITE_ONCE(*(unsigned long *)handle, obj); } /* zpool driver */ #ifdef CONFIG_ZPOOL static void *zs_zpool_create(char *name, gfp_t gfp, struct zpool_ops *zpool_ops) { return zs_create_pool(name, gfp); } static void zs_zpool_destroy(void *pool) { zs_destroy_pool(pool); } static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp, unsigned long *handle) { *handle = zs_malloc(pool, size); return *handle ? 0 : -1; } static void zs_zpool_free(void *pool, unsigned long handle) { zs_free(pool, handle); } static int zs_zpool_shrink(void *pool, unsigned int pages, unsigned int *reclaimed) { return -EINVAL; } static void *zs_zpool_map(void *pool, unsigned long handle, enum zpool_mapmode mm) { enum zs_mapmode zs_mm; switch (mm) { case ZPOOL_MM_RO: zs_mm = ZS_MM_RO; break; case ZPOOL_MM_WO: zs_mm = ZS_MM_WO; break; case ZPOOL_MM_RW: /* fallthru */ default: zs_mm = ZS_MM_RW; break; } return zs_map_object(pool, handle, zs_mm); } static void zs_zpool_unmap(void *pool, unsigned long handle) { zs_unmap_object(pool, handle); } static u64 zs_zpool_total_size(void *pool) { return zs_get_total_pages(pool) << PAGE_SHIFT; } static struct zpool_driver zs_zpool_driver = { .type = "zsmalloc", .owner = THIS_MODULE, .create = zs_zpool_create, .destroy = zs_zpool_destroy, .malloc = zs_zpool_malloc, .free = zs_zpool_free, .shrink = zs_zpool_shrink, .map = zs_zpool_map, .unmap = zs_zpool_unmap, .total_size = zs_zpool_total_size, }; MODULE_ALIAS("zpool-zsmalloc"); #endif /* CONFIG_ZPOOL */ static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage) { return pages_per_zspage * PAGE_SIZE / size; } /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */ static DEFINE_PER_CPU(struct mapping_area, zs_map_area); static int is_first_page(struct page *page) { return PagePrivate(page); } static int is_last_page(struct page *page) { return PagePrivate2(page); } static void get_zspage_mapping(struct page *page, unsigned int *class_idx, enum fullness_group *fullness) { unsigned long m; BUG_ON(!is_first_page(page)); m = (unsigned long)page->mapping; *fullness = m & FULLNESS_MASK; *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK; } static void set_zspage_mapping(struct page *page, unsigned int class_idx, enum fullness_group fullness) { unsigned long m; BUG_ON(!is_first_page(page)); m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) | (fullness & FULLNESS_MASK); page->mapping = (struct address_space *)m; } /* * zsmalloc divides the pool into various size classes where each * class maintains a list of zspages where each zspage is divided * into equal sized chunks. Each allocation falls into one of these * classes depending on its size. This function returns index of the * size class which has chunk size big enough to hold the give size. */ static int get_size_class_index(int size) { int idx = 0; if (likely(size > ZS_MIN_ALLOC_SIZE)) idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE, ZS_SIZE_CLASS_DELTA); return min(zs_size_classes - 1, idx); } #ifdef CONFIG_ZSMALLOC_STAT static inline void zs_stat_inc(struct size_class *class, enum zs_stat_type type, unsigned long cnt) { class->stats.objs[type] += cnt; } static inline void zs_stat_dec(struct size_class *class, enum zs_stat_type type, unsigned long cnt) { class->stats.objs[type] -= cnt; } static inline unsigned long zs_stat_get(struct size_class *class, enum zs_stat_type type) { return class->stats.objs[type]; } static int __init zs_stat_init(void) { if (!debugfs_initialized()) return -ENODEV; zs_stat_root = debugfs_create_dir("zsmalloc", NULL); if (!zs_stat_root) return -ENOMEM; return 0; } static void __exit zs_stat_exit(void) { debugfs_remove_recursive(zs_stat_root); } static int zs_stats_size_show(struct seq_file *s, void *v) { int i; struct zs_pool *pool = s->private; struct size_class *class; int objs_per_zspage; unsigned long class_almost_full, class_almost_empty; unsigned long obj_allocated, obj_used, pages_used; unsigned long total_class_almost_full = 0, total_class_almost_empty = 0; unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0; seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s\n", "class", "size", "almost_full", "almost_empty", "obj_allocated", "obj_used", "pages_used", "pages_per_zspage"); for (i = 0; i < zs_size_classes; i++) { class = pool->size_class[i]; if (class->index != i) continue; spin_lock(&class->lock); class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL); class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY); obj_allocated = zs_stat_get(class, OBJ_ALLOCATED); obj_used = zs_stat_get(class, OBJ_USED); spin_unlock(&class->lock); objs_per_zspage = get_maxobj_per_zspage(class->size, class->pages_per_zspage); pages_used = obj_allocated / objs_per_zspage * class->pages_per_zspage; seq_printf(s, " %5u %5u %11lu %12lu %13lu %10lu %10lu %16d\n", i, class->size, class_almost_full, class_almost_empty, obj_allocated, obj_used, pages_used, class->pages_per_zspage); total_class_almost_full += class_almost_full; total_class_almost_empty += class_almost_empty; total_objs += obj_allocated; total_used_objs += obj_used; total_pages += pages_used; } seq_puts(s, "\n"); seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu\n", "Total", "", total_class_almost_full, total_class_almost_empty, total_objs, total_used_objs, total_pages); return 0; } static int zs_stats_size_open(struct inode *inode, struct file *file) { return single_open(file, zs_stats_size_show, inode->i_private); } static const struct file_operations zs_stat_size_ops = { .open = zs_stats_size_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int zs_pool_stat_create(char *name, struct zs_pool *pool) { struct dentry *entry; if (!zs_stat_root) return -ENODEV; entry = debugfs_create_dir(name, zs_stat_root); if (!entry) { pr_warn("debugfs dir <%s> creation failed\n", name); return -ENOMEM; } pool->stat_dentry = entry; entry = debugfs_create_file("classes", S_IFREG | S_IRUGO, pool->stat_dentry, pool, &zs_stat_size_ops); if (!entry) { pr_warn("%s: debugfs file entry <%s> creation failed\n", name, "classes"); return -ENOMEM; } return 0; } static void zs_pool_stat_destroy(struct zs_pool *pool) { debugfs_remove_recursive(pool->stat_dentry); } #else /* CONFIG_ZSMALLOC_STAT */ static inline void zs_stat_inc(struct size_class *class, enum zs_stat_type type, unsigned long cnt) { } static inline void zs_stat_dec(struct size_class *class, enum zs_stat_type type, unsigned long cnt) { } static inline unsigned long zs_stat_get(struct size_class *class, enum zs_stat_type type) { return 0; } static int __init zs_stat_init(void) { return 0; } static void __exit zs_stat_exit(void) { } static inline int zs_pool_stat_create(char *name, struct zs_pool *pool) { return 0; } static inline void zs_pool_stat_destroy(struct zs_pool *pool) { } #endif /* * For each size class, zspages are divided into different groups * depending on how "full" they are. This was done so that we could * easily find empty or nearly empty zspages when we try to shrink * the pool (not yet implemented). This function returns fullness * status of the given page. */ static enum fullness_group get_fullness_group(struct page *page) { int inuse, max_objects; enum fullness_group fg; BUG_ON(!is_first_page(page)); inuse = page->inuse; max_objects = page->objects; if (inuse == 0) fg = ZS_EMPTY; else if (inuse == max_objects) fg = ZS_FULL; else if (inuse <= 3 * max_objects / fullness_threshold_frac) fg = ZS_ALMOST_EMPTY; else fg = ZS_ALMOST_FULL; return fg; } /* * Each size class maintains various freelists and zspages are assigned * to one of these freelists based on the number of live objects they * have. This functions inserts the given zspage into the freelist * identified by <class, fullness_group>. */ static void insert_zspage(struct page *page, struct size_class *class, enum fullness_group fullness) { struct page **head; BUG_ON(!is_first_page(page)); if (fullness >= _ZS_NR_FULLNESS_GROUPS) return; head = &class->fullness_list[fullness]; if (*head) list_add_tail(&page->lru, &(*head)->lru); *head = page; zs_stat_inc(class, fullness == ZS_ALMOST_EMPTY ? CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1); } /* * This function removes the given zspage from the freelist identified * by <class, fullness_group>. */ static void remove_zspage(struct page *page, struct size_class *class, enum fullness_group fullness) { struct page **head; BUG_ON(!is_first_page(page)); if (fullness >= _ZS_NR_FULLNESS_GROUPS) return; head = &class->fullness_list[fullness]; BUG_ON(!*head); if (list_empty(&(*head)->lru)) *head = NULL; else if (*head == page) *head = (struct page *)list_entry((*head)->lru.next, struct page, lru); list_del_init(&page->lru); zs_stat_dec(class, fullness == ZS_ALMOST_EMPTY ? CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1); } /* * Each size class maintains zspages in different fullness groups depending * on the number of live objects they contain. When allocating or freeing * objects, the fullness status of the page can change, say, from ALMOST_FULL * to ALMOST_EMPTY when freeing an object. This function checks if such * a status change has occurred for the given page and accordingly moves the * page from the freelist of the old fullness group to that of the new * fullness group. */ static enum fullness_group fix_fullness_group(struct size_class *class, struct page *page) { int class_idx; enum fullness_group currfg, newfg; BUG_ON(!is_first_page(page)); get_zspage_mapping(page, &class_idx, &currfg); newfg = get_fullness_group(page); if (newfg == currfg) goto out; remove_zspage(page, class, currfg); insert_zspage(page, class, newfg); set_zspage_mapping(page, class_idx, newfg); out: return newfg; } /* * We have to decide on how many pages to link together * to form a zspage for each size class. This is important * to reduce wastage due to unusable space left at end of * each zspage which is given as: * wastage = Zp % class_size * usage = Zp - wastage * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ... * * For example, for size class of 3/8 * PAGE_SIZE, we should * link together 3 PAGE_SIZE sized pages to form a zspage * since then we can perfectly fit in 8 such objects. */ static int get_pages_per_zspage(int class_size) { int i, max_usedpc = 0; /* zspage order which gives maximum used size per KB */ int max_usedpc_order = 1; for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) { int zspage_size; int waste, usedpc; zspage_size = i * PAGE_SIZE; waste = zspage_size % class_size; usedpc = (zspage_size - waste) * 100 / zspage_size; if (usedpc > max_usedpc) { max_usedpc = usedpc; max_usedpc_order = i; } } return max_usedpc_order; } /* * A single 'zspage' is composed of many system pages which are * linked together using fields in struct page. This function finds * the first/head page, given any component page of a zspage. */ static struct page *get_first_page(struct page *page) { if (is_first_page(page)) return page; else return page->first_page; } static struct page *get_next_page(struct page *page) { struct page *next; if (is_last_page(page)) next = NULL; else if (is_first_page(page)) next = (struct page *)page_private(page); else next = list_entry(page->lru.next, struct page, lru); return next; } /* * Encode <page, obj_idx> as a single handle value. * We use the least bit of handle for tagging. */ static void *location_to_obj(struct page *page, unsigned long obj_idx) { unsigned long obj; if (!page) { BUG_ON(obj_idx); return NULL; } obj = page_to_pfn(page) << OBJ_INDEX_BITS; obj |= ((obj_idx) & OBJ_INDEX_MASK); obj <<= OBJ_TAG_BITS; return (void *)obj; } /* * Decode <page, obj_idx> pair from the given object handle. We adjust the * decoded obj_idx back to its original value since it was adjusted in * location_to_obj(). */ static void obj_to_location(unsigned long obj, struct page **page, unsigned long *obj_idx) { obj >>= OBJ_TAG_BITS; *page = pfn_to_page(obj >> OBJ_INDEX_BITS); *obj_idx = (obj & OBJ_INDEX_MASK); } static unsigned long handle_to_obj(unsigned long handle) { return *(unsigned long *)handle; } static unsigned long obj_to_head(struct size_class *class, struct page *page, void *obj) { if (class->huge) { VM_BUG_ON(!is_first_page(page)); return *(unsigned long *)page_private(page); } else return *(unsigned long *)obj; } static unsigned long obj_idx_to_offset(struct page *page, unsigned long obj_idx, int class_size) { unsigned long off = 0; if (!is_first_page(page)) off = page->index; return off + obj_idx * class_size; } static inline int trypin_tag(unsigned long handle) { unsigned long *ptr = (unsigned long *)handle; return !test_and_set_bit_lock(HANDLE_PIN_BIT, ptr); } static void pin_tag(unsigned long handle) { while (!trypin_tag(handle)); } static void unpin_tag(unsigned long handle) { unsigned long *ptr = (unsigned long *)handle; clear_bit_unlock(HANDLE_PIN_BIT, ptr); } static void reset_page(struct page *page) { clear_bit(PG_private, &page->flags); clear_bit(PG_private_2, &page->flags); set_page_private(page, 0); page->mapping = NULL; page->freelist = NULL; page_mapcount_reset(page); } static void free_zspage(struct page *first_page) { struct page *nextp, *tmp, *head_extra; BUG_ON(!is_first_page(first_page)); BUG_ON(first_page->inuse); head_extra = (struct page *)page_private(first_page); reset_page(first_page); __free_page(first_page); /* zspage with only 1 system page */ if (!head_extra) return; list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) { list_del(&nextp->lru); reset_page(nextp); __free_page(nextp); } reset_page(head_extra); __free_page(head_extra); } /* Initialize a newly allocated zspage */ static void init_zspage(struct page *first_page, struct size_class *class) { unsigned long off = 0; struct page *page = first_page; BUG_ON(!is_first_page(first_page)); while (page) { struct page *next_page; struct link_free *link; unsigned int i = 1; void *vaddr; /* * page->index stores offset of first object starting * in the page. For the first page, this is always 0, * so we use first_page->index (aka ->freelist) to store * head of corresponding zspage's freelist. */ if (page != first_page) page->index = off; vaddr = kmap_atomic(page); link = (struct link_free *)vaddr + off / sizeof(*link); while ((off += class->size) < PAGE_SIZE) { link->next = location_to_obj(page, i++); link += class->size / sizeof(*link); } /* * We now come to the last (full or partial) object on this * page, which must point to the first object on the next * page (if present) */ next_page = get_next_page(page); link->next = location_to_obj(next_page, 0); kunmap_atomic(vaddr); page = next_page; off %= PAGE_SIZE; } } /* * Allocate a zspage for the given size class */ static struct page *alloc_zspage(struct size_class *class, gfp_t flags) { int i, error; struct page *first_page = NULL, *uninitialized_var(prev_page); /* * Allocate individual pages and link them together as: * 1. first page->private = first sub-page * 2. all sub-pages are linked together using page->lru * 3. each sub-page is linked to the first page using page->first_page * * For each size class, First/Head pages are linked together using * page->lru. Also, we set PG_private to identify the first page * (i.e. no other sub-page has this flag set) and PG_private_2 to * identify the last page. */ error = -ENOMEM; for (i = 0; i < class->pages_per_zspage; i++) { struct page *page; page = alloc_page(flags); if (!page) goto cleanup; INIT_LIST_HEAD(&page->lru); if (i == 0) { /* first page */ SetPagePrivate(page); set_page_private(page, 0); first_page = page; first_page->inuse = 0; } if (i == 1) set_page_private(first_page, (unsigned long)page); if (i >= 1) page->first_page = first_page; if (i >= 2) list_add(&page->lru, &prev_page->lru); if (i == class->pages_per_zspage - 1) /* last page */ SetPagePrivate2(page); prev_page = page; } init_zspage(first_page, class); first_page->freelist = location_to_obj(first_page, 0); /* Maximum number of objects we can store in this zspage */ first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size; error = 0; /* Success */ cleanup: if (unlikely(error) && first_page) { free_zspage(first_page); first_page = NULL; } return first_page; } static struct page *find_get_zspage(struct size_class *class) { int i; struct page *page; for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) { page = class->fullness_list[i]; if (page) break; } return page; } #ifdef CONFIG_PGTABLE_MAPPING static inline int __zs_cpu_up(struct mapping_area *area) { /* * Make sure we don't leak memory if a cpu UP notification * and zs_init() race and both call zs_cpu_up() on the same cpu */ if (area->vm) return 0; area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL); if (!area->vm) return -ENOMEM; return 0; } static inline void __zs_cpu_down(struct mapping_area *area) { if (area->vm) free_vm_area(area->vm); area->vm = NULL; } static inline void *__zs_map_object(struct mapping_area *area, struct page *pages[2], int off, int size) { BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages)); area->vm_addr = area->vm->addr; return area->vm_addr + off; } static inline void __zs_unmap_object(struct mapping_area *area, struct page *pages[2], int off, int size) { unsigned long addr = (unsigned long)area->vm_addr; unmap_kernel_range(addr, PAGE_SIZE * 2); } #else /* CONFIG_PGTABLE_MAPPING */ static inline int __zs_cpu_up(struct mapping_area *area) { /* * Make sure we don't leak memory if a cpu UP notification * and zs_init() race and both call zs_cpu_up() on the same cpu */ if (area->vm_buf) return 0; area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL); if (!area->vm_buf) return -ENOMEM; return 0; } static inline void __zs_cpu_down(struct mapping_area *area) { kfree(area->vm_buf); area->vm_buf = NULL; } static void *__zs_map_object(struct mapping_area *area, struct page *pages[2], int off, int size) { int sizes[2]; void *addr; char *buf = area->vm_buf; /* disable page faults to match kmap_atomic() return conditions */ pagefault_disable(); /* no read fastpath */ if (area->vm_mm == ZS_MM_WO) goto out; sizes[0] = PAGE_SIZE - off; sizes[1] = size - sizes[0]; /* copy object to per-cpu buffer */ addr = kmap_atomic(pages[0]); memcpy(buf, addr + off, sizes[0]); kunmap_atomic(addr); addr = kmap_atomic(pages[1]); memcpy(buf + sizes[0], addr, sizes[1]); kunmap_atomic(addr); out: return area->vm_buf; } static void __zs_unmap_object(struct mapping_area *area, struct page *pages[2], int off, int size) { int sizes[2]; void *addr; char *buf; /* no write fastpath */ if (area->vm_mm == ZS_MM_RO) goto out; buf = area->vm_buf; if (!area->huge) { buf = buf + ZS_HANDLE_SIZE; size -= ZS_HANDLE_SIZE; off += ZS_HANDLE_SIZE; } sizes[0] = PAGE_SIZE - off; sizes[1] = size - sizes[0]; /* copy per-cpu buffer to object */ addr = kmap_atomic(pages[0]); memcpy(addr + off, buf, sizes[0]); kunmap_atomic(addr); addr = kmap_atomic(pages[1]); memcpy(addr, buf + sizes[0], sizes[1]); kunmap_atomic(addr); out: /* enable page faults to match kunmap_atomic() return conditions */ pagefault_enable(); } #endif /* CONFIG_PGTABLE_MAPPING */ static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action, void *pcpu) { int ret, cpu = (long)pcpu; struct mapping_area *area; switch (action) { case CPU_UP_PREPARE: area = &per_cpu(zs_map_area, cpu); ret = __zs_cpu_up(area); if (ret) return notifier_from_errno(ret); break; case CPU_DEAD: case CPU_UP_CANCELED: area = &per_cpu(zs_map_area, cpu); __zs_cpu_down(area); break; } return NOTIFY_OK; } static struct notifier_block zs_cpu_nb = { .notifier_call = zs_cpu_notifier }; static int zs_register_cpu_notifier(void) { int cpu, uninitialized_var(ret); cpu_notifier_register_begin(); __register_cpu_notifier(&zs_cpu_nb); for_each_online_cpu(cpu) { ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu); if (notifier_to_errno(ret)) break; } cpu_notifier_register_done(); return notifier_to_errno(ret); } static void zs_unregister_cpu_notifier(void) { int cpu; cpu_notifier_register_begin(); for_each_online_cpu(cpu) zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu); __unregister_cpu_notifier(&zs_cpu_nb); cpu_notifier_register_done(); } static void init_zs_size_classes(void) { int nr; nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1; if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA) nr += 1; zs_size_classes = nr; } static bool can_merge(struct size_class *prev, int size, int pages_per_zspage) { if (prev->pages_per_zspage != pages_per_zspage) return false; if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage) != get_maxobj_per_zspage(size, pages_per_zspage)) return false; return true; } static bool zspage_full(struct page *page) { BUG_ON(!is_first_page(page)); return page->inuse == page->objects; } unsigned long zs_get_total_pages(struct zs_pool *pool) { return atomic_long_read(&pool->pages_allocated); } EXPORT_SYMBOL_GPL(zs_get_total_pages); /** * zs_map_object - get address of allocated object from handle. * @pool: pool from which the object was allocated * @handle: handle returned from zs_malloc * * Before using an object allocated from zs_malloc, it must be mapped using * this function. When done with the object, it must be unmapped using * zs_unmap_object. * * Only one object can be mapped per cpu at a time. There is no protection * against nested mappings. * * This function returns with preemption and page faults disabled. */ void *zs_map_object(struct zs_pool *pool, unsigned long handle, enum zs_mapmode mm) { struct page *page; unsigned long obj, obj_idx, off; unsigned int class_idx; enum fullness_group fg; struct size_class *class; struct mapping_area *area; struct page *pages[2]; void *ret; BUG_ON(!handle); /* * Because we use per-cpu mapping areas shared among the * pools/users, we can't allow mapping in interrupt context * because it can corrupt another users mappings. */ BUG_ON(in_interrupt()); /* From now on, migration cannot move the object */ pin_tag(handle); obj = handle_to_obj(handle); obj_to_location(obj, &page, &obj_idx); get_zspage_mapping(get_first_page(page), &class_idx, &fg); class = pool->size_class[class_idx]; off = obj_idx_to_offset(page, obj_idx, class->size); area = &get_cpu_var(zs_map_area); area->vm_mm = mm; if (off + class->size <= PAGE_SIZE) { /* this object is contained entirely within a page */ area->vm_addr = kmap_atomic(page); ret = area->vm_addr + off; goto out; } /* this object spans two pages */ pages[0] = page; pages[1] = get_next_page(page); BUG_ON(!pages[1]); ret = __zs_map_object(area, pages, off, class->size); out: if (!class->huge) ret += ZS_HANDLE_SIZE; return ret; } EXPORT_SYMBOL_GPL(zs_map_object); void zs_unmap_object(struct zs_pool *pool, unsigned long handle) { struct page *page; unsigned long obj, obj_idx, off; unsigned int class_idx; enum fullness_group fg; struct size_class *class; struct mapping_area *area; BUG_ON(!handle); obj = handle_to_obj(handle); obj_to_location(obj, &page, &obj_idx); get_zspage_mapping(get_first_page(page), &class_idx, &fg); class = pool->size_class[class_idx]; off = obj_idx_to_offset(page, obj_idx, class->size); area = this_cpu_ptr(&zs_map_area); if (off + class->size <= PAGE_SIZE) kunmap_atomic(area->vm_addr); else { struct page *pages[2]; pages[0] = page; pages[1] = get_next_page(page); BUG_ON(!pages[1]); __zs_unmap_object(area, pages, off, class->size); } put_cpu_var(zs_map_area); unpin_tag(handle); } EXPORT_SYMBOL_GPL(zs_unmap_object); static unsigned long obj_malloc(struct page *first_page, struct size_class *class, unsigned long handle) { unsigned long obj; struct link_free *link; struct page *m_page; unsigned long m_objidx, m_offset; void *vaddr; handle |= OBJ_ALLOCATED_TAG; obj = (unsigned long)first_page->freelist; obj_to_location(obj, &m_page, &m_objidx); m_offset = obj_idx_to_offset(m_page, m_objidx, class->size); vaddr = kmap_atomic(m_page); link = (struct link_free *)vaddr + m_offset / sizeof(*link); first_page->freelist = link->next; if (!class->huge) /* record handle in the header of allocated chunk */ link->handle = handle; else /* record handle in first_page->private */ set_page_private(first_page, handle); kunmap_atomic(vaddr); first_page->inuse++; zs_stat_inc(class, OBJ_USED, 1); return obj; } /** * zs_malloc - Allocate block of given size from pool. * @pool: pool to allocate from * @size: size of block to allocate * * On success, handle to the allocated object is returned, * otherwise 0. * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail. */ unsigned long zs_malloc(struct zs_pool *pool, size_t size) { unsigned long handle, obj; struct size_class *class; struct page *first_page; if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE)) return 0; handle = alloc_handle(pool); if (!handle) return 0; /* extra space in chunk to keep the handle */ size += ZS_HANDLE_SIZE; class = pool->size_class[get_size_class_index(size)]; spin_lock(&class->lock); first_page = find_get_zspage(class); if (!first_page) { spin_unlock(&class->lock); first_page = alloc_zspage(class, pool->flags); if (unlikely(!first_page)) { free_handle(pool, handle); return 0; } set_zspage_mapping(first_page, class->index, ZS_EMPTY); atomic_long_add(class->pages_per_zspage, &pool->pages_allocated); spin_lock(&class->lock); zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage( class->size, class->pages_per_zspage)); } obj = obj_malloc(first_page, class, handle); /* Now move the zspage to another fullness group, if required */ fix_fullness_group(class, first_page); record_obj(handle, obj); spin_unlock(&class->lock); return handle; } EXPORT_SYMBOL_GPL(zs_malloc); static void obj_free(struct zs_pool *pool, struct size_class *class, unsigned long obj) { struct link_free *link; struct page *first_page, *f_page; unsigned long f_objidx, f_offset; void *vaddr; int class_idx; enum fullness_group fullness; BUG_ON(!obj); obj &= ~OBJ_ALLOCATED_TAG; obj_to_location(obj, &f_page, &f_objidx); first_page = get_first_page(f_page); get_zspage_mapping(first_page, &class_idx, &fullness); f_offset = obj_idx_to_offset(f_page, f_objidx, class->size); vaddr = kmap_atomic(f_page); /* Insert this object in containing zspage's freelist */ link = (struct link_free *)(vaddr + f_offset); link->next = first_page->freelist; if (class->huge) set_page_private(first_page, 0); kunmap_atomic(vaddr); first_page->freelist = (void *)obj; first_page->inuse--; zs_stat_dec(class, OBJ_USED, 1); } void zs_free(struct zs_pool *pool, unsigned long handle) { struct page *first_page, *f_page; unsigned long obj, f_objidx; int class_idx; struct size_class *class; enum fullness_group fullness; if (unlikely(!handle)) return; pin_tag(handle); obj = handle_to_obj(handle); obj_to_location(obj, &f_page, &f_objidx); first_page = get_first_page(f_page); get_zspage_mapping(first_page, &class_idx, &fullness); class = pool->size_class[class_idx]; spin_lock(&class->lock); obj_free(pool, class, obj); fullness = fix_fullness_group(class, first_page); if (fullness == ZS_EMPTY) { zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage( class->size, class->pages_per_zspage)); atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated); free_zspage(first_page); } spin_unlock(&class->lock); unpin_tag(handle); free_handle(pool, handle); } EXPORT_SYMBOL_GPL(zs_free); static void zs_object_copy(unsigned long src, unsigned long dst, struct size_class *class) { struct page *s_page, *d_page; unsigned long s_objidx, d_objidx; unsigned long s_off, d_off; void *s_addr, *d_addr; int s_size, d_size, size; int written = 0; s_size = d_size = class->size; obj_to_location(src, &s_page, &s_objidx); obj_to_location(dst, &d_page, &d_objidx); s_off = obj_idx_to_offset(s_page, s_objidx, class->size); d_off = obj_idx_to_offset(d_page, d_objidx, class->size); if (s_off + class->size > PAGE_SIZE) s_size = PAGE_SIZE - s_off; if (d_off + class->size > PAGE_SIZE) d_size = PAGE_SIZE - d_off; s_addr = kmap_atomic(s_page); d_addr = kmap_atomic(d_page); while (1) { size = min(s_size, d_size); memcpy(d_addr + d_off, s_addr + s_off, size); written += size; if (written == class->size) break; s_off += size; s_size -= size; d_off += size; d_size -= size; if (s_off >= PAGE_SIZE) { kunmap_atomic(d_addr); kunmap_atomic(s_addr); s_page = get_next_page(s_page); BUG_ON(!s_page); s_addr = kmap_atomic(s_page); d_addr = kmap_atomic(d_page); s_size = class->size - written; s_off = 0; } if (d_off >= PAGE_SIZE) { kunmap_atomic(d_addr); d_page = get_next_page(d_page); BUG_ON(!d_page); d_addr = kmap_atomic(d_page); d_size = class->size - written; d_off = 0; } } kunmap_atomic(d_addr); kunmap_atomic(s_addr); } /* * Find alloced object in zspage from index object and * return handle. */ static unsigned long find_alloced_obj(struct page *page, int index, struct size_class *class) { unsigned long head; int offset = 0; unsigned long handle = 0; void *addr = kmap_atomic(page); if (!is_first_page(page)) offset = page->index; offset += class->size * index; while (offset < PAGE_SIZE) { head = obj_to_head(class, page, addr + offset); if (head & OBJ_ALLOCATED_TAG) { handle = head & ~OBJ_ALLOCATED_TAG; if (trypin_tag(handle)) break; handle = 0; } offset += class->size; index++; } kunmap_atomic(addr); return handle; } struct zs_compact_control { /* Source page for migration which could be a subpage of zspage. */ struct page *s_page; /* Destination page for migration which should be a first page * of zspage. */ struct page *d_page; /* Starting object index within @s_page which used for live object * in the subpage. */ int index; /* how many of objects are migrated */ int nr_migrated; }; static int migrate_zspage(struct zs_pool *pool, struct size_class *class, struct zs_compact_control *cc) { unsigned long used_obj, free_obj; unsigned long handle; struct page *s_page = cc->s_page; struct page *d_page = cc->d_page; unsigned long index = cc->index; int nr_migrated = 0; int ret = 0; while (1) { handle = find_alloced_obj(s_page, index, class); if (!handle) { s_page = get_next_page(s_page); if (!s_page) break; index = 0; continue; } /* Stop if there is no more space */ if (zspage_full(d_page)) { unpin_tag(handle); ret = -ENOMEM; break; } used_obj = handle_to_obj(handle); free_obj = obj_malloc(d_page, class, handle); zs_object_copy(used_obj, free_obj, class); index++; /* * record_obj updates handle's value to free_obj and it will * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which * breaks synchronization using pin_tag(e,g, zs_free) so * let's keep the lock bit. */ free_obj |= BIT(HANDLE_PIN_BIT); record_obj(handle, free_obj); unpin_tag(handle); obj_free(pool, class, used_obj); nr_migrated++; } /* Remember last position in this iteration */ cc->s_page = s_page; cc->index = index; cc->nr_migrated = nr_migrated; return ret; } static struct page *alloc_target_page(struct size_class *class) { int i; struct page *page; for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) { page = class->fullness_list[i]; if (page) { remove_zspage(page, class, i); break; } } return page; } static void putback_zspage(struct zs_pool *pool, struct size_class *class, struct page *first_page) { enum fullness_group fullness; BUG_ON(!is_first_page(first_page)); fullness = get_fullness_group(first_page); insert_zspage(first_page, class, fullness); set_zspage_mapping(first_page, class->index, fullness); if (fullness == ZS_EMPTY) { zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage( class->size, class->pages_per_zspage)); atomic_long_sub(class->pages_per_zspage, &pool->pages_allocated); free_zspage(first_page); } } static struct page *isolate_source_page(struct size_class *class) { struct page *page; page = class->fullness_list[ZS_ALMOST_EMPTY]; if (page) remove_zspage(page, class, ZS_ALMOST_EMPTY); return page; } static unsigned long __zs_compact(struct zs_pool *pool, struct size_class *class) { int nr_to_migrate; struct zs_compact_control cc; struct page *src_page; struct page *dst_page = NULL; unsigned long nr_total_migrated = 0; spin_lock(&class->lock); while ((src_page = isolate_source_page(class))) { BUG_ON(!is_first_page(src_page)); /* The goal is to migrate all live objects in source page */ nr_to_migrate = src_page->inuse; cc.index = 0; cc.s_page = src_page; while ((dst_page = alloc_target_page(class))) { cc.d_page = dst_page; /* * If there is no more space in dst_page, try to * allocate another zspage. */ if (!migrate_zspage(pool, class, &cc)) break; putback_zspage(pool, class, dst_page); nr_total_migrated += cc.nr_migrated; nr_to_migrate -= cc.nr_migrated; } /* Stop if we couldn't find slot */ if (dst_page == NULL) break; putback_zspage(pool, class, dst_page); putback_zspage(pool, class, src_page); spin_unlock(&class->lock); nr_total_migrated += cc.nr_migrated; cond_resched(); spin_lock(&class->lock); } if (src_page) putback_zspage(pool, class, src_page); spin_unlock(&class->lock); return nr_total_migrated; } unsigned long zs_compact(struct zs_pool *pool) { int i; unsigned long nr_migrated = 0; struct size_class *class; for (i = zs_size_classes - 1; i >= 0; i--) { class = pool->size_class[i]; if (!class) continue; if (class->index != i) continue; nr_migrated += __zs_compact(pool, class); } return nr_migrated; } EXPORT_SYMBOL_GPL(zs_compact); /** * zs_create_pool - Creates an allocation pool to work from. * @flags: allocation flags used to allocate pool metadata * * This function must be called before anything when using * the zsmalloc allocator. * * On success, a pointer to the newly created pool is returned, * otherwise NULL. */ struct zs_pool *zs_create_pool(char *name, gfp_t flags) { int i; struct zs_pool *pool; struct size_class *prev_class = NULL; pool = kzalloc(sizeof(*pool), GFP_KERNEL); if (!pool) return NULL; pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *), GFP_KERNEL); if (!pool->size_class) { kfree(pool); return NULL; } pool->name = kstrdup(name, GFP_KERNEL); if (!pool->name) goto err; if (create_handle_cache(pool)) goto err; /* * Iterate reversly, because, size of size_class that we want to use * for merging should be larger or equal to current size. */ for (i = zs_size_classes - 1; i >= 0; i--) { int size; int pages_per_zspage; struct size_class *class; size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA; if (size > ZS_MAX_ALLOC_SIZE) size = ZS_MAX_ALLOC_SIZE; pages_per_zspage = get_pages_per_zspage(size); /* * size_class is used for normal zsmalloc operation such * as alloc/free for that size. Although it is natural that we * have one size_class for each size, there is a chance that we * can get more memory utilization if we use one size_class for * many different sizes whose size_class have same * characteristics. So, we makes size_class point to * previous size_class if possible. */ if (prev_class) { if (can_merge(prev_class, size, pages_per_zspage)) { pool->size_class[i] = prev_class; continue; } } class = kzalloc(sizeof(struct size_class), GFP_KERNEL); if (!class) goto err; class->size = size; class->index = i; class->pages_per_zspage = pages_per_zspage; if (pages_per_zspage == 1 && get_maxobj_per_zspage(size, pages_per_zspage) == 1) class->huge = true; spin_lock_init(&class->lock); pool->size_class[i] = class; prev_class = class; } pool->flags = flags; if (zs_pool_stat_create(name, pool)) goto err; return pool; err: zs_destroy_pool(pool); return NULL; } EXPORT_SYMBOL_GPL(zs_create_pool); void zs_destroy_pool(struct zs_pool *pool) { int i; zs_pool_stat_destroy(pool); for (i = 0; i < zs_size_classes; i++) { int fg; struct size_class *class = pool->size_class[i]; if (!class) continue; if (class->index != i) continue; for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) { if (class->fullness_list[fg]) { pr_info("Freeing non-empty class with size %db, fullness group %d\n", class->size, fg); } } kfree(class); } destroy_handle_cache(pool); kfree(pool->size_class); kfree(pool->name); kfree(pool); } EXPORT_SYMBOL_GPL(zs_destroy_pool); static int __init zs_init(void) { int ret = zs_register_cpu_notifier(); if (ret) goto notifier_fail; init_zs_size_classes(); #ifdef CONFIG_ZPOOL zpool_register_driver(&zs_zpool_driver); #endif ret = zs_stat_init(); if (ret) { pr_err("zs stat initialization failed\n"); goto stat_fail; } return 0; stat_fail: #ifdef CONFIG_ZPOOL zpool_unregister_driver(&zs_zpool_driver); #endif notifier_fail: zs_unregister_cpu_notifier(); return ret; } static void __exit zs_exit(void) { #ifdef CONFIG_ZPOOL zpool_unregister_driver(&zs_zpool_driver); #endif zs_unregister_cpu_notifier(); zs_stat_exit(); } module_init(zs_init); module_exit(zs_exit); MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
amarchandole/capprobe_mptcp
mm/zsmalloc.c
C
gpl-2.0
46,986
/* vfp/vfpsingle.c - ARM VFPv3 emulation unit - SoftFloat single instruction Copyright (C) 2003 Skyeye Develop Group for help please send mail to <skyeye-developer@lists.gro.clinux.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 */ /* * This code is derived in part from : * - Android kernel * - John R. Housers softfloat library, which * carries the following notice: * * =========================================================================== * This C source file is part of the SoftFloat IEC/IEEE Floating-point * Arithmetic Package, Release 2. * * Written by John R. Hauser. This work was made possible in part by the * International Computer Science Institute, located at Suite 600, 1947 Center * Street, Berkeley, California 94704. Funding was partially provided by the * National Science Foundation under grant MIP-9311980. The original version * of this code was written as part of a project to build a fixed-point vector * processor in collaboration with the University of California at Berkeley, * overseen by Profs. Nelson Morgan and John Wawrzynek. More information * is available through the web page `http://HTTP.CS.Berkeley.EDU/~jhauser/ * arithmetic/softfloat.html'. * * THIS SOFTWARE IS DISTRIBUTED AS IS, FOR FREE. Although reasonable effort * has been made to avoid it, THIS SOFTWARE MAY CONTAIN FAULTS THAT WILL AT * TIMES RESULT IN INCORRECT BEHAVIOR. USE OF THIS SOFTWARE IS RESTRICTED TO * PERSONS AND ORGANIZATIONS WHO CAN AND WILL TAKE FULL RESPONSIBILITY FOR ANY * AND ALL LOSSES, COSTS, OR OTHER PROBLEMS ARISING FROM ITS USE. * * Derivative works are acceptable, even for commercial purposes, so long as * (1) they include prominent notice that the work is derivative, and (2) they * include prominent notice akin to these three paragraphs for those parts of * this code that are retained. * =========================================================================== */ #include <algorithm> #include <cinttypes> #include "common/common_funcs.h" #include "common/common_types.h" #include "common/logging/log.h" #include "core/arm/skyeye_common/vfp/asm_vfp.h" #include "core/arm/skyeye_common/vfp/vfp.h" #include "core/arm/skyeye_common/vfp/vfp_helper.h" static struct vfp_single vfp_single_default_qnan = { 255, 0, VFP_SINGLE_SIGNIFICAND_QNAN, }; static void vfp_single_dump(const char* str, struct vfp_single* s) { LOG_TRACE(Core_ARM11, "%s: sign=%d exponent=%d significand=%08x", str, s->sign != 0, s->exponent, s->significand); } static void vfp_single_normalise_denormal(struct vfp_single* vs) { int bits = 31 - fls(vs->significand); vfp_single_dump("normalise_denormal: in", vs); if (bits) { vs->exponent -= bits - 1; vs->significand <<= bits; } vfp_single_dump("normalise_denormal: out", vs); } u32 vfp_single_normaliseround(ARMul_State* state, int sd, struct vfp_single* vs, u32 fpscr, const char* func) { u32 significand, incr, rmode; int exponent, shift, underflow; u32 exceptions = 0; vfp_single_dump("pack: in", vs); /* * Infinities and NaNs are a special case. */ if (vs->exponent == 255 && (vs->significand == 0 || exceptions)) goto pack; /* * Special-case zero. */ if (vs->significand == 0) { vs->exponent = 0; goto pack; } exponent = vs->exponent; significand = vs->significand; /* * Normalise first. Note that we shift the significand up to * bit 31, so we have VFP_SINGLE_LOW_BITS + 1 below the least * significant bit. */ shift = 32 - fls(significand); if (shift < 32 && shift) { exponent -= shift; significand <<= shift; } #if 1 vs->exponent = exponent; vs->significand = significand; vfp_single_dump("pack: normalised", vs); #endif /* * Tiny number? */ underflow = exponent < 0; if (underflow) { significand = vfp_shiftright32jamming(significand, -exponent); exponent = 0; #if 1 vs->exponent = exponent; vs->significand = significand; vfp_single_dump("pack: tiny number", vs); #endif if (!(significand & ((1 << (VFP_SINGLE_LOW_BITS + 1)) - 1))) underflow = 0; } /* * Select rounding increment. */ incr = 0; rmode = fpscr & FPSCR_RMODE_MASK; if (rmode == FPSCR_ROUND_NEAREST) { incr = 1 << VFP_SINGLE_LOW_BITS; if ((significand & (1 << (VFP_SINGLE_LOW_BITS + 1))) == 0) incr -= 1; } else if (rmode == FPSCR_ROUND_TOZERO) { incr = 0; } else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vs->sign != 0)) incr = (1 << (VFP_SINGLE_LOW_BITS + 1)) - 1; LOG_TRACE(Core_ARM11, "rounding increment = 0x%08x", incr); /* * Is our rounding going to overflow? */ if ((significand + incr) < significand) { exponent += 1; significand = (significand >> 1) | (significand & 1); incr >>= 1; #if 1 vs->exponent = exponent; vs->significand = significand; vfp_single_dump("pack: overflow", vs); #endif } /* * If any of the low bits (which will be shifted out of the * number) are non-zero, the result is inexact. */ if (significand & ((1 << (VFP_SINGLE_LOW_BITS + 1)) - 1)) exceptions |= FPSCR_IXC; /* * Do our rounding. */ significand += incr; /* * Infinity? */ if (exponent >= 254) { exceptions |= FPSCR_OFC | FPSCR_IXC; if (incr == 0) { vs->exponent = 253; vs->significand = 0x7fffffff; } else { vs->exponent = 255; /* infinity */ vs->significand = 0; } } else { if (significand >> (VFP_SINGLE_LOW_BITS + 1) == 0) exponent = 0; if (exponent || significand > 0x80000000) underflow = 0; if (underflow) exceptions |= FPSCR_UFC; vs->exponent = exponent; vs->significand = significand >> 1; } pack: vfp_single_dump("pack: final", vs); { s32 d = vfp_single_pack(vs); LOG_TRACE(Core_ARM11, "%s: d(s%d)=%08x exceptions=%08x", func, sd, d, exceptions); vfp_put_float(state, d, sd); } return exceptions; } /* * Propagate the NaN, setting exceptions if it is signalling. * 'n' is always a NaN. 'm' may be a number, NaN or infinity. */ static u32 vfp_propagate_nan(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm, u32 fpscr) { struct vfp_single* nan; int tn, tm = 0; tn = vfp_single_type(vsn); if (vsm) tm = vfp_single_type(vsm); if (fpscr & FPSCR_DEFAULT_NAN) /* * Default NaN mode - always returns a quiet NaN */ nan = &vfp_single_default_qnan; else { /* * Contemporary mode - select the first signalling * NAN, or if neither are signalling, the first * quiet NAN. */ if (tn == VFP_SNAN || (tm != VFP_SNAN && tn == VFP_QNAN)) nan = vsn; else nan = vsm; /* * Make the NaN quiet. */ nan->significand |= VFP_SINGLE_SIGNIFICAND_QNAN; } *vsd = *nan; /* * If one was a signalling NAN, raise invalid operation. */ return tn == VFP_SNAN || tm == VFP_SNAN ? FPSCR_IOC : VFP_NAN_FLAG; } /* * Extended operations */ static u32 vfp_single_fabs(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { vfp_put_float(state, vfp_single_packed_abs(m), sd); return 0; } static u32 vfp_single_fcpy(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { vfp_put_float(state, m, sd); return 0; } static u32 vfp_single_fneg(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { vfp_put_float(state, vfp_single_packed_negate(m), sd); return 0; } static const u16 sqrt_oddadjust[] = { 0x0004, 0x0022, 0x005d, 0x00b1, 0x011d, 0x019f, 0x0236, 0x02e0, 0x039c, 0x0468, 0x0545, 0x0631, 0x072b, 0x0832, 0x0946, 0x0a67, }; static const u16 sqrt_evenadjust[] = { 0x0a2d, 0x08af, 0x075a, 0x0629, 0x051a, 0x0429, 0x0356, 0x029e, 0x0200, 0x0179, 0x0109, 0x00af, 0x0068, 0x0034, 0x0012, 0x0002, }; u32 vfp_estimate_sqrt_significand(u32 exponent, u32 significand) { int index; u32 z, a; if ((significand & 0xc0000000) != 0x40000000) { LOG_TRACE(Core_ARM11, "invalid significand"); } a = significand << 1; index = (a >> 27) & 15; if (exponent & 1) { z = 0x4000 + (a >> 17) - sqrt_oddadjust[index]; z = ((a / z) << 14) + (z << 15); a >>= 1; } else { z = 0x8000 + (a >> 17) - sqrt_evenadjust[index]; z = a / z + z; z = (z >= 0x20000) ? 0xffff8000 : (z << 15); if (z <= a) return (s32)a >> 1; } { u64 v = (u64)a << 31; do_div(v, z); return (u32)(v + (z >> 1)); } } static u32 vfp_single_fsqrt(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { struct vfp_single vsm, vsd, *vsp; int ret, tm; u32 exceptions = 0; exceptions |= vfp_single_unpack(&vsm, m, fpscr); tm = vfp_single_type(&vsm); if (tm & (VFP_NAN | VFP_INFINITY)) { vsp = &vsd; if (tm & VFP_NAN) ret = vfp_propagate_nan(vsp, &vsm, nullptr, fpscr); else if (vsm.sign == 0) { sqrt_copy: vsp = &vsm; ret = 0; } else { sqrt_invalid: vsp = &vfp_single_default_qnan; ret = FPSCR_IOC; } vfp_put_float(state, vfp_single_pack(vsp), sd); return ret; } /* * sqrt(+/- 0) == +/- 0 */ if (tm & VFP_ZERO) goto sqrt_copy; /* * Normalise a denormalised number */ if (tm & VFP_DENORMAL) vfp_single_normalise_denormal(&vsm); /* * sqrt(<0) = invalid */ if (vsm.sign) goto sqrt_invalid; vfp_single_dump("sqrt", &vsm); /* * Estimate the square root. */ vsd.sign = 0; vsd.exponent = ((vsm.exponent - 127) >> 1) + 127; vsd.significand = vfp_estimate_sqrt_significand(vsm.exponent, vsm.significand) + 2; vfp_single_dump("sqrt estimate", &vsd); /* * And now adjust. */ if ((vsd.significand & VFP_SINGLE_LOW_BITS_MASK) <= 5) { if (vsd.significand < 2) { vsd.significand = 0xffffffff; } else { u64 term; s64 rem; vsm.significand <<= static_cast<u32>((vsm.exponent & 1) == 0); term = (u64)vsd.significand * vsd.significand; rem = ((u64)vsm.significand << 32) - term; LOG_TRACE(Core_ARM11, "term=%016" PRIx64 "rem=%016" PRIx64, term, rem); while (rem < 0) { vsd.significand -= 1; rem += ((u64)vsd.significand << 1) | 1; } vsd.significand |= rem != 0; } } vsd.significand = vfp_shiftright32jamming(vsd.significand, 1); exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fsqrt"); return exceptions; } /* * Equal := ZC * Less than := N * Greater than := C * Unordered := CV */ static u32 vfp_compare(ARMul_State* state, int sd, int signal_on_qnan, s32 m, u32 fpscr) { s32 d; u32 ret = 0; d = vfp_get_float(state, sd); if (vfp_single_packed_exponent(m) == 255 && vfp_single_packed_mantissa(m)) { ret |= FPSCR_CFLAG | FPSCR_VFLAG; if (signal_on_qnan || !(vfp_single_packed_mantissa(m) & (1 << (VFP_SINGLE_MANTISSA_BITS - 1)))) /* * Signalling NaN, or signalling on quiet NaN */ ret |= FPSCR_IOC; } if (vfp_single_packed_exponent(d) == 255 && vfp_single_packed_mantissa(d)) { ret |= FPSCR_CFLAG | FPSCR_VFLAG; if (signal_on_qnan || !(vfp_single_packed_mantissa(d) & (1 << (VFP_SINGLE_MANTISSA_BITS - 1)))) /* * Signalling NaN, or signalling on quiet NaN */ ret |= FPSCR_IOC; } if (ret == 0) { if (d == m || vfp_single_packed_abs(d | m) == 0) { /* * equal */ ret |= FPSCR_ZFLAG | FPSCR_CFLAG; } else if (vfp_single_packed_sign(d ^ m)) { /* * different signs */ if (vfp_single_packed_sign(d)) /* * d is negative, so d < m */ ret |= FPSCR_NFLAG; else /* * d is positive, so d > m */ ret |= FPSCR_CFLAG; } else if ((vfp_single_packed_sign(d) != 0) ^ (d < m)) { /* * d < m */ ret |= FPSCR_NFLAG; } else if ((vfp_single_packed_sign(d) != 0) ^ (d > m)) { /* * d > m */ ret |= FPSCR_CFLAG; } } return ret; } static u32 vfp_single_fcmp(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { return vfp_compare(state, sd, 0, m, fpscr); } static u32 vfp_single_fcmpe(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { return vfp_compare(state, sd, 1, m, fpscr); } static u32 vfp_single_fcmpz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { return vfp_compare(state, sd, 0, 0, fpscr); } static u32 vfp_single_fcmpez(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { return vfp_compare(state, sd, 1, 0, fpscr); } static u32 vfp_single_fcvtd(ARMul_State* state, int dd, int unused, s32 m, u32 fpscr) { struct vfp_single vsm; struct vfp_double vdd; int tm; u32 exceptions = 0; exceptions |= vfp_single_unpack(&vsm, m, fpscr); tm = vfp_single_type(&vsm); /* * If we have a signalling NaN, signal invalid operation. */ if (tm == VFP_SNAN) exceptions |= FPSCR_IOC; if (tm & VFP_DENORMAL) vfp_single_normalise_denormal(&vsm); vdd.sign = vsm.sign; vdd.significand = (u64)vsm.significand << 32; /* * If we have an infinity or NaN, the exponent must be 2047. */ if (tm & (VFP_INFINITY | VFP_NAN)) { vdd.exponent = 2047; if (tm == VFP_QNAN) vdd.significand |= VFP_DOUBLE_SIGNIFICAND_QNAN; goto pack_nan; } else if (tm & VFP_ZERO) vdd.exponent = 0; else vdd.exponent = vsm.exponent + (1023 - 127); exceptions |= vfp_double_normaliseround(state, dd, &vdd, fpscr, "fcvtd"); return exceptions; pack_nan: vfp_put_double(state, vfp_double_pack(&vdd), dd); return exceptions; } static u32 vfp_single_fuito(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { struct vfp_single vs; u32 exceptions = 0; vs.sign = 0; vs.exponent = 127 + 31 - 1; vs.significand = (u32)m; exceptions |= vfp_single_normaliseround(state, sd, &vs, fpscr, "fuito"); return exceptions; } static u32 vfp_single_fsito(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { struct vfp_single vs; u32 exceptions = 0; vs.sign = (m & 0x80000000) >> 16; vs.exponent = 127 + 31 - 1; vs.significand = vs.sign ? -m : m; exceptions |= vfp_single_normaliseround(state, sd, &vs, fpscr, "fsito"); return exceptions; } static u32 vfp_single_ftoui(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { struct vfp_single vsm; u32 d, exceptions = 0; int rmode = fpscr & FPSCR_RMODE_MASK; int tm; exceptions |= vfp_single_unpack(&vsm, m, fpscr); vfp_single_dump("VSM", &vsm); /* * Do we have a denormalised number? */ tm = vfp_single_type(&vsm); if (tm & VFP_DENORMAL) exceptions |= FPSCR_IDC; if (tm & VFP_NAN) vsm.sign = 1; if (vsm.exponent >= 127 + 32) { d = vsm.sign ? 0 : 0xffffffff; exceptions |= FPSCR_IOC; } else if (vsm.exponent >= 127) { int shift = 127 + 31 - vsm.exponent; u32 rem, incr = 0; /* * 2^0 <= m < 2^32-2^8 */ d = (vsm.significand << 1) >> shift; if (shift > 0) { rem = (vsm.significand << 1) << (32 - shift); } else { rem = 0; } if (rmode == FPSCR_ROUND_NEAREST) { incr = 0x80000000; if ((d & 1) == 0) incr -= 1; } else if (rmode == FPSCR_ROUND_TOZERO) { incr = 0; } else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vsm.sign != 0)) { incr = ~0; } if ((rem + incr) < rem) { if (d < 0xffffffff) d += 1; else exceptions |= FPSCR_IOC; } if (d && vsm.sign) { d = 0; exceptions |= FPSCR_IOC; } else if (rem) exceptions |= FPSCR_IXC; } else { d = 0; if (vsm.exponent | vsm.significand) { if (rmode == FPSCR_ROUND_NEAREST) { if (vsm.exponent >= 126) { d = vsm.sign ? 0 : 1; exceptions |= vsm.sign ? FPSCR_IOC : FPSCR_IXC; } else { exceptions |= FPSCR_IXC; } } else if (rmode == FPSCR_ROUND_PLUSINF && vsm.sign == 0) { d = 1; exceptions |= FPSCR_IXC; } else if (rmode == FPSCR_ROUND_MINUSINF) { exceptions |= vsm.sign ? FPSCR_IOC : FPSCR_IXC; } else { exceptions |= FPSCR_IXC; } } } LOG_TRACE(Core_ARM11, "ftoui: d(s%d)=%08x exceptions=%08x", sd, d, exceptions); vfp_put_float(state, d, sd); return exceptions; } static u32 vfp_single_ftouiz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { return vfp_single_ftoui(state, sd, unused, m, (fpscr & ~FPSCR_RMODE_MASK) | FPSCR_ROUND_TOZERO); } static u32 vfp_single_ftosi(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { struct vfp_single vsm; u32 d, exceptions = 0; int rmode = fpscr & FPSCR_RMODE_MASK; int tm; exceptions |= vfp_single_unpack(&vsm, m, fpscr); vfp_single_dump("VSM", &vsm); /* * Do we have a denormalised number? */ tm = vfp_single_type(&vsm); if (vfp_single_type(&vsm) & VFP_DENORMAL) exceptions |= FPSCR_IDC; if (tm & VFP_NAN) { d = 0; exceptions |= FPSCR_IOC; } else if (vsm.exponent >= 127 + 31) { /* * m >= 2^31-2^7: invalid */ d = 0x7fffffff; if (vsm.sign) d = ~d; exceptions |= FPSCR_IOC; } else if (vsm.exponent >= 127) { int shift = 127 + 31 - vsm.exponent; u32 rem, incr = 0; /* 2^0 <= m <= 2^31-2^7 */ d = (vsm.significand << 1) >> shift; rem = (vsm.significand << 1) << (32 - shift); if (rmode == FPSCR_ROUND_NEAREST) { incr = 0x80000000; if ((d & 1) == 0) incr -= 1; } else if (rmode == FPSCR_ROUND_TOZERO) { incr = 0; } else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vsm.sign != 0)) { incr = ~0; } if ((rem + incr) < rem && d < 0xffffffff) d += 1; if (d > (0x7fffffffu + (vsm.sign != 0))) { d = (0x7fffffffu + (vsm.sign != 0)); exceptions |= FPSCR_IOC; } else if (rem) exceptions |= FPSCR_IXC; if (vsm.sign) d = (~d + 1); } else { d = 0; if (vsm.exponent | vsm.significand) { exceptions |= FPSCR_IXC; if (rmode == FPSCR_ROUND_NEAREST) { if (vsm.exponent >= 126) d = vsm.sign ? 0xffffffff : 1; } else if (rmode == FPSCR_ROUND_PLUSINF && vsm.sign == 0) { d = 1; } else if (rmode == FPSCR_ROUND_MINUSINF && vsm.sign) { d = 0xffffffff; } } } LOG_TRACE(Core_ARM11, "ftosi: d(s%d)=%08x exceptions=%08x", sd, d, exceptions); vfp_put_float(state, (s32)d, sd); return exceptions; } static u32 vfp_single_ftosiz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) { return vfp_single_ftosi(state, sd, unused, m, (fpscr & ~FPSCR_RMODE_MASK) | FPSCR_ROUND_TOZERO); } static struct op fops_ext[] = { {vfp_single_fcpy, 0}, // 0x00000000 - FEXT_FCPY {vfp_single_fabs, 0}, // 0x00000001 - FEXT_FABS {vfp_single_fneg, 0}, // 0x00000002 - FEXT_FNEG {vfp_single_fsqrt, 0}, // 0x00000003 - FEXT_FSQRT {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {vfp_single_fcmp, OP_SCALAR}, // 0x00000008 - FEXT_FCMP {vfp_single_fcmpe, OP_SCALAR}, // 0x00000009 - FEXT_FCMPE {vfp_single_fcmpz, OP_SCALAR}, // 0x0000000A - FEXT_FCMPZ {vfp_single_fcmpez, OP_SCALAR}, // 0x0000000B - FEXT_FCMPEZ {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {vfp_single_fcvtd, OP_SCALAR | OP_DD}, // 0x0000000F - FEXT_FCVT {vfp_single_fuito, OP_SCALAR}, // 0x00000010 - FEXT_FUITO {vfp_single_fsito, OP_SCALAR}, // 0x00000011 - FEXT_FSITO {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {nullptr, 0}, {vfp_single_ftoui, OP_SCALAR}, // 0x00000018 - FEXT_FTOUI {vfp_single_ftouiz, OP_SCALAR}, // 0x00000019 - FEXT_FTOUIZ {vfp_single_ftosi, OP_SCALAR}, // 0x0000001A - FEXT_FTOSI {vfp_single_ftosiz, OP_SCALAR}, // 0x0000001B - FEXT_FTOSIZ }; static u32 vfp_single_fadd_nonnumber(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm, u32 fpscr) { struct vfp_single* vsp; u32 exceptions = 0; int tn, tm; tn = vfp_single_type(vsn); tm = vfp_single_type(vsm); if (tn & tm & VFP_INFINITY) { /* * Two infinities. Are they different signs? */ if (vsn->sign ^ vsm->sign) { /* * different signs -> invalid */ exceptions |= FPSCR_IOC; vsp = &vfp_single_default_qnan; } else { /* * same signs -> valid */ vsp = vsn; } } else if (tn & VFP_INFINITY && tm & VFP_NUMBER) { /* * One infinity and one number -> infinity */ vsp = vsn; } else { /* * 'n' is a NaN of some type */ return vfp_propagate_nan(vsd, vsn, vsm, fpscr); } *vsd = *vsp; return exceptions; } static u32 vfp_single_add(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm, u32 fpscr) { u32 exp_diff, m_sig; if (vsn->significand & 0x80000000 || vsm->significand & 0x80000000) { LOG_WARNING(Core_ARM11, "bad FP values"); vfp_single_dump("VSN", vsn); vfp_single_dump("VSM", vsm); } /* * Ensure that 'n' is the largest magnitude number. Note that * if 'n' and 'm' have equal exponents, we do not swap them. * This ensures that NaN propagation works correctly. */ if (vsn->exponent < vsm->exponent) { std::swap(vsm, vsn); } /* * Is 'n' an infinity or a NaN? Note that 'm' may be a number, * infinity or a NaN here. */ if (vsn->exponent == 255) return vfp_single_fadd_nonnumber(vsd, vsn, vsm, fpscr); /* * We have two proper numbers, where 'vsn' is the larger magnitude. * * Copy 'n' to 'd' before doing the arithmetic. */ *vsd = *vsn; /* * Align both numbers. */ exp_diff = vsn->exponent - vsm->exponent; m_sig = vfp_shiftright32jamming(vsm->significand, exp_diff); /* * If the signs are different, we are really subtracting. */ if (vsn->sign ^ vsm->sign) { m_sig = vsn->significand - m_sig; if ((s32)m_sig < 0) { vsd->sign = vfp_sign_negate(vsd->sign); m_sig = (~m_sig + 1); } else if (m_sig == 0) { vsd->sign = (fpscr & FPSCR_RMODE_MASK) == FPSCR_ROUND_MINUSINF ? 0x8000 : 0; } } else { m_sig = vsn->significand + m_sig; } vsd->significand = m_sig; return 0; } static u32 vfp_single_multiply(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm, u32 fpscr) { vfp_single_dump("VSN", vsn); vfp_single_dump("VSM", vsm); /* * Ensure that 'n' is the largest magnitude number. Note that * if 'n' and 'm' have equal exponents, we do not swap them. * This ensures that NaN propagation works correctly. */ if (vsn->exponent < vsm->exponent) { std::swap(vsm, vsn); LOG_TRACE(Core_ARM11, "swapping M <-> N"); } vsd->sign = vsn->sign ^ vsm->sign; /* * If 'n' is an infinity or NaN, handle it. 'm' may be anything. */ if (vsn->exponent == 255) { if (vsn->significand || (vsm->exponent == 255 && vsm->significand)) return vfp_propagate_nan(vsd, vsn, vsm, fpscr); if ((vsm->exponent | vsm->significand) == 0) { *vsd = vfp_single_default_qnan; return FPSCR_IOC; } vsd->exponent = vsn->exponent; vsd->significand = 0; return 0; } /* * If 'm' is zero, the result is always zero. In this case, * 'n' may be zero or a number, but it doesn't matter which. */ if ((vsm->exponent | vsm->significand) == 0) { vsd->exponent = 0; vsd->significand = 0; return 0; } /* * We add 2 to the destination exponent for the same reason as * the addition case - though this time we have +1 from each * input operand. */ vsd->exponent = vsn->exponent + vsm->exponent - 127 + 2; vsd->significand = vfp_hi64to32jamming((u64)vsn->significand * vsm->significand); vfp_single_dump("VSD", vsd); return 0; } #define NEG_MULTIPLY (1 << 0) #define NEG_SUBTRACT (1 << 1) static u32 vfp_single_multiply_accumulate(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr, u32 negate, const char* func) { vfp_single vsd, vsp, vsn, vsm; u32 exceptions = 0; s32 v; v = vfp_get_float(state, sn); LOG_TRACE(Core_ARM11, "s%u = %08x", sn, v); exceptions |= vfp_single_unpack(&vsn, v, fpscr); if (vsn.exponent == 0 && vsn.significand) vfp_single_normalise_denormal(&vsn); exceptions |= vfp_single_unpack(&vsm, m, fpscr); if (vsm.exponent == 0 && vsm.significand) vfp_single_normalise_denormal(&vsm); exceptions |= vfp_single_multiply(&vsp, &vsn, &vsm, fpscr); if (negate & NEG_MULTIPLY) vsp.sign = vfp_sign_negate(vsp.sign); v = vfp_get_float(state, sd); LOG_TRACE(Core_ARM11, "s%u = %08x", sd, v); exceptions |= vfp_single_unpack(&vsn, v, fpscr); if (vsn.exponent == 0 && vsn.significand != 0) vfp_single_normalise_denormal(&vsn); if (negate & NEG_SUBTRACT) vsn.sign = vfp_sign_negate(vsn.sign); exceptions |= vfp_single_add(&vsd, &vsn, &vsp, fpscr); exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, func); return exceptions; } /* * Standard operations */ /* * sd = sd + (sn * sm) */ static u32 vfp_single_fmac(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { u32 exceptions = 0; LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd); exceptions |= vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, 0, "fmac"); return exceptions; } /* * sd = sd - (sn * sm) */ static u32 vfp_single_fnmac(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { // TODO: this one has its arguments inverted, investigate. LOG_TRACE(Core_ARM11, "s%u = %08x", sd, sn); return vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, NEG_MULTIPLY, "fnmac"); } /* * sd = -sd + (sn * sm) */ static u32 vfp_single_fmsc(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd); return vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, NEG_SUBTRACT, "fmsc"); } /* * sd = -sd - (sn * sm) */ static u32 vfp_single_fnmsc(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd); return vfp_single_multiply_accumulate(state, sd, sn, m, fpscr, NEG_SUBTRACT | NEG_MULTIPLY, "fnmsc"); } /* * sd = sn * sm */ static u32 vfp_single_fmul(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { struct vfp_single vsd, vsn, vsm; u32 exceptions = 0; s32 n = vfp_get_float(state, sn); LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n); exceptions |= vfp_single_unpack(&vsn, n, fpscr); if (vsn.exponent == 0 && vsn.significand) vfp_single_normalise_denormal(&vsn); exceptions |= vfp_single_unpack(&vsm, m, fpscr); if (vsm.exponent == 0 && vsm.significand) vfp_single_normalise_denormal(&vsm); exceptions |= vfp_single_multiply(&vsd, &vsn, &vsm, fpscr); exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fmul"); return exceptions; } /* * sd = -(sn * sm) */ static u32 vfp_single_fnmul(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { struct vfp_single vsd, vsn, vsm; u32 exceptions = 0; s32 n = vfp_get_float(state, sn); LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n); exceptions |= vfp_single_unpack(&vsn, n, fpscr); if (vsn.exponent == 0 && vsn.significand) vfp_single_normalise_denormal(&vsn); exceptions |= vfp_single_unpack(&vsm, m, fpscr); if (vsm.exponent == 0 && vsm.significand) vfp_single_normalise_denormal(&vsm); exceptions |= vfp_single_multiply(&vsd, &vsn, &vsm, fpscr); vsd.sign = vfp_sign_negate(vsd.sign); exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fnmul"); return exceptions; } /* * sd = sn + sm */ static u32 vfp_single_fadd(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { struct vfp_single vsd, vsn, vsm; u32 exceptions = 0; s32 n = vfp_get_float(state, sn); LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n); /* * Unpack and normalise denormals. */ exceptions |= vfp_single_unpack(&vsn, n, fpscr); if (vsn.exponent == 0 && vsn.significand) vfp_single_normalise_denormal(&vsn); exceptions |= vfp_single_unpack(&vsm, m, fpscr); if (vsm.exponent == 0 && vsm.significand) vfp_single_normalise_denormal(&vsm); exceptions |= vfp_single_add(&vsd, &vsn, &vsm, fpscr); exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fadd"); return exceptions; } /* * sd = sn - sm */ static u32 vfp_single_fsub(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd); /* * Subtraction is addition with one sign inverted. */ if (m != 0x7FC00000) // Only negate if m isn't NaN. m = vfp_single_packed_negate(m); return vfp_single_fadd(state, sd, sn, m, fpscr); } /* * sd = sn / sm */ static u32 vfp_single_fdiv(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) { struct vfp_single vsd, vsn, vsm; u32 exceptions = 0; s32 n = vfp_get_float(state, sn); int tm, tn; LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n); exceptions |= vfp_single_unpack(&vsn, n, fpscr); exceptions |= vfp_single_unpack(&vsm, m, fpscr); vsd.sign = vsn.sign ^ vsm.sign; tn = vfp_single_type(&vsn); tm = vfp_single_type(&vsm); /* * Is n a NAN? */ if (tn & VFP_NAN) goto vsn_nan; /* * Is m a NAN? */ if (tm & VFP_NAN) goto vsm_nan; /* * If n and m are infinity, the result is invalid * If n and m are zero, the result is invalid */ if (tm & tn & (VFP_INFINITY | VFP_ZERO)) goto invalid; /* * If n is infinity, the result is infinity */ if (tn & VFP_INFINITY) goto infinity; /* * If m is zero, raise div0 exception */ if (tm & VFP_ZERO) goto divzero; /* * If m is infinity, or n is zero, the result is zero */ if (tm & VFP_INFINITY || tn & VFP_ZERO) goto zero; if (tn & VFP_DENORMAL) vfp_single_normalise_denormal(&vsn); if (tm & VFP_DENORMAL) vfp_single_normalise_denormal(&vsm); /* * Ok, we have two numbers, we can perform division. */ vsd.exponent = vsn.exponent - vsm.exponent + 127 - 1; vsm.significand <<= 1; if (vsm.significand <= (2 * vsn.significand)) { vsn.significand >>= 1; vsd.exponent++; } { u64 significand = (u64)vsn.significand << 32; do_div(significand, vsm.significand); vsd.significand = (u32)significand; } if ((vsd.significand & 0x3f) == 0) vsd.significand |= ((u64)vsm.significand * vsd.significand != (u64)vsn.significand << 32); exceptions |= vfp_single_normaliseround(state, sd, &vsd, fpscr, "fdiv"); return exceptions; vsn_nan: exceptions |= vfp_propagate_nan(&vsd, &vsn, &vsm, fpscr); pack: vfp_put_float(state, vfp_single_pack(&vsd), sd); return exceptions; vsm_nan: exceptions |= vfp_propagate_nan(&vsd, &vsm, &vsn, fpscr); goto pack; zero: vsd.exponent = 0; vsd.significand = 0; goto pack; divzero: exceptions |= FPSCR_DZC; infinity: vsd.exponent = 255; vsd.significand = 0; goto pack; invalid: vfp_put_float(state, vfp_single_pack(&vfp_single_default_qnan), sd); exceptions |= FPSCR_IOC; return exceptions; } static struct op fops[] = { {vfp_single_fmac, 0}, {vfp_single_fmsc, 0}, {vfp_single_fmul, 0}, {vfp_single_fadd, 0}, {vfp_single_fnmac, 0}, {vfp_single_fnmsc, 0}, {vfp_single_fnmul, 0}, {vfp_single_fsub, 0}, {vfp_single_fdiv, 0}, }; #define FREG_BANK(x) ((x)&0x18) #define FREG_IDX(x) ((x)&7) u32 vfp_single_cpdo(ARMul_State* state, u32 inst, u32 fpscr) { u32 op = inst & FOP_MASK; u32 exceptions = 0; unsigned int dest; unsigned int sn = vfp_get_sn(inst); unsigned int sm = vfp_get_sm(inst); unsigned int vecitr, veclen, vecstride; struct op* fop; vecstride = 1 + ((fpscr & FPSCR_STRIDE_MASK) == FPSCR_STRIDE_MASK); fop = (op == FOP_EXT) ? &fops_ext[FEXT_TO_IDX(inst)] : &fops[FOP_TO_IDX(op)]; /* * fcvtsd takes a dN register number as destination, not sN. * Technically, if bit 0 of dd is set, this is an invalid * instruction. However, we ignore this for efficiency. * It also only operates on scalars. */ if (fop->flags & OP_DD) dest = vfp_get_dd(inst); else dest = vfp_get_sd(inst); /* * If destination bank is zero, vector length is always '1'. * ARM DDI0100F C5.1.3, C5.3.2. */ if ((fop->flags & OP_SCALAR) || FREG_BANK(dest) == 0) veclen = 0; else veclen = fpscr & FPSCR_LENGTH_MASK; LOG_TRACE(Core_ARM11, "vecstride=%u veclen=%u", vecstride, (veclen >> FPSCR_LENGTH_BIT) + 1); if (!fop->fn) { LOG_CRITICAL(Core_ARM11, "could not find single op %d, inst=0x%x@0x%x", FEXT_TO_IDX(inst), inst, state->Reg[15]); Crash(); goto invalid; } for (vecitr = 0; vecitr <= veclen; vecitr += 1 << FPSCR_LENGTH_BIT) { s32 m = vfp_get_float(state, sm); u32 except; char type; type = (fop->flags & OP_DD) ? 'd' : 's'; if (op == FOP_EXT) LOG_TRACE(Core_ARM11, "itr%d (%c%u) = op[%u] (s%u=%08x)", vecitr >> FPSCR_LENGTH_BIT, type, dest, sn, sm, m); else LOG_TRACE(Core_ARM11, "itr%d (%c%u) = (s%u) op[%u] (s%u=%08x)", vecitr >> FPSCR_LENGTH_BIT, type, dest, sn, FOP_TO_IDX(op), sm, m); except = fop->fn(state, dest, sn, m, fpscr); LOG_TRACE(Core_ARM11, "itr%d: exceptions=%08x", vecitr >> FPSCR_LENGTH_BIT, except); exceptions |= except; /* * CHECK: It appears to be undefined whether we stop when * we encounter an exception. We continue. */ dest = FREG_BANK(dest) + ((FREG_IDX(dest) + vecstride) & 7); sn = FREG_BANK(sn) + ((FREG_IDX(sn) + vecstride) & 7); if (FREG_BANK(sm) != 0) sm = FREG_BANK(sm) + ((FREG_IDX(sm) + vecstride) & 7); } return exceptions; invalid: return (u32)-1; }
Kloen/citra
src/core/arm/skyeye_common/vfp/vfpsingle.cpp
C++
gpl-2.0
37,278
/* * QEMU i8255x (PRO100) emulation * * Copyright (C) 2006-2011 Stefan Weil * * Portions of the code are copies from grub / etherboot eepro100.c * and linux e100.c. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) version 3 or 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/>. * * Tested features (i82559): * PXE boot (i386 guest, i386 / mips / mipsel / ppc host) ok * Linux networking (i386) ok * * Untested: * Windows networking * * References: * * Intel 8255x 10/100 Mbps Ethernet Controller Family * Open Source Software Developer Manual * * TODO: * * PHY emulation should be separated from nic emulation. * Most nic emulations could share the same phy code. * * i82550 is untested. It is programmed like the i82559. * * i82562 is untested. It is programmed like the i82559. * * Power management (i82558 and later) is not implemented. * * Wake-on-LAN is not implemented. */ #include <stddef.h> /* offsetof */ #include "hw.h" #include "pci.h" #include "net.h" #include "eeprom93xx.h" #include "sysemu.h" #include "dma.h" /* QEMU sends frames smaller than 60 bytes to ethernet nics. * Such frames are rejected by real nics and their emulations. * To avoid this behaviour, other nic emulations pad received * frames. The following definition enables this padding for * eepro100, too. We keep the define around in case it might * become useful the future if the core networking is ever * changed to pad short packets itself. */ #define CONFIG_PAD_RECEIVED_FRAMES #define KiB 1024 /* Debug EEPRO100 card. */ #if 0 # define DEBUG_EEPRO100 #endif #ifdef DEBUG_EEPRO100 #define logout(fmt, ...) fprintf(stderr, "EE100\t%-24s" fmt, __func__, ## __VA_ARGS__) #else #define logout(fmt, ...) ((void)0) #endif /* Set flags to 0 to disable debug output. */ #define INT 1 /* interrupt related actions */ #define MDI 1 /* mdi related actions */ #define OTHER 1 #define RXTX 1 #define EEPROM 1 /* eeprom related actions */ #define TRACE(flag, command) ((flag) ? (command) : (void)0) #define missing(text) fprintf(stderr, "eepro100: feature is missing in this emulation: " text "\n") #define MAX_ETH_FRAME_SIZE 1514 /* This driver supports several different devices which are declared here. */ #define i82550 0x82550 #define i82551 0x82551 #define i82557A 0x82557a #define i82557B 0x82557b #define i82557C 0x82557c #define i82558A 0x82558a #define i82558B 0x82558b #define i82559A 0x82559a #define i82559B 0x82559b #define i82559C 0x82559c #define i82559ER 0x82559e #define i82562 0x82562 #define i82801 0x82801 /* Use 64 word EEPROM. TODO: could be a runtime option. */ #define EEPROM_SIZE 64 #define PCI_MEM_SIZE (4 * KiB) #define PCI_IO_SIZE 64 #define PCI_FLASH_SIZE (128 * KiB) #define BIT(n) (1 << (n)) #define BITS(n, m) (((0xffffffffU << (31 - n)) >> (31 - n + m)) << m) /* The SCB accepts the following controls for the Tx and Rx units: */ #define CU_NOP 0x0000 /* No operation. */ #define CU_START 0x0010 /* CU start. */ #define CU_RESUME 0x0020 /* CU resume. */ #define CU_STATSADDR 0x0040 /* Load dump counters address. */ #define CU_SHOWSTATS 0x0050 /* Dump statistical counters. */ #define CU_CMD_BASE 0x0060 /* Load CU base address. */ #define CU_DUMPSTATS 0x0070 /* Dump and reset statistical counters. */ #define CU_SRESUME 0x00a0 /* CU static resume. */ #define RU_NOP 0x0000 #define RX_START 0x0001 #define RX_RESUME 0x0002 #define RU_ABORT 0x0004 #define RX_ADDR_LOAD 0x0006 #define RX_RESUMENR 0x0007 #define INT_MASK 0x0100 #define DRVR_INT 0x0200 /* Driver generated interrupt. */ typedef struct { const char *name; const char *desc; uint16_t device_id; uint8_t revision; uint16_t subsystem_vendor_id; uint16_t subsystem_id; uint32_t device; uint8_t stats_size; bool has_extended_tcb_support; bool power_management; } E100PCIDeviceInfo; /* Offsets to the various registers. All accesses need not be longword aligned. */ typedef enum { SCBStatus = 0, /* Status Word. */ SCBAck = 1, SCBCmd = 2, /* Rx/Command Unit command and status. */ SCBIntmask = 3, SCBPointer = 4, /* General purpose pointer. */ SCBPort = 8, /* Misc. commands and operands. */ SCBflash = 12, /* Flash memory control. */ SCBeeprom = 14, /* EEPROM control. */ SCBCtrlMDI = 16, /* MDI interface control. */ SCBEarlyRx = 20, /* Early receive byte count. */ SCBFlow = 24, /* Flow Control. */ SCBpmdr = 27, /* Power Management Driver. */ SCBgctrl = 28, /* General Control. */ SCBgstat = 29, /* General Status. */ } E100RegisterOffset; /* A speedo3 transmit buffer descriptor with two buffers... */ typedef struct { uint16_t status; uint16_t command; uint32_t link; /* void * */ uint32_t tbd_array_addr; /* transmit buffer descriptor array address. */ uint16_t tcb_bytes; /* transmit command block byte count (in lower 14 bits */ uint8_t tx_threshold; /* transmit threshold */ uint8_t tbd_count; /* TBD number */ #if 0 /* This constitutes two "TBD" entries: hdr and data */ uint32_t tx_buf_addr0; /* void *, header of frame to be transmitted. */ int32_t tx_buf_size0; /* Length of Tx hdr. */ uint32_t tx_buf_addr1; /* void *, data to be transmitted. */ int32_t tx_buf_size1; /* Length of Tx data. */ #endif } eepro100_tx_t; /* Receive frame descriptor. */ typedef struct { int16_t status; uint16_t command; uint32_t link; /* struct RxFD * */ uint32_t rx_buf_addr; /* void * */ uint16_t count; uint16_t size; /* Ethernet frame data follows. */ } eepro100_rx_t; typedef enum { COMMAND_EL = BIT(15), COMMAND_S = BIT(14), COMMAND_I = BIT(13), COMMAND_NC = BIT(4), COMMAND_SF = BIT(3), COMMAND_CMD = BITS(2, 0), } scb_command_bit; typedef enum { STATUS_C = BIT(15), STATUS_OK = BIT(13), } scb_status_bit; typedef struct { uint32_t tx_good_frames, tx_max_collisions, tx_late_collisions, tx_underruns, tx_lost_crs, tx_deferred, tx_single_collisions, tx_multiple_collisions, tx_total_collisions; uint32_t rx_good_frames, rx_crc_errors, rx_alignment_errors, rx_resource_errors, rx_overrun_errors, rx_cdt_errors, rx_short_frame_errors; uint32_t fc_xmt_pause, fc_rcv_pause, fc_rcv_unsupported; uint16_t xmt_tco_frames, rcv_tco_frames; /* TODO: i82559 has six reserved statistics but a total of 24 dwords. */ uint32_t reserved[4]; } eepro100_stats_t; typedef enum { cu_idle = 0, cu_suspended = 1, cu_active = 2, cu_lpq_active = 2, cu_hqp_active = 3 } cu_state_t; typedef enum { ru_idle = 0, ru_suspended = 1, ru_no_resources = 2, ru_ready = 4 } ru_state_t; typedef struct { PCIDevice dev; /* Hash register (multicast mask array, multiple individual addresses). */ uint8_t mult[8]; MemoryRegion mmio_bar; MemoryRegion io_bar; MemoryRegion flash_bar; NICState *nic; NICConf conf; uint8_t scb_stat; /* SCB stat/ack byte */ uint8_t int_stat; /* PCI interrupt status */ /* region must not be saved by nic_save. */ uint16_t mdimem[32]; eeprom_t *eeprom; uint32_t device; /* device variant */ /* (cu_base + cu_offset) address the next command block in the command block list. */ uint32_t cu_base; /* CU base address */ uint32_t cu_offset; /* CU address offset */ /* (ru_base + ru_offset) address the RFD in the Receive Frame Area. */ uint32_t ru_base; /* RU base address */ uint32_t ru_offset; /* RU address offset */ uint32_t statsaddr; /* pointer to eepro100_stats_t */ /* Temporary status information (no need to save these values), * used while processing CU commands. */ eepro100_tx_t tx; /* transmit buffer descriptor */ uint32_t cb_address; /* = cu_base + cu_offset */ /* Statistical counters. Also used for wake-up packet (i82559). */ eepro100_stats_t statistics; /* Data in mem is always in the byte order of the controller (le). * It must be dword aligned to allow direct access to 32 bit values. */ uint8_t mem[PCI_MEM_SIZE] __attribute__((aligned(8))); /* Configuration bytes. */ uint8_t configuration[22]; /* vmstate for each particular nic */ VMStateDescription *vmstate; /* Quasi static device properties (no need to save them). */ uint16_t stats_size; bool has_extended_tcb_support; } EEPRO100State; /* Word indices in EEPROM. */ typedef enum { EEPROM_CNFG_MDIX = 0x03, EEPROM_ID = 0x05, EEPROM_PHY_ID = 0x06, EEPROM_VENDOR_ID = 0x0c, EEPROM_CONFIG_ASF = 0x0d, EEPROM_DEVICE_ID = 0x23, EEPROM_SMBUS_ADDR = 0x90, } EEPROMOffset; /* Bit values for EEPROM ID word. */ typedef enum { EEPROM_ID_MDM = BIT(0), /* Modem */ EEPROM_ID_STB = BIT(1), /* Standby Enable */ EEPROM_ID_WMR = BIT(2), /* ??? */ EEPROM_ID_WOL = BIT(5), /* Wake on LAN */ EEPROM_ID_DPD = BIT(6), /* Deep Power Down */ EEPROM_ID_ALT = BIT(7), /* */ /* BITS(10, 8) device revision */ EEPROM_ID_BD = BIT(11), /* boot disable */ EEPROM_ID_ID = BIT(13), /* id bit */ /* BITS(15, 14) signature */ EEPROM_ID_VALID = BIT(14), /* signature for valid eeprom */ } eeprom_id_bit; /* Default values for MDI (PHY) registers */ static const uint16_t eepro100_mdi_default[] = { /* MDI Registers 0 - 6, 7 */ 0x3000, 0x780d, 0x02a8, 0x0154, 0x05e1, 0x0000, 0x0000, 0x0000, /* MDI Registers 8 - 15 */ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, /* MDI Registers 16 - 31 */ 0x0003, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; /* Readonly mask for MDI (PHY) registers */ static const uint16_t eepro100_mdi_mask[] = { 0x0000, 0xffff, 0xffff, 0xffff, 0xc01f, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0fff, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, }; #define POLYNOMIAL 0x04c11db6 static E100PCIDeviceInfo *eepro100_get_class(EEPRO100State *s); /* From FreeBSD (locally modified). */ static unsigned e100_compute_mcast_idx(const uint8_t *ep) { uint32_t crc; int carry, i, j; uint8_t b; crc = 0xffffffff; for (i = 0; i < 6; i++) { b = *ep++; for (j = 0; j < 8; j++) { carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01); crc <<= 1; b >>= 1; if (carry) { crc = ((crc ^ POLYNOMIAL) | carry); } } } return (crc & BITS(7, 2)) >> 2; } /* Read a 16 bit control/status (CSR) register. */ static uint16_t e100_read_reg2(EEPRO100State *s, E100RegisterOffset addr) { assert(!((uintptr_t)&s->mem[addr] & 1)); return le16_to_cpup((uint16_t *)&s->mem[addr]); } /* Read a 32 bit control/status (CSR) register. */ static uint32_t e100_read_reg4(EEPRO100State *s, E100RegisterOffset addr) { assert(!((uintptr_t)&s->mem[addr] & 3)); return le32_to_cpup((uint32_t *)&s->mem[addr]); } /* Write a 16 bit control/status (CSR) register. */ static void e100_write_reg2(EEPRO100State *s, E100RegisterOffset addr, uint16_t val) { assert(!((uintptr_t)&s->mem[addr] & 1)); cpu_to_le16w((uint16_t *)&s->mem[addr], val); } /* Read a 32 bit control/status (CSR) register. */ static void e100_write_reg4(EEPRO100State *s, E100RegisterOffset addr, uint32_t val) { assert(!((uintptr_t)&s->mem[addr] & 3)); cpu_to_le32w((uint32_t *)&s->mem[addr], val); } #if defined(DEBUG_EEPRO100) static const char *nic_dump(const uint8_t * buf, unsigned size) { static char dump[3 * 16 + 1]; char *p = &dump[0]; if (size > 16) { size = 16; } while (size-- > 0) { p += sprintf(p, " %02x", *buf++); } return dump; } #endif /* DEBUG_EEPRO100 */ enum scb_stat_ack { stat_ack_not_ours = 0x00, stat_ack_sw_gen = 0x04, stat_ack_rnr = 0x10, stat_ack_cu_idle = 0x20, stat_ack_frame_rx = 0x40, stat_ack_cu_cmd_done = 0x80, stat_ack_not_present = 0xFF, stat_ack_rx = (stat_ack_sw_gen | stat_ack_rnr | stat_ack_frame_rx), stat_ack_tx = (stat_ack_cu_idle | stat_ack_cu_cmd_done), }; static void disable_interrupt(EEPRO100State * s) { if (s->int_stat) { TRACE(INT, logout("interrupt disabled\n")); qemu_irq_lower(s->dev.irq[0]); s->int_stat = 0; } } static void enable_interrupt(EEPRO100State * s) { if (!s->int_stat) { TRACE(INT, logout("interrupt enabled\n")); qemu_irq_raise(s->dev.irq[0]); s->int_stat = 1; } } static void eepro100_acknowledge(EEPRO100State * s) { s->scb_stat &= ~s->mem[SCBAck]; s->mem[SCBAck] = s->scb_stat; if (s->scb_stat == 0) { disable_interrupt(s); } } static void eepro100_interrupt(EEPRO100State * s, uint8_t status) { uint8_t mask = ~s->mem[SCBIntmask]; s->mem[SCBAck] |= status; status = s->scb_stat = s->mem[SCBAck]; status &= (mask | 0x0f); #if 0 status &= (~s->mem[SCBIntmask] | 0x0xf); #endif if (status && (mask & 0x01)) { /* SCB mask and SCB Bit M do not disable interrupt. */ enable_interrupt(s); } else if (s->int_stat) { disable_interrupt(s); } } static void eepro100_cx_interrupt(EEPRO100State * s) { /* CU completed action command. */ /* Transmit not ok (82557 only, not in emulation). */ eepro100_interrupt(s, 0x80); } static void eepro100_cna_interrupt(EEPRO100State * s) { /* CU left the active state. */ eepro100_interrupt(s, 0x20); } static void eepro100_fr_interrupt(EEPRO100State * s) { /* RU received a complete frame. */ eepro100_interrupt(s, 0x40); } static void eepro100_rnr_interrupt(EEPRO100State * s) { /* RU is not ready. */ eepro100_interrupt(s, 0x10); } static void eepro100_mdi_interrupt(EEPRO100State * s) { /* MDI completed read or write cycle. */ eepro100_interrupt(s, 0x08); } static void eepro100_swi_interrupt(EEPRO100State * s) { /* Software has requested an interrupt. */ eepro100_interrupt(s, 0x04); } #if 0 static void eepro100_fcp_interrupt(EEPRO100State * s) { /* Flow control pause interrupt (82558 and later). */ eepro100_interrupt(s, 0x01); } #endif static void e100_pci_reset(EEPRO100State * s) { E100PCIDeviceInfo *info = eepro100_get_class(s); uint32_t device = s->device; uint8_t *pci_conf = s->dev.config; TRACE(OTHER, logout("%p\n", s)); /* PCI Status */ pci_set_word(pci_conf + PCI_STATUS, PCI_STATUS_DEVSEL_MEDIUM | PCI_STATUS_FAST_BACK); /* PCI Latency Timer */ pci_set_byte(pci_conf + PCI_LATENCY_TIMER, 0x20); /* latency timer = 32 clocks */ /* Capability Pointer is set by PCI framework. */ /* Interrupt Line */ /* Interrupt Pin */ pci_set_byte(pci_conf + PCI_INTERRUPT_PIN, 1); /* interrupt pin A */ /* Minimum Grant */ pci_set_byte(pci_conf + PCI_MIN_GNT, 0x08); /* Maximum Latency */ pci_set_byte(pci_conf + PCI_MAX_LAT, 0x18); s->stats_size = info->stats_size; s->has_extended_tcb_support = info->has_extended_tcb_support; switch (device) { case i82550: case i82551: case i82557A: case i82557B: case i82557C: case i82558A: case i82558B: case i82559A: case i82559B: case i82559ER: case i82562: case i82801: case i82559C: break; default: logout("Device %X is undefined!\n", device); } /* Standard TxCB. */ s->configuration[6] |= BIT(4); /* Standard statistical counters. */ s->configuration[6] |= BIT(5); if (s->stats_size == 80) { /* TODO: check TCO Statistical Counters bit. Documentation not clear. */ if (s->configuration[6] & BIT(2)) { /* TCO statistical counters. */ assert(s->configuration[6] & BIT(5)); } else { if (s->configuration[6] & BIT(5)) { /* No extended statistical counters, i82557 compatible. */ s->stats_size = 64; } else { /* i82558 compatible. */ s->stats_size = 76; } } } else { if (s->configuration[6] & BIT(5)) { /* No extended statistical counters. */ s->stats_size = 64; } } assert(s->stats_size > 0 && s->stats_size <= sizeof(s->statistics)); if (info->power_management) { /* Power Management Capabilities */ int cfg_offset = 0xdc; int r = pci_add_capability(&s->dev, PCI_CAP_ID_PM, cfg_offset, PCI_PM_SIZEOF); assert(r >= 0); pci_set_word(pci_conf + cfg_offset + PCI_PM_PMC, 0x7e21); #if 0 /* TODO: replace dummy code for power management emulation. */ /* TODO: Power Management Control / Status. */ pci_set_word(pci_conf + cfg_offset + PCI_PM_CTRL, 0x0000); /* TODO: Ethernet Power Consumption Registers (i82559 and later). */ pci_set_byte(pci_conf + cfg_offset + PCI_PM_PPB_EXTENSIONS, 0x0000); #endif } #if EEPROM_SIZE > 0 if (device == i82557C || device == i82558B || device == i82559C) { /* TODO: get vendor id from EEPROM for i82557C or later. TODO: get device id from EEPROM for i82557C or later. TODO: status bit 4 can be disabled by EEPROM for i82558, i82559. TODO: header type is determined by EEPROM for i82559. TODO: get subsystem id from EEPROM for i82557C or later. TODO: get subsystem vendor id from EEPROM for i82557C or later. TODO: exp. rom baddr depends on a bit in EEPROM for i82558 or later. TODO: capability pointer depends on EEPROM for i82558. */ logout("Get device id and revision from EEPROM!!!\n"); } #endif /* EEPROM_SIZE > 0 */ } static void nic_selective_reset(EEPRO100State * s) { size_t i; uint16_t *eeprom_contents = eeprom93xx_data(s->eeprom); #if 0 eeprom93xx_reset(s->eeprom); #endif memcpy(eeprom_contents, s->conf.macaddr.a, 6); eeprom_contents[EEPROM_ID] = EEPROM_ID_VALID; if (s->device == i82557B || s->device == i82557C) eeprom_contents[5] = 0x0100; eeprom_contents[EEPROM_PHY_ID] = 1; uint16_t sum = 0; for (i = 0; i < EEPROM_SIZE - 1; i++) { sum += eeprom_contents[i]; } eeprom_contents[EEPROM_SIZE - 1] = 0xbaba - sum; TRACE(EEPROM, logout("checksum=0x%04x\n", eeprom_contents[EEPROM_SIZE - 1])); memset(s->mem, 0, sizeof(s->mem)); e100_write_reg4(s, SCBCtrlMDI, BIT(21)); assert(sizeof(s->mdimem) == sizeof(eepro100_mdi_default)); memcpy(&s->mdimem[0], &eepro100_mdi_default[0], sizeof(s->mdimem)); } static void nic_reset(void *opaque) { EEPRO100State *s = opaque; TRACE(OTHER, logout("%p\n", s)); /* TODO: Clearing of hash register for selective reset, too? */ memset(&s->mult[0], 0, sizeof(s->mult)); nic_selective_reset(s); } #if defined(DEBUG_EEPRO100) static const char * const e100_reg[PCI_IO_SIZE / 4] = { "Command/Status", "General Pointer", "Port", "EEPROM/Flash Control", "MDI Control", "Receive DMA Byte Count", "Flow Control", "General Status/Control" }; static char *regname(uint32_t addr) { static char buf[32]; if (addr < PCI_IO_SIZE) { const char *r = e100_reg[addr / 4]; if (r != 0) { snprintf(buf, sizeof(buf), "%s+%u", r, addr % 4); } else { snprintf(buf, sizeof(buf), "0x%02x", addr); } } else { snprintf(buf, sizeof(buf), "??? 0x%08x", addr); } return buf; } #endif /* DEBUG_EEPRO100 */ /***************************************************************************** * * Command emulation. * ****************************************************************************/ #if 0 static uint16_t eepro100_read_command(EEPRO100State * s) { uint16_t val = 0xffff; TRACE(OTHER, logout("val=0x%04x\n", val)); return val; } #endif /* Commands that can be put in a command list entry. */ enum commands { CmdNOp = 0, CmdIASetup = 1, CmdConfigure = 2, CmdMulticastList = 3, CmdTx = 4, CmdTDR = 5, /* load microcode */ CmdDump = 6, CmdDiagnose = 7, /* And some extra flags: */ CmdSuspend = 0x4000, /* Suspend after completion. */ CmdIntr = 0x2000, /* Interrupt after completion. */ CmdTxFlex = 0x0008, /* Use "Flexible mode" for CmdTx command. */ }; static cu_state_t get_cu_state(EEPRO100State * s) { return ((s->mem[SCBStatus] & BITS(7, 6)) >> 6); } static void set_cu_state(EEPRO100State * s, cu_state_t state) { s->mem[SCBStatus] = (s->mem[SCBStatus] & ~BITS(7, 6)) + (state << 6); } static ru_state_t get_ru_state(EEPRO100State * s) { return ((s->mem[SCBStatus] & BITS(5, 2)) >> 2); } static void set_ru_state(EEPRO100State * s, ru_state_t state) { s->mem[SCBStatus] = (s->mem[SCBStatus] & ~BITS(5, 2)) + (state << 2); } static void dump_statistics(EEPRO100State * s) { /* Dump statistical data. Most data is never changed by the emulation * and always 0, so we first just copy the whole block and then those * values which really matter. * Number of data should check configuration!!! */ pci_dma_write(&s->dev, s->statsaddr, &s->statistics, s->stats_size); stl_le_pci_dma(&s->dev, s->statsaddr + 0, s->statistics.tx_good_frames); stl_le_pci_dma(&s->dev, s->statsaddr + 36, s->statistics.rx_good_frames); stl_le_pci_dma(&s->dev, s->statsaddr + 48, s->statistics.rx_resource_errors); stl_le_pci_dma(&s->dev, s->statsaddr + 60, s->statistics.rx_short_frame_errors); #if 0 stw_le_pci_dma(&s->dev, s->statsaddr + 76, s->statistics.xmt_tco_frames); stw_le_pci_dma(&s->dev, s->statsaddr + 78, s->statistics.rcv_tco_frames); missing("CU dump statistical counters"); #endif } static void read_cb(EEPRO100State *s) { pci_dma_read(&s->dev, s->cb_address, &s->tx, sizeof(s->tx)); s->tx.status = le16_to_cpu(s->tx.status); s->tx.command = le16_to_cpu(s->tx.command); s->tx.link = le32_to_cpu(s->tx.link); s->tx.tbd_array_addr = le32_to_cpu(s->tx.tbd_array_addr); s->tx.tcb_bytes = le16_to_cpu(s->tx.tcb_bytes); } static void tx_command(EEPRO100State *s) { uint32_t tbd_array = le32_to_cpu(s->tx.tbd_array_addr); uint16_t tcb_bytes = (le16_to_cpu(s->tx.tcb_bytes) & 0x3fff); /* Sends larger than MAX_ETH_FRAME_SIZE are allowed, up to 2600 bytes. */ uint8_t buf[2600]; uint16_t size = 0; uint32_t tbd_address = s->cb_address + 0x10; TRACE(RXTX, logout ("transmit, TBD array address 0x%08x, TCB byte count 0x%04x, TBD count %u\n", tbd_array, tcb_bytes, s->tx.tbd_count)); if (tcb_bytes > 2600) { logout("TCB byte count too large, using 2600\n"); tcb_bytes = 2600; } if (!((tcb_bytes > 0) || (tbd_array != 0xffffffff))) { logout ("illegal values of TBD array address and TCB byte count!\n"); } assert(tcb_bytes <= sizeof(buf)); while (size < tcb_bytes) { uint32_t tx_buffer_address = ldl_le_pci_dma(&s->dev, tbd_address); uint16_t tx_buffer_size = lduw_le_pci_dma(&s->dev, tbd_address + 4); #if 0 uint16_t tx_buffer_el = lduw_le_pci_dma(&s->dev, tbd_address + 6); #endif tbd_address += 8; TRACE(RXTX, logout ("TBD (simplified mode): buffer address 0x%08x, size 0x%04x\n", tx_buffer_address, tx_buffer_size)); tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size); pci_dma_read(&s->dev, tx_buffer_address, &buf[size], tx_buffer_size); size += tx_buffer_size; } if (tbd_array == 0xffffffff) { /* Simplified mode. Was already handled by code above. */ } else { /* Flexible mode. */ uint8_t tbd_count = 0; if (s->has_extended_tcb_support && !(s->configuration[6] & BIT(4))) { /* Extended Flexible TCB. */ for (; tbd_count < 2; tbd_count++) { uint32_t tx_buffer_address = ldl_le_pci_dma(&s->dev, tbd_address); uint16_t tx_buffer_size = lduw_le_pci_dma(&s->dev, tbd_address + 4); uint16_t tx_buffer_el = lduw_le_pci_dma(&s->dev, tbd_address + 6); tbd_address += 8; TRACE(RXTX, logout ("TBD (extended flexible mode): buffer address 0x%08x, size 0x%04x\n", tx_buffer_address, tx_buffer_size)); tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size); pci_dma_read(&s->dev, tx_buffer_address, &buf[size], tx_buffer_size); size += tx_buffer_size; if (tx_buffer_el & 1) { break; } } } tbd_address = tbd_array; for (; tbd_count < s->tx.tbd_count; tbd_count++) { uint32_t tx_buffer_address = ldl_le_pci_dma(&s->dev, tbd_address); uint16_t tx_buffer_size = lduw_le_pci_dma(&s->dev, tbd_address + 4); uint16_t tx_buffer_el = lduw_le_pci_dma(&s->dev, tbd_address + 6); tbd_address += 8; TRACE(RXTX, logout ("TBD (flexible mode): buffer address 0x%08x, size 0x%04x\n", tx_buffer_address, tx_buffer_size)); tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size); pci_dma_read(&s->dev, tx_buffer_address, &buf[size], tx_buffer_size); size += tx_buffer_size; if (tx_buffer_el & 1) { break; } } } TRACE(RXTX, logout("%p sending frame, len=%d,%s\n", s, size, nic_dump(buf, size))); qemu_send_packet(&s->nic->nc, buf, size); s->statistics.tx_good_frames++; /* Transmit with bad status would raise an CX/TNO interrupt. * (82557 only). Emulation never has bad status. */ #if 0 eepro100_cx_interrupt(s); #endif } static void set_multicast_list(EEPRO100State *s) { uint16_t multicast_count = s->tx.tbd_array_addr & BITS(13, 0); uint16_t i; memset(&s->mult[0], 0, sizeof(s->mult)); TRACE(OTHER, logout("multicast list, multicast count = %u\n", multicast_count)); for (i = 0; i < multicast_count; i += 6) { uint8_t multicast_addr[6]; pci_dma_read(&s->dev, s->cb_address + 10 + i, multicast_addr, 6); TRACE(OTHER, logout("multicast entry %s\n", nic_dump(multicast_addr, 6))); unsigned mcast_idx = e100_compute_mcast_idx(multicast_addr); assert(mcast_idx < 64); s->mult[mcast_idx >> 3] |= (1 << (mcast_idx & 7)); } } static void action_command(EEPRO100State *s) { for (;;) { bool bit_el; bool bit_s; bool bit_i; bool bit_nc; uint16_t ok_status = STATUS_OK; s->cb_address = s->cu_base + s->cu_offset; read_cb(s); bit_el = ((s->tx.command & COMMAND_EL) != 0); bit_s = ((s->tx.command & COMMAND_S) != 0); bit_i = ((s->tx.command & COMMAND_I) != 0); bit_nc = ((s->tx.command & COMMAND_NC) != 0); #if 0 bool bit_sf = ((s->tx.command & COMMAND_SF) != 0); #endif s->cu_offset = s->tx.link; TRACE(OTHER, logout("val=(cu start), status=0x%04x, command=0x%04x, link=0x%08x\n", s->tx.status, s->tx.command, s->tx.link)); switch (s->tx.command & COMMAND_CMD) { case CmdNOp: /* Do nothing. */ break; case CmdIASetup: pci_dma_read(&s->dev, s->cb_address + 8, &s->conf.macaddr.a[0], 6); TRACE(OTHER, logout("macaddr: %s\n", nic_dump(&s->conf.macaddr.a[0], 6))); break; case CmdConfigure: pci_dma_read(&s->dev, s->cb_address + 8, &s->configuration[0], sizeof(s->configuration)); TRACE(OTHER, logout("configuration: %s\n", nic_dump(&s->configuration[0], 16))); TRACE(OTHER, logout("configuration: %s\n", nic_dump(&s->configuration[16], ARRAY_SIZE(s->configuration) - 16))); if (s->configuration[20] & BIT(6)) { TRACE(OTHER, logout("Multiple IA bit\n")); } break; case CmdMulticastList: set_multicast_list(s); break; case CmdTx: if (bit_nc) { missing("CmdTx: NC = 0"); ok_status = 0; break; } tx_command(s); break; case CmdTDR: TRACE(OTHER, logout("load microcode\n")); /* Starting with offset 8, the command contains * 64 dwords microcode which we just ignore here. */ break; case CmdDiagnose: TRACE(OTHER, logout("diagnose\n")); /* Make sure error flag is not set. */ s->tx.status = 0; break; default: missing("undefined command"); ok_status = 0; break; } /* Write new status. */ stw_le_pci_dma(&s->dev, s->cb_address, s->tx.status | ok_status | STATUS_C); if (bit_i) { /* CU completed action. */ eepro100_cx_interrupt(s); } if (bit_el) { /* CU becomes idle. Terminate command loop. */ set_cu_state(s, cu_idle); eepro100_cna_interrupt(s); break; } else if (bit_s) { /* CU becomes suspended. Terminate command loop. */ set_cu_state(s, cu_suspended); eepro100_cna_interrupt(s); break; } else { /* More entries in list. */ TRACE(OTHER, logout("CU list with at least one more entry\n")); } } TRACE(OTHER, logout("CU list empty\n")); /* List is empty. Now CU is idle or suspended. */ } static void eepro100_cu_command(EEPRO100State * s, uint8_t val) { cu_state_t cu_state; switch (val) { case CU_NOP: /* No operation. */ break; case CU_START: cu_state = get_cu_state(s); if (cu_state != cu_idle && cu_state != cu_suspended) { /* Intel documentation says that CU must be idle or suspended * for the CU start command. */ logout("unexpected CU state is %u\n", cu_state); } set_cu_state(s, cu_active); s->cu_offset = e100_read_reg4(s, SCBPointer); action_command(s); break; case CU_RESUME: if (get_cu_state(s) != cu_suspended) { logout("bad CU resume from CU state %u\n", get_cu_state(s)); /* Workaround for bad Linux eepro100 driver which resumes * from idle state. */ #if 0 missing("cu resume"); #endif set_cu_state(s, cu_suspended); } if (get_cu_state(s) == cu_suspended) { TRACE(OTHER, logout("CU resuming\n")); set_cu_state(s, cu_active); action_command(s); } break; case CU_STATSADDR: /* Load dump counters address. */ s->statsaddr = e100_read_reg4(s, SCBPointer); TRACE(OTHER, logout("val=0x%02x (dump counters address)\n", val)); if (s->statsaddr & 3) { /* Memory must be Dword aligned. */ logout("unaligned dump counters address\n"); /* Handling of misaligned addresses is undefined. * Here we align the address by ignoring the lower bits. */ /* TODO: Test unaligned dump counter address on real hardware. */ s->statsaddr &= ~3; } break; case CU_SHOWSTATS: /* Dump statistical counters. */ TRACE(OTHER, logout("val=0x%02x (dump stats)\n", val)); dump_statistics(s); stl_le_pci_dma(&s->dev, s->statsaddr + s->stats_size, 0xa005); break; case CU_CMD_BASE: /* Load CU base. */ TRACE(OTHER, logout("val=0x%02x (CU base address)\n", val)); s->cu_base = e100_read_reg4(s, SCBPointer); break; case CU_DUMPSTATS: /* Dump and reset statistical counters. */ TRACE(OTHER, logout("val=0x%02x (dump stats and reset)\n", val)); dump_statistics(s); stl_le_pci_dma(&s->dev, s->statsaddr + s->stats_size, 0xa007); memset(&s->statistics, 0, sizeof(s->statistics)); break; case CU_SRESUME: /* CU static resume. */ missing("CU static resume"); break; default: missing("Undefined CU command"); } } static void eepro100_ru_command(EEPRO100State * s, uint8_t val) { switch (val) { case RU_NOP: /* No operation. */ break; case RX_START: /* RU start. */ if (get_ru_state(s) != ru_idle) { logout("RU state is %u, should be %u\n", get_ru_state(s), ru_idle); #if 0 assert(!"wrong RU state"); #endif } set_ru_state(s, ru_ready); s->ru_offset = e100_read_reg4(s, SCBPointer); qemu_flush_queued_packets(&s->nic->nc); TRACE(OTHER, logout("val=0x%02x (rx start)\n", val)); break; case RX_RESUME: /* Restart RU. */ if (get_ru_state(s) != ru_suspended) { logout("RU state is %u, should be %u\n", get_ru_state(s), ru_suspended); #if 0 assert(!"wrong RU state"); #endif } set_ru_state(s, ru_ready); break; case RU_ABORT: /* RU abort. */ if (get_ru_state(s) == ru_ready) { eepro100_rnr_interrupt(s); } set_ru_state(s, ru_idle); break; case RX_ADDR_LOAD: /* Load RU base. */ TRACE(OTHER, logout("val=0x%02x (RU base address)\n", val)); s->ru_base = e100_read_reg4(s, SCBPointer); break; default: logout("val=0x%02x (undefined RU command)\n", val); missing("Undefined SU command"); } } static void eepro100_write_command(EEPRO100State * s, uint8_t val) { eepro100_ru_command(s, val & 0x0f); eepro100_cu_command(s, val & 0xf0); if ((val) == 0) { TRACE(OTHER, logout("val=0x%02x\n", val)); } /* Clear command byte after command was accepted. */ s->mem[SCBCmd] = 0; } /***************************************************************************** * * EEPROM emulation. * ****************************************************************************/ #define EEPROM_CS 0x02 #define EEPROM_SK 0x01 #define EEPROM_DI 0x04 #define EEPROM_DO 0x08 static uint16_t eepro100_read_eeprom(EEPRO100State * s) { uint16_t val = e100_read_reg2(s, SCBeeprom); if (eeprom93xx_read(s->eeprom)) { val |= EEPROM_DO; } else { val &= ~EEPROM_DO; } TRACE(EEPROM, logout("val=0x%04x\n", val)); return val; } static void eepro100_write_eeprom(eeprom_t * eeprom, uint8_t val) { TRACE(EEPROM, logout("val=0x%02x\n", val)); /* mask unwritable bits */ #if 0 val = SET_MASKED(val, 0x31, eeprom->value); #endif int eecs = ((val & EEPROM_CS) != 0); int eesk = ((val & EEPROM_SK) != 0); int eedi = ((val & EEPROM_DI) != 0); eeprom93xx_write(eeprom, eecs, eesk, eedi); } /***************************************************************************** * * MDI emulation. * ****************************************************************************/ #if defined(DEBUG_EEPRO100) static const char * const mdi_op_name[] = { "opcode 0", "write", "read", "opcode 3" }; static const char * const mdi_reg_name[] = { "Control", "Status", "PHY Identification (Word 1)", "PHY Identification (Word 2)", "Auto-Negotiation Advertisement", "Auto-Negotiation Link Partner Ability", "Auto-Negotiation Expansion" }; static const char *reg2name(uint8_t reg) { static char buffer[10]; const char *p = buffer; if (reg < ARRAY_SIZE(mdi_reg_name)) { p = mdi_reg_name[reg]; } else { snprintf(buffer, sizeof(buffer), "reg=0x%02x", reg); } return p; } #endif /* DEBUG_EEPRO100 */ static uint32_t eepro100_read_mdi(EEPRO100State * s) { uint32_t val = e100_read_reg4(s, SCBCtrlMDI); #ifdef DEBUG_EEPRO100 uint8_t raiseint = (val & BIT(29)) >> 29; uint8_t opcode = (val & BITS(27, 26)) >> 26; uint8_t phy = (val & BITS(25, 21)) >> 21; uint8_t reg = (val & BITS(20, 16)) >> 16; uint16_t data = (val & BITS(15, 0)); #endif /* Emulation takes no time to finish MDI transaction. */ val |= BIT(28); TRACE(MDI, logout("val=0x%08x (int=%u, %s, phy=%u, %s, data=0x%04x\n", val, raiseint, mdi_op_name[opcode], phy, reg2name(reg), data)); return val; } static void eepro100_write_mdi(EEPRO100State *s) { uint32_t val = e100_read_reg4(s, SCBCtrlMDI); uint8_t raiseint = (val & BIT(29)) >> 29; uint8_t opcode = (val & BITS(27, 26)) >> 26; uint8_t phy = (val & BITS(25, 21)) >> 21; uint8_t reg = (val & BITS(20, 16)) >> 16; uint16_t data = (val & BITS(15, 0)); TRACE(MDI, logout("val=0x%08x (int=%u, %s, phy=%u, %s, data=0x%04x\n", val, raiseint, mdi_op_name[opcode], phy, reg2name(reg), data)); if (phy != 1) { /* Unsupported PHY address. */ #if 0 logout("phy must be 1 but is %u\n", phy); #endif data = 0; } else if (opcode != 1 && opcode != 2) { /* Unsupported opcode. */ logout("opcode must be 1 or 2 but is %u\n", opcode); data = 0; } else if (reg > 6) { /* Unsupported register. */ logout("register must be 0...6 but is %u\n", reg); data = 0; } else { TRACE(MDI, logout("val=0x%08x (int=%u, %s, phy=%u, %s, data=0x%04x\n", val, raiseint, mdi_op_name[opcode], phy, reg2name(reg), data)); if (opcode == 1) { /* MDI write */ switch (reg) { case 0: /* Control Register */ if (data & 0x8000) { /* Reset status and control registers to default. */ s->mdimem[0] = eepro100_mdi_default[0]; s->mdimem[1] = eepro100_mdi_default[1]; data = s->mdimem[reg]; } else { /* Restart Auto Configuration = Normal Operation */ data &= ~0x0200; } break; case 1: /* Status Register */ missing("not writable"); data = s->mdimem[reg]; break; case 2: /* PHY Identification Register (Word 1) */ case 3: /* PHY Identification Register (Word 2) */ missing("not implemented"); break; case 4: /* Auto-Negotiation Advertisement Register */ case 5: /* Auto-Negotiation Link Partner Ability Register */ break; case 6: /* Auto-Negotiation Expansion Register */ default: missing("not implemented"); } s->mdimem[reg] = data; } else if (opcode == 2) { /* MDI read */ switch (reg) { case 0: /* Control Register */ if (data & 0x8000) { /* Reset status and control registers to default. */ s->mdimem[0] = eepro100_mdi_default[0]; s->mdimem[1] = eepro100_mdi_default[1]; } break; case 1: /* Status Register */ s->mdimem[reg] |= 0x0020; break; case 2: /* PHY Identification Register (Word 1) */ case 3: /* PHY Identification Register (Word 2) */ case 4: /* Auto-Negotiation Advertisement Register */ break; case 5: /* Auto-Negotiation Link Partner Ability Register */ s->mdimem[reg] = 0x41fe; break; case 6: /* Auto-Negotiation Expansion Register */ s->mdimem[reg] = 0x0001; break; } data = s->mdimem[reg]; } /* Emulation takes no time to finish MDI transaction. * Set MDI bit in SCB status register. */ s->mem[SCBAck] |= 0x08; val |= BIT(28); if (raiseint) { eepro100_mdi_interrupt(s); } } val = (val & 0xffff0000) + data; e100_write_reg4(s, SCBCtrlMDI, val); } /***************************************************************************** * * Port emulation. * ****************************************************************************/ #define PORT_SOFTWARE_RESET 0 #define PORT_SELFTEST 1 #define PORT_SELECTIVE_RESET 2 #define PORT_DUMP 3 #define PORT_SELECTION_MASK 3 typedef struct { uint32_t st_sign; /* Self Test Signature */ uint32_t st_result; /* Self Test Results */ } eepro100_selftest_t; static uint32_t eepro100_read_port(EEPRO100State * s) { return 0; } static void eepro100_write_port(EEPRO100State *s) { uint32_t val = e100_read_reg4(s, SCBPort); uint32_t address = (val & ~PORT_SELECTION_MASK); uint8_t selection = (val & PORT_SELECTION_MASK); switch (selection) { case PORT_SOFTWARE_RESET: nic_reset(s); break; case PORT_SELFTEST: TRACE(OTHER, logout("selftest address=0x%08x\n", address)); eepro100_selftest_t data; pci_dma_read(&s->dev, address, (uint8_t *) &data, sizeof(data)); data.st_sign = 0xffffffff; data.st_result = 0; pci_dma_write(&s->dev, address, (uint8_t *) &data, sizeof(data)); break; case PORT_SELECTIVE_RESET: TRACE(OTHER, logout("selective reset, selftest address=0x%08x\n", address)); nic_selective_reset(s); break; default: logout("val=0x%08x\n", val); missing("unknown port selection"); } } /***************************************************************************** * * General hardware emulation. * ****************************************************************************/ static uint8_t eepro100_read1(EEPRO100State * s, uint32_t addr) { uint8_t val = 0; if (addr <= sizeof(s->mem) - sizeof(val)) { val = s->mem[addr]; } switch (addr) { case SCBStatus: case SCBAck: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBCmd: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); #if 0 val = eepro100_read_command(s); #endif break; case SCBIntmask: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBPort + 3: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBeeprom: val = eepro100_read_eeprom(s); break; case SCBCtrlMDI: case SCBCtrlMDI + 1: case SCBCtrlMDI + 2: case SCBCtrlMDI + 3: val = (uint8_t)(eepro100_read_mdi(s) >> (8 * (addr & 3))); TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBpmdr: /* Power Management Driver Register */ val = 0; TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBgctrl: /* General Control Register */ TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBgstat: /* General Status Register */ /* 100 Mbps full duplex, valid link */ val = 0x07; TRACE(OTHER, logout("addr=General Status val=%02x\n", val)); break; default: logout("addr=%s val=0x%02x\n", regname(addr), val); missing("unknown byte read"); } return val; } static uint16_t eepro100_read2(EEPRO100State * s, uint32_t addr) { uint16_t val = 0; if (addr <= sizeof(s->mem) - sizeof(val)) { val = e100_read_reg2(s, addr); } switch (addr) { case SCBStatus: case SCBCmd: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); break; case SCBeeprom: val = eepro100_read_eeprom(s); TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); break; case SCBCtrlMDI: case SCBCtrlMDI + 2: val = (uint16_t)(eepro100_read_mdi(s) >> (8 * (addr & 3))); TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); break; default: logout("addr=%s val=0x%04x\n", regname(addr), val); missing("unknown word read"); } return val; } static uint32_t eepro100_read4(EEPRO100State * s, uint32_t addr) { uint32_t val = 0; if (addr <= sizeof(s->mem) - sizeof(val)) { val = e100_read_reg4(s, addr); } switch (addr) { case SCBStatus: TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); break; case SCBPointer: TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); break; case SCBPort: val = eepro100_read_port(s); TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); break; case SCBflash: val = eepro100_read_eeprom(s); TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); break; case SCBCtrlMDI: val = eepro100_read_mdi(s); break; default: logout("addr=%s val=0x%08x\n", regname(addr), val); missing("unknown longword read"); } return val; } static void eepro100_write1(EEPRO100State * s, uint32_t addr, uint8_t val) { /* SCBStatus is readonly. */ if (addr > SCBStatus && addr <= sizeof(s->mem) - sizeof(val)) { s->mem[addr] = val; } switch (addr) { case SCBStatus: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBAck: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); eepro100_acknowledge(s); break; case SCBCmd: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); eepro100_write_command(s, val); break; case SCBIntmask: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); if (val & BIT(1)) { eepro100_swi_interrupt(s); } eepro100_interrupt(s, 0); break; case SCBPointer: case SCBPointer + 1: case SCBPointer + 2: case SCBPointer + 3: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBPort: case SCBPort + 1: case SCBPort + 2: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBPort + 3: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); eepro100_write_port(s); break; case SCBFlow: /* does not exist on 82557 */ case SCBFlow + 1: case SCBFlow + 2: case SCBpmdr: /* does not exist on 82557 */ TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBeeprom: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); eepro100_write_eeprom(s->eeprom, val); break; case SCBCtrlMDI: case SCBCtrlMDI + 1: case SCBCtrlMDI + 2: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); break; case SCBCtrlMDI + 3: TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val)); eepro100_write_mdi(s); break; default: logout("addr=%s val=0x%02x\n", regname(addr), val); missing("unknown byte write"); } } static void eepro100_write2(EEPRO100State * s, uint32_t addr, uint16_t val) { /* SCBStatus is readonly. */ if (addr > SCBStatus && addr <= sizeof(s->mem) - sizeof(val)) { e100_write_reg2(s, addr, val); } switch (addr) { case SCBStatus: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); s->mem[SCBAck] = (val >> 8); eepro100_acknowledge(s); break; case SCBCmd: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); eepro100_write_command(s, val); eepro100_write1(s, SCBIntmask, val >> 8); break; case SCBPointer: case SCBPointer + 2: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); break; case SCBPort: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); break; case SCBPort + 2: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); eepro100_write_port(s); break; case SCBeeprom: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); eepro100_write_eeprom(s->eeprom, val); break; case SCBCtrlMDI: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); break; case SCBCtrlMDI + 2: TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val)); eepro100_write_mdi(s); break; default: logout("addr=%s val=0x%04x\n", regname(addr), val); missing("unknown word write"); } } static void eepro100_write4(EEPRO100State * s, uint32_t addr, uint32_t val) { if (addr <= sizeof(s->mem) - sizeof(val)) { e100_write_reg4(s, addr, val); } switch (addr) { case SCBPointer: TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); break; case SCBPort: TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); eepro100_write_port(s); break; case SCBflash: TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); val = val >> 16; eepro100_write_eeprom(s->eeprom, val); break; case SCBCtrlMDI: TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val)); eepro100_write_mdi(s); break; default: logout("addr=%s val=0x%08x\n", regname(addr), val); missing("unknown longword write"); } } static uint64_t eepro100_read(void *opaque, hwaddr addr, unsigned size) { EEPRO100State *s = opaque; switch (size) { case 1: return eepro100_read1(s, addr); case 2: return eepro100_read2(s, addr); case 4: return eepro100_read4(s, addr); default: abort(); } } static void eepro100_write(void *opaque, hwaddr addr, uint64_t data, unsigned size) { EEPRO100State *s = opaque; switch (size) { case 1: eepro100_write1(s, addr, data); break; case 2: eepro100_write2(s, addr, data); break; case 4: eepro100_write4(s, addr, data); break; default: abort(); } } static const MemoryRegionOps eepro100_ops = { .read = eepro100_read, .write = eepro100_write, .endianness = DEVICE_LITTLE_ENDIAN, }; static int nic_can_receive(NetClientState *nc) { EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque; TRACE(RXTX, logout("%p\n", s)); return get_ru_state(s) == ru_ready; #if 0 return !eepro100_buffer_full(s); #endif } static ssize_t nic_receive(NetClientState *nc, const uint8_t * buf, size_t size) { /* TODO: * - Magic packets should set bit 30 in power management driver register. * - Interesting packets should set bit 29 in power management driver register. */ EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque; uint16_t rfd_status = 0xa000; #if defined(CONFIG_PAD_RECEIVED_FRAMES) uint8_t min_buf[60]; #endif static const uint8_t broadcast_macaddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; #if defined(CONFIG_PAD_RECEIVED_FRAMES) /* Pad to minimum Ethernet frame length */ if (size < sizeof(min_buf)) { memcpy(min_buf, buf, size); memset(&min_buf[size], 0, sizeof(min_buf) - size); buf = min_buf; size = sizeof(min_buf); } #endif if (s->configuration[8] & 0x80) { /* CSMA is disabled. */ logout("%p received while CSMA is disabled\n", s); return -1; #if !defined(CONFIG_PAD_RECEIVED_FRAMES) } else if (size < 64 && (s->configuration[7] & BIT(0))) { /* Short frame and configuration byte 7/0 (discard short receive) set: * Short frame is discarded */ logout("%p received short frame (%zu byte)\n", s, size); s->statistics.rx_short_frame_errors++; return -1; #endif } else if ((size > MAX_ETH_FRAME_SIZE + 4) && !(s->configuration[18] & BIT(3))) { /* Long frame and configuration byte 18/3 (long receive ok) not set: * Long frames are discarded. */ logout("%p received long frame (%zu byte), ignored\n", s, size); return -1; } else if (memcmp(buf, s->conf.macaddr.a, 6) == 0) { /* !!! */ /* Frame matches individual address. */ /* TODO: check configuration byte 15/4 (ignore U/L). */ TRACE(RXTX, logout("%p received frame for me, len=%zu\n", s, size)); } else if (memcmp(buf, broadcast_macaddr, 6) == 0) { /* Broadcast frame. */ TRACE(RXTX, logout("%p received broadcast, len=%zu\n", s, size)); rfd_status |= 0x0002; } else if (buf[0] & 0x01) { /* Multicast frame. */ TRACE(RXTX, logout("%p received multicast, len=%zu,%s\n", s, size, nic_dump(buf, size))); if (s->configuration[21] & BIT(3)) { /* Multicast all bit is set, receive all multicast frames. */ } else { unsigned mcast_idx = e100_compute_mcast_idx(buf); assert(mcast_idx < 64); if (s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))) { /* Multicast frame is allowed in hash table. */ } else if (s->configuration[15] & BIT(0)) { /* Promiscuous: receive all. */ rfd_status |= 0x0004; } else { TRACE(RXTX, logout("%p multicast ignored\n", s)); return -1; } } /* TODO: Next not for promiscuous mode? */ rfd_status |= 0x0002; } else if (s->configuration[15] & BIT(0)) { /* Promiscuous: receive all. */ TRACE(RXTX, logout("%p received frame in promiscuous mode, len=%zu\n", s, size)); rfd_status |= 0x0004; } else if (s->configuration[20] & BIT(6)) { /* Multiple IA bit set. */ unsigned mcast_idx = compute_mcast_idx(buf); assert(mcast_idx < 64); if (s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))) { TRACE(RXTX, logout("%p accepted, multiple IA bit set\n", s)); } else { TRACE(RXTX, logout("%p frame ignored, multiple IA bit set\n", s)); return -1; } } else { TRACE(RXTX, logout("%p received frame, ignored, len=%zu,%s\n", s, size, nic_dump(buf, size))); return size; } if (get_ru_state(s) != ru_ready) { /* No resources available. */ logout("no resources, state=%u\n", get_ru_state(s)); /* TODO: RNR interrupt only at first failed frame? */ eepro100_rnr_interrupt(s); s->statistics.rx_resource_errors++; #if 0 assert(!"no resources"); #endif return -1; } /* !!! */ eepro100_rx_t rx; pci_dma_read(&s->dev, s->ru_base + s->ru_offset, &rx, sizeof(eepro100_rx_t)); uint16_t rfd_command = le16_to_cpu(rx.command); uint16_t rfd_size = le16_to_cpu(rx.size); if (size > rfd_size) { logout("Receive buffer (%" PRId16 " bytes) too small for data " "(%zu bytes); data truncated\n", rfd_size, size); size = rfd_size; } #if !defined(CONFIG_PAD_RECEIVED_FRAMES) if (size < 64) { rfd_status |= 0x0080; } #endif TRACE(OTHER, logout("command 0x%04x, link 0x%08x, addr 0x%08x, size %u\n", rfd_command, rx.link, rx.rx_buf_addr, rfd_size)); stw_le_pci_dma(&s->dev, s->ru_base + s->ru_offset + offsetof(eepro100_rx_t, status), rfd_status); stw_le_pci_dma(&s->dev, s->ru_base + s->ru_offset + offsetof(eepro100_rx_t, count), size); /* Early receive interrupt not supported. */ #if 0 eepro100_er_interrupt(s); #endif /* Receive CRC Transfer not supported. */ if (s->configuration[18] & BIT(2)) { missing("Receive CRC Transfer"); return -1; } /* TODO: check stripping enable bit. */ #if 0 assert(!(s->configuration[17] & BIT(0))); #endif pci_dma_write(&s->dev, s->ru_base + s->ru_offset + sizeof(eepro100_rx_t), buf, size); s->statistics.rx_good_frames++; eepro100_fr_interrupt(s); s->ru_offset = le32_to_cpu(rx.link); if (rfd_command & COMMAND_EL) { /* EL bit is set, so this was the last frame. */ logout("receive: Running out of frames\n"); set_ru_state(s, ru_no_resources); eepro100_rnr_interrupt(s); } if (rfd_command & COMMAND_S) { /* S bit is set. */ set_ru_state(s, ru_suspended); } return size; } static const VMStateDescription vmstate_eepro100 = { .version_id = 3, .minimum_version_id = 2, .minimum_version_id_old = 2, .fields = (VMStateField []) { VMSTATE_PCI_DEVICE(dev, EEPRO100State), VMSTATE_UNUSED(32), VMSTATE_BUFFER(mult, EEPRO100State), VMSTATE_BUFFER(mem, EEPRO100State), /* Save all members of struct between scb_stat and mem. */ VMSTATE_UINT8(scb_stat, EEPRO100State), VMSTATE_UINT8(int_stat, EEPRO100State), VMSTATE_UNUSED(3*4), VMSTATE_MACADDR(conf.macaddr, EEPRO100State), VMSTATE_UNUSED(19*4), VMSTATE_UINT16_ARRAY(mdimem, EEPRO100State, 32), /* The eeprom should be saved and restored by its own routines. */ VMSTATE_UINT32(device, EEPRO100State), /* TODO check device. */ VMSTATE_UINT32(cu_base, EEPRO100State), VMSTATE_UINT32(cu_offset, EEPRO100State), VMSTATE_UINT32(ru_base, EEPRO100State), VMSTATE_UINT32(ru_offset, EEPRO100State), VMSTATE_UINT32(statsaddr, EEPRO100State), /* Save eepro100_stats_t statistics. */ VMSTATE_UINT32(statistics.tx_good_frames, EEPRO100State), VMSTATE_UINT32(statistics.tx_max_collisions, EEPRO100State), VMSTATE_UINT32(statistics.tx_late_collisions, EEPRO100State), VMSTATE_UINT32(statistics.tx_underruns, EEPRO100State), VMSTATE_UINT32(statistics.tx_lost_crs, EEPRO100State), VMSTATE_UINT32(statistics.tx_deferred, EEPRO100State), VMSTATE_UINT32(statistics.tx_single_collisions, EEPRO100State), VMSTATE_UINT32(statistics.tx_multiple_collisions, EEPRO100State), VMSTATE_UINT32(statistics.tx_total_collisions, EEPRO100State), VMSTATE_UINT32(statistics.rx_good_frames, EEPRO100State), VMSTATE_UINT32(statistics.rx_crc_errors, EEPRO100State), VMSTATE_UINT32(statistics.rx_alignment_errors, EEPRO100State), VMSTATE_UINT32(statistics.rx_resource_errors, EEPRO100State), VMSTATE_UINT32(statistics.rx_overrun_errors, EEPRO100State), VMSTATE_UINT32(statistics.rx_cdt_errors, EEPRO100State), VMSTATE_UINT32(statistics.rx_short_frame_errors, EEPRO100State), VMSTATE_UINT32(statistics.fc_xmt_pause, EEPRO100State), VMSTATE_UINT32(statistics.fc_rcv_pause, EEPRO100State), VMSTATE_UINT32(statistics.fc_rcv_unsupported, EEPRO100State), VMSTATE_UINT16(statistics.xmt_tco_frames, EEPRO100State), VMSTATE_UINT16(statistics.rcv_tco_frames, EEPRO100State), /* Configuration bytes. */ VMSTATE_BUFFER(configuration, EEPRO100State), VMSTATE_END_OF_LIST() } }; static void nic_cleanup(NetClientState *nc) { EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque; s->nic = NULL; } static void pci_nic_uninit(PCIDevice *pci_dev) { EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, pci_dev); memory_region_destroy(&s->mmio_bar); memory_region_destroy(&s->io_bar); memory_region_destroy(&s->flash_bar); vmstate_unregister(&pci_dev->qdev, s->vmstate, s); eeprom93xx_free(&pci_dev->qdev, s->eeprom); qemu_del_net_client(&s->nic->nc); } static NetClientInfo net_eepro100_info = { .type = NET_CLIENT_OPTIONS_KIND_NIC, .size = sizeof(NICState), .can_receive = nic_can_receive, .receive = nic_receive, .cleanup = nic_cleanup, }; static int e100_nic_init(PCIDevice *pci_dev) { EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, pci_dev); E100PCIDeviceInfo *info = eepro100_get_class(s); TRACE(OTHER, logout("\n")); s->device = info->device; e100_pci_reset(s); /* Add 64 * 2 EEPROM. i82557 and i82558 support a 64 word EEPROM, * i82559 and later support 64 or 256 word EEPROM. */ s->eeprom = eeprom93xx_new(&pci_dev->qdev, EEPROM_SIZE); /* Handler for memory-mapped I/O */ memory_region_init_io(&s->mmio_bar, &eepro100_ops, s, "eepro100-mmio", PCI_MEM_SIZE); pci_register_bar(&s->dev, 0, PCI_BASE_ADDRESS_MEM_PREFETCH, &s->mmio_bar); memory_region_init_io(&s->io_bar, &eepro100_ops, s, "eepro100-io", PCI_IO_SIZE); pci_register_bar(&s->dev, 1, PCI_BASE_ADDRESS_SPACE_IO, &s->io_bar); /* FIXME: flash aliases to mmio?! */ memory_region_init_io(&s->flash_bar, &eepro100_ops, s, "eepro100-flash", PCI_FLASH_SIZE); pci_register_bar(&s->dev, 2, 0, &s->flash_bar); qemu_macaddr_default_if_unset(&s->conf.macaddr); logout("macaddr: %s\n", nic_dump(&s->conf.macaddr.a[0], 6)); nic_reset(s); s->nic = qemu_new_nic(&net_eepro100_info, &s->conf, object_get_typename(OBJECT(pci_dev)), pci_dev->qdev.id, s); qemu_format_nic_info_str(&s->nic->nc, s->conf.macaddr.a); TRACE(OTHER, logout("%s\n", s->nic->nc.info_str)); qemu_register_reset(nic_reset, s); s->vmstate = g_malloc(sizeof(vmstate_eepro100)); memcpy(s->vmstate, &vmstate_eepro100, sizeof(vmstate_eepro100)); s->vmstate->name = s->nic->nc.model; vmstate_register(&pci_dev->qdev, -1, s->vmstate, s); add_boot_device_path(s->conf.bootindex, &pci_dev->qdev, "/ethernet-phy@0"); return 0; } static E100PCIDeviceInfo e100_devices[] = { { .name = "i82550", .desc = "Intel i82550 Ethernet", .device = i82550, /* TODO: check device id. */ .device_id = PCI_DEVICE_ID_INTEL_82551IT, /* Revision ID: 0x0c, 0x0d, 0x0e. */ .revision = 0x0e, /* TODO: check size of statistical counters. */ .stats_size = 80, /* TODO: check extended tcb support. */ .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82551", .desc = "Intel i82551 Ethernet", .device = i82551, .device_id = PCI_DEVICE_ID_INTEL_82551IT, /* Revision ID: 0x0f, 0x10. */ .revision = 0x0f, /* TODO: check size of statistical counters. */ .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82557a", .desc = "Intel i82557A Ethernet", .device = i82557A, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x01, .power_management = false, },{ .name = "i82557b", .desc = "Intel i82557B Ethernet", .device = i82557B, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x02, .power_management = false, },{ .name = "i82557c", .desc = "Intel i82557C Ethernet", .device = i82557C, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x03, .power_management = false, },{ .name = "i82558a", .desc = "Intel i82558A Ethernet", .device = i82558A, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x04, .stats_size = 76, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82558b", .desc = "Intel i82558B Ethernet", .device = i82558B, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x05, .stats_size = 76, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82559a", .desc = "Intel i82559A Ethernet", .device = i82559A, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x06, .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82559b", .desc = "Intel i82559B Ethernet", .device = i82559B, .device_id = PCI_DEVICE_ID_INTEL_82557, .revision = 0x07, .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82559c", .desc = "Intel i82559C Ethernet", .device = i82559C, .device_id = PCI_DEVICE_ID_INTEL_82557, #if 0 .revision = 0x08, #endif /* TODO: Windows wants revision id 0x0c. */ .revision = 0x0c, #if EEPROM_SIZE > 0 .subsystem_vendor_id = PCI_VENDOR_ID_INTEL, .subsystem_id = 0x0040, #endif .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82559er", .desc = "Intel i82559ER Ethernet", .device = i82559ER, .device_id = PCI_DEVICE_ID_INTEL_82551IT, .revision = 0x09, .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, },{ .name = "i82562", .desc = "Intel i82562 Ethernet", .device = i82562, /* TODO: check device id. */ .device_id = PCI_DEVICE_ID_INTEL_82551IT, /* TODO: wrong revision id. */ .revision = 0x0e, .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, },{ /* Toshiba Tecra 8200. */ .name = "i82801", .desc = "Intel i82801 Ethernet", .device = i82801, .device_id = 0x2449, .revision = 0x03, .stats_size = 80, .has_extended_tcb_support = true, .power_management = true, } }; static E100PCIDeviceInfo *eepro100_get_class_by_name(const char *typename) { E100PCIDeviceInfo *info = NULL; int i; /* This is admittedly awkward but also temporary. QOM allows for * parameterized typing and for subclassing both of which would suitable * handle what's going on here. But class_data is already being used as * a stop-gap hack to allow incremental qdev conversion so we cannot use it * right now. Once we merge the final QOM series, we can come back here and * do this in a much more elegant fashion. */ for (i = 0; i < ARRAY_SIZE(e100_devices); i++) { if (strcmp(e100_devices[i].name, typename) == 0) { info = &e100_devices[i]; break; } } assert(info != NULL); return info; } static E100PCIDeviceInfo *eepro100_get_class(EEPRO100State *s) { return eepro100_get_class_by_name(object_get_typename(OBJECT(s))); } static Property e100_properties[] = { DEFINE_NIC_PROPERTIES(EEPRO100State, conf), DEFINE_PROP_END_OF_LIST(), }; static void eepro100_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); E100PCIDeviceInfo *info; info = eepro100_get_class_by_name(object_class_get_name(klass)); dc->props = e100_properties; dc->desc = info->desc; k->vendor_id = PCI_VENDOR_ID_INTEL; k->class_id = PCI_CLASS_NETWORK_ETHERNET; k->romfile = "pxe-eepro100.rom"; k->init = e100_nic_init; k->exit = pci_nic_uninit; k->device_id = info->device_id; k->revision = info->revision; k->subsystem_vendor_id = info->subsystem_vendor_id; k->subsystem_id = info->subsystem_id; } static void eepro100_register_types(void) { size_t i; for (i = 0; i < ARRAY_SIZE(e100_devices); i++) { TypeInfo type_info = {}; E100PCIDeviceInfo *info = &e100_devices[i]; type_info.name = info->name; type_info.parent = TYPE_PCI_DEVICE; type_info.class_init = eepro100_class_init; type_info.instance_size = sizeof(EEPRO100State); type_register(&type_info); } } type_init(eepro100_register_types)
piyushroshan/xen-4.3.2
tools/qemu-xen/hw/eepro100.c
C
gpl-2.0
70,695
/*************************************************************** * Name: ThreadSearchLoggerTree * Purpose: ThreadSearchLoggerTree implements the * ThreadSearchLoggerBase interface with a wxTreeCtrl. * Author: Jerome ANTOINE * Created: 2007-07-28 * Copyright: Jerome ANTOINE * License: GPL **************************************************************/ #ifndef THREAD_SEARCH_LOGGER_TREE_H #define THREAD_SEARCH_LOGGER_TREE_H #include <wx/event.h> #include <wx/treebase.h> #include "ThreadSearchLoggerBase.h" class wxString; class wxWindow; class wxPanel; class wxTreeCtrl; class wxTreeEvent; class ThreadSearch; class ThreadSearchView; class ThreadSearchEvent; // MessageLog inheritance is necessary to be able to // add logger to Messages notebook. class ThreadSearchLoggerTree : public wxEvtHandler, public ThreadSearchLoggerBase { public: /** Constructor. */ ThreadSearchLoggerTree(ThreadSearchView& threadSearchView, ThreadSearch& threadSearchPlugin, InsertIndexManager::eFileSorting fileSorting, wxPanel* pParent, long id); /** Destructor. */ virtual ~ThreadSearchLoggerTree(); /** Getter */ virtual eLoggerTypes GetLoggerType() {return TypeTree;} /** Called by ThreadSearchView to process a ThreadSearchEvent * sent by worker thread. */ virtual void OnThreadSearchEvent(const ThreadSearchEvent& event); /** Removes all items from logger. */ virtual void Clear(); /** Called on search begin to prepare logger. */ virtual void OnSearchBegin(const ThreadSearchFindData& findData); /** Returns the logger window. */ virtual wxWindow* GetWindow(); /** Sets focus on list window. */ virtual void SetFocus(); /** Single click event handler */ void OnLoggerTreeClick(wxTreeEvent& event); /** Double click event handler */ void OnLoggerTreeDoubleClick(wxTreeEvent& event); protected: /** GetFileLineFromTreeEvent * Return the file path at index from the list control using dir and file columns. * @param event : list control event * @param filepath : reference that will receive the path * @param line : reference that will receive the line index * @return true if successful. */ bool GetFileLineFromTreeEvent(wxTreeEvent& event, wxString& filepath, long &line); /** hasResultLineForTreeItem * @return Return true if a result line can be found for tree item */ bool hasResultLineForTreeItem(wxTreeItemId treeItemId); /** Dynamic events connection. */ virtual void ConnectEvents(wxEvtHandler* pEvtHandler); /** Dynamic events disconnection. */ virtual void DisconnectEvents(wxEvtHandler* pEvtHandler); /** Contextual menu event handler */ void OnLoggerTreeContextualMenu(wxTreeEvent& event); /** Delete item menu event handler */ void OnDeleteTreeItem(wxCommandEvent& event); /** Delete item menu event handler */ void OnDeleteAllTreeItems(wxCommandEvent& event); /** Deletes an item from the tree */ void DeleteTreeItem(wxTreeItemId id); /** Deletes all items from the tree */ void DeleteTreeItems(); wxTreeCtrl* m_pTreeLog; bool m_FirstItemProcessed; // Used to filter wxTree events and process useful ones only. wxTreeItemId m_FilesParentId; wxTreeItemId m_ToDeleteItemId; }; #endif // THREAD_SEARCH_LOGGER_TREE_H
stahta01/codeblocks_msys2
src/plugins/contrib/ThreadSearch/ThreadSearchLoggerTree.h
C
gpl-3.0
3,445
/* * ELF constants and data structures * * Derived from: * $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.1 2005/12/30 22:13:58 marcel Exp $ * $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.1 2005/12/30 22:13:58 marcel Exp $ * $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.1 2005/12/30 22:13:58 marcel Exp $ * $FreeBSD: src/sys/alpha/include/elf.h,v 1.14 2003/09/25 01:10:22 peter Exp $ * $FreeBSD: src/sys/amd64/include/elf.h,v 1.18 2004/08/03 08:21:48 dfr Exp $ * $FreeBSD: src/sys/arm/include/elf.h,v 1.5.2.1 2006/06/30 21:42:52 cognet Exp $ * $FreeBSD: src/sys/i386/include/elf.h,v 1.16 2004/08/02 19:12:17 dfr Exp $ * $FreeBSD: src/sys/powerpc/include/elf.h,v 1.7 2004/11/02 09:47:01 ssouhlal Exp $ * $FreeBSD: src/sys/sparc64/include/elf.h,v 1.12 2003/09/25 01:10:26 peter Exp $ * "ELF for the ARM® 64-bit Architecture (AArch64)" (ARM IHI 0056B) * * Copyright (c) 1996-1998 John D. Polstra. All rights reserved. * Copyright (c) 2001 David E. O'Brien * Portions Copyright 2009 The Go Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package elf import "strconv" /* * Constants */ // Indexes into the Header.Ident array. const ( EI_CLASS = 4 /* Class of machine. */ EI_DATA = 5 /* Data format. */ EI_VERSION = 6 /* ELF format version. */ EI_OSABI = 7 /* Operating system / ABI identification */ EI_ABIVERSION = 8 /* ABI version */ EI_PAD = 9 /* Start of padding (per SVR4 ABI). */ EI_NIDENT = 16 /* Size of e_ident array. */ ) // Initial magic number for ELF files. const ELFMAG = "\177ELF" // Version is found in Header.Ident[EI_VERSION] and Header.Version. type Version byte const ( EV_NONE Version = 0 EV_CURRENT Version = 1 ) var versionStrings = []intName{ {0, "EV_NONE"}, {1, "EV_CURRENT"}, } func (i Version) String() string { return stringName(uint32(i), versionStrings, false) } func (i Version) GoString() string { return stringName(uint32(i), versionStrings, true) } // Class is found in Header.Ident[EI_CLASS] and Header.Class. type Class byte const ( ELFCLASSNONE Class = 0 /* Unknown class. */ ELFCLASS32 Class = 1 /* 32-bit architecture. */ ELFCLASS64 Class = 2 /* 64-bit architecture. */ ) var classStrings = []intName{ {0, "ELFCLASSNONE"}, {1, "ELFCLASS32"}, {2, "ELFCLASS64"}, } func (i Class) String() string { return stringName(uint32(i), classStrings, false) } func (i Class) GoString() string { return stringName(uint32(i), classStrings, true) } // Data is found in Header.Ident[EI_DATA] and Header.Data. type Data byte const ( ELFDATANONE Data = 0 /* Unknown data format. */ ELFDATA2LSB Data = 1 /* 2's complement little-endian. */ ELFDATA2MSB Data = 2 /* 2's complement big-endian. */ ) var dataStrings = []intName{ {0, "ELFDATANONE"}, {1, "ELFDATA2LSB"}, {2, "ELFDATA2MSB"}, } func (i Data) String() string { return stringName(uint32(i), dataStrings, false) } func (i Data) GoString() string { return stringName(uint32(i), dataStrings, true) } // OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI. type OSABI byte const ( ELFOSABI_NONE OSABI = 0 /* UNIX System V ABI */ ELFOSABI_HPUX OSABI = 1 /* HP-UX operating system */ ELFOSABI_NETBSD OSABI = 2 /* NetBSD */ ELFOSABI_LINUX OSABI = 3 /* GNU/Linux */ ELFOSABI_HURD OSABI = 4 /* GNU/Hurd */ ELFOSABI_86OPEN OSABI = 5 /* 86Open common IA32 ABI */ ELFOSABI_SOLARIS OSABI = 6 /* Solaris */ ELFOSABI_AIX OSABI = 7 /* AIX */ ELFOSABI_IRIX OSABI = 8 /* IRIX */ ELFOSABI_FREEBSD OSABI = 9 /* FreeBSD */ ELFOSABI_TRU64 OSABI = 10 /* TRU64 UNIX */ ELFOSABI_MODESTO OSABI = 11 /* Novell Modesto */ ELFOSABI_OPENBSD OSABI = 12 /* OpenBSD */ ELFOSABI_OPENVMS OSABI = 13 /* Open VMS */ ELFOSABI_NSK OSABI = 14 /* HP Non-Stop Kernel */ ELFOSABI_ARM OSABI = 97 /* ARM */ ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */ ) var osabiStrings = []intName{ {0, "ELFOSABI_NONE"}, {1, "ELFOSABI_HPUX"}, {2, "ELFOSABI_NETBSD"}, {3, "ELFOSABI_LINUX"}, {4, "ELFOSABI_HURD"}, {5, "ELFOSABI_86OPEN"}, {6, "ELFOSABI_SOLARIS"}, {7, "ELFOSABI_AIX"}, {8, "ELFOSABI_IRIX"}, {9, "ELFOSABI_FREEBSD"}, {10, "ELFOSABI_TRU64"}, {11, "ELFOSABI_MODESTO"}, {12, "ELFOSABI_OPENBSD"}, {13, "ELFOSABI_OPENVMS"}, {14, "ELFOSABI_NSK"}, {97, "ELFOSABI_ARM"}, {255, "ELFOSABI_STANDALONE"}, } func (i OSABI) String() string { return stringName(uint32(i), osabiStrings, false) } func (i OSABI) GoString() string { return stringName(uint32(i), osabiStrings, true) } // Type is found in Header.Type. type Type uint16 const ( ET_NONE Type = 0 /* Unknown type. */ ET_REL Type = 1 /* Relocatable. */ ET_EXEC Type = 2 /* Executable. */ ET_DYN Type = 3 /* Shared object. */ ET_CORE Type = 4 /* Core file. */ ET_LOOS Type = 0xfe00 /* First operating system specific. */ ET_HIOS Type = 0xfeff /* Last operating system-specific. */ ET_LOPROC Type = 0xff00 /* First processor-specific. */ ET_HIPROC Type = 0xffff /* Last processor-specific. */ ) var typeStrings = []intName{ {0, "ET_NONE"}, {1, "ET_REL"}, {2, "ET_EXEC"}, {3, "ET_DYN"}, {4, "ET_CORE"}, {0xfe00, "ET_LOOS"}, {0xfeff, "ET_HIOS"}, {0xff00, "ET_LOPROC"}, {0xffff, "ET_HIPROC"}, } func (i Type) String() string { return stringName(uint32(i), typeStrings, false) } func (i Type) GoString() string { return stringName(uint32(i), typeStrings, true) } // Machine is found in Header.Machine. type Machine uint16 const ( EM_NONE Machine = 0 /* Unknown machine. */ EM_M32 Machine = 1 /* AT&T WE32100. */ EM_SPARC Machine = 2 /* Sun SPARC. */ EM_386 Machine = 3 /* Intel i386. */ EM_68K Machine = 4 /* Motorola 68000. */ EM_88K Machine = 5 /* Motorola 88000. */ EM_860 Machine = 7 /* Intel i860. */ EM_MIPS Machine = 8 /* MIPS R3000 Big-Endian only. */ EM_S370 Machine = 9 /* IBM System/370. */ EM_MIPS_RS3_LE Machine = 10 /* MIPS R3000 Little-Endian. */ EM_PARISC Machine = 15 /* HP PA-RISC. */ EM_VPP500 Machine = 17 /* Fujitsu VPP500. */ EM_SPARC32PLUS Machine = 18 /* SPARC v8plus. */ EM_960 Machine = 19 /* Intel 80960. */ EM_PPC Machine = 20 /* PowerPC 32-bit. */ EM_PPC64 Machine = 21 /* PowerPC 64-bit. */ EM_S390 Machine = 22 /* IBM System/390. */ EM_V800 Machine = 36 /* NEC V800. */ EM_FR20 Machine = 37 /* Fujitsu FR20. */ EM_RH32 Machine = 38 /* TRW RH-32. */ EM_RCE Machine = 39 /* Motorola RCE. */ EM_ARM Machine = 40 /* ARM. */ EM_SH Machine = 42 /* Hitachi SH. */ EM_SPARCV9 Machine = 43 /* SPARC v9 64-bit. */ EM_TRICORE Machine = 44 /* Siemens TriCore embedded processor. */ EM_ARC Machine = 45 /* Argonaut RISC Core. */ EM_H8_300 Machine = 46 /* Hitachi H8/300. */ EM_H8_300H Machine = 47 /* Hitachi H8/300H. */ EM_H8S Machine = 48 /* Hitachi H8S. */ EM_H8_500 Machine = 49 /* Hitachi H8/500. */ EM_IA_64 Machine = 50 /* Intel IA-64 Processor. */ EM_MIPS_X Machine = 51 /* Stanford MIPS-X. */ EM_COLDFIRE Machine = 52 /* Motorola ColdFire. */ EM_68HC12 Machine = 53 /* Motorola M68HC12. */ EM_MMA Machine = 54 /* Fujitsu MMA. */ EM_PCP Machine = 55 /* Siemens PCP. */ EM_NCPU Machine = 56 /* Sony nCPU. */ EM_NDR1 Machine = 57 /* Denso NDR1 microprocessor. */ EM_STARCORE Machine = 58 /* Motorola Star*Core processor. */ EM_ME16 Machine = 59 /* Toyota ME16 processor. */ EM_ST100 Machine = 60 /* STMicroelectronics ST100 processor. */ EM_TINYJ Machine = 61 /* Advanced Logic Corp. TinyJ processor. */ EM_X86_64 Machine = 62 /* Advanced Micro Devices x86-64 */ EM_AARCH64 Machine = 183 /* ARM 64-bit Architecture (AArch64) */ /* Non-standard or deprecated. */ EM_486 Machine = 6 /* Intel i486. */ EM_MIPS_RS4_BE Machine = 10 /* MIPS R4000 Big-Endian */ EM_ALPHA_STD Machine = 41 /* Digital Alpha (standard value). */ EM_ALPHA Machine = 0x9026 /* Alpha (written in the absence of an ABI) */ ) var machineStrings = []intName{ {0, "EM_NONE"}, {1, "EM_M32"}, {2, "EM_SPARC"}, {3, "EM_386"}, {4, "EM_68K"}, {5, "EM_88K"}, {7, "EM_860"}, {8, "EM_MIPS"}, {9, "EM_S370"}, {10, "EM_MIPS_RS3_LE"}, {15, "EM_PARISC"}, {17, "EM_VPP500"}, {18, "EM_SPARC32PLUS"}, {19, "EM_960"}, {20, "EM_PPC"}, {21, "EM_PPC64"}, {22, "EM_S390"}, {36, "EM_V800"}, {37, "EM_FR20"}, {38, "EM_RH32"}, {39, "EM_RCE"}, {40, "EM_ARM"}, {42, "EM_SH"}, {43, "EM_SPARCV9"}, {44, "EM_TRICORE"}, {45, "EM_ARC"}, {46, "EM_H8_300"}, {47, "EM_H8_300H"}, {48, "EM_H8S"}, {49, "EM_H8_500"}, {50, "EM_IA_64"}, {51, "EM_MIPS_X"}, {52, "EM_COLDFIRE"}, {53, "EM_68HC12"}, {54, "EM_MMA"}, {55, "EM_PCP"}, {56, "EM_NCPU"}, {57, "EM_NDR1"}, {58, "EM_STARCORE"}, {59, "EM_ME16"}, {60, "EM_ST100"}, {61, "EM_TINYJ"}, {62, "EM_X86_64"}, /* Non-standard or deprecated. */ {6, "EM_486"}, {10, "EM_MIPS_RS4_BE"}, {41, "EM_ALPHA_STD"}, {0x9026, "EM_ALPHA"}, } func (i Machine) String() string { return stringName(uint32(i), machineStrings, false) } func (i Machine) GoString() string { return stringName(uint32(i), machineStrings, true) } // Special section indices. type SectionIndex int const ( SHN_UNDEF SectionIndex = 0 /* Undefined, missing, irrelevant. */ SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */ SHN_LOPROC SectionIndex = 0xff00 /* First processor-specific. */ SHN_HIPROC SectionIndex = 0xff1f /* Last processor-specific. */ SHN_LOOS SectionIndex = 0xff20 /* First operating system-specific. */ SHN_HIOS SectionIndex = 0xff3f /* Last operating system-specific. */ SHN_ABS SectionIndex = 0xfff1 /* Absolute values. */ SHN_COMMON SectionIndex = 0xfff2 /* Common data. */ SHN_XINDEX SectionIndex = 0xffff /* Escape; index stored elsewhere. */ SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */ ) var shnStrings = []intName{ {0, "SHN_UNDEF"}, {0xff00, "SHN_LOPROC"}, {0xff20, "SHN_LOOS"}, {0xfff1, "SHN_ABS"}, {0xfff2, "SHN_COMMON"}, {0xffff, "SHN_XINDEX"}, } func (i SectionIndex) String() string { return stringName(uint32(i), shnStrings, false) } func (i SectionIndex) GoString() string { return stringName(uint32(i), shnStrings, true) } // Section type. type SectionType uint32 const ( SHT_NULL SectionType = 0 /* inactive */ SHT_PROGBITS SectionType = 1 /* program defined information */ SHT_SYMTAB SectionType = 2 /* symbol table section */ SHT_STRTAB SectionType = 3 /* string table section */ SHT_RELA SectionType = 4 /* relocation section with addends */ SHT_HASH SectionType = 5 /* symbol hash table section */ SHT_DYNAMIC SectionType = 6 /* dynamic section */ SHT_NOTE SectionType = 7 /* note section */ SHT_NOBITS SectionType = 8 /* no space section */ SHT_REL SectionType = 9 /* relocation section - no addends */ SHT_SHLIB SectionType = 10 /* reserved - purpose unknown */ SHT_DYNSYM SectionType = 11 /* dynamic symbol table section */ SHT_INIT_ARRAY SectionType = 14 /* Initialization function pointers. */ SHT_FINI_ARRAY SectionType = 15 /* Termination function pointers. */ SHT_PREINIT_ARRAY SectionType = 16 /* Pre-initialization function ptrs. */ SHT_GROUP SectionType = 17 /* Section group. */ SHT_SYMTAB_SHNDX SectionType = 18 /* Section indexes (see SHN_XINDEX). */ SHT_LOOS SectionType = 0x60000000 /* First of OS specific semantics */ SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */ SHT_GNU_HASH SectionType = 0x6ffffff6 /* GNU hash table */ SHT_GNU_LIBLIST SectionType = 0x6ffffff7 /* GNU prelink library list */ SHT_GNU_VERDEF SectionType = 0x6ffffffd /* GNU version definition section */ SHT_GNU_VERNEED SectionType = 0x6ffffffe /* GNU version needs section */ SHT_GNU_VERSYM SectionType = 0x6fffffff /* GNU version symbol table */ SHT_HIOS SectionType = 0x6fffffff /* Last of OS specific semantics */ SHT_LOPROC SectionType = 0x70000000 /* reserved range for processor */ SHT_HIPROC SectionType = 0x7fffffff /* specific section header types */ SHT_LOUSER SectionType = 0x80000000 /* reserved range for application */ SHT_HIUSER SectionType = 0xffffffff /* specific indexes */ ) var shtStrings = []intName{ {0, "SHT_NULL"}, {1, "SHT_PROGBITS"}, {2, "SHT_SYMTAB"}, {3, "SHT_STRTAB"}, {4, "SHT_RELA"}, {5, "SHT_HASH"}, {6, "SHT_DYNAMIC"}, {7, "SHT_NOTE"}, {8, "SHT_NOBITS"}, {9, "SHT_REL"}, {10, "SHT_SHLIB"}, {11, "SHT_DYNSYM"}, {14, "SHT_INIT_ARRAY"}, {15, "SHT_FINI_ARRAY"}, {16, "SHT_PREINIT_ARRAY"}, {17, "SHT_GROUP"}, {18, "SHT_SYMTAB_SHNDX"}, {0x60000000, "SHT_LOOS"}, {0x6ffffff5, "SHT_GNU_ATTRIBUTES"}, {0x6ffffff6, "SHT_GNU_HASH"}, {0x6ffffff7, "SHT_GNU_LIBLIST"}, {0x6ffffffd, "SHT_GNU_VERDEF"}, {0x6ffffffe, "SHT_GNU_VERNEED"}, {0x6fffffff, "SHT_GNU_VERSYM"}, {0x70000000, "SHT_LOPROC"}, {0x7fffffff, "SHT_HIPROC"}, {0x80000000, "SHT_LOUSER"}, {0xffffffff, "SHT_HIUSER"}, } func (i SectionType) String() string { return stringName(uint32(i), shtStrings, false) } func (i SectionType) GoString() string { return stringName(uint32(i), shtStrings, true) } // Section flags. type SectionFlag uint32 const ( SHF_WRITE SectionFlag = 0x1 /* Section contains writable data. */ SHF_ALLOC SectionFlag = 0x2 /* Section occupies memory. */ SHF_EXECINSTR SectionFlag = 0x4 /* Section contains instructions. */ SHF_MERGE SectionFlag = 0x10 /* Section may be merged. */ SHF_STRINGS SectionFlag = 0x20 /* Section contains strings. */ SHF_INFO_LINK SectionFlag = 0x40 /* sh_info holds section index. */ SHF_LINK_ORDER SectionFlag = 0x80 /* Special ordering requirements. */ SHF_OS_NONCONFORMING SectionFlag = 0x100 /* OS-specific processing required. */ SHF_GROUP SectionFlag = 0x200 /* Member of section group. */ SHF_TLS SectionFlag = 0x400 /* Section contains TLS data. */ SHF_COMPRESSED SectionFlag = 0x800 /* Section is compressed. */ SHF_MASKOS SectionFlag = 0x0ff00000 /* OS-specific semantics. */ SHF_MASKPROC SectionFlag = 0xf0000000 /* Processor-specific semantics. */ ) var shfStrings = []intName{ {0x1, "SHF_WRITE"}, {0x2, "SHF_ALLOC"}, {0x4, "SHF_EXECINSTR"}, {0x10, "SHF_MERGE"}, {0x20, "SHF_STRINGS"}, {0x40, "SHF_INFO_LINK"}, {0x80, "SHF_LINK_ORDER"}, {0x100, "SHF_OS_NONCONFORMING"}, {0x200, "SHF_GROUP"}, {0x400, "SHF_TLS"}, {0x800, "SHF_COMPRESSED"}, } func (i SectionFlag) String() string { return flagName(uint32(i), shfStrings, false) } func (i SectionFlag) GoString() string { return flagName(uint32(i), shfStrings, true) } // Section compression type. type CompressionType int const ( COMPRESS_ZLIB CompressionType = 1 /* ZLIB compression. */ COMPRESS_LOOS CompressionType = 0x60000000 /* First OS-specific. */ COMPRESS_HIOS CompressionType = 0x6fffffff /* Last OS-specific. */ COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */ COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */ ) var compressionStrings = []intName{ {0, "COMPRESS_ZLIB"}, {0x60000000, "COMPRESS_LOOS"}, {0x6fffffff, "COMPRESS_HIOS"}, {0x70000000, "COMPRESS_LOPROC"}, {0x7fffffff, "COMPRESS_HIPROC"}, } func (i CompressionType) String() string { return stringName(uint32(i), compressionStrings, false) } func (i CompressionType) GoString() string { return stringName(uint32(i), compressionStrings, true) } // Prog.Type type ProgType int const ( PT_NULL ProgType = 0 /* Unused entry. */ PT_LOAD ProgType = 1 /* Loadable segment. */ PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */ PT_INTERP ProgType = 3 /* Pathname of interpreter. */ PT_NOTE ProgType = 4 /* Auxiliary information. */ PT_SHLIB ProgType = 5 /* Reserved (not used). */ PT_PHDR ProgType = 6 /* Location of program header itself. */ PT_TLS ProgType = 7 /* Thread local storage segment */ PT_LOOS ProgType = 0x60000000 /* First OS-specific. */ PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */ PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */ PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */ ) var ptStrings = []intName{ {0, "PT_NULL"}, {1, "PT_LOAD"}, {2, "PT_DYNAMIC"}, {3, "PT_INTERP"}, {4, "PT_NOTE"}, {5, "PT_SHLIB"}, {6, "PT_PHDR"}, {7, "PT_TLS"}, {0x60000000, "PT_LOOS"}, {0x6fffffff, "PT_HIOS"}, {0x70000000, "PT_LOPROC"}, {0x7fffffff, "PT_HIPROC"}, } func (i ProgType) String() string { return stringName(uint32(i), ptStrings, false) } func (i ProgType) GoString() string { return stringName(uint32(i), ptStrings, true) } // Prog.Flag type ProgFlag uint32 const ( PF_X ProgFlag = 0x1 /* Executable. */ PF_W ProgFlag = 0x2 /* Writable. */ PF_R ProgFlag = 0x4 /* Readable. */ PF_MASKOS ProgFlag = 0x0ff00000 /* Operating system-specific. */ PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */ ) var pfStrings = []intName{ {0x1, "PF_X"}, {0x2, "PF_W"}, {0x4, "PF_R"}, } func (i ProgFlag) String() string { return flagName(uint32(i), pfStrings, false) } func (i ProgFlag) GoString() string { return flagName(uint32(i), pfStrings, true) } // Dyn.Tag type DynTag int const ( DT_NULL DynTag = 0 /* Terminating entry. */ DT_NEEDED DynTag = 1 /* String table offset of a needed shared library. */ DT_PLTRELSZ DynTag = 2 /* Total size in bytes of PLT relocations. */ DT_PLTGOT DynTag = 3 /* Processor-dependent address. */ DT_HASH DynTag = 4 /* Address of symbol hash table. */ DT_STRTAB DynTag = 5 /* Address of string table. */ DT_SYMTAB DynTag = 6 /* Address of symbol table. */ DT_RELA DynTag = 7 /* Address of ElfNN_Rela relocations. */ DT_RELASZ DynTag = 8 /* Total size of ElfNN_Rela relocations. */ DT_RELAENT DynTag = 9 /* Size of each ElfNN_Rela relocation entry. */ DT_STRSZ DynTag = 10 /* Size of string table. */ DT_SYMENT DynTag = 11 /* Size of each symbol table entry. */ DT_INIT DynTag = 12 /* Address of initialization function. */ DT_FINI DynTag = 13 /* Address of finalization function. */ DT_SONAME DynTag = 14 /* String table offset of shared object name. */ DT_RPATH DynTag = 15 /* String table offset of library path. [sup] */ DT_SYMBOLIC DynTag = 16 /* Indicates "symbolic" linking. [sup] */ DT_REL DynTag = 17 /* Address of ElfNN_Rel relocations. */ DT_RELSZ DynTag = 18 /* Total size of ElfNN_Rel relocations. */ DT_RELENT DynTag = 19 /* Size of each ElfNN_Rel relocation. */ DT_PLTREL DynTag = 20 /* Type of relocation used for PLT. */ DT_DEBUG DynTag = 21 /* Reserved (not used). */ DT_TEXTREL DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */ DT_JMPREL DynTag = 23 /* Address of PLT relocations. */ DT_BIND_NOW DynTag = 24 /* [sup] */ DT_INIT_ARRAY DynTag = 25 /* Address of the array of pointers to initialization functions */ DT_FINI_ARRAY DynTag = 26 /* Address of the array of pointers to termination functions */ DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */ DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */ DT_RUNPATH DynTag = 29 /* String table offset of a null-terminated library search path string. */ DT_FLAGS DynTag = 30 /* Object specific flag values. */ DT_ENCODING DynTag = 32 /* Values greater than or equal to DT_ENCODING and less than DT_LOOS follow the rules for the interpretation of the d_un union as follows: even == 'd_ptr', even == 'd_val' or none */ DT_PREINIT_ARRAY DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */ DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */ DT_LOOS DynTag = 0x6000000d /* First OS-specific */ DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */ DT_VERSYM DynTag = 0x6ffffff0 DT_VERNEED DynTag = 0x6ffffffe DT_VERNEEDNUM DynTag = 0x6fffffff DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */ DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */ ) var dtStrings = []intName{ {0, "DT_NULL"}, {1, "DT_NEEDED"}, {2, "DT_PLTRELSZ"}, {3, "DT_PLTGOT"}, {4, "DT_HASH"}, {5, "DT_STRTAB"}, {6, "DT_SYMTAB"}, {7, "DT_RELA"}, {8, "DT_RELASZ"}, {9, "DT_RELAENT"}, {10, "DT_STRSZ"}, {11, "DT_SYMENT"}, {12, "DT_INIT"}, {13, "DT_FINI"}, {14, "DT_SONAME"}, {15, "DT_RPATH"}, {16, "DT_SYMBOLIC"}, {17, "DT_REL"}, {18, "DT_RELSZ"}, {19, "DT_RELENT"}, {20, "DT_PLTREL"}, {21, "DT_DEBUG"}, {22, "DT_TEXTREL"}, {23, "DT_JMPREL"}, {24, "DT_BIND_NOW"}, {25, "DT_INIT_ARRAY"}, {26, "DT_FINI_ARRAY"}, {27, "DT_INIT_ARRAYSZ"}, {28, "DT_FINI_ARRAYSZ"}, {29, "DT_RUNPATH"}, {30, "DT_FLAGS"}, {32, "DT_ENCODING"}, {32, "DT_PREINIT_ARRAY"}, {33, "DT_PREINIT_ARRAYSZ"}, {0x6000000d, "DT_LOOS"}, {0x6ffff000, "DT_HIOS"}, {0x6ffffff0, "DT_VERSYM"}, {0x6ffffffe, "DT_VERNEED"}, {0x6fffffff, "DT_VERNEEDNUM"}, {0x70000000, "DT_LOPROC"}, {0x7fffffff, "DT_HIPROC"}, } func (i DynTag) String() string { return stringName(uint32(i), dtStrings, false) } func (i DynTag) GoString() string { return stringName(uint32(i), dtStrings, true) } // DT_FLAGS values. type DynFlag int const ( DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may make reference to the $ORIGIN substitution string */ DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */ DF_TEXTREL DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */ DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should process all relocations for the object containing this entry before transferring control to the program. */ DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or executable contains code using a static thread-local storage scheme. */ ) var dflagStrings = []intName{ {0x0001, "DF_ORIGIN"}, {0x0002, "DF_SYMBOLIC"}, {0x0004, "DF_TEXTREL"}, {0x0008, "DF_BIND_NOW"}, {0x0010, "DF_STATIC_TLS"}, } func (i DynFlag) String() string { return flagName(uint32(i), dflagStrings, false) } func (i DynFlag) GoString() string { return flagName(uint32(i), dflagStrings, true) } // NType values; used in core files. type NType int const ( NT_PRSTATUS NType = 1 /* Process status. */ NT_FPREGSET NType = 2 /* Floating point registers. */ NT_PRPSINFO NType = 3 /* Process state info. */ ) var ntypeStrings = []intName{ {1, "NT_PRSTATUS"}, {2, "NT_FPREGSET"}, {3, "NT_PRPSINFO"}, } func (i NType) String() string { return stringName(uint32(i), ntypeStrings, false) } func (i NType) GoString() string { return stringName(uint32(i), ntypeStrings, true) } /* Symbol Binding - ELFNN_ST_BIND - st_info */ type SymBind int const ( STB_LOCAL SymBind = 0 /* Local symbol */ STB_GLOBAL SymBind = 1 /* Global symbol */ STB_WEAK SymBind = 2 /* like global - lower precedence */ STB_LOOS SymBind = 10 /* Reserved range for operating system */ STB_HIOS SymBind = 12 /* specific semantics. */ STB_LOPROC SymBind = 13 /* reserved range for processor */ STB_HIPROC SymBind = 15 /* specific semantics. */ ) var stbStrings = []intName{ {0, "STB_LOCAL"}, {1, "STB_GLOBAL"}, {2, "STB_WEAK"}, {10, "STB_LOOS"}, {12, "STB_HIOS"}, {13, "STB_LOPROC"}, {15, "STB_HIPROC"}, } func (i SymBind) String() string { return stringName(uint32(i), stbStrings, false) } func (i SymBind) GoString() string { return stringName(uint32(i), stbStrings, true) } /* Symbol type - ELFNN_ST_TYPE - st_info */ type SymType int const ( STT_NOTYPE SymType = 0 /* Unspecified type. */ STT_OBJECT SymType = 1 /* Data object. */ STT_FUNC SymType = 2 /* Function. */ STT_SECTION SymType = 3 /* Section. */ STT_FILE SymType = 4 /* Source file. */ STT_COMMON SymType = 5 /* Uninitialized common block. */ STT_TLS SymType = 6 /* TLS object. */ STT_LOOS SymType = 10 /* Reserved range for operating system */ STT_HIOS SymType = 12 /* specific semantics. */ STT_LOPROC SymType = 13 /* reserved range for processor */ STT_HIPROC SymType = 15 /* specific semantics. */ ) var sttStrings = []intName{ {0, "STT_NOTYPE"}, {1, "STT_OBJECT"}, {2, "STT_FUNC"}, {3, "STT_SECTION"}, {4, "STT_FILE"}, {5, "STT_COMMON"}, {6, "STT_TLS"}, {10, "STT_LOOS"}, {12, "STT_HIOS"}, {13, "STT_LOPROC"}, {15, "STT_HIPROC"}, } func (i SymType) String() string { return stringName(uint32(i), sttStrings, false) } func (i SymType) GoString() string { return stringName(uint32(i), sttStrings, true) } /* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */ type SymVis int const ( STV_DEFAULT SymVis = 0x0 /* Default visibility (see binding). */ STV_INTERNAL SymVis = 0x1 /* Special meaning in relocatable objects. */ STV_HIDDEN SymVis = 0x2 /* Not visible. */ STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */ ) var stvStrings = []intName{ {0x0, "STV_DEFAULT"}, {0x1, "STV_INTERNAL"}, {0x2, "STV_HIDDEN"}, {0x3, "STV_PROTECTED"}, } func (i SymVis) String() string { return stringName(uint32(i), stvStrings, false) } func (i SymVis) GoString() string { return stringName(uint32(i), stvStrings, true) } /* * Relocation types. */ // Relocation types for x86-64. type R_X86_64 int const ( R_X86_64_NONE R_X86_64 = 0 /* No relocation. */ R_X86_64_64 R_X86_64 = 1 /* Add 64 bit symbol value. */ R_X86_64_PC32 R_X86_64 = 2 /* PC-relative 32 bit signed sym value. */ R_X86_64_GOT32 R_X86_64 = 3 /* PC-relative 32 bit GOT offset. */ R_X86_64_PLT32 R_X86_64 = 4 /* PC-relative 32 bit PLT offset. */ R_X86_64_COPY R_X86_64 = 5 /* Copy data from shared object. */ R_X86_64_GLOB_DAT R_X86_64 = 6 /* Set GOT entry to data address. */ R_X86_64_JMP_SLOT R_X86_64 = 7 /* Set GOT entry to code address. */ R_X86_64_RELATIVE R_X86_64 = 8 /* Add load address of shared object. */ R_X86_64_GOTPCREL R_X86_64 = 9 /* Add 32 bit signed pcrel offset to GOT. */ R_X86_64_32 R_X86_64 = 10 /* Add 32 bit zero extended symbol value */ R_X86_64_32S R_X86_64 = 11 /* Add 32 bit sign extended symbol value */ R_X86_64_16 R_X86_64 = 12 /* Add 16 bit zero extended symbol value */ R_X86_64_PC16 R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */ R_X86_64_8 R_X86_64 = 14 /* Add 8 bit zero extended symbol value */ R_X86_64_PC8 R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */ R_X86_64_DTPMOD64 R_X86_64 = 16 /* ID of module containing symbol */ R_X86_64_DTPOFF64 R_X86_64 = 17 /* Offset in TLS block */ R_X86_64_TPOFF64 R_X86_64 = 18 /* Offset in static TLS block */ R_X86_64_TLSGD R_X86_64 = 19 /* PC relative offset to GD GOT entry */ R_X86_64_TLSLD R_X86_64 = 20 /* PC relative offset to LD GOT entry */ R_X86_64_DTPOFF32 R_X86_64 = 21 /* Offset in TLS block */ R_X86_64_GOTTPOFF R_X86_64 = 22 /* PC relative offset to IE GOT entry */ R_X86_64_TPOFF32 R_X86_64 = 23 /* Offset in static TLS block */ ) var rx86_64Strings = []intName{ {0, "R_X86_64_NONE"}, {1, "R_X86_64_64"}, {2, "R_X86_64_PC32"}, {3, "R_X86_64_GOT32"}, {4, "R_X86_64_PLT32"}, {5, "R_X86_64_COPY"}, {6, "R_X86_64_GLOB_DAT"}, {7, "R_X86_64_JMP_SLOT"}, {8, "R_X86_64_RELATIVE"}, {9, "R_X86_64_GOTPCREL"}, {10, "R_X86_64_32"}, {11, "R_X86_64_32S"}, {12, "R_X86_64_16"}, {13, "R_X86_64_PC16"}, {14, "R_X86_64_8"}, {15, "R_X86_64_PC8"}, {16, "R_X86_64_DTPMOD64"}, {17, "R_X86_64_DTPOFF64"}, {18, "R_X86_64_TPOFF64"}, {19, "R_X86_64_TLSGD"}, {20, "R_X86_64_TLSLD"}, {21, "R_X86_64_DTPOFF32"}, {22, "R_X86_64_GOTTPOFF"}, {23, "R_X86_64_TPOFF32"}, } func (i R_X86_64) String() string { return stringName(uint32(i), rx86_64Strings, false) } func (i R_X86_64) GoString() string { return stringName(uint32(i), rx86_64Strings, true) } // Relocation types for AArch64 (aka arm64) type R_AARCH64 int const ( R_AARCH64_NONE R_AARCH64 = 0 R_AARCH64_P32_ABS32 R_AARCH64 = 1 R_AARCH64_P32_ABS16 R_AARCH64 = 2 R_AARCH64_P32_PREL32 R_AARCH64 = 3 R_AARCH64_P32_PREL16 R_AARCH64 = 4 R_AARCH64_P32_MOVW_UABS_G0 R_AARCH64 = 5 R_AARCH64_P32_MOVW_UABS_G0_NC R_AARCH64 = 6 R_AARCH64_P32_MOVW_UABS_G1 R_AARCH64 = 7 R_AARCH64_P32_MOVW_SABS_G0 R_AARCH64 = 8 R_AARCH64_P32_LD_PREL_LO19 R_AARCH64 = 9 R_AARCH64_P32_ADR_PREL_LO21 R_AARCH64 = 10 R_AARCH64_P32_ADR_PREL_PG_HI21 R_AARCH64 = 11 R_AARCH64_P32_ADD_ABS_LO12_NC R_AARCH64 = 12 R_AARCH64_P32_LDST8_ABS_LO12_NC R_AARCH64 = 13 R_AARCH64_P32_LDST16_ABS_LO12_NC R_AARCH64 = 14 R_AARCH64_P32_LDST32_ABS_LO12_NC R_AARCH64 = 15 R_AARCH64_P32_LDST64_ABS_LO12_NC R_AARCH64 = 16 R_AARCH64_P32_LDST128_ABS_LO12_NC R_AARCH64 = 17 R_AARCH64_P32_TSTBR14 R_AARCH64 = 18 R_AARCH64_P32_CONDBR19 R_AARCH64 = 19 R_AARCH64_P32_JUMP26 R_AARCH64 = 20 R_AARCH64_P32_CALL26 R_AARCH64 = 21 R_AARCH64_P32_GOT_LD_PREL19 R_AARCH64 = 25 R_AARCH64_P32_ADR_GOT_PAGE R_AARCH64 = 26 R_AARCH64_P32_LD32_GOT_LO12_NC R_AARCH64 = 27 R_AARCH64_P32_TLSGD_ADR_PAGE21 R_AARCH64 = 81 R_AARCH64_P32_TLSGD_ADD_LO12_NC R_AARCH64 = 82 R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 103 R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104 R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 105 R_AARCH64_P32_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 106 R_AARCH64_P32_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 107 R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 108 R_AARCH64_P32_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 109 R_AARCH64_P32_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 110 R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 111 R_AARCH64_P32_TLSDESC_LD_PREL19 R_AARCH64 = 122 R_AARCH64_P32_TLSDESC_ADR_PREL21 R_AARCH64 = 123 R_AARCH64_P32_TLSDESC_ADR_PAGE21 R_AARCH64 = 124 R_AARCH64_P32_TLSDESC_LD32_LO12_NC R_AARCH64 = 125 R_AARCH64_P32_TLSDESC_ADD_LO12_NC R_AARCH64 = 126 R_AARCH64_P32_TLSDESC_CALL R_AARCH64 = 127 R_AARCH64_P32_COPY R_AARCH64 = 180 R_AARCH64_P32_GLOB_DAT R_AARCH64 = 181 R_AARCH64_P32_JUMP_SLOT R_AARCH64 = 182 R_AARCH64_P32_RELATIVE R_AARCH64 = 183 R_AARCH64_P32_TLS_DTPMOD R_AARCH64 = 184 R_AARCH64_P32_TLS_DTPREL R_AARCH64 = 185 R_AARCH64_P32_TLS_TPREL R_AARCH64 = 186 R_AARCH64_P32_TLSDESC R_AARCH64 = 187 R_AARCH64_P32_IRELATIVE R_AARCH64 = 188 R_AARCH64_NULL R_AARCH64 = 256 R_AARCH64_ABS64 R_AARCH64 = 257 R_AARCH64_ABS32 R_AARCH64 = 258 R_AARCH64_ABS16 R_AARCH64 = 259 R_AARCH64_PREL64 R_AARCH64 = 260 R_AARCH64_PREL32 R_AARCH64 = 261 R_AARCH64_PREL16 R_AARCH64 = 262 R_AARCH64_MOVW_UABS_G0 R_AARCH64 = 263 R_AARCH64_MOVW_UABS_G0_NC R_AARCH64 = 264 R_AARCH64_MOVW_UABS_G1 R_AARCH64 = 265 R_AARCH64_MOVW_UABS_G1_NC R_AARCH64 = 266 R_AARCH64_MOVW_UABS_G2 R_AARCH64 = 267 R_AARCH64_MOVW_UABS_G2_NC R_AARCH64 = 268 R_AARCH64_MOVW_UABS_G3 R_AARCH64 = 269 R_AARCH64_MOVW_SABS_G0 R_AARCH64 = 270 R_AARCH64_MOVW_SABS_G1 R_AARCH64 = 271 R_AARCH64_MOVW_SABS_G2 R_AARCH64 = 272 R_AARCH64_LD_PREL_LO19 R_AARCH64 = 273 R_AARCH64_ADR_PREL_LO21 R_AARCH64 = 274 R_AARCH64_ADR_PREL_PG_HI21 R_AARCH64 = 275 R_AARCH64_ADR_PREL_PG_HI21_NC R_AARCH64 = 276 R_AARCH64_ADD_ABS_LO12_NC R_AARCH64 = 277 R_AARCH64_LDST8_ABS_LO12_NC R_AARCH64 = 278 R_AARCH64_TSTBR14 R_AARCH64 = 279 R_AARCH64_CONDBR19 R_AARCH64 = 280 R_AARCH64_JUMP26 R_AARCH64 = 282 R_AARCH64_CALL26 R_AARCH64 = 283 R_AARCH64_LDST16_ABS_LO12_NC R_AARCH64 = 284 R_AARCH64_LDST32_ABS_LO12_NC R_AARCH64 = 285 R_AARCH64_LDST64_ABS_LO12_NC R_AARCH64 = 286 R_AARCH64_LDST128_ABS_LO12_NC R_AARCH64 = 299 R_AARCH64_GOT_LD_PREL19 R_AARCH64 = 309 R_AARCH64_ADR_GOT_PAGE R_AARCH64 = 311 R_AARCH64_LD64_GOT_LO12_NC R_AARCH64 = 312 R_AARCH64_TLSGD_ADR_PAGE21 R_AARCH64 = 513 R_AARCH64_TLSGD_ADD_LO12_NC R_AARCH64 = 514 R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 R_AARCH64 = 539 R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC R_AARCH64 = 540 R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 541 R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC R_AARCH64 = 542 R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 543 R_AARCH64_TLSLE_MOVW_TPREL_G2 R_AARCH64 = 544 R_AARCH64_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 545 R_AARCH64_TLSLE_MOVW_TPREL_G1_NC R_AARCH64 = 546 R_AARCH64_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 547 R_AARCH64_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 548 R_AARCH64_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 549 R_AARCH64_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 550 R_AARCH64_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 551 R_AARCH64_TLSDESC_LD_PREL19 R_AARCH64 = 560 R_AARCH64_TLSDESC_ADR_PREL21 R_AARCH64 = 561 R_AARCH64_TLSDESC_ADR_PAGE21 R_AARCH64 = 562 R_AARCH64_TLSDESC_LD64_LO12_NC R_AARCH64 = 563 R_AARCH64_TLSDESC_ADD_LO12_NC R_AARCH64 = 564 R_AARCH64_TLSDESC_OFF_G1 R_AARCH64 = 565 R_AARCH64_TLSDESC_OFF_G0_NC R_AARCH64 = 566 R_AARCH64_TLSDESC_LDR R_AARCH64 = 567 R_AARCH64_TLSDESC_ADD R_AARCH64 = 568 R_AARCH64_TLSDESC_CALL R_AARCH64 = 569 R_AARCH64_COPY R_AARCH64 = 1024 R_AARCH64_GLOB_DAT R_AARCH64 = 1025 R_AARCH64_JUMP_SLOT R_AARCH64 = 1026 R_AARCH64_RELATIVE R_AARCH64 = 1027 R_AARCH64_TLS_DTPMOD64 R_AARCH64 = 1028 R_AARCH64_TLS_DTPREL64 R_AARCH64 = 1029 R_AARCH64_TLS_TPREL64 R_AARCH64 = 1030 R_AARCH64_TLSDESC R_AARCH64 = 1031 R_AARCH64_IRELATIVE R_AARCH64 = 1032 ) var raarch64Strings = []intName{ {0, "R_AARCH64_NONE"}, {1, "R_AARCH64_P32_ABS32"}, {2, "R_AARCH64_P32_ABS16"}, {3, "R_AARCH64_P32_PREL32"}, {4, "R_AARCH64_P32_PREL16"}, {5, "R_AARCH64_P32_MOVW_UABS_G0"}, {6, "R_AARCH64_P32_MOVW_UABS_G0_NC"}, {7, "R_AARCH64_P32_MOVW_UABS_G1"}, {8, "R_AARCH64_P32_MOVW_SABS_G0"}, {9, "R_AARCH64_P32_LD_PREL_LO19"}, {10, "R_AARCH64_P32_ADR_PREL_LO21"}, {11, "R_AARCH64_P32_ADR_PREL_PG_HI21"}, {12, "R_AARCH64_P32_ADD_ABS_LO12_NC"}, {13, "R_AARCH64_P32_LDST8_ABS_LO12_NC"}, {14, "R_AARCH64_P32_LDST16_ABS_LO12_NC"}, {15, "R_AARCH64_P32_LDST32_ABS_LO12_NC"}, {16, "R_AARCH64_P32_LDST64_ABS_LO12_NC"}, {17, "R_AARCH64_P32_LDST128_ABS_LO12_NC"}, {18, "R_AARCH64_P32_TSTBR14"}, {19, "R_AARCH64_P32_CONDBR19"}, {20, "R_AARCH64_P32_JUMP26"}, {21, "R_AARCH64_P32_CALL26"}, {25, "R_AARCH64_P32_GOT_LD_PREL19"}, {26, "R_AARCH64_P32_ADR_GOT_PAGE"}, {27, "R_AARCH64_P32_LD32_GOT_LO12_NC"}, {81, "R_AARCH64_P32_TLSGD_ADR_PAGE21"}, {82, "R_AARCH64_P32_TLSGD_ADD_LO12_NC"}, {103, "R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21"}, {104, "R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC"}, {105, "R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19"}, {106, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G1"}, {107, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0"}, {108, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC"}, {109, "R_AARCH64_P32_TLSLE_ADD_TPREL_HI12"}, {110, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12"}, {111, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC"}, {122, "R_AARCH64_P32_TLSDESC_LD_PREL19"}, {123, "R_AARCH64_P32_TLSDESC_ADR_PREL21"}, {124, "R_AARCH64_P32_TLSDESC_ADR_PAGE21"}, {125, "R_AARCH64_P32_TLSDESC_LD32_LO12_NC"}, {126, "R_AARCH64_P32_TLSDESC_ADD_LO12_NC"}, {127, "R_AARCH64_P32_TLSDESC_CALL"}, {180, "R_AARCH64_P32_COPY"}, {181, "R_AARCH64_P32_GLOB_DAT"}, {182, "R_AARCH64_P32_JUMP_SLOT"}, {183, "R_AARCH64_P32_RELATIVE"}, {184, "R_AARCH64_P32_TLS_DTPMOD"}, {185, "R_AARCH64_P32_TLS_DTPREL"}, {186, "R_AARCH64_P32_TLS_TPREL"}, {187, "R_AARCH64_P32_TLSDESC"}, {188, "R_AARCH64_P32_IRELATIVE"}, {256, "R_AARCH64_NULL"}, {257, "R_AARCH64_ABS64"}, {258, "R_AARCH64_ABS32"}, {259, "R_AARCH64_ABS16"}, {260, "R_AARCH64_PREL64"}, {261, "R_AARCH64_PREL32"}, {262, "R_AARCH64_PREL16"}, {263, "R_AARCH64_MOVW_UABS_G0"}, {264, "R_AARCH64_MOVW_UABS_G0_NC"}, {265, "R_AARCH64_MOVW_UABS_G1"}, {266, "R_AARCH64_MOVW_UABS_G1_NC"}, {267, "R_AARCH64_MOVW_UABS_G2"}, {268, "R_AARCH64_MOVW_UABS_G2_NC"}, {269, "R_AARCH64_MOVW_UABS_G3"}, {270, "R_AARCH64_MOVW_SABS_G0"}, {271, "R_AARCH64_MOVW_SABS_G1"}, {272, "R_AARCH64_MOVW_SABS_G2"}, {273, "R_AARCH64_LD_PREL_LO19"}, {274, "R_AARCH64_ADR_PREL_LO21"}, {275, "R_AARCH64_ADR_PREL_PG_HI21"}, {276, "R_AARCH64_ADR_PREL_PG_HI21_NC"}, {277, "R_AARCH64_ADD_ABS_LO12_NC"}, {278, "R_AARCH64_LDST8_ABS_LO12_NC"}, {279, "R_AARCH64_TSTBR14"}, {280, "R_AARCH64_CONDBR19"}, {282, "R_AARCH64_JUMP26"}, {283, "R_AARCH64_CALL26"}, {284, "R_AARCH64_LDST16_ABS_LO12_NC"}, {285, "R_AARCH64_LDST32_ABS_LO12_NC"}, {286, "R_AARCH64_LDST64_ABS_LO12_NC"}, {299, "R_AARCH64_LDST128_ABS_LO12_NC"}, {309, "R_AARCH64_GOT_LD_PREL19"}, {311, "R_AARCH64_ADR_GOT_PAGE"}, {312, "R_AARCH64_LD64_GOT_LO12_NC"}, {513, "R_AARCH64_TLSGD_ADR_PAGE21"}, {514, "R_AARCH64_TLSGD_ADD_LO12_NC"}, {539, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G1"}, {540, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC"}, {541, "R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21"}, {542, "R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC"}, {543, "R_AARCH64_TLSIE_LD_GOTTPREL_PREL19"}, {544, "R_AARCH64_TLSLE_MOVW_TPREL_G2"}, {545, "R_AARCH64_TLSLE_MOVW_TPREL_G1"}, {546, "R_AARCH64_TLSLE_MOVW_TPREL_G1_NC"}, {547, "R_AARCH64_TLSLE_MOVW_TPREL_G0"}, {548, "R_AARCH64_TLSLE_MOVW_TPREL_G0_NC"}, {549, "R_AARCH64_TLSLE_ADD_TPREL_HI12"}, {550, "R_AARCH64_TLSLE_ADD_TPREL_LO12"}, {551, "R_AARCH64_TLSLE_ADD_TPREL_LO12_NC"}, {560, "R_AARCH64_TLSDESC_LD_PREL19"}, {561, "R_AARCH64_TLSDESC_ADR_PREL21"}, {562, "R_AARCH64_TLSDESC_ADR_PAGE21"}, {563, "R_AARCH64_TLSDESC_LD64_LO12_NC"}, {564, "R_AARCH64_TLSDESC_ADD_LO12_NC"}, {565, "R_AARCH64_TLSDESC_OFF_G1"}, {566, "R_AARCH64_TLSDESC_OFF_G0_NC"}, {567, "R_AARCH64_TLSDESC_LDR"}, {568, "R_AARCH64_TLSDESC_ADD"}, {569, "R_AARCH64_TLSDESC_CALL"}, {1024, "R_AARCH64_COPY"}, {1025, "R_AARCH64_GLOB_DAT"}, {1026, "R_AARCH64_JUMP_SLOT"}, {1027, "R_AARCH64_RELATIVE"}, {1028, "R_AARCH64_TLS_DTPMOD64"}, {1029, "R_AARCH64_TLS_DTPREL64"}, {1030, "R_AARCH64_TLS_TPREL64"}, {1031, "R_AARCH64_TLSDESC"}, {1032, "R_AARCH64_IRELATIVE"}, } func (i R_AARCH64) String() string { return stringName(uint32(i), raarch64Strings, false) } func (i R_AARCH64) GoString() string { return stringName(uint32(i), raarch64Strings, true) } // Relocation types for Alpha. type R_ALPHA int const ( R_ALPHA_NONE R_ALPHA = 0 /* No reloc */ R_ALPHA_REFLONG R_ALPHA = 1 /* Direct 32 bit */ R_ALPHA_REFQUAD R_ALPHA = 2 /* Direct 64 bit */ R_ALPHA_GPREL32 R_ALPHA = 3 /* GP relative 32 bit */ R_ALPHA_LITERAL R_ALPHA = 4 /* GP relative 16 bit w/optimization */ R_ALPHA_LITUSE R_ALPHA = 5 /* Optimization hint for LITERAL */ R_ALPHA_GPDISP R_ALPHA = 6 /* Add displacement to GP */ R_ALPHA_BRADDR R_ALPHA = 7 /* PC+4 relative 23 bit shifted */ R_ALPHA_HINT R_ALPHA = 8 /* PC+4 relative 16 bit shifted */ R_ALPHA_SREL16 R_ALPHA = 9 /* PC relative 16 bit */ R_ALPHA_SREL32 R_ALPHA = 10 /* PC relative 32 bit */ R_ALPHA_SREL64 R_ALPHA = 11 /* PC relative 64 bit */ R_ALPHA_OP_PUSH R_ALPHA = 12 /* OP stack push */ R_ALPHA_OP_STORE R_ALPHA = 13 /* OP stack pop and store */ R_ALPHA_OP_PSUB R_ALPHA = 14 /* OP stack subtract */ R_ALPHA_OP_PRSHIFT R_ALPHA = 15 /* OP stack right shift */ R_ALPHA_GPVALUE R_ALPHA = 16 R_ALPHA_GPRELHIGH R_ALPHA = 17 R_ALPHA_GPRELLOW R_ALPHA = 18 R_ALPHA_IMMED_GP_16 R_ALPHA = 19 R_ALPHA_IMMED_GP_HI32 R_ALPHA = 20 R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21 R_ALPHA_IMMED_BR_HI32 R_ALPHA = 22 R_ALPHA_IMMED_LO32 R_ALPHA = 23 R_ALPHA_COPY R_ALPHA = 24 /* Copy symbol at runtime */ R_ALPHA_GLOB_DAT R_ALPHA = 25 /* Create GOT entry */ R_ALPHA_JMP_SLOT R_ALPHA = 26 /* Create PLT entry */ R_ALPHA_RELATIVE R_ALPHA = 27 /* Adjust by program base */ ) var ralphaStrings = []intName{ {0, "R_ALPHA_NONE"}, {1, "R_ALPHA_REFLONG"}, {2, "R_ALPHA_REFQUAD"}, {3, "R_ALPHA_GPREL32"}, {4, "R_ALPHA_LITERAL"}, {5, "R_ALPHA_LITUSE"}, {6, "R_ALPHA_GPDISP"}, {7, "R_ALPHA_BRADDR"}, {8, "R_ALPHA_HINT"}, {9, "R_ALPHA_SREL16"}, {10, "R_ALPHA_SREL32"}, {11, "R_ALPHA_SREL64"}, {12, "R_ALPHA_OP_PUSH"}, {13, "R_ALPHA_OP_STORE"}, {14, "R_ALPHA_OP_PSUB"}, {15, "R_ALPHA_OP_PRSHIFT"}, {16, "R_ALPHA_GPVALUE"}, {17, "R_ALPHA_GPRELHIGH"}, {18, "R_ALPHA_GPRELLOW"}, {19, "R_ALPHA_IMMED_GP_16"}, {20, "R_ALPHA_IMMED_GP_HI32"}, {21, "R_ALPHA_IMMED_SCN_HI32"}, {22, "R_ALPHA_IMMED_BR_HI32"}, {23, "R_ALPHA_IMMED_LO32"}, {24, "R_ALPHA_COPY"}, {25, "R_ALPHA_GLOB_DAT"}, {26, "R_ALPHA_JMP_SLOT"}, {27, "R_ALPHA_RELATIVE"}, } func (i R_ALPHA) String() string { return stringName(uint32(i), ralphaStrings, false) } func (i R_ALPHA) GoString() string { return stringName(uint32(i), ralphaStrings, true) } // Relocation types for ARM. type R_ARM int const ( R_ARM_NONE R_ARM = 0 /* No relocation. */ R_ARM_PC24 R_ARM = 1 R_ARM_ABS32 R_ARM = 2 R_ARM_REL32 R_ARM = 3 R_ARM_PC13 R_ARM = 4 R_ARM_ABS16 R_ARM = 5 R_ARM_ABS12 R_ARM = 6 R_ARM_THM_ABS5 R_ARM = 7 R_ARM_ABS8 R_ARM = 8 R_ARM_SBREL32 R_ARM = 9 R_ARM_THM_PC22 R_ARM = 10 R_ARM_THM_PC8 R_ARM = 11 R_ARM_AMP_VCALL9 R_ARM = 12 R_ARM_SWI24 R_ARM = 13 R_ARM_THM_SWI8 R_ARM = 14 R_ARM_XPC25 R_ARM = 15 R_ARM_THM_XPC22 R_ARM = 16 R_ARM_COPY R_ARM = 20 /* Copy data from shared object. */ R_ARM_GLOB_DAT R_ARM = 21 /* Set GOT entry to data address. */ R_ARM_JUMP_SLOT R_ARM = 22 /* Set GOT entry to code address. */ R_ARM_RELATIVE R_ARM = 23 /* Add load address of shared object. */ R_ARM_GOTOFF R_ARM = 24 /* Add GOT-relative symbol address. */ R_ARM_GOTPC R_ARM = 25 /* Add PC-relative GOT table address. */ R_ARM_GOT32 R_ARM = 26 /* Add PC-relative GOT offset. */ R_ARM_PLT32 R_ARM = 27 /* Add PC-relative PLT offset. */ R_ARM_GNU_VTENTRY R_ARM = 100 R_ARM_GNU_VTINHERIT R_ARM = 101 R_ARM_RSBREL32 R_ARM = 250 R_ARM_THM_RPC22 R_ARM = 251 R_ARM_RREL32 R_ARM = 252 R_ARM_RABS32 R_ARM = 253 R_ARM_RPC24 R_ARM = 254 R_ARM_RBASE R_ARM = 255 ) var rarmStrings = []intName{ {0, "R_ARM_NONE"}, {1, "R_ARM_PC24"}, {2, "R_ARM_ABS32"}, {3, "R_ARM_REL32"}, {4, "R_ARM_PC13"}, {5, "R_ARM_ABS16"}, {6, "R_ARM_ABS12"}, {7, "R_ARM_THM_ABS5"}, {8, "R_ARM_ABS8"}, {9, "R_ARM_SBREL32"}, {10, "R_ARM_THM_PC22"}, {11, "R_ARM_THM_PC8"}, {12, "R_ARM_AMP_VCALL9"}, {13, "R_ARM_SWI24"}, {14, "R_ARM_THM_SWI8"}, {15, "R_ARM_XPC25"}, {16, "R_ARM_THM_XPC22"}, {20, "R_ARM_COPY"}, {21, "R_ARM_GLOB_DAT"}, {22, "R_ARM_JUMP_SLOT"}, {23, "R_ARM_RELATIVE"}, {24, "R_ARM_GOTOFF"}, {25, "R_ARM_GOTPC"}, {26, "R_ARM_GOT32"}, {27, "R_ARM_PLT32"}, {100, "R_ARM_GNU_VTENTRY"}, {101, "R_ARM_GNU_VTINHERIT"}, {250, "R_ARM_RSBREL32"}, {251, "R_ARM_THM_RPC22"}, {252, "R_ARM_RREL32"}, {253, "R_ARM_RABS32"}, {254, "R_ARM_RPC24"}, {255, "R_ARM_RBASE"}, } func (i R_ARM) String() string { return stringName(uint32(i), rarmStrings, false) } func (i R_ARM) GoString() string { return stringName(uint32(i), rarmStrings, true) } // Relocation types for 386. type R_386 int const ( R_386_NONE R_386 = 0 /* No relocation. */ R_386_32 R_386 = 1 /* Add symbol value. */ R_386_PC32 R_386 = 2 /* Add PC-relative symbol value. */ R_386_GOT32 R_386 = 3 /* Add PC-relative GOT offset. */ R_386_PLT32 R_386 = 4 /* Add PC-relative PLT offset. */ R_386_COPY R_386 = 5 /* Copy data from shared object. */ R_386_GLOB_DAT R_386 = 6 /* Set GOT entry to data address. */ R_386_JMP_SLOT R_386 = 7 /* Set GOT entry to code address. */ R_386_RELATIVE R_386 = 8 /* Add load address of shared object. */ R_386_GOTOFF R_386 = 9 /* Add GOT-relative symbol address. */ R_386_GOTPC R_386 = 10 /* Add PC-relative GOT table address. */ R_386_TLS_TPOFF R_386 = 14 /* Negative offset in static TLS block */ R_386_TLS_IE R_386 = 15 /* Absolute address of GOT for -ve static TLS */ R_386_TLS_GOTIE R_386 = 16 /* GOT entry for negative static TLS block */ R_386_TLS_LE R_386 = 17 /* Negative offset relative to static TLS */ R_386_TLS_GD R_386 = 18 /* 32 bit offset to GOT (index,off) pair */ R_386_TLS_LDM R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */ R_386_TLS_GD_32 R_386 = 24 /* 32 bit offset to GOT (index,off) pair */ R_386_TLS_GD_PUSH R_386 = 25 /* pushl instruction for Sun ABI GD sequence */ R_386_TLS_GD_CALL R_386 = 26 /* call instruction for Sun ABI GD sequence */ R_386_TLS_GD_POP R_386 = 27 /* popl instruction for Sun ABI GD sequence */ R_386_TLS_LDM_32 R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */ R_386_TLS_LDM_PUSH R_386 = 29 /* pushl instruction for Sun ABI LD sequence */ R_386_TLS_LDM_CALL R_386 = 30 /* call instruction for Sun ABI LD sequence */ R_386_TLS_LDM_POP R_386 = 31 /* popl instruction for Sun ABI LD sequence */ R_386_TLS_LDO_32 R_386 = 32 /* 32 bit offset from start of TLS block */ R_386_TLS_IE_32 R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */ R_386_TLS_LE_32 R_386 = 34 /* 32 bit offset within static TLS block */ R_386_TLS_DTPMOD32 R_386 = 35 /* GOT entry containing TLS index */ R_386_TLS_DTPOFF32 R_386 = 36 /* GOT entry containing TLS offset */ R_386_TLS_TPOFF32 R_386 = 37 /* GOT entry of -ve static TLS offset */ ) var r386Strings = []intName{ {0, "R_386_NONE"}, {1, "R_386_32"}, {2, "R_386_PC32"}, {3, "R_386_GOT32"}, {4, "R_386_PLT32"}, {5, "R_386_COPY"}, {6, "R_386_GLOB_DAT"}, {7, "R_386_JMP_SLOT"}, {8, "R_386_RELATIVE"}, {9, "R_386_GOTOFF"}, {10, "R_386_GOTPC"}, {14, "R_386_TLS_TPOFF"}, {15, "R_386_TLS_IE"}, {16, "R_386_TLS_GOTIE"}, {17, "R_386_TLS_LE"}, {18, "R_386_TLS_GD"}, {19, "R_386_TLS_LDM"}, {24, "R_386_TLS_GD_32"}, {25, "R_386_TLS_GD_PUSH"}, {26, "R_386_TLS_GD_CALL"}, {27, "R_386_TLS_GD_POP"}, {28, "R_386_TLS_LDM_32"}, {29, "R_386_TLS_LDM_PUSH"}, {30, "R_386_TLS_LDM_CALL"}, {31, "R_386_TLS_LDM_POP"}, {32, "R_386_TLS_LDO_32"}, {33, "R_386_TLS_IE_32"}, {34, "R_386_TLS_LE_32"}, {35, "R_386_TLS_DTPMOD32"}, {36, "R_386_TLS_DTPOFF32"}, {37, "R_386_TLS_TPOFF32"}, } func (i R_386) String() string { return stringName(uint32(i), r386Strings, false) } func (i R_386) GoString() string { return stringName(uint32(i), r386Strings, true) } // Relocation types for MIPS. type R_MIPS int const ( R_MIPS_NONE R_MIPS = 0 R_MIPS_16 R_MIPS = 1 R_MIPS_32 R_MIPS = 2 R_MIPS_REL32 R_MIPS = 3 R_MIPS_26 R_MIPS = 4 R_MIPS_HI16 R_MIPS = 5 /* high 16 bits of symbol value */ R_MIPS_LO16 R_MIPS = 6 /* low 16 bits of symbol value */ R_MIPS_GPREL16 R_MIPS = 7 /* GP-relative reference */ R_MIPS_LITERAL R_MIPS = 8 /* Reference to literal section */ R_MIPS_GOT16 R_MIPS = 9 /* Reference to global offset table */ R_MIPS_PC16 R_MIPS = 10 /* 16 bit PC relative reference */ R_MIPS_CALL16 R_MIPS = 11 /* 16 bit call thru glbl offset tbl */ R_MIPS_GPREL32 R_MIPS = 12 R_MIPS_SHIFT5 R_MIPS = 16 R_MIPS_SHIFT6 R_MIPS = 17 R_MIPS_64 R_MIPS = 18 R_MIPS_GOT_DISP R_MIPS = 19 R_MIPS_GOT_PAGE R_MIPS = 20 R_MIPS_GOT_OFST R_MIPS = 21 R_MIPS_GOT_HI16 R_MIPS = 22 R_MIPS_GOT_LO16 R_MIPS = 23 R_MIPS_SUB R_MIPS = 24 R_MIPS_INSERT_A R_MIPS = 25 R_MIPS_INSERT_B R_MIPS = 26 R_MIPS_DELETE R_MIPS = 27 R_MIPS_HIGHER R_MIPS = 28 R_MIPS_HIGHEST R_MIPS = 29 R_MIPS_CALL_HI16 R_MIPS = 30 R_MIPS_CALL_LO16 R_MIPS = 31 R_MIPS_SCN_DISP R_MIPS = 32 R_MIPS_REL16 R_MIPS = 33 R_MIPS_ADD_IMMEDIATE R_MIPS = 34 R_MIPS_PJUMP R_MIPS = 35 R_MIPS_RELGOT R_MIPS = 36 R_MIPS_JALR R_MIPS = 37 R_MIPS_TLS_DTPMOD32 R_MIPS = 38 /* Module number 32 bit */ R_MIPS_TLS_DTPREL32 R_MIPS = 39 /* Module-relative offset 32 bit */ R_MIPS_TLS_DTPMOD64 R_MIPS = 40 /* Module number 64 bit */ R_MIPS_TLS_DTPREL64 R_MIPS = 41 /* Module-relative offset 64 bit */ R_MIPS_TLS_GD R_MIPS = 42 /* 16 bit GOT offset for GD */ R_MIPS_TLS_LDM R_MIPS = 43 /* 16 bit GOT offset for LDM */ R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */ R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */ R_MIPS_TLS_GOTTPREL R_MIPS = 46 /* 16 bit GOT offset for IE */ R_MIPS_TLS_TPREL32 R_MIPS = 47 /* TP-relative offset, 32 bit */ R_MIPS_TLS_TPREL64 R_MIPS = 48 /* TP-relative offset, 64 bit */ R_MIPS_TLS_TPREL_HI16 R_MIPS = 49 /* TP-relative offset, high 16 bits */ R_MIPS_TLS_TPREL_LO16 R_MIPS = 50 /* TP-relative offset, low 16 bits */ ) var rmipsStrings = []intName{ {0, "R_MIPS_NONE"}, {1, "R_MIPS_16"}, {2, "R_MIPS_32"}, {3, "R_MIPS_REL32"}, {4, "R_MIPS_26"}, {5, "R_MIPS_HI16"}, {6, "R_MIPS_LO16"}, {7, "R_MIPS_GPREL16"}, {8, "R_MIPS_LITERAL"}, {9, "R_MIPS_GOT16"}, {10, "R_MIPS_PC16"}, {11, "R_MIPS_CALL16"}, {12, "R_MIPS_GPREL32"}, {16, "R_MIPS_SHIFT5"}, {17, "R_MIPS_SHIFT6"}, {18, "R_MIPS_64"}, {19, "R_MIPS_GOT_DISP"}, {20, "R_MIPS_GOT_PAGE"}, {21, "R_MIPS_GOT_OFST"}, {22, "R_MIPS_GOT_HI16"}, {23, "R_MIPS_GOT_LO16"}, {24, "R_MIPS_SUB"}, {25, "R_MIPS_INSERT_A"}, {26, "R_MIPS_INSERT_B"}, {27, "R_MIPS_DELETE"}, {28, "R_MIPS_HIGHER"}, {29, "R_MIPS_HIGHEST"}, {30, "R_MIPS_CALL_HI16"}, {31, "R_MIPS_CALL_LO16"}, {32, "R_MIPS_SCN_DISP"}, {33, "R_MIPS_REL16"}, {34, "R_MIPS_ADD_IMMEDIATE"}, {35, "R_MIPS_PJUMP"}, {36, "R_MIPS_RELGOT"}, {37, "R_MIPS_JALR"}, {38, "R_MIPS_TLS_DTPMOD32"}, {39, "R_MIPS_TLS_DTPREL32"}, {40, "R_MIPS_TLS_DTPMOD64"}, {41, "R_MIPS_TLS_DTPREL64"}, {42, "R_MIPS_TLS_GD"}, {43, "R_MIPS_TLS_LDM"}, {44, "R_MIPS_TLS_DTPREL_HI16"}, {45, "R_MIPS_TLS_DTPREL_LO16"}, {46, "R_MIPS_TLS_GOTTPREL"}, {47, "R_MIPS_TLS_TPREL32"}, {48, "R_MIPS_TLS_TPREL64"}, {49, "R_MIPS_TLS_TPREL_HI16"}, {50, "R_MIPS_TLS_TPREL_LO16"}, } func (i R_MIPS) String() string { return stringName(uint32(i), rmipsStrings, false) } func (i R_MIPS) GoString() string { return stringName(uint32(i), rmipsStrings, true) } // Relocation types for PowerPC. type R_PPC int const ( R_PPC_NONE R_PPC = 0 /* No relocation. */ R_PPC_ADDR32 R_PPC = 1 R_PPC_ADDR24 R_PPC = 2 R_PPC_ADDR16 R_PPC = 3 R_PPC_ADDR16_LO R_PPC = 4 R_PPC_ADDR16_HI R_PPC = 5 R_PPC_ADDR16_HA R_PPC = 6 R_PPC_ADDR14 R_PPC = 7 R_PPC_ADDR14_BRTAKEN R_PPC = 8 R_PPC_ADDR14_BRNTAKEN R_PPC = 9 R_PPC_REL24 R_PPC = 10 R_PPC_REL14 R_PPC = 11 R_PPC_REL14_BRTAKEN R_PPC = 12 R_PPC_REL14_BRNTAKEN R_PPC = 13 R_PPC_GOT16 R_PPC = 14 R_PPC_GOT16_LO R_PPC = 15 R_PPC_GOT16_HI R_PPC = 16 R_PPC_GOT16_HA R_PPC = 17 R_PPC_PLTREL24 R_PPC = 18 R_PPC_COPY R_PPC = 19 R_PPC_GLOB_DAT R_PPC = 20 R_PPC_JMP_SLOT R_PPC = 21 R_PPC_RELATIVE R_PPC = 22 R_PPC_LOCAL24PC R_PPC = 23 R_PPC_UADDR32 R_PPC = 24 R_PPC_UADDR16 R_PPC = 25 R_PPC_REL32 R_PPC = 26 R_PPC_PLT32 R_PPC = 27 R_PPC_PLTREL32 R_PPC = 28 R_PPC_PLT16_LO R_PPC = 29 R_PPC_PLT16_HI R_PPC = 30 R_PPC_PLT16_HA R_PPC = 31 R_PPC_SDAREL16 R_PPC = 32 R_PPC_SECTOFF R_PPC = 33 R_PPC_SECTOFF_LO R_PPC = 34 R_PPC_SECTOFF_HI R_PPC = 35 R_PPC_SECTOFF_HA R_PPC = 36 R_PPC_TLS R_PPC = 67 R_PPC_DTPMOD32 R_PPC = 68 R_PPC_TPREL16 R_PPC = 69 R_PPC_TPREL16_LO R_PPC = 70 R_PPC_TPREL16_HI R_PPC = 71 R_PPC_TPREL16_HA R_PPC = 72 R_PPC_TPREL32 R_PPC = 73 R_PPC_DTPREL16 R_PPC = 74 R_PPC_DTPREL16_LO R_PPC = 75 R_PPC_DTPREL16_HI R_PPC = 76 R_PPC_DTPREL16_HA R_PPC = 77 R_PPC_DTPREL32 R_PPC = 78 R_PPC_GOT_TLSGD16 R_PPC = 79 R_PPC_GOT_TLSGD16_LO R_PPC = 80 R_PPC_GOT_TLSGD16_HI R_PPC = 81 R_PPC_GOT_TLSGD16_HA R_PPC = 82 R_PPC_GOT_TLSLD16 R_PPC = 83 R_PPC_GOT_TLSLD16_LO R_PPC = 84 R_PPC_GOT_TLSLD16_HI R_PPC = 85 R_PPC_GOT_TLSLD16_HA R_PPC = 86 R_PPC_GOT_TPREL16 R_PPC = 87 R_PPC_GOT_TPREL16_LO R_PPC = 88 R_PPC_GOT_TPREL16_HI R_PPC = 89 R_PPC_GOT_TPREL16_HA R_PPC = 90 R_PPC_EMB_NADDR32 R_PPC = 101 R_PPC_EMB_NADDR16 R_PPC = 102 R_PPC_EMB_NADDR16_LO R_PPC = 103 R_PPC_EMB_NADDR16_HI R_PPC = 104 R_PPC_EMB_NADDR16_HA R_PPC = 105 R_PPC_EMB_SDAI16 R_PPC = 106 R_PPC_EMB_SDA2I16 R_PPC = 107 R_PPC_EMB_SDA2REL R_PPC = 108 R_PPC_EMB_SDA21 R_PPC = 109 R_PPC_EMB_MRKREF R_PPC = 110 R_PPC_EMB_RELSEC16 R_PPC = 111 R_PPC_EMB_RELST_LO R_PPC = 112 R_PPC_EMB_RELST_HI R_PPC = 113 R_PPC_EMB_RELST_HA R_PPC = 114 R_PPC_EMB_BIT_FLD R_PPC = 115 R_PPC_EMB_RELSDA R_PPC = 116 ) var rppcStrings = []intName{ {0, "R_PPC_NONE"}, {1, "R_PPC_ADDR32"}, {2, "R_PPC_ADDR24"}, {3, "R_PPC_ADDR16"}, {4, "R_PPC_ADDR16_LO"}, {5, "R_PPC_ADDR16_HI"}, {6, "R_PPC_ADDR16_HA"}, {7, "R_PPC_ADDR14"}, {8, "R_PPC_ADDR14_BRTAKEN"}, {9, "R_PPC_ADDR14_BRNTAKEN"}, {10, "R_PPC_REL24"}, {11, "R_PPC_REL14"}, {12, "R_PPC_REL14_BRTAKEN"}, {13, "R_PPC_REL14_BRNTAKEN"}, {14, "R_PPC_GOT16"}, {15, "R_PPC_GOT16_LO"}, {16, "R_PPC_GOT16_HI"}, {17, "R_PPC_GOT16_HA"}, {18, "R_PPC_PLTREL24"}, {19, "R_PPC_COPY"}, {20, "R_PPC_GLOB_DAT"}, {21, "R_PPC_JMP_SLOT"}, {22, "R_PPC_RELATIVE"}, {23, "R_PPC_LOCAL24PC"}, {24, "R_PPC_UADDR32"}, {25, "R_PPC_UADDR16"}, {26, "R_PPC_REL32"}, {27, "R_PPC_PLT32"}, {28, "R_PPC_PLTREL32"}, {29, "R_PPC_PLT16_LO"}, {30, "R_PPC_PLT16_HI"}, {31, "R_PPC_PLT16_HA"}, {32, "R_PPC_SDAREL16"}, {33, "R_PPC_SECTOFF"}, {34, "R_PPC_SECTOFF_LO"}, {35, "R_PPC_SECTOFF_HI"}, {36, "R_PPC_SECTOFF_HA"}, {67, "R_PPC_TLS"}, {68, "R_PPC_DTPMOD32"}, {69, "R_PPC_TPREL16"}, {70, "R_PPC_TPREL16_LO"}, {71, "R_PPC_TPREL16_HI"}, {72, "R_PPC_TPREL16_HA"}, {73, "R_PPC_TPREL32"}, {74, "R_PPC_DTPREL16"}, {75, "R_PPC_DTPREL16_LO"}, {76, "R_PPC_DTPREL16_HI"}, {77, "R_PPC_DTPREL16_HA"}, {78, "R_PPC_DTPREL32"}, {79, "R_PPC_GOT_TLSGD16"}, {80, "R_PPC_GOT_TLSGD16_LO"}, {81, "R_PPC_GOT_TLSGD16_HI"}, {82, "R_PPC_GOT_TLSGD16_HA"}, {83, "R_PPC_GOT_TLSLD16"}, {84, "R_PPC_GOT_TLSLD16_LO"}, {85, "R_PPC_GOT_TLSLD16_HI"}, {86, "R_PPC_GOT_TLSLD16_HA"}, {87, "R_PPC_GOT_TPREL16"}, {88, "R_PPC_GOT_TPREL16_LO"}, {89, "R_PPC_GOT_TPREL16_HI"}, {90, "R_PPC_GOT_TPREL16_HA"}, {101, "R_PPC_EMB_NADDR32"}, {102, "R_PPC_EMB_NADDR16"}, {103, "R_PPC_EMB_NADDR16_LO"}, {104, "R_PPC_EMB_NADDR16_HI"}, {105, "R_PPC_EMB_NADDR16_HA"}, {106, "R_PPC_EMB_SDAI16"}, {107, "R_PPC_EMB_SDA2I16"}, {108, "R_PPC_EMB_SDA2REL"}, {109, "R_PPC_EMB_SDA21"}, {110, "R_PPC_EMB_MRKREF"}, {111, "R_PPC_EMB_RELSEC16"}, {112, "R_PPC_EMB_RELST_LO"}, {113, "R_PPC_EMB_RELST_HI"}, {114, "R_PPC_EMB_RELST_HA"}, {115, "R_PPC_EMB_BIT_FLD"}, {116, "R_PPC_EMB_RELSDA"}, } func (i R_PPC) String() string { return stringName(uint32(i), rppcStrings, false) } func (i R_PPC) GoString() string { return stringName(uint32(i), rppcStrings, true) } // Relocation types for 64-bit PowerPC or Power Architecture processors. type R_PPC64 int const ( R_PPC64_NONE R_PPC64 = 0 R_PPC64_ADDR32 R_PPC64 = 1 R_PPC64_ADDR24 R_PPC64 = 2 R_PPC64_ADDR16 R_PPC64 = 3 R_PPC64_ADDR16_LO R_PPC64 = 4 R_PPC64_ADDR16_HI R_PPC64 = 5 R_PPC64_ADDR16_HA R_PPC64 = 6 R_PPC64_ADDR14 R_PPC64 = 7 R_PPC64_ADDR14_BRTAKEN R_PPC64 = 8 R_PPC64_ADDR14_BRNTAKEN R_PPC64 = 9 R_PPC64_REL24 R_PPC64 = 10 R_PPC64_REL14 R_PPC64 = 11 R_PPC64_REL14_BRTAKEN R_PPC64 = 12 R_PPC64_REL14_BRNTAKEN R_PPC64 = 13 R_PPC64_GOT16 R_PPC64 = 14 R_PPC64_GOT16_LO R_PPC64 = 15 R_PPC64_GOT16_HI R_PPC64 = 16 R_PPC64_GOT16_HA R_PPC64 = 17 R_PPC64_JMP_SLOT R_PPC64 = 21 R_PPC64_REL32 R_PPC64 = 26 R_PPC64_ADDR64 R_PPC64 = 38 R_PPC64_ADDR16_HIGHER R_PPC64 = 39 R_PPC64_ADDR16_HIGHERA R_PPC64 = 40 R_PPC64_ADDR16_HIGHEST R_PPC64 = 41 R_PPC64_ADDR16_HIGHESTA R_PPC64 = 42 R_PPC64_REL64 R_PPC64 = 44 R_PPC64_TOC16 R_PPC64 = 47 R_PPC64_TOC16_LO R_PPC64 = 48 R_PPC64_TOC16_HI R_PPC64 = 49 R_PPC64_TOC16_HA R_PPC64 = 50 R_PPC64_TOC R_PPC64 = 51 R_PPC64_ADDR16_DS R_PPC64 = 56 R_PPC64_ADDR16_LO_DS R_PPC64 = 57 R_PPC64_GOT16_DS R_PPC64 = 58 R_PPC64_GOT16_LO_DS R_PPC64 = 59 R_PPC64_TOC16_DS R_PPC64 = 63 R_PPC64_TOC16_LO_DS R_PPC64 = 64 R_PPC64_TLS R_PPC64 = 67 R_PPC64_DTPMOD64 R_PPC64 = 68 R_PPC64_TPREL16 R_PPC64 = 69 R_PPC64_TPREL16_LO R_PPC64 = 70 R_PPC64_TPREL16_HI R_PPC64 = 71 R_PPC64_TPREL16_HA R_PPC64 = 72 R_PPC64_TPREL64 R_PPC64 = 73 R_PPC64_DTPREL16 R_PPC64 = 74 R_PPC64_DTPREL16_LO R_PPC64 = 75 R_PPC64_DTPREL16_HI R_PPC64 = 76 R_PPC64_DTPREL16_HA R_PPC64 = 77 R_PPC64_DTPREL64 R_PPC64 = 78 R_PPC64_GOT_TLSGD16 R_PPC64 = 79 R_PPC64_GOT_TLSGD16_LO R_PPC64 = 80 R_PPC64_GOT_TLSGD16_HI R_PPC64 = 81 R_PPC64_GOT_TLSGD16_HA R_PPC64 = 82 R_PPC64_GOT_TLSLD16 R_PPC64 = 83 R_PPC64_GOT_TLSLD16_LO R_PPC64 = 84 R_PPC64_GOT_TLSLD16_HI R_PPC64 = 85 R_PPC64_GOT_TLSLD16_HA R_PPC64 = 86 R_PPC64_GOT_TPREL16_DS R_PPC64 = 87 R_PPC64_GOT_TPREL16_LO_DS R_PPC64 = 88 R_PPC64_GOT_TPREL16_HI R_PPC64 = 89 R_PPC64_GOT_TPREL16_HA R_PPC64 = 90 R_PPC64_GOT_DTPREL16_DS R_PPC64 = 91 R_PPC64_GOT_DTPREL16_LO_DS R_PPC64 = 92 R_PPC64_GOT_DTPREL16_HI R_PPC64 = 93 R_PPC64_GOT_DTPREL16_HA R_PPC64 = 94 R_PPC64_TPREL16_DS R_PPC64 = 95 R_PPC64_TPREL16_LO_DS R_PPC64 = 96 R_PPC64_TPREL16_HIGHER R_PPC64 = 97 R_PPC64_TPREL16_HIGHERA R_PPC64 = 98 R_PPC64_TPREL16_HIGHEST R_PPC64 = 99 R_PPC64_TPREL16_HIGHESTA R_PPC64 = 100 R_PPC64_DTPREL16_DS R_PPC64 = 101 R_PPC64_DTPREL16_LO_DS R_PPC64 = 102 R_PPC64_DTPREL16_HIGHER R_PPC64 = 103 R_PPC64_DTPREL16_HIGHERA R_PPC64 = 104 R_PPC64_DTPREL16_HIGHEST R_PPC64 = 105 R_PPC64_DTPREL16_HIGHESTA R_PPC64 = 106 R_PPC64_TLSGD R_PPC64 = 107 R_PPC64_TLSLD R_PPC64 = 108 R_PPC64_REL16 R_PPC64 = 249 R_PPC64_REL16_LO R_PPC64 = 250 R_PPC64_REL16_HI R_PPC64 = 251 R_PPC64_REL16_HA R_PPC64 = 252 ) var rppc64Strings = []intName{ {0, "R_PPC64_NONE"}, {1, "R_PPC64_ADDR32"}, {2, "R_PPC64_ADDR24"}, {3, "R_PPC64_ADDR16"}, {4, "R_PPC64_ADDR16_LO"}, {5, "R_PPC64_ADDR16_HI"}, {6, "R_PPC64_ADDR16_HA"}, {7, "R_PPC64_ADDR14"}, {8, "R_PPC64_ADDR14_BRTAKEN"}, {9, "R_PPC64_ADDR14_BRNTAKEN"}, {10, "R_PPC64_REL24"}, {11, "R_PPC64_REL14"}, {12, "R_PPC64_REL14_BRTAKEN"}, {13, "R_PPC64_REL14_BRNTAKEN"}, {14, "R_PPC64_GOT16"}, {15, "R_PPC64_GOT16_LO"}, {16, "R_PPC64_GOT16_HI"}, {17, "R_PPC64_GOT16_HA"}, {21, "R_PPC64_JMP_SLOT"}, {26, "R_PPC64_REL32"}, {38, "R_PPC64_ADDR64"}, {39, "R_PPC64_ADDR16_HIGHER"}, {40, "R_PPC64_ADDR16_HIGHERA"}, {41, "R_PPC64_ADDR16_HIGHEST"}, {42, "R_PPC64_ADDR16_HIGHESTA"}, {44, "R_PPC64_REL64"}, {47, "R_PPC64_TOC16"}, {48, "R_PPC64_TOC16_LO"}, {49, "R_PPC64_TOC16_HI"}, {50, "R_PPC64_TOC16_HA"}, {51, "R_PPC64_TOC"}, {56, "R_PPC64_ADDR16_DS"}, {57, "R_PPC64_ADDR16_LO_DS"}, {58, "R_PPC64_GOT16_DS"}, {59, "R_PPC64_GOT16_LO_DS"}, {63, "R_PPC64_TOC16_DS"}, {64, "R_PPC64_TOC16_LO_DS"}, {67, "R_PPC64_TLS"}, {68, "R_PPC64_DTPMOD64"}, {69, "R_PPC64_TPREL16"}, {70, "R_PPC64_TPREL16_LO"}, {71, "R_PPC64_TPREL16_HI"}, {72, "R_PPC64_TPREL16_HA"}, {73, "R_PPC64_TPREL64"}, {74, "R_PPC64_DTPREL16"}, {75, "R_PPC64_DTPREL16_LO"}, {76, "R_PPC64_DTPREL16_HI"}, {77, "R_PPC64_DTPREL16_HA"}, {78, "R_PPC64_DTPREL64"}, {79, "R_PPC64_GOT_TLSGD16"}, {80, "R_PPC64_GOT_TLSGD16_LO"}, {81, "R_PPC64_GOT_TLSGD16_HI"}, {82, "R_PPC64_GOT_TLSGD16_HA"}, {83, "R_PPC64_GOT_TLSLD16"}, {84, "R_PPC64_GOT_TLSLD16_LO"}, {85, "R_PPC64_GOT_TLSLD16_HI"}, {86, "R_PPC64_GOT_TLSLD16_HA"}, {87, "R_PPC64_GOT_TPREL16_DS"}, {88, "R_PPC64_GOT_TPREL16_LO_DS"}, {89, "R_PPC64_GOT_TPREL16_HI"}, {90, "R_PPC64_GOT_TPREL16_HA"}, {91, "R_PPC64_GOT_DTPREL16_DS"}, {92, "R_PPC64_GOT_DTPREL16_LO_DS"}, {93, "R_PPC64_GOT_DTPREL16_HI"}, {94, "R_PPC64_GOT_DTPREL16_HA"}, {95, "R_PPC64_TPREL16_DS"}, {96, "R_PPC64_TPREL16_LO_DS"}, {97, "R_PPC64_TPREL16_HIGHER"}, {98, "R_PPC64_TPREL16_HIGHERA"}, {99, "R_PPC64_TPREL16_HIGHEST"}, {100, "R_PPC64_TPREL16_HIGHESTA"}, {101, "R_PPC64_DTPREL16_DS"}, {102, "R_PPC64_DTPREL16_LO_DS"}, {103, "R_PPC64_DTPREL16_HIGHER"}, {104, "R_PPC64_DTPREL16_HIGHERA"}, {105, "R_PPC64_DTPREL16_HIGHEST"}, {106, "R_PPC64_DTPREL16_HIGHESTA"}, {107, "R_PPC64_TLSGD"}, {108, "R_PPC64_TLSLD"}, {249, "R_PPC64_REL16"}, {250, "R_PPC64_REL16_LO"}, {251, "R_PPC64_REL16_HI"}, {252, "R_PPC64_REL16_HA"}, } func (i R_PPC64) String() string { return stringName(uint32(i), rppc64Strings, false) } func (i R_PPC64) GoString() string { return stringName(uint32(i), rppc64Strings, true) } // Relocation types for s390 type R_390 int const ( R_390_NONE R_390 = 0 R_390_8 R_390 = 1 R_390_12 R_390 = 2 R_390_16 R_390 = 3 R_390_32 R_390 = 4 R_390_PC32 R_390 = 5 R_390_GOT12 R_390 = 6 R_390_GOT32 R_390 = 7 R_390_PLT32 R_390 = 8 R_390_COPY R_390 = 9 R_390_GLOB_DAT R_390 = 10 R_390_JMP_SLOT R_390 = 11 R_390_RELATIVE R_390 = 12 R_390_GOTOFF R_390 = 13 R_390_GOTPC R_390 = 14 R_390_GOT16 R_390 = 15 R_390_PC16 R_390 = 16 R_390_PC16DBL R_390 = 17 R_390_PLT16DBL R_390 = 18 R_390_PC32DBL R_390 = 19 R_390_PLT32DBL R_390 = 20 R_390_GOTPCDBL R_390 = 21 R_390_64 R_390 = 22 R_390_PC64 R_390 = 23 R_390_GOT64 R_390 = 24 R_390_PLT64 R_390 = 25 R_390_GOTENT R_390 = 26 ) var r390Strings = []intName{ {0, "R_390_NONE"}, {1, "R_390_8"}, {2, "R_390_12"}, {3, "R_390_16"}, {4, "R_390_32"}, {5, "R_390_PC32"}, {6, "R_390_GOT12"}, {7, "R_390_GOT32"}, {8, "R_390_PLT32"}, {9, "R_390_COPY"}, {10, "R_390_GLOB_DAT"}, {11, "R_390_JMP_SLOT"}, {12, "R_390_RELATIVE"}, {13, "R_390_GOTOFF"}, {14, "R_390_GOTPC"}, {15, "R_390_GOT16"}, {16, "R_390_PC16"}, {17, "R_390_PC16DBL"}, {18, "R_390_PLT16DBL"}, {19, "R_390_PC32DBL"}, {20, "R_390_PLT32DBL"}, {21, "R_390_GOTPCDBL"}, {22, "R_390_64"}, {23, "R_390_PC64"}, {24, "R_390_GOT64"}, {25, "R_390_PLT64"}, {26, "R_390_GOTENT"}, } func (i R_390) String() string { return stringName(uint32(i), r390Strings, false) } func (i R_390) GoString() string { return stringName(uint32(i), r390Strings, true) } // Relocation types for SPARC. type R_SPARC int const ( R_SPARC_NONE R_SPARC = 0 R_SPARC_8 R_SPARC = 1 R_SPARC_16 R_SPARC = 2 R_SPARC_32 R_SPARC = 3 R_SPARC_DISP8 R_SPARC = 4 R_SPARC_DISP16 R_SPARC = 5 R_SPARC_DISP32 R_SPARC = 6 R_SPARC_WDISP30 R_SPARC = 7 R_SPARC_WDISP22 R_SPARC = 8 R_SPARC_HI22 R_SPARC = 9 R_SPARC_22 R_SPARC = 10 R_SPARC_13 R_SPARC = 11 R_SPARC_LO10 R_SPARC = 12 R_SPARC_GOT10 R_SPARC = 13 R_SPARC_GOT13 R_SPARC = 14 R_SPARC_GOT22 R_SPARC = 15 R_SPARC_PC10 R_SPARC = 16 R_SPARC_PC22 R_SPARC = 17 R_SPARC_WPLT30 R_SPARC = 18 R_SPARC_COPY R_SPARC = 19 R_SPARC_GLOB_DAT R_SPARC = 20 R_SPARC_JMP_SLOT R_SPARC = 21 R_SPARC_RELATIVE R_SPARC = 22 R_SPARC_UA32 R_SPARC = 23 R_SPARC_PLT32 R_SPARC = 24 R_SPARC_HIPLT22 R_SPARC = 25 R_SPARC_LOPLT10 R_SPARC = 26 R_SPARC_PCPLT32 R_SPARC = 27 R_SPARC_PCPLT22 R_SPARC = 28 R_SPARC_PCPLT10 R_SPARC = 29 R_SPARC_10 R_SPARC = 30 R_SPARC_11 R_SPARC = 31 R_SPARC_64 R_SPARC = 32 R_SPARC_OLO10 R_SPARC = 33 R_SPARC_HH22 R_SPARC = 34 R_SPARC_HM10 R_SPARC = 35 R_SPARC_LM22 R_SPARC = 36 R_SPARC_PC_HH22 R_SPARC = 37 R_SPARC_PC_HM10 R_SPARC = 38 R_SPARC_PC_LM22 R_SPARC = 39 R_SPARC_WDISP16 R_SPARC = 40 R_SPARC_WDISP19 R_SPARC = 41 R_SPARC_GLOB_JMP R_SPARC = 42 R_SPARC_7 R_SPARC = 43 R_SPARC_5 R_SPARC = 44 R_SPARC_6 R_SPARC = 45 R_SPARC_DISP64 R_SPARC = 46 R_SPARC_PLT64 R_SPARC = 47 R_SPARC_HIX22 R_SPARC = 48 R_SPARC_LOX10 R_SPARC = 49 R_SPARC_H44 R_SPARC = 50 R_SPARC_M44 R_SPARC = 51 R_SPARC_L44 R_SPARC = 52 R_SPARC_REGISTER R_SPARC = 53 R_SPARC_UA64 R_SPARC = 54 R_SPARC_UA16 R_SPARC = 55 ) var rsparcStrings = []intName{ {0, "R_SPARC_NONE"}, {1, "R_SPARC_8"}, {2, "R_SPARC_16"}, {3, "R_SPARC_32"}, {4, "R_SPARC_DISP8"}, {5, "R_SPARC_DISP16"}, {6, "R_SPARC_DISP32"}, {7, "R_SPARC_WDISP30"}, {8, "R_SPARC_WDISP22"}, {9, "R_SPARC_HI22"}, {10, "R_SPARC_22"}, {11, "R_SPARC_13"}, {12, "R_SPARC_LO10"}, {13, "R_SPARC_GOT10"}, {14, "R_SPARC_GOT13"}, {15, "R_SPARC_GOT22"}, {16, "R_SPARC_PC10"}, {17, "R_SPARC_PC22"}, {18, "R_SPARC_WPLT30"}, {19, "R_SPARC_COPY"}, {20, "R_SPARC_GLOB_DAT"}, {21, "R_SPARC_JMP_SLOT"}, {22, "R_SPARC_RELATIVE"}, {23, "R_SPARC_UA32"}, {24, "R_SPARC_PLT32"}, {25, "R_SPARC_HIPLT22"}, {26, "R_SPARC_LOPLT10"}, {27, "R_SPARC_PCPLT32"}, {28, "R_SPARC_PCPLT22"}, {29, "R_SPARC_PCPLT10"}, {30, "R_SPARC_10"}, {31, "R_SPARC_11"}, {32, "R_SPARC_64"}, {33, "R_SPARC_OLO10"}, {34, "R_SPARC_HH22"}, {35, "R_SPARC_HM10"}, {36, "R_SPARC_LM22"}, {37, "R_SPARC_PC_HH22"}, {38, "R_SPARC_PC_HM10"}, {39, "R_SPARC_PC_LM22"}, {40, "R_SPARC_WDISP16"}, {41, "R_SPARC_WDISP19"}, {42, "R_SPARC_GLOB_JMP"}, {43, "R_SPARC_7"}, {44, "R_SPARC_5"}, {45, "R_SPARC_6"}, {46, "R_SPARC_DISP64"}, {47, "R_SPARC_PLT64"}, {48, "R_SPARC_HIX22"}, {49, "R_SPARC_LOX10"}, {50, "R_SPARC_H44"}, {51, "R_SPARC_M44"}, {52, "R_SPARC_L44"}, {53, "R_SPARC_REGISTER"}, {54, "R_SPARC_UA64"}, {55, "R_SPARC_UA16"}, } func (i R_SPARC) String() string { return stringName(uint32(i), rsparcStrings, false) } func (i R_SPARC) GoString() string { return stringName(uint32(i), rsparcStrings, true) } // Magic number for the elf trampoline, chosen wisely to be an immediate value. const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003 // ELF32 File header. type Header32 struct { Ident [EI_NIDENT]byte /* File identification. */ Type uint16 /* File type. */ Machine uint16 /* Machine architecture. */ Version uint32 /* ELF format version. */ Entry uint32 /* Entry point. */ Phoff uint32 /* Program header file offset. */ Shoff uint32 /* Section header file offset. */ Flags uint32 /* Architecture-specific flags. */ Ehsize uint16 /* Size of ELF header in bytes. */ Phentsize uint16 /* Size of program header entry. */ Phnum uint16 /* Number of program header entries. */ Shentsize uint16 /* Size of section header entry. */ Shnum uint16 /* Number of section header entries. */ Shstrndx uint16 /* Section name strings section. */ } // ELF32 Section header. type Section32 struct { Name uint32 /* Section name (index into the section header string table). */ Type uint32 /* Section type. */ Flags uint32 /* Section flags. */ Addr uint32 /* Address in memory image. */ Off uint32 /* Offset in file. */ Size uint32 /* Size in bytes. */ Link uint32 /* Index of a related section. */ Info uint32 /* Depends on section type. */ Addralign uint32 /* Alignment in bytes. */ Entsize uint32 /* Size of each entry in section. */ } // ELF32 Program header. type Prog32 struct { Type uint32 /* Entry type. */ Off uint32 /* File offset of contents. */ Vaddr uint32 /* Virtual address in memory image. */ Paddr uint32 /* Physical address (not used). */ Filesz uint32 /* Size of contents in file. */ Memsz uint32 /* Size of contents in memory. */ Flags uint32 /* Access permission flags. */ Align uint32 /* Alignment in memory and file. */ } // ELF32 Dynamic structure. The ".dynamic" section contains an array of them. type Dyn32 struct { Tag int32 /* Entry type. */ Val uint32 /* Integer/Address value. */ } // ELF32 Compression header. type Chdr32 struct { Type uint32 Size uint32 Addralign uint32 } /* * Relocation entries. */ // ELF32 Relocations that don't need an addend field. type Rel32 struct { Off uint32 /* Location to be relocated. */ Info uint32 /* Relocation type and symbol index. */ } // ELF32 Relocations that need an addend field. type Rela32 struct { Off uint32 /* Location to be relocated. */ Info uint32 /* Relocation type and symbol index. */ Addend int32 /* Addend. */ } func R_SYM32(info uint32) uint32 { return uint32(info >> 8) } func R_TYPE32(info uint32) uint32 { return uint32(info & 0xff) } func R_INFO32(sym, typ uint32) uint32 { return sym<<8 | typ } // ELF32 Symbol. type Sym32 struct { Name uint32 Value uint32 Size uint32 Info uint8 Other uint8 Shndx uint16 } const Sym32Size = 16 func ST_BIND(info uint8) SymBind { return SymBind(info >> 4) } func ST_TYPE(info uint8) SymType { return SymType(info & 0xF) } func ST_INFO(bind SymBind, typ SymType) uint8 { return uint8(bind)<<4 | uint8(typ)&0xf } func ST_VISIBILITY(other uint8) SymVis { return SymVis(other & 3) } /* * ELF64 */ // ELF64 file header. type Header64 struct { Ident [EI_NIDENT]byte /* File identification. */ Type uint16 /* File type. */ Machine uint16 /* Machine architecture. */ Version uint32 /* ELF format version. */ Entry uint64 /* Entry point. */ Phoff uint64 /* Program header file offset. */ Shoff uint64 /* Section header file offset. */ Flags uint32 /* Architecture-specific flags. */ Ehsize uint16 /* Size of ELF header in bytes. */ Phentsize uint16 /* Size of program header entry. */ Phnum uint16 /* Number of program header entries. */ Shentsize uint16 /* Size of section header entry. */ Shnum uint16 /* Number of section header entries. */ Shstrndx uint16 /* Section name strings section. */ } // ELF64 Section header. type Section64 struct { Name uint32 /* Section name (index into the section header string table). */ Type uint32 /* Section type. */ Flags uint64 /* Section flags. */ Addr uint64 /* Address in memory image. */ Off uint64 /* Offset in file. */ Size uint64 /* Size in bytes. */ Link uint32 /* Index of a related section. */ Info uint32 /* Depends on section type. */ Addralign uint64 /* Alignment in bytes. */ Entsize uint64 /* Size of each entry in section. */ } // ELF64 Program header. type Prog64 struct { Type uint32 /* Entry type. */ Flags uint32 /* Access permission flags. */ Off uint64 /* File offset of contents. */ Vaddr uint64 /* Virtual address in memory image. */ Paddr uint64 /* Physical address (not used). */ Filesz uint64 /* Size of contents in file. */ Memsz uint64 /* Size of contents in memory. */ Align uint64 /* Alignment in memory and file. */ } // ELF64 Dynamic structure. The ".dynamic" section contains an array of them. type Dyn64 struct { Tag int64 /* Entry type. */ Val uint64 /* Integer/address value */ } // ELF64 Compression header. type Chdr64 struct { Type uint32 _ uint32 /* Reserved. */ Size uint64 Addralign uint64 } /* * Relocation entries. */ /* ELF64 relocations that don't need an addend field. */ type Rel64 struct { Off uint64 /* Location to be relocated. */ Info uint64 /* Relocation type and symbol index. */ } /* ELF64 relocations that need an addend field. */ type Rela64 struct { Off uint64 /* Location to be relocated. */ Info uint64 /* Relocation type and symbol index. */ Addend int64 /* Addend. */ } func R_SYM64(info uint64) uint32 { return uint32(info >> 32) } func R_TYPE64(info uint64) uint32 { return uint32(info) } func R_INFO(sym, typ uint32) uint64 { return uint64(sym)<<32 | uint64(typ) } // ELF64 symbol table entries. type Sym64 struct { Name uint32 /* String table index of name. */ Info uint8 /* Type and binding information. */ Other uint8 /* Reserved (not used). */ Shndx uint16 /* Section index of symbol. */ Value uint64 /* Symbol value. */ Size uint64 /* Size of associated object. */ } const Sym64Size = 24 type intName struct { i uint32 s string } func stringName(i uint32, names []intName, goSyntax bool) string { for _, n := range names { if n.i == i { if goSyntax { return "elf." + n.s } return n.s } } // second pass - look for smaller to add with. // assume sorted already for j := len(names) - 1; j >= 0; j-- { n := names[j] if n.i < i { s := n.s if goSyntax { s = "elf." + s } return s + "+" + strconv.FormatUint(uint64(i-n.i), 10) } } return strconv.FormatUint(uint64(i), 10) } func flagName(i uint32, names []intName, goSyntax bool) string { s := "" for _, n := range names { if n.i&i == n.i { if len(s) > 0 { s += "+" } if goSyntax { s += "elf." } s += n.s i -= n.i } } if len(s) == 0 { return "0x" + strconv.FormatUint(uint64(i), 16) } if i != 0 { s += "+0x" + strconv.FormatUint(uint64(i), 16) } return s }
selmentdev/selment-toolchain
source/gcc-latest/libgo/go/debug/elf/elf.go
GO
gpl-3.0
77,224
-- UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Assassin - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 17835 AND `source_type` = 0 AND `id` = 0; UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Chronomancer - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 17892 AND `source_type` = 0 AND `id` = 1; UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Vanquisher - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 18995 AND `source_type` = 0 AND `id` = 1; UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Whelp - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 21818 AND `source_type` = 0 AND `id` = 0; UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Assassin - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 17835 AND `source_type` = 0 AND `id` = 13; UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Chronomancer - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 17892 AND `source_type` = 0 AND `id` = 32; UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Vanquisher - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 18995 AND `source_type` = 0 AND `id` = 18; UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Whelp - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 21818 AND `source_type` = 0 AND `id` = 2; DELETE FROM `smart_scripts` WHERE `entryorguid` = 17835 AND `source_type` = 0 AND `id` = 14; DELETE FROM `smart_scripts` WHERE `entryorguid` = 17892 AND `source_type` = 0 AND `id` = 33; DELETE FROM `smart_scripts` WHERE `entryorguid` = 18995 AND `source_type` = 0 AND `id` = 19; DELETE FROM `smart_scripts` WHERE `entryorguid` = 21818 AND `source_type` = 0 AND `id` = 3; INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`event_param5`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_param4`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES (17835,0,14,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Assassin - On Movement Inform - Set Home Position"), (17892,0,33,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Chronomancer - On Movement Inform - Set Home Position"), (18995,0,19,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Vanquisher - On Movement Inform - Set Home Position"), (21818,0,3,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Whelp - On Movement Inform - Set Home Position"); DELETE FROM `smart_scripts` WHERE `entryorguid`=18994 AND `source_type`=0 AND `id` IN (6,7,8); INSERT INTO `smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `event_param5`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_param4`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (18994, 0, 6, 0, 1, 0, 100, 7, 1000, 1000, 0, 0, 0, 69, 1, 0, 0, 10, 0, 0, 19, 15608, 200, 0, 0, 0, 0, 0, 0, "Infinite Executioner - Out of Combat - Move To Closest Creature 'Medivh'"), (18994, 0, 7, 0, 34, 0, 100, 7, 8, 1, 0, 0, 0, 11, 31326, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, "Infinite Executioner - On Movement Inform - Cast 'Corrupt Medivh'"), (18994, 0, 8, 0, 34, 0, 100, 7, 8, 1, 0, 0, 0, 101, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, "Infinite Executioner - On Movement Inform - Set Home Position");
CypherCore/CypherCore
sql/updates/world/master/2022_01_04_13_world_2020_05_15_01_world.sql
SQL
gpl-3.0
4,600
--TEST-- PHPT skip condition results in correct code location hint --FILE-- <?php declare(strict_types=1); print "Nothing to see here, move along"; --SKIPIF-- <?php declare(strict_types=1); print "skip: something terrible happened\n"; --EXPECT-- Nothing to see here, move along
Merrick28/delain
web/vendor/phpunit/phpunit/tests/end-to-end/_files/phpt-skipif-location-hint-example.phpt
PHP
gpl-3.0
278
if (typeof process !== "undefined") { require("amd-loader"); require("../../test/setup_paths"); } define(function(require, exports, module) { var assert = require("assert"); var report = require("./linereport_base"); module.exports = { "test parse line" : function(next) { var results = report.parseOutput("1:2: 3"); console.log(results[0]); assert.equal(results[0].pos.sl, 0); assert.equal(results[0].pos.sc, 1); assert.equal(results[0].message, "3"); next(); }, "test parse two lines" : function(next) { var results = report.parseOutput("1:1: line 1\n1:2: line 2"); assert.equal(results.length, 2); next(); }, "test ignore lines" : function(next) { var results = report.parseOutput("1:1: line 1\n1:2: line 2\bmove zig"); assert.equal(results.length, 2); next(); } }; }); if (typeof module !== "undefined" && module === require.main) { require("asyncjs").test.testcase(module.exports).exec(); }
precise-partner/cloud9
plugins-client/ext.linereport/linereport_test.js
JavaScript
gpl-3.0
1,047
package info.ephyra.answerselection.filters; import info.ephyra.io.Logger; import info.ephyra.io.MsgPrinter; import info.ephyra.nlp.NETagger; import info.ephyra.nlp.OpenNLP; import info.ephyra.nlp.SnowballStemmer; import info.ephyra.nlp.StanfordNeTagger; import info.ephyra.nlp.indices.WordFrequencies; import info.ephyra.querygeneration.Query; import info.ephyra.querygeneration.generators.BagOfWordsG; import info.ephyra.questionanalysis.AnalyzedQuestion; import info.ephyra.questionanalysis.KeywordExtractor; import info.ephyra.questionanalysis.QuestionNormalizer; import info.ephyra.search.Result; import info.ephyra.trec.TREC13To16Parser; import info.ephyra.trec.TRECTarget; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; /** * <p>A web reinforcement approach that ranks answer candidates for definitional * questions. Several variations of the target of the question are generated and * are used to retrieve relevant text snippets from the web. The frequencies of * content words in these snippets are counted and the scores of the answers are * adjusted to assign higher scores to candidates that cover frequent keywords. * This approach is based on the assumption that terms that often cooccur with * the target provide relevant information on the target that should be covered * by the answers.</p> * * <p>Several instances of this web term importance filter have been implemented * that use different sources for text snippets.</p> * * <p>This class extends the class <code>Filter</code>.</p> * * @author Guido Sautter * @version 2008-02-15 */ public abstract class WebTermImportanceFilter extends Filter { protected static final String person = "person"; protected static final String organization = "organization"; protected static final String location = "location"; protected static final String event = "event"; public static final int NO_NORMALIZATION = 0; public static final int LINEAR_LENGTH_NORMALIZATION = 1; public static final int SQUARE_ROOT_LENGTH_NORMALIZATION = 2; public static final int LOG_LENGTH_NORMALIZATION = 3; public static final int LOG_10_LENGTH_NORMALIZATION = 4; private final int normalizationMode; private final int tfNormalizationMode; private final boolean isCombined; // protected static final String WIKIPEDIA = "wikipedia"; /** */ protected WebTermImportanceFilter(int normalizationMode, int tfNormalizationMode, boolean isCombined) { this.normalizationMode = normalizationMode; this.tfNormalizationMode = tfNormalizationMode; this.isCombined = isCombined; } /** * fetch the term frequencies in the top X result snippets of a web search * for some target * * @param targets an array of strings containing the targets * @return a HashMap mapping the terms in the web serach results to their * frequency in the snippets */ public abstract HashMap<String, TermCounter> getTermCounters(String[] targets); /** * @author sautter * * Mutable integer class to avoid creating new objects all the time */ protected class TermCounter { private int value = 0; /** Constructor */ protected TermCounter() {} /** * Constructor * @param value the initial value */ protected TermCounter(int value) { this.value = value; } /** @return the value of this TermCounter */ public int getValue() { return this.value; } /** increment the value of this TermCounter by 1 */ public void increment() { this.value++; } /** increment the value of this TermCounter by <code>inc</code> * @param inc */ public void increment(int inc) { this.value += inc; } /** decrement the value of this TermCounter by 1 */ public void decrement() { this.value--; } /** decrement the value of this TermCounter by <code>dec</code> * @param dec */ public void decrement(int dec) { this.value -= dec; } /** multiply the value of this TermCounter times <code>fact</code> * @param fact */ public void multiplyValue(int fact) { this.value *= fact; } /** devide the value of this TermCounter times <code>denom</code> * @param denom */ public void divideValue(int denom) { this.value /= denom; } } /** * produce the target variations for a given target * * @param target the original traget String * @return an array of strings containing the variations of the target * String, including the original target */ public String[] getTargets(String target) { ArrayList<String> targets = new ArrayList<String>(); targets.add(target); boolean isPerson = false; boolean brackets = false; // If target starts with "the", "a", or "an", remove it. if (target.startsWith("the ")) { targets.add(target.substring(4, target.length())); } else if (target.startsWith("an ")) { targets.add(target.substring(3, target.length())); } else if (target.startsWith("a ")) { targets.add(target.substring(2, target.length())); } String targetType = this.checkType(target); if (TEST_TARGET_GENERATION) { if (targetType == null) System.out.println(" target type could not be determined"); else System.out.println(" target type is " + targetType); } if (person.equals(targetType)) { // (complete) target is of type Person, no further processing is necessary isPerson = true; // split parts in brackets from parts not in brackets: // "Norwegian Cruise Lines (NCL)" --> "Norwegian Cruise Lines" + "NCL" } else if (target.contains("(") && target.contains(")")) { int i1 = target.indexOf("("); int i2 = target.indexOf(")"); String s1 = target.substring(0, i1 - 1); String s2 = target.substring(i1 + 1, i2); // Log.println("*** '"+s1+"' '"+s2+"'", true); targets.clear(); targets.add(s1); targets.add(s2); // Log.println(" "+target+" contains brackest. No further processing // necessary.", true); brackets = true; } else if (this.cutExtension(target, targets)) { // do nothing, it's in the cutExtensions method } else if (target.endsWith("University")) { // chop off "University" String toAdd = target.substring(0, target.length() - 11); targets.add(toAdd); } else if (target.endsWith("International")) { // chop off International" String toAdd = target.substring(0, target.length() - 14); targets.add(toAdd); } else if (target.endsWith("Corporation")) { // chop off "Corporation" String toAdd = target.substring(0, target.length() - 12); targets.add(toAdd); } else { this.extractUpperCaseParts(targets); HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String item = iter.next(); String type = this.checkType(item); if (person.equals(type)) { // after removing the first NP, check again if target is // Person (example: "philanthropist Alberto Vilar") // Log.println(" "+item+" is Person. No further processing // necessary.", true); // attention, this also discarts events containing person names!!! // maybe remove this call //targets.clear(); targets.add(item); } } } if (isPerson) { targets.add("\"" + target + "\""); // // own extension: add 'wikipedia' to target // targets.add(target + " " + WIKIPEDIA); // targets.add("\"" + target + "\" " + WIKIPEDIA); } else if (!brackets) { // maybe remove condition //targets = this.processLongTargets(targets); this.extractUpperCaseParts(targets); //targets = this.checkForEvent(targets); // described effect done in extractUpperCaseParts(), uses NLP stuff we don't have //targets = this.checkForDeterminer(targets); // bad thing, uses to many miraculous external classen we don't have //targets = this.removeAttachedPP(targets); // done in extractUpperCaseParts() //targets = this.cutFirstNpInNpSequence(targets); this.cutFirstNpInNpSequence(targets); //targets = this.removeNounAfterNounGroup(targets); // done in extractUpperCaseParts() // own extension: extract acronyms 'Basque ETA' --> 'ETA' this.extractAcronyms(targets); //targets = this.postProcess(targets); this.postProcess(targets); } HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String item = iter.next(); String type = this.checkType(item); if (organization.equals(type)/* && !brackets*/) { targets.add("the " + item); if (!brackets) targets.add("the " + target); } else if (person.equals(type)) { targets.add("\"" + item + "\""); // // own extension: add 'wikipedia' to target // targets.add(item + " " + WIKIPEDIA); // targets.add("\"" + item + "\" " + WIKIPEDIA); } // own extension: add determiner to acronyms if (item.matches("([A-Z]){3,}")) targets.add("the " + item); else if (item.matches("([A-Z]\\.){2,}")) targets.add("the " + item); } // own extension: add quoted version of title case targets like 'The Daily Show' duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String item = iter.next(); if (item.matches("([A-Z][a-z]++)++")) { targets.add("\"" + item + "\""); // // own extension: add 'wikipedia' to target // targets.add(item + " " + WIKIPEDIA); // targets.add("\"" + item + "\" " + WIKIPEDIA); } } // own extension: always use quoted version of original target if it has more than one word String[] targetTokens = NETagger.tokenize(target); if (targetTokens.length > 1) { targets.add("\"" + target + "\""); // // own extension: add 'wikipedia' to target // targets.add(target + " " + WIKIPEDIA); // targets.add("\"" + target + "\" " + WIKIPEDIA); } duplicateFreeTargets = new LinkedHashSet<String>(targets); return duplicateFreeTargets.toArray(new String[duplicateFreeTargets.size()]); } /** * find the NE type of a target * * @param target the target String to check * @return the NE type of target, or null, if the type couldn't be determined */ private String checkType(String target) { if (!StanfordNeTagger.isInitialized()) StanfordNeTagger.init(); HashMap<String, String[]> nesByType = StanfordNeTagger.extractNEs(target); ArrayList<String> neTypes = new ArrayList<String>(nesByType.keySet()); for (int t = 0; t < neTypes.size(); t++) { String type = neTypes.get(t); String[] nes = nesByType.get(type); for (int n = 0; n < nes.length; n++) if (nes[n].equals(target)) return type.replace("NE", ""); } return null; } /** * cut tailing words like "University", "International", "Corporation": * "Microsoft Corporation" --> "Microsoft" and add the non-cut part to target list * * @param target the target String to cut * @param targets the target list to add the cut part to * @return true if a cut target was added, false otherwise */ private boolean cutExtension(String target, ArrayList<String> targets) { if (this.extensionList.isEmpty()) for (int i = 0; i < extensions.length; i++) this.extensionList.add(extensions[i]); String[] targetTokens = target.split("\\s"); String last = targetTokens[targetTokens.length - 1]; if (this.extensionList.contains(last) && (targetTokens.length > 1)) { String cutTarget = targetTokens[0]; for (int i = 1; i < (targetTokens.length - 1); i++) cutTarget += " " + targetTokens[i]; targets.add(cutTarget); return true; } return false; } private HashSet<String> extensionList = new HashSet<String>(); private static final String[] extensions = { "University", "Corporation", "International", // last year's winner's list ends here "Incorporated", "Inc.", "Comp.", "Corp.", "Co.", "Museum", "<to be extended>" }; /** extract non lower case parts from the targets: * "the film 'Star Wars'" --> "'Star Wars'" * "1998 indictment and trial of Susan McDougal" --> "Susan McDougal" * "Miss Universe 2000 crowned" --> "Miss Universe 2000" * "Abraham from the bible" --> "Abraham" * "Gobi desert" --> "Gobi" * * @param targets the list of targets */ private void extractUpperCaseParts(ArrayList<String> targets) { HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String target = iter.next(); String[] targetTokens = target.split("\\s"); String upperCasePart = null; int i = 0; while (i < targetTokens.length) { // find start of next upper case part while ((i < targetTokens.length) && !Character.isUpperCase(targetTokens[i].charAt(0))) i++; // start upper case part if (i < targetTokens.length) { upperCasePart = targetTokens[i]; i++; } // collect non-lower-case part while ((i < targetTokens.length) && !Character.isLowerCase(targetTokens[i].charAt(0))) { upperCasePart += " " + targetTokens[i]; i++; } if (upperCasePart != null) { targets.add(upperCasePart); upperCasePart = null; } } } } /** extract acronyms from the targets: * "Basque ETA" --> "ETA" * * @param targets the list of targets */ private void extractAcronyms(ArrayList<String> targets) { HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String target = iter.next(); String[] targetTokens = target.split("\\s"); for (String t : targetTokens) { if (t.matches("([A-Z]){3,}")) { targets.add(t); } else if (t.matches("([A-Z]\\.){2,}")) { targets.add(t); } } } } /** remove first NP in a sequence of NPs: * "the film 'Star Wars'" --> "'Star Wars'" * * @param targets the list of targets */ private void cutFirstNpInNpSequence(ArrayList<String> targets) { HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String target = iter.next(); // tokenize and tag sentence String[] targetTokens = OpenNLP.tokenize(target); String[] posTags = OpenNLP.tagPos(targetTokens); String[] chunkTags = OpenNLP.tagChunks(targetTokens, posTags); String np = null; int i = 0; // find first NP while ((i < targetTokens.length) && !"B-NP".equals(chunkTags[i])) i++; // skip first NP i++; // find next NP while (( i < targetTokens.length) && !"B-NP".equals(chunkTags[i])) i++; // start NP if (i < targetTokens.length) { np = targetTokens[i]; i++; } // add rest of NP while (i < targetTokens.length) { np += " " + targetTokens[i]; i++; } if (np != null) targets.add(np); } } /** take care of remaining brackets * * @param targets the list of targets */ private void postProcess(ArrayList<String> targets) { HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); targets.clear(); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String target = iter.next().trim(); boolean add = true; if (target.startsWith("(") && target.endsWith(")")) target = target.substring(1, target.length() - 1).trim(); if (target.startsWith("(") != target.endsWith(")")) add = false; // own extension: cut leading and tailing apostrophes while (target.startsWith("'")) target = target.substring(1).trim(); while (target.endsWith("'")) target = target.substring(0, (target.length() - 1)).trim(); // own extension: cut leading singel letters, but keep determiner "a" while (target.matches("[b-z]\\s.++")) target = target.substring(2); // own extension: filter one-char targets if (target.length() < 2) add = false; if (add) targets.add(target); } } /** * Increment the score of each result snippet for each word in it according * to the number of top-100 web search engine snippets containing this * particular word. This favors snippets that provide information given * frequently and thus likely to be more important with regard to the * target. * * @param results array of <code>Result</code> objects * @return extended array of <code>Result</code> objects */ @SuppressWarnings("unchecked") public Result[] apply(Result[] results) { // catch empty result if (results.length == 0) return results; // produce target variations String target = results[0].getQuery().getOriginalQueryString(); System.out.println("WebTermImportanceFilter:\n processing target '" + target + "'"); HashMap<String, TermCounter> rawTermCounters = this.cacheLookup(target); // query generation test if (TEST_TARGET_GENERATION) { String[] targets = this.getTargets(target); System.out.println(" generated web serach Strings:"); for (String t : targets) System.out.println(" - " + t); // query generation test only return results; // cache miss } else if (rawTermCounters == null) { String[] targets = this.getTargets(target); System.out.println(" web serach Strings are"); for (String t : targets) System.out.println(" - " + t); rawTermCounters = this.getTermCounters(targets); this.cache(target, rawTermCounters); } // get target tokens HashSet<String> rawTargetTerms = new HashSet<String>(); String[] targetTokens = OpenNLP.tokenize(target); for (String tt : targetTokens) if (Character.isLetterOrDigit(tt.charAt(0))) rawTargetTerms.add(tt); // stem terms, collect target terms HashMap<String, TermCounter> termCounters = new HashMap<String, TermCounter>();//this.getTermCounters(targets); HashSet<String> targetTerms = new HashSet<String>(); ArrayList<String> rawTerms = new ArrayList<String>(rawTermCounters.keySet()); for (String rawTerm : rawTerms) { String stemmedTerm = SnowballStemmer.stem(rawTerm.toLowerCase()); if (!termCounters.containsKey(stemmedTerm)) termCounters.put(stemmedTerm, new TermCounter()); termCounters.get(stemmedTerm).increment(rawTermCounters.get(rawTerm).getValue()); if (rawTargetTerms.contains(rawTerm)) targetTerms.add(stemmedTerm); } // get overall recall (since 20070718) int termCount = this.getCountSum(termCounters); int termCountLog = ((termCount > 100) ? ((int) Math.log10(termCount)) : 2); System.out.println("WebTermImportanceFilter: termCountLog is " + termCountLog); // score results ArrayList<Result> resultList = new ArrayList<Result>(); boolean goOn; do { goOn = false; ArrayList<Result> rawResults = new ArrayList<Result>(); // score all results for (Result r : results) { if (r.getScore() != Float.NEGATIVE_INFINITY) { // tokenize sentence String[] sentence = NETagger.tokenize(r.getAnswer()); float importance = 0; // scan sentence for terms from web result for (int i = 0; i < sentence.length; i++) { String term = sentence[i]; if ((term.length() > 1)/* && !StringUtils.isSubsetKeywords(term, r.getQuery().getAnalyzedQuestion().getQuestion()) && !FunctionWords.lookup(term)*/) { term = SnowballStemmer.stem(term.toLowerCase()); TermCounter count = termCounters.get(term); if (count != null) { double tf; // 20070706 if (this.tfNormalizationMode == NO_NORMALIZATION) tf = 1; else if (this.tfNormalizationMode == LOG_LENGTH_NORMALIZATION) { tf = WordFrequencies.lookup(sentence[i].toLowerCase()); if (tf > Math.E) tf = Math.log(tf); else tf = 1; } else if (this.tfNormalizationMode == LOG_LENGTH_NORMALIZATION) { tf = WordFrequencies.lookup(sentence[i].toLowerCase()); if (tf > 10) tf = Math.log10(tf); else tf = 1; } else tf = 1; importance += (count.getValue() / tf); } } } // don't throw out 0-scored results for combining approaches if (this.isCombined || (importance > 0)) { if (this.normalizationMode == NO_NORMALIZATION) r.setScore(importance); else if (this.normalizationMode == LINEAR_LENGTH_NORMALIZATION) r.setScore(importance / sentence.length); // try normalized score else if (this.normalizationMode == SQUARE_ROOT_LENGTH_NORMALIZATION) r.setScore(importance / ((float) Math.sqrt(sentence.length))); // try normalized score else if (this.normalizationMode == LOG_LENGTH_NORMALIZATION) r.setScore(importance / (1 + ((float) Math.log(sentence.length)))); // try normalized score else if (this.normalizationMode == LOG_10_LENGTH_NORMALIZATION) r.setScore(importance / (1 + ((float) Math.log10(sentence.length)))); // try normalized score rawResults.add(r); } } } if (rawResults.size() != 0) { // find top result Collections.sort(rawResults); Collections.reverse(rawResults); Result top = rawResults.remove(0); resultList.add(top); // decrement scores of top result terms String[] sentence = NETagger.tokenize(top.getAnswer()); for (int i = 0; i < sentence.length; i++) { String term = SnowballStemmer.stem(sentence[i].toLowerCase()); TermCounter count = termCounters.get(term); if (count != null) { // if (targetTerms.contains(term)) count.divideValue(2); // else count.divideValue(5); // if (targetTerms.contains(term)) count.divideValue(2); // else count.divideValue(3); // if (targetTerms.contains(term)) count.divideValue(2); // else count.divideValue(2); // 20070718 if (targetTerms.contains(term)) count.divideValue(2); else count.divideValue(termCountLog); if (count.getValue() == 0) termCounters.remove(term); } } // prepare remaining results for next round results = rawResults.toArray(new Result[rawResults.size()]); goOn = true; } } while (goOn); Collections.sort(resultList); Collections.reverse(resultList); // set position-dependent extra score for combining approaches if (this.isCombined) { float eScore = 100; for (Result r : resultList) { r.addExtraScore((this.getClass().getName() + this.normalizationMode), eScore); eScore *= 0.9f; } } return resultList.toArray(new Result[resultList.size()]); } // private static String lastTarget = null; // private static String lastCacherClassName = null; // private static HashMap<String, TermCounter> lastTargetTermCounters = null; private static class CacheEntry { String target; HashMap<String, TermCounter> termCounters; public CacheEntry(String target, HashMap<String, TermCounter> termCounters) { this.target = target; this.termCounters = termCounters; } } private static HashMap<String, CacheEntry> cache = new HashMap<String, CacheEntry>(); private void cache(String target, HashMap<String, TermCounter> termCounters) { String className = this.getClass().getName(); System.out.println("WebTermImportanceFilter: caching web lookup result for target '" + target + "' from class '" + className + "'"); CacheEntry ce = new CacheEntry(target, termCounters); cache.put(className, ce); // lastTarget = target; // lastCacherClassName = className; // lastTargetTermCounters = termCounters; } private HashMap<String, TermCounter> cacheLookup(String target) { String className = this.getClass().getName(); System.out.println("WebTermImportanceFilter: doing cache lookup result for target '" + target + "', class '" + className + "'"); CacheEntry ce = cache.get(className); if (ce == null) { System.out.println(" --> cache miss, no entry for '" + className + "' so far"); return null; } else if (target.equals(ce.target)) { System.out.println(" --> cache hit"); return ce.termCounters; } else { System.out.println(" --> cache miss, last target for '" + className + "' is '" + ce.target + "'"); return null; } } /** add all the term counters in source to target (perform a union of the key sets, summing up the counters) * @param source * @param target */ protected void addTermCounters(HashMap<String, TermCounter> source, HashMap<String, TermCounter> target) { for (Iterator<String> keys = source.keySet().iterator(); keys.hasNext();) { String key = keys.next(); int count = source.get(key).getValue(); if (!target.containsKey(key)) target.put(key, new TermCounter()); target.get(key).increment(count); } } /** get the maximum count out of a set of counters * @param counters */ protected int getMaxCount(HashMap<String, TermCounter> counters) { int max = 0; for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();) max = Math.max(max, counters.get(keys.next()).getValue()); return max; } /** get the sum of a set of counters * @param counters */ protected int getCountSum(HashMap<String, TermCounter> counters) { int sum = 0; for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();) sum += counters.get(keys.next()).getValue(); return sum; } /** get the sum of a set of counters, each one minus the count in another set of counters * @param counters * @param compare */ protected int sumDiff(HashMap<String, TermCounter> counters, HashMap<String, TermCounter> compare) { int diffSum = 0; for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();) { String key = keys.next(); int count = counters.get(key).getValue(); int comp = (compare.containsKey(key) ? compare.get(key).getValue() : 0); diffSum += Math.max((count - comp), 0); } return diffSum; } protected static boolean TEST_TARGET_GENERATION = false; public static void main(String[] args) { TEST_TARGET_GENERATION = true; MsgPrinter.enableStatusMsgs(true); MsgPrinter.enableErrorMsgs(true); // create tokenizer MsgPrinter.printStatusMsg("Creating tokenizer..."); if (!OpenNLP.createTokenizer("res/nlp/tokenizer/opennlp/EnglishTok.bin.gz")) MsgPrinter.printErrorMsg("Could not create tokenizer."); // LingPipe.createTokenizer(); // create sentence detector // MsgPrinter.printStatusMsg("Creating sentence detector..."); // if (!OpenNLP.createSentenceDetector("res/nlp/sentencedetector/opennlp/EnglishSD.bin.gz")) // MsgPrinter.printErrorMsg("Could not create sentence detector."); // LingPipe.createSentenceDetector(); // create stemmer MsgPrinter.printStatusMsg("Creating stemmer..."); SnowballStemmer.create(); // create part of speech tagger MsgPrinter.printStatusMsg("Creating POS tagger..."); if (!OpenNLP.createPosTagger("res/nlp/postagger/opennlp/tag.bin.gz", "res/nlp/postagger/opennlp/tagdict")) MsgPrinter.printErrorMsg("Could not create OpenNLP POS tagger."); // if (!StanfordPosTagger.init("res/nlp/postagger/stanford/" + // "train-wsj-0-18.holder")) // MsgPrinter.printErrorMsg("Could not create Stanford POS tagger."); // create chunker MsgPrinter.printStatusMsg("Creating chunker..."); if (!OpenNLP.createChunker("res/nlp/phrasechunker/opennlp/" + "EnglishChunk.bin.gz")) MsgPrinter.printErrorMsg("Could not create chunker."); // create named entity taggers MsgPrinter.printStatusMsg("Creating NE taggers..."); NETagger.loadListTaggers("res/nlp/netagger/lists/"); NETagger.loadRegExTaggers("res/nlp/netagger/patterns.lst"); MsgPrinter.printStatusMsg(" ...loading models"); // if (!NETagger.loadNameFinders("res/nlp/netagger/opennlp/")) // MsgPrinter.printErrorMsg("Could not create OpenNLP NE tagger."); if (!StanfordNeTagger.isInitialized() && !StanfordNeTagger.init()) MsgPrinter.printErrorMsg("Could not create Stanford NE tagger."); MsgPrinter.printStatusMsg(" ...done"); WebTermImportanceFilter wtif = new TargetGeneratorTest(NO_NORMALIZATION); TRECTarget[] targets = TREC13To16Parser.loadTargets(args[0]); for (TRECTarget target : targets) { String question = target.getTargetDesc(); // query generation MsgPrinter.printGeneratingQueries(); String qn = QuestionNormalizer.normalize(question); MsgPrinter.printNormalization(qn); // print normalized question string Logger.logNormalization(qn); // log normalized question string String[] kws = KeywordExtractor.getKeywords(qn); AnalyzedQuestion aq = new AnalyzedQuestion(question); aq.setKeywords(kws); aq.setFactoid(false); Query[] queries = new BagOfWordsG().generateQueries(aq); for (int q = 0; q < queries.length; q++) queries[q].setOriginalQueryString(question); Result[] results = new Result[1]; results[0] = new Result("This would be the answer", queries[0]); wtif.apply(results); } } private static class TargetGeneratorTest extends WebTermImportanceFilter { TargetGeneratorTest(int normalizationMode) { super(normalizationMode, normalizationMode, false); } public HashMap<String, TermCounter> getTermCounters(String[] targets) { return new HashMap<String, TermCounter>(); } } }
vishnujayvel/QAGenerator
src/info/ephyra/answerselection/filters/WebTermImportanceFilter.java
Java
gpl-3.0
30,379
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8"/> <title>CSS3 Text, linebreaks: 3043 HIRAGANA LETTER SMALL I</title> <link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'> <meta name='flags' content=''> <style type='text/css'> @font-face { font-family: 'mplus-1p-regular'; src: url('support/mplus-1p-regular.woff') format('woff'); /* filesize: 803K */ } .test, .ref { font-size: 30px; font-family: mplus-1p-regular, sans-serif; width: 95px; padding: 0; border: 1px solid orange; line-height: 1em; } </style> </head> <body> <p class="instructions">Test passes if the two orange boxes are identical.</p> <div class='ref'>かか<br />か&#x3043;な</div> <div class='ref'>かか<br />か&#x3043;な</div> </body> </html>
vwvww/servo
tests/wpt/web-platform-tests/css/css-text/i18n/reference/css3-text-line-break-opclns-251-ref.html
HTML
mpl-2.0
765
require File.expand_path(File.dirname(__FILE__) + '/../helpers/manage_groups_common') require 'thread' describe "account admin manage groups" do include_context "in-process server selenium tests" def add_account_category (account, name) f(".add_category_link").click form = f("#add_category_form") replace_content form.find_element(:css, "input[type=text]"), name submit_form(form) wait_for_ajaximations category = account.group_categories.where(name: name).first expect(category).not_to be_nil category end before (:each) do skip #course_with_admin_logged_in #@admin_account = Account.default #@admin_account.settings[:enable_manage_groups2] = false #@admin_account.save! end it "should show one div.group_category per category" do group_categories = create_categories @course.account create_new_set_groups(@course.account, group_categories[0], group_categories[1], group_categories[1], group_categories[2]) get "/accounts/#{@course.account.id}/groups" group_divs = find_all_with_jquery("div.group_category") expect(group_divs.size).to eq 4 # three groups + blank ids = group_divs.map { |div| div.attribute(:id) } group_categories.each { |category| expect(ids).to include("category_#{category.id}") } expect(ids).to include("category_template") end it "should show one li.category per category" do group_categories = create_categories @admin_account create_new_set_groups(@admin_account, group_categories[0], group_categories[1], group_categories[1], group_categories[2]) get "/accounts/#{@admin_account.id}/groups" group_divs = driver.find_elements(:css, "li.category") expect(group_divs.size).to eq 3 labels = group_divs.map { |div| div.find_element(:css, "a").text } group_categories.each { |category| expect(labels).to be_include(category.name) } end context "single category" do before (:each) do @courses_group_category = @admin_account.group_categories.create(:name => "Existing Category") groups_student_enrollment 1 end it "should add new categories at the end of the tabs" do create_new_set_groups @admin_account, @courses_group_category get "/accounts/#{@admin_account.id}/groups" expect(driver.find_elements(:css, "#category_list li").size).to eq 1 # submit new category form add_account_category @admin_account, 'New Category' expect(driver.find_elements(:css, "#category_list li").size).to eq 2 expect(driver.find_elements(:css, "#category_list li a").last.text).to eq "New Category" end it "should remove tab and sidebar entries for deleted category" do get "/accounts/#{@admin_account.id}/groups" expect(f("#category_#{@courses_group_category.id}")).to be_displayed expect(f("#sidebar_category_#{@courses_group_category.id}")).to be_displayed f("#category_#{@courses_group_category.id} .delete_category_link").click confirm_dialog = driver.switch_to.alert confirm_dialog.accept wait_for_ajaximations expect(find_with_jquery("#category_#{@courses_group_category.id}")).to be_nil expect(find_with_jquery("#sidebar_category_#{@courses_group_category.id}")).to be_nil end it "should populate sidebar with new category when adding a category" do group = @admin_account.groups.create(:name => "Group 1", :group_category => @courses_group_category) get "/accounts/#{Account.default.id}/groups" expect(f("#sidebar_category_#{@courses_group_category.id}")).to be_displayed expect(f("#sidebar_category_#{@courses_group_category.id} #sidebar_group_#{group.id}")).to be_displayed new_category = add_account_category(@admin_account, 'New Category') # We need to refresh the page because it doesn't update the sidebar, # This is should probably be reported as a bug refresh_page expect(f("#sidebar_category_#{new_category.id}")).to be_displayed end it "should populate sidebar with new category when adding a category and group" do group = @admin_account.groups.create(:name => "Group 1", :group_category => @courses_group_category) get "/accounts/#{Account.default.id}/groups" expect(f("#sidebar_category_#{@courses_group_category.id}")).to be_displayed expect(f("#sidebar_category_#{@courses_group_category.id} #sidebar_group_#{group.id}")).to be_displayed new_category = add_account_category(@admin_account, 'New Category') group2 = add_group_to_category new_category, "New Group Category 2" expect(f("#sidebar_category_#{new_category.id}")).to be_displayed expect(driver.find_element(:css, "#sidebar_category_#{new_category.id} #sidebar_group_#{group2.id}")).to be_displayed end it "should preserve group to category association when editing a group" do group = @admin_account.groups.create(:name => "Group 1", :group_category => @courses_group_category) get "/accounts/#{Account.default.id}/groups" wait_for_ajaximations expect(find_with_jquery("#category_#{@courses_group_category.id} #group_#{group.id}")).to be_displayed # submit new category form hover_and_click(".edit_group_link") form = f("#edit_group_form") replace_content form.find_element(:css, "input[type=text]"), "New Name" submit_form(form) expect(f("#category_#{@courses_group_category.id} #group_#{group.id}")).to be_displayed end it "should populate a group tag and check if it's there" do get "/accounts/#{@admin_account.id}/groups" category = add_account_category @admin_account, 'New Category' category_tabs = driver.find_elements(:css, '#category_list li') category_tabs[1].click category_name = f("#category_#{category.id} .category_name").text expect(category_name).to include_text(category.name) end it "should add another group and see that the group is there" do get "/accounts/#{@admin_account.id}/groups" group = add_group_to_category @courses_group_category, 'group 1' expect(f("#group_#{group.id} .group_name").text).to eq group.name end it "should add multiple groups and validate they exist" do groups = add_groups_in_category @courses_group_category get "/accounts/#{Account.default.id}/groups" category_groups = driver.find_elements(:css, ".left_side .group .name") category_groups.each_with_index { |cg, i| expect(cg.text).to include_text(groups[i].name)} end it "should add multiple groups and be sure they are all deleted" do add_groups_in_category @courses_group_category get "/accounts/#{@admin_account.id}/groups" make_full_screen delete = f(".delete_category_link") delete.click confirm_dialog = driver.switch_to.alert confirm_dialog.accept wait_for_ajaximations expect(driver.find_elements(:css, ".left_side .group")).to be_empty expect(@admin_account.group_categories.count).to eq 0 end it "should edit an individual group" do get "/accounts/#{@admin_account.id}/groups" group = add_group_to_category @courses_group_category, "group 1" expect(group).not_to be_nil f("#group_#{group.id}").click wait_for_ajaximations f("#group_#{group.id} .edit_group_link").click wait_for_ajaximations name = "new group 1" f("#group_name").send_keys(name) f("#group_#{group.id} .btn").click wait_for_ajaximations group = @admin_account.groups.where(name: name).first expect(group).not_to be_nil end it "should delete an individual group" do get "/accounts/#{@admin_account.id}/groups" group = add_group_to_category @courses_group_category, "group 1" f("#group_#{group.id}").click driver.find_element(:css, "#group_#{group.id} .delete_group_link").click confirm_dialog = driver.switch_to.alert confirm_dialog.accept wait_for_ajaximations expect(driver.find_elements(:css, ".left_side .group")).to be_empty @admin_account.group_categories.last.groups.last.workflow_state =='deleted' end it "should drag a user to a group" do student = @course.students.last get "/accounts/#{@admin_account.id}/groups" group = add_group_to_category @courses_group_category, "group 1" simulate_group_drag(student.id, "blank", group.id) group_div = f("#group_#{group.id}") expect(group_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed end it "should drag a user to 2 different groups" do student = @course.students.last groups = add_groups_in_category @courses_group_category, 2 get "/accounts/#{@admin_account.id}/groups" wait_for_ajax_requests simulate_group_drag(student.id, "blank", groups[0].id) group1_div = f("#group_#{groups[0].id}") expect(group1_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed simulate_group_drag(student.id, groups[0].id, groups[1].id) group2_div = f("#group_#{groups[1].id}") expect(group2_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed end it "should drag a user to 2 different groups and back to the unassigned group" do student = @course.students.last groups = add_groups_in_category @courses_group_category, 2 get "/accounts/#{@admin_account.id}/groups" wait_for_ajax_requests simulate_group_drag(student.id, "blank", groups[0].id) group1_div = f("#group_#{groups[0].id}") expect(group1_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed simulate_group_drag(student.id, groups[0].id, groups[1].id) group2_div = f("#group_#{groups[1].id}") expect(group2_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed unassigned_div = f("#category_#{@courses_group_category.id} .group_blank") simulate_group_drag(student.id, groups[1].id, "blank") expect(unassigned_div.find_elements(:css, ".user_id_#{student.id}")).not_to be_empty get "/accounts/#{@admin_account.id}/groups" unassigned_div =f("#category_#{@courses_group_category.id} .group_blank") expect(unassigned_div.find_elements(:css, ".user_id_#{student.id}")).not_to be_empty end it "should create a category and should be able to edit it" do get "/accounts/#{@admin_account.id}/groups" expect(@admin_account.group_categories.last.name).to eq "Existing Category" make_full_screen f("#category_#{@courses_group_category.id} .edit_category_link .icon-edit").click wait_for_ajaximations form = f("#edit_category_form") input_box = form.find_element(:css, "input[type=text]") category_name = "New Category" replace_content input_box, category_name submit_form(form) wait_for_ajaximations expect(@admin_account.group_categories.last.name).to eq category_name end it "should not be able to check the Allow self sign-up box" do get "/accounts/#{@admin_account.id}/groups" expect(@admin_account.group_categories.last.name).to eq "Existing Category" make_full_screen f("#category_#{@courses_group_category.id} .edit_category_link .icon-edit").click wait_for_ajaximations form = driver.find_element(:id, "edit_category_form") expect(ff("#category_enable_self_signup", form)).to be_empty submit_form(form) wait_for_ajaximations expect(f("#category_#{@courses_group_category.id} .self_signup_text")).not_to include_text "Self sign-up is enabled" end end end
greyhwndz/canvas-lms
spec/selenium/admin/account_admin_manage_groups_spec.rb
Ruby
agpl-3.0
11,626
/* * SessionPlots.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_PLOTS_HPP #define SESSION_PLOTS_HPP namespace rstudio { namespace core { class Error; } } namespace rstudio { namespace session { namespace modules { namespace plots { bool haveCairoPdf(); core::Error initialize(); } // namespace plots } // namespace modules } // namespace session } // namespace rstudio #endif // SESSION_PLOTS_HPP
more1/rstudio
src/cpp/session/modules/SessionPlots.hpp
C++
agpl-3.0
953
package eventstreamapi import ( "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/eventstream" ) // Marshaler provides a marshaling interface for event types to event stream // messages. type Marshaler interface { MarshalEvent(protocol.PayloadMarshaler) (eventstream.Message, error) } // Encoder is an stream encoder that will encode an event stream message for // the transport. type Encoder interface { Encode(eventstream.Message) error } // EventWriter provides a wrapper around the underlying event stream encoder // for an io.WriteCloser. type EventWriter struct { encoder Encoder payloadMarshaler protocol.PayloadMarshaler eventTypeFor func(Marshaler) (string, error) } // NewEventWriter returns a new event stream writer, that will write to the // writer provided. Use the WriteEvent method to write an event to the stream. func NewEventWriter(encoder Encoder, pm protocol.PayloadMarshaler, eventTypeFor func(Marshaler) (string, error), ) *EventWriter { return &EventWriter{ encoder: encoder, payloadMarshaler: pm, eventTypeFor: eventTypeFor, } } // WriteEvent writes an event to the stream. Returns an error if the event // fails to marshal into a message, or writing to the underlying writer fails. func (w *EventWriter) WriteEvent(event Marshaler) error { msg, err := w.marshal(event) if err != nil { return err } return w.encoder.Encode(msg) } func (w *EventWriter) marshal(event Marshaler) (eventstream.Message, error) { eventType, err := w.eventTypeFor(event) if err != nil { return eventstream.Message{}, err } msg, err := event.MarshalEvent(w.payloadMarshaler) if err != nil { return eventstream.Message{}, err } msg.Headers.Set(EventTypeHeader, eventstream.StringValue(eventType)) return msg, nil }
kubernetes/kops
vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/writer.go
GO
apache-2.0
1,823
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Sql.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Represents recommended elastic pool metric. /// </summary> public partial class RecommendedElasticPoolMetric { /// <summary> /// Initializes a new instance of the RecommendedElasticPoolMetric /// class. /// </summary> public RecommendedElasticPoolMetric() { CustomInit(); } /// <summary> /// Initializes a new instance of the RecommendedElasticPoolMetric /// class. /// </summary> /// <param name="dateTime">The time of metric (ISO8601 format).</param> /// <param name="dtu">Gets or sets the DTUs (Database Transaction /// Units). See /// https://azure.microsoft.com/documentation/articles/sql-database-what-is-a-dtu/</param> /// <param name="sizeGB">Gets or sets size in gigabytes.</param> public RecommendedElasticPoolMetric(System.DateTime? dateTime = default(System.DateTime?), double? dtu = default(double?), double? sizeGB = default(double?)) { DateTime = dateTime; Dtu = dtu; SizeGB = sizeGB; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the time of metric (ISO8601 format). /// </summary> [JsonProperty(PropertyName = "dateTime")] public System.DateTime? DateTime { get; set; } /// <summary> /// Gets or sets the DTUs (Database Transaction Units). See /// https://azure.microsoft.com/documentation/articles/sql-database-what-is-a-dtu/ /// </summary> [JsonProperty(PropertyName = "dtu")] public double? Dtu { get; set; } /// <summary> /// Gets or sets size in gigabytes. /// </summary> [JsonProperty(PropertyName = "sizeGB")] public double? SizeGB { get; set; } } }
SiddharthChatrolaMs/azure-sdk-for-net
src/SDKs/SqlManagement/Management.Sql/Generated/Models/RecommendedElasticPoolMetric.cs
C#
apache-2.0
2,488
<html><body><span wicket:id="label"><img alt="logo" src="../logo.png"><br>Some text<br>Some more text</span></body></html>
dashorst/wicket
wicket-core/src/test/java/org/apache/wicket/markup/parser/filter/DynamicMarkupPageWithNonClosedTags_expected.html
HTML
apache-2.0
122
//// [wrappedAndRecursiveConstraints.ts] // no errors expected class C<T extends Date> { constructor(public data: T) { } foo<U extends T>(x: U) { return x; } } interface Foo extends Date { foo: string; } var y: Foo = null; var c = new C(y); var r = c.foo(y); //// [wrappedAndRecursiveConstraints.js] // no errors expected var C = /** @class */ (function () { function C(data) { this.data = data; } C.prototype.foo = function (x) { return x; }; return C; }()); var y = null; var c = new C(y); var r = c.foo(y);
weswigham/TypeScript
tests/baselines/reference/wrappedAndRecursiveConstraints.js
JavaScript
apache-2.0
591
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * 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 */ package proguard.classfile.attribute.annotation.target.visitor; import proguard.classfile.*; import proguard.classfile.attribute.CodeAttribute; import proguard.classfile.attribute.annotation.*; import proguard.classfile.attribute.annotation.target.*; /** * This interface specifies the methods for a visitor of <code>TargetInfo</code> * objects. * * @author Eric Lafortune */ public interface TargetInfoVisitor { public void visitTypeParameterTargetInfo( Clazz clazz, TypeAnnotation typeAnnotation, TypeParameterTargetInfo typeParameterTargetInfo); public void visitTypeParameterTargetInfo( Clazz clazz, Method method, TypeAnnotation typeAnnotation, TypeParameterTargetInfo typeParameterTargetInfo); public void visitSuperTypeTargetInfo( Clazz clazz, TypeAnnotation typeAnnotation, SuperTypeTargetInfo superTypeTargetInfo); public void visitTypeParameterBoundTargetInfo(Clazz clazz, TypeAnnotation typeAnnotation, TypeParameterBoundTargetInfo typeParameterBoundTargetInfo); public void visitTypeParameterBoundTargetInfo(Clazz clazz, Field field, TypeAnnotation typeAnnotation, TypeParameterBoundTargetInfo typeParameterBoundTargetInfo); public void visitTypeParameterBoundTargetInfo(Clazz clazz, Method method, TypeAnnotation typeAnnotation, TypeParameterBoundTargetInfo typeParameterBoundTargetInfo); public void visitEmptyTargetInfo( Clazz clazz, Field field, TypeAnnotation typeAnnotation, EmptyTargetInfo emptyTargetInfo); public void visitEmptyTargetInfo( Clazz clazz, Method method, TypeAnnotation typeAnnotation, EmptyTargetInfo emptyTargetInfo); public void visitFormalParameterTargetInfo( Clazz clazz, Method method, TypeAnnotation typeAnnotation, FormalParameterTargetInfo formalParameterTargetInfo); public void visitThrowsTargetInfo( Clazz clazz, Method method, TypeAnnotation typeAnnotation, ThrowsTargetInfo throwsTargetInfo); public void visitLocalVariableTargetInfo( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, LocalVariableTargetInfo localVariableTargetInfo); public void visitCatchTargetInfo( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, CatchTargetInfo catchTargetInfo); public void visitOffsetTargetInfo( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, OffsetTargetInfo offsetTargetInfo); public void visitTypeArgumentTargetInfo( Clazz clazz, Method method, CodeAttribute codeAttribute, TypeAnnotation typeAnnotation, TypeArgumentTargetInfo typeArgumentTargetInfo); }
dslomov/bazel
third_party/java/proguard/proguard5.3.3/src/proguard/classfile/attribute/annotation/target/visitor/TargetInfoVisitor.java
Java
apache-2.0
3,983
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalDirAllocator; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.mapred.IFile.Reader; import org.apache.hadoop.mapred.IFile.Writer; import org.apache.hadoop.mapred.Merger.Segment; import org.apache.hadoop.mapreduce.MRConfig; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <code>BackupStore</code> is an utility class that is used to support * the mark-reset functionality of values iterator * * <p>It has two caches - a memory cache and a file cache where values are * stored as they are iterated, after a mark. On reset, values are retrieved * from these caches. Framework moves from the memory cache to the * file cache when the memory cache becomes full. * */ @InterfaceAudience.Private @InterfaceStability.Unstable public class BackupStore<K,V> { private static final Logger LOG = LoggerFactory.getLogger(BackupStore.class.getName()); private static final int MAX_VINT_SIZE = 9; private static final int EOF_MARKER_SIZE = 2 * MAX_VINT_SIZE; private final TaskAttemptID tid; private MemoryCache memCache; private FileCache fileCache; List<Segment<K,V>> segmentList = new LinkedList<Segment<K,V>>(); private int readSegmentIndex = 0; private int firstSegmentOffset = 0; private int currentKVOffset = 0; private int nextKVOffset = -1; private DataInputBuffer currentKey = null; private DataInputBuffer currentValue = new DataInputBuffer(); private DataInputBuffer currentDiskValue = new DataInputBuffer(); private boolean hasMore = false; private boolean inReset = false; private boolean clearMarkFlag = false; private boolean lastSegmentEOF = false; private Configuration conf; public BackupStore(Configuration conf, TaskAttemptID taskid) throws IOException { final float bufferPercent = conf.getFloat(JobContext.REDUCE_MARKRESET_BUFFER_PERCENT, 0f); if (bufferPercent > 1.0 || bufferPercent < 0.0) { throw new IOException(JobContext.REDUCE_MARKRESET_BUFFER_PERCENT + bufferPercent); } int maxSize = (int)Math.min( Runtime.getRuntime().maxMemory() * bufferPercent, Integer.MAX_VALUE); // Support an absolute size also. int tmp = conf.getInt(JobContext.REDUCE_MARKRESET_BUFFER_SIZE, 0); if (tmp > 0) { maxSize = tmp; } memCache = new MemoryCache(maxSize); fileCache = new FileCache(conf); tid = taskid; this.conf = conf; LOG.info("Created a new BackupStore with a memory of " + maxSize); } /** * Write the given K,V to the cache. * Write to memcache if space is available, else write to the filecache * @param key * @param value * @throws IOException */ public void write(DataInputBuffer key, DataInputBuffer value) throws IOException { assert (key != null && value != null); if (fileCache.isActive()) { fileCache.write(key, value); return; } if (memCache.reserveSpace(key, value)) { memCache.write(key, value); } else { fileCache.activate(); fileCache.write(key, value); } } public void mark() throws IOException { // We read one KV pair in advance in hasNext. // If hasNext has read the next KV pair from a new segment, but the // user has not called next() for that KV, then reset the readSegmentIndex // to the previous segment if (nextKVOffset == 0) { assert (readSegmentIndex != 0); assert (currentKVOffset != 0); readSegmentIndex --; } // just drop segments before the current active segment int i = 0; Iterator<Segment<K,V>> itr = segmentList.iterator(); while (itr.hasNext()) { Segment<K,V> s = itr.next(); if (i == readSegmentIndex) { break; } s.close(); itr.remove(); i++; LOG.debug("Dropping a segment"); } // FirstSegmentOffset is the offset in the current segment from where we // need to start reading on the next reset firstSegmentOffset = currentKVOffset; readSegmentIndex = 0; LOG.debug("Setting the FirsSegmentOffset to " + currentKVOffset); } public void reset() throws IOException { // Create a new segment for the previously written records only if we // are not already in the reset mode if (!inReset) { if (fileCache.isActive) { fileCache.createInDiskSegment(); } else { memCache.createInMemorySegment(); } } inReset = true; // Reset the segments to the correct position from where the next read // should begin. for (int i = 0; i < segmentList.size(); i++) { Segment<K,V> s = segmentList.get(i); if (s.inMemory()) { int offset = (i == 0) ? firstSegmentOffset : 0; s.getReader().reset(offset); } else { s.closeReader(); if (i == 0) { s.reinitReader(firstSegmentOffset); s.getReader().disableChecksumValidation(); } } } currentKVOffset = firstSegmentOffset; nextKVOffset = -1; readSegmentIndex = 0; hasMore = false; lastSegmentEOF = false; LOG.debug("Reset - First segment offset is " + firstSegmentOffset + " Segment List Size is " + segmentList.size()); } public boolean hasNext() throws IOException { if (lastSegmentEOF) { return false; } // We read the next KV from the cache to decide if there is any left. // Since hasNext can be called several times before the actual call to // next(), we use hasMore to avoid extra reads. hasMore is set to false // when the user actually consumes this record in next() if (hasMore) { return true; } Segment<K,V> seg = segmentList.get(readSegmentIndex); // Mark the current position. This would be set to currentKVOffset // when the user consumes this record in next(). nextKVOffset = (int) seg.getActualPosition(); if (seg.nextRawKey()) { currentKey = seg.getKey(); seg.getValue(currentValue); hasMore = true; return true; } else { if (!seg.inMemory()) { seg.closeReader(); } } // If this is the last segment, mark the lastSegmentEOF flag and return if (readSegmentIndex == segmentList.size() - 1) { nextKVOffset = -1; lastSegmentEOF = true; return false; } nextKVOffset = 0; readSegmentIndex ++; Segment<K,V> nextSegment = segmentList.get(readSegmentIndex); // We possibly are moving from a memory segment to a disk segment. // Reset so that we do not corrupt the in-memory segment buffer. // See HADOOP-5494 if (!nextSegment.inMemory()) { currentValue.reset(currentDiskValue.getData(), currentDiskValue.getLength()); nextSegment.init(null); } if (nextSegment.nextRawKey()) { currentKey = nextSegment.getKey(); nextSegment.getValue(currentValue); hasMore = true; return true; } else { throw new IOException("New segment did not have even one K/V"); } } public void next() throws IOException { if (!hasNext()) { throw new NoSuchElementException("iterate past last value"); } // Reset hasMore. See comment in hasNext() hasMore = false; currentKVOffset = nextKVOffset; nextKVOffset = -1; } public DataInputBuffer nextValue() { return currentValue; } public DataInputBuffer nextKey() { return currentKey; } public void reinitialize() throws IOException { if (segmentList.size() != 0) { clearSegmentList(); } memCache.reinitialize(true); fileCache.reinitialize(); readSegmentIndex = firstSegmentOffset = 0; currentKVOffset = 0; nextKVOffset = -1; hasMore = inReset = clearMarkFlag = false; } /** * This function is called the ValuesIterator when a mark is called * outside of a reset zone. */ public void exitResetMode() throws IOException { inReset = false; if (clearMarkFlag ) { // If a flag was set to clear mark, do the reinit now. // See clearMark() reinitialize(); return; } if (!fileCache.isActive) { memCache.reinitialize(false); } } /** For writing the first key and value bytes directly from the * value iterators, pass the current underlying output stream * @param length The length of the impending write */ public DataOutputStream getOutputStream(int length) throws IOException { if (memCache.reserveSpace(length)) { return memCache.dataOut; } else { fileCache.activate(); return fileCache.writer.getOutputStream(); } } /** This method is called by the valueIterators after writing the first * key and value bytes to the BackupStore * @param length */ public void updateCounters(int length) { if (fileCache.isActive) { fileCache.writer.updateCountersForExternalAppend(length); } else { memCache.usedSize += length; } } public void clearMark() throws IOException { if (inReset) { // If we are in the reset mode, we just mark a flag and come out // The actual re initialization would be done when we exit the reset // mode clearMarkFlag = true; } else { reinitialize(); } } private void clearSegmentList() throws IOException { for (Segment<K,V> segment: segmentList) { long len = segment.getLength(); segment.close(); if (segment.inMemory()) { memCache.unreserve(len); } } segmentList.clear(); } class MemoryCache { private DataOutputBuffer dataOut; private int blockSize; private int usedSize; private final BackupRamManager ramManager; // Memory cache is made up of blocks. private int defaultBlockSize = 1024 * 1024; public MemoryCache(int maxSize) { ramManager = new BackupRamManager(maxSize); if (maxSize < defaultBlockSize) { defaultBlockSize = maxSize; } } public void unreserve(long len) { ramManager.unreserve((int)len); } /** * Re-initialize the memory cache. * * @param clearAll If true, re-initialize the ramManager also. */ void reinitialize(boolean clearAll) { if (clearAll) { ramManager.reinitialize(); } int allocatedSize = createNewMemoryBlock(defaultBlockSize, defaultBlockSize); assert(allocatedSize == defaultBlockSize || allocatedSize == 0); LOG.debug("Created a new mem block of " + allocatedSize); } private int createNewMemoryBlock(int requestedSize, int minSize) { int allocatedSize = ramManager.reserve(requestedSize, minSize); usedSize = 0; if (allocatedSize == 0) { dataOut = null; blockSize = 0; } else { dataOut = new DataOutputBuffer(allocatedSize); blockSize = allocatedSize; } return allocatedSize; } /** * This method determines if there is enough space left in the * memory cache to write to the requested length + space for * subsequent EOF makers. * @param length * @return true if enough space is available */ boolean reserveSpace(int length) throws IOException { int availableSize = blockSize - usedSize; if (availableSize >= length + EOF_MARKER_SIZE) { return true; } // Not enough available. Close this block assert (!inReset); createInMemorySegment(); // Create a new block int tmp = Math.max(length + EOF_MARKER_SIZE, defaultBlockSize); availableSize = createNewMemoryBlock(tmp, (length + EOF_MARKER_SIZE)); return (availableSize == 0) ? false : true; } boolean reserveSpace(DataInputBuffer key, DataInputBuffer value) throws IOException { int keyLength = key.getLength() - key.getPosition(); int valueLength = value.getLength() - value.getPosition(); int requestedSize = keyLength + valueLength + WritableUtils.getVIntSize(keyLength) + WritableUtils.getVIntSize(valueLength); return reserveSpace(requestedSize); } /** * Write the key and value to the cache in the IFile format * @param key * @param value * @throws IOException */ public void write(DataInputBuffer key, DataInputBuffer value) throws IOException { int keyLength = key.getLength() - key.getPosition(); int valueLength = value.getLength() - value.getPosition(); WritableUtils.writeVInt(dataOut, keyLength); WritableUtils.writeVInt(dataOut, valueLength); dataOut.write(key.getData(), key.getPosition(), keyLength); dataOut.write(value.getData(), value.getPosition(), valueLength); usedSize += keyLength + valueLength + WritableUtils.getVIntSize(keyLength) + WritableUtils.getVIntSize(valueLength); LOG.debug("ID: " + segmentList.size() + " WRITE TO MEM"); } /** * This method creates a memory segment from the existing buffer * @throws IOException */ void createInMemorySegment () throws IOException { // If nothing was written in this block because the record size // was greater than the allocated block size, just return. if (usedSize == 0) { ramManager.unreserve(blockSize); return; } // spaceAvailable would have ensured that there is enough space // left for the EOF markers. assert ((blockSize - usedSize) >= EOF_MARKER_SIZE); WritableUtils.writeVInt(dataOut, IFile.EOF_MARKER); WritableUtils.writeVInt(dataOut, IFile.EOF_MARKER); usedSize += EOF_MARKER_SIZE; ramManager.unreserve(blockSize - usedSize); Reader<K, V> reader = new org.apache.hadoop.mapreduce.task.reduce.InMemoryReader<K, V>(null, (org.apache.hadoop.mapred.TaskAttemptID) tid, dataOut.getData(), 0, usedSize, conf); Segment<K, V> segment = new Segment<K, V>(reader, false); segmentList.add(segment); LOG.debug("Added Memory Segment to List. List Size is " + segmentList.size()); } } class FileCache { private LocalDirAllocator lDirAlloc; private final Configuration conf; private final FileSystem fs; private boolean isActive = false; private Path file = null; private IFile.Writer<K,V> writer = null; private int spillNumber = 0; public FileCache(Configuration conf) throws IOException { this.conf = conf; this.fs = FileSystem.getLocal(conf); this.lDirAlloc = new LocalDirAllocator(MRConfig.LOCAL_DIR); } void write(DataInputBuffer key, DataInputBuffer value) throws IOException { if (writer == null) { // If spillNumber is 0, we should have called activate and not // come here at all assert (spillNumber != 0); writer = createSpillFile(); } writer.append(key, value); LOG.debug("ID: " + segmentList.size() + " WRITE TO DISK"); } void reinitialize() { spillNumber = 0; writer = null; isActive = false; } void activate() throws IOException { isActive = true; writer = createSpillFile(); } void createInDiskSegment() throws IOException { assert (writer != null); writer.close(); Segment<K,V> s = new Segment<K, V>(conf, fs, file, null, true); writer = null; segmentList.add(s); LOG.debug("Disk Segment added to List. Size is " + segmentList.size()); } boolean isActive() { return isActive; } private Writer<K,V> createSpillFile() throws IOException { Path tmp = new Path(MRJobConfig.OUTPUT + "/backup_" + tid.getId() + "_" + (spillNumber++) + ".out"); LOG.info("Created file: " + tmp); file = lDirAlloc.getLocalPathForWrite(tmp.toUri().getPath(), -1, conf); FSDataOutputStream out = fs.create(file); out = CryptoUtils.wrapIfNecessary(conf, out); return new Writer<K, V>(conf, out, null, null, null, null, true); } } static class BackupRamManager implements RamManager { private int availableSize = 0; private final int maxSize; public BackupRamManager(int size) { availableSize = maxSize = size; } public boolean reserve(int requestedSize, InputStream in) { // Not used LOG.warn("Reserve(int, InputStream) not supported by BackupRamManager"); return false; } int reserve(int requestedSize) { if (availableSize == 0) { return 0; } int reservedSize = Math.min(requestedSize, availableSize); availableSize -= reservedSize; LOG.debug("Reserving: " + reservedSize + " Requested: " + requestedSize); return reservedSize; } int reserve(int requestedSize, int minSize) { if (availableSize < minSize) { LOG.debug("No space available. Available: " + availableSize + " MinSize: " + minSize); return 0; } else { return reserve(requestedSize); } } public void unreserve(int requestedSize) { availableSize += requestedSize; LOG.debug("Unreserving: " + requestedSize + ". Available: " + availableSize); } void reinitialize() { availableSize = maxSize; } } }
dennishuo/hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/BackupStore.java
Java
apache-2.0
18,966
//// [es6ClassTest8.ts] function f1(x:any) {return x;} class C { constructor() { var bar:any = (function() { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } } class Vector { static norm(v:Vector):Vector {return null;} static minus(v1:Vector, v2:Vector):Vector {return null;} static times(v1:Vector, v2:Vector):Vector {return null;} static cross(v1:Vector, v2:Vector):Vector {return null;} constructor(public x: number, public y: number, public z: number) { } static dot(v1:Vector, v2:Vector):Vector {return null;} } class Camera { public forward: Vector; public right: Vector; public up: Vector; constructor(public pos: Vector, lookAt: Vector) { var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt,this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.up = Vector.times(down, Vector.norm(Vector.cross(this.forward, this.right))); } } //// [es6ClassTest8.js] function f1(x) { return x; } var C = /** @class */ (function () { function C() { var bar = (function () { return bar; // 'bar' should be resolvable }); var b = f1(f1(bar)); } return C; }()); var Vector = /** @class */ (function () { function Vector(x, y, z) { this.x = x; this.y = y; this.z = z; } Vector.norm = function (v) { return null; }; Vector.minus = function (v1, v2) { return null; }; Vector.times = function (v1, v2) { return null; }; Vector.cross = function (v1, v2) { return null; }; Vector.dot = function (v1, v2) { return null; }; return Vector; }()); var Camera = /** @class */ (function () { function Camera(pos, lookAt) { this.pos = pos; var down = new Vector(0.0, -1.0, 0.0); this.forward = Vector.norm(Vector.minus(lookAt, this.pos)); this.right = Vector.times(down, Vector.norm(Vector.cross(this.forward, down))); this.up = Vector.times(down, Vector.norm(Vector.cross(this.forward, this.right))); } return Camera; }());
donaldpipowitch/TypeScript
tests/baselines/reference/es6ClassTest8.js
JavaScript
apache-2.0
2,281
Long short-term memory unit (LSTM) recurrent network cell. The default non-peephole implementation is based on: http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf S. Hochreiter and J. Schmidhuber. "Long Short-Term Memory". Neural Computation, 9(8):1735-1780, 1997. The peephole implementation is based on: https://research.google.com/pubs/archive/43905.pdf Hasim Sak, Andrew Senior, and Francoise Beaufays. "Long short-term memory recurrent neural network architectures for large scale acoustic modeling." INTERSPEECH, 2014. The class uses optional peep-hole connections, optional cell clipping, and an optional projection layer. - - - #### `tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)` {#LSTMCell.__call__} Run one step of LSTM. ##### Args: * <b>`inputs`</b>: input Tensor, 2D, batch x num_units. * <b>`state`</b>: if `state_is_tuple` is False, this must be a state Tensor, `2-D, batch x state_size`. If `state_is_tuple` is True, this must be a tuple of state Tensors, both `2-D`, with column sizes `c_state` and `m_state`. * <b>`scope`</b>: VariableScope for the created subgraph; defaults to "LSTMCell". ##### Returns: A tuple containing: - A `2-D, [batch x output_dim]`, Tensor representing the output of the LSTM after reading `inputs` when previous state was `state`. Here output_dim is: num_proj if num_proj was set, num_units otherwise. - Tensor(s) representing the new state of LSTM after reading `inputs` when the previous state was `state`. Same type and shape(s) as `state`. ##### Raises: * <b>`ValueError`</b>: If input size cannot be inferred from inputs via static shape inference. - - - #### `tf.nn.rnn_cell.LSTMCell.__init__(num_units, input_size=None, use_peepholes=False, cell_clip=None, initializer=None, num_proj=None, proj_clip=None, num_unit_shards=1, num_proj_shards=1, forget_bias=1.0, state_is_tuple=True, activation=tanh)` {#LSTMCell.__init__} Initialize the parameters for an LSTM cell. ##### Args: * <b>`num_units`</b>: int, The number of units in the LSTM cell * <b>`input_size`</b>: Deprecated and unused. * <b>`use_peepholes`</b>: bool, set True to enable diagonal/peephole connections. * <b>`cell_clip`</b>: (optional) A float value, if provided the cell state is clipped by this value prior to the cell output activation. * <b>`initializer`</b>: (optional) The initializer to use for the weight and projection matrices. * <b>`num_proj`</b>: (optional) int, The output dimensionality for the projection matrices. If None, no projection is performed. * <b>`proj_clip`</b>: (optional) A float value. If `num_proj > 0` and `proj_clip` is provided, then the projected values are clipped elementwise to within `[-proj_clip, proj_clip]`. * <b>`num_unit_shards`</b>: How to split the weight matrix. If >1, the weight matrix is stored across num_unit_shards. * <b>`num_proj_shards`</b>: How to split the projection matrix. If >1, the projection matrix is stored across num_proj_shards. * <b>`forget_bias`</b>: Biases of the forget gate are initialized by default to 1 in order to reduce the scale of forgetting at the beginning of the training. * <b>`state_is_tuple`</b>: If True, accepted and returned states are 2-tuples of the `c_state` and `m_state`. If False, they are concatenated along the column axis. This latter behavior will soon be deprecated. * <b>`activation`</b>: Activation function of the inner states. - - - #### `tf.nn.rnn_cell.LSTMCell.output_size` {#LSTMCell.output_size} - - - #### `tf.nn.rnn_cell.LSTMCell.state_size` {#LSTMCell.state_size} - - - #### `tf.nn.rnn_cell.LSTMCell.zero_state(batch_size, dtype)` {#LSTMCell.zero_state} Return zero-filled state tensor(s). ##### Args: * <b>`batch_size`</b>: int, float, or unit Tensor representing the batch size. * <b>`dtype`</b>: the data type to use for the state. ##### Returns: If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size x state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size x s]` for each s in `state_size`.
nanditav/15712-TensorFlow
tensorflow/g3doc/api_docs/python/functions_and_classes/shard5/tf.nn.rnn_cell.LSTMCell.md
Markdown
apache-2.0
4,306
//----------------------------------------------------------------------- // <copyright file="SimpleJson.cs" company="The Outercurve Foundation"> // Copyright (c) 2011, The Outercurve Foundation. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.opensource.org/licenses/mit-license.php // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author> // <website>https://github.com/facebook-csharp-sdk/simple-json</website> //----------------------------------------------------------------------- // VERSION: // NOTE: uncomment the following line to make SimpleJson class internal. //#define SIMPLE_JSON_INTERNAL // NOTE: uncomment the following line to make JsonArray and JsonObject class internal. //#define SIMPLE_JSON_OBJARRAYINTERNAL // NOTE: uncomment the following line to enable dynamic support. //#define SIMPLE_JSON_DYNAMIC // NOTE: uncomment the following line to enable DataContract support. //#define SIMPLE_JSON_DATACONTRACT // NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support. //#define SIMPLE_JSON_READONLY_COLLECTIONS // NOTE: uncomment the following line if you are compiling under Window Metro style application/library. // usually already defined in properties #if UNITY_WSA && UNITY_WP8 #define NETFX_CORE #endif // If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #if UNITY_WP8 || UNITY_WP8_1 || UNITY_WSA // #define SIMPLE_JSON_TYPEINFO #endif // original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html #if NETFX_CORE #define SIMPLE_JSON_TYPEINFO #endif using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; #if SIMPLE_JSON_DYNAMIC using System.Dynamic; #endif using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; // ReSharper disable LoopCanBeConvertedToQuery // ReSharper disable RedundantExplicitArrayCreation // ReSharper disable SuggestUseVarKeywordEvident namespace PlayFab.Json { public enum NullValueHandling { Include, // Include null values when serializing and deserializing objects Ignore // Ignore null values when serializing and deserializing objects } /// <summary> /// Customize the json output of a field or property /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class JsonProperty : Attribute { public string PropertyName = null; public NullValueHandling NullValueHandling = NullValueHandling.Include; } /// <summary> /// Represents the json array. /// </summary> [GeneratedCode("simple-json", "1.0.0")] [EditorBrowsable(EditorBrowsableState.Never)] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] #if SIMPLE_JSON_OBJARRAYINTERNAL internal #else public #endif class JsonArray : List<object> { /// <summary> /// Initializes a new instance of the <see cref="JsonArray"/> class. /// </summary> public JsonArray() { } /// <summary> /// Initializes a new instance of the <see cref="JsonArray"/> class. /// </summary> /// <param name="capacity">The capacity of the json array.</param> public JsonArray(int capacity) : base(capacity) { } /// <summary> /// The json representation of the array. /// </summary> /// <returns>The json representation of the array.</returns> public override string ToString() { return PlayFabSimpleJson.SerializeObject(this) ?? string.Empty; } } /// <summary> /// Represents the json object. /// </summary> [GeneratedCode("simple-json", "1.0.0")] [EditorBrowsable(EditorBrowsableState.Never)] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] #if SIMPLE_JSON_OBJARRAYINTERNAL internal #else public #endif class JsonObject : #if SIMPLE_JSON_DYNAMIC DynamicObject, #endif IDictionary<string, object> { private const int DICTIONARY_DEFAULT_SIZE = 16; /// <summary> /// The internal member dictionary. /// </summary> private readonly Dictionary<string, object> _members; /// <summary> /// Initializes a new instance of <see cref="JsonObject"/>. /// </summary> public JsonObject() { _members = new Dictionary<string, object>(DICTIONARY_DEFAULT_SIZE); } /// <summary> /// Initializes a new instance of <see cref="JsonObject"/>. /// </summary> /// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> implementation to use when comparing keys, or null to use the default <see cref="T:System.Collections.Generic.EqualityComparer`1"/> for the type of the key.</param> public JsonObject(IEqualityComparer<string> comparer) { _members = new Dictionary<string, object>(comparer); } /// <summary> /// Gets the <see cref="System.Object"/> at the specified index. /// </summary> /// <value></value> public object this[int index] { get { return GetAtIndex(_members, index); } } internal static object GetAtIndex(IDictionary<string, object> obj, int index) { if (obj == null) throw new ArgumentNullException("obj"); if (index >= obj.Count) throw new ArgumentOutOfRangeException("index"); int i = 0; foreach (KeyValuePair<string, object> o in obj) if (i++ == index) return o.Value; return null; } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public void Add(string key, object value) { _members.Add(key, value); } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(string key) { return _members.ContainsKey(key); } /// <summary> /// Gets the keys. /// </summary> /// <value>The keys.</value> public ICollection<string> Keys { get { return _members.Keys; } } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public bool Remove(string key) { return _members.Remove(key); } /// <summary> /// Tries the get value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns></returns> public bool TryGetValue(string key, out object value) { return _members.TryGetValue(key, out value); } /// <summary> /// Gets the values. /// </summary> /// <value>The values.</value> public ICollection<object> Values { get { return _members.Values; } } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value></value> public object this[string key] { get { return _members[key]; } set { _members[key] = value; } } /// <summary> /// Adds the specified item. /// </summary> /// <param name="item">The item.</param> public void Add(KeyValuePair<string, object> item) { _members.Add(item.Key, item.Value); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { _members.Clear(); } /// <summary> /// Determines whether [contains] [the specified item]. /// </summary> /// <param name="item">The item.</param> /// <returns> /// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<string, object> item) { return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value; } /// <summary> /// Copies to. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); int num = Count; foreach (KeyValuePair<string, object> kvp in _members) { array[arrayIndex++] = kvp; if (--num <= 0) return; } } /// <summary> /// Gets the count. /// </summary> /// <value>The count.</value> public int Count { get { return _members.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> public bool IsReadOnly { get { return false; } } /// <summary> /// Removes the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns></returns> public bool Remove(KeyValuePair<string, object> item) { return _members.Remove(item.Key); } /// <summary> /// Gets the enumerator. /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return _members.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return _members.GetEnumerator(); } /// <summary> /// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return PlayFabSimpleJson.SerializeObject(_members); } #if SIMPLE_JSON_DYNAMIC /// <summary> /// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another. /// </summary> /// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param> /// <param name="result">The result of the type conversion operation.</param> /// <returns> /// Alwasy returns true. /// </returns> public override bool TryConvert(ConvertBinder binder, out object result) { // <pex> if (binder == null) throw new ArgumentNullException("binder"); // </pex> Type targetType = binder.Type; if ((targetType == typeof(IEnumerable)) || (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) || (targetType == typeof(IDictionary<string, object>)) || (targetType == typeof(IDictionary))) { result = this; return true; } return base.TryConvert(binder, out result); } /// <summary> /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic. /// </summary> /// <param name="binder">Provides information about the deletion.</param> /// <returns> /// Alwasy returns true. /// </returns> public override bool TryDeleteMember(DeleteMemberBinder binder) { // <pex> if (binder == null) throw new ArgumentNullException("binder"); // </pex> return _members.Remove(binder.Name); } /// <summary> /// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations. /// </summary> /// <param name="binder">Provides information about the operation.</param> /// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name="indexes"/> is equal to 3.</param> /// <param name="result">The result of the index operation.</param> /// <returns> /// Alwasy returns true. /// </returns> public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (indexes == null) throw new ArgumentNullException("indexes"); if (indexes.Length == 1) { result = ((IDictionary<string, object>)this)[(string)indexes[0]]; return true; } result = null; return true; } /// <summary> /// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param> /// <returns> /// Alwasy returns true. /// </returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { object value; if (_members.TryGetValue(binder.Name, out value)) { result = value; return true; } result = null; return true; } /// <summary> /// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index. /// </summary> /// <param name="binder">Provides information about the operation.</param> /// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="indexes"/> is equal to 3.</param> /// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown. /// </returns> public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { if (indexes == null) throw new ArgumentNullException("indexes"); if (indexes.Length == 1) { ((IDictionary<string, object>)this)[(string)indexes[0]] = value; return true; } return base.TrySetIndex(binder, indexes, value); } /// <summary> /// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property. /// </summary> /// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param> /// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param> /// <returns> /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) /// </returns> public override bool TrySetMember(SetMemberBinder binder, object value) { // <pex> if (binder == null) throw new ArgumentNullException("binder"); // </pex> _members[binder.Name] = value; return true; } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns> /// A sequence that contains dynamic member names. /// </returns> public override IEnumerable<string> GetDynamicMemberNames() { foreach (var key in Keys) yield return key; } #endif } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList&lt;object>) and JsonObject(IDictionary&lt;string,object>). /// All numbers are parsed to doubles. /// </summary> [GeneratedCode("simple-json", "1.0.0")] #if SIMPLE_JSON_INTERNAL internal #else public #endif static class PlayFabSimpleJson { private enum TokenType : byte { NONE = 0, CURLY_OPEN = 1, CURLY_CLOSE = 2, SQUARED_OPEN = 3, SQUARED_CLOSE = 4, COLON = 5, COMMA = 6, STRING = 7, NUMBER = 8, TRUE = 9, FALSE = 10, NULL = 11, } private const int BUILDER_INIT = 2000; private static readonly char[] EscapeTable; private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' }; // private static readonly string EscapeCharactersString = new string(EscapeCharacters); internal static readonly List<Type> NumberTypes = new List<Type> { typeof(bool), typeof(byte), typeof(ushort), typeof(uint), typeof(ulong), typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(double), typeof(float), typeof(decimal) }; // Performance stuff [ThreadStatic] private static StringBuilder _serializeObjectBuilder; [ThreadStatic] private static StringBuilder _parseStringBuilder; static PlayFabSimpleJson() { EscapeTable = new char[93]; EscapeTable['"'] = '"'; EscapeTable['\\'] = '\\'; EscapeTable['\b'] = 'b'; EscapeTable['\f'] = 'f'; EscapeTable['\n'] = 'n'; EscapeTable['\r'] = 'r'; EscapeTable['\t'] = 't'; } /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An IList&lt;object>, a IDictionary&lt;string,object>, a double, a string, null, true, or false</returns> public static object DeserializeObject(string json) { object obj; if (TryDeserializeObject(json, out obj)) return obj; throw new SerializationException("Invalid JSON string"); } /// <summary> /// Try parsing the json string into a value. /// </summary> /// <param name="json"> /// A JSON string. /// </param> /// <param name="obj"> /// The object. /// </param> /// <returns> /// Returns true if successfull otherwise false. /// </returns> [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] public static bool TryDeserializeObject(string json, out object obj) { bool success = true; if (json != null) { int index = 0; obj = ParseValue(json, ref index, ref success); } else obj = null; return success; } public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy = null) { object jsonObject = DeserializeObject(json); if (type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)) return jsonObject; return (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type); } public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy = null) { return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy); } /// <summary> /// Converts a IDictionary&lt;string,object> / IList&lt;object> object into a JSON string /// </summary> /// <param name="json">A IDictionary&lt;string,object> / IList&lt;object></param> /// <param name="jsonSerializerStrategy">Serializer strategy to use</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy = null) { if (_serializeObjectBuilder == null) _serializeObjectBuilder = new StringBuilder(BUILDER_INIT); _serializeObjectBuilder.Length = 0; if (jsonSerializerStrategy == null) jsonSerializerStrategy = CurrentJsonSerializerStrategy; bool success = SerializeValue(jsonSerializerStrategy, json, _serializeObjectBuilder); return (success ? _serializeObjectBuilder.ToString() : null); } public static string EscapeToJavascriptString(string jsonString) { if (string.IsNullOrEmpty(jsonString)) return jsonString; StringBuilder sb = new StringBuilder(); char c; for (int i = 0; i < jsonString.Length;) { c = jsonString[i++]; if (c == '\\') { int remainingLength = jsonString.Length - i; if (remainingLength >= 2) { char lookahead = jsonString[i]; if (lookahead == '\\') { sb.Append('\\'); ++i; } else if (lookahead == '"') { sb.Append("\""); ++i; } else if (lookahead == 't') { sb.Append('\t'); ++i; } else if (lookahead == 'b') { sb.Append('\b'); ++i; } else if (lookahead == 'n') { sb.Append('\n'); ++i; } else if (lookahead == 'r') { sb.Append('\r'); ++i; } } } else { sb.Append(c); } } return sb.ToString(); } static IDictionary<string, object> ParseObject(string json, ref int index, ref bool success) { IDictionary<string, object> table = new JsonObject(); TokenType token; // { NextToken(json, ref index); bool done = false; while (!done) { token = LookAhead(json, index); if (token == TokenType.NONE) { success = false; return null; } else if (token == TokenType.COMMA) NextToken(json, ref index); else if (token == TokenType.CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index, ref success); if (!success) { success = false; return null; } // : token = NextToken(json, ref index); if (token != TokenType.COLON) { success = false; return null; } // value object value = ParseValue(json, ref index, ref success); if (!success) { success = false; return null; } table[name] = value; } } return table; } static JsonArray ParseArray(string json, ref int index, ref bool success) { JsonArray array = new JsonArray(); // [ NextToken(json, ref index); bool done = false; while (!done) { TokenType token = LookAhead(json, index); if (token == TokenType.NONE) { success = false; return null; } else if (token == TokenType.COMMA) NextToken(json, ref index); else if (token == TokenType.SQUARED_CLOSE) { NextToken(json, ref index); break; } else { object value = ParseValue(json, ref index, ref success); if (!success) return null; array.Add(value); } } return array; } static object ParseValue(string json, ref int index, ref bool success) { switch (LookAhead(json, index)) { case TokenType.STRING: return ParseString(json, ref index, ref success); case TokenType.NUMBER: return ParseNumber(json, ref index, ref success); case TokenType.CURLY_OPEN: return ParseObject(json, ref index, ref success); case TokenType.SQUARED_OPEN: return ParseArray(json, ref index, ref success); case TokenType.TRUE: NextToken(json, ref index); return true; case TokenType.FALSE: NextToken(json, ref index); return false; case TokenType.NULL: NextToken(json, ref index); return null; case TokenType.NONE: break; } success = false; return null; } static string ParseString(string json, ref int index, ref bool success) { if (_parseStringBuilder == null) _parseStringBuilder = new StringBuilder(BUILDER_INIT); _parseStringBuilder.Length = 0; EatWhitespace(json, ref index); // " char c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) break; c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) break; c = json[index++]; if (c == '"') _parseStringBuilder.Append('"'); else if (c == '\\') _parseStringBuilder.Append('\\'); else if (c == '/') _parseStringBuilder.Append('/'); else if (c == 'b') _parseStringBuilder.Append('\b'); else if (c == 'f') _parseStringBuilder.Append('\f'); else if (c == 'n') _parseStringBuilder.Append('\n'); else if (c == 'r') _parseStringBuilder.Append('\r'); else if (c == 't') _parseStringBuilder.Append('\t'); else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // parse the 32 bit hex into an integer codepoint uint codePoint; if (!(success = UInt32.TryParse(json.Substring(index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) return ""; // convert the integer codepoint to a unicode char and add to string if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate { index += 4; // skip 4 chars remainingLength = json.Length - index; if (remainingLength >= 6) { uint lowCodePoint; if (json.Substring(index, 2) == "\\u" && UInt32.TryParse(json.Substring(index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint)) { if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate { _parseStringBuilder.Append((char)codePoint); _parseStringBuilder.Append((char)lowCodePoint); index += 6; // skip 6 chars continue; } } } success = false; // invalid surrogate pair return ""; } _parseStringBuilder.Append(ConvertFromUtf32((int)codePoint)); // skip 4 chars index += 4; } else break; } } else _parseStringBuilder.Append(c); } if (!complete) { success = false; return null; } return _parseStringBuilder.ToString(); } private static string ConvertFromUtf32(int utf32) { // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm if (utf32 < 0 || utf32 > 0x10FFFF) throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); if (0xD800 <= utf32 && utf32 <= 0xDFFF) throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); if (utf32 < 0x10000) return new string((char)utf32, 1); utf32 -= 0x10000; return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) }); } static object ParseNumber(string json, ref int index, ref bool success) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; object returnNumber; string str = json.Substring(index, charLength); if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) { double number; success = double.TryParse(json.Substring(index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); returnNumber = number; } else if (str.IndexOf("-", StringComparison.OrdinalIgnoreCase) == -1) { ulong number; success = ulong.TryParse(json.Substring(index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); returnNumber = number; } else { long number; success = long.TryParse(json.Substring(index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); returnNumber = number; } index = lastIndex + 1; return returnNumber; } static int GetLastIndexOfNumber(string json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break; return lastIndex - 1; } static void EatWhitespace(string json, ref int index) { for (; index < json.Length; index++) if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break; } static TokenType LookAhead(string json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] static TokenType NextToken(string json, ref int index) { EatWhitespace(json, ref index); if (index == json.Length) return TokenType.NONE; char c = json[index]; index++; switch (c) { case '{': return TokenType.CURLY_OPEN; case '}': return TokenType.CURLY_CLOSE; case '[': return TokenType.SQUARED_OPEN; case ']': return TokenType.SQUARED_CLOSE; case ',': return TokenType.COMMA; case '"': return TokenType.STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TokenType.NUMBER; case ':': return TokenType.COLON; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return TokenType.FALSE; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return TokenType.TRUE; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return TokenType.NULL; } } return TokenType.NONE; } static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder) { bool success = true; string stringValue = value as string; if (value == null) builder.Append("null"); else if (stringValue != null) success = SerializeString(stringValue, builder); else { IDictionary<string, object> dict = value as IDictionary<string, object>; Type type = value.GetType(); Type[] genArgs = ReflectionUtils.GetGenericTypeArguments(type); var isStringKeyDictionary = type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>) && genArgs[0] == typeof(string); if (isStringKeyDictionary) { var strDictValue = value as IDictionary; success = SerializeObject(jsonSerializerStrategy, strDictValue.Keys, strDictValue.Values, builder); } else if (dict != null) { success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); } else { IDictionary<string, string> stringDictionary = value as IDictionary<string, string>; if (stringDictionary != null) { success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder); } else { IEnumerable enumerableValue = value as IEnumerable; if (enumerableValue != null) success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder); else if (IsNumeric(value)) success = SerializeNumber(value, builder); else if (value is bool) builder.Append((bool)value ? "true" : "false"); else { object serializedObject; success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject); if (success) SerializeValue(jsonSerializerStrategy, serializedObject, builder); } } } } return success; } static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder) { builder.Append("{"); IEnumerator ke = keys.GetEnumerator(); IEnumerator ve = values.GetEnumerator(); bool first = true; while (ke.MoveNext() && ve.MoveNext()) { object key = ke.Current; object value = ve.Current; if (!first) builder.Append(","); string stringKey = key as string; if (stringKey != null) SerializeString(stringKey, builder); else if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; builder.Append(":"); if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; first = false; } builder.Append("}"); return true; } static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder) { builder.Append("["); bool first = true; foreach (object value in anArray) { if (!first) builder.Append(","); if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; first = false; } builder.Append("]"); return true; } static bool SerializeString(string aString, StringBuilder builder) { // Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged) if (aString.IndexOfAny(EscapeCharacters) == -1) { builder.Append('"'); builder.Append(aString); builder.Append('"'); return true; } builder.Append('"'); int safeCharacterCount = 0; char[] charArray = aString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { char c = charArray[i]; // Non ascii characters are fine, buffer them up and send them to the builder // in larger chunks if possible. The escape table is a 1:1 translation table // with \0 [default(char)] denoting a safe character. if (c >= EscapeTable.Length || EscapeTable[c] == default(char)) { safeCharacterCount++; } else { if (safeCharacterCount > 0) { builder.Append(charArray, i - safeCharacterCount, safeCharacterCount); safeCharacterCount = 0; } builder.Append('\\'); builder.Append(EscapeTable[c]); } } if (safeCharacterCount > 0) { builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount); } builder.Append('"'); return true; } static bool SerializeNumber(object number, StringBuilder builder) { if (number is decimal) builder.Append(((decimal)number).ToString("R", CultureInfo.InvariantCulture)); else if (number is double) builder.Append(((double)number).ToString("R", CultureInfo.InvariantCulture)); else if (number is float) builder.Append(((float)number).ToString("R", CultureInfo.InvariantCulture)); else if (NumberTypes.IndexOf(number.GetType()) != -1) builder.Append(number); return true; } /// <summary> /// Determines if a given object is numeric in any way /// (can be integer, double, null, etc). /// </summary> static bool IsNumeric(object value) { if (value is sbyte) return true; if (value is byte) return true; if (value is short) return true; if (value is ushort) return true; if (value is int) return true; if (value is uint) return true; if (value is long) return true; if (value is ulong) return true; if (value is float) return true; if (value is double) return true; if (value is decimal) return true; return false; } private static IJsonSerializerStrategy _currentJsonSerializerStrategy; public static IJsonSerializerStrategy CurrentJsonSerializerStrategy { get { return _currentJsonSerializerStrategy ?? (_currentJsonSerializerStrategy = #if SIMPLE_JSON_DATACONTRACT DataContractJsonSerializerStrategy #else PocoJsonSerializerStrategy #endif ); } set { _currentJsonSerializerStrategy = value; } } private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy; [EditorBrowsable(EditorBrowsableState.Advanced)] public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy { get { return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy()); } } #if SIMPLE_JSON_DATACONTRACT private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy; [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy { get { return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy()); } } #endif } [GeneratedCode("simple-json", "1.0.0")] #if SIMPLE_JSON_INTERNAL internal #else public #endif interface IJsonSerializerStrategy { [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] bool TrySerializeNonPrimitiveObject(object input, out object output); object DeserializeObject(object value, Type type); } [GeneratedCode("simple-json", "1.0.0")] #if SIMPLE_JSON_INTERNAL internal #else public #endif class PocoJsonSerializerStrategy : IJsonSerializerStrategy { internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache; internal IDictionary<Type, IDictionary<MemberInfo, ReflectionUtils.GetDelegate>> GetCache; internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache; internal static readonly Type[] EmptyTypes = new Type[0]; internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) }; private static readonly string[] Iso8601Format = new string[] { @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z", @"yyyy-MM-dd\THH:mm:ss\Z", @"yyyy-MM-dd\THH:mm:ssK" }; public PocoJsonSerializerStrategy() { ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory); GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<MemberInfo, ReflectionUtils.GetDelegate>>(GetterValueFactory); SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory); } protected virtual string MapClrMemberNameToJsonFieldName(MemberInfo memberInfo) { // TODO: Optimize and/or cache foreach (JsonProperty eachAttr in memberInfo.GetCustomAttributes(typeof(JsonProperty), true)) if (!string.IsNullOrEmpty(eachAttr.PropertyName)) return eachAttr.PropertyName; return memberInfo.Name; } protected virtual void MapClrMemberNameToJsonFieldName(MemberInfo memberInfo, out string jsonName, out JsonProperty jsonProp) { jsonName = memberInfo.Name; jsonProp = null; // TODO: Optimize and/or cache foreach (JsonProperty eachAttr in memberInfo.GetCustomAttributes(typeof(JsonProperty), true)) { jsonProp = eachAttr; if (!string.IsNullOrEmpty(eachAttr.PropertyName)) jsonName = eachAttr.PropertyName; } } internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key) { return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes); } internal virtual IDictionary<MemberInfo, ReflectionUtils.GetDelegate> GetterValueFactory(Type type) { IDictionary<MemberInfo, ReflectionUtils.GetDelegate> result = new Dictionary<MemberInfo, ReflectionUtils.GetDelegate>(); foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) { if (propertyInfo.CanRead) { MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo); if (getMethod.IsStatic || !getMethod.IsPublic) continue; result[propertyInfo] = ReflectionUtils.GetGetMethod(propertyInfo); } } foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) { if (fieldInfo.IsStatic || !fieldInfo.IsPublic) continue; result[fieldInfo] = ReflectionUtils.GetGetMethod(fieldInfo); } return result; } internal virtual IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type) { IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>(); foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) { if (propertyInfo.CanWrite) { MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo); if (setMethod.IsStatic || !setMethod.IsPublic) continue; result[MapClrMemberNameToJsonFieldName(propertyInfo)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo)); } } foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) { if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic) continue; result[MapClrMemberNameToJsonFieldName(fieldInfo)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo)); } return result; } public virtual bool TrySerializeNonPrimitiveObject(object input, out object output) { return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public virtual object DeserializeObject(object value, Type type) { if (type == null) throw new ArgumentNullException("type"); if (value != null && type.IsInstanceOfType(value)) return value; string str = value as string; if (type == typeof(Guid) && string.IsNullOrEmpty(str)) return default(Guid); if (value == null) return null; object obj = null; if (str != null) { if (str.Length != 0) // We know it can't be null now. { if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime))) return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset))) return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))) return new Guid(str); if (type == typeof(Uri)) { bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute); Uri result; if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result)) return result; return null; } if (type == typeof(string)) return str; return Convert.ChangeType(str, type, CultureInfo.InvariantCulture); } else { if (type == typeof(Guid)) obj = default(Guid); else if (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)) obj = null; else obj = str; } // Empty string case if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)) return str; } else if (value is bool) return value; bool valueIsLong = value is long; bool valueIsUlong = value is ulong; bool valueIsDouble = value is double; Type nullableType = Nullable.GetUnderlyingType(type); if (nullableType != null && PlayFabSimpleJson.NumberTypes.IndexOf(nullableType) != -1) type = nullableType; // Just use the regular type for the conversion bool isNumberType = PlayFabSimpleJson.NumberTypes.IndexOf(type) != -1; bool isEnumType = type.GetTypeInfo().IsEnum; if ((valueIsLong && type == typeof(long)) || (valueIsUlong && type == typeof(ulong)) || (valueIsDouble && type == typeof(double))) return value; if ((valueIsLong || valueIsUlong || valueIsDouble) && isEnumType) return Enum.ToObject(type, Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture)); if ((valueIsLong || valueIsUlong || valueIsDouble) && isNumberType) return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); IDictionary<string, object> objects = value as IDictionary<string, object>; if (objects != null) { IDictionary<string, object> jsonObject = objects; if (ReflectionUtils.IsTypeDictionary(type)) { // if dictionary then Type[] types = ReflectionUtils.GetGenericTypeArguments(type); Type keyType = types[0]; Type valueType = types[1]; Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); IDictionary dict = (IDictionary)ConstructorCache[genericType](); foreach (KeyValuePair<string, object> kvp in jsonObject) dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType)); obj = dict; } else { if (type == typeof(object)) obj = value; else { obj = ConstructorCache[type](); foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in SetCache[type]) { object jsonValue; if (jsonObject.TryGetValue(setter.Key, out jsonValue)) { jsonValue = DeserializeObject(jsonValue, setter.Value.Key); setter.Value.Value(obj, jsonValue); } } } } } else { IList<object> valueAsList = value as IList<object>; if (valueAsList != null) { IList<object> jsonObject = valueAsList; IList list = null; if (type.IsArray) { list = (IList)ConstructorCache[type](jsonObject.Count); int i = 0; foreach (object o in jsonObject) list[i++] = DeserializeObject(o, type.GetElementType()); } else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type) || type == typeof(object)) { Type innerType = ReflectionUtils.GetGenericListElementType(type); ReflectionUtils.ConstructorDelegate ctrDelegate = null; if (type != typeof(object)) ctrDelegate = ConstructorCache[type]; if (ctrDelegate == null) ctrDelegate = ConstructorCache[typeof(List<>).MakeGenericType(innerType)]; list = (IList)ctrDelegate(); foreach (object o in jsonObject) list.Add(DeserializeObject(o, innerType)); } obj = list; } return obj; } if (ReflectionUtils.IsNullableType(type)) return ReflectionUtils.ToNullableType(obj, type); return obj; } protected virtual object SerializeEnum(Enum p) { return Convert.ToDouble(p, CultureInfo.InvariantCulture); } [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] protected virtual bool TrySerializeKnownTypes(object input, out object output) { bool returnValue = true; if (input is DateTime) output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); else if (input is DateTimeOffset) output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); else if (input is Guid) output = ((Guid)input).ToString("D"); else if (input is Uri) output = input.ToString(); else { Enum inputEnum = input as Enum; if (inputEnum != null) output = SerializeEnum(inputEnum); else { returnValue = false; output = null; } } return returnValue; } [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] protected virtual bool TrySerializeUnknownTypes(object input, out object output) { if (input == null) throw new ArgumentNullException("input"); output = null; Type type = input.GetType(); if (type.FullName == null) return false; IDictionary<string, object> obj = new JsonObject(); IDictionary<MemberInfo, ReflectionUtils.GetDelegate> getters = GetCache[type]; foreach (KeyValuePair<MemberInfo, ReflectionUtils.GetDelegate> getter in getters) { if (getter.Value == null) continue; string jsonKey; JsonProperty jsonProp; MapClrMemberNameToJsonFieldName(getter.Key, out jsonKey, out jsonProp); if (obj.ContainsKey(jsonKey)) throw new Exception("The given key is defined multiple times in the same type: " + input.GetType().Name + "." + jsonKey); object value = getter.Value(input); if (jsonProp == null || jsonProp.NullValueHandling == NullValueHandling.Include || value != null) obj.Add(jsonKey, value); } output = obj; return true; } } #if SIMPLE_JSON_DATACONTRACT [GeneratedCode("simple-json", "1.0.0")] #if SIMPLE_JSON_INTERNAL internal #else public #endif class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy { public DataContractJsonSerializerStrategy() { GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory); SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory); } internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type) { bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; if (!hasDataContract) return base.GetterValueFactory(type); string jsonKey; IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>(); foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) { if (propertyInfo.CanRead) { MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo); if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey)) result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo); } } foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) { if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey)) result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo); } return result; } internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type) { bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; if (!hasDataContract) return base.SetterValueFactory(type); string jsonKey; IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>(); foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) { if (propertyInfo.CanWrite) { MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo); if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey)) result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo)); } } foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) { if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey)) result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo)); } // todo implement sorting for DATACONTRACT. return result; } private static bool CanAdd(MemberInfo info, out string jsonKey) { jsonKey = null; if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null) return false; DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute)); if (dataMemberAttribute == null) return false; jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name; return true; } } #endif // This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules // that might be in place in the target project. [GeneratedCode("reflection-utils", "1.0.0")] #if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC public #else internal #endif class ReflectionUtils { private static readonly object[] EmptyObjects = new object[0]; public delegate object GetDelegate(object source); public delegate void SetDelegate(object source, object value); public delegate object ConstructorDelegate(params object[] args); public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key); [ThreadStatic] private static object[] _1ObjArray; #if SIMPLE_JSON_TYPEINFO public static TypeInfo GetTypeInfo(Type type) { return type.GetTypeInfo(); } #else public static Type GetTypeInfo(Type type) { return type; } #endif public static Attribute GetAttribute(MemberInfo info, Type type) { #if SIMPLE_JSON_TYPEINFO if (info == null || type == null || !info.IsDefined(type)) return null; return info.GetCustomAttribute(type); #else if (info == null || type == null || !Attribute.IsDefined(info, type)) return null; return Attribute.GetCustomAttribute(info, type); #endif } public static Type GetGenericListElementType(Type type) { if (type == typeof(object)) return type; IEnumerable<Type> interfaces; #if SIMPLE_JSON_TYPEINFO interfaces = type.GetTypeInfo().ImplementedInterfaces; #else interfaces = type.GetInterfaces(); #endif foreach (Type implementedInterface in interfaces) { if (IsTypeGeneric(implementedInterface) && implementedInterface.GetGenericTypeDefinition() == typeof(IList<>)) { return GetGenericTypeArguments(implementedInterface)[0]; } } return GetGenericTypeArguments(type)[0]; } public static Attribute GetAttribute(Type objectType, Type attributeType) { #if SIMPLE_JSON_TYPEINFO if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType)) return null; return objectType.GetTypeInfo().GetCustomAttribute(attributeType); #else if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType)) return null; return Attribute.GetCustomAttribute(objectType, attributeType); #endif } public static Type[] GetGenericTypeArguments(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetTypeInfo().GenericTypeArguments; #else return type.GetGenericArguments(); #endif } public static bool IsTypeGeneric(Type type) { return GetTypeInfo(type).IsGenericType; } public static bool IsTypeGenericeCollectionInterface(Type type) { if (!IsTypeGeneric(type)) return false; Type genericDefinition = type.GetGenericTypeDefinition(); return (genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>) #if SIMPLE_JSON_READONLY_COLLECTIONS || genericDefinition == typeof(IReadOnlyCollection<>) || genericDefinition == typeof(IReadOnlyList<>) #endif ); } public static bool IsAssignableFrom(Type type1, Type type2) { return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2)); } public static bool IsTypeDictionary(Type type) { #if SIMPLE_JSON_TYPEINFO if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) return true; #else if (typeof(System.Collections.IDictionary).IsAssignableFrom(type)) return true; #endif if (!GetTypeInfo(type).IsGenericType) return false; Type genericDefinition = type.GetGenericTypeDefinition(); return genericDefinition == typeof(IDictionary<,>) || genericDefinition == typeof(Dictionary<,>); } public static bool IsNullableType(Type type) { return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static object ToNullableType(object obj, Type nullableType) { return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture); } public static bool IsValueType(Type type) { return GetTypeInfo(type).IsValueType; } public static IEnumerable<ConstructorInfo> GetConstructors(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetTypeInfo().DeclaredConstructors; #else return type.GetConstructors(); #endif } public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType) { IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type); int i; bool matches; foreach (ConstructorInfo constructorInfo in constructorInfos) { ParameterInfo[] parameters = constructorInfo.GetParameters(); if (argsType.Length != parameters.Length) continue; i = 0; matches = true; foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters()) { if (parameterInfo.ParameterType != argsType[i]) { matches = false; break; } } if (matches) return constructorInfo; } return null; } public static IEnumerable<PropertyInfo> GetProperties(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetRuntimeProperties(); #else return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); #endif } public static IEnumerable<FieldInfo> GetFields(Type type) { #if SIMPLE_JSON_TYPEINFO return type.GetRuntimeFields(); #else return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); #endif } public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo) { #if SIMPLE_JSON_TYPEINFO return propertyInfo.GetMethod; #else return propertyInfo.GetGetMethod(true); #endif } public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo) { #if SIMPLE_JSON_TYPEINFO return propertyInfo.SetMethod; #else return propertyInfo.GetSetMethod(true); #endif } public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo) { return GetConstructorByReflection(constructorInfo); } public static ConstructorDelegate GetContructor(Type type, params Type[] argsType) { return GetConstructorByReflection(type, argsType); } public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo) { return delegate (object[] args) { var x = constructorInfo; return x.Invoke(args); }; } public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType) { ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType); return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo); } public static GetDelegate GetGetMethod(PropertyInfo propertyInfo) { return GetGetMethodByReflection(propertyInfo); } public static GetDelegate GetGetMethod(FieldInfo fieldInfo) { return GetGetMethodByReflection(fieldInfo); } public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo) { MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo); return delegate (object source) { return methodInfo.Invoke(source, EmptyObjects); }; } public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo) { return delegate (object source) { return fieldInfo.GetValue(source); }; } public static SetDelegate GetSetMethod(PropertyInfo propertyInfo) { return GetSetMethodByReflection(propertyInfo); } public static SetDelegate GetSetMethod(FieldInfo fieldInfo) { return GetSetMethodByReflection(fieldInfo); } public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo) { MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo); return delegate (object source, object value) { if (_1ObjArray == null) _1ObjArray = new object[1]; _1ObjArray[0] = value; methodInfo.Invoke(source, _1ObjArray); }; } public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo) { return delegate (object source, object value) { fieldInfo.SetValue(source, value); }; } public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private readonly object _lock = new object(); private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory; private Dictionary<TKey, TValue> _dictionary; public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory) { _valueFactory = valueFactory; } private TValue Get(TKey key) { if (_dictionary == null) return AddValue(key); TValue value; if (!_dictionary.TryGetValue(key, out value)) return AddValue(key); return value; } private TValue AddValue(TKey key) { TValue value = _valueFactory(key); lock (_lock) { if (_dictionary == null) { _dictionary = new Dictionary<TKey, TValue>(); _dictionary[key] = value; } else { TValue val; if (_dictionary.TryGetValue(key, out val)) return val; Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(_dictionary); dict[key] = value; _dictionary = dict; } } return value; } public void Add(TKey key, TValue value) { throw new NotImplementedException(); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public ICollection<TKey> Keys { get { return _dictionary.Keys; } } public bool Remove(TKey key) { throw new NotImplementedException(); } public bool TryGetValue(TKey key, out TValue value) { value = this[key]; return true; } public ICollection<TValue> Values { get { return _dictionary.Values; } } public TValue this[TKey key] { get { return Get(key); } set { throw new NotImplementedException(); } } public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } public int Count { get { return _dictionary.Count; } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dictionary.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } } } } // ReSharper restore LoopCanBeConvertedToQuery // ReSharper restore RedundantExplicitArrayCreation // ReSharper restore SuggestUseVarKeywordEvident
JoshuaStrunk/SDKGenerator
targets/unity-v2/source/Shared/Internal/SimpleJson.cs
C#
apache-2.0
83,283
package io.cattle.platform.networking.host.dao.impl; import static io.cattle.platform.core.model.tables.HostTable.*; import static io.cattle.platform.core.model.tables.HostVnetMapTable.*; import static io.cattle.platform.core.model.tables.SubnetVnetMapTable.*; import static io.cattle.platform.core.model.tables.VnetTable.*; import java.util.List; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.HostVnetMap; import io.cattle.platform.core.model.Network; import io.cattle.platform.core.model.Subnet; import io.cattle.platform.core.model.SubnetVnetMap; import io.cattle.platform.core.model.Vnet; import io.cattle.platform.core.model.tables.records.VnetRecord; import io.cattle.platform.db.jooq.dao.impl.AbstractJooqDao; import io.cattle.platform.networking.host.contants.HostOnlyConstants; import io.cattle.platform.networking.host.dao.HostOnlyDao; import io.cattle.platform.object.ObjectManager; import javax.inject.Inject; import org.jooq.Record; public class HostOnlyDaoImpl extends AbstractJooqDao implements HostOnlyDao { ObjectManager objectManager; @Override public Vnet getVnetForHost(Network network, Host host) { Long physicalHostId = host.getPhysicalHostId(); Record record = null; if ( physicalHostId == null ) { record = create() .select(VNET.fields()) .from(VNET) .join(HOST_VNET_MAP) .on(HOST_VNET_MAP.VNET_ID.eq(VNET.ID)) .where(VNET.NETWORK_ID.eq(network.getId()) .and(HOST_VNET_MAP.HOST_ID.eq(host.getId())) .and(HOST_VNET_MAP.REMOVED.isNull())) .fetchAny(); } else { record = create() .select(VNET.fields()) .from(VNET) .join(HOST_VNET_MAP) .on(HOST_VNET_MAP.VNET_ID.eq(VNET.ID)) .join(HOST) .on(HOST_VNET_MAP.HOST_ID.eq(HOST.ID)) .where(VNET.NETWORK_ID.eq(network.getId()) .and(HOST.PHYSICAL_HOST_ID.eq(physicalHostId)) .and(HOST_VNET_MAP.REMOVED.isNull())) .fetchAny(); } return record == null ? null : record.into(VnetRecord.class); } @Override public Vnet createVnetForHost(Network network, Host host, Subnet subnet, String uri) { if ( uri == null ) { uri = HostOnlyConstants.DEFAULT_HOST_SUBNET_URI; } Vnet vnet = objectManager.create(Vnet.class, VNET.URI, uri, VNET.ACCOUNT_ID, network.getAccountId(), VNET.NETWORK_ID, network.getId()); objectManager.create(HostVnetMap.class, HOST_VNET_MAP.VNET_ID, vnet.getId(), HOST_VNET_MAP.HOST_ID, host.getId()); if ( subnet != null ) { objectManager.create(SubnetVnetMap.class, SUBNET_VNET_MAP.VNET_ID, vnet.getId(), SUBNET_VNET_MAP.SUBNET_ID, subnet.getId()); } return vnet; } @Override public HostVnetMap mapVnetToHost(Vnet vnet, Host host) { List<HostVnetMap> maps = objectManager.find(HostVnetMap.class, HOST_VNET_MAP.VNET_ID, vnet.getId(), HOST_VNET_MAP.HOST_ID, host.getId()); if ( maps.size() > 0 ) { return maps.get(0); } return objectManager.create(HostVnetMap.class, HOST_VNET_MAP.VNET_ID, vnet.getId(), HOST_VNET_MAP.HOST_ID, host.getId()); } public ObjectManager getObjectManager() { return objectManager; } @Inject public void setObjectManager(ObjectManager objectManager) { this.objectManager = objectManager; } }
stresler/cattle
code/implementation/host-only-network/src/main/java/io/cattle/platform/networking/host/dao/impl/HostOnlyDaoImpl.java
Java
apache-2.0
3,937
// // Copyright 2013 Uncodin, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "document.h" namespace Bypass { Document::Document() : elements() { } Document::~Document() { } void Document::append(const Element& element) { elements.push_back(Element(element)); } size_t Document::size() { return elements.size(); } Element Document::operator[](size_t i) { return elements[i]; } }
trello/bypass
src/document.cpp
C++
apache-2.0
940
/* * Copyright (C) 2015 Bilibili * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tv.danmaku.ijk.media.player.misc; import android.annotation.TargetApi; import android.os.Build; import android.text.TextUtils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import tv.danmaku.ijk.media.player.IjkMediaMeta; public class IjkMediaFormat implements IMediaFormat { // Common public static final String KEY_IJK_CODEC_LONG_NAME_UI = "ijk-codec-long-name-ui"; public static final String KEY_IJK_CODEC_NAME_UI = "ijk-codec-name-ui"; public static final String KEY_IJK_BIT_RATE_UI = "ijk-bit-rate-ui"; // Video public static final String KEY_IJK_CODEC_PROFILE_LEVEL_UI = "ijk-profile-level-ui"; public static final String KEY_IJK_CODEC_PIXEL_FORMAT_UI = "ijk-pixel-format-ui"; public static final String KEY_IJK_RESOLUTION_UI = "ijk-resolution-ui"; public static final String KEY_IJK_FRAME_RATE_UI = "ijk-frame-rate-ui"; // Audio public static final String KEY_IJK_SAMPLE_RATE_UI = "ijk-sample-rate-ui"; public static final String KEY_IJK_CHANNEL_UI = "ijk-channel-ui"; // Codec public static final String CODEC_NAME_H264 = "h264"; public final IjkMediaMeta.IjkStreamMeta mMediaFormat; public IjkMediaFormat(IjkMediaMeta.IjkStreamMeta streamMeta) { mMediaFormat = streamMeta; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public int getInteger(String name) { if (mMediaFormat == null) return 0; return mMediaFormat.getInt(name); } @Override public String getString(String name) { if (mMediaFormat == null) return null; if (sFormatterMap.containsKey(name)) { Formatter formatter = sFormatterMap.get(name); return formatter.format(this); } return mMediaFormat.getString(name); } //------------------------- // Formatter //------------------------- private static abstract class Formatter { public String format(IjkMediaFormat mediaFormat) { String value = doFormat(mediaFormat); if (TextUtils.isEmpty(value)) return getDefaultString(); return value; } protected abstract String doFormat(IjkMediaFormat mediaFormat); @SuppressWarnings("SameReturnValue") protected String getDefaultString() { return "N/A"; } } private static final Map<String, Formatter> sFormatterMap = new HashMap<String, Formatter>(); { sFormatterMap.put(KEY_IJK_CODEC_LONG_NAME_UI, new Formatter() { @Override public String doFormat(IjkMediaFormat mediaFormat) { return mMediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_LONG_NAME); } }); sFormatterMap.put(KEY_IJK_CODEC_NAME_UI, new Formatter() { @Override public String doFormat(IjkMediaFormat mediaFormat) { return mMediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_NAME); } }); sFormatterMap.put(KEY_IJK_BIT_RATE_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int bitRate = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_BITRATE); if (bitRate <= 0) { return null; } else if (bitRate < 1000) { return String.format(Locale.US, "%d bit/s", bitRate); } else { return String.format(Locale.US, "%d kb/s", bitRate / 1000); } } }); sFormatterMap.put(KEY_IJK_CODEC_PROFILE_LEVEL_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int profileIndex = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_CODEC_PROFILE_ID); String profile; switch (profileIndex) { case IjkMediaMeta.FF_PROFILE_H264_BASELINE: profile = "Baseline"; break; case IjkMediaMeta.FF_PROFILE_H264_CONSTRAINED_BASELINE: profile = "Constrained Baseline"; break; case IjkMediaMeta.FF_PROFILE_H264_MAIN: profile = "Main"; break; case IjkMediaMeta.FF_PROFILE_H264_EXTENDED: profile = "Extended"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH: profile = "High"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_10: profile = "High 10"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_10_INTRA: profile = "High 10 Intra"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_422: profile = "High 4:2:2"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_422_INTRA: profile = "High 4:2:2 Intra"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_444: profile = "High 4:4:4"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_444_PREDICTIVE: profile = "High 4:4:4 Predictive"; break; case IjkMediaMeta.FF_PROFILE_H264_HIGH_444_INTRA: profile = "High 4:4:4 Intra"; break; case IjkMediaMeta.FF_PROFILE_H264_CAVLC_444: profile = "CAVLC 4:4:4"; break; default: return null; } StringBuilder sb = new StringBuilder(); sb.append(profile); String codecName = mediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_NAME); if (!TextUtils.isEmpty(codecName) && codecName.equalsIgnoreCase(CODEC_NAME_H264)) { int level = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_CODEC_LEVEL); if (level < 10) return sb.toString(); sb.append(" Profile Level "); sb.append((level / 10) % 10); if ((level % 10) != 0) { sb.append("."); sb.append(level % 10); } } return sb.toString(); } }); sFormatterMap.put(KEY_IJK_CODEC_PIXEL_FORMAT_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { return mediaFormat.getString(IjkMediaMeta.IJKM_KEY_CODEC_PIXEL_FORMAT); } }); sFormatterMap.put(KEY_IJK_RESOLUTION_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int width = mediaFormat.getInteger(KEY_WIDTH); int height = mediaFormat.getInteger(KEY_HEIGHT); int sarNum = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_SAR_NUM); int sarDen = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_SAR_DEN); if (width <= 0 || height <= 0) { return null; } else if (sarNum <= 0 || sarDen <= 0) { return String.format(Locale.US, "%d x %d", width, height); } else { return String.format(Locale.US, "%d x %d [SAR %d:%d]", width, height, sarNum, sarDen); } } }); sFormatterMap.put(KEY_IJK_FRAME_RATE_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int fpsNum = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_FPS_NUM); int fpsDen = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_FPS_DEN); if (fpsNum <= 0 || fpsDen <= 0) { return null; } else { return String.valueOf(((float) (fpsNum)) / fpsDen); } } }); sFormatterMap.put(KEY_IJK_SAMPLE_RATE_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int sampleRate = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_SAMPLE_RATE); if (sampleRate <= 0) { return null; } else { return String.format(Locale.US, "%d Hz", sampleRate); } } }); sFormatterMap.put(KEY_IJK_CHANNEL_UI, new Formatter() { @Override protected String doFormat(IjkMediaFormat mediaFormat) { int channelLayout = mediaFormat.getInteger(IjkMediaMeta.IJKM_KEY_CHANNEL_LAYOUT); if (channelLayout <= 0) { return null; } else { if (channelLayout == IjkMediaMeta.AV_CH_LAYOUT_MONO) { return "mono"; } else if (channelLayout == IjkMediaMeta.AV_CH_LAYOUT_STEREO) { return "stereo"; } else { return String.format(Locale.US, "%x", channelLayout); } } } }); } }
Kerr1Gan/ShareBox
ijkplayer-java/src/main/java/tv/danmaku/ijk/media/player/misc/IjkMediaFormat.java
Java
apache-2.0
10,341
/* * Copyright 2000-2014 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.client; import junit.framework.TestCase; import org.junit.Assert; import com.vaadin.client.componentlocator.LocatorUtil; /* * Test LocatorUtil.isUIElement() & isNotificaitonElement methods */ public class LocatorUtilTest extends TestCase { public void testIsUI1() { boolean isUI = LocatorUtil.isUIElement("com.vaadin.ui.UI"); Assert.assertTrue(isUI); } public void testIsUI2() { boolean isUI = LocatorUtil.isUIElement("/com.vaadin.ui.UI"); Assert.assertTrue(isUI); } public void testIsUI3() { boolean isUI = LocatorUtil .isUIElement("//com.vaadin.ui.UI[RandomString"); Assert.assertTrue(isUI); } public void testIsUI4() { boolean isUI = LocatorUtil.isUIElement("//com.vaadin.ui.UI[0]"); Assert.assertTrue(isUI); } public void testIsNotification1() { boolean isUI = LocatorUtil .isNotificationElement("com.vaadin.ui.VNotification"); Assert.assertTrue(isUI); } public void testIsNotification2() { boolean isUI = LocatorUtil .isNotificationElement("com.vaadin.ui.Notification"); Assert.assertTrue(isUI); } public void testIsNotification3() { boolean isUI = LocatorUtil .isNotificationElement("/com.vaadin.ui.VNotification["); Assert.assertTrue(isUI); } public void testIsNotification4() { boolean isUI = LocatorUtil .isNotificationElement("//com.vaadin.ui.VNotification[0]"); Assert.assertTrue(isUI); } }
udayinfy/vaadin
client/tests/src/com/vaadin/client/LocatorUtilTest.java
Java
apache-2.0
2,206
# # Description: Placeholder for service request validation #
maas-ufcg/manageiq
db/fixtures/ae_datastore/ManageIQ/Service/Provisioning/StateMachines/ServiceProvisionRequestApproval.class/__methods__/validate_request.rb
Ruby
apache-2.0
62
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Sql.Tests { public class UsageScenarioTests { [Fact] public void TestGetSubscriptionUsageData() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); // Get subscription usages for a location IEnumerable<SubscriptionUsage> subscriptionUsages = sqlClient.SubscriptionUsages.ListByLocation(TestEnvironmentUtilities.DefaultLocation); Assert.True(subscriptionUsages.Count() > 0); // Get a single subscription usage for a location SubscriptionUsage subscriptionUsage = sqlClient.SubscriptionUsages.Get(TestEnvironmentUtilities.DefaultLocation, "ServerQuota"); } } [Fact] public void TestGetUsageData() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); // Get server Usages IEnumerable<ServerUsage> serverUsages = sqlClient.ServerUsages.ListByServer(resourceGroup.Name, server.Name); Assert.True(serverUsages.Count(s => s.ResourceName == server.Name) > 1); // Create a database and get usages string dbName = SqlManagementTestUtilities.GenerateName(); var dbInput = new Database() { Location = server.Location }; sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput); IEnumerable<DatabaseUsage> databaseUsages = sqlClient.DatabaseUsages.ListByDatabase(resourceGroup.Name, server.Name, dbName); Assert.True(databaseUsages.Where(db => db.ResourceName == dbName).Count() == 1); } } } }
SiddharthChatrolaMs/azure-sdk-for-net
src/SDKs/SqlManagement/Sql.Tests/UsageScenarioTests.cs
C#
apache-2.0
2,605
module Fog module Compute class Ecloud class Real basic_request :get_backup_internet_service end end end end
jreichhold/chef-repo
vendor/ruby/2.0.0/gems/fog-1.20.0/lib/fog/ecloud/requests/compute/get_backup_internet_service.rb
Ruby
apache-2.0
143
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.suggest; import org.apache.lucene.search.spell.DirectSpellChecker; import org.apache.lucene.search.spell.StringDistance; import org.apache.lucene.search.spell.SuggestMode; import org.apache.lucene.util.automaton.LevenshteinAutomata; public class DirectSpellcheckerSettings { // NB: If this changes, make sure to change the default in TermBuilderSuggester public static SuggestMode DEFAULT_SUGGEST_MODE = SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX; public static float DEFAULT_ACCURACY = 0.5f; public static SortBy DEFAULT_SORT = SortBy.SCORE; // NB: If this changes, make sure to change the default in TermBuilderSuggester public static StringDistance DEFAULT_STRING_DISTANCE = DirectSpellChecker.INTERNAL_LEVENSHTEIN; public static int DEFAULT_MAX_EDITS = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE; public static int DEFAULT_MAX_INSPECTIONS = 5; public static float DEFAULT_MAX_TERM_FREQ = 0.01f; public static int DEFAULT_PREFIX_LENGTH = 1; public static int DEFAULT_MIN_WORD_LENGTH = 4; public static float DEFAULT_MIN_DOC_FREQ = 0f; private SuggestMode suggestMode = DEFAULT_SUGGEST_MODE; private float accuracy = DEFAULT_ACCURACY; private SortBy sort = DEFAULT_SORT; private StringDistance stringDistance = DEFAULT_STRING_DISTANCE; private int maxEdits = DEFAULT_MAX_EDITS; private int maxInspections = DEFAULT_MAX_INSPECTIONS; private float maxTermFreq = DEFAULT_MAX_TERM_FREQ; private int prefixLength = DEFAULT_PREFIX_LENGTH; private int minWordLength = DEFAULT_MIN_WORD_LENGTH; private float minDocFreq = DEFAULT_MIN_DOC_FREQ; public SuggestMode suggestMode() { return suggestMode; } public void suggestMode(SuggestMode suggestMode) { this.suggestMode = suggestMode; } public float accuracy() { return accuracy; } public void accuracy(float accuracy) { this.accuracy = accuracy; } public SortBy sort() { return sort; } public void sort(SortBy sort) { this.sort = sort; } public StringDistance stringDistance() { return stringDistance; } public void stringDistance(StringDistance distance) { this.stringDistance = distance; } public int maxEdits() { return maxEdits; } public void maxEdits(int maxEdits) { this.maxEdits = maxEdits; } public int maxInspections() { return maxInspections; } public void maxInspections(int maxInspections) { this.maxInspections = maxInspections; } public float maxTermFreq() { return maxTermFreq; } public void maxTermFreq(float maxTermFreq) { this.maxTermFreq = maxTermFreq; } public int prefixLength() { return prefixLength; } public void prefixLength(int prefixLength) { this.prefixLength = prefixLength; } public int minWordLength() { return minWordLength; } public void minWordLength(int minWordLength) { this.minWordLength = minWordLength; } public float minDocFreq() { return minDocFreq; } public void minDocFreq(float minDocFreq) { this.minDocFreq = minDocFreq; } @Override public String toString() { return "[" + "suggestMode=" + suggestMode + ",sort=" + sort + ",stringDistance=" + stringDistance + ",accuracy=" + accuracy + ",maxEdits=" + maxEdits + ",maxInspections=" + maxInspections + ",maxTermFreq=" + maxTermFreq + ",prefixLength=" + prefixLength + ",minWordLength=" + minWordLength + ",minDocFreq=" + minDocFreq + "]"; } }
camilojd/elasticsearch
core/src/main/java/org/elasticsearch/search/suggest/DirectSpellcheckerSettings.java
Java
apache-2.0
4,660
//======================================================================== // //File: $RCSfile: AddToLayerAction.java,v $ //Version: $Revision: 1.4 $ //Modified: $Date: 2013/01/10 23:05:58 $ // //Copyright (c) 2005-2014 Mentor Graphics Corporation. All rights reserved. // //======================================================================== // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. //======================================================================== package org.xtuml.bp.ui.graphics.actions; import java.util.ArrayList; import java.util.List; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.GraphicalViewer; import org.eclipse.jface.action.Action; import org.xtuml.bp.core.CorePlugin; import org.xtuml.bp.core.common.ClassQueryInterface_c; import org.xtuml.bp.core.common.Transaction; import org.xtuml.bp.core.common.TransactionManager; import org.xtuml.bp.ui.canvas.Connector_c; import org.xtuml.bp.ui.canvas.GraphicalElement_c; import org.xtuml.bp.ui.canvas.Graphicalelementinlayer_c; import org.xtuml.bp.ui.canvas.Layer_c; import org.xtuml.bp.ui.canvas.Model_c; import org.xtuml.bp.ui.canvas.Ooaofgraphics; import org.xtuml.bp.ui.canvas.Shape_c; import org.xtuml.bp.ui.graphics.editor.GraphicalEditor; import org.xtuml.bp.ui.graphics.parts.ConnectorEditPart; import org.xtuml.bp.ui.graphics.parts.ShapeEditPart; public class AddToLayerAction extends Action { private String layerName; private Model_c model; public AddToLayerAction(String layerName, Model_c model) { this.layerName = layerName; this.model = model; } @Override public void run() { Layer_c layer = Layer_c.getOneGD_LAYOnR34(model, new ClassQueryInterface_c() { @Override public boolean evaluate(Object candidate) { return ((Layer_c) candidate).getLayer_name().equals( layerName); } }); if (layer != null) { Transaction transaction = null; TransactionManager manager = TransactionManager.getSingleton(); try { transaction = manager.startTransaction( "Add element(s) to layer", Ooaofgraphics .getDefaultInstance()); List<GraphicalEditPart> selection = new ArrayList<GraphicalEditPart>(); GraphicalViewer viewer = GraphicalEditor.getEditor(model) .getGraphicalViewer(); for (Object selected : viewer.getSelectedEditParts()) { selection.add((GraphicalEditPart) selected); } for (GraphicalEditPart part : selection) { if (part instanceof ShapeEditPart || part instanceof ConnectorEditPart) { GraphicalElement_c elem = null; Object partModel = part.getModel(); if (partModel instanceof Connector_c) { elem = GraphicalElement_c .getOneGD_GEOnR2((Connector_c) partModel); } else { elem = GraphicalElement_c .getOneGD_GEOnR2((Shape_c) partModel); } if (elem != null) { // if this element already exists in the layer // skip, the tool allows this when at least one // selected element is not part of the layer Layer_c[] participatingLayers = Layer_c .getManyGD_LAYsOnR35(Graphicalelementinlayer_c .getManyGD_GLAYsOnR35(elem)); for(int i = 0; i < participatingLayers.length; i++) { if(participatingLayers[i] == layer) { continue; } } if (part instanceof ShapeEditPart) { ShapeEditPart shapePart = (ShapeEditPart) part; participatingLayers = shapePart .getInheritedLayers(); for (int i = 0; i < participatingLayers.length; i++) { if (participatingLayers[i] == layer) { continue; } } } if (part instanceof ConnectorEditPart) { ConnectorEditPart conPart = (ConnectorEditPart) part; participatingLayers = conPart .getInheritedLayers(); for (int i = 0; i < participatingLayers.length; i++) { if (participatingLayers[i] == layer) { continue; } } } layer.Addelementtolayer(elem.getElementid()); } if(!layer.getVisible()) { // see if the part also belongs to any // visible layers, otherwise de-select Layer_c[] existingLayers = Layer_c .getManyGD_LAYsOnR35(Graphicalelementinlayer_c .getManyGD_GLAYsOnR35(elem)); boolean participatesInVisibleLayer = false; for(int i = 0; i < existingLayers.length; i++) { if(existingLayers[i].getVisible()) { participatesInVisibleLayer = true; break; } } if(!participatesInVisibleLayer) { viewer.deselect(part); } } } } manager.endTransaction(transaction); } catch (Exception e) { if (transaction != null) { manager.cancelTransaction(transaction, e); } CorePlugin.logError("Unable to add element to layer.", e); } } } }
lwriemen/bridgepoint
src/org.xtuml.bp.ui.graphics/src/org/xtuml/bp/ui/graphics/actions/AddToLayerAction.java
Java
apache-2.0
5,561
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.ObjectModel Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Text.Tagging Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class RenameTagProducerTests Private Shared Function CreateCommandHandler(workspace As TestWorkspace) As RenameCommandHandler Return workspace.ExportProvider.GetCommandHandler(Of RenameCommandHandler)(PredefinedCommandHandlerNames.Rename) End Function Private Shared Async Function VerifyEmptyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, SpecializedCollections.EmptyEnumerable(Of Span)) End Function Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task Dim expectedSpans = actualWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan()) Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Async Function VerifyTaggedSpans(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task Dim expectedSpans = expectedTaggedWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Select(Function(ts) ts.ToSpan()) Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Async Function VerifyAnnotatedTaggedSpans(tagType As TextMarkerTag, annotationString As String, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedTaggedWorkspace As TestWorkspace) As Task Dim annotatedDocument = expectedTaggedWorkspace.Documents.SingleOrDefault(Function(d) d.AnnotatedSpans.Any()) Dim expectedSpans As IEnumerable(Of Span) If annotatedDocument Is Nothing Then expectedSpans = SpecializedCollections.EmptyEnumerable(Of Span) Else expectedSpans = GetAnnotatedSpans(annotationString, annotatedDocument) End If Await VerifyTaggedSpansCore(tagType, actualWorkspace, renameService, expectedSpans) End Function Private Shared Function GetAnnotatedSpans(annotationString As String, annotatedDocument As TestHostDocument) As IEnumerable(Of Span) Return annotatedDocument.AnnotatedSpans.SelectMany(Function(kvp) If kvp.Key = annotationString Then Return kvp.Value.Select(Function(ts) ts.ToSpan()) End If Return SpecializedCollections.EmptyEnumerable(Of Span) End Function) End Function Private Shared Async Function VerifySpansBeforeConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService) As Task ' Verify no fixup/resolved non-reference conflict span. Await VerifyEmptyTaggedSpans(HighlightTags.RenameFixupTag.Instance, actualWorkspace, renameService) ' Verify valid reference tags. Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService) End Function Private Shared Async Function VerifySpansAndBufferForConflictResolution(actualWorkspace As TestWorkspace, renameService As InlineRenameService, resolvedConflictWorkspace As TestWorkspace, session As IInlineRenameSession, Optional sessionCommit As Boolean = False, Optional sessionCancel As Boolean = False) As System.Threading.Tasks.Task Await WaitForRename(actualWorkspace) ' Verify fixup/resolved conflict spans. Await VerifyAnnotatedTaggedSpans(HighlightTags.RenameFixupTag.Instance, "Complexified", actualWorkspace, renameService, resolvedConflictWorkspace) ' Verify valid reference tags. Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, actualWorkspace, renameService, resolvedConflictWorkspace) VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) If sessionCommit Or sessionCancel Then Assert.True(Not sessionCommit Or Not sessionCancel) If sessionCancel Then session.Cancel() VerifyBufferContentsInWorkspace(actualWorkspace, actualWorkspace) ElseIf sessionCommit Then session.Commit() VerifyBufferContentsInWorkspace(actualWorkspace, resolvedConflictWorkspace) End If End If End Function Private Shared Async Function VerifyTaggedSpansCore(tagType As TextMarkerTag, actualWorkspace As TestWorkspace, renameService As InlineRenameService, expectedSpans As IEnumerable(Of Span)) As Task Dim taggedSpans = Await GetTagsOfType(tagType, actualWorkspace, renameService) Assert.Equal(expectedSpans, taggedSpans) End Function Private Shared Sub VerifyBufferContentsInWorkspace(actualWorkspace As TestWorkspace, expectedWorkspace As TestWorkspace) Dim actualDocs = actualWorkspace.Documents Dim expectedDocs = expectedWorkspace.Documents Assert.Equal(expectedDocs.Count, actualDocs.Count) For i = 0 To actualDocs.Count - 1 Dim actualDocument = actualDocs(i) Dim expectedDocument = expectedDocs(i) Dim actualText = actualDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim() Dim expectedText = expectedDocument.GetTextBuffer().CurrentSnapshot.GetText().Trim() Assert.Equal(expectedText, actualText) Next End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ValidTagsDuringSimpleRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifyTaggedSpans(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) session.Cancel() End Using End Function <WpfTheory> <WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function UnresolvableConflictInModifiedDocument(host As RenameTestHost) As System.Threading.Tasks.Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|conflict:args|}, int $$goo) { Goo(c => IsInt({|conflict:goo|}, c)); } private static void Goo(Func&lt;char, bool> p) { } private static void Goo(Func&lt;int, bool> p) { } private static bool IsInt(int goo, char c) { } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Replace(New Span(location, 3), "args") Await WaitForRename(workspace) Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] {|conflict:args|}, int args) { Goo(c => IsInt({|conflict:args|}, c)); } private static void Goo(Func&lt;char, bool> p) { } private static void Goo(Func&lt;int, bool> p) { } private static bool IsInt(int goo, char c) { } } </Document> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.Single() Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_InterleavedResolvedConflicts(host As RenameTestHost) As System.Threading.Tasks.Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> public class Class1 { #if Proj2 int fieldclash; #endif int field$$; void M() { int fieldclash = 8; #if Proj1 var a = [|field|]; #elif Proj2 var a = [|field|]; #elif Proj3 var a = field; #endif #if Proj1 var b = [|field|]; #elif Proj2 var b = [|field|]; #elif Proj3 var b = field; #endif } } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Insert(location, "clash") Await WaitForRename(workspace) Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"> public class Class1 { #if Proj2 int fieldclash; #endif int {|valid:fieldclash|}; void M() { int fieldclash = 8; #if Proj1 {|resolved:var a = this.{|valid:fieldclash|};|} #elif Proj2 var a = {|conflict:fieldclash|}; #elif Proj3 var a = field; #endif #if Proj1 {|resolved:var b = this.{|valid:fieldclash|};|} #elif Proj2 var b = {|conflict:fieldclash|}; #elif Proj3 var b = field; #endif } } </Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.First() Dim expectedSpans = GetAnnotatedSpans("resolved", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameFixupTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) expectedSpans = GetAnnotatedSpans("valid", renamedDocument) taggedSpans = GetTagsOfType(RenameFieldBackgroundAndBorderTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_UnresolvableConflictComments(host As RenameTestHost) As Task Dim originalDocument = " public class Class1 { #if Proj1 void Test(double x) { } #elif Proj2 void Test(long x) { } #endif void Tes$$(int i) { } void M() { Test(5); } }" Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><%= originalDocument %></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim document = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim location = document.CursorPosition.Value Dim session = StartSession(workspace) document.GetTextBuffer().Insert(location, "t") Await WaitForRename(workspace) Dim expectedDocument = $" public class Class1 {{ #if Proj1 void Test(double x) {{ }} #elif Proj2 void Test(long x) {{ }} #endif void Test(int i) {{ }} void M() {{ {{|conflict:{{|conflict:/* {String.Format(WorkspacesResources.Unmerged_change_from_project_0, "CSharpAssembly1")} {WorkspacesResources.Before_colon} Test(5); {WorkspacesResources.After_colon} Test((long)5); *|}}|}}/ Test((double)5); }} }}" Using renamedWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><%= expectedDocument %></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Dim renamedDocument = renamedWorkspace.Documents.First() Dim expectedSpans = GetAnnotatedSpans("conflict", renamedDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, document.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Using End Function <WpfTheory> <WorkItem(922197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/922197")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function UnresolvableConflictInUnmodifiedDocument(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$A|] { } </Document> <Document FilePath="B.cs"> class {|conflict:B|} { } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).GetTextBuffer() Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 1), "B") Await WaitForRename(workspace) Dim conflictDocument = workspace.Documents.Single(Function(d) d.FilePath = "B.cs") Dim expectedSpans = GetAnnotatedSpans("conflict", conflictDocument) Dim taggedSpans = GetTagsOfType(RenameConflictTag.Instance, renameService, conflictDocument.GetTextBuffer()) Assert.Equal(expectedSpans, taggedSpans) End Using End Function <WpfTheory> <WorkItem(847467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847467")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ValidStateWithEmptyReplacementTextAfterConflictResolution(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$T|] { } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 1), "this") ' Verify @ escaping Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class @[|this|] { } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Delete(New Span(location + 1, 4)) Await WaitForRename(workspace) ' Verify no escaping Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class { } </Document> </Project> </Workspace>, host) VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using session.Commit() Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class T { } </Document> </Project> </Workspace>, host) VerifyBufferContentsInWorkspace(workspace, resolvedConflictWorkspace) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(812789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812789")> Public Async Function RenamingEscapedIdentifiers(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void @$$as() { } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Verify @ escaping is still present Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void @[|as|]() { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Replace(New Span(location, 2), "bar") ' Verify @ escaping is removed Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|bar|]() { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using End Using End Function <WpfTheory> <WorkItem(812795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812795")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function BackspacingAfterConflictResolutionPreservesTrackingSpans(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { $$Bar(0); } void Goo(int i) { } void Bar(double d) { } } </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 3), "Goo") Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { {|Complexified:[|Goo|]((double)0);|} } void Goo(int i) { } void [|Goo|](double d) { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Delete Goo and type "as" commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New BackspaceKeyCommandArgs(view, view.TextBuffer), Sub() editorOperations.Backspace(), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "a"c), Sub() editorOperations.InsertText("a"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "s"c), Sub() editorOperations.InsertText("s"), Utilities.TestCommandExecutionContext.Create()) Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Method() { @[|as|](0); } void Goo(int i) { } void @[|as|](double d) { } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|$$goo|]) { var x = [|goo|]; bar = 23; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved non-reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved non-reference conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|bar|]) { var x = [|bar|]; {|Complexified:this.{|Resolved:bar|} = 23;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Replace(New Span(location, 3), "baR") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int bar; void M(int [|$$baR|]) { var x = [|baR|]; bar = 23; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NonReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|$$goo|] As Integer) Dim x = [|goo|] BAR = 23 End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved non-reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved non-reference conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|bar|] As Integer) Dim x = [|bar|] {|Complexified:Me.{|Resolved:BAR|} = 23|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Replace(New Span(location, 3), "boo") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim bar As Integer Sub M([|$$boo|] As Integer) Dim x = [|boo|] BAR = 23 End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|$$goo|]; void M(int bar) { [|goo|] = [|goo|] + bar; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|bar|]; void M(int bar) { {|Complexified:this.{|Resolved:[|bar|]|} = this.{|Resolved:[|bar|]|} + bar;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using textBuffer.Replace(New Span(location, 3), "ba") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int [|$$ba|]; void M(int bar) { [|ba|] = [|ba|] + bar; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_ReferenceConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|$$goo|] As Integer Sub M(bar As Integer) [|goo|] = [|goo|] + bar End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|bar|] As Integer Sub M(bar As Integer) {|Complexified:Me.{|Resolved:[|bar|]|} = Me.{|Resolved:[|bar|]|} + bar|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. textBuffer.Replace(New Span(location, 3), "ba") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [|$$ba|] As Integer Sub M(bar As Integer) [|ba|] = [|ba|] + bar End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCancel:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int [|$$goo|]) { var x = [|goo|]; @int = 23; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved escaping conflict. textBuffer.Replace(New Span(location, 3), "int") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int {|Resolved:@[|int|]|}) { var x = {|Resolved:@[|int|]|}; {|Complexified:this.{|Resolved:@int|} = 23;|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit to change "int" to "@in" so that we have no more conflicts, just escaping. textBuffer.Replace(New Span(location + 1, 3), "in") ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { int @int; void M(int {|Resolved:@[|in|]|}) { var x = {|Resolved:@[|in|]|}; @int = 23; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VisualBasic_FixupSpanDuringResolvableConflict_NeedsEscaping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M([|$$goo|] As Integer) Dim x = [|goo|] [NEW] = 23 End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved escaping conflict. textBuffer.Replace(New Span(location, 3), "New") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M({|Resolved:[[|New|]]|} As Integer) Dim x = {|Resolved:[[|New|]]|} {|Complexified:Me.{|Resolved:[NEW]|} = 23|} End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit to change "New" to "[Do]" so that we have no more conflicts, just escaping. textBuffer.Replace(New Span(location + 1, 3), "Do") ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Dim [New] As Integer Sub M({|Resolved:[[|Do|]]|} As Integer) Dim x = {|Resolved:[[|Do|]]|} [NEW] = 23 End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function FixupSpanDuringResolvableConflict_VerifyCaret(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|N$$w|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)()) Dim buffers = New Collection(Of ITextBuffer) buffers.Add(view.TextBuffer) DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Type first in the main identifier view.Selection.Clear() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create()) ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [[|Ne$$w|]](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) Dim location = view.Caret.Position.BufferPosition.Position Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.Equal(expectedLocation, location) End Using ' Make another edit to change "New" to "Nexw" so that we have no more conflicts or escaping. commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "x"c), Sub() editorOperations.InsertText("x"), Utilities.TestCommandExecutionContext.Create()) ' Verify resolved escaping conflict spans. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|Nex$$w|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) Dim location = view.Caret.Position.BufferPosition.Position Dim expectedLocation = resolvedConflictWorkspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.Equal(expectedLocation, location) End Using End Using End Function <WpfTheory> <WorkItem(771743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771743")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoSelectionAfterCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub [|M$$ain|](goo As Integer) End Sub End Class </Document> </Project> </Workspace>, host) Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) Dim commandHandler = CreateCommandHandler(workspace) Dim textViewService = Assert.IsType(Of TextBufferAssociatedViewService)(workspace.ExportProvider.GetExportedValue(Of ITextBufferAssociatedViewService)()) Dim buffers = New Collection(Of ITextBuffer) buffers.Add(view.TextBuffer) DirectCast(textViewService, ITextViewConnectionListener).SubjectBuffersConnected(view, ConnectionReason.TextViewLifetime, buffers) Dim location = view.Caret.Position.BufferPosition.Position view.Selection.Select(New SnapshotSpan(view.Caret.Position.BufferPosition, 2), False) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Type few characters. view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "e"c), Sub() editorOperations.InsertText("e"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "f"c), Sub() editorOperations.InsertText("f"), Utilities.TestCommandExecutionContext.Create()) commandHandler.ExecuteCommand(New TypeCharCommandArgs(view, view.TextBuffer, "g"c), Sub() editorOperations.InsertText("g"), Utilities.TestCommandExecutionContext.Create()) session.Commit() Dim selectionLength = view.Selection.End.Position - view.Selection.Start.Position Assert.Equal(0, selectionLength) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationOutsideConflict(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int x = [|$$Bar|](Goo([|Bar|](0))); } static int Goo(int i) { return 0; } static int [|Bar|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "Goo") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { {|Complexified:int x = {|Resolved:[|Goo|]|}((double)Goo({|Resolved:[|Goo|]|}((double)0)));|} } static int Goo(int i) { return 0; } static int [|Goo|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session) End Using ' Make another edit so that we have no more conflicts. textBuffer.Replace(New Span(location, 3), "GOO") Using newWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { int x = [|$$GOO|](Goo([|GOO|](0))); } static int Goo(int i) { return 0; } static int [|GOO|](double d) { return 1; } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, newWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ContainedComplexifiedSpan(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; namespace N { class A<T> { public virtual void Goo(T x) { } class B<S> : A<B<S>> { class [|$$C|]<U> : B<[|C|]<U>> // Rename C to A { public override void Goo(A<A<T>.B<S>>.B<A<T>.B<S>.[|C|]<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 1), "A") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; namespace N { class A<T> { public virtual void Goo(T x) { } class B<S> : A<B<S>> { class [|A|]<U> : B<[|A|]<U>> // Rename C to A { public override void Goo({|Complexified:N.{|Resolved:A|}<N.{|Resolved:A|}<T>.B<S>>|}.B<{|Complexified:N.{|Resolved:A|}<T>|}.B<S>.[|A|]<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Async Function CSharp_FixupSpanDuringResolvableConflict_ComplexificationReordersReferenceSpans(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class E { public static C [|$$Goo|](this C x, int tag) { return new C(); } } class C { C Bar(int tag) { return this.[|Goo|](1).[|Goo|](2); } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 3), "Bar") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class E { public static C [|Bar|](this C x, int tag) { return new C(); } } class C { C Bar(int tag) { {|Complexified:return E.{|Resolved:[|Bar|]|}(E.{|Resolved:[|Bar|]|}(this, 1), 2);|} } } </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_WithinCrefs(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using F = N; namespace N { interface I { void Goo(); } } class C { class E : F.I { /// <summary> /// This is a function <see cref="F.I.Goo"/> /// </summary> public void Goo() { } } class [|$$K|] { } } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 1), "F") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using F = N; namespace N { interface I { void Goo(); } } class C { class E : {|Complexified:{|Resolved:N|}|}.I { /// <summary> /// This is a function <see cref="{|Complexified:{|Resolved:N|}|}.I.Goo"/> /// </summary> public void Goo() { } } class [|$$F|] { } } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharp_FixupSpanDuringResolvableConflict_OverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; static class C { static void Ex(this string x) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Main() { Outer(y => Inner(x => x.Ex(), y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Goo } ]]> </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Await VerifySpansBeforeConflictResolution(workspace, renameService) ' Apply edit so that we have a resolved reference conflict. textBuffer.Replace(New Span(location, 2), "Goo") ' Verify fixup/resolved conflict span. Using resolvedConflictWorkspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; static class C { static void Ex(this string x) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Main() { {|Complexified:{|Resolved:Outer|}((string y) => {|Resolved:Inner|}(x => x.Ex(), y), 0);|} } } static class E { public static void [|Goo|](this int x) { } // Rename Ex to Goo } ]]> </Document> </Project> </Workspace>, host) Await VerifySpansAndBufferForConflictResolution(workspace, renameService, resolvedConflictWorkspace, session, sessionCommit:=True) End Using End Using End Function <WpfTheory> <WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CSharpShowDeclarationConflictsImmediately(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void Main(string[] args) { const int {|valid:$$V|} = 5; int {|conflict:V|} = 99; } } </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan()) Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService) Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan()) session.Cancel() AssertEx.Equal(validExpectedSpans, validTaggedSpans) AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans) End Using End Function <WpfTheory> <WorkItem(530817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530817")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VBShowDeclarationConflictsImmediately(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Bar() Dim {|valid:$$V|} as Integer Dim {|conflict:V|} as String End Sub End Class </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim session = StartSession(workspace) Dim validTaggedSpans = Await GetTagsOfType(HighlightTags.RenameFieldBackgroundAndBorderTag.Instance, workspace, renameService) Dim validExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("valid").Select(Function(ts) ts.ToSpan()) Dim conflictTaggedSpans = Await GetTagsOfType(RenameConflictTag.Instance, workspace, renameService) Dim conflictExpectedSpans = workspace.Documents.Single(Function(d) d.AnnotatedSpans.Count > 0).AnnotatedSpans("conflict").Select(Function(ts) ts.ToSpan()) session.Cancel() AssertEx.Equal(validExpectedSpans, validTaggedSpans) AssertEx.Equal(conflictExpectedSpans, conflictTaggedSpans) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ActiveSpanInSecondaryView(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|$$Goo|] End Class </Document> <Document> ' [|Goo|] </Document> </Project> </Workspace>, host) Dim renameService = workspace.GetService(Of InlineRenameService)() Dim location = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents(0).GetTextBuffer() Dim session = StartSession(workspace) session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=True) Await WaitForRename(workspace) session.RefreshRenameSessionWithOptionsChanged(CodeAnalysis.Rename.RenameOptions.RenameInComments, newValue:=False) Await WaitForRename(workspace) textBuffer.Replace(New Span(location, 3), "Bar") Await WaitForRename(workspace) End Using End Function Private Shared Async Function GetTagsOfType(expectedTagType As ITextMarkerTag, workspace As TestWorkspace, renameService As InlineRenameService) As Task(Of IEnumerable(Of Span)) Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Await WaitForRename(workspace) Return GetTagsOfType(expectedTagType, renameService, textBuffer) End Function Private Shared Function GetTagsOfType(expectedTagType As ITextMarkerTag, renameService As InlineRenameService, textBuffer As ITextBuffer) As IEnumerable(Of Span) Dim tagger = New RenameTagger(textBuffer, renameService) Dim tags = tagger.GetTags(textBuffer.CurrentSnapshot.GetSnapshotSpanCollection()) Return (From tag In tags Where tag.Tag Is expectedTagType Order By tag.Span.Start Select tag.Span.Span).ToList() End Function End Class End Namespace
AmadeusW/roslyn
src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb
Visual Basic
apache-2.0
73,739
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ec2.model; import java.io.Serializable; /** * <p> * Contains the output of DescribeSpotInstanceRequests. * </p> */ public class DescribeSpotInstanceRequestsResult implements Serializable, Cloneable { /** * One or more Spot Instance requests. */ private com.amazonaws.internal.ListWithAutoConstructFlag<SpotInstanceRequest> spotInstanceRequests; /** * One or more Spot Instance requests. * * @return One or more Spot Instance requests. */ public java.util.List<SpotInstanceRequest> getSpotInstanceRequests() { if (spotInstanceRequests == null) { spotInstanceRequests = new com.amazonaws.internal.ListWithAutoConstructFlag<SpotInstanceRequest>(); spotInstanceRequests.setAutoConstruct(true); } return spotInstanceRequests; } /** * One or more Spot Instance requests. * * @param spotInstanceRequests One or more Spot Instance requests. */ public void setSpotInstanceRequests(java.util.Collection<SpotInstanceRequest> spotInstanceRequests) { if (spotInstanceRequests == null) { this.spotInstanceRequests = null; return; } com.amazonaws.internal.ListWithAutoConstructFlag<SpotInstanceRequest> spotInstanceRequestsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<SpotInstanceRequest>(spotInstanceRequests.size()); spotInstanceRequestsCopy.addAll(spotInstanceRequests); this.spotInstanceRequests = spotInstanceRequestsCopy; } /** * One or more Spot Instance requests. * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setSpotInstanceRequests(java.util.Collection)} or * {@link #withSpotInstanceRequests(java.util.Collection)} if you want to * override the existing values. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param spotInstanceRequests One or more Spot Instance requests. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeSpotInstanceRequestsResult withSpotInstanceRequests(SpotInstanceRequest... spotInstanceRequests) { if (getSpotInstanceRequests() == null) setSpotInstanceRequests(new java.util.ArrayList<SpotInstanceRequest>(spotInstanceRequests.length)); for (SpotInstanceRequest value : spotInstanceRequests) { getSpotInstanceRequests().add(value); } return this; } /** * One or more Spot Instance requests. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param spotInstanceRequests One or more Spot Instance requests. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeSpotInstanceRequestsResult withSpotInstanceRequests(java.util.Collection<SpotInstanceRequest> spotInstanceRequests) { if (spotInstanceRequests == null) { this.spotInstanceRequests = null; } else { com.amazonaws.internal.ListWithAutoConstructFlag<SpotInstanceRequest> spotInstanceRequestsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<SpotInstanceRequest>(spotInstanceRequests.size()); spotInstanceRequestsCopy.addAll(spotInstanceRequests); this.spotInstanceRequests = spotInstanceRequestsCopy; } return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSpotInstanceRequests() != null) sb.append("SpotInstanceRequests: " + getSpotInstanceRequests() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSpotInstanceRequests() == null) ? 0 : getSpotInstanceRequests().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeSpotInstanceRequestsResult == false) return false; DescribeSpotInstanceRequestsResult other = (DescribeSpotInstanceRequestsResult)obj; if (other.getSpotInstanceRequests() == null ^ this.getSpotInstanceRequests() == null) return false; if (other.getSpotInstanceRequests() != null && other.getSpotInstanceRequests().equals(this.getSpotInstanceRequests()) == false) return false; return true; } @Override public DescribeSpotInstanceRequestsResult clone() { try { return (DescribeSpotInstanceRequestsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
sheofir/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeSpotInstanceRequestsResult.java
Java
apache-2.0
6,035
package org.asteriskjava.manager.event; public class DongleCENDEvent extends ManagerEvent { private static final long serialVersionUID = 3257845467831284784L; private String device; private String endstatus; private String cccause; private String duration; private String callidx; public DongleCENDEvent(Object source) { super(source); } public String getDevice() { return this.device; } public void setDevice(String device) { this.device = device; } public String getCallidx() { return callidx; } public void setCallidx(String callidx) { this.callidx = callidx; } public String getCccause() { return cccause; } public void setCccause(String cccause) { this.cccause = cccause; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getEndstatus() { return endstatus; } public void setEndstatus(String endstatus) { this.endstatus = endstatus; } }
seanbright/asterisk-java
src/main/java/org/asteriskjava/manager/event/DongleCENDEvent.java
Java
apache-2.0
1,118
package org.apache.lucene.util.junitcompat; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Properties; import org.junit.*; import org.junit.rules.TestRule; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import com.carrotsearch.randomizedtesting.rules.SystemPropertiesInvariantRule; import com.carrotsearch.randomizedtesting.rules.SystemPropertiesRestoreRule; /** * @see SystemPropertiesRestoreRule * @see SystemPropertiesInvariantRule */ public class TestSystemPropertiesInvariantRule extends WithNestedTests { public static final String PROP_KEY1 = "new-property-1"; public static final String VALUE1 = "new-value-1"; public TestSystemPropertiesInvariantRule() { super(true); } public static class Base extends WithNestedTests.AbstractNestedTest { public void testEmpty() {} } public static class InBeforeClass extends Base { @BeforeClass public static void beforeClass() { System.setProperty(PROP_KEY1, VALUE1); } } public static class InAfterClass extends Base { @AfterClass public static void afterClass() { System.setProperty(PROP_KEY1, VALUE1); } } public static class InTestMethod extends Base { public void testMethod1() { if (System.getProperty(PROP_KEY1) != null) { throw new RuntimeException("Shouldn't be here."); } System.setProperty(PROP_KEY1, VALUE1); } public void testMethod2() { testMethod1(); } } public static class NonStringProperties extends Base { public void testMethod1() { if (System.getProperties().get(PROP_KEY1) != null) { throw new RuntimeException("Will pass."); } Properties properties = System.getProperties(); properties.put(PROP_KEY1, new Object()); Assert.assertTrue(System.getProperties().get(PROP_KEY1) != null); } public void testMethod2() { testMethod1(); } @AfterClass public static void cleanup() { System.getProperties().remove(PROP_KEY1); } } public static class IgnoredProperty { @Rule public TestRule invariant = new SystemPropertiesInvariantRule(PROP_KEY1); @Test public void testMethod1() { System.setProperty(PROP_KEY1, VALUE1); } } @Before @After public void cleanup() { System.clearProperty(PROP_KEY1); } @Test public void testRuleInvariantBeforeClass() { Result runClasses = JUnitCore.runClasses(InBeforeClass.class); Assert.assertEquals(1, runClasses.getFailureCount()); Assert.assertTrue(runClasses.getFailures().get(0).getMessage() .contains(PROP_KEY1)); Assert.assertNull(System.getProperty(PROP_KEY1)); } @Test public void testRuleInvariantAfterClass() { Result runClasses = JUnitCore.runClasses(InAfterClass.class); Assert.assertEquals(1, runClasses.getFailureCount()); Assert.assertTrue(runClasses.getFailures().get(0).getMessage() .contains(PROP_KEY1)); Assert.assertNull(System.getProperty(PROP_KEY1)); } @Test public void testRuleInvariantInTestMethod() { Result runClasses = JUnitCore.runClasses(InTestMethod.class); Assert.assertEquals(2, runClasses.getFailureCount()); for (Failure f : runClasses.getFailures()) { Assert.assertTrue(f.getMessage().contains(PROP_KEY1)); } Assert.assertNull(System.getProperty(PROP_KEY1)); } @Test public void testNonStringProperties() { Result runClasses = JUnitCore.runClasses(NonStringProperties.class); Assert.assertEquals(1, runClasses.getFailureCount()); Assert.assertTrue(runClasses.getFailures().get(0).getMessage().contains("Will pass")); Assert.assertEquals(3, runClasses.getRunCount()); } @Test public void testIgnoredProperty() { System.clearProperty(PROP_KEY1); try { Result runClasses = JUnitCore.runClasses(IgnoredProperty.class); Assert.assertEquals(0, runClasses.getFailureCount()); Assert.assertEquals(VALUE1, System.getProperty(PROP_KEY1)); } finally { System.clearProperty(PROP_KEY1); } } }
smartan/lucene
src/test/java/org/apache/lucene/util/junitcompat/TestSystemPropertiesInvariantRule.java
Java
apache-2.0
4,895
#if defined(MPI_VERSION) #if (MPI_VERSION > 3) || (MPI_VERSION == 3 && MPI_SUBVERSION >= 1) #define PyMPI_HAVE_MPI_Aint_add 1 #define PyMPI_HAVE_MPI_Aint_diff 1 #define PyMPI_HAVE_MPI_File_iread_at_all 1 #define PyMPI_HAVE_MPI_File_iwrite_at_all 1 #define PyMPI_HAVE_MPI_File_iread_all 1 #define PyMPI_HAVE_MPI_File_iwrite_all 1 #endif #endif
pressel/mpi4py
src/lib-mpi/config/mpi-31.h
C
bsd-2-clause
348
PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,value LONGVARCHAR); INSERT INTO "meta" VALUES('version','43'); INSERT INTO "meta" VALUES('last_compatible_version','43'); INSERT INTO "meta" VALUES('Default Search Provider ID','2'); INSERT INTO "meta" VALUES('Default Search Provider ID Backup','3'); INSERT INTO "meta" VALUES('Default Search Provider ID Backup Signature','Invalid signature'); INSERT INTO "meta" VALUES('Builtin Keyword Version','37'); CREATE TABLE keywords (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,show_in_default_list INTEGER,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,autogenerate_keyword INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR); INSERT INTO "keywords" VALUES(2,'Google','google.com','http://www.google.com/favicon.ico','{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q={searchTerms}',1,1,'',0,0,'UTF-8','{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}',1,1,1234,0,'{google:baseURL}webhp?{google:RLZ}sourceid=chrome-instant&ie={inputEncoding}&ion=1{searchTerms}&nord=1',0,'{1234-5678-90AB-CDEF}'); CREATE TABLE keywords_backup (id INTEGER PRIMARY KEY,short_name VARCHAR NOT NULL,keyword VARCHAR NOT NULL,favicon_url VARCHAR NOT NULL,url VARCHAR NOT NULL,show_in_default_list INTEGER,safe_for_autoreplace INTEGER,originating_url VARCHAR,date_created INTEGER DEFAULT 0,usage_count INTEGER DEFAULT 0,input_encodings VARCHAR,suggest_url VARCHAR,prepopulate_id INTEGER DEFAULT 0,autogenerate_keyword INTEGER DEFAULT 0,logo_id INTEGER DEFAULT 0,created_by_policy INTEGER DEFAULT 0,instant_url VARCHAR,last_modified INTEGER DEFAULT 0, sync_guid VARCHAR); INSERT INTO "keywords_backup" VALUES(2,'Google','google.com','http://www.google.com/favicon.ico','{google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q={searchTerms}',1,1,'',0,0,'UTF-8','{google:baseSuggestURL}search?client=chrome&hl={language}&q={searchTerms}',1,1,1234,0,'{google:baseURL}webhp?{google:RLZ}sourceid=chrome-instant&ie={inputEncoding}&ion=1{searchTerms}&nord=1',0,'{1234-5678-90AB-CDEF}'); CREATE TABLE logins (origin_url VARCHAR NOT NULL, action_url VARCHAR, username_element VARCHAR, username_value VARCHAR, password_element VARCHAR, password_value BLOB, submit_element VARCHAR, signon_realm VARCHAR NOT NULL,ssl_valid INTEGER NOT NULL,preferred INTEGER NOT NULL,date_created INTEGER NOT NULL,blacklisted_by_user INTEGER NOT NULL,scheme INTEGER NOT NULL,UNIQUE (origin_url, username_element, username_value, password_element, submit_element, signon_realm)); CREATE TABLE web_app_icons (url LONGVARCHAR,width int,height int,image BLOB, UNIQUE (url, width, height)); CREATE TABLE web_apps (url LONGVARCHAR UNIQUE,has_all_images INTEGER NOT NULL); CREATE TABLE autofill (name VARCHAR, value VARCHAR, value_lower VARCHAR, pair_id INTEGER PRIMARY KEY, count INTEGER DEFAULT 1); CREATE TABLE autofill_dates ( pair_id INTEGER DEFAULT 0, date_created INTEGER DEFAULT 0); CREATE TABLE autofill_profiles ( guid VARCHAR PRIMARY KEY, company_name VARCHAR, address_line_1 VARCHAR, address_line_2 VARCHAR, city VARCHAR, state VARCHAR, zipcode VARCHAR, country VARCHAR, country_code VARCHAR, date_modified INTEGER NOT NULL DEFAULT 0); CREATE TABLE autofill_profile_names ( guid VARCHAR, first_name VARCHAR, middle_name VARCHAR, last_name VARCHAR); CREATE TABLE autofill_profile_emails ( guid VARCHAR, email VARCHAR); CREATE TABLE autofill_profile_phones ( guid VARCHAR, type INTEGER DEFAULT 0, number VARCHAR); CREATE TABLE credit_cards ( guid VARCHAR PRIMARY KEY, name_on_card VARCHAR, expiration_month INTEGER, expiration_year INTEGER, card_number_encrypted BLOB, date_modified INTEGER NOT NULL DEFAULT 0); CREATE TABLE token_service (service VARCHAR PRIMARY KEY NOT NULL,encrypted_token BLOB); CREATE INDEX logins_signon ON logins (signon_realm); CREATE INDEX web_apps_url_index ON web_apps (url); CREATE INDEX autofill_name ON autofill (name); CREATE INDEX autofill_name_value_lower ON autofill (name, value_lower); CREATE INDEX autofill_dates_pair_id ON autofill_dates (pair_id); COMMIT;
ropik/chromium
chrome/test/data/web_database/version_43.sql
SQL
bsd-3-clause
4,559
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Larry's favorite LaTeX macros for making technical books. These have % been refined for years, starting with SIGGRAPH course notes in the % '90's, further refined for _Advanced RenderMan_. % % Please use or modify this at will. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Define typesetting commands for filenames and code % % Just like Advanced RenderMan -- all code in courier, keywords in text % courier but not bold. \def\codefont{\ttfamily} % font to use for code \def\ce{\codefont\bfseries} % emphasize something in code % % Define typesetting commands for filenames and code % \def\cf{\codefont} % abbreviation for \codefont \def\fn{\codefont} % in-line filenames & unix commands \def\kw{\codefont} % in-line keyword \newcommand{\var}[1]{{\kw \emph{#1}}} % variable \newcommand{\qkw}[1]{{\kw "#1"}} % quoted keyword \newcommand{\qkws}[1]{{\small \kw "#1"}} % quoted keyword, small \newcommand{\qkwf}[1]{{\footnotesize \kw "#1"}} % quoted keyword, tiny % Define some environments for easy typesetting of small amounts of % code. These are mostly just wrappers around verbatim, but the % different varieties also change font sizes. \newenvironment{code}{\small \verbatimtab}{\endverbatimtab} \newenvironment{smallcode}{\small \renewcommand{\baselinestretch}{0.8} \verbatimtab}{\endverbatimtab \renewcommand{\baselinestretch}{1}} \newenvironment{tinycode}{\footnotesize \renewcommand{\baselinestretch}{0.75} \verbatimtab}{\endverbatimtab \renewcommand{\baselinestretch}{1}} \begin{htmlonly} \renewenvironment{code}{\begin{verbatim}}{\end{verbatim}} \newenvironment{smallcode}{\begin{verbatim}}{\end{verbatim}} \newenvironment{tinycode}{\begin{verbatim}}{\end{verbatim}} \end{htmlonly} \newcommand{\includedcode}[1]{{\small \verbatimtabinput{#1}}} \newcommand{\smallincludedcode}[1]{{\small \renewcommand{\baselinestretch}{0.8} \verbatimtabinput{#1} \renewcommand{\baselinestretch}{1}}} \newcommand{\tinyincludedcode}[1]{{\footnotesize \renewcommand{\baselinestretch}{0.75} \verbatimtabinput{#1} \renewcommand{\baselinestretch}{1}}} % Also create a hyphenation list, essentially just to guarantee that % type names aren't hyphenated %\hyphenation{Attribute} % Handy for parameter lists \def\pl{{\rm\emph{...params...}\xspace}} \def\dotdotdot{{\rm\emph{...}\xspace}} \hyphenation{parameterlist} %begin{latexonly} \newenvironment{apilist}{\begin{list}{}{\medskip \item[]}}{\end{list}} \newcommand{\apiitem}[1]{\vspace{12pt} \noindent {\bf\tt #1} \vspace{-10pt}\begin{apilist}\nopagebreak[4]} \newcommand{\apiend}{\end{apilist}\medskip\pagebreak[2]} \def\bigspc{\makebox[72pt]{}} \def\spc{\makebox[24pt]{}} \def\halfspc{\makebox[12pt]{}} \def\neghalfspc{\hspace{-12pt}} \def\negspc{\hspace{-24pt}} \def\chapwidthbegin{} \def\chapwidthend{} %end{latexonly} \begin{htmlonly} \newcommand{\apiitem}[1]{\medskip \noindent {\bf #1} \begin{quote}} \newcommand{\apiend}{\end{quote}} \def\halfspc{\begin{rawhtml} &nbsp; &nbsp; \end{rawhtml}} \def\spc{\halfspc\halfspc} \pagecolor[named]{White} \def\chapwidthbegin{\begin{rawhtml}<p><table cellspacing=1><tr><td width=550>\end{rawhtml}} \def\chapwidthend{\begin{rawhtml}</td></tr></table>\end{rawhtml}} \end{htmlonly} \newcommand{\apibinding}[3]{\apiitem{#1\\[1ex]#2\\[1ex]#3}} \newcommand{\CPPBINDING}[1]{\par {\small C++ BINDING:}\par {\spc \codefont #1}} \newcommand{\PARAMETERS}{\par {\small PARAMETERS:} \par} \newcommand{\EXAMPLE}{\par {\small EXAMPLE:} \par} \newcommand{\EXAMPLES}{\par {\small EXAMPLES:} \par} \newcommand{\SEEALSO}{\par \hspace{-20pt} See Also: \par} % The \begin{algorithm} \end{algorithm} macros (in algorithm.sty) are % great for code that can fit all on one page. But when it can't, use % these macros. The first parameter is the caption, the second is the % label name. \newcommand{\longalgorithmbegin}[2]{\noindent\hrulefill \\ \refstepcounter{algorithm} \noindent {\bf Listing \arabic{chapter}.\arabic{algorithm}}: #1 \label{#2} \\ \addcontentsline{loa}{algorithm}{\numberline {\arabic{algorithm}} #1} \noindent\hrulefill } \newcommand{\longalgorithmend}{\noindent\hrulefill \\} \def\NEW{\marginpar[\medskip\hfill~\fbox{\sffamily \Huge NEW!}~]{\medskip~\fbox{\sffamily \Huge NEW!}~}} \newcommand{\NEWdown}[1]{\marginpar[\vspace{#1}\hfill\fbox{\sffamily \Huge NEW!}]{\vspace{#1}\fbox{\sffamily \Huge NEW!}}} \def\DEPRECATED{\marginpar[\medskip\hfill~\fbox{\sffamily \Large Deprecated}]{\medskip~\fbox{\sffamily \Large Deprecated}}} \newcommand{\DEPRECATEDdown}[1]{\marginpar{\vspace{#1}\fbox{\sffamily \Large Deprecated}}} \def\CHANGED{\marginpar[\medskip\hfill~\fbox{\sffamily \huge CHANGED!}~]{\medskip~\fbox{\sffamily \huge CHANGED!}~}} \def\ENHANCED{\marginpar[\medskip\hfill~\fbox{\sffamily \huge ENHANCED}~]{\medskip~\fbox{\sffamily \huge ENHANCED}~}} \def\QUESTION{\marginpar[\medskip\hfill~\fbox{\sffamily \Huge ?}~~~~]{\medskip~\fbox{\sffamily \Huge ?}~~~~}} \newcommand{\indexapi}[1]{\index{#1@\tt#1\rm}} \newenvironment{annotate}{\medskip\sffamily\em\noindent}{\medskip} %\newenvironment{annotate}{\begin{comment}}{\end{comment}}
mcanthony/OpenShadingLanguage
src/doc/macros.tex
TeX
bsd-3-clause
5,201
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import shutil import tempfile from telemetry import decorators from telemetry.testing import options_for_unittests from telemetry.testing import page_test_test_case from measurements import skpicture_printer class SkpicturePrinterUnitTest(page_test_test_case.PageTestTestCase): def setUp(self): self._options = options_for_unittests.GetCopy() self._skp_outdir = tempfile.mkdtemp('_skp_test') def tearDown(self): shutil.rmtree(self._skp_outdir) @decorators.Disabled('android') def testSkpicturePrinter(self): ps = self.CreateStorySetFromFileInUnittestDataDir('blank.html') measurement = skpicture_printer.SkpicturePrinter(self._skp_outdir) results = self.RunMeasurement(measurement, ps, options=self._options) # Picture printing is not supported on all platforms. if results.failures: assert 'not supported' in results.failures[0].exc_info[1].message return saved_picture_count = results.FindAllPageSpecificValuesNamed( 'saved_picture_count') self.assertEquals(len(saved_picture_count), 1) self.assertGreater(saved_picture_count[0].GetRepresentativeNumber(), 0)
axinging/chromium-crosswalk
tools/perf/measurements/skpicture_printer_unittest.py
Python
bsd-3-clause
1,305