repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
vvavrychuk/glibc
misc/usleep.c
1019
/* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <unistd.h> /* Sleep USECONDS microseconds, or until a previously set timer goes off. */ int usleep (useconds) useconds_t useconds; { __set_errno (ENOSYS); return -1; } stub_warning (usleep)
gpl-2.0
hannes/linux
arch/x86/mm/cpu_entry_area.c
5234
// SPDX-License-Identifier: GPL-2.0 #include <linux/spinlock.h> #include <linux/percpu.h> #include <asm/cpu_entry_area.h> #include <asm/pgtable.h> #include <asm/fixmap.h> #include <asm/desc.h> static DEFINE_PER_CPU_PAGE_ALIGNED(struct entry_stack_page, entry_stack_storage); #ifdef CONFIG_X86_64 static DEFINE_PER_CPU_PAGE_ALIGNED(char, exception_stacks [(N_EXCEPTION_STACKS - 1) * EXCEPTION_STKSZ + DEBUG_STKSZ]); #endif struct cpu_entry_area *get_cpu_entry_area(int cpu) { unsigned long va = CPU_ENTRY_AREA_PER_CPU + cpu * CPU_ENTRY_AREA_SIZE; BUILD_BUG_ON(sizeof(struct cpu_entry_area) % PAGE_SIZE != 0); return (struct cpu_entry_area *) va; } EXPORT_SYMBOL(get_cpu_entry_area); void cea_set_pte(void *cea_vaddr, phys_addr_t pa, pgprot_t flags) { unsigned long va = (unsigned long) cea_vaddr; set_pte_vaddr(va, pfn_pte(pa >> PAGE_SHIFT, flags)); } static void __init cea_map_percpu_pages(void *cea_vaddr, void *ptr, int pages, pgprot_t prot) { for ( ; pages; pages--, cea_vaddr+= PAGE_SIZE, ptr += PAGE_SIZE) cea_set_pte(cea_vaddr, per_cpu_ptr_to_phys(ptr), prot); } static void percpu_setup_debug_store(int cpu) { #ifdef CONFIG_CPU_SUP_INTEL int npages; void *cea; if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) return; cea = &get_cpu_entry_area(cpu)->cpu_debug_store; npages = sizeof(struct debug_store) / PAGE_SIZE; BUILD_BUG_ON(sizeof(struct debug_store) % PAGE_SIZE != 0); cea_map_percpu_pages(cea, &per_cpu(cpu_debug_store, cpu), npages, PAGE_KERNEL); cea = &get_cpu_entry_area(cpu)->cpu_debug_buffers; /* * Force the population of PMDs for not yet allocated per cpu * memory like debug store buffers. */ npages = sizeof(struct debug_store_buffers) / PAGE_SIZE; for (; npages; npages--, cea += PAGE_SIZE) cea_set_pte(cea, 0, PAGE_NONE); #endif } /* Setup the fixmap mappings only once per-processor */ static void __init setup_cpu_entry_area(int cpu) { #ifdef CONFIG_X86_64 extern char _entry_trampoline[]; /* On 64-bit systems, we use a read-only fixmap GDT and TSS. */ pgprot_t gdt_prot = PAGE_KERNEL_RO; pgprot_t tss_prot = PAGE_KERNEL_RO; #else /* * On native 32-bit systems, the GDT cannot be read-only because * our double fault handler uses a task gate, and entering through * a task gate needs to change an available TSS to busy. If the * GDT is read-only, that will triple fault. The TSS cannot be * read-only because the CPU writes to it on task switches. * * On Xen PV, the GDT must be read-only because the hypervisor * requires it. */ pgprot_t gdt_prot = boot_cpu_has(X86_FEATURE_XENPV) ? PAGE_KERNEL_RO : PAGE_KERNEL; pgprot_t tss_prot = PAGE_KERNEL; #endif cea_set_pte(&get_cpu_entry_area(cpu)->gdt, get_cpu_gdt_paddr(cpu), gdt_prot); cea_map_percpu_pages(&get_cpu_entry_area(cpu)->entry_stack_page, per_cpu_ptr(&entry_stack_storage, cpu), 1, PAGE_KERNEL); /* * The Intel SDM says (Volume 3, 7.2.1): * * Avoid placing a page boundary in the part of the TSS that the * processor reads during a task switch (the first 104 bytes). The * processor may not correctly perform address translations if a * boundary occurs in this area. During a task switch, the processor * reads and writes into the first 104 bytes of each TSS (using * contiguous physical addresses beginning with the physical address * of the first byte of the TSS). So, after TSS access begins, if * part of the 104 bytes is not physically contiguous, the processor * will access incorrect information without generating a page-fault * exception. * * There are also a lot of errata involving the TSS spanning a page * boundary. Assert that we're not doing that. */ BUILD_BUG_ON((offsetof(struct tss_struct, x86_tss) ^ offsetofend(struct tss_struct, x86_tss)) & PAGE_MASK); BUILD_BUG_ON(sizeof(struct tss_struct) % PAGE_SIZE != 0); cea_map_percpu_pages(&get_cpu_entry_area(cpu)->tss, &per_cpu(cpu_tss_rw, cpu), sizeof(struct tss_struct) / PAGE_SIZE, tss_prot); #ifdef CONFIG_X86_32 per_cpu(cpu_entry_area, cpu) = get_cpu_entry_area(cpu); #endif #ifdef CONFIG_X86_64 BUILD_BUG_ON(sizeof(exception_stacks) % PAGE_SIZE != 0); BUILD_BUG_ON(sizeof(exception_stacks) != sizeof(((struct cpu_entry_area *)0)->exception_stacks)); cea_map_percpu_pages(&get_cpu_entry_area(cpu)->exception_stacks, &per_cpu(exception_stacks, cpu), sizeof(exception_stacks) / PAGE_SIZE, PAGE_KERNEL); cea_set_pte(&get_cpu_entry_area(cpu)->entry_trampoline, __pa_symbol(_entry_trampoline), PAGE_KERNEL_RX); #endif percpu_setup_debug_store(cpu); } static __init void setup_cpu_entry_area_ptes(void) { #ifdef CONFIG_X86_32 unsigned long start, end; BUILD_BUG_ON(CPU_ENTRY_AREA_PAGES * PAGE_SIZE < CPU_ENTRY_AREA_MAP_SIZE); BUG_ON(CPU_ENTRY_AREA_BASE & ~PMD_MASK); start = CPU_ENTRY_AREA_BASE; end = start + CPU_ENTRY_AREA_MAP_SIZE; /* Careful here: start + PMD_SIZE might wrap around */ for (; start < end && start >= CPU_ENTRY_AREA_BASE; start += PMD_SIZE) populate_extra_pte(start); #endif } void __init setup_cpu_entry_areas(void) { unsigned int cpu; setup_cpu_entry_area_ptes(); for_each_possible_cpu(cpu) setup_cpu_entry_area(cpu); }
gpl-2.0
rneugeba/linux-stable
drivers/gpu/drm/amd/amdgpu/amdgpu_ih.h
2696
/* * Copyright 2014 Advanced Micro Devices, Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 __AMDGPU_IH_H__ #define __AMDGPU_IH_H__ struct amdgpu_device; struct amdgpu_iv_entry; /* * R6xx+ IH ring */ struct amdgpu_ih_ring { struct amdgpu_bo *ring_obj; volatile uint32_t *ring; unsigned rptr; unsigned ring_size; uint64_t gpu_addr; uint32_t ptr_mask; atomic_t lock; bool enabled; unsigned wptr_offs; unsigned rptr_offs; u32 doorbell_index; bool use_doorbell; bool use_bus_addr; dma_addr_t rb_dma_addr; /* only used when use_bus_addr = true */ }; /* provided by the ih block */ struct amdgpu_ih_funcs { /* ring read/write ptr handling, called from interrupt context */ u32 (*get_wptr)(struct amdgpu_device *adev); bool (*prescreen_iv)(struct amdgpu_device *adev); void (*decode_iv)(struct amdgpu_device *adev, struct amdgpu_iv_entry *entry); void (*set_rptr)(struct amdgpu_device *adev); }; #define amdgpu_ih_get_wptr(adev) (adev)->irq.ih_funcs->get_wptr((adev)) #define amdgpu_ih_prescreen_iv(adev) (adev)->irq.ih_funcs->prescreen_iv((adev)) #define amdgpu_ih_decode_iv(adev, iv) (adev)->irq.ih_funcs->decode_iv((adev), (iv)) #define amdgpu_ih_set_rptr(adev) (adev)->irq.ih_funcs->set_rptr((adev)) int amdgpu_ih_ring_init(struct amdgpu_device *adev, struct amdgpu_ih_ring *ih, unsigned ring_size, bool use_bus_addr); void amdgpu_ih_ring_fini(struct amdgpu_device *adev, struct amdgpu_ih_ring *ih); int amdgpu_ih_process(struct amdgpu_device *adev, struct amdgpu_ih_ring *ih, void (*callback)(struct amdgpu_device *adev, struct amdgpu_ih_ring *ih)); #endif
gpl-2.0
abg1979/git
t/t0025-crlf-renormalize.sh
1012
#!/bin/sh test_description='CRLF renormalization' TEST_PASSES_SANITIZE_LEAK=true . ./test-lib.sh test_expect_success setup ' git config core.autocrlf false && printf "LINEONE\nLINETWO\nLINETHREE\n" >LF.txt && printf "LINEONE\r\nLINETWO\r\nLINETHREE\r\n" >CRLF.txt && printf "LINEONE\r\nLINETWO\nLINETHREE\n" >CRLF_mix_LF.txt && git add . && git commit -m initial ' test_expect_success 'renormalize CRLF in repo' ' echo "*.txt text=auto" >.gitattributes && git add --renormalize "*.txt" && cat >expect <<-\EOF && i/lf w/crlf attr/text=auto CRLF.txt i/lf w/lf attr/text=auto LF.txt i/lf w/mixed attr/text=auto CRLF_mix_LF.txt EOF git ls-files --eol | sed -e "s/ / /g" -e "s/ */ /g" | sort >actual && test_cmp expect actual ' test_expect_success 'ignore-errors not mistaken for renormalize' ' git reset --hard && echo "*.txt text=auto" >.gitattributes && git ls-files --eol >expect && git add --ignore-errors "*.txt" && git ls-files --eol >actual && test_cmp expect actual ' test_done
gpl-2.0
jongh90/kvm
drivers/gpu/drm/i915/intel_uncore.c
39461
/* * Copyright © 2013 Intel Corporation * * 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 (including the next * paragraph) 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. */ #include "i915_drv.h" #include "intel_drv.h" #include "i915_vgpu.h" #include <linux/pm_runtime.h> #define FORCEWAKE_ACK_TIMEOUT_MS 2 #define __raw_i915_read8(dev_priv__, reg__) readb((dev_priv__)->regs + (reg__)) #define __raw_i915_write8(dev_priv__, reg__, val__) writeb(val__, (dev_priv__)->regs + (reg__)) #define __raw_i915_read16(dev_priv__, reg__) readw((dev_priv__)->regs + (reg__)) #define __raw_i915_write16(dev_priv__, reg__, val__) writew(val__, (dev_priv__)->regs + (reg__)) #define __raw_i915_read32(dev_priv__, reg__) readl((dev_priv__)->regs + (reg__)) #define __raw_i915_write32(dev_priv__, reg__, val__) writel(val__, (dev_priv__)->regs + (reg__)) #define __raw_i915_read64(dev_priv__, reg__) readq((dev_priv__)->regs + (reg__)) #define __raw_i915_write64(dev_priv__, reg__, val__) writeq(val__, (dev_priv__)->regs + (reg__)) #define __raw_posting_read(dev_priv__, reg__) (void)__raw_i915_read32(dev_priv__, reg__) static const char * const forcewake_domain_names[] = { "render", "blitter", "media", }; const char * intel_uncore_forcewake_domain_to_str(const enum forcewake_domain_id id) { BUILD_BUG_ON((sizeof(forcewake_domain_names)/sizeof(const char *)) != FW_DOMAIN_ID_COUNT); if (id >= 0 && id < FW_DOMAIN_ID_COUNT) return forcewake_domain_names[id]; WARN_ON(id); return "unknown"; } static void assert_device_not_suspended(struct drm_i915_private *dev_priv) { WARN_ONCE(HAS_RUNTIME_PM(dev_priv->dev) && dev_priv->pm.suspended, "Device suspended\n"); } static inline void fw_domain_reset(const struct intel_uncore_forcewake_domain *d) { WARN_ON(d->reg_set == 0); __raw_i915_write32(d->i915, d->reg_set, d->val_reset); } static inline void fw_domain_arm_timer(struct intel_uncore_forcewake_domain *d) { mod_timer_pinned(&d->timer, jiffies + 1); } static inline void fw_domain_wait_ack_clear(const struct intel_uncore_forcewake_domain *d) { if (wait_for_atomic((__raw_i915_read32(d->i915, d->reg_ack) & FORCEWAKE_KERNEL) == 0, FORCEWAKE_ACK_TIMEOUT_MS)) DRM_ERROR("%s: timed out waiting for forcewake ack to clear.\n", intel_uncore_forcewake_domain_to_str(d->id)); } static inline void fw_domain_get(const struct intel_uncore_forcewake_domain *d) { __raw_i915_write32(d->i915, d->reg_set, d->val_set); } static inline void fw_domain_wait_ack(const struct intel_uncore_forcewake_domain *d) { if (wait_for_atomic((__raw_i915_read32(d->i915, d->reg_ack) & FORCEWAKE_KERNEL), FORCEWAKE_ACK_TIMEOUT_MS)) DRM_ERROR("%s: timed out waiting for forcewake ack request.\n", intel_uncore_forcewake_domain_to_str(d->id)); } static inline void fw_domain_put(const struct intel_uncore_forcewake_domain *d) { __raw_i915_write32(d->i915, d->reg_set, d->val_clear); } static inline void fw_domain_posting_read(const struct intel_uncore_forcewake_domain *d) { /* something from same cacheline, but not from the set register */ if (d->reg_post) __raw_posting_read(d->i915, d->reg_post); } static void fw_domains_get(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { struct intel_uncore_forcewake_domain *d; enum forcewake_domain_id id; for_each_fw_domain_mask(d, fw_domains, dev_priv, id) { fw_domain_wait_ack_clear(d); fw_domain_get(d); fw_domain_wait_ack(d); } } static void fw_domains_put(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { struct intel_uncore_forcewake_domain *d; enum forcewake_domain_id id; for_each_fw_domain_mask(d, fw_domains, dev_priv, id) { fw_domain_put(d); fw_domain_posting_read(d); } } static void fw_domains_posting_read(struct drm_i915_private *dev_priv) { struct intel_uncore_forcewake_domain *d; enum forcewake_domain_id id; /* No need to do for all, just do for first found */ for_each_fw_domain(d, dev_priv, id) { fw_domain_posting_read(d); break; } } static void fw_domains_reset(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { struct intel_uncore_forcewake_domain *d; enum forcewake_domain_id id; if (dev_priv->uncore.fw_domains == 0) return; for_each_fw_domain_mask(d, fw_domains, dev_priv, id) fw_domain_reset(d); fw_domains_posting_read(dev_priv); } static void __gen6_gt_wait_for_thread_c0(struct drm_i915_private *dev_priv) { /* w/a for a sporadic read returning 0 by waiting for the GT * thread to wake up. */ if (wait_for_atomic_us((__raw_i915_read32(dev_priv, GEN6_GT_THREAD_STATUS_REG) & GEN6_GT_THREAD_STATUS_CORE_MASK) == 0, 500)) DRM_ERROR("GT thread status wait timed out\n"); } static void fw_domains_get_with_thread_status(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { fw_domains_get(dev_priv, fw_domains); /* WaRsForcewakeWaitTC0:snb,ivb,hsw,bdw,vlv */ __gen6_gt_wait_for_thread_c0(dev_priv); } static void gen6_gt_check_fifodbg(struct drm_i915_private *dev_priv) { u32 gtfifodbg; gtfifodbg = __raw_i915_read32(dev_priv, GTFIFODBG); if (WARN(gtfifodbg, "GT wake FIFO error 0x%x\n", gtfifodbg)) __raw_i915_write32(dev_priv, GTFIFODBG, gtfifodbg); } static void fw_domains_put_with_fifo(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { fw_domains_put(dev_priv, fw_domains); gen6_gt_check_fifodbg(dev_priv); } static inline u32 fifo_free_entries(struct drm_i915_private *dev_priv) { u32 count = __raw_i915_read32(dev_priv, GTFIFOCTL); return count & GT_FIFO_FREE_ENTRIES_MASK; } static int __gen6_gt_wait_for_fifo(struct drm_i915_private *dev_priv) { int ret = 0; /* On VLV, FIFO will be shared by both SW and HW. * So, we need to read the FREE_ENTRIES everytime */ if (IS_VALLEYVIEW(dev_priv->dev)) dev_priv->uncore.fifo_count = fifo_free_entries(dev_priv); if (dev_priv->uncore.fifo_count < GT_FIFO_NUM_RESERVED_ENTRIES) { int loop = 500; u32 fifo = fifo_free_entries(dev_priv); while (fifo <= GT_FIFO_NUM_RESERVED_ENTRIES && loop--) { udelay(10); fifo = fifo_free_entries(dev_priv); } if (WARN_ON(loop < 0 && fifo <= GT_FIFO_NUM_RESERVED_ENTRIES)) ++ret; dev_priv->uncore.fifo_count = fifo; } dev_priv->uncore.fifo_count--; return ret; } static void intel_uncore_fw_release_timer(unsigned long arg) { struct intel_uncore_forcewake_domain *domain = (void *)arg; unsigned long irqflags; assert_device_not_suspended(domain->i915); spin_lock_irqsave(&domain->i915->uncore.lock, irqflags); if (WARN_ON(domain->wake_count == 0)) domain->wake_count++; if (--domain->wake_count == 0) domain->i915->uncore.funcs.force_wake_put(domain->i915, 1 << domain->id); spin_unlock_irqrestore(&domain->i915->uncore.lock, irqflags); } void intel_uncore_forcewake_reset(struct drm_device *dev, bool restore) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long irqflags; struct intel_uncore_forcewake_domain *domain; int retry_count = 100; enum forcewake_domain_id id; enum forcewake_domains fw = 0, active_domains; /* Hold uncore.lock across reset to prevent any register access * with forcewake not set correctly. Wait until all pending * timers are run before holding. */ while (1) { active_domains = 0; for_each_fw_domain(domain, dev_priv, id) { if (del_timer_sync(&domain->timer) == 0) continue; intel_uncore_fw_release_timer((unsigned long)domain); } spin_lock_irqsave(&dev_priv->uncore.lock, irqflags); for_each_fw_domain(domain, dev_priv, id) { if (timer_pending(&domain->timer)) active_domains |= (1 << id); } if (active_domains == 0) break; if (--retry_count == 0) { DRM_ERROR("Timed out waiting for forcewake timers to finish\n"); break; } spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags); cond_resched(); } WARN_ON(active_domains); for_each_fw_domain(domain, dev_priv, id) if (domain->wake_count) fw |= 1 << id; if (fw) dev_priv->uncore.funcs.force_wake_put(dev_priv, fw); fw_domains_reset(dev_priv, FORCEWAKE_ALL); if (restore) { /* If reset with a user forcewake, try to restore */ if (fw) dev_priv->uncore.funcs.force_wake_get(dev_priv, fw); if (IS_GEN6(dev) || IS_GEN7(dev)) dev_priv->uncore.fifo_count = fifo_free_entries(dev_priv); } if (!restore) assert_forcewakes_inactive(dev_priv); spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags); } static void intel_uncore_ellc_detect(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; if ((IS_HASWELL(dev) || IS_BROADWELL(dev) || INTEL_INFO(dev)->gen >= 9) && (__raw_i915_read32(dev_priv, HSW_EDRAM_PRESENT) & EDRAM_ENABLED)) { /* The docs do not explain exactly how the calculation can be * made. It is somewhat guessable, but for now, it's always * 128MB. * NB: We can't write IDICR yet because we do not have gt funcs * set up */ dev_priv->ellc_size = 128; DRM_INFO("Found %zuMB of eLLC\n", dev_priv->ellc_size); } } static void __intel_uncore_early_sanitize(struct drm_device *dev, bool restore_forcewake) { struct drm_i915_private *dev_priv = dev->dev_private; if (HAS_FPGA_DBG_UNCLAIMED(dev)) __raw_i915_write32(dev_priv, FPGA_DBG, FPGA_DBG_RM_NOCLAIM); /* clear out old GT FIFO errors */ if (IS_GEN6(dev) || IS_GEN7(dev)) __raw_i915_write32(dev_priv, GTFIFODBG, __raw_i915_read32(dev_priv, GTFIFODBG)); intel_uncore_forcewake_reset(dev, restore_forcewake); } void intel_uncore_early_sanitize(struct drm_device *dev, bool restore_forcewake) { __intel_uncore_early_sanitize(dev, restore_forcewake); i915_check_and_clear_faults(dev); } void intel_uncore_sanitize(struct drm_device *dev) { /* BIOS often leaves RC6 enabled, but disable it for hw init */ intel_disable_gt_powersave(dev); } /** * intel_uncore_forcewake_get - grab forcewake domain references * @dev_priv: i915 device instance * @fw_domains: forcewake domains to get reference on * * This function can be used get GT's forcewake domain references. * Normal register access will handle the forcewake domains automatically. * However if some sequence requires the GT to not power down a particular * forcewake domains this function should be called at the beginning of the * sequence. And subsequently the reference should be dropped by symmetric * call to intel_unforce_forcewake_put(). Usually caller wants all the domains * to be kept awake so the @fw_domains would be then FORCEWAKE_ALL. */ void intel_uncore_forcewake_get(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { unsigned long irqflags; struct intel_uncore_forcewake_domain *domain; enum forcewake_domain_id id; if (!dev_priv->uncore.funcs.force_wake_get) return; WARN_ON(dev_priv->pm.suspended); fw_domains &= dev_priv->uncore.fw_domains; spin_lock_irqsave(&dev_priv->uncore.lock, irqflags); for_each_fw_domain_mask(domain, fw_domains, dev_priv, id) { if (domain->wake_count++) fw_domains &= ~(1 << id); } if (fw_domains) dev_priv->uncore.funcs.force_wake_get(dev_priv, fw_domains); spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags); } /** * intel_uncore_forcewake_put - release a forcewake domain reference * @dev_priv: i915 device instance * @fw_domains: forcewake domains to put references * * This function drops the device-level forcewakes for specified * domains obtained by intel_uncore_forcewake_get(). */ void intel_uncore_forcewake_put(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { unsigned long irqflags; struct intel_uncore_forcewake_domain *domain; enum forcewake_domain_id id; if (!dev_priv->uncore.funcs.force_wake_put) return; fw_domains &= dev_priv->uncore.fw_domains; spin_lock_irqsave(&dev_priv->uncore.lock, irqflags); for_each_fw_domain_mask(domain, fw_domains, dev_priv, id) { if (WARN_ON(domain->wake_count == 0)) continue; if (--domain->wake_count) continue; domain->wake_count++; fw_domain_arm_timer(domain); } spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags); } void assert_forcewakes_inactive(struct drm_i915_private *dev_priv) { struct intel_uncore_forcewake_domain *domain; enum forcewake_domain_id id; if (!dev_priv->uncore.funcs.force_wake_get) return; for_each_fw_domain(domain, dev_priv, id) WARN_ON(domain->wake_count); } /* We give fast paths for the really cool registers */ #define NEEDS_FORCE_WAKE(dev_priv, reg) \ ((reg) < 0x40000 && (reg) != FORCEWAKE) #define REG_RANGE(reg, start, end) ((reg) >= (start) && (reg) < (end)) #define FORCEWAKE_VLV_RENDER_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x2000, 0x4000) || \ REG_RANGE((reg), 0x5000, 0x8000) || \ REG_RANGE((reg), 0xB000, 0x12000) || \ REG_RANGE((reg), 0x2E000, 0x30000)) #define FORCEWAKE_VLV_MEDIA_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x12000, 0x14000) || \ REG_RANGE((reg), 0x22000, 0x24000) || \ REG_RANGE((reg), 0x30000, 0x40000)) #define FORCEWAKE_CHV_RENDER_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x2000, 0x4000) || \ REG_RANGE((reg), 0x5200, 0x8000) || \ REG_RANGE((reg), 0x8300, 0x8500) || \ REG_RANGE((reg), 0xB000, 0xB480) || \ REG_RANGE((reg), 0xE000, 0xE800)) #define FORCEWAKE_CHV_MEDIA_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x8800, 0x8900) || \ REG_RANGE((reg), 0xD000, 0xD800) || \ REG_RANGE((reg), 0x12000, 0x14000) || \ REG_RANGE((reg), 0x1A000, 0x1C000) || \ REG_RANGE((reg), 0x1E800, 0x1EA00) || \ REG_RANGE((reg), 0x30000, 0x38000)) #define FORCEWAKE_CHV_COMMON_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x4000, 0x5000) || \ REG_RANGE((reg), 0x8000, 0x8300) || \ REG_RANGE((reg), 0x8500, 0x8600) || \ REG_RANGE((reg), 0x9000, 0xB000) || \ REG_RANGE((reg), 0xF000, 0x10000)) #define FORCEWAKE_GEN9_UNCORE_RANGE_OFFSET(reg) \ REG_RANGE((reg), 0xB00, 0x2000) #define FORCEWAKE_GEN9_RENDER_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x2000, 0x2700) || \ REG_RANGE((reg), 0x3000, 0x4000) || \ REG_RANGE((reg), 0x5200, 0x8000) || \ REG_RANGE((reg), 0x8140, 0x8160) || \ REG_RANGE((reg), 0x8300, 0x8500) || \ REG_RANGE((reg), 0x8C00, 0x8D00) || \ REG_RANGE((reg), 0xB000, 0xB480) || \ REG_RANGE((reg), 0xE000, 0xE900) || \ REG_RANGE((reg), 0x24400, 0x24800)) #define FORCEWAKE_GEN9_MEDIA_RANGE_OFFSET(reg) \ (REG_RANGE((reg), 0x8130, 0x8140) || \ REG_RANGE((reg), 0x8800, 0x8A00) || \ REG_RANGE((reg), 0xD000, 0xD800) || \ REG_RANGE((reg), 0x12000, 0x14000) || \ REG_RANGE((reg), 0x1A000, 0x1EA00) || \ REG_RANGE((reg), 0x30000, 0x40000)) #define FORCEWAKE_GEN9_COMMON_RANGE_OFFSET(reg) \ REG_RANGE((reg), 0x9400, 0x9800) #define FORCEWAKE_GEN9_BLITTER_RANGE_OFFSET(reg) \ ((reg) < 0x40000 &&\ !FORCEWAKE_GEN9_UNCORE_RANGE_OFFSET(reg) && \ !FORCEWAKE_GEN9_RENDER_RANGE_OFFSET(reg) && \ !FORCEWAKE_GEN9_MEDIA_RANGE_OFFSET(reg) && \ !FORCEWAKE_GEN9_COMMON_RANGE_OFFSET(reg)) static void ilk_dummy_write(struct drm_i915_private *dev_priv) { /* WaIssueDummyWriteToWakeupFromRC6:ilk Issue a dummy write to wake up * the chip from rc6 before touching it for real. MI_MODE is masked, * hence harmless to write 0 into. */ __raw_i915_write32(dev_priv, MI_MODE, 0); } static void hsw_unclaimed_reg_debug(struct drm_i915_private *dev_priv, u32 reg, bool read, bool before) { const char *op = read ? "reading" : "writing to"; const char *when = before ? "before" : "after"; if (!i915.mmio_debug) return; if (__raw_i915_read32(dev_priv, FPGA_DBG) & FPGA_DBG_RM_NOCLAIM) { WARN(1, "Unclaimed register detected %s %s register 0x%x\n", when, op, reg); __raw_i915_write32(dev_priv, FPGA_DBG, FPGA_DBG_RM_NOCLAIM); i915.mmio_debug--; /* Only report the first N failures */ } } static void hsw_unclaimed_reg_detect(struct drm_i915_private *dev_priv) { static bool mmio_debug_once = true; if (i915.mmio_debug || !mmio_debug_once) return; if (__raw_i915_read32(dev_priv, FPGA_DBG) & FPGA_DBG_RM_NOCLAIM) { DRM_DEBUG("Unclaimed register detected, " "enabling oneshot unclaimed register reporting. " "Please use i915.mmio_debug=N for more information.\n"); __raw_i915_write32(dev_priv, FPGA_DBG, FPGA_DBG_RM_NOCLAIM); i915.mmio_debug = mmio_debug_once--; } } #define GEN2_READ_HEADER(x) \ u##x val = 0; \ assert_device_not_suspended(dev_priv); #define GEN2_READ_FOOTER \ trace_i915_reg_rw(false, reg, val, sizeof(val), trace); \ return val #define __gen2_read(x) \ static u##x \ gen2_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ GEN2_READ_HEADER(x); \ val = __raw_i915_read##x(dev_priv, reg); \ GEN2_READ_FOOTER; \ } #define __gen5_read(x) \ static u##x \ gen5_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ GEN2_READ_HEADER(x); \ ilk_dummy_write(dev_priv); \ val = __raw_i915_read##x(dev_priv, reg); \ GEN2_READ_FOOTER; \ } __gen5_read(8) __gen5_read(16) __gen5_read(32) __gen5_read(64) __gen2_read(8) __gen2_read(16) __gen2_read(32) __gen2_read(64) #undef __gen5_read #undef __gen2_read #undef GEN2_READ_FOOTER #undef GEN2_READ_HEADER #define GEN6_READ_HEADER(x) \ unsigned long irqflags; \ u##x val = 0; \ assert_device_not_suspended(dev_priv); \ spin_lock_irqsave(&dev_priv->uncore.lock, irqflags) #define GEN6_READ_FOOTER \ spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags); \ trace_i915_reg_rw(false, reg, val, sizeof(val), trace); \ return val static inline void __force_wake_get(struct drm_i915_private *dev_priv, enum forcewake_domains fw_domains) { struct intel_uncore_forcewake_domain *domain; enum forcewake_domain_id id; if (WARN_ON(!fw_domains)) return; /* Ideally GCC would be constant-fold and eliminate this loop */ for_each_fw_domain_mask(domain, fw_domains, dev_priv, id) { if (domain->wake_count) { fw_domains &= ~(1 << id); continue; } domain->wake_count++; fw_domain_arm_timer(domain); } if (fw_domains) dev_priv->uncore.funcs.force_wake_get(dev_priv, fw_domains); } #define __vgpu_read(x) \ static u##x \ vgpu_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ GEN6_READ_HEADER(x); \ val = __raw_i915_read##x(dev_priv, reg); \ GEN6_READ_FOOTER; \ } #define __gen6_read(x) \ static u##x \ gen6_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ GEN6_READ_HEADER(x); \ hsw_unclaimed_reg_debug(dev_priv, reg, true, true); \ if (NEEDS_FORCE_WAKE((dev_priv), (reg))) \ __force_wake_get(dev_priv, FORCEWAKE_RENDER); \ val = __raw_i915_read##x(dev_priv, reg); \ hsw_unclaimed_reg_debug(dev_priv, reg, true, false); \ GEN6_READ_FOOTER; \ } #define __vlv_read(x) \ static u##x \ vlv_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ GEN6_READ_HEADER(x); \ if (FORCEWAKE_VLV_RENDER_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_RENDER); \ else if (FORCEWAKE_VLV_MEDIA_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_MEDIA); \ val = __raw_i915_read##x(dev_priv, reg); \ GEN6_READ_FOOTER; \ } #define __chv_read(x) \ static u##x \ chv_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ GEN6_READ_HEADER(x); \ if (FORCEWAKE_CHV_RENDER_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_RENDER); \ else if (FORCEWAKE_CHV_MEDIA_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_MEDIA); \ else if (FORCEWAKE_CHV_COMMON_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, \ FORCEWAKE_RENDER | FORCEWAKE_MEDIA); \ val = __raw_i915_read##x(dev_priv, reg); \ GEN6_READ_FOOTER; \ } #define SKL_NEEDS_FORCE_WAKE(dev_priv, reg) \ ((reg) < 0x40000 && !FORCEWAKE_GEN9_UNCORE_RANGE_OFFSET(reg)) #define __gen9_read(x) \ static u##x \ gen9_read##x(struct drm_i915_private *dev_priv, off_t reg, bool trace) { \ enum forcewake_domains fw_engine; \ GEN6_READ_HEADER(x); \ if (!SKL_NEEDS_FORCE_WAKE((dev_priv), (reg))) \ fw_engine = 0; \ else if (FORCEWAKE_GEN9_RENDER_RANGE_OFFSET(reg)) \ fw_engine = FORCEWAKE_RENDER; \ else if (FORCEWAKE_GEN9_MEDIA_RANGE_OFFSET(reg)) \ fw_engine = FORCEWAKE_MEDIA; \ else if (FORCEWAKE_GEN9_COMMON_RANGE_OFFSET(reg)) \ fw_engine = FORCEWAKE_RENDER | FORCEWAKE_MEDIA; \ else \ fw_engine = FORCEWAKE_BLITTER; \ if (fw_engine) \ __force_wake_get(dev_priv, fw_engine); \ val = __raw_i915_read##x(dev_priv, reg); \ GEN6_READ_FOOTER; \ } __vgpu_read(8) __vgpu_read(16) __vgpu_read(32) __vgpu_read(64) __gen9_read(8) __gen9_read(16) __gen9_read(32) __gen9_read(64) __chv_read(8) __chv_read(16) __chv_read(32) __chv_read(64) __vlv_read(8) __vlv_read(16) __vlv_read(32) __vlv_read(64) __gen6_read(8) __gen6_read(16) __gen6_read(32) __gen6_read(64) #undef __gen9_read #undef __chv_read #undef __vlv_read #undef __gen6_read #undef __vgpu_read #undef GEN6_READ_FOOTER #undef GEN6_READ_HEADER #define GEN2_WRITE_HEADER \ trace_i915_reg_rw(true, reg, val, sizeof(val), trace); \ assert_device_not_suspended(dev_priv); \ #define GEN2_WRITE_FOOTER #define __gen2_write(x) \ static void \ gen2_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, bool trace) { \ GEN2_WRITE_HEADER; \ __raw_i915_write##x(dev_priv, reg, val); \ GEN2_WRITE_FOOTER; \ } #define __gen5_write(x) \ static void \ gen5_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, bool trace) { \ GEN2_WRITE_HEADER; \ ilk_dummy_write(dev_priv); \ __raw_i915_write##x(dev_priv, reg, val); \ GEN2_WRITE_FOOTER; \ } __gen5_write(8) __gen5_write(16) __gen5_write(32) __gen5_write(64) __gen2_write(8) __gen2_write(16) __gen2_write(32) __gen2_write(64) #undef __gen5_write #undef __gen2_write #undef GEN2_WRITE_FOOTER #undef GEN2_WRITE_HEADER #define GEN6_WRITE_HEADER \ unsigned long irqflags; \ trace_i915_reg_rw(true, reg, val, sizeof(val), trace); \ assert_device_not_suspended(dev_priv); \ spin_lock_irqsave(&dev_priv->uncore.lock, irqflags) #define GEN6_WRITE_FOOTER \ spin_unlock_irqrestore(&dev_priv->uncore.lock, irqflags) #define __gen6_write(x) \ static void \ gen6_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, bool trace) { \ u32 __fifo_ret = 0; \ GEN6_WRITE_HEADER; \ if (NEEDS_FORCE_WAKE((dev_priv), (reg))) { \ __fifo_ret = __gen6_gt_wait_for_fifo(dev_priv); \ } \ __raw_i915_write##x(dev_priv, reg, val); \ if (unlikely(__fifo_ret)) { \ gen6_gt_check_fifodbg(dev_priv); \ } \ GEN6_WRITE_FOOTER; \ } #define __hsw_write(x) \ static void \ hsw_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, bool trace) { \ u32 __fifo_ret = 0; \ GEN6_WRITE_HEADER; \ if (NEEDS_FORCE_WAKE((dev_priv), (reg))) { \ __fifo_ret = __gen6_gt_wait_for_fifo(dev_priv); \ } \ hsw_unclaimed_reg_debug(dev_priv, reg, false, true); \ __raw_i915_write##x(dev_priv, reg, val); \ if (unlikely(__fifo_ret)) { \ gen6_gt_check_fifodbg(dev_priv); \ } \ hsw_unclaimed_reg_debug(dev_priv, reg, false, false); \ hsw_unclaimed_reg_detect(dev_priv); \ GEN6_WRITE_FOOTER; \ } #define __vgpu_write(x) \ static void vgpu_write##x(struct drm_i915_private *dev_priv, \ off_t reg, u##x val, bool trace) { \ GEN6_WRITE_HEADER; \ __raw_i915_write##x(dev_priv, reg, val); \ GEN6_WRITE_FOOTER; \ } static const u32 gen8_shadowed_regs[] = { FORCEWAKE_MT, GEN6_RPNSWREQ, GEN6_RC_VIDEO_FREQ, RING_TAIL(RENDER_RING_BASE), RING_TAIL(GEN6_BSD_RING_BASE), RING_TAIL(VEBOX_RING_BASE), RING_TAIL(BLT_RING_BASE), /* TODO: Other registers are not yet used */ }; static bool is_gen8_shadowed(struct drm_i915_private *dev_priv, u32 reg) { int i; for (i = 0; i < ARRAY_SIZE(gen8_shadowed_regs); i++) if (reg == gen8_shadowed_regs[i]) return true; return false; } #define __gen8_write(x) \ static void \ gen8_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, bool trace) { \ GEN6_WRITE_HEADER; \ hsw_unclaimed_reg_debug(dev_priv, reg, false, true); \ if (reg < 0x40000 && !is_gen8_shadowed(dev_priv, reg)) \ __force_wake_get(dev_priv, FORCEWAKE_RENDER); \ __raw_i915_write##x(dev_priv, reg, val); \ hsw_unclaimed_reg_debug(dev_priv, reg, false, false); \ hsw_unclaimed_reg_detect(dev_priv); \ GEN6_WRITE_FOOTER; \ } #define __chv_write(x) \ static void \ chv_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, bool trace) { \ bool shadowed = is_gen8_shadowed(dev_priv, reg); \ GEN6_WRITE_HEADER; \ if (!shadowed) { \ if (FORCEWAKE_CHV_RENDER_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_RENDER); \ else if (FORCEWAKE_CHV_MEDIA_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_MEDIA); \ else if (FORCEWAKE_CHV_COMMON_RANGE_OFFSET(reg)) \ __force_wake_get(dev_priv, FORCEWAKE_RENDER | FORCEWAKE_MEDIA); \ } \ __raw_i915_write##x(dev_priv, reg, val); \ GEN6_WRITE_FOOTER; \ } static const u32 gen9_shadowed_regs[] = { RING_TAIL(RENDER_RING_BASE), RING_TAIL(GEN6_BSD_RING_BASE), RING_TAIL(VEBOX_RING_BASE), RING_TAIL(BLT_RING_BASE), FORCEWAKE_BLITTER_GEN9, FORCEWAKE_RENDER_GEN9, FORCEWAKE_MEDIA_GEN9, GEN6_RPNSWREQ, GEN6_RC_VIDEO_FREQ, /* TODO: Other registers are not yet used */ }; static bool is_gen9_shadowed(struct drm_i915_private *dev_priv, u32 reg) { int i; for (i = 0; i < ARRAY_SIZE(gen9_shadowed_regs); i++) if (reg == gen9_shadowed_regs[i]) return true; return false; } #define __gen9_write(x) \ static void \ gen9_write##x(struct drm_i915_private *dev_priv, off_t reg, u##x val, \ bool trace) { \ enum forcewake_domains fw_engine; \ GEN6_WRITE_HEADER; \ if (!SKL_NEEDS_FORCE_WAKE((dev_priv), (reg)) || \ is_gen9_shadowed(dev_priv, reg)) \ fw_engine = 0; \ else if (FORCEWAKE_GEN9_RENDER_RANGE_OFFSET(reg)) \ fw_engine = FORCEWAKE_RENDER; \ else if (FORCEWAKE_GEN9_MEDIA_RANGE_OFFSET(reg)) \ fw_engine = FORCEWAKE_MEDIA; \ else if (FORCEWAKE_GEN9_COMMON_RANGE_OFFSET(reg)) \ fw_engine = FORCEWAKE_RENDER | FORCEWAKE_MEDIA; \ else \ fw_engine = FORCEWAKE_BLITTER; \ if (fw_engine) \ __force_wake_get(dev_priv, fw_engine); \ __raw_i915_write##x(dev_priv, reg, val); \ GEN6_WRITE_FOOTER; \ } __gen9_write(8) __gen9_write(16) __gen9_write(32) __gen9_write(64) __chv_write(8) __chv_write(16) __chv_write(32) __chv_write(64) __gen8_write(8) __gen8_write(16) __gen8_write(32) __gen8_write(64) __hsw_write(8) __hsw_write(16) __hsw_write(32) __hsw_write(64) __gen6_write(8) __gen6_write(16) __gen6_write(32) __gen6_write(64) __vgpu_write(8) __vgpu_write(16) __vgpu_write(32) __vgpu_write(64) #undef __gen9_write #undef __chv_write #undef __gen8_write #undef __hsw_write #undef __gen6_write #undef __vgpu_write #undef GEN6_WRITE_FOOTER #undef GEN6_WRITE_HEADER #define ASSIGN_WRITE_MMIO_VFUNCS(x) \ do { \ dev_priv->uncore.funcs.mmio_writeb = x##_write8; \ dev_priv->uncore.funcs.mmio_writew = x##_write16; \ dev_priv->uncore.funcs.mmio_writel = x##_write32; \ dev_priv->uncore.funcs.mmio_writeq = x##_write64; \ } while (0) #define ASSIGN_READ_MMIO_VFUNCS(x) \ do { \ dev_priv->uncore.funcs.mmio_readb = x##_read8; \ dev_priv->uncore.funcs.mmio_readw = x##_read16; \ dev_priv->uncore.funcs.mmio_readl = x##_read32; \ dev_priv->uncore.funcs.mmio_readq = x##_read64; \ } while (0) static void fw_domain_init(struct drm_i915_private *dev_priv, enum forcewake_domain_id domain_id, u32 reg_set, u32 reg_ack) { struct intel_uncore_forcewake_domain *d; if (WARN_ON(domain_id >= FW_DOMAIN_ID_COUNT)) return; d = &dev_priv->uncore.fw_domain[domain_id]; WARN_ON(d->wake_count); d->wake_count = 0; d->reg_set = reg_set; d->reg_ack = reg_ack; if (IS_GEN6(dev_priv)) { d->val_reset = 0; d->val_set = FORCEWAKE_KERNEL; d->val_clear = 0; } else { /* WaRsClearFWBitsAtReset:bdw,skl */ d->val_reset = _MASKED_BIT_DISABLE(0xffff); d->val_set = _MASKED_BIT_ENABLE(FORCEWAKE_KERNEL); d->val_clear = _MASKED_BIT_DISABLE(FORCEWAKE_KERNEL); } if (IS_VALLEYVIEW(dev_priv)) d->reg_post = FORCEWAKE_ACK_VLV; else if (IS_GEN6(dev_priv) || IS_GEN7(dev_priv) || IS_GEN8(dev_priv)) d->reg_post = ECOBUS; else d->reg_post = 0; d->i915 = dev_priv; d->id = domain_id; setup_timer(&d->timer, intel_uncore_fw_release_timer, (unsigned long)d); dev_priv->uncore.fw_domains |= (1 << domain_id); fw_domain_reset(d); } static void intel_uncore_fw_domains_init(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; if (INTEL_INFO(dev_priv->dev)->gen <= 5) return; if (IS_GEN9(dev)) { dev_priv->uncore.funcs.force_wake_get = fw_domains_get; dev_priv->uncore.funcs.force_wake_put = fw_domains_put; fw_domain_init(dev_priv, FW_DOMAIN_ID_RENDER, FORCEWAKE_RENDER_GEN9, FORCEWAKE_ACK_RENDER_GEN9); fw_domain_init(dev_priv, FW_DOMAIN_ID_BLITTER, FORCEWAKE_BLITTER_GEN9, FORCEWAKE_ACK_BLITTER_GEN9); fw_domain_init(dev_priv, FW_DOMAIN_ID_MEDIA, FORCEWAKE_MEDIA_GEN9, FORCEWAKE_ACK_MEDIA_GEN9); } else if (IS_VALLEYVIEW(dev)) { dev_priv->uncore.funcs.force_wake_get = fw_domains_get; if (!IS_CHERRYVIEW(dev)) dev_priv->uncore.funcs.force_wake_put = fw_domains_put_with_fifo; else dev_priv->uncore.funcs.force_wake_put = fw_domains_put; fw_domain_init(dev_priv, FW_DOMAIN_ID_RENDER, FORCEWAKE_VLV, FORCEWAKE_ACK_VLV); fw_domain_init(dev_priv, FW_DOMAIN_ID_MEDIA, FORCEWAKE_MEDIA_VLV, FORCEWAKE_ACK_MEDIA_VLV); } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) { dev_priv->uncore.funcs.force_wake_get = fw_domains_get_with_thread_status; dev_priv->uncore.funcs.force_wake_put = fw_domains_put; fw_domain_init(dev_priv, FW_DOMAIN_ID_RENDER, FORCEWAKE_MT, FORCEWAKE_ACK_HSW); } else if (IS_IVYBRIDGE(dev)) { u32 ecobus; /* IVB configs may use multi-threaded forcewake */ /* A small trick here - if the bios hasn't configured * MT forcewake, and if the device is in RC6, then * force_wake_mt_get will not wake the device and the * ECOBUS read will return zero. Which will be * (correctly) interpreted by the test below as MT * forcewake being disabled. */ dev_priv->uncore.funcs.force_wake_get = fw_domains_get_with_thread_status; dev_priv->uncore.funcs.force_wake_put = fw_domains_put_with_fifo; /* We need to init first for ECOBUS access and then * determine later if we want to reinit, in case of MT access is * not working. In this stage we don't know which flavour this * ivb is, so it is better to reset also the gen6 fw registers * before the ecobus check. */ __raw_i915_write32(dev_priv, FORCEWAKE, 0); __raw_posting_read(dev_priv, ECOBUS); fw_domain_init(dev_priv, FW_DOMAIN_ID_RENDER, FORCEWAKE_MT, FORCEWAKE_MT_ACK); mutex_lock(&dev->struct_mutex); fw_domains_get_with_thread_status(dev_priv, FORCEWAKE_ALL); ecobus = __raw_i915_read32(dev_priv, ECOBUS); fw_domains_put_with_fifo(dev_priv, FORCEWAKE_ALL); mutex_unlock(&dev->struct_mutex); if (!(ecobus & FORCEWAKE_MT_ENABLE)) { DRM_INFO("No MT forcewake available on Ivybridge, this can result in issues\n"); DRM_INFO("when using vblank-synced partial screen updates.\n"); fw_domain_init(dev_priv, FW_DOMAIN_ID_RENDER, FORCEWAKE, FORCEWAKE_ACK); } } else if (IS_GEN6(dev)) { dev_priv->uncore.funcs.force_wake_get = fw_domains_get_with_thread_status; dev_priv->uncore.funcs.force_wake_put = fw_domains_put_with_fifo; fw_domain_init(dev_priv, FW_DOMAIN_ID_RENDER, FORCEWAKE, FORCEWAKE_ACK); } /* All future platforms are expected to require complex power gating */ WARN_ON(dev_priv->uncore.fw_domains == 0); } void intel_uncore_init(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; i915_check_vgpu(dev); intel_uncore_ellc_detect(dev); intel_uncore_fw_domains_init(dev); __intel_uncore_early_sanitize(dev, false); switch (INTEL_INFO(dev)->gen) { default: MISSING_CASE(INTEL_INFO(dev)->gen); return; case 9: ASSIGN_WRITE_MMIO_VFUNCS(gen9); ASSIGN_READ_MMIO_VFUNCS(gen9); break; case 8: if (IS_CHERRYVIEW(dev)) { ASSIGN_WRITE_MMIO_VFUNCS(chv); ASSIGN_READ_MMIO_VFUNCS(chv); } else { ASSIGN_WRITE_MMIO_VFUNCS(gen8); ASSIGN_READ_MMIO_VFUNCS(gen6); } break; case 7: case 6: if (IS_HASWELL(dev)) { ASSIGN_WRITE_MMIO_VFUNCS(hsw); } else { ASSIGN_WRITE_MMIO_VFUNCS(gen6); } if (IS_VALLEYVIEW(dev)) { ASSIGN_READ_MMIO_VFUNCS(vlv); } else { ASSIGN_READ_MMIO_VFUNCS(gen6); } break; case 5: ASSIGN_WRITE_MMIO_VFUNCS(gen5); ASSIGN_READ_MMIO_VFUNCS(gen5); break; case 4: case 3: case 2: ASSIGN_WRITE_MMIO_VFUNCS(gen2); ASSIGN_READ_MMIO_VFUNCS(gen2); break; } if (intel_vgpu_active(dev)) { ASSIGN_WRITE_MMIO_VFUNCS(vgpu); ASSIGN_READ_MMIO_VFUNCS(vgpu); } i915_check_and_clear_faults(dev); } #undef ASSIGN_WRITE_MMIO_VFUNCS #undef ASSIGN_READ_MMIO_VFUNCS void intel_uncore_fini(struct drm_device *dev) { /* Paranoia: make sure we have disabled everything before we exit. */ intel_uncore_sanitize(dev); intel_uncore_forcewake_reset(dev, false); } #define GEN_RANGE(l, h) GENMASK(h, l) static const struct register_whitelist { uint64_t offset; uint32_t size; /* supported gens, 0x10 for 4, 0x30 for 4 and 5, etc. */ uint32_t gen_bitmask; } whitelist[] = { { RING_TIMESTAMP(RENDER_RING_BASE), 8, GEN_RANGE(4, 9) }, }; int i915_reg_read_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_i915_reg_read *reg = data; struct register_whitelist const *entry = whitelist; int i, ret = 0; for (i = 0; i < ARRAY_SIZE(whitelist); i++, entry++) { if (entry->offset == reg->offset && (1 << INTEL_INFO(dev)->gen & entry->gen_bitmask)) break; } if (i == ARRAY_SIZE(whitelist)) return -EINVAL; intel_runtime_pm_get(dev_priv); switch (entry->size) { case 8: reg->val = I915_READ64(reg->offset); break; case 4: reg->val = I915_READ(reg->offset); break; case 2: reg->val = I915_READ16(reg->offset); break; case 1: reg->val = I915_READ8(reg->offset); break; default: MISSING_CASE(entry->size); ret = -EINVAL; goto out; } out: intel_runtime_pm_put(dev_priv); return ret; } int i915_get_reset_stats_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_private *dev_priv = dev->dev_private; struct drm_i915_reset_stats *args = data; struct i915_ctx_hang_stats *hs; struct intel_context *ctx; int ret; if (args->flags || args->pad) return -EINVAL; if (args->ctx_id == DEFAULT_CONTEXT_HANDLE && !capable(CAP_SYS_ADMIN)) return -EPERM; ret = mutex_lock_interruptible(&dev->struct_mutex); if (ret) return ret; ctx = i915_gem_context_get(file->driver_priv, args->ctx_id); if (IS_ERR(ctx)) { mutex_unlock(&dev->struct_mutex); return PTR_ERR(ctx); } hs = &ctx->hang_stats; if (capable(CAP_SYS_ADMIN)) args->reset_count = i915_reset_count(&dev_priv->gpu_error); else args->reset_count = 0; args->batch_active = hs->batch_active; args->batch_pending = hs->batch_pending; mutex_unlock(&dev->struct_mutex); return 0; } static int i915_reset_complete(struct drm_device *dev) { u8 gdrst; pci_read_config_byte(dev->pdev, I915_GDRST, &gdrst); return (gdrst & GRDOM_RESET_STATUS) == 0; } static int i915_do_reset(struct drm_device *dev) { /* assert reset for at least 20 usec */ pci_write_config_byte(dev->pdev, I915_GDRST, GRDOM_RESET_ENABLE); udelay(20); pci_write_config_byte(dev->pdev, I915_GDRST, 0); return wait_for(i915_reset_complete(dev), 500); } static int g4x_reset_complete(struct drm_device *dev) { u8 gdrst; pci_read_config_byte(dev->pdev, I915_GDRST, &gdrst); return (gdrst & GRDOM_RESET_ENABLE) == 0; } static int g33_do_reset(struct drm_device *dev) { pci_write_config_byte(dev->pdev, I915_GDRST, GRDOM_RESET_ENABLE); return wait_for(g4x_reset_complete(dev), 500); } static int g4x_do_reset(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int ret; pci_write_config_byte(dev->pdev, I915_GDRST, GRDOM_RENDER | GRDOM_RESET_ENABLE); ret = wait_for(g4x_reset_complete(dev), 500); if (ret) return ret; /* WaVcpClkGateDisableForMediaReset:ctg,elk */ I915_WRITE(VDECCLK_GATE_D, I915_READ(VDECCLK_GATE_D) | VCP_UNIT_CLOCK_GATE_DISABLE); POSTING_READ(VDECCLK_GATE_D); pci_write_config_byte(dev->pdev, I915_GDRST, GRDOM_MEDIA | GRDOM_RESET_ENABLE); ret = wait_for(g4x_reset_complete(dev), 500); if (ret) return ret; /* WaVcpClkGateDisableForMediaReset:ctg,elk */ I915_WRITE(VDECCLK_GATE_D, I915_READ(VDECCLK_GATE_D) & ~VCP_UNIT_CLOCK_GATE_DISABLE); POSTING_READ(VDECCLK_GATE_D); pci_write_config_byte(dev->pdev, I915_GDRST, 0); return 0; } static int ironlake_do_reset(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int ret; I915_WRITE(MCHBAR_MIRROR_BASE + ILK_GDSR, ILK_GRDOM_RENDER | ILK_GRDOM_RESET_ENABLE); ret = wait_for((I915_READ(MCHBAR_MIRROR_BASE + ILK_GDSR) & ILK_GRDOM_RESET_ENABLE) == 0, 500); if (ret) return ret; I915_WRITE(MCHBAR_MIRROR_BASE + ILK_GDSR, ILK_GRDOM_MEDIA | ILK_GRDOM_RESET_ENABLE); ret = wait_for((I915_READ(MCHBAR_MIRROR_BASE + ILK_GDSR) & ILK_GRDOM_RESET_ENABLE) == 0, 500); if (ret) return ret; I915_WRITE(MCHBAR_MIRROR_BASE + ILK_GDSR, 0); return 0; } static int gen6_do_reset(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int ret; /* Reset the chip */ /* GEN6_GDRST is not in the gt power well, no need to check * for fifo space for the write or forcewake the chip for * the read */ __raw_i915_write32(dev_priv, GEN6_GDRST, GEN6_GRDOM_FULL); /* Spin waiting for the device to ack the reset request */ ret = wait_for((__raw_i915_read32(dev_priv, GEN6_GDRST) & GEN6_GRDOM_FULL) == 0, 500); intel_uncore_forcewake_reset(dev, true); return ret; } int intel_gpu_reset(struct drm_device *dev) { if (INTEL_INFO(dev)->gen >= 6) return gen6_do_reset(dev); else if (IS_GEN5(dev)) return ironlake_do_reset(dev); else if (IS_G4X(dev)) return g4x_do_reset(dev); else if (IS_G33(dev)) return g33_do_reset(dev); else if (INTEL_INFO(dev)->gen >= 3) return i915_do_reset(dev); else return -ENODEV; } void intel_uncore_check_errors(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; if (HAS_FPGA_DBG_UNCLAIMED(dev) && (__raw_i915_read32(dev_priv, FPGA_DBG) & FPGA_DBG_RM_NOCLAIM)) { DRM_ERROR("Unclaimed register before interrupt\n"); __raw_i915_write32(dev_priv, FPGA_DBG, FPGA_DBG_RM_NOCLAIM); } }
gpl-2.0
chancegrissom/qmk_firmware
keyboards/dp60/dp60.h
5454
/** * dp60.h * */ #pragma once #include "quantum.h" // This a shortcut to help you visually see your layout. // The first section contains all of the arguements // The second converts the arguments into a two-dimensional array #define LAYOUT_60_ansi( \ k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k0a, k0b, k0c, k0e, \ k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e, \ k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2e, \ k30, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, \ k40, k42, k43, k47, k48, k49, k4a, k4b \ ) \ { \ {k00, k01, k02, k03, k04, k05, k06, k08, k09, k0a, k0b, k0c, KC_NO, k0e}, \ {k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e}, \ {k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, KC_NO, k2e}, \ {k30, KC_NO, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, KC_NO}, \ {k40, k42, k43, KC_NO, KC_NO, KC_NO, k47, k07, KC_NO, KC_NO, k48, k49, k4a, k4b} \ } #define LAYOUT_60_iso( \ k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k0a, k0b, k0c, k0e, \ k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, \ k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2d, k2e, \ k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c,\ k40, k42, k43, k47, k48, k49, k4a, k4b \ ) \ { \ {k00, k01, k02, k03, k04, k05, k06, k08, k09, k0a, k0b, k0c, KC_NO, k0e}, \ {k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, KC_NO}, \ {k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2d, k2e}, \ {k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, KC_NO}, \ {k40, k42, k43, KC_NO, KC_NO, KC_NO, k47, k07, KC_NO, KC_NO, k48, k49, k4a, k4b} \ } #define LAYOUT_60_wkl( \ k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k0a, k0b, k0c, k0e, \ k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e, \ k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2e, \ k30, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d, \ k40, k42, k43, k47, k49, k4a, k4b \ ) \ { \ {k00, k01, k02, k03, k04, k05, k06, k08, k09, k0a, k0b, k0c, KC_NO, k0e}, \ {k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e}, \ {k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, KC_NO, k2e}, \ {k30, KC_NO, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d}, \ {k40, k42, k43, KC_NO, KC_NO, KC_NO, k47, k07, KC_NO, KC_NO, KC_NO, k49, k4a, k4b} \ } #define LAYOUT_60_hhkb( \ k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k0a, k0b, k0c, k0d, k0e, \ k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e, \ k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2e, \ k30, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d, \ k42, k43, k47, k49, k4a \ ) \ { \ {k00, k01, k02, k03, k04, k05, k06, k08, k09, k0a, k0b, k0c, k0d, k0e}, \ {k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e}, \ {k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, KC_NO, k2e}, \ {k30, KC_NO, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d}, \ {KC_NO, k42, k43, KC_NO, KC_NO, KC_NO, k47, k07, KC_NO, KC_NO, KC_NO, k49, k4a, KC_NO} \ } #define LAYOUT_60_wkl_split_bs( \ k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k0a, k0b, k0c, k0d, k0e, \ k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e, \ k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2e, \ k30, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d, \ k40, k42, k43, k47, k49, k4a, k4b \ ) \ { \ {k00, k01, k02, k03, k04, k05, k06, k08, k09, k0a, k0b, k0c, k0d, k0e}, \ {k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e}, \ {k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, KC_NO, k2e}, \ {k30, KC_NO, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d}, \ {k40, k42, k43, KC_NO, KC_NO, KC_NO, k47, k07, KC_NO, KC_NO, KC_NO, k49, k4a, k4b} \ } #define LAYOUT_60_ansi_split_bs_rshift( \ k00, k01, k02, k03, k04, k05, k06, k07, k08, k09, k0a, k0b, k0c, k0d, k0e, \ k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e, \ k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, k2e, \ k30, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d, \ k40, k42, k43, k47, k48, k49, k4a, k4b \ ) \ { \ {k00, k01, k02, k03, k04, k05, k06, k08, k09, k0a, k0b, k0c, k0d, k0e}, \ {k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k1a, k1b, k1c, k1e}, \ {k20, k22, k23, k24, k25, k26, k27, k28, k29, k2a, k2b, k2c, KC_NO, k2e}, \ {k30, KC_NO, k32, k33, k34, k35, k36, k37, k38, k39, k3a, k3b, k3c, k3d}, \ {k40, k42, k43, KC_NO, KC_NO, KC_NO, k47, k07, KC_NO, KC_NO, k48, k49, k4a, k4b} \ }
gpl-2.0
drupaals/demo.com
d8/core/modules/config/src/Tests/ConfigModuleOverridesTest.php
2710
<?php /** * @file * Definition of Drupal\config\Tests\ConfigModuleOverridesTest. */ namespace Drupal\config\Tests; use Drupal\simpletest\DrupalUnitTestBase; /** * Tests module overrides of configuration using event subscribers. */ class ConfigModuleOverridesTest extends DrupalUnitTestBase { public static $modules = array('system', 'config', 'config_override'); public static function getInfo() { return array( 'name' => 'Module overrides', 'description' => 'Tests that modules can override configuration with event subscribers.', 'group' => 'Configuration', ); } public function testSimpleModuleOverrides() { $GLOBALS['config_test_run_module_overrides'] = TRUE; $name = 'system.site'; $overridden_name = 'ZOMG overridden site name'; $non_overridden_name = 'ZOMG this name is on disk mkay'; $overridden_slogan = 'Yay for overrides!'; $non_overridden_slogan = 'Yay for defaults!'; $config_factory = $this->container->get('config.factory'); $config_factory ->get($name) ->set('name', $non_overridden_name) ->set('slogan', $non_overridden_slogan) ->save(); $this->assertTrue($config_factory->getOverrideState(), 'By default ConfigFactory has overrides enabled.'); $old_state = $config_factory->getOverrideState(); $config_factory->setOverrideState(FALSE); $this->assertFalse($config_factory->getOverrideState(), 'ConfigFactory can disable overrides.'); $this->assertEqual($non_overridden_name, $config_factory->get('system.site')->get('name')); $this->assertEqual($non_overridden_slogan, $config_factory->get('system.site')->get('slogan')); $config_factory->setOverrideState(TRUE); $this->assertTrue($config_factory->getOverrideState(), 'ConfigFactory can enable overrides.'); $this->assertEqual($overridden_name, $config_factory->get('system.site')->get('name')); $this->assertEqual($overridden_slogan, $config_factory->get('system.site')->get('slogan')); // Test overrides of completely new configuration objects. In normal runtime // this should only happen for configuration entities as we should not be // creating simple configuration objects on the fly. $config = $config_factory->get('config_override.new'); $this->assertTrue($config->isNew(), 'The configuration object config_override.new is new'); $this->assertIdentical($config->get('module'), 'override'); $config_factory->setOverrideState(FALSE); $config = \Drupal::config('config_override.new'); $this->assertIdentical($config->get('module'), NULL); $config_factory->setOverrideState($old_state); unset($GLOBALS['config_test_run_module_overrides']); } }
gpl-2.0
laijs/linux-kernel-ancient-history
drivers/media/video/cx88/Makefile
410
cx88xx-objs := cx88-cards.o cx88-core.o cx88-i2c.o cx88-tvaudio.o \ cx88-input.o cx8800-objs := cx88-video.o cx88-vbi.o cx8802-objs := cx88-mpeg.o obj-$(CONFIG_VIDEO_CX88) += cx88xx.o cx8800.o cx8802.o cx88-blackbird.o obj-$(CONFIG_VIDEO_CX88_DVB) += cx88-dvb.o EXTRA_CFLAGS += -I$(src)/.. EXTRA_CFLAGS += -I$(srctree)/drivers/media/dvb/dvb-core EXTRA_CFLAGS += -I$(srctree)/drivers/media/dvb/frontends
gpl-2.0
gwq5210/litlib
thirdparty/sources/boost_1_60_0/libs/fusion/doc/html/fusion/adapted/adapt_tpl_adt.html
19325
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>BOOST_FUSION_ADAPT_TPL_ADT</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Fusion 2.2"> <link rel="up" href="../adapted.html" title="Adapted"> <link rel="prev" href="adapt_adt.html" title="BOOST_FUSION_ADAPT_ADT"> <link rel="next" href="adapt_assoc_adt.html" title="BOOST_FUSION_ADAPT_ASSOC_ADT"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="adapt_adt.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../adapted.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="adapt_assoc_adt.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="fusion.adapted.adapt_tpl_adt"></a><a class="link" href="adapt_tpl_adt.html" title="BOOST_FUSION_ADAPT_TPL_ADT">BOOST_FUSION_ADAPT_TPL_ADT</a> </h3></div></div></div> <p> BOOST_FUSION_ADAPT_TPL_ADT is a macro than can be used to generate all the necessary boilerplate to adapt an arbitrary template class type as a model of <a class="link" href="../sequence/concepts/random_access_sequence.html" title="Random Access Sequence">Random Access Sequence</a>. </p> <h5> <a name="fusion.adapted.adapt_tpl_adt.h0"></a> <span class="phrase"><a name="fusion.adapted.adapt_tpl_adt.synopsis"></a></span><a class="link" href="adapt_tpl_adt.html#fusion.adapted.adapt_tpl_adt.synopsis">Synopsis</a> </h5> <pre class="programlisting"><span class="identifier">BOOST_FUSION_ADAPT_TPL_ADT</span><span class="special">(</span> <span class="special">(</span><span class="identifier">template_param0</span><span class="special">)(</span><span class="identifier">template_param1</span><span class="special">)...,</span> <span class="special">(</span><span class="identifier">type_name</span><span class="special">)</span> <span class="special">(</span><span class="identifier">specialization_param0</span><span class="special">)(</span><span class="identifier">specialization_param1</span><span class="special">)...,</span> <span class="special">([</span><span class="identifier">attribute_type0</span><span class="special">,</span> <span class="identifier">attribute_const_type0</span><span class="special">,]</span> <span class="identifier">get_expr0</span><span class="special">,</span> <span class="identifier">set_expr0</span><span class="special">)</span> <span class="special">([</span><span class="identifier">attribute_type1</span><span class="special">,</span> <span class="identifier">attribute_const_type1</span><span class="special">,]</span> <span class="identifier">get_expr1</span><span class="special">,</span> <span class="identifier">set_expr1</span><span class="special">)</span> <span class="special">...</span> <span class="special">)</span> </pre> <h5> <a name="fusion.adapted.adapt_tpl_adt.h1"></a> <span class="phrase"><a name="fusion.adapted.adapt_tpl_adt.expression_semantics"></a></span><a class="link" href="adapt_tpl_adt.html#fusion.adapted.adapt_tpl_adt.expression_semantics">Expression Semantics</a> </h5> <p> The above macro generates the necessary code to adapt <code class="computeroutput"><span class="identifier">type_name</span></code> or an arbitrary specialization of <code class="computeroutput"><span class="identifier">type_name</span></code> as a model of <a class="link" href="../sequence/concepts/random_access_sequence.html" title="Random Access Sequence">Random Access Sequence</a>. The sequence <code class="computeroutput"><span class="special">(</span><span class="identifier">template_param0</span><span class="special">)(</span><span class="identifier">template_param1</span><span class="special">)...</span></code> declares the names of the template type parameters used. The sequence <code class="computeroutput"><span class="special">(</span><span class="identifier">specialization_param0</span><span class="special">)(</span><span class="identifier">specialization_param1</span><span class="special">)...</span></code> declares the template parameters of the actual specialization of <code class="computeroutput"><span class="identifier">type_name</span></code> that is adapted as a fusion sequence. The sequence of <code class="literal">(attribute_type<span class="emphasis"><em>N</em></span>, attribute_const_type<span class="emphasis"><em>N</em></span>, get_expr<span class="emphasis"><em>N</em></span>, set_expr<span class="emphasis"><em>N</em></span>)</code> quadruples declares the types, const types, get-expressions and set-expressions of the elements that are part of the adapted fusion sequence. <code class="literal">get_expr<span class="emphasis"><em>N</em></span></code> is the expression that is invoked to get the <span class="emphasis"><em>N</em></span>th element of an instance of <code class="computeroutput"><span class="identifier">type_name</span></code>. This expression may access a variable named <code class="computeroutput"><span class="identifier">obj</span></code> of type <code class="computeroutput"><span class="identifier">type_name</span><span class="special">&amp;</span></code> or <code class="computeroutput"><span class="identifier">type_name</span> <span class="keyword">const</span><span class="special">&amp;</span></code> which represents the underlying instance of <code class="computeroutput"><span class="identifier">type_name</span></code>. <code class="literal">attribute_type<span class="emphasis"><em>N</em></span></code> and <code class="literal">attribute_const_type<span class="emphasis"><em>N</em></span></code> may specify the types that <code class="literal">get_expr<span class="emphasis"><em>N</em></span></code> denotes to, when omitted the type is deduced from [get_expr<span class="emphasis"><em>N</em></span>] return type via BOOST_TYPEOF. On compiler missing support for variadic macros BOOST_FUSION_ADAPT_AUTO can be used to avoid repeating the type. <code class="literal">set_expr<span class="emphasis"><em>N</em></span></code> is the expression that is invoked to set the <span class="emphasis"><em>N</em></span>th element of an instance of <code class="computeroutput"><span class="identifier">type_name</span></code>. This expression may access variables named <code class="computeroutput"><span class="identifier">obj</span></code> of type <code class="computeroutput"><span class="identifier">type_name</span><span class="special">&amp;</span></code>, which represent the corresponding instance of <code class="computeroutput"><span class="identifier">type_name</span></code>, and <code class="computeroutput"><span class="identifier">val</span></code> of an arbitrary const-qualified reference template type parameter <code class="computeroutput"><span class="identifier">Val</span></code>, which represents the right operand of the assignment expression. </p> <p> The actual return type of fusion's intrinsic sequence access (meta-)functions when in invoked with (an instance of) <code class="computeroutput"><span class="identifier">type_name</span></code> is a proxy type. This type is implicitly convertible to the attribute type via <code class="literal">get_expr<span class="emphasis"><em>N</em></span></code> and forwards assignment to the underlying element via <code class="literal">set_expr<span class="emphasis"><em>N</em></span></code>. The value type (that is the type returned by <a class="link" href="../iterator/metafunctions/value_of.html" title="value_of"><code class="computeroutput"><span class="identifier">result_of</span><span class="special">::</span><span class="identifier">value_of</span></code></a>, <a class="link" href="../sequence/intrinsic/metafunctions/value_at.html" title="value_at"><code class="computeroutput"><span class="identifier">result_of</span><span class="special">::</span><span class="identifier">value_at</span></code></a> and <a class="link" href="../sequence/intrinsic/metafunctions/value_at_c.html" title="value_at_c"><code class="computeroutput"><span class="identifier">result_of</span><span class="special">::</span><span class="identifier">value_at_c</span></code></a>) of the <span class="emphasis"><em>N</em></span>th element is <code class="literal">attribute_type<span class="emphasis"><em>N</em></span></code> with const-qualifier and reference removed. </p> <p> The macro should be used at global scope, and <code class="computeroutput"><span class="identifier">type_name</span></code> should be the fully namespace qualified name of the template class type to be adapted. </p> <h5> <a name="fusion.adapted.adapt_tpl_adt.h2"></a> <span class="phrase"><a name="fusion.adapted.adapt_tpl_adt.header"></a></span><a class="link" href="adapt_tpl_adt.html#fusion.adapted.adapt_tpl_adt.header">Header</a> </h5> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">fusion</span><span class="special">/</span><span class="identifier">adapted</span><span class="special">/</span><span class="identifier">adt</span><span class="special">/</span><span class="identifier">adapt_adt</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">fusion</span><span class="special">/</span><span class="identifier">include</span><span class="special">/</span><span class="identifier">adapt_adt</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> </pre> <h5> <a name="fusion.adapted.adapt_tpl_adt.h3"></a> <span class="phrase"><a name="fusion.adapted.adapt_tpl_adt.example"></a></span><a class="link" href="adapt_tpl_adt.html#fusion.adapted.adapt_tpl_adt.example">Example</a> </h5> <pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">demo</span> <span class="special">{</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">Name</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Age</span><span class="special">&gt;</span> <span class="keyword">struct</span> <span class="identifier">employee</span> <span class="special">{</span> <span class="keyword">private</span><span class="special">:</span> <span class="identifier">Name</span> <span class="identifier">name</span><span class="special">;</span> <span class="identifier">Age</span> <span class="identifier">age</span><span class="special">;</span> <span class="keyword">public</span><span class="special">:</span> <span class="keyword">void</span> <span class="identifier">set_name</span><span class="special">(</span><span class="identifier">Name</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">n</span><span class="special">)</span> <span class="special">{</span> <span class="identifier">name</span><span class="special">=</span><span class="identifier">n</span><span class="special">;</span> <span class="special">}</span> <span class="keyword">void</span> <span class="identifier">set_age</span><span class="special">(</span><span class="identifier">Age</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">a</span><span class="special">)</span> <span class="special">{</span> <span class="identifier">age</span><span class="special">=</span><span class="identifier">a</span><span class="special">;</span> <span class="special">}</span> <span class="identifier">Name</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">get_name</span><span class="special">()</span><span class="keyword">const</span> <span class="special">{</span> <span class="keyword">return</span> <span class="identifier">name</span><span class="special">;</span> <span class="special">}</span> <span class="identifier">Age</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">get_age</span><span class="special">()</span><span class="keyword">const</span> <span class="special">{</span> <span class="keyword">return</span> <span class="identifier">age</span><span class="special">;</span> <span class="special">}</span> <span class="special">};</span> <span class="special">}</span> <span class="identifier">BOOST_FUSION_ADAPT_TPL_ADT</span><span class="special">(</span> <span class="special">(</span><span class="identifier">Name</span><span class="special">)(</span><span class="identifier">Age</span><span class="special">),</span> <span class="special">(</span><span class="identifier">demo</span><span class="special">::</span><span class="identifier">employee</span><span class="special">)</span> <span class="special">(</span><span class="identifier">Name</span><span class="special">)(</span><span class="identifier">Age</span><span class="special">),</span> <span class="special">(</span><span class="identifier">Name</span> <span class="keyword">const</span><span class="special">&amp;,</span> <span class="identifier">Name</span> <span class="keyword">const</span><span class="special">&amp;,</span> <span class="identifier">obj</span><span class="special">.</span><span class="identifier">get_name</span><span class="special">(),</span> <span class="identifier">obj</span><span class="special">.</span><span class="identifier">set_name</span><span class="special">(</span><span class="identifier">val</span><span class="special">))</span> <span class="special">(</span><span class="identifier">Age</span> <span class="keyword">const</span><span class="special">&amp;,</span> <span class="identifier">Age</span> <span class="keyword">const</span><span class="special">&amp;,</span> <span class="identifier">obj</span><span class="special">.</span><span class="identifier">get_age</span><span class="special">(),</span> <span class="identifier">obj</span><span class="special">.</span><span class="identifier">set_age</span><span class="special">(</span><span class="identifier">val</span><span class="special">)))</span> <span class="identifier">demo</span><span class="special">::</span><span class="identifier">employee</span><span class="special">&lt;</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span><span class="special">,</span> <span class="keyword">int</span><span class="special">&gt;</span> <span class="identifier">e</span><span class="special">;</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">fusion</span><span class="special">::</span><span class="identifier">front</span><span class="special">(</span><span class="identifier">e</span><span class="special">)=</span><span class="string">"Edward Norton"</span><span class="special">;</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">fusion</span><span class="special">::</span><span class="identifier">back</span><span class="special">(</span><span class="identifier">e</span><span class="special">)=</span><span class="number">41</span><span class="special">;</span> <span class="comment">//Prints 'Edward Norton is 41 years old'</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cout</span> <span class="special">&lt;&lt;</span> <span class="identifier">e</span><span class="special">.</span><span class="identifier">get_name</span><span class="special">()</span> <span class="special">&lt;&lt;</span> <span class="string">" is "</span> <span class="special">&lt;&lt;</span> <span class="identifier">e</span><span class="special">.</span><span class="identifier">get_age</span><span class="special">()</span> <span class="special">&lt;&lt;</span> <span class="string">" years old"</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> </pre> <h5> <a name="fusion.adapted.adapt_tpl_adt.h4"></a> <span class="phrase"><a name="fusion.adapted.adapt_tpl_adt.see_also"></a></span><a class="link" href="adapt_tpl_adt.html#fusion.adapted.adapt_tpl_adt.see_also">See also</a> </h5> <p> <a class="link" href="../notes.html#fusion.notes.adt_attribute_proxy"><code class="computeroutput"><span class="identifier">adt_attribute_proxy</span></code></a> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2001-2006, 2011, 2012 Joel de Guzman, Dan Marsden, Tobias Schwinger<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="adapt_adt.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../adapted.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="adapt_assoc_adt.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
gpl-3.0
andybarry/ardupilot
libraries/AP_InertialSensor/AP_InertialSensor_MPU6000.cpp
60871
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include <AP_HAL.h> #include "AP_InertialSensor_MPU6000.h" extern const AP_HAL::HAL& hal; // MPU6000 accelerometer scaling #define MPU6000_ACCEL_SCALE_1G (GRAVITY_MSS / 4096.0f) // MPU 6000 registers #define MPUREG_XG_OFFS_TC 0x00 #define MPUREG_YG_OFFS_TC 0x01 #define MPUREG_ZG_OFFS_TC 0x02 #define MPUREG_X_FINE_GAIN 0x03 #define MPUREG_Y_FINE_GAIN 0x04 #define MPUREG_Z_FINE_GAIN 0x05 #define MPUREG_XA_OFFS_H 0x06 // X axis accelerometer offset (high byte) #define MPUREG_XA_OFFS_L 0x07 // X axis accelerometer offset (low byte) #define MPUREG_YA_OFFS_H 0x08 // Y axis accelerometer offset (high byte) #define MPUREG_YA_OFFS_L 0x09 // Y axis accelerometer offset (low byte) #define MPUREG_ZA_OFFS_H 0x0A // Z axis accelerometer offset (high byte) #define MPUREG_ZA_OFFS_L 0x0B // Z axis accelerometer offset (low byte) #define MPUREG_PRODUCT_ID 0x0C // Product ID Register #define MPUREG_XG_OFFS_USRH 0x13 // X axis gyro offset (high byte) #define MPUREG_XG_OFFS_USRL 0x14 // X axis gyro offset (low byte) #define MPUREG_YG_OFFS_USRH 0x15 // Y axis gyro offset (high byte) #define MPUREG_YG_OFFS_USRL 0x16 // Y axis gyro offset (low byte) #define MPUREG_ZG_OFFS_USRH 0x17 // Z axis gyro offset (high byte) #define MPUREG_ZG_OFFS_USRL 0x18 // Z axis gyro offset (low byte) #define MPUREG_SMPLRT_DIV 0x19 // sample rate. Fsample= 1Khz/(<this value>+1) = 200Hz # define MPUREG_SMPLRT_1000HZ 0x00 # define MPUREG_SMPLRT_500HZ 0x01 # define MPUREG_SMPLRT_250HZ 0x03 # define MPUREG_SMPLRT_200HZ 0x04 # define MPUREG_SMPLRT_100HZ 0x09 # define MPUREG_SMPLRT_50HZ 0x13 #define MPUREG_CONFIG 0x1A #define MPUREG_GYRO_CONFIG 0x1B // bit definitions for MPUREG_GYRO_CONFIG # define BITS_GYRO_FS_250DPS 0x00 # define BITS_GYRO_FS_500DPS 0x08 # define BITS_GYRO_FS_1000DPS 0x10 # define BITS_GYRO_FS_2000DPS 0x18 # define BITS_GYRO_FS_MASK 0x18 // only bits 3 and 4 are used for gyro full scale so use this to mask off other bits # define BITS_GYRO_ZGYRO_SELFTEST 0x20 # define BITS_GYRO_YGYRO_SELFTEST 0x40 # define BITS_GYRO_XGYRO_SELFTEST 0x80 #define MPUREG_ACCEL_CONFIG 0x1C #define MPUREG_MOT_THR 0x1F // detection threshold for Motion interrupt generation. Motion is detected when the absolute value of any of the accelerometer measurements exceeds this #define MPUREG_MOT_DUR 0x20 // duration counter threshold for Motion interrupt generation. The duration counter ticks at 1 kHz, therefore MOT_DUR has a unit of 1 LSB = 1 ms #define MPUREG_ZRMOT_THR 0x21 // detection threshold for Zero Motion interrupt generation. #define MPUREG_ZRMOT_DUR 0x22 // duration counter threshold for Zero Motion interrupt generation. The duration counter ticks at 16 Hz, therefore ZRMOT_DUR has a unit of 1 LSB = 64 ms. #define MPUREG_FIFO_EN 0x23 #define MPUREG_INT_PIN_CFG 0x37 # define BIT_INT_RD_CLEAR 0x10 // clear the interrupt when any read occurs # define BIT_LATCH_INT_EN 0x20 // latch data ready pin #define MPUREG_INT_ENABLE 0x38 // bit definitions for MPUREG_INT_ENABLE # define BIT_RAW_RDY_EN 0x01 # define BIT_DMP_INT_EN 0x02 // enabling this bit (DMP_INT_EN) also enables RAW_RDY_EN it seems # define BIT_UNKNOWN_INT_EN 0x04 # define BIT_I2C_MST_INT_EN 0x08 # define BIT_FIFO_OFLOW_EN 0x10 # define BIT_ZMOT_EN 0x20 # define BIT_MOT_EN 0x40 # define BIT_FF_EN 0x80 #define MPUREG_INT_STATUS 0x3A // bit definitions for MPUREG_INT_STATUS (same bit pattern as above because this register shows what interrupt actually fired) # define BIT_RAW_RDY_INT 0x01 # define BIT_DMP_INT 0x02 # define BIT_UNKNOWN_INT 0x04 # define BIT_I2C_MST_INT 0x08 # define BIT_FIFO_OFLOW_INT 0x10 # define BIT_ZMOT_INT 0x20 # define BIT_MOT_INT 0x40 # define BIT_FF_INT 0x80 #define MPUREG_ACCEL_XOUT_H 0x3B #define MPUREG_ACCEL_XOUT_L 0x3C #define MPUREG_ACCEL_YOUT_H 0x3D #define MPUREG_ACCEL_YOUT_L 0x3E #define MPUREG_ACCEL_ZOUT_H 0x3F #define MPUREG_ACCEL_ZOUT_L 0x40 #define MPUREG_TEMP_OUT_H 0x41 #define MPUREG_TEMP_OUT_L 0x42 #define MPUREG_GYRO_XOUT_H 0x43 #define MPUREG_GYRO_XOUT_L 0x44 #define MPUREG_GYRO_YOUT_H 0x45 #define MPUREG_GYRO_YOUT_L 0x46 #define MPUREG_GYRO_ZOUT_H 0x47 #define MPUREG_GYRO_ZOUT_L 0x48 #define MPUREG_USER_CTRL 0x6A // bit definitions for MPUREG_USER_CTRL # define BIT_USER_CTRL_SIG_COND_RESET 0x01 // resets signal paths and results registers for all sensors (gyros, accel, temp) # define BIT_USER_CTRL_I2C_MST_RESET 0x02 // reset I2C Master (only applicable if I2C_MST_EN bit is set) # define BIT_USER_CTRL_FIFO_RESET 0x04 // Reset (i.e. clear) FIFO buffer # define BIT_USER_CTRL_DMP_RESET 0x08 // Reset DMP # define BIT_USER_CTRL_I2C_IF_DIS 0x10 // Disable primary I2C interface and enable hal.spi->interface # define BIT_USER_CTRL_I2C_MST_EN 0x20 // Enable MPU to act as the I2C Master to external slave sensors # define BIT_USER_CTRL_FIFO_EN 0x40 // Enable FIFO operations # define BIT_USER_CTRL_DMP_EN 0x80 // Enable DMP operations #define MPUREG_PWR_MGMT_1 0x6B # define BIT_PWR_MGMT_1_CLK_INTERNAL 0x00 // clock set to internal 8Mhz oscillator # define BIT_PWR_MGMT_1_CLK_XGYRO 0x01 // PLL with X axis gyroscope reference # define BIT_PWR_MGMT_1_CLK_YGYRO 0x02 // PLL with Y axis gyroscope reference # define BIT_PWR_MGMT_1_CLK_ZGYRO 0x03 // PLL with Z axis gyroscope reference # define BIT_PWR_MGMT_1_CLK_EXT32KHZ 0x04 // PLL with external 32.768kHz reference # define BIT_PWR_MGMT_1_CLK_EXT19MHZ 0x05 // PLL with external 19.2MHz reference # define BIT_PWR_MGMT_1_CLK_STOP 0x07 // Stops the clock and keeps the timing generator in reset # define BIT_PWR_MGMT_1_TEMP_DIS 0x08 // disable temperature sensor # define BIT_PWR_MGMT_1_CYCLE 0x20 // put sensor into cycle mode. cycles between sleep mode and waking up to take a single sample of data from active sensors at a rate determined by LP_WAKE_CTRL # define BIT_PWR_MGMT_1_SLEEP 0x40 // put sensor into low power sleep mode # define BIT_PWR_MGMT_1_DEVICE_RESET 0x80 // reset entire device #define MPUREG_PWR_MGMT_2 0x6C // allows the user to configure the frequency of wake-ups in Accelerometer Only Low Power Mode #define MPUREG_BANK_SEL 0x6D // DMP bank selection register (used to indirectly access DMP registers) #define MPUREG_MEM_START_ADDR 0x6E // DMP memory start address (used to indirectly write to dmp memory) #define MPUREG_MEM_R_W 0x6F // DMP related register #define MPUREG_DMP_CFG_1 0x70 // DMP related register #define MPUREG_DMP_CFG_2 0x71 // DMP related register #define MPUREG_FIFO_COUNTH 0x72 #define MPUREG_FIFO_COUNTL 0x73 #define MPUREG_FIFO_R_W 0x74 #define MPUREG_WHOAMI 0x75 // Configuration bits MPU 3000 and MPU 6000 (not revised)? #define BITS_DLPF_CFG_256HZ_NOLPF2 0x00 #define BITS_DLPF_CFG_188HZ 0x01 #define BITS_DLPF_CFG_98HZ 0x02 #define BITS_DLPF_CFG_42HZ 0x03 #define BITS_DLPF_CFG_20HZ 0x04 #define BITS_DLPF_CFG_10HZ 0x05 #define BITS_DLPF_CFG_5HZ 0x06 #define BITS_DLPF_CFG_2100HZ_NOLPF 0x07 #define BITS_DLPF_CFG_MASK 0x07 // Product ID Description for MPU6000 // high 4 bits low 4 bits // Product Name Product Revision #define MPU6000ES_REV_C4 0x14 // 0001 0100 #define MPU6000ES_REV_C5 0x15 // 0001 0101 #define MPU6000ES_REV_D6 0x16 // 0001 0110 #define MPU6000ES_REV_D7 0x17 // 0001 0111 #define MPU6000ES_REV_D8 0x18 // 0001 1000 #define MPU6000_REV_C4 0x54 // 0101 0100 #define MPU6000_REV_C5 0x55 // 0101 0101 #define MPU6000_REV_D6 0x56 // 0101 0110 #define MPU6000_REV_D7 0x57 // 0101 0111 #define MPU6000_REV_D8 0x58 // 0101 1000 #define MPU6000_REV_D9 0x59 // 0101 1001 // DMP output rate constants #define MPU6000_200HZ 0x00 // default value #define MPU6000_100HZ 0x01 #define MPU6000_66HZ 0x02 #define MPU6000_50HZ 0x03 // DMP FIFO constants // Default quaternion FIFO size (4*4) + Footer(2) #define FIFO_PACKET_SIZE 18 // Rate of the gyro bias from gravity correction (200Hz/4) => 50Hz #define GYRO_BIAS_FROM_GRAVITY_RATE 4 // Default gain for accel fusion (with gyros) #define DEFAULT_ACCEL_FUSION_GAIN 0x80 /* * RM-MPU-6000A-00.pdf, page 33, section 4.25 lists LSB sensitivity of * gyro as 16.4 LSB/DPS at scale factor of +/- 2000dps (FS_SEL==3) */ const float AP_InertialSensor_MPU6000::_gyro_scale = (0.0174532 / 16.4); /* pch: I believe the accel and gyro indicies are correct * but somone else should please confirm. * * jamesjb: Y and Z axes are flipped on the PX4FMU */ const uint8_t AP_InertialSensor_MPU6000::_gyro_data_index[3] = { 5, 4, 6 }; const uint8_t AP_InertialSensor_MPU6000::_accel_data_index[3] = { 1, 0, 2 }; #if CONFIG_HAL_BOARD == HAL_BOARD_SMACCM const int8_t AP_InertialSensor_MPU6000::_gyro_data_sign[3] = { 1, -1, 1 }; const int8_t AP_InertialSensor_MPU6000::_accel_data_sign[3] = { 1, -1, 1 }; #else const int8_t AP_InertialSensor_MPU6000::_gyro_data_sign[3] = { 1, 1, -1 }; const int8_t AP_InertialSensor_MPU6000::_accel_data_sign[3] = { 1, 1, -1 }; #endif const uint8_t AP_InertialSensor_MPU6000::_temp_data_index = 3; int16_t AP_InertialSensor_MPU6000::_mpu6000_product_id = AP_PRODUCT_ID_NONE; AP_HAL::DigitalSource *AP_InertialSensor_MPU6000::_drdy_pin = NULL; // time we start collecting sample (reset on update) // time latest sample was collected static volatile uint32_t _last_sample_time_micros = 0; // DMP related static variables bool AP_InertialSensor_MPU6000::_dmp_initialised = false; // high byte of number of elements in fifo buffer uint8_t AP_InertialSensor_MPU6000::_fifoCountH; // low byte of number of elements in fifo buffer uint8_t AP_InertialSensor_MPU6000::_fifoCountL; // holds the 4 quaternions representing attitude taken directly from the DMP Quaternion AP_InertialSensor_MPU6000::quaternion; /* Static SPI device driver */ AP_HAL::SPIDeviceDriver* AP_InertialSensor_MPU6000::_spi = NULL; AP_HAL::Semaphore* AP_InertialSensor_MPU6000::_spi_sem = NULL; /* * RM-MPU-6000A-00.pdf, page 31, section 4.23 lists LSB sensitivity of * accel as 4096 LSB/mg at scale factor of +/- 8g (AFS_SEL==2) * * See note below about accel scaling of engineering sample MPU6k * variants however */ AP_InertialSensor_MPU6000::AP_InertialSensor_MPU6000() : AP_InertialSensor() { _temp = 0; _initialised = false; _dmp_initialised = false; } uint16_t AP_InertialSensor_MPU6000::_init_sensor( Sample_rate sample_rate ) { if (_initialised) return _mpu6000_product_id; _initialised = true; _spi = hal.spi->device(AP_HAL::SPIDevice_MPU6000); _spi_sem = _spi->get_semaphore(); /* Pin 70 defined especially to hook up PE6 to the hal.gpio abstraction. (It is not a valid pin under Arduino.) */ _drdy_pin = hal.gpio->channel(70); hal.scheduler->suspend_timer_procs(); uint8_t tries = 0; do { bool success = hardware_init(sample_rate); if (success) { hal.scheduler->delay(5+2); if (_data_ready()) { break; } else { hal.console->println_P( PSTR("MPU6000 startup failed: no data ready")); } } if (tries++ > 5) { hal.scheduler->panic(PSTR("PANIC: failed to boot MPU6000 5 times")); } } while (1); hal.scheduler->resume_timer_procs(); /* read the first lot of data. * _read_data_transaction requires the spi semaphore to be taken by * its caller. */ _last_sample_time_micros = hal.scheduler->micros(); _read_data_transaction(); // start the timer process to read samples hal.scheduler->register_timer_process(_poll_data); #if MPU6000_DEBUG _dump_registers(); #endif return _mpu6000_product_id; } // accumulation in ISR - must be read with interrupts disabled // the sum of the values since last read static volatile int32_t _sum[7]; // how many values we've accumulated since last read static volatile uint16_t _count; /*================ AP_INERTIALSENSOR PUBLIC INTERFACE ==================== */ void AP_InertialSensor_MPU6000::wait_for_sample() { uint32_t tstart = hal.scheduler->micros(); while (num_samples_available() == 0) { uint32_t now = hal.scheduler->micros(); uint32_t dt = now - tstart; if (dt > 50000) { hal.scheduler->panic( PSTR("PANIC: AP_InertialSensor_MPU6000::update " "waited 50ms for data from interrupt")); } } } bool AP_InertialSensor_MPU6000::update( void ) { int32_t sum[7]; float count_scale; Vector3f accel_scale = _accel_scale.get(); // wait for at least 1 sample wait_for_sample(); // disable timer procs for mininum time hal.scheduler->suspend_timer_procs(); /** ATOMIC SECTION w/r/t TIMER PROCESS */ { for (int i=0; i<7; i++) { sum[i] = _sum[i]; _sum[i] = 0; } _num_samples = _count; _count = 0; } hal.scheduler->resume_timer_procs(); count_scale = 1.0f / _num_samples; _gyro = Vector3f(_gyro_data_sign[0] * sum[_gyro_data_index[0]], _gyro_data_sign[1] * sum[_gyro_data_index[1]], _gyro_data_sign[2] * sum[_gyro_data_index[2]]); _gyro.rotate(_board_orientation); _gyro *= _gyro_scale * count_scale; _gyro -= _gyro_offset; _accel = Vector3f(_accel_data_sign[0] * sum[_accel_data_index[0]], _accel_data_sign[1] * sum[_accel_data_index[1]], _accel_data_sign[2] * sum[_accel_data_index[2]]); _accel.rotate(_board_orientation); _accel *= count_scale * MPU6000_ACCEL_SCALE_1G; _accel.x *= accel_scale.x; _accel.y *= accel_scale.y; _accel.z *= accel_scale.z; _accel -= _accel_offset; _temp = _temp_to_celsius(sum[_temp_data_index] * count_scale); if (_last_filter_hz != _mpu6000_filter) { if (_spi_sem->take(10)) { _set_filter_register(_mpu6000_filter, 0); _spi_sem->give(); } } return true; } /*================ HARDWARE FUNCTIONS ==================== */ /** * Return true if the MPU6000 has new data available for reading. * * We use the data ready pin if it is available. Otherwise, read the * status register. */ bool AP_InertialSensor_MPU6000::_data_ready() { if (_drdy_pin) { return _drdy_pin->read() != 0; } if (hal.scheduler->in_timerprocess()) { bool got = _spi_sem->take_nonblocking(); if (got) { uint8_t status = _register_read(MPUREG_INT_STATUS); _spi_sem->give(); return (status & BIT_RAW_RDY_INT) != 0; } else { return false; } } else { bool got = _spi_sem->take(10); if (got) { uint8_t status = _register_read(MPUREG_INT_STATUS); _spi_sem->give(); return (status & BIT_RAW_RDY_INT) != 0; } else { hal.scheduler->panic( PSTR("PANIC: AP_InertialSensor_MPU6000::_data_ready failed to " "take SPI semaphore synchronously")); } } return false; } /** * Timer process to poll for new data from the MPU6000. */ void AP_InertialSensor_MPU6000::_poll_data(uint32_t now) { if (_data_ready()) { if (hal.scheduler->in_timerprocess()) { _read_data_from_timerprocess(); } else { /* Synchronous read - take semaphore */ bool got = _spi_sem->take(10); if (got) { _last_sample_time_micros = hal.scheduler->micros(); _read_data_transaction(); _spi_sem->give(); } else { hal.scheduler->panic( PSTR("PANIC: AP_InertialSensor_MPU6000::_poll_data " "failed to take SPI semaphore synchronously")); } } } } /* * this is called from the _poll_data, in the timer process context. * when the MPU6000 has new sensor data available and add it to _sum[] to * ensure this is the case, these other devices must perform their spi reads * after being called by the AP_TimerProcess. */ void AP_InertialSensor_MPU6000::_read_data_from_timerprocess() { static uint8_t semfail_ctr = 0; bool got = _spi_sem->take_nonblocking(); if (!got) { semfail_ctr++; if (semfail_ctr > 100) { hal.scheduler->panic(PSTR("PANIC: failed to take SPI semaphore " "100 times in AP_InertialSensor_MPU6000::" "_read_data_from_timerprocess")); } return; } else { semfail_ctr = 0; } _last_sample_time_micros = hal.scheduler->micros(); _read_data_transaction(); _spi_sem->give(); } void AP_InertialSensor_MPU6000::_read_data_transaction() { /* one resister address followed by seven 2-byte registers */ uint8_t tx[15]; uint8_t rx[15]; memset(tx,0,15); tx[0] = MPUREG_ACCEL_XOUT_H | 0x80; _spi->transaction(tx, rx, 15); for (uint8_t i = 0; i < 7; i++) { _sum[i] += (int16_t)(((uint16_t)rx[2*i+1] << 8) | rx[2*i+2]); } _count++; if (_count == 0) { // rollover - v unlikely memset((void*)_sum, 0, sizeof(_sum)); } // should also read FIFO data if enabled if( _dmp_initialised ) { if( FIFO_ready() ) { FIFO_getPacket(); } } } uint8_t AP_InertialSensor_MPU6000::_register_read( uint8_t reg ) { uint8_t addr = reg | 0x80; // Set most significant bit uint8_t tx[2]; uint8_t rx[2]; tx[0] = addr; tx[1] = 0; _spi->transaction(tx, rx, 2); return rx[1]; } void AP_InertialSensor_MPU6000::register_write(uint8_t reg, uint8_t val) { uint8_t tx[2]; uint8_t rx[2]; tx[0] = reg; tx[1] = val; _spi->transaction(tx, rx, 2); } /* set the DLPF filter frequency. Assumes caller has taken semaphore */ void AP_InertialSensor_MPU6000::_set_filter_register(uint8_t filter_hz, uint8_t default_filter) { uint8_t filter = default_filter; // choose filtering frequency switch (filter_hz) { case 5: filter = BITS_DLPF_CFG_5HZ; break; case 10: filter = BITS_DLPF_CFG_10HZ; break; case 20: filter = BITS_DLPF_CFG_20HZ; break; case 42: filter = BITS_DLPF_CFG_42HZ; break; case 98: filter = BITS_DLPF_CFG_98HZ; break; } if (filter != 0) { _last_filter_hz = filter_hz; register_write(MPUREG_CONFIG, filter); } } bool AP_InertialSensor_MPU6000::hardware_init(Sample_rate sample_rate) { if (!_spi_sem->take(100)) { hal.scheduler->panic(PSTR("MPU6000: Unable to get semaphore")); } // Chip reset uint8_t tries; for (tries = 0; tries<5; tries++) { register_write(MPUREG_PWR_MGMT_1, BIT_PWR_MGMT_1_DEVICE_RESET); hal.scheduler->delay(100); // Wake up device and select GyroZ clock. Note that the // MPU6000 starts up in sleep mode, and it can take some time // for it to come out of sleep register_write(MPUREG_PWR_MGMT_1, BIT_PWR_MGMT_1_CLK_ZGYRO); hal.scheduler->delay(5); // check it has woken up if (_register_read(MPUREG_PWR_MGMT_1) == BIT_PWR_MGMT_1_CLK_ZGYRO) { break; } #if MPU6000_DEBUG _dump_registers(); #endif } if (tries == 5) { hal.console->println_P(PSTR("Failed to boot MPU6000 5 times")); _spi_sem->give(); return false; } register_write(MPUREG_PWR_MGMT_2, 0x00); // only used for wake-up in accelerometer only low power mode hal.scheduler->delay(1); // Disable I2C bus (recommended on datasheet) register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_I2C_IF_DIS); hal.scheduler->delay(1); uint8_t default_filter; // sample rate and filtering // to minimise the effects of aliasing we choose a filter // that is less than half of the sample rate switch (sample_rate) { case RATE_50HZ: // this is used for plane and rover, where noise resistance is // more important than update rate. Tests on an aerobatic plane // show that 10Hz is fine, and makes it very noise resistant default_filter = BITS_DLPF_CFG_10HZ; _sample_shift = 2; break; case RATE_100HZ: default_filter = BITS_DLPF_CFG_20HZ; _sample_shift = 1; break; case RATE_200HZ: default: default_filter = BITS_DLPF_CFG_20HZ; _sample_shift = 0; break; } _set_filter_register(_mpu6000_filter, default_filter); // set sample rate to 200Hz, and use _sample_divider to give // the requested rate to the application register_write(MPUREG_SMPLRT_DIV, MPUREG_SMPLRT_200HZ); hal.scheduler->delay(1); register_write(MPUREG_GYRO_CONFIG, BITS_GYRO_FS_2000DPS); // Gyro scale 2000º/s hal.scheduler->delay(1); // read the product ID rev c has 1/2 the sensitivity of rev d _mpu6000_product_id = _register_read(MPUREG_PRODUCT_ID); //Serial.printf("Product_ID= 0x%x\n", (unsigned) _mpu6000_product_id); if ((_mpu6000_product_id == MPU6000ES_REV_C4) || (_mpu6000_product_id == MPU6000ES_REV_C5) || (_mpu6000_product_id == MPU6000_REV_C4) || (_mpu6000_product_id == MPU6000_REV_C5)) { // Accel scale 8g (4096 LSB/g) // Rev C has different scaling than rev D register_write(MPUREG_ACCEL_CONFIG,1<<3); } else { // Accel scale 8g (4096 LSB/g) register_write(MPUREG_ACCEL_CONFIG,2<<3); } hal.scheduler->delay(1); // configure interrupt to fire when new data arrives register_write(MPUREG_INT_ENABLE, BIT_RAW_RDY_EN); hal.scheduler->delay(1); // clear interrupt on any read, and hold the data ready pin high // until we clear the interrupt register_write(MPUREG_INT_PIN_CFG, BIT_INT_RD_CLEAR | BIT_LATCH_INT_EN); hal.scheduler->delay(1); _spi_sem->give(); return true; } float AP_InertialSensor_MPU6000::_temp_to_celsius ( uint16_t regval ) { /* TODO */ return 20.0; } // return the MPU6k gyro drift rate in radian/s/s // note that this is much better than the oilpan gyros float AP_InertialSensor_MPU6000::get_gyro_drift_rate(void) { // 0.5 degrees/second/minute return ToRad(0.5/60); } // get number of samples read from the sensors uint16_t AP_InertialSensor_MPU6000::num_samples_available() { _poll_data(0); return _count >> _sample_shift; } #if MPU6000_DEBUG // dump all config registers - used for debug void AP_InertialSensor_MPU6000::_dump_registers(void) { hal.console->println_P(PSTR("MPU6000 registers")); for (uint8_t reg=MPUREG_PRODUCT_ID; reg<=108; reg++) { uint8_t v = _register_read(reg); hal.console->printf_P(PSTR("%02x:%02x "), (unsigned)reg, (unsigned)v); if ((reg - (MPUREG_PRODUCT_ID-1)) % 16 == 0) { hal.console->println(); } } hal.console->println(); } #endif // get_delta_time returns the time period in seconds overwhich the sensor data was collected float AP_InertialSensor_MPU6000::get_delta_time() { // the sensor runs at 200Hz return 0.005 * _num_samples; } // Update gyro offsets with new values. Offsets provided in as scaled deg/sec values void AP_InertialSensor_MPU6000::push_gyro_offsets_to_dmp() { Vector3f gyro_offsets = _gyro_offset.get(); int16_t offsetX = gyro_offsets.x / _gyro_scale * _gyro_data_sign[0]; int16_t offsetY = gyro_offsets.y / _gyro_scale * _gyro_data_sign[1]; int16_t offsetZ = gyro_offsets.z / _gyro_scale * _gyro_data_sign[2]; set_dmp_gyro_offsets(offsetX, offsetY, offsetZ); // remove ins level offsets to avoid double counting gyro_offsets.x = 0; gyro_offsets.y = 0; gyro_offsets.z = 0; _gyro_offset = gyro_offsets; } // Update gyro offsets with new values. New offset values are substracted to actual offset values. // offset values in gyro LSB units (as read from registers) void AP_InertialSensor_MPU6000::set_dmp_gyro_offsets(int16_t offsetX, int16_t offsetY, int16_t offsetZ) { int16_t aux_int; if (offsetX != 0) { // Read actual value aux_int = (_register_read(MPUREG_XG_OFFS_USRH)<<8) | _register_read(MPUREG_XG_OFFS_USRL); aux_int -= offsetX<<1; // Adjust to internal units // Write to MPU registers register_write(MPUREG_XG_OFFS_USRH, (aux_int>>8)&0xFF); register_write(MPUREG_XG_OFFS_USRL, aux_int&0xFF); } if (offsetY != 0) { aux_int = (_register_read(MPUREG_YG_OFFS_USRH)<<8) | _register_read(MPUREG_YG_OFFS_USRL); aux_int -= offsetY<<1; // Adjust to internal units // Write to MPU registers register_write(MPUREG_YG_OFFS_USRH, (aux_int>>8)&0xFF); register_write(MPUREG_YG_OFFS_USRL, aux_int&0xFF); } if (offsetZ != 0) { aux_int = (_register_read(MPUREG_ZG_OFFS_USRH)<<8) | _register_read(MPUREG_ZG_OFFS_USRL); aux_int -= offsetZ<<1; // Adjust to internal units // Write to MPU registers register_write(MPUREG_ZG_OFFS_USRH, (aux_int>>8)&0xFF); register_write(MPUREG_ZG_OFFS_USRL, aux_int&0xFF); } } // Update accel offsets with new values. Offsets provided in as scaled values (1G) void AP_InertialSensor_MPU6000::push_accel_offsets_to_dmp() { Vector3f accel_offset = _accel_offset.get(); Vector3f accel_scale = _accel_scale.get(); int16_t offsetX = accel_offset.x / (accel_scale.x * _accel_data_sign[0] * MPU6000_ACCEL_SCALE_1G); int16_t offsetY = accel_offset.y / (accel_scale.y * _accel_data_sign[1] * MPU6000_ACCEL_SCALE_1G); int16_t offsetZ = accel_offset.z / (accel_scale.z * _accel_data_sign[2] * MPU6000_ACCEL_SCALE_1G); // strangely x and y are reversed set_dmp_accel_offsets(offsetY, offsetX, offsetZ); } // set_accel_offsets - adds an offset to acceleromter readings // This is useful for dynamic acceleration correction (for example centripetal force correction) // and for the initial offset calibration // Input, accel offsets for X,Y and Z in LSB units (as read from raw values) void AP_InertialSensor_MPU6000::set_dmp_accel_offsets(int16_t offsetX, int16_t offsetY, int16_t offsetZ) { int aux_int; uint8_t regs[2]; // Write accel offsets to DMP memory... // TO-DO: why don't we write to main accel offset registries? i.e. MPUREG_XA_OFFS_H aux_int = offsetX>>1; // Transform to internal units regs[0]=(aux_int>>8)&0xFF; regs[1]=aux_int&0xFF; dmp_register_write(0x01,0x08,2,regs); // key KEY_D_1_8 Accel X offset aux_int = offsetY>>1; regs[0]=(aux_int>>8)&0xFF; regs[1]=aux_int&0xFF; dmp_register_write(0x01,0x0A,2,regs); // key KEY_D_1_10 Accel Y offset aux_int = offsetZ>>1; regs[0]=(aux_int>>8)&0xFF; regs[1]=aux_int&0xFF; dmp_register_write(0x01,0x02,2,regs); // key KEY_D_1_2 Accel Z offset } // dmp_register_write - method to write to dmp's registers // the dmp is logically separated from the main mpu6000. To write a block of memory to the DMP's memory you // write the "bank" and starting address into two of the main MPU's registers, then write the data one byte // at a time into the MPUREG_MEM_R_W register void AP_InertialSensor_MPU6000::dmp_register_write(uint8_t bank, uint8_t address, uint8_t num_bytes, uint8_t data[]) { register_write(MPUREG_BANK_SEL,bank); register_write(MPUREG_MEM_START_ADDR,address); _spi->cs_assert(); _spi->transfer(MPUREG_MEM_R_W); for (uint8_t i=0; i<num_bytes; i++) { _spi->transfer(data[i]); } _spi->cs_release(); } // MPU6000 DMP initialization // this should be called after hardware_init if you wish to enable the dmp void AP_InertialSensor_MPU6000::dmp_init() { uint8_t regs[4]; // for writing to dmp // ensure we only initialise once if( _dmp_initialised ) { return; } // load initial values into DMP memory dmp_load_mem(); dmp_set_gyro_calibration(); dmp_set_accel_calibration(); dmp_apply_endian_accel(); dmp_set_mpu_sensors(); dmp_set_bias_none(); dmp_set_fifo_interrupt(); dmp_send_quaternion(); // By default we only send the quaternion to the FIFO (18 bytes packet size) dmp_set_fifo_rate(MPU6000_200HZ); // 200Hz DMP output rate register_write(MPUREG_INT_ENABLE, BIT_RAW_RDY_EN | BIT_DMP_INT_EN ); // configure interrupts to fire only when new data arrives from DMP (in fifo buffer) // Randy: no idea what this does register_write(MPUREG_DMP_CFG_1, 0x03); //MPUREG_DMP_CFG_1, 0x03 register_write(MPUREG_DMP_CFG_2, 0x00); //MPUREG_DMP_CFG_2, 0x00 //inv_state_change_fifo regs[0] = 0xFF; regs[1] = 0xFF; dmp_register_write(0x01, 0xB2, 0x02, regs); // D_1_178 // ?? FIFO ?? regs[0] = 0x09; regs[1] = 0x23; regs[2] = 0xA1; regs[3] = 0x35; dmp_register_write(0x01, 0x90, 0x04, regs); // D_1_144 //register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_FIFO_RESET); //MPUREG_USER_CTRL, BIT_FIFO_RST FIFO_reset(); FIFO_ready(); //register_write(MPUREG_USER_CTRL, 0x00); // MPUREG_USER_CTRL, 0. TO-DO: is all this setting of USER_CTRL really necessary? register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_FIFO_RESET); //MPUREG_USER_CTRL, BIT_FIFO_RST. TO-DO: replace this call with FIFO_reset()? register_write(MPUREG_USER_CTRL, 0x00); // MPUREG_USER_CTRL: 0 register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_DMP_EN | BIT_USER_CTRL_FIFO_EN | BIT_USER_CTRL_DMP_RESET); // Set the gain of the accel in the sensor fusion dmp_set_sensor_fusion_accel_gain(DEFAULT_ACCEL_FUSION_GAIN); // default value // dmp initialisation complete _dmp_initialised = true; } // dmp_reset - reset dmp (required for changes in gains or offsets to take effect) void AP_InertialSensor_MPU6000::dmp_reset() { //uint8_t tmp = register_read(MPUREG_USER_CTRL); //tmp |= BIT_USER_CTRL_DMP_RESET; //register_write(MPUREG_USER_CTRL,tmp); register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_FIFO_RESET); //MPUREG_USER_CTRL, BIT_FIFO_RST. TO-DO: replace this call with FIFO_reset()? register_write(MPUREG_USER_CTRL, 0x00); // MPUREG_USER_CTRL: 0 register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_DMP_EN | BIT_USER_CTRL_FIFO_EN | BIT_USER_CTRL_DMP_RESET); } // New data packet in FIFO? bool AP_InertialSensor_MPU6000::FIFO_ready() { _fifoCountH = _register_read(MPUREG_FIFO_COUNTH); _fifoCountL = _register_read(MPUREG_FIFO_COUNTL); if(_fifoCountL == FIFO_PACKET_SIZE) { return 1; } else{ //We should not reach this point or maybe we have more than one packet (we should manage this!) FIFO_reset(); return 0; } } // FIFO_reset - reset/clear FIFO buffer used to capture attitude information from DMP void AP_InertialSensor_MPU6000::FIFO_reset() { uint8_t temp; temp = _register_read(MPUREG_USER_CTRL); temp = temp | BIT_USER_CTRL_FIFO_RESET; // FIFO RESET BIT register_write(MPUREG_USER_CTRL, temp); } // FIFO_getPacket - read an attitude packet from FIFO buffer // TO-DO: interpret results instead of just dumping into a buffer void AP_InertialSensor_MPU6000::FIFO_getPacket() { uint8_t i; int16_t q_data[4]; uint8_t addr = MPUREG_FIFO_R_W | 0x80; // Set most significant bit to indicate a read uint8_t received_packet[DMP_FIFO_BUFFER_SIZE]; // FIFO packet buffer _spi->cs_assert(); _spi->transfer(addr); // send address we want to read from for(i = 0; i < _fifoCountL; i++) { received_packet[i] = _spi->transfer(0); // request value } _spi->cs_release(); // we are using 16 bits resolution q_data[0] = (int16_t) ((((uint16_t) received_packet[0]) << 8) + ((uint16_t) received_packet[1])); q_data[1] = (int16_t) ((((uint16_t) received_packet[4]) << 8) + ((uint16_t) received_packet[5])); q_data[2] = (int16_t) ((((uint16_t) received_packet[8]) << 8) + ((uint16_t) received_packet[9])); q_data[3] = (int16_t) ((((uint16_t) received_packet[12]) << 8) + ((uint16_t) received_packet[13])); quaternion.q1 = ((float)q_data[0]) / 16384.0f; // convert from fixed point to float quaternion.q2 = ((float)q_data[2]) / 16384.0f; // convert from fixed point to float quaternion.q3 = ((float)q_data[1]) / 16384.0f; // convert from fixed point to float quaternion.q4 = ((float)-q_data[3]) / 16384.0f; // convert from fixed point to float } // dmp_set_gyro_calibration - apply default gyro calibration FS=2000dps and default orientation void AP_InertialSensor_MPU6000::dmp_set_gyro_calibration() { uint8_t regs[4]; regs[0]=0x4C; regs[1]=0xCD; regs[2]=0x6C; dmp_register_write(0x03, 0x7B, 0x03, regs); //FCFG_1 inv_set_gyro_calibration regs[0]=0x36; regs[1]=0x56; regs[2]=0x76; dmp_register_write(0x03, 0xAB, 0x03, regs); //FCFG_3 inv_set_gyro_calibration regs[0]=0x02; regs[1]=0xCB; regs[2]=0x47; regs[3]=0xA2; dmp_register_write(0x00, 0x68, 0x04, regs); //D_0_104 inv_set_gyro_calibration regs[0]=0x00; regs[1]=0x05; regs[2]=0x8B; regs[3]=0xC1; dmp_register_write(0x02, 0x18, 0x04, regs); //D_0_24 inv_set_gyro_calibration } // dmp_set_accel_calibration - apply default accel calibration scale=8g and default orientation void AP_InertialSensor_MPU6000::dmp_set_accel_calibration() { uint8_t regs[6]; regs[0]=0x00; regs[1]=0x00; regs[2]=0x00; regs[3]=0x00; dmp_register_write(0x01, 0x0C, 0x04, regs); //D_1_152 inv_set_accel_calibration regs[0]=0x0C; regs[1]=0xC9; regs[2]=0x2C; regs[3]=0x97; regs[4]=0x97; regs[5]=0x97; dmp_register_write(0x03, 0x7F, 0x06, regs); //FCFG_2 inv_set_accel_calibration regs[0]=0x26; regs[1]=0x46; regs[2]=0x66; dmp_register_write(0x03, 0x89, 0x03, regs); //FCFG_7 inv_set_accel_calibration // accel range, 0x20,0x00 => 2g, 0x10,0x00=>4g regs= (1073741824/accel_scale*65536) //regs[0]=0x20; // 2g regs[0]=0x08; // 8g regs[1]=0x00; dmp_register_write(0x00, 0x6C, 0x02, regs); //D_0_108 inv_set_accel_calibration } // dmp_apply_endian_accel - set byte order of accelerometer values? void AP_InertialSensor_MPU6000::dmp_apply_endian_accel() { uint8_t regs[4]; regs[0]=0x00; regs[1]=0x00; regs[2]=0x40; regs[3]=0x00; dmp_register_write(0x01, 0xEC, 0x04, regs); //D_1_236 inv_apply_endian_accel } // dmp_set_mpu_sensors - to configure for SIX_AXIS output void AP_InertialSensor_MPU6000::dmp_set_mpu_sensors() { uint8_t regs[6]; regs[0]=0x0C; regs[1]=0xC9; regs[2]=0x2C; regs[3]=0x97; regs[4]=0x97; regs[5]=0x97; dmp_register_write(0x03, 0x7F, 0x06, regs); //FCFG_2 inv_set_mpu_sensors(INV_SIX_AXIS_GYRO_ACCEL); } // dmp_set_bias_from_no_motion - turn on bias from no motion void AP_InertialSensor_MPU6000::dmp_set_bias_from_no_motion() { uint8_t regs[4]; regs[0]=0x0D; regs[1]=0x35; regs[2]=0x5D; dmp_register_write(0x04, 0x02, 0x03, regs); //CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion regs[0]=0x87; regs[1]=0x2D; regs[2]=0x35; regs[3]=0x3D; dmp_register_write(0x04, 0x09, 0x04, regs); //FCFG_5 inv_set_bias_update( INV_BIAS_FROM_NO_MOTION ); } // dmp_set_bias_none - turn off internal bias correction (we will use this and we handle the gyro bias correction externally) void AP_InertialSensor_MPU6000::dmp_set_bias_none() { uint8_t regs[4]; regs[0]=0x98; regs[1]=0x98; regs[2]=0x98; dmp_register_write(0x04, 0x02, 0x03, regs); //CFG_MOTION_BIAS inv_turn_off_bias_from_no_motion regs[0]=0x87; regs[1]=0x2D; regs[2]=0x35; regs[3]=0x3D; dmp_register_write(0x04, 0x09, 0x04, regs); //FCFG_5 inv_set_bias_update( INV_BIAS_FROM_NO_MOTION ); } // dmp_set_fifo_interrupt void AP_InertialSensor_MPU6000::dmp_set_fifo_interrupt() { uint8_t regs[1]; regs[0]=0xFE; dmp_register_write(0x07, 0x86, 0x01, regs); //CFG_6 inv_set_fifo_interupt } // dmp_send_quaternion - send quaternion data to FIFO void AP_InertialSensor_MPU6000::dmp_send_quaternion() { uint8_t regs[5]; regs[0]=0xF1; regs[1]=0x20; regs[2]=0x28; regs[3]=0x30; regs[4]=0x38; dmp_register_write(0x07, 0x41, 0x05, regs); //CFG_8 inv_send_quaternion regs[0]=0x30; dmp_register_write(0x07, 0x7E, 0x01, regs); //CFG_16 inv_set_footer } // dmp_send_gyro - send gyro data to FIFO void AP_InertialSensor_MPU6000::dmp_send_gyro() { uint8_t regs[4]; regs[0]=0xF1; regs[1]=0x28; regs[2]=0x30; regs[3]=0x38; dmp_register_write(0x07, 0x47, 0x04, regs); //CFG_9 inv_send_gyro } // dmp_send_accel - send accel data to FIFO void AP_InertialSensor_MPU6000::dmp_send_accel() { uint8_t regs[54]; regs[0]=0xF1; regs[1]=0x28; regs[2]=0x30; regs[3]=0x38; dmp_register_write(0x07, 0x6C, 0x04, regs); //CFG_12 inv_send_accel } // This functions defines the rate at wich attitude data is send to FIFO // Rate: 0 => SAMPLE_RATE(ex:200Hz), 1=> SAMPLE_RATE/2 (ex:100Hz), 2=> SAMPLE_RATE/3 (ex:66Hz) // rate constant definitions in MPU6000.h void AP_InertialSensor_MPU6000::dmp_set_fifo_rate(uint8_t rate) { uint8_t regs[2]; regs[0]=0x00; regs[1]=rate; dmp_register_write(0x02, 0x16, 0x02, regs); //D_0_22 inv_set_fifo_rate } // This function defines the weight of the accel on the sensor fusion // default value is 0x80 // The official invensense name is inv_key_0_96 (??) void AP_InertialSensor_MPU6000::dmp_set_sensor_fusion_accel_gain(uint8_t gain) { //inv_key_0_96 register_write(MPUREG_BANK_SEL,0x00); register_write(MPUREG_MEM_START_ADDR, 0x60); _spi->cs_assert(); _spi->transfer(MPUREG_MEM_R_W); _spi->transfer(0x00); _spi->transfer(gain); // Original : 0x80 To test: 0x40, 0x20 (too less) _spi->transfer(0x00); _spi->transfer(0x00); _spi->cs_release(); } // Load initial memory values into DMP memory banks void AP_InertialSensor_MPU6000::dmp_load_mem() { for(int i = 0; i < 7; i++) { register_write(MPUREG_BANK_SEL,i); //MPUREG_BANK_SEL for(uint8_t j = 0; j < 16; j++) { uint8_t start_addy = j * 0x10; register_write(MPUREG_MEM_START_ADDR,start_addy); _spi->cs_assert(); _spi->transfer(MPUREG_MEM_R_W); for(int k = 0; k < 16; k++) { uint8_t byteToSend = pgm_read_byte((const prog_char *)&(dmpMem[i][j][k])); _spi->transfer((uint8_t) byteToSend); } _spi->cs_release(); } } register_write(MPUREG_BANK_SEL,7); //MPUREG_BANK_SEL for(uint8_t j = 0; j < 8; j++) { uint8_t start_addy = j * 0x10; register_write(MPUREG_MEM_START_ADDR,start_addy); _spi->cs_assert(); _spi->transfer(MPUREG_MEM_R_W); for(int k = 0; k < 16; k++) { uint8_t byteToSend = pgm_read_byte((const prog_char *)&(dmpMem[7][j][k])); _spi->transfer((uint8_t) byteToSend); } _spi->cs_release(); } register_write(MPUREG_MEM_START_ADDR,0x80); _spi->cs_assert(); _spi->transfer(MPUREG_MEM_R_W); for(int k = 0; k < 9; k++) { uint8_t byteToSend = pgm_read_byte((const prog_char *)&(dmpMem[7][8][k])); _spi->transfer((uint8_t) byteToSend); } _spi->cs_release(); } // ========= DMP MEMORY ================================ const uint8_t dmpMem[8][16][16] PROGMEM = { { { 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00 } , { 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01 } , { 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01 } , { 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00 } , { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00 } , { 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82 } , { 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00 } , { 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0 } , { 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC } , { 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4 } , { 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10 } } , { { 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8 } , { 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7 } , { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C } , { 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C } , { 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0 } } , { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00 } , { 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } , { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } , { { 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F } , { 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2 } , { 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF } , { 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C } , { 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1 } , { 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01 } , { 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80 } , { 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C } , { 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80 } , { 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E } , { 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9 } , { 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24 } , { 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0 } , { 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86 } , { 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1 } , { 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86 } } , { { 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA } , { 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C } , { 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8 } , { 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3 } , { 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84 } , { 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5 } , { 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3 } , { 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1 } , { 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5 } , { 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D } , { 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9 } , { 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D } , { 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9 } , { 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A } , { 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8 } , { 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87 } } , { { 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8 } , { 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68 } , { 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D } , { 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94 } , { 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA } , { 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56 } , { 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9 } , { 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA } , { 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A } , { 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60 } , { 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97 } , { 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04 } , { 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78 } , { 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79 } , { 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68 } , { 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68 } } , { { 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04 } , { 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66 } , { 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31 } , { 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60 } , { 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76 } , { 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56 } , { 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD } , { 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91 } , { 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8 } , { 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE } , { 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9 } , { 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD } , { 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E } , { 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8 } , { 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89 } , { 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79 } } , { { 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8 } , { 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA } , { 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB } , { 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3 } , { 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3 } , { 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3 } , { 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3 } , { 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC } , { 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF } } };
gpl-3.0
viniciusferreira/mautic
plugins/MauticCrmBundle/MauticCrmBundle.php
444
<?php /** * @package Mautic * @copyright 2014 Mautic Contributors. All rights reserved. * @author Mautic * @link http://mautic.org * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ namespace MauticPlugin\MauticCrmBundle; use Mautic\PluginBundle\Bundle\PluginBundleBase; /** * Class MauticCrmBundle * * @package MauticPlugin\MauticCrmBundle */ class MauticCrmBundle extends PluginBundleBase { }
gpl-3.0
brion/gimp
libgimp/gimpmessage_pdb.c
3415
/* LIBGIMP - The GIMP Library * Copyright (C) 1995-2003 Peter Mattis and Spencer Kimball * * gimpmessage_pdb.c * * This library is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ /* NOTE: This file is auto-generated by pdbgen.pl */ #include "config.h" #include "gimp.h" /** * SECTION: gimpmessage * @title: gimpmessage * @short_description: Display a dialog box with a message. * * Display a dialog box with a message. **/ /** * gimp_message: * @message: Message to display in the dialog. * * Displays a dialog box with a message. * * Displays a dialog box with a message. Useful for status or error * reporting. The message must be in UTF-8 encoding. * * Returns: TRUE on success. **/ gboolean gimp_message (const gchar *message) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-message", &nreturn_vals, GIMP_PDB_STRING, message, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; } /** * gimp_message_get_handler: * * Returns the current state of where warning messages are displayed. * * This procedure returns the way g_message warnings are displayed. * They can be shown in a dialog box or printed on the console where * gimp was started. * * Returns: The current handler type. **/ GimpMessageHandlerType gimp_message_get_handler (void) { GimpParam *return_vals; gint nreturn_vals; GimpMessageHandlerType handler = 0; return_vals = gimp_run_procedure ("gimp-message-get-handler", &nreturn_vals, GIMP_PDB_END); if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS) handler = return_vals[1].data.d_int32; gimp_destroy_params (return_vals, nreturn_vals); return handler; } /** * gimp_message_set_handler: * @handler: The new handler type. * * Controls where warning messages are displayed. * * This procedure controls how g_message warnings are displayed. They * can be shown in a dialog box or printed on the console where gimp * was started. * * Returns: TRUE on success. **/ gboolean gimp_message_set_handler (GimpMessageHandlerType handler) { GimpParam *return_vals; gint nreturn_vals; gboolean success = TRUE; return_vals = gimp_run_procedure ("gimp-message-set-handler", &nreturn_vals, GIMP_PDB_INT32, handler, GIMP_PDB_END); success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS; gimp_destroy_params (return_vals, nreturn_vals); return success; }
gpl-3.0
lthall/Leonard_ardupilot
libraries/AP_Baro/AP_Baro_BMP388.h
1869
#pragma once #include <AP_HAL/AP_HAL.h> #include <AP_HAL/Device.h> #include <AP_HAL/utility/OwnPtr.h> #include "AP_Baro_Backend.h" #ifndef HAL_BARO_BMP388_I2C_ADDR #define HAL_BARO_BMP388_I2C_ADDR (0x76) #endif #ifndef HAL_BARO_BMP388_I2C_ADDR2 #define HAL_BARO_BMP388_I2C_ADDR2 (0x77) #endif class AP_Baro_BMP388 : public AP_Baro_Backend { public: AP_Baro_BMP388(AP_Baro &baro, AP_HAL::OwnPtr<AP_HAL::Device> _dev); /* AP_Baro public interface: */ void update() override; static AP_Baro_Backend *probe(AP_Baro &baro, AP_HAL::OwnPtr<AP_HAL::Device> _dev); private: bool init(void); void timer(void); void update_temperature(uint32_t); void update_pressure(uint32_t); AP_HAL::OwnPtr<AP_HAL::Device> dev; uint8_t instance; float pressure_sum; uint32_t pressure_count; float temperature; // Internal calibration registers struct PACKED { int16_t nvm_par_p1; // at 0x36 int16_t nvm_par_p2; int8_t nvm_par_p3; int8_t nvm_par_p4; int16_t nvm_par_p5; int16_t nvm_par_p6; int8_t nvm_par_p7; int8_t nvm_par_p8; int16_t nvm_par_p9; int8_t nvm_par_p10; int8_t nvm_par_p11; } calib_p; struct PACKED { uint16_t nvm_par_t1; // at 0x31 uint16_t nvm_par_t2; int8_t nvm_par_t3; } calib_t; // scaled calibration data struct { float par_t1; float par_t2; float par_t3; float par_p1; float par_p2; float par_p3; float par_p4; float par_p5; float par_p6; float par_p7; float par_p8; float par_p9; float par_p10; float par_p11; float t_lin; } calib; void scale_calibration_data(void); bool read_registers(uint8_t reg, uint8_t *data, uint8_t len); };
gpl-3.0
neos/typo3cr
Tests/Functional/Domain/Fixtures/HappyNode.php
665
<?php namespace Neos\ContentRepository\Tests\Functional\Domain\Fixtures; /* * This file is part of the Neos.ContentRepository package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\ContentRepository\Domain\Model\Node; /** * A happier node than the default node that can clap hands to show it! */ class HappyNode extends Node { /** * @return string */ public function clapsHands() { return $this->getName() . ' claps hands!'; } }
gpl-3.0
caoxiongkun/qgroundcontrol
src/CmdLineOptParser.cc
2813
/*===================================================================== QGroundControl Open Source Ground Control Station (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> This file is part of the QGROUNDCONTROL project QGROUNDCONTROL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>. ======================================================================*/ /// @file /// @brief Command line option parser /// /// @author Don Gagne <[email protected]> #include "CmdLineOptParser.h" #include <QString> /// @brief Implements a simple command line parser which sets booleans to true if the option is found. void ParseCmdLineOptions(int& argc, ///< count of arguments in argv char* argv[], ///< command line arguments CmdLineOpt_t* prgOpts, ///< command line options size_t cOpts, ///< count of command line options bool removeParsedOptions) ///< true: remove parsed option from argc/argv { // Start with all options off for (size_t iOption=0; iOption<cOpts; iOption++) { *prgOpts[iOption].optionFound = false; } for (int iArg=1; iArg<argc; iArg++) { for (size_t iOption=0; iOption<cOpts; iOption++) { bool found = false; QString arg(argv[iArg]); QString optionStr(prgOpts[iOption].optionStr); if (arg.startsWith(QString("%1:").arg(optionStr), Qt::CaseInsensitive)) { found = true; prgOpts[iOption].optionArg = arg.right(arg.length() - (optionStr.length() + 1)); } else if (arg.compare(optionStr, Qt::CaseInsensitive) == 0) { found = true; } if (found) { *prgOpts[iOption].optionFound = true; if (removeParsedOptions) { for (int iShift=iArg; iShift<argc-1; iShift++) { argv[iShift] = argv[iShift+1]; } argc--; iArg--; } } } } }
agpl-3.0
pesser/dealii
tests/bits/cone_01.cc
1753
// --------------------------------------------------------------------- // // Copyright (C) 2003 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // check ConeBoundary and GridGenerator::truncated_cone #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_boundary_lib.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_out.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/fe/mapping_c1.h> #include <fstream> template <int dim> void check () { Triangulation<dim> triangulation; GridGenerator::truncated_cone (triangulation); Point<dim> p1, p2; p1[0] = -1; p2[0] = 1; static const ConeBoundary<dim> boundary (1, 0.5, p1, p2); triangulation.set_boundary (0, boundary); triangulation.refine_global (2); GridOut().write_gnuplot (triangulation, deallog.get_file_stream()); } int main () { std::ofstream logfile("output"); deallog.attach(logfile); deallog.threshold_double(1.e-10); check<2> (); check<3> (); }
lgpl-2.1
nuclear-wizard/moose
framework/src/postprocessors/AreaPostprocessor.C
1109
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "AreaPostprocessor.h" registerMooseObject("MooseApp", AreaPostprocessor); defineLegacyParams(AreaPostprocessor); InputParameters AreaPostprocessor::validParams() { InputParameters params = SideIntegralPostprocessor::validParams(); params.addClassDescription("Computes the \"area\" or dimension - 1 \"volume\" of a given " "boundary or boundaries in your mesh."); return params; } AreaPostprocessor::AreaPostprocessor(const InputParameters & parameters) : SideIntegralPostprocessor(parameters) { } void AreaPostprocessor::threadJoin(const UserObject & y) { const AreaPostprocessor & pps = static_cast<const AreaPostprocessor &>(y); _integral_value += pps._integral_value; } Real AreaPostprocessor::computeQpIntegral() { return 1.0; }
lgpl-2.1
danielru/moose
python/PresentationBuilder/slidesets/MergeCoverSet.py
1395
# Import the SlideSet base class import math from ..slidesets import RemarkSlideSet ## # A special set of slides for creating cover page and contents class MergeCoverSet(RemarkSlideSet): ## # Extract the valid parameters for this object @staticmethod def validParams(): params = RemarkSlideSet.validParams() params.addRequiredParam('slide_sets', 'A vector of slideset names to combine into a single contents') return params def __init__(self, name, params, **kwargs): RemarkSlideSet.__init__(self, name, params) # The SlideSetWarehoue self.__warehouse = self.getParam('_warehouse') # Build a list of sets to merge self.__merge_list = self.getParam('slide_sets').split() ## # Search through all the slides in the specified slide sets for table of contents content def _extractContents(self): # print len(self.__merge_list) # print self.__merge_list # Count the number of contents entries contents = [] for obj in self.__warehouse.objects: if (obj is not self) and (len(self.__merge_list) == 0 or obj.name() in self.__merge_list): # print 'TUTORIAL_SUMMARY_COVER:', obj.name() pages = obj._extractContents() for page in pages: contents += page n = int(self.getParam('contents_items_per_slide')) output = [contents[i:i+n] for i in range(0, len(contents),n)] return output
lgpl-2.1
department-of-veterans-affairs/ChartReview
web-app/js/ext-5.1.0/src/view/MultiSelectorSearch.js
8477
/** * This component provides a grid holding selected items from a second store of potential * members. The `store` of this component represents the selected items. The `searchStore` * represents the potentially selected items. * * The default view defined by this class is intended to be easily replaced by deriving a * new class and overriding the appropriate methods. For example, the following is a very * different view that uses a date range and a data view: * * Ext.define('App.view.DateBoundSearch', { * extend: 'Ext.view.MultiSelectorSearch', * * makeDockedItems: function () { * return { * xtype: 'toolbar', * items: [{ * xtype: 'datefield', * emptyText: 'Start date...', * flex: 1 * },{ * xtype: 'datefield', * emptyText: 'End date...', * flex: 1 * }] * }; * }, * * makeItems: function () { * return [{ * xtype: 'dataview', * itemSelector: '.search-item', * selModel: 'rowselection', * store: this.store, * scrollable: true, * tpl: * '<tpl for=".">' + * '<div class="search-item">' + * '<img src="{icon}">' + * '<div>{name}</div>' + * '</div>' + * '</tpl>' * }]; * }, * * getSearchStore: function () { * return this.items.getAt(0).getStore(); * }, * * selectRecords: function (records) { * var view = this.items.getAt(0); * return view.getSelectionModel().select(records); * } * }); * * **Important**: This class assumes there are two components with specific `reference` * names assigned to them. These are `"searchField"` and `"searchGrid"`. These components * are produced by the `makeDockedItems` and `makeItems` method, respectively. When * overriding these it is important to remember to place these `reference` values on the * appropriate components. */ Ext.define('Ext.view.MultiSelectorSearch', { extend: 'Ext.panel.Panel', xtype: 'multiselector-search', layout: 'fit', floating: true, resizable: true, minWidth: 200, minHeight: 200, border: true, defaultListenerScope: true, referenceHolder: true, /** * @cfg {String} searchText * This text is displayed as the "emptyText" of the search `textfield`. */ searchText: 'Search...', initComponent: function () { var me = this, owner = me.owner, items = me.makeItems(), i, item, records, store; me.dockedItems = me.makeDockedItems(); me.items = items; store = Ext.data.StoreManager.lookup(me.store); for (i = items.length; i--; ) { if ((item = items[i]).xtype === 'grid') { item.store = store; item.isSearchGrid = true; item.selModel = item.selModel || { type: 'checkboxmodel', pruneRemoved: false, listeners: { selectionchange: 'onSelectionChange' } }; Ext.merge(item, me.grid); if (!item.columns) { item.hideHeaders = true; item.columns = [{ flex: 1, dataIndex: me.field }]; } break; } } me.callParent(); records = me.getOwnerStore().getRange(); if (!owner.convertSelectionRecord.$nullFn) { for (i = records.length; i--; ) { records[i] = owner.convertSelectionRecord(records[i]); } } if (store.isLoading() || (store.loadCount === 0 && !store.getCount())) { store.on('load', function() { if (!me.isDestroyed) { me.selectRecords(records); } }, null, {single: true}); } else { me.selectRecords(records); } }, getOwnerStore: function() { return this.owner.getStore(); }, afterShow: function () { var searchField = this.lookupReference('searchField'); this.callParent(arguments); if (searchField) { searchField.focus(); } }, /** * Returns the store that holds search results. By default this comes from the * "search grid". If this aspect of the view is changed sufficiently so that the * search grid cannot be found, this method should be overridden to return the proper * store. * @return {Ext.data.Store} */ getSearchStore: function () { var searchGrid = this.lookupReference('searchGrid'); return searchGrid.getStore(); }, makeDockedItems: function () { return [{ xtype: 'textfield', reference: 'searchField', dock: 'top', hideFieldLabel: true, emptyText: this.searchText, triggers: { clear: { cls: Ext.baseCSSPrefix + 'form-clear-trigger', handler: 'onClearSearch', hidden: true } }, listeners: { change: 'onSearchChange', buffer: 300 } }]; }, makeItems: function () { return [{ xtype: 'grid', reference: 'searchGrid', trailingBufferZone: 2, leadingBufferZone: 2, viewConfig: { deferEmptyText: false, emptyText: 'No results.' } }]; }, selectRecords: function (records) { var searchGrid = this.lookupReference('searchGrid'); return searchGrid.getSelectionModel().select(records); }, deselectRecords: function(records) { var searchGrid = this.lookupReference('searchGrid'); return searchGrid.getSelectionModel().deselect(records); }, search: function (text) { var me = this, filter = me.searchFilter, filters = me.getSearchStore().getFilters(); if (text) { filters.beginUpdate(); if (filter) { filter.setValue(text); } else { me.searchFilter = filter = new Ext.util.Filter({ id: 'search', property: me.field, value: text }); } filters.add(filter); filters.endUpdate(); } else if (filter) { filters.remove(filter); } }, privates: { onClearSearch: function () { var searchField = this.lookupReference('searchField'); searchField.setValue(null); searchField.focus(); }, onSearchChange: function (searchField) { var value = searchField.getValue(), trigger = searchField.getTrigger('clear'); trigger.setHidden(!value); this.search(value); }, onSelectionChange: function (selModel, selection) { var owner = this.owner, store = owner.getStore(), data = store.data, remove = 0, map = {}, add, i, id, record; for (i = selection.length; i--; ) { record = selection[i]; id = record.id; map[id] = record; if (!data.containsKey(id)) { (add || (add = [])).push(owner.convertSearchRecord(record)); } } for (i = data.length; i--; ) { record = data.getAt(i); if (!map[record.id]) { (remove || (remove = [])).push(record); } } if (add || remove) { data.splice(data.length, remove, add); } } } });
apache-2.0
begoldsm/azure-sdk-for-node
test/services/blob/blobservice-tests.js
59746
// // Copyright (c) Microsoft and contributors. 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. // var assert = require('assert'); var fs = require('fs'); var path = require('path'); var util = require('util'); var sinon = require('sinon'); var url = require('url'); var request = require('request'); // Test includes var testutil = require('../../util/util'); var blobtestutil = require('../../framework/blob-test-utils'); // Lib includes var common = require('azure-common'); var storage = testutil.libRequire('services/legacyStorage'); var azureutil = common.util; var azure = testutil.libRequire('azure'); var WebResource = common.WebResource; var SharedAccessSignature = storage.SharedAccessSignature; var BlobService = storage.BlobService; var ServiceClient = common.ServiceClient; var ExponentialRetryPolicyFilter = common.ExponentialRetryPolicyFilter; var Constants = common.Constants; var BlobConstants = Constants.BlobConstants; var HttpConstants = Constants.HttpConstants; var ServiceClientConstants = common.ServiceClientConstants; var QueryStringConstants = Constants.QueryStringConstants; var containerNames = []; var containerNamesPrefix = 'cont'; var blobNames = []; var blobNamesPrefix = 'blob'; var testPrefix = 'blobservice-tests'; var blobService; var suiteUtil; describe('BlobService', function () { before(function (done) { blobService = storage.createBlobService() .withFilter(new common.ExponentialRetryPolicyFilter()); suiteUtil = blobtestutil.createBlobTestUtils(blobService, testPrefix); suiteUtil.setupSuite(done); }); after(function (done) { suiteUtil.teardownSuite(done); }); beforeEach(function (done) { suiteUtil.setupTest(done); }); afterEach(function (done) { suiteUtil.teardownTest(done); }); describe('createContainer', function () { it('should detect incorrect container names', function (done) { assert.throws(function () { blobService.createContainer(null, function () { }); }, BlobService.incorrectContainerNameErr); assert.throws(function () { blobService.createContainer('', function () { }); }, BlobService.incorrectContainerNameErr); assert.throws(function () { blobService.createContainer('as', function () { }); }, BlobService.incorrectContainerNameFormatErr); assert.throws(function () { blobService.createContainer('a--s', function () { }); }, BlobService.incorrectContainerNameFormatErr); assert.throws(function () { blobService.createContainer('cont-', function () { }); }, BlobService.incorrectContainerNameFormatErr); assert.throws(function () { blobService.createContainer('conTain', function () { }); }, BlobService.incorrectContainerNameFormatErr); done(); }); it('should work', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); blobService.createContainer(containerName, function (createError, container1, createContainerResponse) { assert.equal(createError, null); assert.notEqual(container1, null); if (container1) { assert.notEqual(container1.name, null); assert.notEqual(container1.etag, null); assert.notEqual(container1.lastModified, null); } assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created); // creating again will result in a duplicate error blobService.createContainer(containerName, function (createError2, container2) { assert.equal(createError2.code, Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS); assert.equal(container2, null); done(); }); }); }); }); describe('blobExists', function () { it('should detect incorrect blob names', function (done) { assert.throws(function () { blobService.blobExists('container', null, function () { }); }, BlobService.incorrectBlobNameFormatErr); assert.throws(function () { blobService.blobExists('container', '', function () { }); }, BlobService.incorrectBlobNameFormatErr); done(); }); }); describe('getServiceProperties', function () { it('should get blob service properties', function (done) { blobService.getServiceProperties(function (error, serviceProperties) { assert.equal(error, null); assert.notEqual(serviceProperties, null); if (serviceProperties) { assert.notEqual(serviceProperties.Logging, null); if (serviceProperties.Logging) { assert.notEqual(serviceProperties.Logging.RetentionPolicy); assert.notEqual(serviceProperties.Logging.Version); } if (serviceProperties.Metrics) { assert.notEqual(serviceProperties.Metrics, null); assert.notEqual(serviceProperties.Metrics.RetentionPolicy); assert.notEqual(serviceProperties.Metrics.Version); } } done(); }); }); }); describe('getServiceProperties', function () { it('should set blob service properties', function (done) { blobService.getServiceProperties(function (error, serviceProperties) { assert.equal(error, null); serviceProperties.DefaultServiceVersion = '2009-09-19'; serviceProperties.Logging.Read = true; blobService.setServiceProperties(serviceProperties, function (error2) { assert.equal(error2, null); blobService.getServiceProperties(function (error3, serviceProperties2) { assert.equal(error3, null); assert.equal(serviceProperties2.DefaultServiceVersion, '2009-09-19'); assert.equal(serviceProperties2.Logging.Read, true); done(); }); }); }); }); }); describe('listContainers', function () { it('should work', function (done) { var containerName1 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var metadata1 = { color: 'orange', containernumber: '01', somemetadataname: 'SomeMetadataValue' }; var containerName2 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var metadata2 = { color: 'pink', containernumber: '02', somemetadataname: 'SomeMetadataValue' }; var containerName3 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var metadata3 = { color: 'brown', containernumber: '03', somemetadataname: 'SomeMetadataValue' }; var containerName4 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var metadata4 = { color: 'blue', containernumber: '04', somemetadataname: 'SomeMetadataValue' }; var validateContainers = function (containers, entries) { containers.forEach(function (container) { if (container.name == containerName1) { assert.equal(container.metadata.color, metadata1.color); assert.equal(container.metadata.containernumber, metadata1.containernumber); assert.equal(container.metadata.somemetadataname, metadata1.somemetadataname); entries.push(container.name); } else if (container.name == containerName2) { assert.equal(container.metadata.color, metadata2.color); assert.equal(container.metadata.containernumber, metadata2.containernumber); assert.equal(container.metadata.somemetadataname, metadata2.somemetadataname); entries.push(container.name); } else if (container.name == containerName3) { assert.equal(container.metadata.color, metadata3.color); assert.equal(container.metadata.containernumber, metadata3.containernumber); assert.equal(container.metadata.somemetadataname, metadata3.somemetadataname); entries.push(container.name); } else if (container.name == containerName4) { assert.equal(container.metadata.color, metadata4.color); assert.equal(container.metadata.containernumber, metadata4.containernumber); assert.equal(container.metadata.somemetadataname, metadata4.somemetadataname); entries.push(container.name); } }); return entries; }; blobService.createContainer(containerName1, { metadata: metadata1 }, function (createError1, createContainer1, createResponse1) { assert.equal(createError1, null); assert.notEqual(createContainer1, null); assert.ok(createResponse1.isSuccessful); blobService.createContainer(containerName2, { metadata: metadata2 }, function (createError2, createContainer2, createResponse2) { assert.equal(createError2, null); assert.notEqual(createContainer2, null); assert.ok(createResponse2.isSuccessful); blobService.createContainer(containerName3, { metadata: metadata3 }, function (createError3, createContainer3, createResponse3) { assert.equal(createError3, null); assert.notEqual(createContainer3, null); assert.ok(createResponse3.isSuccessful); blobService.createContainer(containerName4, { metadata: metadata4 }, function (createError4, createContainer4, createResponse4) { assert.equal(createError4, null); assert.notEqual(createContainer4, null); assert.ok(createResponse4.isSuccessful); var options = { 'maxresults': 3, 'include': 'metadata' }; blobService.listContainers(options, function (listError, containers, containersContinuation, listResponse) { assert.equal(listError, null); assert.ok(listResponse.isSuccessful); assert.equal(containers.length, 3); var entries = validateContainers(containers, []); assert.equal(containersContinuation.hasNextPage(), true); containersContinuation.getNextPage(function (listErrorContinuation, containers2) { assert.equal(listErrorContinuation, null); assert.ok(listResponse.isSuccessful); validateContainers(containers2, entries); assert.equal(entries.length, 4); done(); }); }); }); }); }); }); }); it('should work with optional parameters', function (done) { blobService.listContainers(null, function (err) { assert.equal(err, null); done(); }); }); it('should work with prefix parameter', function (done) { blobService.listContainers({ prefix : '中文' }, function (err) { assert.equal(err, null); done(); }); }); }); describe('createContainerIfNotExists', function() { it('should create a container if not exists', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); blobService.createContainer(containerName, function (createError, container1, createContainerResponse) { assert.equal(createError, null); assert.notEqual(container1, null); if (container1) { assert.notEqual(container1.name, null); assert.notEqual(container1.etag, null); assert.notEqual(container1.lastModified, null); } assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created); // creating again will result in a duplicate error blobService.createContainerIfNotExists(containerName, function (createError2, isCreated) { assert.equal(createError2, null); assert.equal(isCreated, false); done(); }); }); }); it('should throw if called with a callback', function (done) { assert.throws(function () { blobService.createContainerIfNotExists('name'); }, Error ); done(); }); }); describe('container', function () { var containerName; var metadata; beforeEach(function (done) { containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); metadata = { color: 'blue' }; blobService.createContainer(containerName, { metadata: metadata }, done); }); describe('getContainerProperties', function () { it('should work', function (done) { blobService.getContainerProperties(containerName, function (getError, container2, getResponse) { assert.equal(getError, null); assert.notEqual(container2, null); if (container2) { assert.equal('unlocked', container2.leaseStatus); assert.equal('available', container2.leaseState); assert.equal(null, container2.leaseDuration); assert.notEqual(null, container2.requestId); assert.equal(container2.metadata.color, metadata.color); } assert.notEqual(getResponse, null); assert.equal(getResponse.isSuccessful, true); done(); }); }); }); describe('setContainerMetadata', function () { it('should work', function (done) { var metadata = { 'class': 'test' }; blobService.setContainerMetadata(containerName, metadata, function (setMetadataError, setMetadataResponse) { assert.equal(setMetadataError, null); assert.ok(setMetadataResponse.isSuccessful); blobService.getContainerMetadata(containerName, function (getMetadataError, containerMetadata, getMetadataResponse) { assert.equal(getMetadataError, null); assert.notEqual(containerMetadata, null); assert.notEqual(containerMetadata.metadata, null); if (containerMetadata.metadata) { assert.equal(containerMetadata.metadata.class, 'test'); } assert.ok(getMetadataResponse.isSuccessful); done(); }); }); }); }); describe('getContainerAcl', function () { it('should work', function (done) { blobService.getContainerAcl(containerName, function (containerAclError, containerBlob, containerAclResponse) { assert.equal(containerAclError, null); assert.notEqual(containerBlob, null); if (containerBlob) { assert.equal(containerBlob.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.OFF); } assert.equal(containerAclResponse.isSuccessful, true); done(); }); }); }); describe('setContainerAcl', function () { it('should work', function (done) { blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.BLOB, function (setAclError, setAclContainer1, setResponse1) { assert.equal(setAclError, null); assert.notEqual(setAclContainer1, null); assert.ok(setResponse1.isSuccessful); blobService.getContainerAcl(containerName, function (getAclError, getAclContainer1, getResponse1) { assert.equal(getAclError, null); assert.notEqual(getAclContainer1, null); if (getAclContainer1) { assert.equal(getAclContainer1.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.BLOB); } assert.ok(getResponse1.isSuccessful); blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.CONTAINER, function (setAclError2, setAclContainer2, setResponse2) { assert.equal(setAclError2, null); assert.notEqual(setAclContainer2, null); assert.ok(setResponse2.isSuccessful); setTimeout(function () { blobService.getContainerAcl(containerName, function (getAclError2, getAclContainer2, getResponse3) { assert.equal(getAclError2, null); assert.notEqual(getAclContainer2, null); if (getAclContainer2) { assert.equal(getAclContainer2.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.CONTAINER); } assert.ok(getResponse3.isSuccessful); done(); }); }, (suiteUtil.isMocked && !suiteUtil.isRecording) ? 0 : 5000); }); }); }); }); it('should work with policies', function (done) { var readWriteStartDate = new Date(Date.UTC(2012, 10, 10)); var readWriteExpiryDate = new Date(readWriteStartDate); readWriteExpiryDate.setMinutes(readWriteStartDate.getMinutes() + 10); readWriteExpiryDate.setMilliseconds(999); var readWriteSharedAccessPolicy = { Id: 'readwrite', AccessPolicy: { Start: readWriteStartDate, Expiry: readWriteExpiryDate, Permissions: 'rw' } }; var readSharedAccessPolicy = { Id: 'read', AccessPolicy: { Expiry: readWriteStartDate, Permissions: 'r' } }; var options = {}; options.signedIdentifiers = [readWriteSharedAccessPolicy, readSharedAccessPolicy]; blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.BLOB, options, function (setAclError, setAclContainer1, setResponse1) { assert.equal(setAclError, null); assert.notEqual(setAclContainer1, null); assert.ok(setResponse1.isSuccessful); blobService.getContainerAcl(containerName, function (getAclError, getAclContainer1, getResponse1) { assert.equal(getAclError, null); assert.notEqual(getAclContainer1, null); if (getAclContainer1) { assert.equal(getAclContainer1.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.BLOB); assert.equal(getAclContainer1.signedIdentifiers[0].AccessPolicy.Expiry.getTime(), readWriteExpiryDate.getTime()); } assert.ok(getResponse1.isSuccessful); blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.CONTAINER, function (setAclError2, setAclContainer2, setResponse2) { assert.equal(setAclError2, null); assert.notEqual(setAclContainer2, null); assert.ok(setResponse2.isSuccessful); blobService.getContainerAcl(containerName, function (getAclError2, getAclContainer2, getResponse3) { assert.equal(getAclError2, null); assert.notEqual(getAclContainer2, null); if (getAclContainer2) { assert.equal(getAclContainer2.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.CONTAINER); } assert.ok(getResponse3.isSuccessful); done(); }); }); }); }); }); it('should work with signed identifiers', function (done) { var options = {}; options.signedIdentifiers = [ { Id: 'id1', AccessPolicy: { Start: '2009-10-10T00:00:00.123Z', Expiry: '2009-10-11T00:00:00.456Z', Permissions: 'r' } }, { Id: 'id2', AccessPolicy: { Start: '2009-11-10T00:00:00.006Z', Expiry: '2009-11-11T00:00:00.4Z', Permissions: 'w' } }]; blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.OFF, options, function (setAclError, setAclContainer, setAclResponse) { assert.equal(setAclError, null); assert.notEqual(setAclContainer, null); assert.ok(setAclResponse.isSuccessful); blobService.getContainerAcl(containerName, function (getAclError, containerAcl, getAclResponse) { assert.equal(getAclError, null); assert.notEqual(containerAcl, null); assert.notEqual(getAclResponse, null); if (getAclResponse) { assert.equal(getAclResponse.isSuccessful, true); } var entries = 0; if (containerAcl) { if (containerAcl.signedIdentifiers) { containerAcl.signedIdentifiers.forEach(function (identifier) { if (identifier.Id === 'id1') { assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-10-10T00:00:00.123Z').getTime()); assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-10-11T00:00:00.456Z').getTime()); assert.equal(identifier.AccessPolicy.Permission, 'r'); entries += 1; } else if (identifier.Id === 'id2') { assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-11-10T00:00:00.006Z').getTime()); assert.equal(identifier.AccessPolicy.Start.getMilliseconds(), 6); assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-11-11T00:00:00.4Z').getTime()); assert.equal(identifier.AccessPolicy.Expiry.getMilliseconds(), 400); assert.equal(identifier.AccessPolicy.Permission, 'w'); entries += 2; } }); } } assert.equal(entries, 3); done(); }); }); }); }); describe('createBlockBlobFromText', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText = 'Hello World'; blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) { assert.equal(uploadError, null); assert.ok(uploadResponse.isSuccessful); blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) { assert.equal(downloadErr, null); assert.equal(blobTextResponse, blobText); done(); }); }); }); }); describe('createBlobSnapshot', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText = 'Hello World'; blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, putResponse) { assert.equal(uploadError, null); assert.notEqual(putResponse, null); if (putResponse) { assert.ok(putResponse.isSuccessful); } blobService.createBlobSnapshot(containerName, blobName, function (snapshotError, snapshotId, snapshotResponse) { assert.equal(snapshotError, null); assert.notEqual(snapshotResponse, null); assert.notEqual(snapshotId, null); if (snapshotResponse) { assert.ok(snapshotResponse.isSuccessful); } blobService.getBlobToText(containerName, blobName, function (getError, content, blockBlob, getResponse) { assert.equal(getError, null); assert.notEqual(blockBlob, null); assert.notEqual(getResponse, null); if (getResponse) { assert.ok(getResponse.isSuccessful); } assert.equal(blobText, content); done(); }); }); }); }); }); describe('acquireLease', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText = 'hello'; blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) { assert.equal(uploadError, null); assert.notEqual(blob, null); assert.ok(uploadResponse.isSuccessful); // Acquire a lease blobService.acquireLease(containerName, blobName, function (leaseBlobError, lease, leaseBlobResponse) { assert.equal(leaseBlobError, null); assert.notEqual(lease, null); if (lease) { assert.ok(lease.id); } assert.notEqual(leaseBlobResponse, null); if (leaseBlobResponse) { assert.ok(leaseBlobResponse.isSuccessful); } // Second lease should not be possible blobService.acquireLease(containerName, blobName, function (secondLeaseBlobError, secondLease, secondLeaseBlobResponse) { assert.equal(secondLeaseBlobError.code, 'LeaseAlreadyPresent'); assert.equal(secondLease, null); assert.equal(secondLeaseBlobResponse.isSuccessful, false); // Delete should not be possible blobService.deleteBlob(containerName, blobName, function (deleteError, deleted, deleteResponse) { assert.equal(deleteError.code, 'LeaseIdMissing'); assert.equal(deleteResponse.isSuccessful, false); done(); }); }); }); }); }); }); describe('getBlobProperties', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var metadata = { color: 'blue' }; blobService.createBlockBlobFromText(containerName, blobName, 'hello', { metadata: metadata }, function (blobErr) { assert.equal(blobErr, null); blobService.getBlobProperties(containerName, blobName, function (getErr, blob) { assert.equal(getErr, null); assert.notEqual(blob, null); if (blob) { assert.notEqual(blob.metadata, null); if (blob.metadata) { assert.equal(blob.metadata.color, metadata.color); } } done(); }); }); }); }); describe('setBlobProperties', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var text = 'hello'; blobService.createBlockBlobFromText(containerName, blobName, text, function (blobErr) { assert.equal(blobErr, null); var options = {}; options.contentType = 'text'; options.contentEncoding = 'utf8'; options.contentLanguage = 'pt'; options.cacheControl = 'true'; blobService.setBlobProperties(containerName, blobName, options, function (setErr) { assert.equal(setErr, null); blobService.getBlobProperties(containerName, blobName, function (getErr, blob) { assert.equal(getErr, null); assert.notEqual(blob, null); if (blob) { assert.equal(blob.contentLength, text.length); assert.equal(blob.contentType, options.contentType); assert.equal(blob.contentEncoding, options.contentEncoding); assert.equal(blob.contentLanguage, options.contentLanguage); assert.equal(blob.cacheControl, options.cacheControl); } done(); }); }); }); }); }); describe('getBlobMetadata', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var metadata = { color: 'blue' }; blobService.createBlockBlobFromText(containerName, blobName, 'hello', { metadata: metadata }, function (blobErr) { assert.equal(blobErr, null); blobService.getBlobMetadata(containerName, blobName, function (getErr, blob) { assert.equal(getErr, null); assert.notEqual(blob, null); if (blob) { assert.notEqual(blob.metadata, null); if (blob.metadata) { assert.equal(blob.metadata.color, metadata.color); } } done(); }); }); }); }); describe('pageBlob', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var data1 = 'Hello, World!' + repeat(' ', 1024 - 13); var data2 = 'Hello, World!' + repeat(' ', 512 - 13); // Create the empty page blob blobService.createPageBlob(containerName, blobName, 1024, function (err) { assert.equal(err, null); // Upload all data blobService.createBlobPagesFromText(containerName, blobName, data1, 0, 1023, function (err2) { assert.equal(err2, null); // Verify contents blobService.getBlobToText(containerName, blobName, function (err3, content1) { assert.equal(err3, null); assert.equal(content1, data1); // Clear the page blob blobService.clearBlobPages(containerName, blobName, 0, 1023, function (err4) { assert.equal(err4); // Upload other data in 2 pages blobService.createBlobPagesFromText(containerName, blobName, data2, 0, 511, function (err5) { assert.equal(err5, null); blobService.createBlobPagesFromText(containerName, blobName, data2, 512, 1023, function (err6) { assert.equal(err6, null); blobService.getBlobToText(containerName, blobName, function (err7, content2) { assert.equal(err7, null); assert.equal(data2 + data2, content2); done(); }); }); }); }); }); }); }); }); }); describe('createBlockBlobFromText', function () { it('should work with access condition', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText = 'hello'; blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error2) { assert.equal(error2, null); blobService.getBlobProperties(containerName, blobName, function (error4, blobProperties) { assert.equal(error4, null); var options = { accessConditions: { 'if-none-match': blobProperties.etag} }; blobService.createBlockBlobFromText(containerName, blobName, blobText, options, function (error3) { assert.notEqual(error3, null); assert.equal(error3.code, Constants.StorageErrorCodeStrings.CONDITION_NOT_MET); done(); }); }); }); }); it('should work for small size from file', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked) + ' a'; var blobText = 'Hello World'; blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blobResponse, uploadResponse) { assert.equal(uploadError, null); assert.notEqual(blobResponse, null); assert.ok(uploadResponse.isSuccessful); blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) { assert.equal(downloadErr, null); assert.equal(blobTextResponse, blobText); done(); }); }); }); }); describe('getBlobRange', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var data1 = 'Hello, World!'; // Create the empty page blob blobService.createBlockBlobFromText(containerName, blobName, data1, function (err) { assert.equal(err, null); blobService.getBlobToText(containerName, blobName, { rangeStart: 2, rangeEnd: 3 }, function (err3, content1) { assert.equal(err3, null); // get the double ll's in the hello assert.equal(content1, 'll'); done(); }); }); }); }); describe('getBlobRangeOpenEnded', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var data1 = 'Hello, World!'; // Create the empty page blob blobService.createBlockBlobFromText(containerName, blobName, data1, function (err) { assert.equal(err, null); blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1) { assert.equal(err3, null); // get the last bytes from the message assert.equal(content1, 'llo, World!'); done(); }); }); }); }); describe('setBlobMime', function () { it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var fileNameSource = testutil.generateId('file') + '.bmp'; // fake bmp file with text... var blobText = 'Hello World!'; fs.writeFile(fileNameSource, blobText, function () { // Create the empty page blob var blobOptions = {blockIdPrefix : 'blockId' }; blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (err) { assert.equal(err, null); blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1, blob) { assert.equal(err3, null); // get the last bytes from the message assert.equal(content1, 'llo World!'); assert.ok(blob.contentType === 'image/bmp' || blob.contentType === 'image/x-ms-bmp'); fs.unlink(fileNameSource, function () { done(); }); }); }); }); }); it('should work with skip', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var fileNameSource = testutil.generateId('prefix') + '.bmp'; // fake bmp file with text... var blobText = 'Hello World!'; fs.writeFile(fileNameSource, blobText, function () { // Create the empty page blob blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, { contentType: null, contentTypeHeader: null, blockIdPrefix : 'blockId' }, function (err) { assert.equal(err, null); blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1, blob) { assert.equal(err3, null); // get the last bytes from the message assert.equal(content1, 'llo World!'); assert.equal(blob.contentType, 'application/octet-stream'); fs.unlink(fileNameSource, function () { done(); }); }); }); }); }); }); }); describe('copyBlob', function () { it('should work', function (done) { var sourceContainerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var targetContainerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var sourceBlobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var targetBlobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText = 'hi there'; blobService.createContainer(sourceContainerName, function (createErr1) { assert.equal(createErr1, null); blobService.createContainer(targetContainerName, function (createErr2) { assert.equal(createErr2, null); blobService.createBlockBlobFromText(sourceContainerName, sourceBlobName, blobText, function (uploadErr) { assert.equal(uploadErr, null); blobService.copyBlob(blobService.getBlobUrl(sourceContainerName, sourceBlobName), targetContainerName, targetBlobName, function (copyErr) { assert.equal(copyErr, null); blobService.getBlobToText(targetContainerName, targetBlobName, function (downloadErr, text) { assert.equal(downloadErr, null); assert.equal(text, blobText); done(); }); }); }); }); }); }); }); describe('listBlobs', function () { var containerName; beforeEach(function (done) { containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); blobService.createContainer(containerName, done); }); it('should work', function (done) { var blobName1 = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobName2 = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText1 = 'hello1'; var blobText2 = 'hello2'; // Test listing 0 blobs blobService.listBlobs(containerName, function (listErrNoBlobs, listNoBlobs) { assert.equal(listErrNoBlobs, null); assert.notEqual(listNoBlobs, null); if (listNoBlobs) { assert.equal(listNoBlobs.length, 0); } blobService.createBlockBlobFromText(containerName, blobName1, blobText1, function (blobErr1) { assert.equal(blobErr1, null); // Test listing 1 blob blobService.listBlobs(containerName, function (listErr, listBlobs) { assert.equal(listErr, null); assert.notEqual(listBlobs, null); assert.equal(listBlobs.length, 1); blobService.createBlockBlobFromText(containerName, blobName2, blobText2, function (blobErr2) { assert.equal(blobErr2, null); // Test listing multiple blobs blobService.listBlobs(containerName, function (listErr2, listBlobs2) { assert.equal(listErr2, null); assert.notEqual(listBlobs2, null); if (listBlobs2) { assert.equal(listBlobs2.length, 2); var entries = 0; listBlobs2.forEach(function (blob) { if (blob.name === blobName1) { entries += 1; } else if (blob.name === blobName2) { entries += 2; } }); assert.equal(entries, 3); } blobService.createBlobSnapshot(containerName, blobName1, function (snapErr) { assert.equal(snapErr, null); // Test listing without requesting snapshots blobService.listBlobs(containerName, function (listErr3, listBlobs3) { assert.equal(listErr3, null); assert.notEqual(listBlobs3, null); if (listBlobs3) { assert.equal(listBlobs3.length, 2); } // Test listing including snapshots blobService.listBlobs(containerName, { include: BlobConstants.BlobListingDetails.SNAPSHOTS }, function (listErr4, listBlobs4) { assert.equal(listErr4, null); assert.notEqual(listBlobs4, null); if (listBlobs3) { assert.equal(listBlobs4.length, 3); } done(); }); }); }); }); }); }); }); }); }); }); describe('getPageRegions', function () { var containerName; beforeEach(function (done) { containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); blobService.createContainer(containerName, done); }); it('should work', function (done) { var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var data = 'Hello, World!' + repeat(' ', 512 - 13); // Upload contents in 2 parts blobService.createPageBlob(containerName, blobName, 1024 * 1024 * 1024, function (err) { assert.equal(err, null); // Upload all data blobService.createBlobPagesFromText(containerName, blobName, data, 0, 511, function (err2) { assert.equal(err2, null); // Only one region present blobService.listBlobRegions(containerName, blobName, 0, null, function (error, regions) { assert.equal(error, null); assert.notEqual(regions, null); if (regions) { assert.equal(regions.length, 1); var entries = 0; regions.forEach(function (region) { if (region.start === 0) { assert.equal(region.end, 511); entries += 1; } }); assert.equal(entries, 1); } blobService.createBlobPagesFromText(containerName, blobName, data, 1048576, 1049087, null, function (err3) { assert.equal(err3, null); // Get page regions blobService.listBlobRegions(containerName, blobName, 0, null, function (error5, regions) { assert.equal(error5, null); assert.notEqual(regions, null); if (regions) { assert.equal(regions.length, 2); var entries = 0; regions.forEach(function (region) { if (region.start === 0) { assert.equal(region.end, 511); entries += 1; } else if (region.start === 1048576) { assert.equal(region.end, 1049087); entries += 2; } }); assert.equal(entries, 3); } done(); }); }); }); }); }); }); }); it('CreateBlobWithBars', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = 'blobs/' + testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobText = 'Hello World!'; blobService.createContainer(containerName, function (createError) { assert.equal(createError, null); // Create the empty page blob blobService.createBlockBlobFromText(containerName, blobName, blobText, function (err) { assert.equal(err, null); blobService.getBlobProperties(containerName, blobName, function (error, properties) { assert.equal(error, null); assert.equal(properties.container, containerName); assert.equal(properties.blob, blobName); done(); }); }); }); }); it('works with files without specifying content type', function (done) { // This test ensures that blocks can be created from files correctly // and was created to ensure that the request module does not magically add // a content type to the request when the user did not specify one. var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var fileName= testutil.generateId('prefix') + '.txt'; var blobText = 'Hello World!'; try { fs.unlinkSync(fileName); } catch (e) {} fs.writeFileSync(fileName, blobText); var stat = fs.statSync(fileName); blobService.createContainer(containerName, function (createErr1) { assert.equal(createErr1, null); blobService.createBlobBlockFromStream('test', containerName, blobName, fs.createReadStream(fileName), stat.size, function (error) { try { fs.unlinkSync(fileName); } catch (e) {} assert.equal(error, null); done(); }); }); }); it('CommitBlockList', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); blobService.createContainer(containerName, function (error) { assert.equal(error, null); blobService.createBlobBlockFromText('id1', containerName, blobName, 'id1', function (error2) { assert.equal(error2, null); blobService.createBlobBlockFromText('id2', containerName, blobName, 'id2', function (error3) { assert.equal(error3, null); var blockList = { LatestBlocks: ['id1'], UncommittedBlocks: ['id2'] }; blobService.commitBlobBlocks(containerName, blobName, blockList, function (error4) { assert.equal(error4, null); blobService.listBlobBlocks(containerName, blobName, BlobConstants.BlockListFilter.ALL, function (error5, list) { assert.equal(error5, null); assert.notEqual(list, null); assert.notEqual(list.CommittedBlocks, null); assert.equal(list.CommittedBlocks.length, 2); done(); }); }); }); }); }); }); describe('shared access signature', function () { describe('getBlobUrl', function () { it('should work', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80'); var blobUrl = blobServiceassert.getBlobUrl(containerName); assert.equal(blobUrl, 'https://host.com:80/' + containerName); blobUrl = blobServiceassert.getBlobUrl(containerName, blobName); assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName); done(); }); it('should work with shared access policy', function (done) { var containerName = 'container'; var blobName = 'blob'; var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80'); var sharedAccessPolicy = { AccessPolicy: { Expiry: new Date('October 12, 2011 11:53:40 am GMT') } }; var blobUrl = blobServiceassert.getBlobUrl(containerName, blobName, sharedAccessPolicy); assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName + '?se=2011-10-12T11%3A53%3A40Z&sr=b&sv=2012-02-12&sig=gDOuwDoa4F7hhQJW9ReCimoHN2qp7NF1Nu3sdHjwIfs%3D'); done(); }); it('should work with container acl permissions and spaces in name', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked) + ' foobar'; var blobText = 'Hello World'; var fileNameSource = testutil.generateId('prefix') + '.txt'; // fake bmp file with text... blobService.createContainer(containerName, function (err) { assert.equal(err, null); var startTime = new Date('April 15, 2013 11:53:40 am GMT'); var readWriteSharedAccessPolicy = { Id: 'readwrite', AccessPolicy: { Start: startTime, Permissions: 'rwdl' } }; blobService.setContainerAcl(containerName, null, { signedIdentifiers: [ readWriteSharedAccessPolicy ] }, function (err) { assert.equal(err, null); blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) { assert.equal(uploadError, null); assert.ok(uploadResponse.isSuccessful); var blobUrl = blobService.getBlobUrl(containerName, blobName, { Id: 'readwrite', AccessPolicy: { Expiry: new Date('April 15, 2099 11:53:40 am GMT') } }); function responseCallback(err, rsp) { assert.equal(rsp.statusCode, 200); assert.equal(err, null); fs.unlink(fileNameSource, done); } request.get(blobUrl, responseCallback).pipe(fs.createWriteStream(fileNameSource)); }); }); }); }); it('should work with container acl permissions', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var fileNameSource = testutil.generateId('prefix') + '.bmp'; // fake bmp file with text... var blobText = 'Hello World!'; blobService.createContainer(containerName, function (error) { assert.equal(error, null); var startTime = new Date('April 15, 2013 11:53:40 am GMT'); var readWriteSharedAccessPolicy = { Id: 'readwrite', AccessPolicy: { Start: startTime, Permissions: 'rwdl' } }; blobService.setContainerAcl(containerName, null, { signedIdentifiers: [ readWriteSharedAccessPolicy ] }, function (err) { assert.equal(err, null); blobService.createBlockBlobFromText(containerName, blobName, blobText, function (err) { assert.equal(err, null); var blobUrl = blobService.getBlobUrl(containerName, blobName, { Id: 'readwrite', AccessPolicy: { Expiry: new Date('April 15, 2099 11:53:40 am GMT') } }); function responseCallback(err, rsp) { assert.equal(rsp.statusCode, 200); assert.equal(err, null); fs.unlink(fileNameSource, done); } request.get(blobUrl, responseCallback).pipe(fs.createWriteStream(fileNameSource)); }); }); }); }); it('should work with duration', function (done) { var containerName = 'container'; var blobName = 'blob'; var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80'); // Mock Date just to ensure a fixed signature this.clock = sinon.useFakeTimers(0); var sharedAccessPolicy = { AccessPolicy: { Expiry: storage.date.minutesFromNow(10) } }; this.clock.restore(); var blobUrl = blobServiceassert.getBlobUrl(containerName, blobName, sharedAccessPolicy); assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName + '?se=1970-01-01T00%3A10%3A00Z&sr=b&sv=2012-02-12&sig=ca700zLsjqapO1sUBVHIBblj2XoJCON1V4gMSfyQZc8%3D'); done(); }); }); it('GenerateSharedAccessSignature', function (done) { var containerName = 'images'; var blobName = 'pic1.png'; var devStorageBlobService = storage.createBlobService(ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY); var sharedAccessPolicy = { AccessPolicy: { Permissions: BlobConstants.SharedAccessPermissions.READ, Start: new Date('October 11, 2011 11:03:40 am GMT'), Expiry: new Date('October 12, 2011 11:53:40 am GMT') } }; var sharedAccessSignature = devStorageBlobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy); assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_START], '2011-10-11T11:03:40Z'); assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_EXPIRY], '2011-10-12T11:53:40Z'); assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_RESOURCE], BlobConstants.ResourceTypes.BLOB); assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_PERMISSIONS], BlobConstants.SharedAccessPermissions.READ); assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_VERSION], '2012-02-12'); assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNATURE], 'ju4tX0G79vPxMOkBb7UfNVEgrj9+ZnSMutpUemVYHLY='); done(); }); }); it('responseEmits', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var responseReceived = false; blobService.on('response', function (response) { assert.notEqual(response, null); responseReceived = true; blobService.removeAllListeners('response'); }); blobService.createContainer(containerName, function (error) { assert.equal(error, null); blobService.createBlobBlockFromText('id1', containerName, blobName, 'id1', function (error2) { assert.equal(error2, null); // By the time the complete callback is processed the response header callback must have been called before assert.equal(responseReceived, true); done(); }); }); }); it('getBlobToStream', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var fileNameTarget = testutil.generateId('getBlobFile', [], suiteUtil.isMocked) + '.test'; var blobText = 'Hello World'; blobService.createContainer(containerName, function (createError1, container1) { assert.equal(createError1, null); assert.notEqual(container1, null); blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error1) { assert.equal(error1, null); blobService.getBlobToFile(containerName, blobName, fileNameTarget, function (error2) { assert.equal(error2, null); var exists = azureutil.pathExistsSync(fileNameTarget); assert.equal(exists, true); fs.readFile(fileNameTarget, function (err, fileText) { assert.equal(blobText, fileText); done(); }); }); }); }); }); it('SmallUploadBlobFromFile', function (done) { var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked); var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked); var fileNameSource = testutil.generateId('getBlobFile', [], suiteUtil.isMocked) + '.test'; var blobText = 'Hello World'; fs.writeFile(fileNameSource, blobText, function () { blobService.createContainer(containerName, function (createError1, container1, createResponse1) { assert.equal(createError1, null); assert.notEqual(container1, null); assert.ok(createResponse1.isSuccessful); assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created); var blobOptions = { contentType: 'text', blockIdPrefix : 'blockId' }; blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (uploadError, blobResponse, uploadResponse) { assert.equal(uploadError, null); assert.notEqual(blobResponse, null); assert.ok(uploadResponse.isSuccessful); blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) { assert.equal(downloadErr, null); assert.equal(blobTextResponse, blobText); blobService.getBlobProperties(containerName, blobName, function (getBlobPropertiesErr, blobGetResponse) { assert.equal(getBlobPropertiesErr, null); assert.notEqual(blobGetResponse, null); if (blobGetResponse) { assert.equal(blobOptions.contentType, blobGetResponse.contentType); } done(); }); }); }); }); }); }); it('storageConnectionStrings', function (done) { var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA=='; var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key; var blobService = storage.createBlobService(connectionString); assert.equal(blobService.storageAccount, 'myaccount'); assert.equal(blobService.storageAccessKey, key); assert.equal(blobService.protocol, 'https:'); assert.equal(blobService.host, 'myaccount.blob.core.windows.net'); done(); }); it('storageConnectionStringsDevStore', function (done) { var connectionString = 'UseDevelopmentStorage=true'; var blobService = storage.createBlobService(connectionString); assert.equal(blobService.storageAccount, ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT); assert.equal(blobService.storageAccessKey, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY); assert.equal(blobService.protocol, 'http:'); assert.equal(blobService.host, '127.0.0.1'); assert.equal(blobService.port, '10000'); done(); }); it('should be creatable from config', function (done) { var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA=='; var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key; var config = common.configure('testenvironment', function (c) { c.storage(connectionString); }); var blobService = storage.createBlobService(common.config('testenvironment')); assert.equal(blobService.storageAccount, 'myaccount'); assert.equal(blobService.storageAccessKey, key); assert.equal(blobService.protocol, 'https:'); assert.equal(blobService.host, 'myaccount.blob.core.windows.net'); done(); }); }); function repeat(s, n) { var ret = ''; for (var i = 0; i < n; i++) { ret += s; } return ret; }
apache-2.0
abel-von/commons
src/java/com/twitter/common/net/UrlResolver.java
15827
// ================================================================================================= // Copyright 2011 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.net; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ListenableFutureTask; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.twitter.common.base.ExceptionalFunction; import com.twitter.common.net.UrlResolver.ResolvedUrl.EndState; import com.twitter.common.quantity.Amount; import com.twitter.common.quantity.Time; import com.twitter.common.stats.PrintableHistogram; import com.twitter.common.util.BackoffStrategy; import com.twitter.common.util.Clock; import com.twitter.common.util.TruncatedBinaryBackoff; import com.twitter.common.util.caching.Cache; import com.twitter.common.util.caching.LRUCache; /** * Class to aid in resolving URLs by following redirects, which can optionally be performed * asynchronously using a thread pool. * * @author William Farner */ public class UrlResolver { private static final Logger LOG = Logger.getLogger(UrlResolver.class.getName()); private static final String TWITTER_UA = "Twitterbot/0.1"; private static final UrlResolverUtil URL_RESOLVER = new UrlResolverUtil(Functions.constant(TWITTER_UA)); private static final ExceptionalFunction<String, String, IOException> RESOLVER = new ExceptionalFunction<String, String, IOException>() { @Override public String apply(String url) throws IOException { return URL_RESOLVER.getEffectiveUrl(url, null); } }; private static ExceptionalFunction<String, String, IOException> getUrlResolver(final @Nullable ProxyConfig proxyConfig) { if (proxyConfig != null) { return new ExceptionalFunction<String, String, IOException>() { @Override public String apply(String url) throws IOException { return URL_RESOLVER.getEffectiveUrl(url, proxyConfig); } }; } else { return RESOLVER; } } private final ExceptionalFunction<String, String, IOException> resolver; private final int maxRedirects; // Tracks the number of active tasks (threads in use). private final Semaphore poolEntrySemaphore; private final Integer threadPoolSize; // Helps with signaling the handler. private final Executor handlerExecutor; // Manages the thread pool and task execution. private ExecutorService executor; // Cache to store resolved URLs. private final Cache<String, String> urlCache = LRUCache.<String, String>builder() .maxSize(10000) .makeSynchronized(true) .build(); // Variables to track connection/request stats. private AtomicInteger requestCount = new AtomicInteger(0); private AtomicInteger cacheHits = new AtomicInteger(0); private AtomicInteger failureCount = new AtomicInteger(0); // Tracks the time (in milliseconds) required to resolve URLs. private final PrintableHistogram urlResolutionTimesMs = new PrintableHistogram( 1, 5, 10, 25, 50, 75, 100, 150, 200, 250, 300, 500, 750, 1000, 1500, 2000); private final Clock clock; private final BackoffStrategy backoffStrategy; @VisibleForTesting UrlResolver(Clock clock, BackoffStrategy backoffStrategy, ExceptionalFunction<String, String, IOException> resolver, int maxRedirects) { this(clock, backoffStrategy, resolver, maxRedirects, null); } /** * Creates a new asynchronous URL resolver. A thread pool will be used to resolve URLs, and * resolved URLs will be announced via {@code handler}. * * @param maxRedirects The maximum number of HTTP redirects to follow. * @param threadPoolSize The number of threads to use for resolving URLs. * @param proxyConfig The proxy settings with which to make the HTTP request, or null for the * default configured proxy. */ public UrlResolver(int maxRedirects, int threadPoolSize, @Nullable ProxyConfig proxyConfig) { this(Clock.SYSTEM_CLOCK, new TruncatedBinaryBackoff(Amount.of(100L, Time.MILLISECONDS), Amount.of(1L, Time.SECONDS)), getUrlResolver(proxyConfig), maxRedirects, threadPoolSize); } public UrlResolver(int maxRedirects, int threadPoolSize) { this(maxRedirects, threadPoolSize, null); } private UrlResolver(Clock clock, BackoffStrategy backoffStrategy, ExceptionalFunction<String, String, IOException> resolver, int maxRedirects, @Nullable Integer threadPoolSize) { this.clock = clock; this.backoffStrategy = backoffStrategy; this.resolver = resolver; this.maxRedirects = maxRedirects; if (threadPoolSize != null) { this.threadPoolSize = threadPoolSize; Preconditions.checkState(threadPoolSize > 0); poolEntrySemaphore = new Semaphore(threadPoolSize); // Start up the thread pool. reset(); // Executor to send notifications back to the handler. This also needs to be // a daemon thread. handlerExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).build()); } else { this.threadPoolSize = null; poolEntrySemaphore = null; handlerExecutor = null; } } public Future<ResolvedUrl> resolveUrlAsync(final String url, final ResolvedUrlHandler handler) { Preconditions.checkNotNull( "Asynchronous URL resolution cannot be performed without a valid handler.", handler); try { poolEntrySemaphore.acquire(); } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Interrupted while waiting for thread to resolve URL: " + url, e); return null; } final ListenableFutureTask<ResolvedUrl> future = ListenableFutureTask.create( new Callable<ResolvedUrl>() { @Override public ResolvedUrl call() { return resolveUrl(url); } }); future.addListener(new Runnable() { @Override public void run() { try { handler.resolved(future); } finally { poolEntrySemaphore.release(); } } }, handlerExecutor); executor.execute(future); return future; } private void logThreadpoolInfo() { LOG.info("Shutting down thread pool, available permits: " + poolEntrySemaphore.availablePermits()); LOG.info("Queued threads? " + poolEntrySemaphore.hasQueuedThreads()); LOG.info("Queue length: " + poolEntrySemaphore.getQueueLength()); } public void reset() { Preconditions.checkState(threadPoolSize != null); if (executor != null) { Preconditions.checkState(executor.isShutdown(), "The thread pool must be shut down before resetting."); Preconditions.checkState(executor.isTerminated(), "There may still be pending async tasks."); } // Create a thread pool with daemon threads, so that they may be terminated when no // application threads are running. executor = Executors.newFixedThreadPool(threadPoolSize, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("UrlResolver[%d]").build()); } /** * Terminates the thread pool, waiting at most {@code waitSeconds} for active threads to complete. * After this method is called, no more URLs may be submitted for resolution. * * @param waitSeconds The number of seconds to wait for active threads to complete. */ public void clearAsyncTasks(int waitSeconds) { Preconditions.checkState(threadPoolSize != null, "finish() should not be called on a synchronous URL resolver."); logThreadpoolInfo(); executor.shutdown(); // Disable new tasks from being submitted. try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { LOG.info("Pool did not terminate, forcing shutdown."); logThreadpoolInfo(); List<Runnable> remaining = executor.shutdownNow(); LOG.info("Tasks still running: " + remaining); // Wait a while for tasks to respond to being cancelled if (!executor.awaitTermination(waitSeconds, TimeUnit.SECONDS)) { LOG.warning("Pool did not terminate."); logThreadpoolInfo(); } } } catch (InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while waiting for threadpool to finish.", e); // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } /** * Resolves a URL synchronously. * * @param url The URL to resolve. * @return The resolved URL. */ public ResolvedUrl resolveUrl(String url) { ResolvedUrl resolvedUrl = new ResolvedUrl(); resolvedUrl.setStartUrl(url); String cached = urlCache.get(url); if (cached != null) { cacheHits.incrementAndGet(); resolvedUrl.setNextResolve(cached); resolvedUrl.setEndState(EndState.CACHED); return resolvedUrl; } String currentUrl = url; long backoffMs = 0L; String next = null; for (int i = 0; i < maxRedirects; i++) { try { next = resolveOnce(currentUrl); // If there was a 4xx or a 5xx, we''ll get a null back, so we pretend like we never advanced // to allow for a retry within the redirect limit. // TODO(John Sirois): we really need access to the return code here to do the right thing; ie: // retry for internal server errors but probably not for unauthorized if (next == null) { if (i < maxRedirects - 1) { // don't wait if we're about to exit the loop backoffMs = backoffStrategy.calculateBackoffMs(backoffMs); try { clock.waitFor(backoffMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException( "Interrupted waiting to retry a failed resolution for: " + currentUrl, e); } } continue; } backoffMs = 0L; if (next.equals(currentUrl)) { // We've reached the end of the redirect chain. resolvedUrl.setEndState(EndState.REACHED_LANDING); urlCache.put(url, currentUrl); for (String intermediateUrl : resolvedUrl.getIntermediateUrls()) { urlCache.put(intermediateUrl, currentUrl); } return resolvedUrl; } else if (!url.equals(next)) { resolvedUrl.setNextResolve(next); } currentUrl = next; } catch (IOException e) { LOG.log(Level.INFO, "Failed to resolve url: " + url, e); resolvedUrl.setEndState(EndState.ERROR); return resolvedUrl; } } resolvedUrl.setEndState(next == null || url.equals(currentUrl) ? EndState.ERROR : EndState.REDIRECT_LIMIT); return resolvedUrl; } /** * Resolves a url, following at most one redirect. Thread-safe. * * @param url The URL to resolve. * @return The result of following the URL through at most one redirect or null if the url could * not be followed * @throws IOException If an error occurs while resolving the URL. */ private String resolveOnce(String url) throws IOException { requestCount.incrementAndGet(); String resolvedUrl = urlCache.get(url); if (resolvedUrl != null) { cacheHits.incrementAndGet(); return resolvedUrl; } try { long startTimeMs = System.currentTimeMillis(); resolvedUrl = resolver.apply(url); if (resolvedUrl == null) { return null; } urlCache.put(url, resolvedUrl); synchronized (urlResolutionTimesMs) { urlResolutionTimesMs.addValue(System.currentTimeMillis() - startTimeMs); } return resolvedUrl; } catch (IOException e) { failureCount.incrementAndGet(); throw e; } } @Override public String toString() { return String.format("Cache: %s\nFailed requests: %d,\nResolution Times: %s", urlCache, failureCount.get(), urlResolutionTimesMs.toString()); } /** * Class to wrap the result of a URL resolution. */ public static class ResolvedUrl { public enum EndState { REACHED_LANDING, ERROR, CACHED, REDIRECT_LIMIT } private String startUrl; private final List<String> resolveChain; private EndState endState; public ResolvedUrl() { resolveChain = Lists.newArrayList(); } @VisibleForTesting public ResolvedUrl(EndState endState, String startUrl, String... resolveChain) { this.endState = endState; this.startUrl = startUrl; this.resolveChain = Lists.newArrayList(resolveChain); } public String getStartUrl() { return startUrl; } void setStartUrl(String startUrl) { this.startUrl = startUrl; } /** * Returns the last URL resolved following a redirect chain, or null if the startUrl is a * landing URL. */ public String getEndUrl() { return resolveChain.isEmpty() ? null : Iterables.getLast(resolveChain); } void setNextResolve(String endUrl) { this.resolveChain.add(endUrl); } /** * Returns any immediate URLs encountered on the resolution chain. If the startUrl redirects * directly to the endUrl or they are the same the imtermediate URLs will be empty. */ public Iterable<String> getIntermediateUrls() { return resolveChain.size() <= 1 ? ImmutableList.<String>of() : resolveChain.subList(0, resolveChain.size() - 1); } public EndState getEndState() { return endState; } void setEndState(EndState endState) { this.endState = endState; } public String toString() { return String.format("%s -> %s [%s, %d redirects]", startUrl, Joiner.on(" -> ").join(resolveChain), endState, resolveChain.size()); } } /** * Interface to use for notifying the caller of resolved URLs. */ public interface ResolvedUrlHandler { /** * Signals that a URL has been resolved to its target. The implementation of this method must * be thread safe. * * @param future The future that has finished resolving a URL. */ public void resolved(Future<ResolvedUrl> future); } }
apache-2.0
ketralnis/elephant-bird
src/java/com/twitter/elephantbird/pig/piggybank/InvokeForDouble.java
1672
/* * 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 com.twitter.elephantbird.pig.piggybank; import org.apache.pig.impl.logicalLayer.FrontendException; /** * @see GenericInvoker */ public class InvokeForDouble extends GenericInvoker<Double> { public InvokeForDouble() {} public InvokeForDouble(String fullName) throws FrontendException, SecurityException, ClassNotFoundException, NoSuchMethodException { super(fullName); } public InvokeForDouble(String fullName, String paramSpecsStr) throws FrontendException, SecurityException, ClassNotFoundException, NoSuchMethodException { super(fullName, paramSpecsStr); } public InvokeForDouble(String fullName, String paramSpecsStr, String isStatic) throws ClassNotFoundException, FrontendException, SecurityException, NoSuchMethodException { super(fullName, paramSpecsStr, isStatic); } }
apache-2.0
EnquistLab/ffdm-frontend
public/assets/images/Workers/ThirdParty/GltfPipeline/updateVersion.js
36201
define([ './addExtensionsRequired', './addToArray', './ForEach', './getAccessorByteStride', '../../Core/Cartesian3', '../../Core/Math', '../../Core/clone', '../../Core/defaultValue', '../../Core/defined', '../../Core/Quaternion', '../../Core/WebGLConstants' ], function( addExtensionsRequired, addToArray, ForEach, getAccessorByteStride, Cartesian3, CesiumMath, clone, defaultValue, defined, Quaternion, WebGLConstants) { 'use strict'; var updateFunctions = { '0.8' : glTF08to10, '1.0' : glTF10to20, '2.0' : undefined }; /** * Update the glTF version to the latest version (2.0), or targetVersion if specified. * Applies changes made to the glTF spec between revisions so that the core library * only has to handle the latest version. * * @param {Object} gltf A javascript object containing a glTF asset. * @param {Object} [options] Options for updating the glTF. * @param {String} [options.targetVersion] The glTF will be upgraded until it hits the specified version. * @returns {Object} The updated glTF asset. */ function updateVersion(gltf, options) { options = defaultValue(options, {}); var targetVersion = options.targetVersion; var version = gltf.version; gltf.asset = defaultValue(gltf.asset, { version: '1.0' }); version = defaultValue(version, gltf.asset.version); // invalid version if (!updateFunctions.hasOwnProperty(version)) { // try truncating trailing version numbers, could be a number as well if it is 0.8 if (defined(version)) { version = ('' + version).substring(0, 3); } // default to 1.0 if it cannot be determined if (!updateFunctions.hasOwnProperty(version)) { version = '1.0'; } } var updateFunction = updateFunctions[version]; while (defined(updateFunction)) { if (version === targetVersion) { break; } updateFunction(gltf); version = gltf.asset.version; updateFunction = updateFunctions[version]; } return gltf; } function updateInstanceTechniques(gltf) { var materials = gltf.materials; for (var materialId in materials) { if (materials.hasOwnProperty(materialId)) { var material = materials[materialId]; var instanceTechnique = material.instanceTechnique; if (defined(instanceTechnique)) { material.technique = instanceTechnique.technique; material.values = instanceTechnique.values; delete material.instanceTechnique; } } } } function setPrimitiveModes(gltf) { var meshes = gltf.meshes; for (var meshId in meshes) { if (meshes.hasOwnProperty(meshId)) { var mesh = meshes[meshId]; var primitives = mesh.primitives; if (defined(primitives)) { var primitivesLength = primitives.length; for (var i = 0; i < primitivesLength; i++) { var primitive = primitives[i]; var defaultMode = defaultValue(primitive.primitive, WebGLConstants.TRIANGLES); primitive.mode = defaultValue(primitive.mode, defaultMode); delete primitive.primitive; } } } } } function updateNodes(gltf) { var nodes = gltf.nodes; var axis = new Cartesian3(); var quat = new Quaternion(); for (var nodeId in nodes) { if (nodes.hasOwnProperty(nodeId)) { var node = nodes[nodeId]; if (defined(node.rotation)) { var rotation = node.rotation; Cartesian3.fromArray(rotation, 0, axis); Quaternion.fromAxisAngle(axis, rotation[3], quat); node.rotation = [quat.x, quat.y, quat.z, quat.w]; } var instanceSkin = node.instanceSkin; if (defined(instanceSkin)) { node.skeletons = instanceSkin.skeletons; node.skin = instanceSkin.skin; node.meshes = instanceSkin.meshes; delete node.instanceSkin; } } } } function removeTechniquePasses(gltf) { var techniques = gltf.techniques; for (var techniqueId in techniques) { if (techniques.hasOwnProperty(techniqueId)) { var technique = techniques[techniqueId]; var passes = technique.passes; if (defined(passes)) { var passName = defaultValue(technique.pass, 'defaultPass'); if (passes.hasOwnProperty(passName)) { var pass = passes[passName]; var instanceProgram = pass.instanceProgram; technique.attributes = defaultValue(technique.attributes, instanceProgram.attributes); technique.program = defaultValue(technique.program, instanceProgram.program); technique.uniforms = defaultValue(technique.uniforms, instanceProgram.uniforms); technique.states = defaultValue(technique.states, pass.states); } delete technique.passes; delete technique.pass; } } } } function glTF08to10(gltf) { if (!defined(gltf.asset)) { gltf.asset = {}; } var asset = gltf.asset; asset.version = '1.0'; // profile should be an object, not a string if (!defined(asset.profile) || (typeof asset.profile === 'string')) { asset.profile = {}; } // version property should be in asset, not on the root element if (defined(gltf.version)) { delete gltf.version; } // material.instanceTechnique properties should be directly on the material updateInstanceTechniques(gltf); // primitive.primitive should be primitive.mode setPrimitiveModes(gltf); // node rotation should be quaternion, not axis-angle // node.instanceSkin is deprecated updateNodes(gltf); // technique.pass and techniques.passes are deprecated removeTechniquePasses(gltf); // gltf.lights -> khrMaterialsCommon.lights if (defined(gltf.lights)) { var extensions = defaultValue(gltf.extensions, {}); gltf.extensions = extensions; var materialsCommon = defaultValue(extensions.KHR_materials_common, {}); extensions.KHR_materials_common = materialsCommon; materialsCommon.lights = gltf.lights; delete gltf.lights; } // gltf.allExtensions -> extensionsUsed if (defined(gltf.allExtensions)) { gltf.extensionsUsed = gltf.allExtensions; gltf.allExtensions = undefined; } } function removeAnimationSamplersIndirection(gltf) { var animations = gltf.animations; for (var animationId in animations) { if (animations.hasOwnProperty(animationId)) { var animation = animations[animationId]; var parameters = animation.parameters; if (defined(parameters)) { var samplers = animation.samplers; for (var samplerId in samplers) { if (samplers.hasOwnProperty(samplerId)) { var sampler = samplers[samplerId]; sampler.input = parameters[sampler.input]; sampler.output = parameters[sampler.output]; } } delete animation.parameters; } } } } function objectToArray(object, mapping) { var array = []; for (var id in object) { if (object.hasOwnProperty(id)) { var value = object[id]; mapping[id] = array.length; array.push(value); if (!defined(value.name) && typeof(value) === 'object') { value.name = id; } } } return array; } function objectsToArrays(gltf) { var i; var globalMapping = { accessors: {}, animations: {}, bufferViews: {}, buffers: {}, cameras: {}, materials: {}, meshes: {}, nodes: {}, programs: {}, shaders: {}, skins: {}, techniques: {} }; // Map joint names to id names var jointName; var jointNameToId = {}; var nodes = gltf.nodes; for (var id in nodes) { if (nodes.hasOwnProperty(id)) { jointName = nodes[id].jointName; if (defined(jointName)) { jointNameToId[jointName] = id; } } } // Convert top level objects to arrays for (var topLevelId in gltf) { if (gltf.hasOwnProperty(topLevelId) && topLevelId !== 'extras' && topLevelId !== 'asset' && topLevelId !== 'extensions') { var objectMapping = {}; var object = gltf[topLevelId]; if (typeof(object) === 'object' && !Array.isArray(object)) { gltf[topLevelId] = objectToArray(object, objectMapping); globalMapping[topLevelId] = objectMapping; if (topLevelId === 'animations') { objectMapping = {}; object.samplers = objectToArray(object.samplers, objectMapping); globalMapping[topLevelId].samplers = objectMapping; } } } } // Remap joint names to array indexes for (jointName in jointNameToId) { if (jointNameToId.hasOwnProperty(jointName)) { jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]]; } } // Fix references if (defined(gltf.scene)) { gltf.scene = globalMapping.scenes[gltf.scene]; } ForEach.bufferView(gltf, function(bufferView) { if (defined(bufferView.buffer)) { bufferView.buffer = globalMapping.buffers[bufferView.buffer]; } }); ForEach.accessor(gltf, function(accessor) { if (defined(accessor.bufferView)) { accessor.bufferView = globalMapping.bufferViews[accessor.bufferView]; } }); ForEach.shader(gltf, function(shader) { var extensions = shader.extensions; if (defined(extensions)) { var binaryGltf = extensions.KHR_binary_glTF; if (defined(binaryGltf)) { shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView]; delete extensions.KHR_binary_glTF; } if (Object.keys(extensions).length === 0) { delete shader.extensions; } } }); ForEach.program(gltf, function(program) { if (defined(program.vertexShader)) { program.vertexShader = globalMapping.shaders[program.vertexShader]; } if (defined(program.fragmentShader)) { program.fragmentShader = globalMapping.shaders[program.fragmentShader]; } }); ForEach.technique(gltf, function(technique) { if (defined(technique.program)) { technique.program = globalMapping.programs[technique.program]; } ForEach.techniqueParameter(technique, function(parameter) { if (defined(parameter.node)) { parameter.node = globalMapping.nodes[parameter.node]; } var value = parameter.value; if (defined(value)) { if (Array.isArray(value)) { if (value.length === 1) { var textureId = value[0]; if (typeof textureId === 'string') { value[0] = globalMapping.textures[textureId]; } } } else if (typeof value === 'string') { parameter.value = [globalMapping.textures[value]]; } } }); }); ForEach.mesh(gltf, function(mesh) { ForEach.meshPrimitive(mesh, function(primitive) { if (defined(primitive.indices)) { primitive.indices = globalMapping.accessors[primitive.indices]; } ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) { primitive.attributes[semantic] = globalMapping.accessors[accessorId]; }); if (defined(primitive.material)) { primitive.material = globalMapping.materials[primitive.material]; } }); }); ForEach.node(gltf, function(node) { var children = node.children; if (defined(children)) { var childrenLength = children.length; for (i = 0; i < childrenLength; i++) { children[i] = globalMapping.nodes[children[i]]; } } if (defined(node.meshes)) { // Split out meshes on nodes var meshes = node.meshes; var meshesLength = meshes.length; if (meshesLength > 0) { node.mesh = globalMapping.meshes[meshes[0]]; for (i = 1; i < meshesLength; i++) { var meshNode = { mesh: globalMapping.meshes[meshes[i]], extras: { _pipeline: {} } }; var meshNodeId = addToArray(gltf.nodes, meshNode); if (!defined(children)) { children = []; node.children = children; } children.push(meshNodeId); } } delete node.meshes; } if (defined(node.camera)) { node.camera = globalMapping.cameras[node.camera]; } if (defined(node.skeletons)) { // Assign skeletons to skins var skeletons = node.skeletons; var skeletonsLength = skeletons.length; if ((skeletonsLength > 0) && defined(node.skin)) { var skin = gltf.skins[globalMapping.skins[node.skin]]; skin.skeleton = globalMapping.nodes[skeletons[0]]; } delete node.skeletons; } if (defined(node.skin)) { node.skin = globalMapping.skins[node.skin]; } if (defined(node.jointName)) { delete(node.jointName); } }); ForEach.skin(gltf, function(skin) { if (defined(skin.inverseBindMatrices)) { skin.inverseBindMatrices = globalMapping.accessors[skin.inverseBindMatrices]; } var joints = []; var jointNames = skin.jointNames; if (defined(jointNames)) { for (i = 0; i < jointNames.length; i++) { joints[i] = jointNameToId[jointNames[i]]; } skin.joints = joints; delete skin.jointNames; } }); ForEach.scene(gltf, function(scene) { var sceneNodes = scene.nodes; if (defined(sceneNodes)) { var sceneNodesLength = sceneNodes.length; for (i = 0; i < sceneNodesLength; i++) { sceneNodes[i] = globalMapping.nodes[sceneNodes[i]]; } } }); ForEach.animation(gltf, function(animation) { var samplerMapping = {}; animation.samplers = objectToArray(animation.samplers, samplerMapping); ForEach.animationSampler(animation, function(sampler) { sampler.input = globalMapping.accessors[sampler.input]; sampler.output = globalMapping.accessors[sampler.output]; }); var channels = animation.channels; if (defined(channels)) { var channelsLength = channels.length; for (i = 0; i < channelsLength; i++) { var channel = channels[i]; channel.sampler = samplerMapping[channel.sampler]; var target = channel.target; if (defined(target)) { target.node = globalMapping.nodes[target.id]; delete target.id; } } } }); ForEach.material(gltf, function(material) { if (defined(material.technique)) { material.technique = globalMapping.techniques[material.technique]; } ForEach.materialValue(material, function(value, name) { if (Array.isArray(value)) { if (value.length === 1) { var textureId = value[0]; if (typeof textureId === 'string') { value[0] = globalMapping.textures[textureId]; } } } else if (typeof value === 'string') { material.values[name] = { index : globalMapping.textures[value] }; } }); var extensions = material.extensions; if (defined(extensions)) { var materialsCommon = extensions.KHR_materials_common; if (defined(materialsCommon)) { ForEach.materialValue(materialsCommon, function(value, name) { if (Array.isArray(value)) { if (value.length === 1) { var textureId = value[0]; if (typeof textureId === 'string') { value[0] = globalMapping.textures[textureId]; } } } else if (typeof value === 'string') { materialsCommon.values[name] = { index: globalMapping.textures[value] }; } }); } } }); ForEach.image(gltf, function(image) { var extensions = image.extensions; if (defined(extensions)) { var binaryGltf = extensions.KHR_binary_glTF; if (defined(binaryGltf)) { image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView]; image.mimeType = binaryGltf.mimeType; delete extensions.KHR_binary_glTF; } if (Object.keys(extensions).length === 0) { delete image.extensions; } } if (defined(image.extras)) { var compressedImages = image.extras.compressedImage3DTiles; for (var type in compressedImages) { if (compressedImages.hasOwnProperty(type)) { var compressedImage = compressedImages[type]; var compressedExtensions = compressedImage.extensions; if (defined(compressedExtensions)) { var compressedBinaryGltf = compressedExtensions.KHR_binary_glTF; if (defined(compressedBinaryGltf)) { compressedImage.bufferView = globalMapping.bufferViews[compressedBinaryGltf.bufferView]; compressedImage.mimeType = compressedBinaryGltf.mimeType; delete compressedExtensions.KHR_binary_glTF; } if (Object.keys(compressedExtensions).length === 0) { delete compressedImage.extensions; } } } } } }); ForEach.texture(gltf, function(texture) { if (defined(texture.sampler)) { texture.sampler = globalMapping.samplers[texture.sampler]; } if (defined(texture.source)) { texture.source = globalMapping.images[texture.source]; } }); } function stripProfile(gltf) { var asset = gltf.asset; delete asset.profile; } var knownExtensions = { CESIUM_RTC : true, KHR_materials_common : true, WEB3D_quantized_attributes : true }; function requireKnownExtensions(gltf) { var extensionsUsed = gltf.extensionsUsed; gltf.extensionsRequired = defaultValue(gltf.extensionsRequired, []); if (defined(extensionsUsed)) { var extensionsUsedLength = extensionsUsed.length; for (var i = 0; i < extensionsUsedLength; i++) { var extension = extensionsUsed[i]; if (defined(knownExtensions[extension])) { gltf.extensionsRequired.push(extension); } } } } function removeBufferType(gltf) { ForEach.buffer(gltf, function(buffer) { delete buffer.type; }); } function requireAttributeSetIndex(gltf) { ForEach.mesh(gltf, function(mesh) { ForEach.meshPrimitive(mesh, function(primitive) { ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) { if (semantic === 'TEXCOORD') { primitive.attributes.TEXCOORD_0 = accessorId; } else if (semantic === 'COLOR') { primitive.attributes.COLOR_0 = accessorId; } }); delete primitive.attributes.TEXCOORD; delete primitive.attributes.COLOR; }); }); ForEach.technique(gltf, function(technique) { ForEach.techniqueParameter(technique, function(parameter) { var semantic = parameter.semantic; if (defined(semantic)) { if (semantic === 'TEXCOORD') { parameter.semantic = 'TEXCOORD_0'; } else if (semantic === 'COLOR') { parameter.semantic = 'COLOR_0'; } } }); }); } var knownSemantics = { POSITION: true, NORMAL: true, TEXCOORD: true, COLOR: true, JOINT: true, WEIGHT: true }; function underscoreApplicationSpecificSemantics(gltf) { var mappedSemantics = {}; ForEach.mesh(gltf, function(mesh) { ForEach.meshPrimitive(mesh, function(primitive) { /* jshint unused:vars */ ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) { if (semantic.charAt(0) !== '_') { var setIndex = semantic.search(/_[0-9]+/g); var strippedSemantic = semantic; if (setIndex >= 0) { strippedSemantic = semantic.substring(0, setIndex); } if (!defined(knownSemantics[strippedSemantic])) { var newSemantic = '_' + semantic; mappedSemantics[semantic] = newSemantic; } } }); for (var semantic in mappedSemantics) { if (mappedSemantics.hasOwnProperty(semantic)) { var mappedSemantic = mappedSemantics[semantic]; var accessorId = primitive.attributes[semantic]; if (defined(accessorId)) { delete primitive.attributes[semantic]; primitive.attributes[mappedSemantic] = accessorId; } } } }); }); ForEach.technique(gltf, function(technique) { ForEach.techniqueParameter(technique, function(parameter) { var mappedSemantic = mappedSemantics[parameter.semantic]; if (defined(mappedSemantic)) { parameter.semantic = mappedSemantic; } }); }); } function removeScissorFromTechniques(gltf) { ForEach.technique(gltf, function(technique) { var techniqueStates = technique.states; if (defined(techniqueStates)) { var techniqueFunctions = techniqueStates.functions; if (defined(techniqueFunctions)) { delete techniqueFunctions.scissor; } var enableStates = techniqueStates.enable; if (defined(enableStates)) { var scissorIndex = enableStates.indexOf(WebGLConstants.SCISSOR_TEST); if (scissorIndex >= 0) { enableStates.splice(scissorIndex, 1); } } } }); } function clampTechniqueFunctionStates(gltf) { ForEach.technique(gltf, function(technique) { var techniqueStates = technique.states; if (defined(techniqueStates)) { var functions = techniqueStates.functions; if (defined(functions)) { var blendColor = functions.blendColor; if (defined(blendColor)) { for (var i = 0; i < 4; i++) { blendColor[i] = CesiumMath.clamp(blendColor[i], 0.0, 1.0); } } var depthRange = functions.depthRange; if (defined(depthRange)) { depthRange[1] = CesiumMath.clamp(depthRange[1], 0.0, 1.0); depthRange[0] = CesiumMath.clamp(depthRange[0], 0.0, depthRange[1]); } } } }); } function clampCameraParameters(gltf) { ForEach.camera(gltf, function(camera) { var perspective = camera.perspective; if (defined(perspective)) { var aspectRatio = perspective.aspectRatio; if (defined(aspectRatio) && aspectRatio === 0.0) { delete perspective.aspectRatio; } var yfov = perspective.yfov; if (defined(yfov) && yfov === 0.0) { perspective.yfov = 1.0; } } }); } function requireByteLength(gltf) { ForEach.buffer(gltf, function(buffer) { if (!defined(buffer.byteLength)) { buffer.byteLength = buffer.extras._pipeline.source.length; } }); ForEach.bufferView(gltf, function(bufferView) { if (!defined(bufferView.byteLength)) { var bufferViewBufferId = bufferView.buffer; var bufferViewBuffer = gltf.buffers[bufferViewBufferId]; bufferView.byteLength = bufferViewBuffer.byteLength; } }); } function moveByteStrideToBufferView(gltf) { var bufferViews = gltf.bufferViews; var bufferViewsToDelete = {}; ForEach.accessor(gltf, function(accessor) { var oldBufferViewId = accessor.bufferView; if (defined(oldBufferViewId)) { if (!defined(bufferViewsToDelete[oldBufferViewId])) { bufferViewsToDelete[oldBufferViewId] = true; } var bufferView = clone(bufferViews[oldBufferViewId]); var accessorByteStride = (defined(accessor.byteStride) && accessor.byteStride !== 0) ? accessor.byteStride : getAccessorByteStride(gltf, accessor); if (defined(accessorByteStride)) { bufferView.byteStride = accessorByteStride; if (bufferView.byteStride !== 0) { bufferView.byteLength = accessor.count * accessorByteStride; } bufferView.byteOffset += accessor.byteOffset; accessor.byteOffset = 0; delete accessor.byteStride; } accessor.bufferView = addToArray(bufferViews, bufferView); } }); var bufferViewShiftMap = {}; var bufferViewRemovalCount = 0; /* jshint unused:vars */ ForEach.bufferView(gltf, function(bufferView, bufferViewId) { if (defined(bufferViewsToDelete[bufferViewId])) { bufferViewRemovalCount++; } else { bufferViewShiftMap[bufferViewId] = bufferViewId - bufferViewRemovalCount; } }); var removedCount = 0; for (var bufferViewId in bufferViewsToDelete) { if (defined(bufferViewId)) { var index = parseInt(bufferViewId) - removedCount; bufferViews.splice(index, 1); removedCount++; } } ForEach.accessor(gltf, function(accessor) { var accessorBufferView = accessor.bufferView; if (defined(accessorBufferView)) { accessor.bufferView = bufferViewShiftMap[accessorBufferView]; } }); ForEach.shader(gltf, function(shader) { var shaderBufferView = shader.bufferView; if (defined(shaderBufferView)) { shader.bufferView = bufferViewShiftMap[shaderBufferView]; } }); ForEach.image(gltf, function(image) { var imageBufferView = image.bufferView; if (defined(imageBufferView)) { image.bufferView = bufferViewShiftMap[imageBufferView]; } if (defined(image.extras)) { var compressedImages = image.extras.compressedImage3DTiles; for (var type in compressedImages) { if (compressedImages.hasOwnProperty(type)) { var compressedImage = compressedImages[type]; var compressedImageBufferView = compressedImage.bufferView; if (defined(compressedImageBufferView)) { compressedImage.bufferView = bufferViewShiftMap[compressedImageBufferView]; } } } } }); } function stripTechniqueAttributeValues(gltf) { ForEach.technique(gltf, function(technique) { ForEach.techniqueAttribute(technique, function(attribute) { var parameter = technique.parameters[attribute]; if (defined(parameter.value)) { delete parameter.value; } }); }); } function stripTechniqueParameterCount(gltf) { ForEach.technique(gltf, function(technique) { ForEach.techniqueParameter(technique, function(parameter) { if (defined(parameter.count)) { var semantic = parameter.semantic; if (!defined(semantic) || (semantic !== 'JOINTMATRIX' && semantic.indexOf('_') !== 0)) { delete parameter.count; } } }); }); } function addKHRTechniqueExtension(gltf) { var techniques = gltf.techniques; if (defined(techniques) && techniques.length > 0) { addExtensionsRequired(gltf, 'KHR_technique_webgl'); } } function glTF10to20(gltf) { if (!defined(gltf.asset)) { gltf.asset = {}; } var asset = gltf.asset; asset.version = '2.0'; // material.instanceTechnique properties should be directly on the material. instanceTechnique is a gltf 0.8 property but is seen in some 1.0 models. updateInstanceTechniques(gltf); // animation.samplers now refers directly to accessors and animation.parameters should be removed removeAnimationSamplersIndirection(gltf); // top-level objects are now arrays referenced by index instead of id objectsToArrays(gltf); // asset.profile no longer exists stripProfile(gltf); // move known extensions from extensionsUsed to extensionsRequired requireKnownExtensions(gltf); // bufferView.byteLength and buffer.byteLength are required requireByteLength(gltf); // byteStride moved from accessor to bufferView moveByteStrideToBufferView(gltf); // buffer.type is unnecessary and should be removed removeBufferType(gltf); // TEXCOORD and COLOR attributes must be written with a set index (TEXCOORD_#) requireAttributeSetIndex(gltf); // Add underscores to application-specific parameters underscoreApplicationSpecificSemantics(gltf); // remove scissor from techniques removeScissorFromTechniques(gltf); // clamp technique function states to min/max clampTechniqueFunctionStates(gltf); // clamp camera parameters clampCameraParameters(gltf); // a technique parameter specified as an attribute cannot have a value stripTechniqueAttributeValues(gltf); // only techniques with a JOINTMATRIX or application specific semantic may have a defined count property stripTechniqueParameterCount(gltf); // add KHR_technique_webgl extension addKHRTechniqueExtension(gltf); } return updateVersion; });
apache-2.0
jkotas/roslyn
src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs
15102
// 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.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; public VisualStudioDocumentNavigationService( SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e)) { } return false; } var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var document = OpenDocument(workspace, documentId, options); if (document == null) { return false; } var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var textBuffer = text.Container.GetTextBuffer(); var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length); if (boundedTextSpan != textSpan) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e)) { } } var vsTextSpan = text.GetVsTextSpanForSpan(boundedTextSpan); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan); } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var document = OpenDocument(workspace, documentId, options); if (document == null) { return false; } var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan); } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread); } var document = OpenDocument(workspace, documentId, options); if (document == null) { return false; } var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var textBuffer = text.Container.GetTextBuffer(); var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length); if (boundedPosition != position) { try { throw new ArgumentOutOfRangeException(); } catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e)) { } } var vsTextSpan = text.GetVsTextSpanForPosition(boundedPosition, virtualSpace); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan); } /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a position that is not /// inside the bounds of the associated <see cref="Document"/>. This method returns a /// position that is guaranteed to be inside the <see cref="Document"/> bounds. If the /// returned position is different from the given position, then the worst observable /// behavior is either no navigation or navigation to the end of the document. See the /// following bugs for more details: /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318 /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409 /// </summary> private static int GetPositionWithinDocumentBounds(int position, int documentLength) { return Math.Min(documentLength, Math.Max(position, 0)); } /// <summary> /// It is unclear why, but we are sometimes asked to navigate to a <see cref="TextSpan"/> /// that is not inside the bounds of the associated <see cref="Document"/>. This method /// returns a span that is guaranteed to be inside the <see cref="Document"/> bounds. If /// the returned span is different from the given span, then the worst observable behavior /// is either no navigation or navigation to the end of the document. /// See https://github.com/dotnet/roslyn/issues/7660 for more details. /// </summary> private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength) { return TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength)); } private static Document OpenDocument(Workspace workspace, DocumentId documentId, OptionSet options) { options = options ?? workspace.Options; // Always open the document again, even if the document is already open in the // workspace. If a document is already open in a preview tab and it is opened again // in a permanent tab, this allows the document to transition to the new state. if (workspace.CanOpenDocuments) { if (options.GetOption(NavigationOptions.PreferProvisionalTab)) { // If we're just opening the provisional tab, then do not "activate" the document // (i.e. don't give it focus). This way if a user is just arrowing through a set // of FindAllReferences results, they don't have their cursor placed into the document. var state = __VSNEWDOCUMENTSTATE.NDS_Provisional | __VSNEWDOCUMENTSTATE.NDS_NoActivate; using (var scope = new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation)) { workspace.OpenDocument(documentId); } } else { workspace.OpenDocument(documentId); } } if (!workspace.IsDocumentOpen(documentId)) { return null; } return workspace.CurrentSolution.GetDocument(documentId); } private bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan) { using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, CancellationToken.None)) { var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer); if (vsTextBuffer == null) { Debug.Fail("Could not get IVsTextBuffer for document!"); return false; } var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { Debug.Fail("Could not get IVsTextManager service!"); return false; } return ErrorHandler.Succeeded( textManager.NavigateToLineAndColumn2( vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow)); } } private bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId) { var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace == null) { return false; } var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument; if (containedDocument == null) { return false; } return true; } private bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer) { return spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out var spanInPrimaryBuffer); } } }
apache-2.0
tr3vr/jena
jena-arq/src/main/java/org/apache/jena/sparql/expr/E_StrEncodeForURI.java
1365
/* * 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.jena.sparql.expr; import org.apache.jena.sparql.expr.nodevalue.XSDFuncOp ; import org.apache.jena.sparql.sse.Tags ; public class E_StrEncodeForURI extends ExprFunction1 { private static final String symbol = Tags.tagStrEncodeForURI ; public E_StrEncodeForURI(Expr expr) { super(expr, symbol) ; } @Override public NodeValue eval(NodeValue v) { return XSDFuncOp.strEncodeForURI(v) ; } @Override public Expr copy(Expr expr) { return new E_StrEncodeForURI(expr) ; } }
apache-2.0
kasungayan/product-as
modules/integration/tests-ui-integration/tests-ui/src/test/java/org/wso2/appserver/ui/integration/test/webapp/spring/SpringWebApplicationDeploymentTestCase.java
8185
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. 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.wso2.appserver.ui.integration.test.webapp.spring; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.appserver.integration.common.ui.page.LoginPage; import org.wso2.appserver.integration.common.ui.page.main.WebAppListPage; import org.wso2.appserver.integration.common.ui.page.main.WebAppUploadingPage; import org.wso2.appserver.integration.common.utils.ASIntegrationUITest; import org.wso2.carbon.automation.extensions.selenium.BrowserManager; import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; import java.io.File; import java.io.IOException; import java.util.Calendar; import static org.testng.AssertJUnit.assertTrue; /** * This class tests the deployment and accessibility of a web application which use spring framework */ public class SpringWebApplicationDeploymentTestCase extends ASIntegrationUITest { private WebDriver driver; private final String context = "/booking-faces"; @BeforeClass(alwaysRun = true, enabled = false) public void setUp() throws Exception { super.init(); driver = BrowserManager.getWebDriver(); driver.get(getLoginURL()); LoginPage test = new LoginPage(driver); test.loginAs(userInfo.getUserName(), userInfo.getPassword()); } @Test(groups = "wso2.as", description = "Uploading the web app which use spring", enabled = false) public void uploadSpringWebApplicationTest() throws Exception { String filePath = TestConfigurationProvider.getResourceLocation("AS") + File.separator + "war" + File.separator + "spring" + File.separator + "booking-faces.war"; WebAppUploadingPage uploadPage = new WebAppUploadingPage(driver); Assert.assertTrue(uploadPage.uploadWebApp(filePath), "Web Application uploading failed"); } @Test(groups = "wso2.as", description = "Verifying Deployment the web app which use spring" , dependsOnMethods = "uploadSpringWebApplicationTest", enabled = false) public void webApplicationDeploymentTest() throws Exception { WebAppListPage webAppListPage = new WebAppListPage(driver); assertTrue("Web Application Deployment Failed. Web Application /booking-faces not found in Web application List" , isWebAppDeployed(webAppListPage, context)); driver.findElement(By.id("webappsTable")).findElement(By.linkText("/booking-faces")).click(); } @Test(groups = "wso2.as", description = "Access the spring application" , dependsOnMethods = "webApplicationDeploymentTest", enabled = false) public void invokeSpringApplicationTest() throws Exception { WebDriver driverForApp = null; try { driverForApp = BrowserManager.getWebDriver(); //Go to application driverForApp.get(webAppURL + "/booking-faces/spring/intro"); driverForApp.findElement(By.linkText("Start your Spring Travel experience")).click(); //searching hotels to reserve driverForApp.findElement(By.xpath("//*[@id=\"j_idt13:searchString\"]")).sendKeys("Con"); driverForApp.findElement(By.xpath("//*[@id=\"j_idt13:findHotels\"]")).click(); //view hotel information driverForApp.findElement(By.xpath("//*[@id=\"j_idt12:hotels:0:viewHotelLink\"]")).click(); //go to book hotel driverForApp.findElement(By.xpath("//*[@id=\"hotel:book\"]")).click(); //providing user name and password driverForApp.findElement(By.xpath("/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[1]/input")) .sendKeys("keith"); driverForApp.findElement(By.xpath("/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[2]/input")) .sendKeys("melbourne"); //authenticating driverForApp.findElement(By.xpath("/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[4]/input")) .click(); //booking hotel driverForApp.findElement(By.xpath("//*[@id=\"hotel:book\"]")).click(); //providing payments information driverForApp.findElement(By.xpath("//*[@id=\"bookingForm:creditCard\"]")).sendKeys("1234567890123456"); driverForApp.findElement(By.xpath("//*[@id=\"bookingForm:creditCardName\"]")).sendKeys("xyz"); //proceed transaction driverForApp.findElement(By.xpath("//*[@id=\"bookingForm:proceed\"]")).click(); //confirm booking driverForApp.findElement(By.xpath("//*[@id=\"j_idt13:confirm\"]")).click(); //verify whether the hotel booked is in the booked hotel tabled Assert.assertEquals(driverForApp.findElement(By.xpath("//*[@id=\"bookings_header\"]")).getText() , "Your Hotel Bookings", "Booked Hotel table Not Found"); //verify the hotel name is exist in the booked hotel table Assert.assertEquals(driverForApp.findElement(By.xpath("//*[@id=\"j_idt23:j_idt24_data\"]/tr/td[1]")) .getText(), "Conrad Miami\n" + "1395 Brickell Ave\n" + "Miami, FL", "Hotel Name mismatch"); } finally { if (driverForApp != null) { driverForApp.quit(); } } } @AfterClass(alwaysRun = true, enabled = false) public void deleteWebApplication() throws Exception { try { WebAppListPage webAppListPage = new WebAppListPage(driver); if (webAppListPage.findWebApp(context)) { Assert.assertTrue(webAppListPage.deleteWebApp(context), "Web Application Deletion failed"); Assert.assertTrue(isWebAppUnDeployed(webAppListPage, context)); } } finally { driver.quit(); } } private boolean isWebAppDeployed(WebAppListPage listPage, String webAppContext) throws IOException { boolean isServiceDeployed = false; Calendar startTime = Calendar.getInstance(); long time; while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 1000 * 60 * 2) { listPage = new WebAppListPage(driver); if (listPage.findWebApp(webAppContext)) { isServiceDeployed = true; break; } try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return isServiceDeployed; } private boolean isWebAppUnDeployed(WebAppListPage listPage, String webAppContext) throws IOException { boolean isServiceUnDeployed = false; Calendar startTime = Calendar.getInstance(); long time; while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 1000 * 60 * 2) { listPage = new WebAppListPage(driver); if (!listPage.findWebApp(webAppContext)) { isServiceUnDeployed = true; break; } try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } return isServiceUnDeployed; } }
apache-2.0
apache/flink
flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/proxy/KinesisProxyV2Interface.java
2775
/* * 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.streaming.connectors.kinesis.proxy; import org.apache.flink.annotation.Internal; import software.amazon.awssdk.services.kinesis.model.DeregisterStreamConsumerResponse; import software.amazon.awssdk.services.kinesis.model.DescribeStreamConsumerResponse; import software.amazon.awssdk.services.kinesis.model.DescribeStreamSummaryResponse; import software.amazon.awssdk.services.kinesis.model.RegisterStreamConsumerResponse; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * Interface for a Kinesis proxy using AWS SDK v2.x operating on multiple Kinesis streams within the * same AWS service region. */ @Internal public interface KinesisProxyV2Interface { DescribeStreamSummaryResponse describeStreamSummary(String stream) throws InterruptedException, ExecutionException; DescribeStreamConsumerResponse describeStreamConsumer(final String streamConsumerArn) throws InterruptedException, ExecutionException; DescribeStreamConsumerResponse describeStreamConsumer( final String streamArn, final String consumerName) throws InterruptedException, ExecutionException; RegisterStreamConsumerResponse registerStreamConsumer( final String streamArn, final String consumerName) throws InterruptedException, ExecutionException; DeregisterStreamConsumerResponse deregisterStreamConsumer(final String consumerArn) throws InterruptedException, ExecutionException; CompletableFuture<Void> subscribeToShard( SubscribeToShardRequest request, SubscribeToShardResponseHandler responseHandler); /** Destroy any open resources used by the factory. */ default void close() { // Do nothing by default } }
apache-2.0
mingzhi22/homebrew-cask
Casks/dragthing.rb
361
cask 'dragthing' do version '5.9.12' sha256 '4a351c593aff1c3214613d622a4e81f184e8ae238df6db921dd822efeefe27e6' # amazonaws.com is the official download host per the vendor homepage url "https://s3.amazonaws.com/tlasystems/DragThing-#{version}.dmg" name 'DragThing' homepage 'http://www.dragthing.com' license :freemium app 'DragThing.app' end
bsd-2-clause
exclie/Imagenologia
vendor/zendframework/zendframework/tests/ZendTest/Mvc/Router/Http/TestAsset/DummyRouteWithParam.php
1223
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Mvc\Router\Http\TestAsset; use Zend\Mvc\Router\Http\RouteInterface; use Zend\Mvc\Router\Http\RouteMatch; use Zend\Stdlib\RequestInterface; /** * Dummy route. * */ class DummyRouteWithParam extends DummyRoute { /** * match(): defined by RouteInterface interface. * * @see Route::match() * @param RequestInterface $request * @return RouteMatch */ public function match(RequestInterface $request) { return new RouteMatch(array('foo' => 'bar'), -4); } /** * assemble(): defined by RouteInterface interface. * * @see Route::assemble() * @param array $params * @param array $options * @return mixed */ public function assemble(array $params = null, array $options = null) { if (isset($params['foo'])) { return $params['foo']; } return ''; } }
bsd-3-clause
nwjs/chromium.src
third_party/protobuf/js/experimental/runtime/kernel/conformance/conformance_testee.js
3602
goog.module('javascript.protobuf.conformance'); const ConformanceRequest = goog.require('proto.conformance.ConformanceRequest'); const ConformanceResponse = goog.require('proto.conformance.ConformanceResponse'); const TestAllTypesProto2 = goog.require('proto.conformance.TestAllTypesProto2'); const TestAllTypesProto3 = goog.require('proto.conformance.TestAllTypesProto3'); const WireFormat = goog.require('proto.conformance.WireFormat'); const base64 = goog.require('goog.crypt.base64'); /** * Creates a `proto.conformance.ConformanceResponse` response according to the * `proto.conformance.ConformanceRequest` request. * @param {!ConformanceRequest} request * @return {!ConformanceResponse} response */ function doTest(request) { const response = ConformanceResponse.createEmpty(); if(request.getPayloadCase() === ConformanceRequest.PayloadCase.JSON_PAYLOAD) { response.setSkipped('Json is not supported as input format.'); return response; } if(request.getPayloadCase() === ConformanceRequest.PayloadCase.TEXT_PAYLOAD) { response.setSkipped('Text format is not supported as input format.'); return response; } if(request.getPayloadCase() === ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET) { response.setRuntimeError('Request didn\'t have payload.'); return response; } if(request.getPayloadCase() !== ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD) { throw new Error('Request didn\'t have accepted input format.'); } if (request.getRequestedOutputFormat() === WireFormat.JSON) { response.setSkipped('Json is not supported as output format.'); return response; } if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) { response.setSkipped('Text format is not supported as output format.'); return response; } if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) { response.setRuntimeError('Unspecified output format'); return response; } if (request.getRequestedOutputFormat() !== WireFormat.PROTOBUF) { throw new Error('Request didn\'t have accepted output format.'); } if (request.getMessageType() === 'conformance.FailureSet') { response.setProtobufPayload(new ArrayBuffer(0)); } else if ( request.getMessageType() === 'protobuf_test_messages.proto2.TestAllTypesProto2') { try { const testMessage = TestAllTypesProto2.deserialize(request.getProtobufPayload()); response.setProtobufPayload(testMessage.serialize()); } catch (err) { response.setParseError(err.toString()); } } else if ( request.getMessageType() === 'protobuf_test_messages.proto3.TestAllTypesProto3') { try { const testMessage = TestAllTypesProto3.deserialize(request.getProtobufPayload()); response.setProtobufPayload(testMessage.serialize()); } catch (err) { response.setParseError(err.toString()); } } else { throw new Error( `Payload message not supported: ${request.getMessageType()}.`); } return response; } /** * Same as doTest, but both request and response are in base64. * @param {string} base64Request * @return {string} response */ function runConformanceTest(base64Request) { const request = ConformanceRequest.deserialize( base64.decodeStringToUint8Array(base64Request).buffer); const response = doTest(request); return base64.encodeByteArray(new Uint8Array(response.serialize())); } // Needed for node test exports.doTest = doTest; // Needed for browser test goog.exportSymbol('runConformanceTest', runConformanceTest);
bsd-3-clause
eprislac/guard-yard
vendor/jruby/1.9/gems/rails_best_practices-1.15.7/spec/rails_best_practices/core/klasses_spec.rb
1109
require 'spec_helper' module RailsBestPractices::Core describe Klasses do it { should be_a_kind_of Array } context "Klass" do context "#class_name" do it "gets class name without module" do klass = Klass.new("BlogPost", "Post", []) expect(klass.class_name).to eq("BlogPost") end it "gets class name with moduel" do klass = Klass.new("BlogPost", "Post", ["Admin"]) expect(klass.class_name).to eq("Admin::BlogPost") end end context "#extend_class_name" do it "gets extend class name without module" do klass = Klass.new("BlogPost", "Post", []) expect(klass.extend_class_name).to eq("Post") end it "gets extend class name with module" do klass = Klass.new("BlogPost", "Post", ["Admin"]) expect(klass.extend_class_name).to eq("Admin::Post") end end it "gets to_s equal to class_name" do klass = Klass.new("BlogPost", "Post", ["Admin"]) expect(klass.to_s).to eq(klass.class_name) end end end end
mit
sekcheong/referencesource
mscorlib/system/arithmeticexception.cs
1736
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ArithmeticException ** ** ** Purpose: Exception class for bad arithmetic conditions! ** ** =============================================================================*/ namespace System { using System; using System.Runtime.Serialization; // The ArithmeticException is thrown when overflow or underflow // occurs. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class ArithmeticException : SystemException { // Creates a new ArithmeticException with its message string set to // the empty string, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. public ArithmeticException() : base(Environment.GetResourceString("Arg_ArithmeticException")) { SetErrorCode(__HResults.COR_E_ARITHMETIC); } // Creates a new ArithmeticException with its message string set to // message, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. // public ArithmeticException(String message) : base(message) { SetErrorCode(__HResults.COR_E_ARITHMETIC); } public ArithmeticException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_ARITHMETIC); } protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
mit
pniebla/test-repo-console
svn/git-1.8.3.3.tar/git-1.8.3.3/git-1.8.3.3/cache-tree.c
16875
#include "cache.h" #include "tree.h" #include "tree-walk.h" #include "cache-tree.h" #ifndef DEBUG #define DEBUG 0 #endif struct cache_tree *cache_tree(void) { struct cache_tree *it = xcalloc(1, sizeof(struct cache_tree)); it->entry_count = -1; return it; } void cache_tree_free(struct cache_tree **it_p) { int i; struct cache_tree *it = *it_p; if (!it) return; for (i = 0; i < it->subtree_nr; i++) if (it->down[i]) { cache_tree_free(&it->down[i]->cache_tree); free(it->down[i]); } free(it->down); free(it); *it_p = NULL; } static int subtree_name_cmp(const char *one, int onelen, const char *two, int twolen) { if (onelen < twolen) return -1; if (twolen < onelen) return 1; return memcmp(one, two, onelen); } static int subtree_pos(struct cache_tree *it, const char *path, int pathlen) { struct cache_tree_sub **down = it->down; int lo, hi; lo = 0; hi = it->subtree_nr; while (lo < hi) { int mi = (lo + hi) / 2; struct cache_tree_sub *mdl = down[mi]; int cmp = subtree_name_cmp(path, pathlen, mdl->name, mdl->namelen); if (!cmp) return mi; if (cmp < 0) hi = mi; else lo = mi + 1; } return -lo-1; } static struct cache_tree_sub *find_subtree(struct cache_tree *it, const char *path, int pathlen, int create) { struct cache_tree_sub *down; int pos = subtree_pos(it, path, pathlen); if (0 <= pos) return it->down[pos]; if (!create) return NULL; pos = -pos-1; if (it->subtree_alloc <= it->subtree_nr) { it->subtree_alloc = alloc_nr(it->subtree_alloc); it->down = xrealloc(it->down, it->subtree_alloc * sizeof(*it->down)); } it->subtree_nr++; down = xmalloc(sizeof(*down) + pathlen + 1); down->cache_tree = NULL; down->namelen = pathlen; memcpy(down->name, path, pathlen); down->name[pathlen] = 0; if (pos < it->subtree_nr) memmove(it->down + pos + 1, it->down + pos, sizeof(down) * (it->subtree_nr - pos - 1)); it->down[pos] = down; return down; } struct cache_tree_sub *cache_tree_sub(struct cache_tree *it, const char *path) { int pathlen = strlen(path); return find_subtree(it, path, pathlen, 1); } void cache_tree_invalidate_path(struct cache_tree *it, const char *path) { /* a/b/c * ==> invalidate self * ==> find "a", have it invalidate "b/c" * a * ==> invalidate self * ==> if "a" exists as a subtree, remove it. */ const char *slash; int namelen; struct cache_tree_sub *down; #if DEBUG fprintf(stderr, "cache-tree invalidate <%s>\n", path); #endif if (!it) return; slash = strchr(path, '/'); it->entry_count = -1; if (!slash) { int pos; namelen = strlen(path); pos = subtree_pos(it, path, namelen); if (0 <= pos) { cache_tree_free(&it->down[pos]->cache_tree); free(it->down[pos]); /* 0 1 2 3 4 5 * ^ ^subtree_nr = 6 * pos * move 4 and 5 up one place (2 entries) * 2 = 6 - 3 - 1 = subtree_nr - pos - 1 */ memmove(it->down+pos, it->down+pos+1, sizeof(struct cache_tree_sub *) * (it->subtree_nr - pos - 1)); it->subtree_nr--; } return; } namelen = slash - path; down = find_subtree(it, path, namelen, 0); if (down) cache_tree_invalidate_path(down->cache_tree, slash + 1); } static int verify_cache(struct cache_entry **cache, int entries, int flags) { int i, funny; int silent = flags & WRITE_TREE_SILENT; /* Verify that the tree is merged */ funny = 0; for (i = 0; i < entries; i++) { struct cache_entry *ce = cache[i]; if (ce_stage(ce)) { if (silent) return -1; if (10 < ++funny) { fprintf(stderr, "...\n"); break; } fprintf(stderr, "%s: unmerged (%s)\n", ce->name, sha1_to_hex(ce->sha1)); } } if (funny) return -1; /* Also verify that the cache does not have path and path/file * at the same time. At this point we know the cache has only * stage 0 entries. */ funny = 0; for (i = 0; i < entries - 1; i++) { /* path/file always comes after path because of the way * the cache is sorted. Also path can appear only once, * which means conflicting one would immediately follow. */ const char *this_name = cache[i]->name; const char *next_name = cache[i+1]->name; int this_len = strlen(this_name); if (this_len < strlen(next_name) && strncmp(this_name, next_name, this_len) == 0 && next_name[this_len] == '/') { if (10 < ++funny) { fprintf(stderr, "...\n"); break; } fprintf(stderr, "You have both %s and %s\n", this_name, next_name); } } if (funny) return -1; return 0; } static void discard_unused_subtrees(struct cache_tree *it) { struct cache_tree_sub **down = it->down; int nr = it->subtree_nr; int dst, src; for (dst = src = 0; src < nr; src++) { struct cache_tree_sub *s = down[src]; if (s->used) down[dst++] = s; else { cache_tree_free(&s->cache_tree); free(s); it->subtree_nr--; } } } int cache_tree_fully_valid(struct cache_tree *it) { int i; if (!it) return 0; if (it->entry_count < 0 || !has_sha1_file(it->sha1)) return 0; for (i = 0; i < it->subtree_nr; i++) { if (!cache_tree_fully_valid(it->down[i]->cache_tree)) return 0; } return 1; } static int update_one(struct cache_tree *it, struct cache_entry **cache, int entries, const char *base, int baselen, int *skip_count, int flags) { struct strbuf buffer; int missing_ok = flags & WRITE_TREE_MISSING_OK; int dryrun = flags & WRITE_TREE_DRY_RUN; int to_invalidate = 0; int i; *skip_count = 0; if (0 <= it->entry_count && has_sha1_file(it->sha1)) return it->entry_count; /* * We first scan for subtrees and update them; we start by * marking existing subtrees -- the ones that are unmarked * should not be in the result. */ for (i = 0; i < it->subtree_nr; i++) it->down[i]->used = 0; /* * Find the subtrees and update them. */ i = 0; while (i < entries) { struct cache_entry *ce = cache[i]; struct cache_tree_sub *sub; const char *path, *slash; int pathlen, sublen, subcnt, subskip; path = ce->name; pathlen = ce_namelen(ce); if (pathlen <= baselen || memcmp(base, path, baselen)) break; /* at the end of this level */ slash = strchr(path + baselen, '/'); if (!slash) { i++; continue; } /* * a/bbb/c (base = a/, slash = /c) * ==> * path+baselen = bbb/c, sublen = 3 */ sublen = slash - (path + baselen); sub = find_subtree(it, path + baselen, sublen, 1); if (!sub->cache_tree) sub->cache_tree = cache_tree(); subcnt = update_one(sub->cache_tree, cache + i, entries - i, path, baselen + sublen + 1, &subskip, flags); if (subcnt < 0) return subcnt; i += subcnt; sub->count = subcnt; /* to be used in the next loop */ *skip_count += subskip; sub->used = 1; } discard_unused_subtrees(it); /* * Then write out the tree object for this level. */ strbuf_init(&buffer, 8192); i = 0; while (i < entries) { struct cache_entry *ce = cache[i]; struct cache_tree_sub *sub; const char *path, *slash; int pathlen, entlen; const unsigned char *sha1; unsigned mode; path = ce->name; pathlen = ce_namelen(ce); if (pathlen <= baselen || memcmp(base, path, baselen)) break; /* at the end of this level */ slash = strchr(path + baselen, '/'); if (slash) { entlen = slash - (path + baselen); sub = find_subtree(it, path + baselen, entlen, 0); if (!sub) die("cache-tree.c: '%.*s' in '%s' not found", entlen, path + baselen, path); i += sub->count; sha1 = sub->cache_tree->sha1; mode = S_IFDIR; if (sub->cache_tree->entry_count < 0) to_invalidate = 1; } else { sha1 = ce->sha1; mode = ce->ce_mode; entlen = pathlen - baselen; i++; } if (mode != S_IFGITLINK && !missing_ok && !has_sha1_file(sha1)) { strbuf_release(&buffer); return error("invalid object %06o %s for '%.*s'", mode, sha1_to_hex(sha1), entlen+baselen, path); } /* * CE_REMOVE entries are removed before the index is * written to disk. Skip them to remain consistent * with the future on-disk index. */ if (ce->ce_flags & CE_REMOVE) { *skip_count = *skip_count + 1; continue; } /* * CE_INTENT_TO_ADD entries exist on on-disk index but * they are not part of generated trees. Invalidate up * to root to force cache-tree users to read elsewhere. */ if (ce->ce_flags & CE_INTENT_TO_ADD) { to_invalidate = 1; continue; } strbuf_grow(&buffer, entlen + 100); strbuf_addf(&buffer, "%o %.*s%c", mode, entlen, path + baselen, '\0'); strbuf_add(&buffer, sha1, 20); #if DEBUG fprintf(stderr, "cache-tree update-one %o %.*s\n", mode, entlen, path + baselen); #endif } if (dryrun) hash_sha1_file(buffer.buf, buffer.len, tree_type, it->sha1); else if (write_sha1_file(buffer.buf, buffer.len, tree_type, it->sha1)) { strbuf_release(&buffer); return -1; } strbuf_release(&buffer); it->entry_count = to_invalidate ? -1 : i - *skip_count; #if DEBUG fprintf(stderr, "cache-tree update-one (%d ent, %d subtree) %s\n", it->entry_count, it->subtree_nr, sha1_to_hex(it->sha1)); #endif return i; } int cache_tree_update(struct cache_tree *it, struct cache_entry **cache, int entries, int flags) { int i, skip; i = verify_cache(cache, entries, flags); if (i) return i; i = update_one(it, cache, entries, "", 0, &skip, flags); if (i < 0) return i; return 0; } static void write_one(struct strbuf *buffer, struct cache_tree *it, const char *path, int pathlen) { int i; /* One "cache-tree" entry consists of the following: * path (NUL terminated) * entry_count, subtree_nr ("%d %d\n") * tree-sha1 (missing if invalid) * subtree_nr "cache-tree" entries for subtrees. */ strbuf_grow(buffer, pathlen + 100); strbuf_add(buffer, path, pathlen); strbuf_addf(buffer, "%c%d %d\n", 0, it->entry_count, it->subtree_nr); #if DEBUG if (0 <= it->entry_count) fprintf(stderr, "cache-tree <%.*s> (%d ent, %d subtree) %s\n", pathlen, path, it->entry_count, it->subtree_nr, sha1_to_hex(it->sha1)); else fprintf(stderr, "cache-tree <%.*s> (%d subtree) invalid\n", pathlen, path, it->subtree_nr); #endif if (0 <= it->entry_count) { strbuf_add(buffer, it->sha1, 20); } for (i = 0; i < it->subtree_nr; i++) { struct cache_tree_sub *down = it->down[i]; if (i) { struct cache_tree_sub *prev = it->down[i-1]; if (subtree_name_cmp(down->name, down->namelen, prev->name, prev->namelen) <= 0) die("fatal - unsorted cache subtree"); } write_one(buffer, down->cache_tree, down->name, down->namelen); } } void cache_tree_write(struct strbuf *sb, struct cache_tree *root) { write_one(sb, root, "", 0); } static struct cache_tree *read_one(const char **buffer, unsigned long *size_p) { const char *buf = *buffer; unsigned long size = *size_p; const char *cp; char *ep; struct cache_tree *it; int i, subtree_nr; it = NULL; /* skip name, but make sure name exists */ while (size && *buf) { size--; buf++; } if (!size) goto free_return; buf++; size--; it = cache_tree(); cp = buf; it->entry_count = strtol(cp, &ep, 10); if (cp == ep) goto free_return; cp = ep; subtree_nr = strtol(cp, &ep, 10); if (cp == ep) goto free_return; while (size && *buf && *buf != '\n') { size--; buf++; } if (!size) goto free_return; buf++; size--; if (0 <= it->entry_count) { if (size < 20) goto free_return; hashcpy(it->sha1, (const unsigned char*)buf); buf += 20; size -= 20; } #if DEBUG if (0 <= it->entry_count) fprintf(stderr, "cache-tree <%s> (%d ent, %d subtree) %s\n", *buffer, it->entry_count, subtree_nr, sha1_to_hex(it->sha1)); else fprintf(stderr, "cache-tree <%s> (%d subtrees) invalid\n", *buffer, subtree_nr); #endif /* * Just a heuristic -- we do not add directories that often but * we do not want to have to extend it immediately when we do, * hence +2. */ it->subtree_alloc = subtree_nr + 2; it->down = xcalloc(it->subtree_alloc, sizeof(struct cache_tree_sub *)); for (i = 0; i < subtree_nr; i++) { /* read each subtree */ struct cache_tree *sub; struct cache_tree_sub *subtree; const char *name = buf; sub = read_one(&buf, &size); if (!sub) goto free_return; subtree = cache_tree_sub(it, name); subtree->cache_tree = sub; } if (subtree_nr != it->subtree_nr) die("cache-tree: internal error"); *buffer = buf; *size_p = size; return it; free_return: cache_tree_free(&it); return NULL; } struct cache_tree *cache_tree_read(const char *buffer, unsigned long size) { if (buffer[0]) return NULL; /* not the whole tree */ return read_one(&buffer, &size); } static struct cache_tree *cache_tree_find(struct cache_tree *it, const char *path) { if (!it) return NULL; while (*path) { const char *slash; struct cache_tree_sub *sub; slash = strchr(path, '/'); if (!slash) slash = path + strlen(path); /* between path and slash is the name of the * subtree to look for. */ sub = find_subtree(it, path, slash - path, 0); if (!sub) return NULL; it = sub->cache_tree; if (slash) while (*slash && *slash == '/') slash++; if (!slash || !*slash) return it; /* prefix ended with slashes */ path = slash; } return it; } int write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix) { int entries, was_valid, newfd; struct lock_file *lock_file; /* * We can't free this memory, it becomes part of a linked list * parsed atexit() */ lock_file = xcalloc(1, sizeof(struct lock_file)); newfd = hold_locked_index(lock_file, 1); entries = read_cache(); if (entries < 0) return WRITE_TREE_UNREADABLE_INDEX; if (flags & WRITE_TREE_IGNORE_CACHE_TREE) cache_tree_free(&(active_cache_tree)); if (!active_cache_tree) active_cache_tree = cache_tree(); was_valid = cache_tree_fully_valid(active_cache_tree); if (!was_valid) { if (cache_tree_update(active_cache_tree, active_cache, active_nr, flags) < 0) return WRITE_TREE_UNMERGED_INDEX; if (0 <= newfd) { if (!write_cache(newfd, active_cache, active_nr) && !commit_lock_file(lock_file)) newfd = -1; } /* Not being able to write is fine -- we are only interested * in updating the cache-tree part, and if the next caller * ends up using the old index with unupdated cache-tree part * it misses the work we did here, but that is just a * performance penalty and not a big deal. */ } if (prefix) { struct cache_tree *subtree = cache_tree_find(active_cache_tree, prefix); if (!subtree) return WRITE_TREE_PREFIX_ERROR; hashcpy(sha1, subtree->sha1); } else hashcpy(sha1, active_cache_tree->sha1); if (0 <= newfd) rollback_lock_file(lock_file); return 0; } static void prime_cache_tree_rec(struct cache_tree *it, struct tree *tree) { struct tree_desc desc; struct name_entry entry; int cnt; hashcpy(it->sha1, tree->object.sha1); init_tree_desc(&desc, tree->buffer, tree->size); cnt = 0; while (tree_entry(&desc, &entry)) { if (!S_ISDIR(entry.mode)) cnt++; else { struct cache_tree_sub *sub; struct tree *subtree = lookup_tree(entry.sha1); if (!subtree->object.parsed) parse_tree(subtree); sub = cache_tree_sub(it, entry.path); sub->cache_tree = cache_tree(); prime_cache_tree_rec(sub->cache_tree, subtree); cnt += sub->cache_tree->entry_count; } } it->entry_count = cnt; } void prime_cache_tree(struct cache_tree **it, struct tree *tree) { cache_tree_free(it); *it = cache_tree(); prime_cache_tree_rec(*it, tree); } /* * find the cache_tree that corresponds to the current level without * exploding the full path into textual form. The root of the * cache tree is given as "root", and our current level is "info". * (1) When at root level, info->prev is NULL, so it is "root" itself. * (2) Otherwise, find the cache_tree that corresponds to one level * above us, and find ourselves in there. */ static struct cache_tree *find_cache_tree_from_traversal(struct cache_tree *root, struct traverse_info *info) { struct cache_tree *our_parent; if (!info->prev) return root; our_parent = find_cache_tree_from_traversal(root, info->prev); return cache_tree_find(our_parent, info->name.path); } int cache_tree_matches_traversal(struct cache_tree *root, struct name_entry *ent, struct traverse_info *info) { struct cache_tree *it; it = find_cache_tree_from_traversal(root, info); it = cache_tree_find(it, ent->path); if (it && it->entry_count > 0 && !hashcmp(ent->sha1, it->sha1)) return it->entry_count; return 0; } int update_main_cache_tree(int flags) { if (!the_index.cache_tree) the_index.cache_tree = cache_tree(); return cache_tree_update(the_index.cache_tree, the_index.cache, the_index.cache_nr, flags); }
mit
AlexGhiondea/buildtools
src/Microsoft.DotNet.Build.VstsBuildsApi/VstsReleaseHttpClient.cs
2198
// 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. using Microsoft.DotNet.Build.VstsBuildsApi.Configuration; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Microsoft.DotNet.Build.VstsBuildsApi { internal class VstsReleaseHttpClient : VstsDefinitionHttpClient { private const string ReleaseApiType = "release"; public VstsReleaseHttpClient(JObject definition, VstsApiEndpointConfig config) : base(new Uri(definition["url"].ToString()), config, ReleaseApiType) { } public override async Task<JObject> UpdateDefinitionAsync(JObject definition) => await JsonClient.PutAsync( GetRequestUri(definition, "definitions"), definition); protected override bool IsMatching(JObject localDefinition, JObject retrievedDefinition) { return localDefinition["name"].ToString() == retrievedDefinition["name"].ToString(); } protected override IEnumerable<JObject> FindObjectsWithIdentifiableProperties(JObject definition) { IEnumerable<JObject> environments = definition["environments"].Children<JObject>(); IEnumerable<JObject> approvals = environments .SelectMany(env => new[] { env["preDeployApprovals"], env["postDeployApprovals"] }) .SelectMany(approvalWrapper => approvalWrapper["approvals"].Values<JObject>()); return new[] { definition } .Concat(environments) .Concat(approvals); } /// <summary> /// From a url like https://devdiv.vsrm.visualstudio.com/1234/_apis/Release/definitions/1 /// in the url property of the given definition, gets the project, "1234". /// </summary> protected override string GetDefinitionProject(JObject definition) { return new Uri(definition["url"].ToString()).Segments[1].TrimEnd('/'); } } }
mit
nbarbettini/corefx
src/shims/manual/mscorlib.forwards.cs
3065
// 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. // Add any internal types that we need to forward from mscorlib. // These types are required for Desktop to Core serialization as they are not covered by GenAPI because they are marked as internal. [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.CultureAwareComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.OrdinalComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.GenericComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NullableComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ObjectComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.GenericEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NullableEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ObjectEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NonRandomizedStringEqualityComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ByteEqualityComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.EnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.SByteEnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ShortEnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.LongEnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.ListDictionaryInternal))] // This is temporary as we are building the mscorlib shim against netfx461 which doesn't contain ValueTuples. [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,,,>))]
mit
MelanieGault/puppet-logrotate
spec/defines/rule_spec.rb
30362
require 'spec_helper' describe 'logrotate::rule' do context 'with an alphanumeric title' do let(:title) { 'test' } context 'and ensure => absent' do let(:params) { {:ensure => 'absent'} } it do should contain_file('/etc/logrotate.d/test').with_ensure('absent') end end let(:params) { {:path => '/var/log/foo.log'} } it do should contain_class('logrotate::base') should contain_file('/etc/logrotate.d/test').with({ 'owner' => 'root', 'group' => 'root', 'ensure' => 'present', 'mode' => '0444', }).with_content(%r{^/var/log/foo\.log \{\n\}\n}) end context 'with an array path' do let (:params) { {:path => ['/var/log/foo1.log','/var/log/foo2.log']} } it do should contain_file('/etc/logrotate.d/test').with_content( %r{/var/log/foo1\.log /var/log/foo2\.log \{\n\}\n} ) end end ########################################################################### # COMPRESS context 'and compress => true' do let(:params) { {:path => '/var/log/foo.log', :compress => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ compress$/) end end context 'and compress => false' do let(:params) { {:path => '/var/log/foo.log', :compress => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nocompress$/) end end context 'and compress => foo' do let(:params) { {:path => '/var/log/foo.log', :compress => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /compress must be a boolean/) end end ########################################################################### # COMPRESSCMD context 'and compresscmd => bzip2' do let(:params) { {:path => '/var/log/foo.log', :compresscmd => 'bzip2'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ compresscmd bzip2$/) end end ########################################################################### # COMPRESSEXT context 'and compressext => .bz2' do let(:params) { {:path => '/var/log/foo.log', :compressext => '.bz2'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ compressext .bz2$/) end end ########################################################################### # COMPRESSOPTIONS context 'and compressoptions => -9' do let(:params) { {:path => '/var/log/foo.log', :compressoptions => '-9'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ compressoptions -9$/) end end ########################################################################### # COPY context 'and copy => true' do let(:params) { {:path => '/var/log/foo.log', :copy => true} } it do should contain_file('/etc/logrotate.d/test').with_content(/^ copy$/) end end context 'and copy => false' do let(:params) { {:path => '/var/log/foo.log', :copy => false} } it do should contain_file('/etc/logrotate.d/test').with_content(/^ nocopy$/) end end context 'and copy => foo' do let(:params) { {:path => '/var/log/foo.log', :copy => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /copy must be a boolean/) end end ########################################################################### # COPYTRUNCATE context 'and copytruncate => true' do let(:params) { {:path => '/var/log/foo.log', :copytruncate => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ copytruncate$/) end end context 'and copytruncate => false' do let(:params) { {:path => '/var/log/foo.log', :copytruncate => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nocopytruncate$/) end end context 'and copytruncate => foo' do let(:params) { {:path => '/var/log/foo.log', :copytruncate => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /copytruncate must be a boolean/) end end ########################################################################### # CREATE / CREATE_MODE / CREATE_OWNER / CREATE_GROUP context 'and create => true' do let(:params) { {:path => '/var/log/foo.log', :create => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ create$/) end context 'and create_mode => 0777' do let(:params) { { :path => '/var/log/foo.log', :create => true, :create_mode => '0777', } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ create 0777$/) end context 'and create_owner => www-data' do let(:params) { { :path => '/var/log/foo.log', :create => true, :create_mode => '0777', :create_owner => 'www-data', } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ create 0777 www-data/) end context 'and create_group => admin' do let(:params) { { :path => '/var/log/foo.log', :create => true, :create_mode => '0777', :create_owner => 'www-data', :create_group => 'admin', } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ create 0777 www-data admin$/) end end end context 'and create_group => admin' do let(:params) { { :path => '/var/log/foo.log', :create => true, :create_mode => '0777', :create_group => 'admin', } } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /create_group requires create_owner/) end end end context 'and create_owner => www-data' do let(:params) { { :path => '/var/log/foo.log', :create => true, :create_owner => 'www-data', } } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /create_owner requires create_mode/) end end end context 'and create => false' do let(:params) { {:path => '/var/log/foo.log', :create => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nocreate$/) end context 'and create_mode => 0777' do let(:params) { { :path => '/var/log/foo.log', :create => false, :create_mode => '0777', } } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /create_mode requires create/) end end end context 'and create => foo' do let(:params) { {:path => '/var/log/foo.log', :create => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /create must be a boolean/) end end ########################################################################### # DATEEXT context 'and dateext => true' do let(:params) { {:path => '/var/log/foo.log', :dateext => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ dateext$/) end end context 'and dateext => false' do let(:params) { {:path => '/var/log/foo.log', :dateext => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nodateext$/) end end context 'and dateext => foo' do let(:params) { {:path => '/var/log/foo.log', :dateext => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /dateext must be a boolean/) end end ########################################################################### # DATEFORMAT context 'and dateformat => -%Y%m%d' do let(:params) { {:path => '/var/log/foo.log', :dateformat => '-%Y%m%d'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ dateformat -%Y%m%d$/) end end ########################################################################### # DELAYCOMPRESS context 'and delaycompress => true' do let(:params) { {:path => '/var/log/foo.log', :delaycompress => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ delaycompress$/) end end context 'and delaycompress => false' do let(:params) { {:path => '/var/log/foo.log', :delaycompress => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nodelaycompress$/) end end context 'and delaycompress => foo' do let(:params) { {:path => '/var/log/foo.log', :delaycompress => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /delaycompress must be a boolean/) end end ########################################################################### # EXTENSION context 'and extension => foo' do let(:params) { {:path => '/var/log/foo.log', :extension => '.foo'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ extension \.foo$/) end end ########################################################################### # IFEMPTY context 'and ifempty => true' do let(:params) { {:path => '/var/log/foo.log', :ifempty => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ ifempty$/) end end context 'and ifempty => false' do let(:params) { {:path => '/var/log/foo.log', :ifempty => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ notifempty$/) end end context 'and ifempty => foo' do let(:params) { {:path => '/var/log/foo.log', :ifempty => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /ifempty must be a boolean/) end end ########################################################################### # MAIL / MAILFIRST / MAILLAST context 'and mail => test.example.com' do let(:params) { {:path => '/var/log/foo.log', :mail => '[email protected]'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ mail [email protected]$/) end context 'and mailfirst => true' do let(:params) { { :path => '/var/log/foo.log', :mail => '[email protected]', :mailfirst => true, } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ mailfirst$/) end context 'and maillast => true' do let(:params) { { :path => '/var/log/foo.log', :mail => '[email protected]', :mailfirst => true, :maillast => true, } } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /set both mailfirst and maillast/) end end end context 'and maillast => true' do let(:params) { { :path => '/var/log/foo.log', :mail => '[email protected]', :maillast => true, } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ maillast$/) end end end context 'and mail => false' do let(:params) { {:path => '/var/log/foo.log', :mail => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nomail$/) end end ########################################################################### # MAXAGE context 'and maxage => 3' do let(:params) { {:path => '/var/log/foo.log', :maxage => 3} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ maxage 3$/) end end context 'and maxage => foo' do let(:params) { {:path => '/var/log/foo.log', :maxage => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /maxage must be an integer/) end end ########################################################################### # MINSIZE context 'and minsize => 100' do let(:params) { {:path => '/var/log/foo.log', :minsize => 100} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ minsize 100$/) end end context 'and minsize => 100k' do let(:params) { {:path => '/var/log/foo.log', :minsize => '100k'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ minsize 100k$/) end end context 'and minsize => 100M' do let(:params) { {:path => '/var/log/foo.log', :minsize => '100M'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ minsize 100M$/) end end context 'and minsize => 100G' do let(:params) { {:path => '/var/log/foo.log', :minsize => '100G'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ minsize 100G$/) end end context 'and minsize => foo' do let(:params) { {:path => '/var/log/foo.log', :minsize => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /minsize must match/) end end ########################################################################### # MISSINGOK context 'and missingok => true' do let(:params) { {:path => '/var/log/foo.log', :missingok => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ missingok$/) end end context 'and missingok => false' do let(:params) { {:path => '/var/log/foo.log', :missingok => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nomissingok$/) end end context 'and missingok => foo' do let(:params) { {:path => '/var/log/foo.log', :missingok => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /missingok must be a boolean/) end end ########################################################################### # OLDDIR context 'and olddir => /var/log/old' do let(:params) { {:path => '/var/log/foo.log', :olddir => '/var/log/old'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ olddir \/var\/log\/old$/) end end context 'and olddir => false' do let(:params) { {:path => '/var/log/foo.log', :olddir => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ noolddir$/) end end ########################################################################### # POSTROTATE context 'and postrotate => /bin/true' do let(:params) { {:path => '/var/log/foo.log', :postrotate => '/bin/true'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/postrotate\n \/bin\/true\n endscript/) end end context "and postrotate => ['/bin/true', '/bin/false']" do let(:params) { {:path => '/var/log/foo.log', :postrotate => ['/bin/true', '/bin/false']} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/postrotate\n \/bin\/true\n \/bin\/false\n endscript/) end end ########################################################################### # PREROTATE context 'and prerotate => /bin/true' do let(:params) { {:path => '/var/log/foo.log', :prerotate => '/bin/true'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/prerotate\n \/bin\/true\n endscript/) end end context "and prerotate => ['/bin/true', '/bin/false']" do let(:params) { {:path => '/var/log/foo.log', :prerotate => ['/bin/true', '/bin/false']} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/prerotate\n \/bin\/true\n \/bin\/false\n endscript/) end end ########################################################################### # FIRSTACTION context 'and firstaction => /bin/true' do let(:params) { {:path => '/var/log/foo.log', :firstaction => '/bin/true'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/firstaction\n \/bin\/true\n endscript/) end end context "and firstaction => ['/bin/true', '/bin/false']" do let(:params) { {:path => '/var/log/foo.log', :firstaction => ['/bin/true', '/bin/false']} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/firstaction\n \/bin\/true\n \/bin\/false\n endscript/) end end ########################################################################### # LASTACTION context 'and lastaction => /bin/true' do let(:params) { {:path => '/var/log/foo.log', :lastaction => '/bin/true'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/lastaction\n \/bin\/true\n endscript/) end end context "and lastaction => ['/bin/true', '/bin/false']" do let(:params) { {:path => '/var/log/foo.log', :lastaction => ['/bin/true', '/bin/false']} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/lastaction\n \/bin\/true\n \/bin\/false\n endscript/) end end ########################################################################### # ROTATE context 'and rotate => 3' do let(:params) { {:path => '/var/log/foo.log', :rotate => 3} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ rotate 3$/) end end context 'and rotate => foo' do let(:params) { {:path => '/var/log/foo.log', :rotate => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /rotate must be an integer/) end end ########################################################################### # ROTATE_EVERY context 'and rotate_every => hour' do let(:params) { {:path => '/var/log/foo.log', :rotate_every => 'hour'} } it { should contain_class('logrotate::hourly') } it { should contain_file('/etc/logrotate.d/hourly/test') } it { should contain_file('/etc/logrotate.d/test').with_ensure('absent') } end context 'and rotate_every => day' do let(:params) { {:path => '/var/log/foo.log', :rotate_every => 'day'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ daily$/) end it do should contain_file('/etc/logrotate.d/hourly/test') \ .with_ensure('absent') end end context 'and rotate_every => week' do let(:params) { {:path => '/var/log/foo.log', :rotate_every => 'week'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ weekly$/) end it do should contain_file('/etc/logrotate.d/hourly/test') \ .with_ensure('absent') end end context 'and rotate_every => month' do let(:params) { {:path => '/var/log/foo.log', :rotate_every => 'month'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ monthly$/) end it do should contain_file('/etc/logrotate.d/hourly/test') \ .with_ensure('absent') end end context 'and rotate_every => year' do let(:params) { {:path => '/var/log/foo.log', :rotate_every => 'year'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ yearly$/) end it do should contain_file('/etc/logrotate.d/hourly/test') \ .with_ensure('absent') end end context 'and rotate_every => foo' do let(:params) { {:path => '/var/log/foo.log', :rotate_every => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /invalid rotate_every value/) end end ########################################################################### # SIZE context 'and size => 100' do let(:params) { {:path => '/var/log/foo.log', :size => 100} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ size 100$/) end end context 'and size => 100k' do let(:params) { {:path => '/var/log/foo.log', :size => '100k'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ size 100k$/) end end context 'and size => 100M' do let(:params) { {:path => '/var/log/foo.log', :size => '100M'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ size 100M$/) end end context 'and size => 100G' do let(:params) { {:path => '/var/log/foo.log', :size => '100G'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ size 100G$/) end end context 'and size => foo' do let(:params) { {:path => '/var/log/foo.log', :size => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /size must match/) end end ########################################################################### # SHAREDSCRIPTS context 'and sharedscripts => true' do let(:params) { {:path => '/var/log/foo.log', :sharedscripts => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ sharedscripts$/) end end context 'and sharedscripts => false' do let(:params) { {:path => '/var/log/foo.log', :sharedscripts => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ nosharedscripts$/) end end context 'and sharedscripts => foo' do let(:params) { {:path => '/var/log/foo.log', :sharedscripts => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /sharedscripts must be a boolean/) end end ########################################################################### # SHRED / SHREDCYCLES context 'and shred => true' do let(:params) { {:path => '/var/log/foo.log', :shred => true} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ shred$/) end context 'and shredcycles => 3' do let(:params) { {:path => '/var/log/foo.log', :shred => true, :shredcycles => 3} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ shredcycles 3$/) end end context 'and shredcycles => foo' do let(:params) { {:path => '/var/log/foo.log', :shred => true, :shredcycles => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /shredcycles must be an integer/) end end end context 'and shred => false' do let(:params) { {:path => '/var/log/foo.log', :shred => false} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ noshred$/) end end context 'and shred => foo' do let(:params) { {:path => '/var/log/foo.log', :shred => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /shred must be a boolean/) end end ########################################################################### # START context 'and start => 0' do let(:params) { {:path => '/var/log/foo.log', :start => 0} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ start 0$/) end end context 'and start => foo' do let(:params) { {:path => '/var/log/foo.log', :start => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /start must be an integer/) end end ########################################################################### # SU / SU_OWNER / SU_GROUP context 'and su => true' do let(:params) { {:path => '/var/log/foo.log', :su => true} } context 'and su_owner => www-data' do let(:params) { { :path => '/var/log/foo.log', :su => true, :su_owner => 'www-data', } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ su www-data/) end context 'and su_group => admin' do let(:params) { { :path => '/var/log/foo.log', :su => true, :su_owner => 'www-data', :su_group => 'admin', } } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ su www-data admin$/) end end end context 'and missing su_owner' do let(:params) { { :path => '/var/log/foo.log', :su => true, } } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /su requires su_owner/) end end end context 'and su => false' do let(:params) { {:path => '/var/log/foo.log', :su => false} } it do should_not contain_file('/etc/logrotate.d/test') \ .with_content(/^ su\s/) end context 'and su_owner => wwww-data' do let(:params) { { :path => '/var/log/foo.log', :su => false, :su_owner => 'www-data', } } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /su_owner requires su/) end end end context 'and su => foo' do let(:params) { {:path => '/var/log/foo.log', :su => 'foo'} } it do expect { should contain_file('/etc/logrotate.d/test') }.to raise_error(Puppet::Error, /su must be a boolean/) end end ########################################################################### # UNCOMPRESSCMD context 'and uncompresscmd => bunzip2' do let(:params) { {:path => '/var/log/foo.log', :uncompresscmd => 'bunzip2'} } it do should contain_file('/etc/logrotate.d/test') \ .with_content(/^ uncompresscmd bunzip2$/) end end end context 'with a non-alphanumeric title' do let(:title) { 'foo bar' } let(:params) { {:path => '/var/log/foo.log'} } it do expect { should contain_file('/etc/logrotate.d/foo bar') }.to raise_error(Puppet::Error, /namevar must be alphanumeric/) end end end
mit
Teisi/typo3-deploy
vendor/symfony/console/Tests/Style/SymfonyStyleTest.php
3826
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Console\Tests\Style; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Console\Tester\CommandTester; class SymfonyStyleTest extends TestCase { /** @var Command */ protected $command; /** @var CommandTester */ protected $tester; protected function setUp() { putenv('COLUMNS=121'); $this->command = new Command('sfstyle'); $this->tester = new CommandTester($this->command); } protected function tearDown() { putenv('COLUMNS'); $this->command = null; $this->tester = null; } /** * @dataProvider inputCommandToOutputFilesProvider */ public function testOutputs($inputCommandFilepath, $outputFilepath) { $code = require $inputCommandFilepath; $this->command->setCode($code); $this->tester->execute(array(), array('interactive' => false, 'decorated' => false)); $this->assertStringEqualsFile($outputFilepath, $this->tester->getDisplay(true)); } /** * @dataProvider inputInteractiveCommandToOutputFilesProvider */ public function testInteractiveOutputs($inputCommandFilepath, $outputFilepath) { $code = require $inputCommandFilepath; $this->command->setCode($code); $this->tester->execute(array(), array('interactive' => true, 'decorated' => false)); $this->assertStringEqualsFile($outputFilepath, $this->tester->getDisplay(true)); } public function inputInteractiveCommandToOutputFilesProvider() { $baseDir = __DIR__.'/../Fixtures/Style/SymfonyStyle'; return array_map(null, glob($baseDir.'/command/interactive_command_*.php'), glob($baseDir.'/output/interactive_output_*.txt')); } public function inputCommandToOutputFilesProvider() { $baseDir = __DIR__.'/../Fixtures/Style/SymfonyStyle'; return array_map(null, glob($baseDir.'/command/command_*.php'), glob($baseDir.'/output/output_*.txt')); } public function testGetErrorStyle() { $input = $this->getMockBuilder(InputInterface::class)->getMock(); $errorOutput = $this->getMockBuilder(OutputInterface::class)->getMock(); $errorOutput ->method('getFormatter') ->willReturn(new OutputFormatter()); $errorOutput ->expects($this->once()) ->method('write'); $output = $this->getMockBuilder(ConsoleOutputInterface::class)->getMock(); $output ->method('getFormatter') ->willReturn(new OutputFormatter()); $output ->expects($this->once()) ->method('getErrorOutput') ->willReturn($errorOutput); $io = new SymfonyStyle($input, $output); $io->getErrorStyle()->write(''); } public function testGetErrorStyleUsesTheCurrentOutputIfNoErrorOutputIsAvailable() { $output = $this->getMockBuilder(OutputInterface::class)->getMock(); $output ->method('getFormatter') ->willReturn(new OutputFormatter()); $style = new SymfonyStyle($this->getMockBuilder(InputInterface::class)->getMock(), $output); $this->assertInstanceOf(SymfonyStyle::class, $style->getErrorStyle()); } }
mit
akoeplinger/referencesource
System.ServiceModel/System/ServiceModel/Channels/IMessageSource.cs
733
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Threading; enum AsyncReceiveResult { Completed, Pending, } interface IMessageSource { AsyncReceiveResult BeginReceive(TimeSpan timeout, WaitCallback callback, object state); Message EndReceive(); Message Receive(TimeSpan timeout); AsyncReceiveResult BeginWaitForMessage(TimeSpan timeout, WaitCallback callback, object state); bool EndWaitForMessage(); bool WaitForMessage(TimeSpan timeout); } }
mit
xcaliber-tech/angular
modules/@angular/core/test/di/forward_ref_spec.ts
661
/** * @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 */ import {Type} from '@angular/core'; import {forwardRef, resolveForwardRef} from '@angular/core/src/di'; import {describe, expect, it} from '@angular/core/testing/testing_internal'; export function main() { describe('forwardRef', function() { it('should wrap and unwrap the reference', () => { const ref = forwardRef(() => String); expect(ref instanceof Type).toBe(true); expect(resolveForwardRef(ref)).toBe(String); }); }); }
mit
imadige/zephirbuild
zephir/ext/test/7__closure.zep.c
658
#ifdef HAVE_CONFIG_H #include "../ext_config.h" #endif #include <php.h> #include "../php_ext.h" #include "../ext.h" #include <Zend/zend_operators.h> #include <Zend/zend_exceptions.h> #include <Zend/zend_interfaces.h> #include "kernel/main.h" #include "kernel/operators.h" #include "kernel/memory.h" ZEPHIR_INIT_CLASS(test_7__closure) { ZEPHIR_REGISTER_CLASS(test, 7__closure, test, 7__closure, test_7__closure_method_entry, ZEND_ACC_FINAL_CLASS); return SUCCESS; } PHP_METHOD(test_7__closure, __invoke) { zval *x; zephir_fetch_params(0, 1, 0, &x); RETURN_LONG((((zephir_get_numberval(x) + 100)) + ((zephir_get_numberval(x) * 150)))); }
mit
josephwilk/finger-smudge
vendor/chromaprint/src/chroma_filter.cpp
1885
/* * Chromaprint -- Audio fingerprinting toolkit * Copyright (C) 2010 Lukas Lalinsky <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ #include <limits> #include <assert.h> #include <math.h> #include "chroma_filter.h" #include "utils.h" using namespace std; using namespace Chromaprint; ChromaFilter::ChromaFilter(const double *coefficients, int length, FeatureVectorConsumer *consumer) : m_coefficients(coefficients), m_length(length), m_buffer(8), m_result(12), m_buffer_offset(0), m_buffer_size(1), m_consumer(consumer) { } ChromaFilter::~ChromaFilter() { } void ChromaFilter::Reset() { m_buffer_size = 1; m_buffer_offset = 0; } void ChromaFilter::Consume(std::vector<double> &features) { m_buffer[m_buffer_offset] = features; m_buffer_offset = (m_buffer_offset + 1) % 8; if (m_buffer_size >= m_length) { int offset = (m_buffer_offset + 8 - m_length) % 8; fill(m_result.begin(), m_result.end(), 0.0); for (int i = 0; i < 12; i++) { for (int j = 0; j < m_length; j++) { m_result[i] += m_buffer[(offset + j) % 8][i] * m_coefficients[j]; } } m_consumer->Consume(m_result); } else { m_buffer_size++; } }
epl-1.0
tobiasjakobi/mpv
sub/draw_bmp.c
19551
/* * This file is part of mpv. * * mpv is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * mpv is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with mpv. If not, see <http://www.gnu.org/licenses/>. */ #include <stddef.h> #include <stdbool.h> #include <assert.h> #include <math.h> #include <inttypes.h> #include <libswscale/swscale.h> #include <libavutil/common.h> #include "common/common.h" #include "draw_bmp.h" #include "img_convert.h" #include "video/mp_image.h" #include "video/sws_utils.h" #include "video/img_format.h" #include "video/csputils.h" const bool mp_draw_sub_formats[SUBBITMAP_COUNT] = { [SUBBITMAP_LIBASS] = true, [SUBBITMAP_RGBA] = true, }; struct sub_cache { struct mp_image *i, *a; }; struct part { int change_id; int imgfmt; enum mp_csp colorspace; enum mp_csp_levels levels; int num_imgs; struct sub_cache *imgs; }; struct mp_draw_sub_cache { struct part *parts[MAX_OSD_PARTS]; struct mp_image *upsample_img; struct mp_image upsample_temp; }; static struct part *get_cache(struct mp_draw_sub_cache *cache, struct sub_bitmaps *sbs, struct mp_image *format); static bool get_sub_area(struct mp_rect bb, struct mp_image *temp, struct sub_bitmap *sb, struct mp_image *out_area, int *out_src_x, int *out_src_y); #define CONDITIONAL 1 #define BLEND_CONST_ALPHA(TYPE) \ TYPE *dst_r = dst_rp; \ for (int x = 0; x < w; x++) { \ uint32_t srcap = srca_r[x]; \ if (CONDITIONAL && !srcap) continue; \ srcap *= srcamul; /* now 0..65025 */ \ dst_r[x] = (srcp * srcap + dst_r[x] * (65025 - srcap) + 32512) / 65025; \ } // dst = srcp * (srca * srcamul) + dst * (1 - (srca * srcamul)) static void blend_const_alpha(void *dst, int dst_stride, int srcp, uint8_t *srca, int srca_stride, uint8_t srcamul, int w, int h, int bytes) { if (!srcamul) return; for (int y = 0; y < h; y++) { void *dst_rp = (uint8_t *)dst + dst_stride * y; uint8_t *srca_r = srca + srca_stride * y; if (bytes == 2) { BLEND_CONST_ALPHA(uint16_t) } else if (bytes == 1) { BLEND_CONST_ALPHA(uint8_t) } } } #define BLEND_SRC_ALPHA(TYPE) \ TYPE *dst_r = dst_rp, *src_r = src_rp; \ for (int x = 0; x < w; x++) { \ uint32_t srcap = srca_r[x]; \ if (CONDITIONAL && !srcap) continue; \ dst_r[x] = (src_r[x] * srcap + dst_r[x] * (255 - srcap) + 127) / 255; \ } // dst = src * srca + dst * (1 - srca) static void blend_src_alpha(void *dst, int dst_stride, void *src, int src_stride, uint8_t *srca, int srca_stride, int w, int h, int bytes) { for (int y = 0; y < h; y++) { void *dst_rp = (uint8_t *)dst + dst_stride * y; void *src_rp = (uint8_t *)src + src_stride * y; uint8_t *srca_r = srca + srca_stride * y; if (bytes == 2) { BLEND_SRC_ALPHA(uint16_t) } else if (bytes == 1) { BLEND_SRC_ALPHA(uint8_t) } } } #define BLEND_SRC_DST_MUL(TYPE, MAX) \ TYPE *dst_r = dst_rp; \ for (int x = 0; x < w; x++) { \ uint16_t srcp = src_r[x] * srcmul; /* now 0..65025 */ \ dst_r[x] = (srcp * (MAX) + dst_r[x] * (65025 - srcp) + 32512) / 65025; \ } // dst = src * srcmul + dst * (1 - src * srcmul) static void blend_src_dst_mul(void *dst, int dst_stride, uint8_t *src, int src_stride, uint8_t srcmul, int w, int h, int dst_bytes) { for (int y = 0; y < h; y++) { void *dst_rp = (uint8_t *)dst + dst_stride * y; uint8_t *src_r = (uint8_t *)src + src_stride * y; if (dst_bytes == 2) { BLEND_SRC_DST_MUL(uint16_t, 65025) } else if (dst_bytes == 1) { BLEND_SRC_DST_MUL(uint8_t, 255) } } } static void unpremultiply_and_split_BGR32(struct mp_image *img, struct mp_image *alpha) { for (int y = 0; y < img->h; ++y) { uint32_t *irow = (uint32_t *) &img->planes[0][img->stride[0] * y]; uint8_t *arow = &alpha->planes[0][alpha->stride[0] * y]; for (int x = 0; x < img->w; ++x) { uint32_t pval = irow[x]; uint8_t aval = (pval >> 24); uint8_t rval = (pval >> 16) & 0xFF; uint8_t gval = (pval >> 8) & 0xFF; uint8_t bval = pval & 0xFF; // multiplied = separate * alpha / 255 // separate = rint(multiplied * 255 / alpha) // = floor(multiplied * 255 / alpha + 0.5) // = floor((multiplied * 255 + 0.5 * alpha) / alpha) // = floor((multiplied * 255 + floor(0.5 * alpha)) / alpha) int div = (int) aval; int add = div / 2; if (aval) { rval = FFMIN(255, (rval * 255 + add) / div); gval = FFMIN(255, (gval * 255 + add) / div); bval = FFMIN(255, (bval * 255 + add) / div); irow[x] = bval + (gval << 8) + (rval << 16) + (aval << 24); } arow[x] = aval; } } } // dst_format merely contains the target colorspace/format information static void scale_sb_rgba(struct sub_bitmap *sb, struct mp_image *dst_format, struct mp_image **out_sbi, struct mp_image **out_sba) { struct mp_image sbisrc = {0}; mp_image_setfmt(&sbisrc, IMGFMT_BGR32); mp_image_set_size(&sbisrc, sb->w, sb->h); sbisrc.planes[0] = sb->bitmap; sbisrc.stride[0] = sb->stride; struct mp_image *sbisrc2 = mp_image_alloc(IMGFMT_BGR32, sb->dw, sb->dh); struct mp_image *sba = mp_image_alloc(IMGFMT_Y8, sb->dw, sb->dh); struct mp_image *sbi = mp_image_alloc(dst_format->imgfmt, sb->dw, sb->dh); if (!sbisrc2 || !sba || !sbi) { talloc_free(sbisrc2); talloc_free(sba); talloc_free(sbi); return; } mp_image_swscale(sbisrc2, &sbisrc, SWS_BILINEAR); unpremultiply_and_split_BGR32(sbisrc2, sba); sbi->params.color = dst_format->params.color; mp_image_swscale(sbi, sbisrc2, SWS_BILINEAR); talloc_free(sbisrc2); *out_sbi = sbi; *out_sba = sba; } static void draw_rgba(struct mp_draw_sub_cache *cache, struct mp_rect bb, struct mp_image *temp, int bits, struct sub_bitmaps *sbs) { struct part *part = get_cache(cache, sbs, temp); assert(part); for (int i = 0; i < sbs->num_parts; ++i) { struct sub_bitmap *sb = &sbs->parts[i]; if (sb->w < 1 || sb->h < 1) continue; struct mp_image dst; int src_x, src_y; if (!get_sub_area(bb, temp, sb, &dst, &src_x, &src_y)) continue; struct mp_image *sbi = part->imgs[i].i; struct mp_image *sba = part->imgs[i].a; if (!(sbi && sba)) scale_sb_rgba(sb, temp, &sbi, &sba); // on OOM, skip drawing if (!(sbi && sba)) continue; int bytes = (bits + 7) / 8; uint8_t *alpha_p = sba->planes[0] + src_y * sba->stride[0] + src_x; for (int p = 0; p < (temp->num_planes > 2 ? 3 : 1); p++) { void *src = sbi->planes[p] + src_y * sbi->stride[p] + src_x * bytes; blend_src_alpha(dst.planes[p], dst.stride[p], src, sbi->stride[p], alpha_p, sba->stride[0], dst.w, dst.h, bytes); } if (temp->num_planes >= 4) { blend_src_dst_mul(dst.planes[3], dst.stride[3], alpha_p, sba->stride[0], 255, dst.w, dst.h, bytes); } part->imgs[i].i = talloc_steal(part, sbi); part->imgs[i].a = talloc_steal(part, sba); } } static void draw_ass(struct mp_draw_sub_cache *cache, struct mp_rect bb, struct mp_image *temp, int bits, struct sub_bitmaps *sbs) { struct mp_csp_params cspar = MP_CSP_PARAMS_DEFAULTS; mp_csp_set_image_params(&cspar, &temp->params); cspar.levels_out = MP_CSP_LEVELS_PC; // RGB (libass.color) cspar.input_bits = bits; cspar.texture_bits = (bits + 7) / 8 * 8; struct mp_cmat yuv2rgb, rgb2yuv; bool need_conv = temp->fmt.flags & MP_IMGFLAG_YUV; if (need_conv) { mp_get_csp_matrix(&cspar, &yuv2rgb); mp_invert_cmat(&rgb2yuv, &yuv2rgb); } for (int i = 0; i < sbs->num_parts; ++i) { struct sub_bitmap *sb = &sbs->parts[i]; struct mp_image dst; int src_x, src_y; if (!get_sub_area(bb, temp, sb, &dst, &src_x, &src_y)) continue; int r = (sb->libass.color >> 24) & 0xFF; int g = (sb->libass.color >> 16) & 0xFF; int b = (sb->libass.color >> 8) & 0xFF; int a = 255 - (sb->libass.color & 0xFF); int color_yuv[3]; if (need_conv) { int rgb[3] = {r, g, b}; mp_map_fixp_color(&rgb2yuv, 8, rgb, cspar.texture_bits, color_yuv); } else { color_yuv[0] = g; color_yuv[1] = b; color_yuv[2] = r; } int bytes = (bits + 7) / 8; uint8_t *alpha_p = (uint8_t *)sb->bitmap + src_y * sb->stride + src_x; for (int p = 0; p < (temp->num_planes > 2 ? 3 : 1); p++) { blend_const_alpha(dst.planes[p], dst.stride[p], color_yuv[p], alpha_p, sb->stride, a, dst.w, dst.h, bytes); } if (temp->num_planes >= 4) { blend_src_dst_mul(dst.planes[3], dst.stride[3], alpha_p, sb->stride, a, dst.w, dst.h, bytes); } } } static void get_swscale_alignment(const struct mp_image *img, int *out_xstep, int *out_ystep) { int sx = (1 << img->fmt.chroma_xs); int sy = (1 << img->fmt.chroma_ys); for (int p = 0; p < img->num_planes; ++p) { int bits = img->fmt.bpp[p]; // the * 2 fixes problems with writing past the destination width while (((sx >> img->fmt.chroma_xs) * bits) % (SWS_MIN_BYTE_ALIGN * 8 * 2)) sx *= 2; } *out_xstep = sx; *out_ystep = sy; } static void align_bbox(int xstep, int ystep, struct mp_rect *rc) { rc->x0 = rc->x0 & ~(xstep - 1); rc->y0 = rc->y0 & ~(ystep - 1); rc->x1 = FFALIGN(rc->x1, xstep); rc->y1 = FFALIGN(rc->y1, ystep); } // Post condition, if true returned: rc is inside img static bool align_bbox_for_swscale(struct mp_image *img, struct mp_rect *rc) { struct mp_rect img_rect = {0, 0, img->w, img->h}; // Get rid of negative coordinates if (!mp_rect_intersection(rc, &img_rect)) return false; int xstep, ystep; get_swscale_alignment(img, &xstep, &ystep); align_bbox(xstep, ystep, rc); return mp_rect_intersection(rc, &img_rect); } // Try to find best/closest YUV 444 format (or similar) for imgfmt static void get_closest_y444_format(int imgfmt, int *out_format, int *out_bits) { struct mp_imgfmt_desc desc = mp_imgfmt_get_desc(imgfmt); int planes = desc.flags & MP_IMGFLAG_ALPHA ? 4 : 3; int bits = desc.component_bits > 8 ? 16 : 8; if (desc.flags & MP_IMGFLAG_RGB) { *out_format = mp_imgfmt_find(0, 0, planes, bits, MP_IMGFLAG_RGB_P); if (!mp_sws_supported_format(*out_format)) *out_format = mp_imgfmt_find(0, 0, planes, 8, MP_IMGFLAG_RGB_P); } else if (desc.flags & MP_IMGFLAG_YUV_P) { *out_format = mp_imgfmt_find(0, 0, planes, bits, MP_IMGFLAG_YUV_P); } else { *out_format = 0; } if (!mp_sws_supported_format(*out_format)) *out_format = IMGFMT_444P; // generic fallback *out_bits = mp_imgfmt_get_desc(*out_format).component_bits; } static struct part *get_cache(struct mp_draw_sub_cache *cache, struct sub_bitmaps *sbs, struct mp_image *format) { struct part *part = NULL; bool use_cache = sbs->format == SUBBITMAP_RGBA; if (use_cache) { part = cache->parts[sbs->render_index]; if (part) { if (part->change_id != sbs->change_id || part->imgfmt != format->imgfmt || part->colorspace != format->params.color.space || part->levels != format->params.color.levels) { talloc_free(part); part = NULL; } } if (!part) { part = talloc(cache, struct part); *part = (struct part) { .change_id = sbs->change_id, .num_imgs = sbs->num_parts, .imgfmt = format->imgfmt, .levels = format->params.color.levels, .colorspace = format->params.color.space, }; part->imgs = talloc_zero_array(part, struct sub_cache, part->num_imgs); } assert(part->num_imgs == sbs->num_parts); cache->parts[sbs->render_index] = part; } return part; } // Return area of intersection between target and sub-bitmap as cropped image static bool get_sub_area(struct mp_rect bb, struct mp_image *temp, struct sub_bitmap *sb, struct mp_image *out_area, int *out_src_x, int *out_src_y) { // coordinates are relative to the bbox struct mp_rect dst = {sb->x - bb.x0, sb->y - bb.y0}; dst.x1 = dst.x0 + sb->dw; dst.y1 = dst.y0 + sb->dh; if (!mp_rect_intersection(&dst, &(struct mp_rect){0, 0, temp->w, temp->h})) return false; *out_src_x = (dst.x0 - sb->x) + bb.x0; *out_src_y = (dst.y0 - sb->y) + bb.y0; *out_area = *temp; mp_image_crop_rc(out_area, dst); return true; } // Convert the src image to imgfmt (which should be a 444 format) static struct mp_image *chroma_up(struct mp_draw_sub_cache *cache, int imgfmt, struct mp_image *src) { if (src->imgfmt == imgfmt) return src; if (!cache->upsample_img || cache->upsample_img->imgfmt != imgfmt || cache->upsample_img->w < src->w || cache->upsample_img->h < src->h) { talloc_free(cache->upsample_img); cache->upsample_img = mp_image_alloc(imgfmt, src->w, src->h); talloc_steal(cache, cache->upsample_img); if (!cache->upsample_img) return NULL; } cache->upsample_temp = *cache->upsample_img; struct mp_image *temp = &cache->upsample_temp; mp_image_set_size(temp, src->w, src->h); // The temp image is always YUV, but src not necessarily. // Reduce amount of conversions in YUV case (upsampling/shifting only) if (src->fmt.flags & MP_IMGFLAG_YUV) temp->params.color = src->params.color; if (src->imgfmt == IMGFMT_420P) { assert(imgfmt == IMGFMT_444P); // Faster upsampling: keep Y plane, upsample chroma planes only // The whole point is not having swscale copy the Y plane struct mp_image t_dst = *temp; mp_image_setfmt(&t_dst, IMGFMT_Y8); mp_image_set_size(&t_dst, temp->w, temp->h); struct mp_image t_src = t_dst; mp_image_set_size(&t_src, src->w >> 1, src->h >> 1); for (int c = 0; c < 2; c++) { t_dst.planes[0] = temp->planes[1 + c]; t_dst.stride[0] = temp->stride[1 + c]; t_src.planes[0] = src->planes[1 + c]; t_src.stride[0] = src->stride[1 + c]; mp_image_swscale(&t_dst, &t_src, SWS_POINT); } temp->planes[0] = src->planes[0]; temp->stride[0] = src->stride[0]; } else { mp_image_swscale(temp, src, SWS_POINT); } return temp; } // Undo chroma_up() (copy temp to old_src if needed) static void chroma_down(struct mp_image *old_src, struct mp_image *temp) { assert(old_src->w == temp->w && old_src->h == temp->h); if (temp != old_src) { if (old_src->imgfmt == IMGFMT_420P) { // Downsampling, skipping the Y plane (see chroma_up()) assert(temp->imgfmt == IMGFMT_444P); assert(temp->planes[0] == old_src->planes[0]); struct mp_image t_dst = *temp; mp_image_setfmt(&t_dst, IMGFMT_Y8); mp_image_set_size(&t_dst, old_src->w >> 1, old_src->h >> 1); struct mp_image t_src = t_dst; mp_image_set_size(&t_src, temp->w, temp->h); for (int c = 0; c < 2; c++) { t_dst.planes[0] = old_src->planes[1 + c]; t_dst.stride[0] = old_src->stride[1 + c]; t_src.planes[0] = temp->planes[1 + c]; t_src.stride[0] = temp->stride[1 + c]; mp_image_swscale(&t_dst, &t_src, SWS_AREA); } } else { mp_image_swscale(old_src, temp, SWS_AREA); // chroma down } } } // cache: if not NULL, the function will set *cache to a talloc-allocated cache // containing scaled versions of sbs contents - free the cache with // talloc_free() void mp_draw_sub_bitmaps(struct mp_draw_sub_cache **cache, struct mp_image *dst, struct sub_bitmaps *sbs) { assert(mp_draw_sub_formats[sbs->format]); if (!mp_sws_supported_format(dst->imgfmt)) return; struct mp_draw_sub_cache *cache_ = cache ? *cache : NULL; if (!cache_) cache_ = talloc_zero(NULL, struct mp_draw_sub_cache); int format, bits; get_closest_y444_format(dst->imgfmt, &format, &bits); struct mp_rect rc_list[MP_SUB_BB_LIST_MAX]; int num_rc = mp_get_sub_bb_list(sbs, rc_list, MP_SUB_BB_LIST_MAX); for (int r = 0; r < num_rc; r++) { struct mp_rect bb = rc_list[r]; if (!align_bbox_for_swscale(dst, &bb)) return; struct mp_image dst_region = *dst; mp_image_crop_rc(&dst_region, bb); struct mp_image *temp = chroma_up(cache_, format, &dst_region); if (!temp) continue; // on OOM, skip region if (sbs->format == SUBBITMAP_RGBA) { draw_rgba(cache_, bb, temp, bits, sbs); } else if (sbs->format == SUBBITMAP_LIBASS) { draw_ass(cache_, bb, temp, bits, sbs); } chroma_down(&dst_region, temp); } if (cache) { *cache = cache_; } else { talloc_free(cache_); } } // vim: ts=4 sw=4 et tw=80
gpl-2.0
visi0nary/mediatek
mt6732/mediatek/kernel/drivers/combo/drv_wlan/mt6628/wlan/os/linux/gl_wext_priv.c
76740
/* ** $Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/os/linux/gl_wext_priv.c#4 $ */ /*! \file gl_wext_priv.c \brief This file includes private ioctl support. */ /* ** $Log: gl_wext_priv.c $ * * 07 17 2012 yuche.tsai * NULL * Let netdev bring up. * * 06 13 2012 yuche.tsai * NULL * Update maintrunk driver. * Add support for driver compose assoc request frame. * * 03 20 2012 wh.su * [WCXRP00001153] [MT6620 Wi-Fi][Driver] Adding the get_ch_list and set_tx_power proto type function[WCXRP00001202] [MT6628 Wi-Fi][FW] Adding the New PN init code * use return to avoid the ioctl return not supported * * 03 02 2012 terry.wu * NULL * Snc CFG80211 modification for ICS migration from branch 2.2. * * 01 16 2012 wh.su * [WCXRP00001170] [MT6620 Wi-Fi][Driver] Adding the related code for set/get band ioctl * Adding the template code for set / get band IOCTL (with ICS supplicant_6).. * * 01 05 2012 wh.su * [WCXRP00001153] [MT6620 Wi-Fi][Driver] Adding the get_ch_list and set_tx_power proto type function * Adding the related ioctl / wlan oid function to set the Tx power cfg. * * 01 02 2012 wh.su * [WCXRP00001153] [MT6620 Wi-Fi][Driver] Adding the get_ch_list and set_tx_power proto type function * Adding the proto type function for set_int set_tx_power and get int get_ch_list. * * 11 10 2011 cp.wu * [WCXRP00001098] [MT6620 Wi-Fi][Driver] Replace printk by DBG LOG macros in linux porting layer * 1. eliminaite direct calls to printk in porting layer. * 2. replaced by DBGLOG, which would be XLOG on ALPS platforms. * * 11 02 2011 chinghwa.yu * [WCXRP00000063] Update BCM CoEx design and settings * Fixed typo. * * 09 20 2011 chinglan.wang * [WCXRP00000989] [WiFi Direct] [Driver] Add a new io control API to start the formation for the sigma test. * . * * 07 28 2011 chinghwa.yu * [WCXRP00000063] Update BCM CoEx design and settings * Add BWCS cmd and event. * * 07 18 2011 chinghwa.yu * [WCXRP00000063] Update BCM CoEx design and settings[WCXRP00000612] [MT6620 Wi-Fi] [FW] CSD update SWRDD algorithm * Add CMD/Event for RDD and BWCS. * * 03 17 2011 chinglan.wang * [WCXRP00000570] [MT6620 Wi-Fi][Driver] Add Wi-Fi Protected Setup v2.0 feature * . * * 03 07 2011 terry.wu * [WCXRP00000521] [MT6620 Wi-Fi][Driver] Remove non-standard debug message * Toggle non-standard debug messages to comments. * * 01 27 2011 cm.chang * [WCXRP00000402] [MT6620 Wi-Fi][Driver] Enable MCR read/write by iwpriv by default * . * * 01 26 2011 wh.su * [WCXRP00000396] [MT6620 Wi-Fi][Driver] Support Sw Ctrl ioctl at linux * adding the SW cmd ioctl support, use set/get structure ioctl. * * 01 20 2011 eddie.chen * [WCXRP00000374] [MT6620 Wi-Fi][DRV] SW debug control * Adjust OID order. * * 01 20 2011 eddie.chen * [WCXRP00000374] [MT6620 Wi-Fi][DRV] SW debug control * Add Oid for sw control debug command * * 01 07 2011 cm.chang * [WCXRP00000336] [MT6620 Wi-Fi][Driver] Add test mode commands in normal phone operation * Add a new compiling option to control if MCR read/write is permitted * * 12 31 2010 cm.chang * [WCXRP00000336] [MT6620 Wi-Fi][Driver] Add test mode commands in normal phone operation * Add some iwpriv commands to support test mode operation * * 12 15 2010 george.huang * [WCXRP00000152] [MT6620 Wi-Fi] AP mode power saving function * Support set PS profile and set WMM-PS related iwpriv. * * 11 08 2010 wh.su * [WCXRP00000171] [MT6620 Wi-Fi][Driver] Add message check code same behavior as mt5921 * add the message check code from mt5921. * * 10 18 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000086] [MT6620 Wi-Fi][Driver] The mac address is all zero at android * complete implementation of Android NVRAM access * * 09 24 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check * correct typo for NVRAM access. * * 09 23 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check * add skeleton for NVRAM integration * * 08 04 2010 cp.wu * NULL * revert changelist #15371, efuse read/write access will be done by RF test approach * * 08 04 2010 cp.wu * NULL * add OID definitions for EFUSE read/write access. * * 07 08 2010 cp.wu * * [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository. * * 06 06 2010 kevin.huang * [WPD00003832][MT6620 5931] Create driver base * [MT6620 5931] Create driver base * * 06 01 2010 cp.wu * [WPD00001943]Create WiFi test driver framework on WinXP * enable OID_CUSTOM_MTK_WIFI_TEST for RFTest & META tool * * 05 29 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix private ioctl for rftest * * 04 21 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * add for private ioctl support ** \main\maintrunk.MT5921\32 2009-10-08 10:33:25 GMT mtk01090 ** Avoid accessing private data of net_device directly. Replace with netdev_priv(). Add more checking for input parameters and pointers. ** \main\maintrunk.MT5921\31 2009-09-29 16:46:21 GMT mtk01090 ** Remove unused functions ** \main\maintrunk.MT5921\30 2009-09-29 14:46:47 GMT mtk01090 ** Fix compile warning ** \main\maintrunk.MT5921\29 2009-09-29 14:28:48 GMT mtk01090 ** Fix compile warning ** \main\maintrunk.MT5921\28 2009-09-28 22:21:38 GMT mtk01090 ** Refine lines to supress compile warning ** \main\maintrunk.MT5921\27 2009-09-28 20:19:14 GMT mtk01090 ** Add private ioctl to carry OID structures. Restructure public/private ioctl interfaces to Linux kernel. ** \main\maintrunk.MT5921\26 2009-08-18 22:56:53 GMT mtk01090 ** Add Linux SDIO (with mmc core) support. ** Add Linux 2.6.21, 2.6.25, 2.6.26. ** Fix compile warning in Linux. ** \main\maintrunk.MT5921\25 2009-05-07 22:26:15 GMT mtk01089 ** Add mandatory and private IO control for Linux BWCS ** \main\maintrunk.MT5921\24 2009-04-29 10:07:05 GMT mtk01088 ** fixed the compiling error at linux ** \main\maintrunk.MT5921\23 2009-04-24 09:09:45 GMT mtk01088 ** mark the code not used at linux supplicant v0.6.7 ** \main\maintrunk.MT5921\22 2008-11-24 21:03:51 GMT mtk01425 ** 1. Add PTA_ENABLED flag ** \main\maintrunk.MT5921\21 2008-08-29 14:55:59 GMT mtk01088 ** adjust the code for meet the coding style, and add assert check ** \main\maintrunk.MT5921\20 2008-07-16 15:23:20 GMT mtk01104 ** Support GPIO2 mode ** \main\maintrunk.MT5921\19 2008-07-15 17:43:11 GMT mtk01084 ** modify variable name ** \main\maintrunk.MT5921\18 2008-07-14 14:37:58 GMT mtk01104 ** Add exception handle about length in function priv_set_struct() ** \main\maintrunk.MT5921\17 2008-07-14 13:55:32 GMT mtk01104 ** Support PRIV_CMD_BT_COEXIST ** \main\maintrunk.MT5921\16 2008-07-09 00:20:15 GMT mtk01461 ** Add priv oid to support WMM_PS_TEST ** \main\maintrunk.MT5921\15 2008-06-02 11:15:22 GMT mtk01461 ** Update after wlanoidSetPowerMode changed ** \main\maintrunk.MT5921\14 2008-05-30 19:31:07 GMT mtk01461 ** Add IOCTL for Power Mode ** \main\maintrunk.MT5921\13 2008-05-30 18:57:15 GMT mtk01461 ** Not use wlanoidSetCSUMOffloadForLinux() ** \main\maintrunk.MT5921\12 2008-05-30 15:13:18 GMT mtk01084 ** rename wlanoid ** \main\maintrunk.MT5921\11 2008-05-29 14:16:31 GMT mtk01084 ** rename for wlanoidSetBeaconIntervalForLinux ** \main\maintrunk.MT5921\10 2008-04-17 23:06:37 GMT mtk01461 ** Add iwpriv support for AdHocMode setting ** \main\maintrunk.MT5921\9 2008-03-31 21:00:55 GMT mtk01461 ** Add priv IOCTL for VOIP setting ** \main\maintrunk.MT5921\8 2008-03-31 13:49:43 GMT mtk01461 ** Add priv ioctl to turn on / off roaming ** \main\maintrunk.MT5921\7 2008-03-26 15:35:14 GMT mtk01461 ** Add CSUM offload priv ioctl for Linux ** \main\maintrunk.MT5921\6 2008-03-11 14:50:59 GMT mtk01461 ** Unify priv ioctl ** \main\maintrunk.MT5921\5 2007-11-06 19:32:30 GMT mtk01088 ** add WPS code ** \main\maintrunk.MT5921\4 2007-10-30 12:01:39 GMT MTK01425 ** 1. Update wlanQueryInformation and wlanSetInformation */ /******************************************************************************* * C O M P I L E R F L A G S ******************************************************************************** */ /******************************************************************************* * E X T E R N A L R E F E R E N C E S ******************************************************************************** */ #include "gl_os.h" #include "gl_wext_priv.h" #if CFG_SUPPORT_WAPI #include "gl_sec.h" #endif #if CFG_ENABLE_WIFI_DIRECT #include "gl_p2p_os.h" #endif /******************************************************************************* * C O N S T A N T S ******************************************************************************** */ #define NUM_SUPPORTED_OIDS (sizeof(arWlanOidReqTable) / sizeof(WLAN_REQ_ENTRY)) /******************************************************************************* * F U N C T I O N D E C L A R A T I O N S ******************************************************************************** */ static int priv_get_ndis ( IN struct net_device *prNetDev, IN NDIS_TRANSPORT_STRUCT* prNdisReq, OUT PUINT_32 pu4OutputLen ); static int priv_set_ndis ( IN struct net_device *prNetDev, IN NDIS_TRANSPORT_STRUCT* prNdisReq, OUT PUINT_32 pu4OutputLen ); #if 0 /* CFG_SUPPORT_WPS */ static int priv_set_appie ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, OUT char *pcExtra ); static int priv_set_filter ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, OUT char *pcExtra ); #endif /* CFG_SUPPORT_WPS */ static BOOLEAN reqSearchSupportedOidEntry ( IN UINT_32 rOid, OUT P_WLAN_REQ_ENTRY *ppWlanReqEntry ); #if 0 static WLAN_STATUS reqExtQueryConfiguration ( IN P_GLUE_INFO_T prGlueInfo, OUT PVOID pvQueryBuffer, IN UINT_32 u4QueryBufferLen, OUT PUINT_32 pu4QueryInfoLen ); static WLAN_STATUS reqExtSetConfiguration ( IN P_GLUE_INFO_T prGlueInfo, IN PVOID pvSetBuffer, IN UINT_32 u4SetBufferLen, OUT PUINT_32 pu4SetInfoLen ); #endif static WLAN_STATUS reqExtSetAcpiDevicePowerState ( IN P_GLUE_INFO_T prGlueInfo, IN PVOID pvSetBuffer, IN UINT_32 u4SetBufferLen, OUT PUINT_32 pu4SetInfoLen ); /******************************************************************************* * P R I V A T E D A T A ******************************************************************************** */ static UINT_8 aucOidBuf[4096] = {0}; /* OID processing table */ /* Order is important here because the OIDs should be in order of increasing value for binary searching. */ static WLAN_REQ_ENTRY arWlanOidReqTable[] = { /* {(NDIS_OID)rOid, (PUINT_8)pucOidName, fgQryBufLenChecking, fgSetBufLenChecking, fgIsHandleInGlueLayerOnly, u4InfoBufLen, pfOidQueryHandler, pfOidSetHandler} */ /* General Operational Characteristics */ /* Ethernet Operational Characteristics */ {OID_802_3_CURRENT_ADDRESS, DISP_STRING("OID_802_3_CURRENT_ADDRESS"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, 6, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryCurrentAddr, NULL}, /* OID_802_3_MULTICAST_LIST */ /* OID_802_3_MAXIMUM_LIST_SIZE */ /* Ethernet Statistics */ /* NDIS 802.11 Wireless LAN OIDs */ {OID_802_11_SUPPORTED_RATES, DISP_STRING("OID_802_11_SUPPORTED_RATES"), TRUE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_RATES_EX), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQuerySupportedRates, NULL}, /* {OID_802_11_CONFIGURATION, DISP_STRING("OID_802_11_CONFIGURATION"), TRUE, TRUE, ENUM_OID_GLUE_EXTENSION, sizeof(PARAM_802_11_CONFIG_T), (PFN_OID_HANDLER_FUNC_REQ)reqExtQueryConfiguration, (PFN_OID_HANDLER_FUNC_REQ)reqExtSetConfiguration}, */ {OID_PNP_SET_POWER, DISP_STRING("OID_PNP_SET_POWER"), TRUE, FALSE, ENUM_OID_GLUE_EXTENSION, sizeof(PARAM_DEVICE_POWER_STATE), NULL, (PFN_OID_HANDLER_FUNC_REQ)reqExtSetAcpiDevicePowerState}, /* Custom OIDs */ {OID_CUSTOM_OID_INTERFACE_VERSION, DISP_STRING("OID_CUSTOM_OID_INTERFACE_VERSION"), TRUE, FALSE, ENUM_OID_DRIVER_CORE, 4, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryOidInterfaceVersion, NULL}, /* #if PTA_ENABLED {OID_CUSTOM_BT_COEXIST_CTRL, DISP_STRING("OID_CUSTOM_BT_COEXIST_CTRL"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_BT_COEXIST_T), NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBtCoexistCtrl}, #endif */ /* {OID_CUSTOM_POWER_MANAGEMENT_PROFILE, DISP_STRING("OID_CUSTOM_POWER_MANAGEMENT_PROFILE"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryPwrMgmtProfParam, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetPwrMgmtProfParam}, {OID_CUSTOM_PATTERN_CONFIG, DISP_STRING("OID_CUSTOM_PATTERN_CONFIG"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_PATTERN_SEARCH_CONFIG_STRUC_T), NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetPatternConfig}, {OID_CUSTOM_BG_SSID_SEARCH_CONFIG, DISP_STRING("OID_CUSTOM_BG_SSID_SEARCH_CONFIG"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBgSsidParam}, {OID_CUSTOM_VOIP_SETUP, DISP_STRING("OID_CUSTOM_VOIP_SETUP"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryVoipConnectionStatus, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetVoipConnectionStatus}, {OID_CUSTOM_ADD_TS, DISP_STRING("OID_CUSTOM_ADD_TS"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidAddTS}, {OID_CUSTOM_DEL_TS, DISP_STRING("OID_CUSTOM_DEL_TS"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidDelTS}, */ /* #if CFG_LP_PATTERN_SEARCH_SLT {OID_CUSTOM_SLT, DISP_STRING("OID_CUSTOM_SLT"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQuerySltResult, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetSltMode}, #endif {OID_CUSTOM_ROAMING_EN, DISP_STRING("OID_CUSTOM_ROAMING_EN"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryRoamingFunction, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetRoamingFunction}, {OID_CUSTOM_WMM_PS_TEST, DISP_STRING("OID_CUSTOM_WMM_PS_TEST"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWiFiWmmPsTest}, {OID_CUSTOM_COUNTRY_STRING, DISP_STRING("OID_CUSTOM_COUNTRY_STRING"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryCurrentCountry, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetCurrentCountry}, #if CFG_SUPPORT_802_11D {OID_CUSTOM_MULTI_DOMAIN_CAPABILITY, DISP_STRING("OID_CUSTOM_MULTI_DOMAIN_CAPABILITY"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryMultiDomainCap, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetMultiDomainCap}, #endif {OID_CUSTOM_GPIO2_MODE, DISP_STRING("OID_CUSTOM_GPIO2_MODE"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(ENUM_PARAM_GPIO2_MODE_T), NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetGPIO2Mode}, {OID_CUSTOM_CONTINUOUS_POLL, DISP_STRING("OID_CUSTOM_CONTINUOUS_POLL"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CONTINUOUS_POLL_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryContinuousPollInterval, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetContinuousPollProfile}, {OID_CUSTOM_DISABLE_BEACON_DETECTION, DISP_STRING("OID_CUSTOM_DISABLE_BEACON_DETECTION"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, 4, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryDisableBeaconDetectionFunc, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetDisableBeaconDetectionFunc}, */ /* WPS */ /* {OID_CUSTOM_DISABLE_PRIVACY_CHECK, DISP_STRING("OID_CUSTOM_DISABLE_PRIVACY_CHECK"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, 4, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetDisablePriavcyCheck}, */ {OID_CUSTOM_MCR_RW, DISP_STRING("OID_CUSTOM_MCR_RW"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_MCR_RW_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryMcrRead, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetMcrWrite}, {OID_CUSTOM_EEPROM_RW, DISP_STRING("OID_CUSTOM_EEPROM_RW"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_EEPROM_RW_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryEepromRead, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetEepromWrite}, {OID_CUSTOM_SW_CTRL, DISP_STRING("OID_CUSTOM_SW_CTRL"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_SW_CTRL_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQuerySwCtrlRead, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetSwCtrlWrite}, {OID_CUSTOM_MEM_DUMP, DISP_STRING("OID_CUSTOM_MEM_DUMP"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_MEM_DUMP_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryMemDump, NULL}, {OID_CUSTOM_TEST_MODE, DISP_STRING("OID_CUSTOM_TEST_MODE"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestSetTestMode}, /* {OID_CUSTOM_TEST_RX_STATUS, DISP_STRING("OID_CUSTOM_TEST_RX_STATUS"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_RFTEST_RX_STATUS_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryRfTestRxStatus, NULL}, {OID_CUSTOM_TEST_TX_STATUS, DISP_STRING("OID_CUSTOM_TEST_TX_STATUS"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_RFTEST_TX_STATUS_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryRfTestTxStatus, NULL}, */ {OID_CUSTOM_ABORT_TEST_MODE, DISP_STRING("OID_CUSTOM_ABORT_TEST_MODE"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestSetAbortTestMode}, {OID_CUSTOM_MTK_WIFI_TEST, DISP_STRING("OID_CUSTOM_MTK_WIFI_TEST"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_MTK_WIFI_TEST_STRUC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestQueryAutoTest, (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestSetAutoTest}, /* OID_CUSTOM_EMULATION_VERSION_CONTROL */ /* BWCS */ #if CFG_SUPPORT_BCM && CFG_SUPPORT_BCM_BWCS {OID_CUSTOM_BWCS_CMD, DISP_STRING("OID_CUSTOM_BWCS_CMD"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(PTA_IPC_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryBT, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBT}, #endif /* {OID_CUSTOM_SINGLE_ANTENNA, DISP_STRING("OID_CUSTOM_SINGLE_ANTENNA"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 4, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryBtSingleAntenna, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBtSingleAntenna}, {OID_CUSTOM_SET_PTA, DISP_STRING("OID_CUSTOM_SET_PTA"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 4, (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryPta, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetPta}, */ { OID_CUSTOM_MTK_NVRAM_RW, DISP_STRING("OID_CUSTOM_MTK_NVRAM_RW"), TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_NVRAM_RW_STRUCT_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryNvramRead, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetNvramWrite }, { OID_CUSTOM_CFG_SRC_TYPE, DISP_STRING("OID_CUSTOM_CFG_SRC_TYPE"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(ENUM_CFG_SRC_TYPE_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryCfgSrcType, NULL }, { OID_CUSTOM_EEPROM_TYPE, DISP_STRING("OID_CUSTOM_EEPROM_TYPE"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(ENUM_EEPROM_TYPE_T), (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryEepromType, NULL }, #if CFG_SUPPORT_WAPI {OID_802_11_WAPI_MODE, DISP_STRING("OID_802_11_WAPI_MODE"), FALSE, TRUE, ENUM_OID_DRIVER_CORE, 4, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWapiMode}, {OID_802_11_WAPI_ASSOC_INFO, DISP_STRING("OID_802_11_WAPI_ASSOC_INFO"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWapiAssocInfo}, {OID_802_11_SET_WAPI_KEY, DISP_STRING("OID_802_11_SET_WAPI_KEY"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_WPI_KEY_T), NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWapiKey}, #endif #if CFG_SUPPORT_WPS2 {OID_802_11_WSC_ASSOC_INFO, DISP_STRING("OID_802_11_WSC_ASSOC_INFO"), FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0, NULL, (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWSCAssocInfo}, #endif }; /******************************************************************************* * F U N C T I O N S ******************************************************************************** */ /*----------------------------------------------------------------------------*/ /*! * \brief Dispatching function for private ioctl region (SIOCIWFIRSTPRIV ~ * SIOCIWLASTPRIV). * * \param[in] prNetDev Net device requested. * \param[in] prIfReq Pointer to ifreq structure. * \param[in] i4Cmd Command ID between SIOCIWFIRSTPRIV and SIOCIWLASTPRIV. * * \retval 0 for success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EFAULT For fail. * */ /*----------------------------------------------------------------------------*/ int priv_support_ioctl ( IN struct net_device *prNetDev, IN OUT struct ifreq *prIfReq, IN int i4Cmd ) { /* prIfReq is verified in the caller function wlanDoIOCTL() */ struct iwreq *prIwReq = (struct iwreq *)prIfReq; struct iw_request_info rIwReqInfo; /* prDev is verified in the caller function wlanDoIOCTL() */ /* Prepare the call */ rIwReqInfo.cmd = (__u16)i4Cmd; rIwReqInfo.flags = 0; switch (i4Cmd) { case IOCTL_SET_INT: /* NOTE(Kevin): 1/3 INT Type <= IFNAMSIZ, so we don't need copy_from/to_user() */ return priv_set_int(prNetDev, &rIwReqInfo, &(prIwReq->u), (char *) &(prIwReq->u)); case IOCTL_GET_INT: /* NOTE(Kevin): 1/3 INT Type <= IFNAMSIZ, so we don't need copy_from/to_user() */ return priv_get_int(prNetDev, &rIwReqInfo, &(prIwReq->u), (char *) &(prIwReq->u)); case IOCTL_SET_STRUCT: case IOCTL_SET_STRUCT_FOR_EM: return priv_set_struct(prNetDev, &rIwReqInfo, &prIwReq->u, (char *) &(prIwReq->u)); case IOCTL_GET_STRUCT: return priv_get_struct(prNetDev, &rIwReqInfo, &prIwReq->u, (char *) &(prIwReq->u)); default: return -EOPNOTSUPP; } /* end of switch */ }/* priv_support_ioctl */ /*----------------------------------------------------------------------------*/ /*! * \brief Private ioctl set int handler. * * \param[in] prNetDev Net device requested. * \param[in] prIwReqInfo Pointer to iwreq structure. * \param[in] prIwReqData The ioctl data structure, use the field of sub-command. * \param[in] pcExtra The buffer with input value * * \retval 0 For success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EINVAL If a value is out of range. * */ /*----------------------------------------------------------------------------*/ int priv_set_int ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, IN char *pcExtra ) { UINT_32 u4SubCmd; PUINT_32 pu4IntBuf; P_NDIS_TRANSPORT_STRUCT prNdisReq; P_GLUE_INFO_T prGlueInfo; UINT_32 u4BufLen = 0; int status = 0; P_PTA_IPC_T prPtaIpc; ASSERT(prNetDev); ASSERT(prIwReqInfo); ASSERT(prIwReqData); ASSERT(pcExtra); if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) { return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); u4SubCmd = (UINT_32) prIwReqData->mode; pu4IntBuf = (PUINT_32) pcExtra; switch (u4SubCmd) { case PRIV_CMD_TEST_MODE: //printk("TestMode=%ld\n", pu4IntBuf[1]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; if (pu4IntBuf[1] == PRIV_CMD_TEST_MAGIC_KEY) { prNdisReq->ndisOidCmd = OID_CUSTOM_TEST_MODE; } else if (pu4IntBuf[1] == 0) { prNdisReq->ndisOidCmd = OID_CUSTOM_ABORT_TEST_MODE; } else { status = 0; break; } prNdisReq->inNdisOidlength = 0; prNdisReq->outNdisOidLength = 0; /* Execute this OID */ status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen); break; case PRIV_CMD_TEST_CMD: //printk("CMD=0x%08lx, data=0x%08lx\n", pu4IntBuf[1], pu4IntBuf[2]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_MTK_WIFI_TEST; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; /* Execute this OID */ status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen); break; #if CFG_SUPPORT_PRIV_MCR_RW case PRIV_CMD_ACCESS_MCR: //printk("addr=0x%08lx, data=0x%08lx\n", pu4IntBuf[1], pu4IntBuf[2]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; if (!prGlueInfo->fgMcrAccessAllowed) { if (pu4IntBuf[1] == PRIV_CMD_TEST_MAGIC_KEY && pu4IntBuf[2] == PRIV_CMD_TEST_MAGIC_KEY) { prGlueInfo->fgMcrAccessAllowed = TRUE; } status = 0; break; } kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_MCR_RW; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; /* Execute this OID */ status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen); break; #endif case PRIV_CMD_SW_CTRL: //printk("addr=0x%08lx, data=0x%08lx\n", pu4IntBuf[1], pu4IntBuf[2]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; /* Execute this OID */ status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen); break; #if 0 case PRIV_CMD_BEACON_PERIOD: rStatus = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetBeaconInterval, (PVOID)&pu4IntBuf[1], /* pu4IntBuf[0] is used as input SubCmd */ sizeof(UINT_32), &u4BufLen); break; #endif #if CFG_TCP_IP_CHKSUM_OFFLOAD case PRIV_CMD_CSUM_OFFLOAD: { UINT_32 u4CSUMFlags; if (pu4IntBuf[1] == 1) { u4CSUMFlags = CSUM_OFFLOAD_EN_ALL; } else if (pu4IntBuf[1] == 0) { u4CSUMFlags = 0; } else { return -EINVAL; } if (kalIoctl(prGlueInfo, wlanoidSetCSUMOffload, (PVOID)&u4CSUMFlags, sizeof(UINT_32), FALSE, FALSE, TRUE, FALSE, &u4BufLen ) == WLAN_STATUS_SUCCESS) { if (pu4IntBuf[1] == 1) { prNetDev->features |= NETIF_F_HW_CSUM; } else if (pu4IntBuf[1] == 0) { prNetDev->features &= ~NETIF_F_HW_CSUM; } } } break; #endif /* CFG_TCP_IP_CHKSUM_OFFLOAD */ case PRIV_CMD_POWER_MODE: kalIoctl(prGlueInfo, wlanoidSet802dot11PowerSaveProfile, (PVOID)&pu4IntBuf[1], /* pu4IntBuf[0] is used as input SubCmd */ sizeof(UINT_32), FALSE, FALSE, TRUE, FALSE, &u4BufLen); break; case PRIV_CMD_WMM_PS: { PARAM_CUSTOM_WMM_PS_TEST_STRUC_T rWmmPsTest; rWmmPsTest.bmfgApsdEnAc = (UINT_8)pu4IntBuf[1]; rWmmPsTest.ucIsEnterPsAtOnce = (UINT_8)pu4IntBuf[2]; rWmmPsTest.ucIsDisableUcTrigger = (UINT_8)pu4IntBuf[3]; rWmmPsTest.reserved = 0; kalIoctl(prGlueInfo, wlanoidSetWiFiWmmPsTest, (PVOID)&rWmmPsTest, sizeof(PARAM_CUSTOM_WMM_PS_TEST_STRUC_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen); } break; #if 0 case PRIV_CMD_ADHOC_MODE: rStatus = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetAdHocMode, (PVOID)&pu4IntBuf[1], /* pu4IntBuf[0] is used as input SubCmd */ sizeof(UINT_32), &u4BufLen); break; #endif case PRIV_CUSTOM_BWCS_CMD: DBGLOG(REQ, INFO, ("pu4IntBuf[1] = %lx, size of PTA_IPC_T = %d.\n", pu4IntBuf[1], sizeof(PARAM_PTA_IPC_T))); prPtaIpc = (P_PTA_IPC_T) aucOidBuf; prPtaIpc->u.aucBTPParams[0] = (UINT_8) (pu4IntBuf[1] >> 24); prPtaIpc->u.aucBTPParams[1] = (UINT_8) (pu4IntBuf[1] >> 16); prPtaIpc->u.aucBTPParams[2] = (UINT_8) (pu4IntBuf[1] >> 8); prPtaIpc->u.aucBTPParams[3] = (UINT_8) (pu4IntBuf[1]); DBGLOG(REQ, INFO, ("BCM BWCS CMD : PRIV_CUSTOM_BWCS_CMD : aucBTPParams[0] = %02x, aucBTPParams[1] = %02x, aucBTPParams[2] = %02x, aucBTPParams[3] = %02x.\n", prPtaIpc->u.aucBTPParams[0], prPtaIpc->u.aucBTPParams[1], prPtaIpc->u.aucBTPParams[2], prPtaIpc->u.aucBTPParams[3])); #if 0 status = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetBT, (PVOID)&aucOidBuf[0], u4CmdLen, &u4BufLen); #endif status = wlanoidSetBT(prGlueInfo->prAdapter, (PVOID)&aucOidBuf[0], sizeof(PARAM_PTA_IPC_T), &u4BufLen); if (WLAN_STATUS_SUCCESS != status) { status = -EFAULT; } break; case PRIV_CMD_BAND_CONFIG: { DBGLOG(INIT, INFO, ("CMD set_band=%lu\n", pu4IntBuf[1])); } break; #if CFG_ENABLE_WIFI_DIRECT case PRIV_CMD_P2P_MODE: { PARAM_CUSTOM_P2P_SET_STRUC_T rSetP2P; WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS; rSetP2P.u4Enable = pu4IntBuf[1]; rSetP2P.u4Mode = pu4IntBuf[2]; if(!rSetP2P.u4Enable) { p2pNetUnregister(prGlueInfo, TRUE); } rWlanStatus = kalIoctl(prGlueInfo, wlanoidSetP2pMode, (PVOID)&rSetP2P, /* pu4IntBuf[0] is used as input SubCmd */ sizeof(PARAM_CUSTOM_P2P_SET_STRUC_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen); if(rSetP2P.u4Enable) { p2pNetRegister(prGlueInfo, TRUE); } } break; #endif default: return -EOPNOTSUPP; } return status; } /*----------------------------------------------------------------------------*/ /*! * \brief Private ioctl get int handler. * * \param[in] pDev Net device requested. * \param[out] pIwReq Pointer to iwreq structure. * \param[in] prIwReqData The ioctl req structure, use the field of sub-command. * \param[out] pcExtra The buffer with put the return value * * \retval 0 For success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EFAULT For fail. * */ /*----------------------------------------------------------------------------*/ int priv_get_int ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, IN OUT char *pcExtra ) { UINT_32 u4SubCmd; PUINT_32 pu4IntBuf; P_GLUE_INFO_T prGlueInfo; UINT_32 u4BufLen = 0; int status = 0; P_NDIS_TRANSPORT_STRUCT prNdisReq; INT_32 ch[50]; ASSERT(prNetDev); ASSERT(prIwReqInfo); ASSERT(prIwReqData); ASSERT(pcExtra); if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) { return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); u4SubCmd = (UINT_32) prIwReqData->mode; pu4IntBuf = (PUINT_32) pcExtra; switch (u4SubCmd) { case PRIV_CMD_TEST_CMD: //printk("CMD=0x%08lx, data=0x%08lx\n", pu4IntBuf[1], pu4IntBuf[2]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_MTK_WIFI_TEST; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen); if (status == 0) { //printk("Result=%ld\n", *(PUINT_32)&prNdisReq->ndisOidContent[4]); prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[4]; /* if (copy_to_user(prIwReqData->data.pointer, &prNdisReq->ndisOidContent[4], 4)) { printk(KERN_NOTICE "priv_get_int() copy_to_user oidBuf fail(3)\n"); return -EFAULT; } */ } return status; #if CFG_SUPPORT_PRIV_MCR_RW case PRIV_CMD_ACCESS_MCR: //printk("addr=0x%08lx\n", pu4IntBuf[1]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; if (!prGlueInfo->fgMcrAccessAllowed) { status = 0; return status; } kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_MCR_RW; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen); if (status == 0) { //printk("Result=%ld\n", *(PUINT_32)&prNdisReq->ndisOidContent[4]); prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[4]; } return status; #endif case PRIV_CMD_DUMP_MEM: prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; #if 1 if (!prGlueInfo->fgMcrAccessAllowed) { status = 0; return status; } #endif kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_MEM_DUMP; prNdisReq->inNdisOidlength = sizeof(PARAM_CUSTOM_MEM_DUMP_STRUC_T); prNdisReq->outNdisOidLength = sizeof(PARAM_CUSTOM_MEM_DUMP_STRUC_T); status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen); if (status == 0) { prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[0]; } return status; case PRIV_CMD_SW_CTRL: //printk(" addr=0x%08lx\n", pu4IntBuf[1]); prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8); prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen); if (status == 0) { //printk("Result=%ld\n", *(PUINT_32)&prNdisReq->ndisOidContent[4]); prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[4]; } return status; #if 0 case PRIV_CMD_BEACON_PERIOD: status = wlanQueryInformation(prGlueInfo->prAdapter, wlanoidQueryBeaconInterval, (PVOID)pu4IntBuf, sizeof(UINT_32), &u4BufLen); return status; case PRIV_CMD_POWER_MODE: status = wlanQueryInformation(prGlueInfo->prAdapter, wlanoidQuery802dot11PowerSaveProfile, (PVOID)pu4IntBuf, sizeof(UINT_32), &u4BufLen); return status; case PRIV_CMD_ADHOC_MODE: status = wlanQueryInformation(prGlueInfo->prAdapter, wlanoidQueryAdHocMode, (PVOID)pu4IntBuf, sizeof(UINT_32), &u4BufLen); return status; #endif case PRIV_CMD_BAND_CONFIG: DBGLOG(INIT, INFO, ("CMD get_band=\n")); prIwReqData->mode = 0; return status; default: break; } u4SubCmd = (UINT_32) prIwReqData->data.flags; switch (u4SubCmd) { case PRIV_CMD_GET_CH_LIST: { UINT_16 i, j = 0; UINT_8 NumOfChannel = 50; UINT_8 ucMaxChannelNum = 50; RF_CHANNEL_INFO_T aucChannelList[50]; kalGetChannelList(prGlueInfo, BAND_NULL, ucMaxChannelNum, &NumOfChannel, aucChannelList); if (NumOfChannel > 50) NumOfChannel = 50; if (kalIsAPmode(prGlueInfo)) { for (i = 0; i < NumOfChannel; i++) { if ((aucChannelList[i].ucChannelNum <= 13) || (aucChannelList[i].ucChannelNum == 36 || aucChannelList[i].ucChannelNum == 40 || aucChannelList[i].ucChannelNum == 44 || aucChannelList[i].ucChannelNum == 48)) { ch[j] = (INT_32)aucChannelList[i].ucChannelNum; j++; } } } else { for (j = 0; j < NumOfChannel; j++) { ch[j] = (INT_32)aucChannelList[j].ucChannelNum; } } prIwReqData->data.length = j; if (copy_to_user(prIwReqData->data.pointer, ch, NumOfChannel*sizeof(INT_32))) { return -EFAULT; } else return status; } case PRIV_CMD_GET_BUILD_DATE_CODE: { UINT_8 aucBuffer[16]; if(kalIoctl(prGlueInfo, wlanoidQueryBuildDateCode, (PVOID)aucBuffer, sizeof(UINT_8) * 16, TRUE, TRUE, TRUE, FALSE, &u4BufLen) == WLAN_STATUS_SUCCESS) { prIwReqData->data.length = sizeof(UINT_8) * 16; if (copy_to_user(prIwReqData->data.pointer, aucBuffer, prIwReqData->data.length)) { return -EFAULT; } else return status; } else { return -EFAULT; } } default: return -EOPNOTSUPP; } return status; } /* priv_get_int */ /*----------------------------------------------------------------------------*/ /*! * \brief Private ioctl set int array handler. * * \param[in] prNetDev Net device requested. * \param[in] prIwReqInfo Pointer to iwreq structure. * \param[in] prIwReqData The ioctl data structure, use the field of sub-command. * \param[in] pcExtra The buffer with input value * * \retval 0 For success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EINVAL If a value is out of range. * */ /*----------------------------------------------------------------------------*/ int priv_set_ints ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, IN char *pcExtra ) { UINT_32 u4SubCmd, u4BufLen; P_GLUE_INFO_T prGlueInfo; int status = 0; WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS; P_SET_TXPWR_CTRL_T prTxpwr; ASSERT(prNetDev); ASSERT(prIwReqInfo); ASSERT(prIwReqData); ASSERT(pcExtra); if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) { return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); u4SubCmd = (UINT_32) prIwReqData->data.flags; switch (u4SubCmd) { case PRIV_CMD_SET_TX_POWER: { INT_32 *setting = prIwReqData->data.pointer; UINT_16 i; #if 0 printk("Tx power num = %d\n", prIwReqData->data.length); printk("Tx power setting = %d %d %d %d\n", setting[0], setting[1], setting[2], setting[3]); #endif prTxpwr = &prGlueInfo->rTxPwr; if (setting[0] == 0 && prIwReqData->data.length == 4 /* argc num */) { /* 0 (All networks), 1 (legacy STA), 2 (Hotspot AP), 3 (P2P), 4 (BT over Wi-Fi) */ if (setting[1] == 1 || setting[1] == 0) { if (setting[2] == 0 || setting[2] == 1) prTxpwr->c2GLegacyStaPwrOffset = setting[3]; if (setting[2] == 0 || setting[2] == 2) prTxpwr->c5GLegacyStaPwrOffset = setting[3]; } if (setting[1] == 2 || setting[1] == 0) { if (setting[2] == 0 || setting[2] == 1) prTxpwr->c2GHotspotPwrOffset = setting[3]; if (setting[2] == 0 || setting[2] == 2) prTxpwr->c5GHotspotPwrOffset = setting[3]; } if (setting[1] == 3 || setting[1] == 0) { if (setting[2] == 0 || setting[2] == 1) prTxpwr->c2GP2pPwrOffset = setting[3]; if (setting[2] == 0 || setting[2] == 2) prTxpwr->c5GP2pPwrOffset = setting[3]; } if (setting[1] == 4 || setting[1] == 0) { if (setting[2] == 0 || setting[2] == 1) prTxpwr->c2GBowPwrOffset = setting[3]; if (setting[2] == 0 || setting[2] == 2) prTxpwr->c5GBowPwrOffset = setting[3]; } } else if (setting[0] == 1 && prIwReqData->data.length == 2) { prTxpwr->ucConcurrencePolicy = setting[1]; } else if (setting[0] == 2 && prIwReqData->data.length == 3) { if (setting[1] == 0) { for (i=0; i<14; i++) prTxpwr->acTxPwrLimit2G[i] = setting[2]; } else if (setting[1] <= 14) prTxpwr->acTxPwrLimit2G[setting[1] - 1] = setting[2]; } else if (setting[0] == 3 && prIwReqData->data.length == 3) { if (setting[1] == 0) { for (i=0; i<4; i++) prTxpwr->acTxPwrLimit5G[i] = setting[2]; } else if (setting[1] <= 4) prTxpwr->acTxPwrLimit5G[setting[1] - 1] = setting[2]; } else if (setting[0] == 4 && prIwReqData->data.length == 2) { if (setting[1] == 0) { wlanDefTxPowerCfg(prGlueInfo->prAdapter); } rStatus = kalIoctl(prGlueInfo, wlanoidSetTxPower, prTxpwr, sizeof(SET_TXPWR_CTRL_T), TRUE, FALSE, FALSE, FALSE, &u4BufLen); } else return -EFAULT; } return status; default: break; } return status; } /*----------------------------------------------------------------------------*/ /*! * \brief Private ioctl get int array handler. * * \param[in] pDev Net device requested. * \param[out] pIwReq Pointer to iwreq structure. * \param[in] prIwReqData The ioctl req structure, use the field of sub-command. * \param[out] pcExtra The buffer with put the return value * * \retval 0 For success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EFAULT For fail. * */ /*----------------------------------------------------------------------------*/ int priv_get_ints ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, IN OUT char *pcExtra ) { UINT_32 u4SubCmd; P_GLUE_INFO_T prGlueInfo; int status = 0; INT_32 ch[50]; ASSERT(prNetDev); ASSERT(prIwReqInfo); ASSERT(prIwReqData); ASSERT(pcExtra); if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) { return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); u4SubCmd = (UINT_32) prIwReqData->data.flags; switch (u4SubCmd) { case PRIV_CMD_GET_CH_LIST: { UINT_16 i; UINT_8 NumOfChannel = 50; UINT_8 ucMaxChannelNum = 50; RF_CHANNEL_INFO_T aucChannelList[50]; kalGetChannelList(prGlueInfo, BAND_NULL, ucMaxChannelNum, &NumOfChannel, aucChannelList); if (NumOfChannel > 50) NumOfChannel = 50; for (i = 0; i < NumOfChannel; i++) { ch[i] = (INT_32)aucChannelList[i].ucChannelNum; } prIwReqData->data.length = NumOfChannel; if (copy_to_user(prIwReqData->data.pointer, ch, NumOfChannel*sizeof(INT_32))) { return -EFAULT; } else return status; } default: break; } return status; } /* priv_get_int */ /*----------------------------------------------------------------------------*/ /*! * \brief Private ioctl set structure handler. * * \param[in] pDev Net device requested. * \param[in] prIwReqData Pointer to iwreq_data structure. * * \retval 0 For success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EINVAL If a value is out of range. * */ /*----------------------------------------------------------------------------*/ int priv_set_struct ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, IN char *pcExtra ) { UINT_32 u4SubCmd = 0; int status = 0; //WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS; UINT_32 u4CmdLen = 0; P_NDIS_TRANSPORT_STRUCT prNdisReq; PUINT_32 pu4IntBuf = NULL; P_GLUE_INFO_T prGlueInfo = NULL; UINT_32 u4BufLen = 0; ASSERT(prNetDev); //ASSERT(prIwReqInfo); ASSERT(prIwReqData); //ASSERT(pcExtra); kalMemZero(&aucOidBuf[0], sizeof(aucOidBuf)); if (FALSE == GLUE_CHK_PR2(prNetDev, prIwReqData)) { return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); u4SubCmd = (UINT_32) prIwReqData->data.flags; #if 0 printk(KERN_INFO DRV_NAME"priv_set_struct(): prIwReqInfo->cmd(0x%X), u4SubCmd(%ld)\n", prIwReqInfo->cmd, u4SubCmd ); #endif switch (u4SubCmd) { #if 0 //PTA_ENABLED case PRIV_CMD_BT_COEXIST: u4CmdLen = prIwReqData->data.length * sizeof(UINT_32); ASSERT(sizeof(PARAM_CUSTOM_BT_COEXIST_T) >= u4CmdLen); if (sizeof(PARAM_CUSTOM_BT_COEXIST_T) < u4CmdLen) { return -EFAULT; } if (copy_from_user(&aucOidBuf[0], prIwReqData->data.pointer, u4CmdLen)) { status = -EFAULT; //return -EFAULT; break; } rStatus = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetBtCoexistCtrl, (PVOID)&aucOidBuf[0], u4CmdLen, &u4BufLen); if (WLAN_STATUS_SUCCESS != rStatus) { status = -EFAULT; } break; #endif case PRIV_CUSTOM_BWCS_CMD: u4CmdLen = prIwReqData->data.length * sizeof(UINT_32); ASSERT(sizeof(PARAM_PTA_IPC_T) >= u4CmdLen); if (sizeof(PARAM_PTA_IPC_T) < u4CmdLen) { return -EFAULT; } #if CFG_SUPPORT_BCM && CFG_SUPPORT_BCM_BWCS && CFG_SUPPORT_BCM_BWCS_DEBUG DBGLOG(REQ, INFO, ("ucCmdLen = %d, size of PTA_IPC_T = %d, prIwReqData->data = 0x%x.\n", u4CmdLen, sizeof(PARAM_PTA_IPC_T), prIwReqData->data)); DBGLOG(REQ, INFO, ("priv_set_struct(): prIwReqInfo->cmd(0x%X), u4SubCmd(%ld)\n", prIwReqInfo->cmd, u4SubCmd )); DBGLOG(REQ, INFO, ("*pcExtra = 0x%x\n", *pcExtra)); #endif if (copy_from_user(&aucOidBuf[0], prIwReqData->data.pointer, u4CmdLen)) { status = -EFAULT; //return -EFAULT; break; } #if CFG_SUPPORT_BCM && CFG_SUPPORT_BCM_BWCS && CFG_SUPPORT_BCM_BWCS_DEBUG DBGLOG(REQ, INFO, ("priv_set_struct(): BWCS CMD = %02x%02x%02x%02x\n", aucOidBuf[2], aucOidBuf[3], aucOidBuf[4], aucOidBuf[5])); #endif #if 0 status = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetBT, (PVOID)&aucOidBuf[0], u4CmdLen, &u4BufLen); #endif #if 1 status = wlanoidSetBT(prGlueInfo->prAdapter, (PVOID)&aucOidBuf[0], u4CmdLen, &u4BufLen); #endif if (WLAN_STATUS_SUCCESS != status) { status = -EFAULT; } break; #if CFG_SUPPORT_WPS2 case PRIV_CMD_WSC_PROBE_REQ: { /* retrieve IE for Probe Request */ if (prIwReqData->data.length > 0) { if (copy_from_user(prGlueInfo->aucWSCIE, prIwReqData->data.pointer, prIwReqData->data.length)) { status = -EFAULT; break; } prGlueInfo->u2WSCIELen = prIwReqData->data.length; } else { prGlueInfo->u2WSCIELen = 0; } } break; #endif case PRIV_CMD_OID: if (copy_from_user(&aucOidBuf[0], prIwReqData->data.pointer, prIwReqData->data.length)) { status = -EFAULT; break; } if (!kalMemCmp(&aucOidBuf[0], pcExtra, prIwReqData->data.length)) { DBGLOG(REQ, INFO, ("pcExtra buffer is valid\n")); } else DBGLOG(REQ, INFO, ("pcExtra 0x%p\n", pcExtra)); /* Execute this OID */ status = priv_set_ndis(prNetDev, (P_NDIS_TRANSPORT_STRUCT)&aucOidBuf[0], &u4BufLen); /* Copy result to user space */ ((P_NDIS_TRANSPORT_STRUCT)&aucOidBuf[0])->outNdisOidLength = u4BufLen; if (copy_to_user(prIwReqData->data.pointer, &aucOidBuf[0], OFFSET_OF(NDIS_TRANSPORT_STRUCT, ndisOidContent))) { DBGLOG(REQ, INFO, ("copy_to_user oidBuf fail\n")); status = -EFAULT; } break; case PRIV_CMD_SW_CTRL: pu4IntBuf = (PUINT_32)prIwReqData->data.pointer; prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; //kalMemCopy(&prNdisReq->ndisOidContent[0], prIwReqData->data.pointer, 8); if (copy_from_user(&prNdisReq->ndisOidContent[0], prIwReqData->data.pointer, prIwReqData->data.length)) { status = -EFAULT; break; } prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; /* Execute this OID */ status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen); break; default: return -EOPNOTSUPP; } return status; } /*----------------------------------------------------------------------------*/ /*! * \brief Private ioctl get struct handler. * * \param[in] pDev Net device requested. * \param[out] pIwReq Pointer to iwreq structure. * \param[in] cmd Private sub-command. * * \retval 0 For success. * \retval -EFAULT If copy from user space buffer fail. * \retval -EOPNOTSUPP Parameter "cmd" not recognized. * */ /*----------------------------------------------------------------------------*/ int priv_get_struct ( IN struct net_device *prNetDev, IN struct iw_request_info *prIwReqInfo, IN union iwreq_data *prIwReqData, IN OUT char *pcExtra ) { UINT_32 u4SubCmd = 0; P_NDIS_TRANSPORT_STRUCT prNdisReq= NULL; P_GLUE_INFO_T prGlueInfo = NULL; UINT_32 u4BufLen = 0; PUINT_32 pu4IntBuf = NULL; int status = 0; kalMemZero(&aucOidBuf[0], sizeof(aucOidBuf)); ASSERT(prNetDev); ASSERT(prIwReqData); if (!prNetDev || !prIwReqData) { DBGLOG(REQ, INFO, ("priv_get_struct(): invalid param(0x%p, 0x%p)\n", prNetDev, prIwReqData)); return -EINVAL; } u4SubCmd = (UINT_32) prIwReqData->data.flags; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(REQ, INFO, ("priv_get_struct(): invalid prGlueInfo(0x%p, 0x%p)\n", prNetDev, *((P_GLUE_INFO_T *) netdev_priv(prNetDev)))); return -EINVAL; } #if 0 printk(KERN_INFO DRV_NAME"priv_get_struct(): prIwReqInfo->cmd(0x%X), u4SubCmd(%ld)\n", prIwReqInfo->cmd, u4SubCmd ); #endif memset(aucOidBuf, 0, sizeof(aucOidBuf)); switch (u4SubCmd) { case PRIV_CMD_OID: if (copy_from_user(&aucOidBuf[0], prIwReqData->data.pointer, sizeof(NDIS_TRANSPORT_STRUCT))) { DBGLOG(REQ, INFO, ("priv_get_struct() copy_from_user oidBuf fail\n")); return -EFAULT; } prNdisReq = (P_NDIS_TRANSPORT_STRUCT)&aucOidBuf[0]; #if 0 printk(KERN_NOTICE "\n priv_get_struct cmd 0x%02x len:%d OID:0x%08x OID Len:%d\n", cmd, pIwReq->u.data.length, ndisReq->ndisOidCmd, ndisReq->inNdisOidlength); #endif if (priv_get_ndis(prNetDev, prNdisReq, &u4BufLen) == 0) { prNdisReq->outNdisOidLength = u4BufLen; if (copy_to_user(prIwReqData->data.pointer, &aucOidBuf[0], u4BufLen + sizeof(NDIS_TRANSPORT_STRUCT) - sizeof(prNdisReq->ndisOidContent))) { DBGLOG(REQ, INFO, ("priv_get_struct() copy_to_user oidBuf fail(1)\n")); return -EFAULT; } return 0; } else { prNdisReq->outNdisOidLength = u4BufLen; if (copy_to_user(prIwReqData->data.pointer, &aucOidBuf[0], OFFSET_OF(NDIS_TRANSPORT_STRUCT, ndisOidContent))) { DBGLOG(REQ, INFO, ("priv_get_struct() copy_to_user oidBuf fail(2)\n")); } return -EFAULT; } break; case PRIV_CMD_SW_CTRL: pu4IntBuf = (PUINT_32)prIwReqData->data.pointer; prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0]; if (copy_from_user(&prNdisReq->ndisOidContent[0], prIwReqData->data.pointer, prIwReqData->data.length)) { DBGLOG(REQ, INFO, ("priv_get_struct() copy_from_user oidBuf fail\n")); return -EFAULT; } prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL; prNdisReq->inNdisOidlength = 8; prNdisReq->outNdisOidLength = 8; status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen); if (status == 0) { prNdisReq->outNdisOidLength = u4BufLen; //printk("len=%d Result=%08lx\n", u4BufLen, *(PUINT_32)&prNdisReq->ndisOidContent[4]); if (copy_to_user(prIwReqData->data.pointer, &prNdisReq->ndisOidContent[4], 4 /* OFFSET_OF(NDIS_TRANSPORT_STRUCT, ndisOidContent)*/)) { DBGLOG(REQ, INFO, ("priv_get_struct() copy_to_user oidBuf fail(2)\n")); } } return 0; break; default: DBGLOG(REQ, WARN, ("get struct cmd:0x%lx\n", u4SubCmd)); return -EOPNOTSUPP; } } /* priv_get_struct */ /*----------------------------------------------------------------------------*/ /*! * \brief The routine handles a set operation for a single OID. * * \param[in] pDev Net device requested. * \param[in] ndisReq Ndis request OID information copy from user. * \param[out] outputLen_p If the call is successful, returns the number of * bytes written into the query buffer. If the * call failed due to invalid length of the query * buffer, returns the amount of storage needed.. * * \retval 0 On success. * \retval -EOPNOTSUPP If cmd is not supported. * */ /*----------------------------------------------------------------------------*/ static int priv_set_ndis ( IN struct net_device *prNetDev, IN NDIS_TRANSPORT_STRUCT* prNdisReq, OUT PUINT_32 pu4OutputLen ) { P_WLAN_REQ_ENTRY prWlanReqEntry = NULL; WLAN_STATUS status = WLAN_STATUS_SUCCESS; P_GLUE_INFO_T prGlueInfo = NULL; UINT_32 u4SetInfoLen = 0; ASSERT(prNetDev); ASSERT(prNdisReq); ASSERT(pu4OutputLen); if (!prNetDev || !prNdisReq || !pu4OutputLen) { DBGLOG(REQ, INFO, ("priv_set_ndis(): invalid param(0x%p, 0x%p, 0x%p)\n", prNetDev, prNdisReq, pu4OutputLen)); return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(REQ, INFO, ("priv_set_ndis(): invalid prGlueInfo(0x%p, 0x%p)\n", prNetDev, *((P_GLUE_INFO_T *) netdev_priv(prNetDev)))); return -EINVAL; } #if 0 printk(KERN_INFO DRV_NAME"priv_set_ndis(): prNdisReq->ndisOidCmd(0x%lX)\n", prNdisReq->ndisOidCmd ); #endif if (FALSE == reqSearchSupportedOidEntry(prNdisReq->ndisOidCmd, &prWlanReqEntry)) { //WARNLOG(("Set OID: 0x%08lx (unknown)\n", prNdisReq->ndisOidCmd)); return -EOPNOTSUPP; } if (NULL == prWlanReqEntry->pfOidSetHandler) { //WARNLOG(("Set %s: Null set handler\n", prWlanReqEntry->pucOidName)); return -EOPNOTSUPP; } #if 0 printk(KERN_INFO DRV_NAME"priv_set_ndis(): %s\n", prWlanReqEntry->pucOidName ); #endif if (prWlanReqEntry->fgSetBufLenChecking) { if (prNdisReq->inNdisOidlength != prWlanReqEntry->u4InfoBufLen) { DBGLOG(REQ, WARN, ("Set %s: Invalid length (current=%ld, needed=%ld)\n", prWlanReqEntry->pucOidName, prNdisReq->inNdisOidlength, prWlanReqEntry->u4InfoBufLen)); *pu4OutputLen = prWlanReqEntry->u4InfoBufLen; return -EINVAL; } } if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_ONLY) { /* GLUE sw info only */ status = prWlanReqEntry->pfOidSetHandler(prGlueInfo, prNdisReq->ndisOidContent, prNdisReq->inNdisOidlength, &u4SetInfoLen); } else if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_EXTENSION) { /* multiple sw operations */ status = prWlanReqEntry->pfOidSetHandler(prGlueInfo, prNdisReq->ndisOidContent, prNdisReq->inNdisOidlength, &u4SetInfoLen); } else if (prWlanReqEntry->eOidMethod == ENUM_OID_DRIVER_CORE) { /* driver core*/ status = kalIoctl(prGlueInfo, (PFN_OID_HANDLER_FUNC)prWlanReqEntry->pfOidSetHandler, prNdisReq->ndisOidContent, prNdisReq->inNdisOidlength, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); } else { DBGLOG(REQ, INFO, ("priv_set_ndis(): unsupported OID method:0x%x\n", prWlanReqEntry->eOidMethod)); return -EOPNOTSUPP; } *pu4OutputLen = u4SetInfoLen; switch (status) { case WLAN_STATUS_SUCCESS: break; case WLAN_STATUS_INVALID_LENGTH: //WARNLOG(("Set %s: Invalid length (current=%ld, needed=%ld)\n", // prWlanReqEntry->pucOidName, //prNdisReq->inNdisOidlength, //u4SetInfoLen)); break; } if (WLAN_STATUS_SUCCESS != status) { return -EFAULT; } return 0; } /* priv_set_ndis */ /*----------------------------------------------------------------------------*/ /*! * \brief The routine handles a query operation for a single OID. Basically we * return information about the current state of the OID in question. * * \param[in] pDev Net device requested. * \param[in] ndisReq Ndis request OID information copy from user. * \param[out] outputLen_p If the call is successful, returns the number of * bytes written into the query buffer. If the * call failed due to invalid length of the query * buffer, returns the amount of storage needed.. * * \retval 0 On success. * \retval -EOPNOTSUPP If cmd is not supported. * \retval -EINVAL invalid input parameters * */ /*----------------------------------------------------------------------------*/ static int priv_get_ndis ( IN struct net_device *prNetDev, IN NDIS_TRANSPORT_STRUCT* prNdisReq, OUT PUINT_32 pu4OutputLen ) { P_WLAN_REQ_ENTRY prWlanReqEntry = NULL; UINT_32 u4BufLen = 0; WLAN_STATUS status = WLAN_STATUS_SUCCESS; P_GLUE_INFO_T prGlueInfo = NULL; ASSERT(prNetDev); ASSERT(prNdisReq); ASSERT(pu4OutputLen); if (!prNetDev || !prNdisReq || !pu4OutputLen) { DBGLOG(REQ, INFO, ("priv_get_ndis(): invalid param(0x%p, 0x%p, 0x%p)\n", prNetDev, prNdisReq, pu4OutputLen)); return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev)); ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(REQ, INFO, ("priv_get_ndis(): invalid prGlueInfo(0x%p, 0x%p)\n", prNetDev, *((P_GLUE_INFO_T *) netdev_priv(prNetDev)))); return -EINVAL; } #if 0 printk(KERN_INFO DRV_NAME"priv_get_ndis(): prNdisReq->ndisOidCmd(0x%lX)\n", prNdisReq->ndisOidCmd ); #endif if (FALSE == reqSearchSupportedOidEntry(prNdisReq->ndisOidCmd, &prWlanReqEntry)) { //WARNLOG(("Query OID: 0x%08lx (unknown)\n", prNdisReq->ndisOidCmd)); return -EOPNOTSUPP; } if (NULL == prWlanReqEntry->pfOidQueryHandler) { //WARNLOG(("Query %s: Null query handler\n", prWlanReqEntry->pucOidName)); return -EOPNOTSUPP; } #if 0 printk(KERN_INFO DRV_NAME"priv_get_ndis(): %s\n", prWlanReqEntry->pucOidName ); #endif if (prWlanReqEntry->fgQryBufLenChecking) { if (prNdisReq->inNdisOidlength < prWlanReqEntry->u4InfoBufLen) { /* Not enough room in InformationBuffer. Punt */ //WARNLOG(("Query %s: Buffer too short (current=%ld, needed=%ld)\n", //prWlanReqEntry->pucOidName, //prNdisReq->inNdisOidlength, //prWlanReqEntry->u4InfoBufLen)); *pu4OutputLen = prWlanReqEntry->u4InfoBufLen; status = WLAN_STATUS_INVALID_LENGTH; return -EINVAL; } } if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_ONLY) { /* GLUE sw info only */ status = prWlanReqEntry->pfOidQueryHandler(prGlueInfo, prNdisReq->ndisOidContent, prNdisReq->inNdisOidlength, &u4BufLen); } else if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_EXTENSION) { /* multiple sw operations */ status = prWlanReqEntry->pfOidQueryHandler(prGlueInfo, prNdisReq->ndisOidContent, prNdisReq->inNdisOidlength, &u4BufLen); } else if (prWlanReqEntry->eOidMethod == ENUM_OID_DRIVER_CORE) { /* driver core*/ status = kalIoctl(prGlueInfo, (PFN_OID_HANDLER_FUNC)prWlanReqEntry->pfOidQueryHandler, prNdisReq->ndisOidContent, prNdisReq->inNdisOidlength, TRUE, TRUE, TRUE, FALSE, &u4BufLen); } else { DBGLOG(REQ, INFO, ("priv_set_ndis(): unsupported OID method:0x%x\n", prWlanReqEntry->eOidMethod)); return -EOPNOTSUPP; } *pu4OutputLen = u4BufLen; switch (status) { case WLAN_STATUS_SUCCESS: break; case WLAN_STATUS_INVALID_LENGTH: //WARNLOG(("Set %s: Invalid length (current=%ld, needed=%ld)\n", // prWlanReqEntry->pucOidName, //prNdisReq->inNdisOidlength, //u4BufLen)); break; } if (WLAN_STATUS_SUCCESS != status) { return -EOPNOTSUPP; } return 0; } /* priv_get_ndis */ /*----------------------------------------------------------------------------*/ /*! * \brief This routine is called to search desired OID. * * \param rOid[in] Desired NDIS_OID * \param ppWlanReqEntry[out] Found registered OID entry * * \retval TRUE: Matched OID is found * \retval FALSE: No matched OID is found */ /*----------------------------------------------------------------------------*/ static BOOLEAN reqSearchSupportedOidEntry ( IN UINT_32 rOid, OUT P_WLAN_REQ_ENTRY *ppWlanReqEntry ) { INT_32 i, j, k; i = 0; j = NUM_SUPPORTED_OIDS - 1; while (i <= j) { k = (i + j) / 2; if (rOid == arWlanOidReqTable[k].rOid) { *ppWlanReqEntry = &arWlanOidReqTable[k]; return TRUE; } else if (rOid < arWlanOidReqTable[k].rOid) { j = k - 1; } else { i = k + 1; } } return FALSE; } /* reqSearchSupportedOidEntry */ #if 0 /*----------------------------------------------------------------------------*/ /*! * \brief This routine is called to query the radio configuration used in IBSS * mode and RF test mode. * * \param[in] prGlueInfo Pointer to the GLUE_INFO_T structure. * \param[out] pvQueryBuffer Pointer to the buffer that holds the result of the query. * \param[in] u4QueryBufferLen The length of the query buffer. * \param[out] pu4QueryInfoLen If the call is successful, returns the number of * bytes written into the query buffer. If the call * failed due to invalid length of the query buffer, * returns the amount of storage needed. * * \retval WLAN_STATUS_SUCCESS * \retval WLAN_STATUS_INVALID_LENGTH */ /*----------------------------------------------------------------------------*/ static WLAN_STATUS reqExtQueryConfiguration ( IN P_GLUE_INFO_T prGlueInfo, OUT PVOID pvQueryBuffer, IN UINT_32 u4QueryBufferLen, OUT PUINT_32 pu4QueryInfoLen ) { P_PARAM_802_11_CONFIG_T prQueryConfig = (P_PARAM_802_11_CONFIG_T)pvQueryBuffer; WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS; UINT_32 u4QueryInfoLen = 0; DEBUGFUNC("wlanoidQueryConfiguration"); ASSERT(prGlueInfo); ASSERT(pu4QueryInfoLen); *pu4QueryInfoLen = sizeof(PARAM_802_11_CONFIG_T); if (u4QueryBufferLen < sizeof(PARAM_802_11_CONFIG_T)) { return WLAN_STATUS_INVALID_LENGTH; } ASSERT(pvQueryBuffer); kalMemZero(prQueryConfig, sizeof(PARAM_802_11_CONFIG_T)); /* Update the current radio configuration. */ prQueryConfig->u4Length = sizeof(PARAM_802_11_CONFIG_T); #if defined(_HIF_SDIO) rStatus = sdio_io_ctrl(prGlueInfo, wlanoidSetBeaconInterval, &prQueryConfig->u4BeaconPeriod, sizeof(UINT_32), TRUE, TRUE, &u4QueryInfoLen); #else rStatus = wlanQueryInformation(prGlueInfo->prAdapter, wlanoidQueryBeaconInterval, &prQueryConfig->u4BeaconPeriod, sizeof(UINT_32), &u4QueryInfoLen); #endif if (rStatus != WLAN_STATUS_SUCCESS) { return rStatus; } #if defined(_HIF_SDIO) rStatus = sdio_io_ctrl(prGlueInfo, wlanoidQueryAtimWindow, &prQueryConfig->u4ATIMWindow, sizeof(UINT_32), TRUE, TRUE, &u4QueryInfoLen); #else rStatus = wlanQueryInformation(prGlueInfo->prAdapter, wlanoidQueryAtimWindow, &prQueryConfig->u4ATIMWindow, sizeof(UINT_32), &u4QueryInfoLen); #endif if (rStatus != WLAN_STATUS_SUCCESS) { return rStatus; } #if defined(_HIF_SDIO) rStatus = sdio_io_ctrl(prGlueInfo, wlanoidQueryFrequency, &prQueryConfig->u4DSConfig, sizeof(UINT_32), TRUE, TRUE, &u4QueryInfoLen); #else rStatus = wlanQueryInformation(prGlueInfo->prAdapter, wlanoidQueryFrequency, &prQueryConfig->u4DSConfig, sizeof(UINT_32), &u4QueryInfoLen); #endif if (rStatus != WLAN_STATUS_SUCCESS) { return rStatus; } prQueryConfig->rFHConfig.u4Length = sizeof(PARAM_802_11_CONFIG_FH_T); return rStatus; } /* end of reqExtQueryConfiguration() */ /*----------------------------------------------------------------------------*/ /*! * \brief This routine is called to set the radio configuration used in IBSS * mode. * * \param[in] prGlueInfo Pointer to the GLUE_INFO_T structure. * \param[in] pvSetBuffer A pointer to the buffer that holds the data to be set. * \param[in] u4SetBufferLen The length of the set buffer. * \param[out] pu4SetInfoLen If the call is successful, returns the number of * bytes read from the set buffer. If the call failed * due to invalid length of the set buffer, returns * the amount of storage needed. * * \retval WLAN_STATUS_SUCCESS * \retval WLAN_STATUS_INVALID_LENGTH * \retval WLAN_STATUS_NOT_ACCEPTED */ /*----------------------------------------------------------------------------*/ static WLAN_STATUS reqExtSetConfiguration ( IN P_GLUE_INFO_T prGlueInfo, IN PVOID pvSetBuffer, IN UINT_32 u4SetBufferLen, OUT PUINT_32 pu4SetInfoLen ) { WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS; P_PARAM_802_11_CONFIG_T prNewConfig = (P_PARAM_802_11_CONFIG_T)pvSetBuffer; UINT_32 u4SetInfoLen = 0; DEBUGFUNC("wlanoidSetConfiguration"); ASSERT(prGlueInfo); ASSERT(pu4SetInfoLen); *pu4SetInfoLen = sizeof(PARAM_802_11_CONFIG_T); if (u4SetBufferLen < *pu4SetInfoLen) { return WLAN_STATUS_INVALID_LENGTH; } /* OID_802_11_CONFIGURATION. If associated, NOT_ACCEPTED shall be returned. */ if (prGlueInfo->eParamMediaStateIndicated == PARAM_MEDIA_STATE_CONNECTED) { return WLAN_STATUS_NOT_ACCEPTED; } ASSERT(pvSetBuffer); #if defined(_HIF_SDIO) rStatus = sdio_io_ctrl(prGlueInfo, wlanoidSetBeaconInterval, &prNewConfig->u4BeaconPeriod, sizeof(UINT_32), FALSE, TRUE, &u4SetInfoLen); #else rStatus = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetBeaconInterval, &prNewConfig->u4BeaconPeriod, sizeof(UINT_32), &u4SetInfoLen); #endif if (rStatus != WLAN_STATUS_SUCCESS) { return rStatus; } #if defined(_HIF_SDIO) rStatus = sdio_io_ctrl(prGlueInfo, wlanoidSetAtimWindow, &prNewConfig->u4ATIMWindow, sizeof(UINT_32), FALSE, TRUE, &u4SetInfoLen); #else rStatus = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetAtimWindow, &prNewConfig->u4ATIMWindow, sizeof(UINT_32), &u4SetInfoLen); #endif if (rStatus != WLAN_STATUS_SUCCESS) { return rStatus; } #if defined(_HIF_SDIO) rStatus = sdio_io_ctrl(prGlueInfo, wlanoidSetFrequency, &prNewConfig->u4DSConfig, sizeof(UINT_32), FALSE, TRUE, &u4SetInfoLen); #else rStatus = wlanSetInformation(prGlueInfo->prAdapter, wlanoidSetFrequency, &prNewConfig->u4DSConfig, sizeof(UINT_32), &u4SetInfoLen); #endif if (rStatus != WLAN_STATUS_SUCCESS) { return rStatus; } return rStatus; } /* end of reqExtSetConfiguration() */ #endif /*----------------------------------------------------------------------------*/ /*! * \brief This routine is called to set beacon detection function enable/disable state * This is mainly designed for usage under BT inquiry state (disable function). * * \param[in] pvAdapter Pointer to the Adapter structure * \param[in] pvSetBuffer A pointer to the buffer that holds the data to be set * \param[in] u4SetBufferLen The length of the set buffer * \param[out] pu4SetInfoLen If the call is successful, returns the number of * bytes read from the set buffer. If the call failed due to invalid length of * the set buffer, returns the amount of storage needed. * * \retval WLAN_STATUS_SUCCESS * \retval WLAN_STATUS_INVALID_DATA If new setting value is wrong. * \retval WLAN_STATUS_INVALID_LENGTH * */ /*----------------------------------------------------------------------------*/ static WLAN_STATUS reqExtSetAcpiDevicePowerState ( IN P_GLUE_INFO_T prGlueInfo, IN PVOID pvSetBuffer, IN UINT_32 u4SetBufferLen, OUT PUINT_32 pu4SetInfoLen ) { WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS; ASSERT(prGlueInfo); ASSERT(pvSetBuffer); ASSERT(pu4SetInfoLen); /* WIFI is enabled, when ACPI is D0 (ParamDeviceStateD0 = 1). And vice versa */ //rStatus = wlanSetInformation(prGlueInfo->prAdapter, // wlanoidSetAcpiDevicePowerState, // pvSetBuffer, // u4SetBufferLen, // pu4SetInfoLen); return rStatus; }
gpl-2.0
Chong-Li/RTDS-ToolStack
tools/libxc/xc_compression.c
16432
/****************************************************************************** * xc_compression.c * * Checkpoint Compression using Page Delta Algorithm. * - A LRU cache of recently dirtied guest pages is maintained. * - For each dirty guest page in the checkpoint, if a previous version of the * page exists in the cache, XOR both pages and send the non-zero sections * to the receiver. The cache is then updated with the newer copy of guest page. * - The receiver will XOR the non-zero sections against its copy of the guest * page, thereby bringing the guest page up-to-date with the sender side. * * Copyright (c) 2011 Shriram Rajagopalan ([email protected]). * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <inttypes.h> #include "xc_private.h" #include "xenctrl.h" #include "xg_save_restore.h" #include "xg_private.h" #include "xc_dom.h" /* Page Cache for Delta Compression*/ #define DELTA_CACHE_SIZE (XC_PAGE_SIZE * 8192) /* Internal page buffer to hold dirty pages of a checkpoint, * to be compressed after the domain is resumed for execution. */ #define PAGE_BUFFER_SIZE (XC_PAGE_SIZE * 8192) struct cache_page { char *page; xen_pfn_t pfn; struct cache_page *next; struct cache_page *prev; }; struct compression_ctx { /* compression buffer - holds compressed data */ char *compbuf; unsigned long compbuf_size; unsigned long compbuf_pos; /* Page buffer to hold pages to be compressed */ char *inputbuf; /* pfns of pages to be compressed */ xen_pfn_t *sendbuf_pfns; unsigned int pfns_len; unsigned int pfns_index; /* Compression Cache (LRU) */ char *cache_base; struct cache_page **pfn2cache; struct cache_page *cache; struct cache_page *page_list_head; struct cache_page *page_list_tail; unsigned long dom_pfnlist_size; }; #define RUNFLAG 0 #define SKIPFLAG ((char)128) #define FLAGMASK SKIPFLAG #define LENMASK ((char)127) /* * see xg_save_restore.h for details on the compressed stream format. * delta size = 4 bytes. * run header = 1 byte (1 bit for runtype, 7bits for run length). * i.e maximum size of a run = 127 * 4 = 508 bytes. * Worst case compression: Entire page has changed. * In the worst case, the size of the compressed page is * 8 runs of 508 bytes + 1 run of 32 bytes + 9 run headers * = 4105 bytes. * We could detect this worst case and send the entire page with a * FULL_PAGE marker, reducing the total size to 4097 bytes. The cost * of this size reduction is an additional memcpy, on top of two previous * memcpy (to the compressed stream and the cache page in the for loop). * * We might as well sacrifice an extra 8 bytes instead of a memcpy. */ #define WORST_COMP_PAGE_SIZE (XC_PAGE_SIZE + 9) /* * A zero length skip indicates full page. */ #define EMPTY_PAGE 0 #define FULL_PAGE SKIPFLAG #define FULL_PAGE_SIZE (XC_PAGE_SIZE + 1) #define MAX_DELTAS (XC_PAGE_SIZE/sizeof(uint32_t)) /* * Add a pagetable page or a new page (uncached) * if srcpage is a pagetable page, cache_page is null. * if srcpage is a page that was not previously in the cache, * cache_page points to a free page slot in the cache where * this new page can be copied to. */ static int add_full_page(comp_ctx *ctx, char *srcpage, char *cache_page) { char *dest = (ctx->compbuf + ctx->compbuf_pos); if ( (ctx->compbuf_pos + FULL_PAGE_SIZE) > ctx->compbuf_size) return -1; if (cache_page) memcpy(cache_page, srcpage, XC_PAGE_SIZE); dest[0] = FULL_PAGE; memcpy(&dest[1], srcpage, XC_PAGE_SIZE); ctx->compbuf_pos += FULL_PAGE_SIZE; return FULL_PAGE_SIZE; } static int compress_page(comp_ctx *ctx, char *srcpage, char *cache_page) { char *dest = (ctx->compbuf + ctx->compbuf_pos); uint32_t *new, *old; int off, runptr = 0; int wascopying = 0, copying = 0, bytes_skipped = 0; int complen = 0, pageoff = 0, runbytes = 0; char runlen = 0; if ( (ctx->compbuf_pos + WORST_COMP_PAGE_SIZE) > ctx->compbuf_size) return -1; /* * There are no alignment issues here since srcpage is * domU's page passed from xc_domain_save and cache_page is * a ptr to cache page (cache is page aligned). */ new = (uint32_t*)srcpage; old = (uint32_t*)cache_page; for (off = 0; off <= MAX_DELTAS; off++) { /* * At (off == MAX_DELTAS), we are processing the last run * in the page. Since there is no XORing, make wascopying != copying * to satisfy the if-block below. */ copying = ((off < MAX_DELTAS) ? (old[off] != new[off]) : !wascopying); if (runlen) { /* switching between run types or current run is full */ if ( (wascopying != copying) || (runlen == LENMASK) ) { runbytes = runlen * sizeof(uint32_t); runlen |= (wascopying ? RUNFLAG : SKIPFLAG); dest[complen++] = runlen; if (wascopying) /* RUNFLAG */ { pageoff = runptr * sizeof(uint32_t); memcpy(dest + complen, srcpage + pageoff, runbytes); memcpy(cache_page + pageoff, srcpage + pageoff, runbytes); complen += runbytes; } else /* SKIPFLAG */ { bytes_skipped += runbytes; } runlen = 0; runptr = off; } } runlen++; wascopying = copying; } /* * Check for empty page. */ if (bytes_skipped == XC_PAGE_SIZE) { complen = 1; dest[0] = EMPTY_PAGE; } ctx->compbuf_pos += complen; return complen; } static char *get_cache_page(comp_ctx *ctx, xen_pfn_t pfn, int *israw) { struct cache_page *item = NULL; item = ctx->pfn2cache[pfn]; if (!item) { *israw = 1; /* If the list is full, evict a page from the tail end. */ item = ctx->page_list_tail; if (item->pfn != INVALID_P2M_ENTRY) ctx->pfn2cache[item->pfn] = NULL; item->pfn = pfn; ctx->pfn2cache[pfn] = item; } /* if requested item is in cache move to head of list */ if (item != ctx->page_list_head) { if (item == ctx->page_list_tail) { /* item at tail of list. */ ctx->page_list_tail = item->prev; (ctx->page_list_tail)->next = NULL; } else { /* item in middle of list */ item->prev->next = item->next; item->next->prev = item->prev; } item->prev = NULL; item->next = ctx->page_list_head; (ctx->page_list_head)->prev = item; ctx->page_list_head = item; } return (ctx->page_list_head)->page; } /* Remove pagetable pages from cache and move to tail, as free pages */ static void invalidate_cache_page(comp_ctx *ctx, xen_pfn_t pfn) { struct cache_page *item = NULL; item = ctx->pfn2cache[pfn]; if (item) { if (item != ctx->page_list_tail) { /* item at head of list */ if (item == ctx->page_list_head) { ctx->page_list_head = (ctx->page_list_head)->next; (ctx->page_list_head)->prev = NULL; } else /* item in middle of list */ { item->prev->next = item->next; item->next->prev = item->prev; } item->next = NULL; item->prev = ctx->page_list_tail; (ctx->page_list_tail)->next = item; ctx->page_list_tail = item; } ctx->pfn2cache[pfn] = NULL; (ctx->page_list_tail)->pfn = INVALID_P2M_ENTRY; } } int xc_compression_add_page(xc_interface *xch, comp_ctx *ctx, char *page, xen_pfn_t pfn, int israw) { if (pfn > ctx->dom_pfnlist_size) { ERROR("Invalid pfn passed into " "xc_compression_add_page %" PRIpfn "\n", pfn); return -2; } /* pagetable page */ if (israw) invalidate_cache_page(ctx, pfn); ctx->sendbuf_pfns[ctx->pfns_len] = israw ? INVALID_P2M_ENTRY : pfn; memcpy(ctx->inputbuf + ctx->pfns_len * XC_PAGE_SIZE, page, XC_PAGE_SIZE); ctx->pfns_len++; /* check if we have run out of space. If so, * we need to synchronously compress the pages and flush them out */ if (ctx->pfns_len == NRPAGES(PAGE_BUFFER_SIZE)) return -1; return 0; } int xc_compression_compress_pages(xc_interface *xch, comp_ctx *ctx, char *compbuf, unsigned long compbuf_size, unsigned long *compbuf_len) { char *cache_copy = NULL, *current_page = NULL; int israw, rc = 1; if (!ctx->pfns_len || (ctx->pfns_index == ctx->pfns_len)) { ctx->pfns_len = ctx->pfns_index = 0; return 0; } ctx->compbuf_pos = 0; ctx->compbuf = compbuf; ctx->compbuf_size = compbuf_size; for (; ctx->pfns_index < ctx->pfns_len; ctx->pfns_index++) { israw = 0; cache_copy = NULL; current_page = ctx->inputbuf + ctx->pfns_index * XC_PAGE_SIZE; if (ctx->sendbuf_pfns[ctx->pfns_index] == INVALID_P2M_ENTRY) israw = 1; else cache_copy = get_cache_page(ctx, ctx->sendbuf_pfns[ctx->pfns_index], &israw); if (israw) rc = (add_full_page(ctx, current_page, cache_copy) >= 0); else rc = (compress_page(ctx, current_page, cache_copy) >= 0); if ( !rc ) { /* Out of space in outbuf! flush and come back */ rc = -1; break; } } if (compbuf_len) *compbuf_len = ctx->compbuf_pos; return rc; } inline void xc_compression_reset_pagebuf(xc_interface *xch, comp_ctx *ctx) { ctx->pfns_index = ctx->pfns_len = 0; } int xc_compression_uncompress_page(xc_interface *xch, char *compbuf, unsigned long compbuf_size, unsigned long *compbuf_pos, char *destpage) { unsigned long pos; unsigned int len = 0, pagepos = 0; char flag; pos = *compbuf_pos; if (pos >= compbuf_size) { ERROR("Out of bounds exception in compression buffer (a):" "read ptr:%lu, bufsize = %lu\n", *compbuf_pos, compbuf_size); return -1; } switch (compbuf[pos]) { case EMPTY_PAGE: pos++; break; case FULL_PAGE: { /* Check if the input buffer has 4KB of data */ if ((pos + FULL_PAGE_SIZE) > compbuf_size) { ERROR("Out of bounds exception in compression buffer (b):" "read ptr = %lu, bufsize = %lu\n", *compbuf_pos, compbuf_size); return -1; } memcpy(destpage, &compbuf[pos + 1], XC_PAGE_SIZE); pos += FULL_PAGE_SIZE; } break; default: /* Normal page with one or more runs */ { do { flag = compbuf[pos] & FLAGMASK; len = (compbuf[pos] & LENMASK) * sizeof(uint32_t); /* Sanity Check: Zero-length runs are allowed only for * FULL_PAGE and EMPTY_PAGE. */ if (!len) { ERROR("Zero length run encountered for normal page: " "buffer (d):read ptr = %lu, flag = %u, " "bufsize = %lu, pagepos = %u\n", pos, (unsigned int)flag, compbuf_size, pagepos); return -1; } pos++; if (flag == RUNFLAG) { /* Check if the input buffer has len bytes of data * and whether it would fit in the destination page. */ if (((pos + len) > compbuf_size) || ((pagepos + len) > XC_PAGE_SIZE)) { ERROR("Out of bounds exception in compression " "buffer (c):read ptr = %lu, runlen = %u, " "bufsize = %lu, pagepos = %u\n", pos, len, compbuf_size, pagepos); return -1; } memcpy(&destpage[pagepos], &compbuf[pos], len); pos += len; } pagepos += len; } while ((pagepos < XC_PAGE_SIZE) && (pos < compbuf_size)); /* Make sure we have copied/skipped 4KB worth of data */ if (pagepos != XC_PAGE_SIZE) { ERROR("Invalid data in compression buffer:" "read ptr = %lu, bufsize = %lu, pagepos = %u\n", pos, compbuf_size, pagepos); return -1; } } } *compbuf_pos = pos; return 0; } void xc_compression_free_context(xc_interface *xch, comp_ctx *ctx) { if (!ctx) return; free(ctx->inputbuf); free(ctx->sendbuf_pfns); free(ctx->cache_base); free(ctx->pfn2cache); free(ctx->cache); free(ctx); } comp_ctx *xc_compression_create_context(xc_interface *xch, unsigned long p2m_size) { unsigned long i; comp_ctx *ctx = NULL; unsigned long num_cache_pages = DELTA_CACHE_SIZE/XC_PAGE_SIZE; ctx = (comp_ctx *)malloc(sizeof(comp_ctx)); if (!ctx) { ERROR("Failed to allocate compression_ctx\n"); goto error; } memset(ctx, 0, sizeof(comp_ctx)); ctx->inputbuf = xc_memalign(xch, XC_PAGE_SIZE, PAGE_BUFFER_SIZE); if (!ctx->inputbuf) { ERROR("Failed to allocate page buffer\n"); goto error; } ctx->cache_base = xc_memalign(xch, XC_PAGE_SIZE, DELTA_CACHE_SIZE); if (!ctx->cache_base) { ERROR("Failed to allocate delta cache\n"); goto error; } ctx->sendbuf_pfns = malloc(NRPAGES(PAGE_BUFFER_SIZE) * sizeof(xen_pfn_t)); if (!ctx->sendbuf_pfns) { ERROR("Could not alloc sendbuf_pfns\n"); goto error; } memset(ctx->sendbuf_pfns, -1, NRPAGES(PAGE_BUFFER_SIZE) * sizeof(xen_pfn_t)); ctx->pfn2cache = calloc(p2m_size, sizeof(struct cache_page *)); if (!ctx->pfn2cache) { ERROR("Could not alloc pfn2cache map\n"); goto error; } ctx->cache = malloc(num_cache_pages * sizeof(struct cache_page)); if (!ctx->cache) { ERROR("Could not alloc compression cache\n"); goto error; } for (i = 0; i < num_cache_pages; i++) { ctx->cache[i].pfn = INVALID_P2M_ENTRY; ctx->cache[i].page = ctx->cache_base + i * XC_PAGE_SIZE; ctx->cache[i].prev = (i == 0) ? NULL : &(ctx->cache[i - 1]); ctx->cache[i].next = ((i+1) == num_cache_pages)? NULL : &(ctx->cache[i + 1]); } ctx->page_list_head = &(ctx->cache[0]); ctx->page_list_tail = &(ctx->cache[num_cache_pages -1]); ctx->dom_pfnlist_size = p2m_size; return ctx; error: xc_compression_free_context(xch, ctx); return NULL; } /* * Local variables: * mode: C * c-file-style: "BSD" * c-basic-offset: 4 * tab-width: 4 * indent-tabs-mode: nil * End: */
gpl-2.0
neutrino-mp/neutrino-mp
lib/libmd5sum/libmd5sum.c
1867
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include <sys/types.h> #include <error.h> #include <errno.h> #include <string.h> #include "libmd5sum.h" #include "md5.h" #include "getline.h" #define STREQ(a, b) (strcmp ((a), (b)) == 0) static int have_read_stdin; #if O_BINARY # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT) # define TEXT1TO1 "rb" # define TEXTCNVT "r" #else # if defined VMS # define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT) # define TEXT1TO1 "rb", "ctx=stm" # define TEXTCNVT "r", "ctx=stm" # else # if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION # define OPENOPTS(BINARY) "r" # else /* The following line is intended to evoke an error. Using #error is not portable enough. */ "Cannot determine system type." # endif # endif #endif int md5_file (const char *filename, int binary, unsigned char *md5_result) { FILE *fp; int err; (void)binary; if (STREQ (filename, "-")) { have_read_stdin = 1; fp = stdin; #if O_BINARY /* If we need binary reads from a pipe or redirected stdin, we need to switch it to BINARY mode here, since stdin is already open. */ if (binary) SET_BINARY (fileno (stdin)); #endif } else { /* OPENOPTS is a macro. It varies with the system. Some systems distinguish between internal and external text representations. */ fp = fopen (filename, OPENOPTS (binary)); if (fp == NULL) { error (0, errno, "%s", filename); return 1; } } err = md5_stream (fp, md5_result); if (err) { error (0, errno, "%s", filename); if (fp != stdin) fclose (fp); return 1; } if (fp != stdin && fclose (fp) == EOF) { error (0, errno, "%s", filename); return 1; } return 0; }
gpl-2.0
raumfeld/linux-am33xx
drivers/mmc/host/dw_mmc.c
91646
/* * Synopsys DesignWare Multimedia Card Interface driver * (Based on NXP driver for lpc 31xx) * * Copyright (C) 2009 NXP Semiconductors * Copyright (C) 2009, 2010 Imagination Technologies Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/blkdev.h> #include <linux/clk.h> #include <linux/debugfs.h> #include <linux/device.h> #include <linux/dma-mapping.h> #include <linux/err.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/iopoll.h> #include <linux/ioport.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/stat.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <linux/mmc/sdio.h> #include <linux/bitops.h> #include <linux/regulator/consumer.h> #include <linux/of.h> #include <linux/of_gpio.h> #include <linux/mmc/slot-gpio.h> #include "dw_mmc.h" /* Common flag combinations */ #define DW_MCI_DATA_ERROR_FLAGS (SDMMC_INT_DRTO | SDMMC_INT_DCRC | \ SDMMC_INT_HTO | SDMMC_INT_SBE | \ SDMMC_INT_EBE | SDMMC_INT_HLE) #define DW_MCI_CMD_ERROR_FLAGS (SDMMC_INT_RTO | SDMMC_INT_RCRC | \ SDMMC_INT_RESP_ERR | SDMMC_INT_HLE) #define DW_MCI_ERROR_FLAGS (DW_MCI_DATA_ERROR_FLAGS | \ DW_MCI_CMD_ERROR_FLAGS) #define DW_MCI_SEND_STATUS 1 #define DW_MCI_RECV_STATUS 2 #define DW_MCI_DMA_THRESHOLD 16 #define DW_MCI_FREQ_MAX 200000000 /* unit: HZ */ #define DW_MCI_FREQ_MIN 100000 /* unit: HZ */ #define IDMAC_INT_CLR (SDMMC_IDMAC_INT_AI | SDMMC_IDMAC_INT_NI | \ SDMMC_IDMAC_INT_CES | SDMMC_IDMAC_INT_DU | \ SDMMC_IDMAC_INT_FBE | SDMMC_IDMAC_INT_RI | \ SDMMC_IDMAC_INT_TI) #define DESC_RING_BUF_SZ PAGE_SIZE struct idmac_desc_64addr { u32 des0; /* Control Descriptor */ #define IDMAC_OWN_CLR64(x) \ !((x) & cpu_to_le32(IDMAC_DES0_OWN)) u32 des1; /* Reserved */ u32 des2; /*Buffer sizes */ #define IDMAC_64ADDR_SET_BUFFER1_SIZE(d, s) \ ((d)->des2 = ((d)->des2 & cpu_to_le32(0x03ffe000)) | \ ((cpu_to_le32(s)) & cpu_to_le32(0x1fff))) u32 des3; /* Reserved */ u32 des4; /* Lower 32-bits of Buffer Address Pointer 1*/ u32 des5; /* Upper 32-bits of Buffer Address Pointer 1*/ u32 des6; /* Lower 32-bits of Next Descriptor Address */ u32 des7; /* Upper 32-bits of Next Descriptor Address */ }; struct idmac_desc { __le32 des0; /* Control Descriptor */ #define IDMAC_DES0_DIC BIT(1) #define IDMAC_DES0_LD BIT(2) #define IDMAC_DES0_FD BIT(3) #define IDMAC_DES0_CH BIT(4) #define IDMAC_DES0_ER BIT(5) #define IDMAC_DES0_CES BIT(30) #define IDMAC_DES0_OWN BIT(31) __le32 des1; /* Buffer sizes */ #define IDMAC_SET_BUFFER1_SIZE(d, s) \ ((d)->des1 = ((d)->des1 & cpu_to_le32(0x03ffe000)) | (cpu_to_le32((s) & 0x1fff))) __le32 des2; /* buffer 1 physical address */ __le32 des3; /* buffer 2 physical address */ }; /* Each descriptor can transfer up to 4KB of data in chained mode */ #define DW_MCI_DESC_DATA_LENGTH 0x1000 #if defined(CONFIG_DEBUG_FS) static int dw_mci_req_show(struct seq_file *s, void *v) { struct dw_mci_slot *slot = s->private; struct mmc_request *mrq; struct mmc_command *cmd; struct mmc_command *stop; struct mmc_data *data; /* Make sure we get a consistent snapshot */ spin_lock_bh(&slot->host->lock); mrq = slot->mrq; if (mrq) { cmd = mrq->cmd; data = mrq->data; stop = mrq->stop; if (cmd) seq_printf(s, "CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n", cmd->opcode, cmd->arg, cmd->flags, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[2], cmd->error); if (data) seq_printf(s, "DATA %u / %u * %u flg %x err %d\n", data->bytes_xfered, data->blocks, data->blksz, data->flags, data->error); if (stop) seq_printf(s, "CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\n", stop->opcode, stop->arg, stop->flags, stop->resp[0], stop->resp[1], stop->resp[2], stop->resp[2], stop->error); } spin_unlock_bh(&slot->host->lock); return 0; } DEFINE_SHOW_ATTRIBUTE(dw_mci_req); static int dw_mci_regs_show(struct seq_file *s, void *v) { struct dw_mci *host = s->private; pm_runtime_get_sync(host->dev); seq_printf(s, "STATUS:\t0x%08x\n", mci_readl(host, STATUS)); seq_printf(s, "RINTSTS:\t0x%08x\n", mci_readl(host, RINTSTS)); seq_printf(s, "CMD:\t0x%08x\n", mci_readl(host, CMD)); seq_printf(s, "CTRL:\t0x%08x\n", mci_readl(host, CTRL)); seq_printf(s, "INTMASK:\t0x%08x\n", mci_readl(host, INTMASK)); seq_printf(s, "CLKENA:\t0x%08x\n", mci_readl(host, CLKENA)); pm_runtime_put_autosuspend(host->dev); return 0; } DEFINE_SHOW_ATTRIBUTE(dw_mci_regs); static void dw_mci_init_debugfs(struct dw_mci_slot *slot) { struct mmc_host *mmc = slot->mmc; struct dw_mci *host = slot->host; struct dentry *root; struct dentry *node; root = mmc->debugfs_root; if (!root) return; node = debugfs_create_file("regs", S_IRUSR, root, host, &dw_mci_regs_fops); if (!node) goto err; node = debugfs_create_file("req", S_IRUSR, root, slot, &dw_mci_req_fops); if (!node) goto err; node = debugfs_create_u32("state", S_IRUSR, root, (u32 *)&host->state); if (!node) goto err; node = debugfs_create_x32("pending_events", S_IRUSR, root, (u32 *)&host->pending_events); if (!node) goto err; node = debugfs_create_x32("completed_events", S_IRUSR, root, (u32 *)&host->completed_events); if (!node) goto err; return; err: dev_err(&mmc->class_dev, "failed to initialize debugfs for slot\n"); } #endif /* defined(CONFIG_DEBUG_FS) */ static bool dw_mci_ctrl_reset(struct dw_mci *host, u32 reset) { u32 ctrl; ctrl = mci_readl(host, CTRL); ctrl |= reset; mci_writel(host, CTRL, ctrl); /* wait till resets clear */ if (readl_poll_timeout_atomic(host->regs + SDMMC_CTRL, ctrl, !(ctrl & reset), 1, 500 * USEC_PER_MSEC)) { dev_err(host->dev, "Timeout resetting block (ctrl reset %#x)\n", ctrl & reset); return false; } return true; } static void dw_mci_wait_while_busy(struct dw_mci *host, u32 cmd_flags) { u32 status; /* * Databook says that before issuing a new data transfer command * we need to check to see if the card is busy. Data transfer commands * all have SDMMC_CMD_PRV_DAT_WAIT set, so we'll key off that. * * ...also allow sending for SDMMC_CMD_VOLT_SWITCH where busy is * expected. */ if ((cmd_flags & SDMMC_CMD_PRV_DAT_WAIT) && !(cmd_flags & SDMMC_CMD_VOLT_SWITCH)) { if (readl_poll_timeout_atomic(host->regs + SDMMC_STATUS, status, !(status & SDMMC_STATUS_BUSY), 10, 500 * USEC_PER_MSEC)) dev_err(host->dev, "Busy; trying anyway\n"); } } static void mci_send_cmd(struct dw_mci_slot *slot, u32 cmd, u32 arg) { struct dw_mci *host = slot->host; unsigned int cmd_status = 0; mci_writel(host, CMDARG, arg); wmb(); /* drain writebuffer */ dw_mci_wait_while_busy(host, cmd); mci_writel(host, CMD, SDMMC_CMD_START | cmd); if (readl_poll_timeout_atomic(host->regs + SDMMC_CMD, cmd_status, !(cmd_status & SDMMC_CMD_START), 1, 500 * USEC_PER_MSEC)) dev_err(&slot->mmc->class_dev, "Timeout sending command (cmd %#x arg %#x status %#x)\n", cmd, arg, cmd_status); } static u32 dw_mci_prepare_command(struct mmc_host *mmc, struct mmc_command *cmd) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; u32 cmdr; cmd->error = -EINPROGRESS; cmdr = cmd->opcode; if (cmd->opcode == MMC_STOP_TRANSMISSION || cmd->opcode == MMC_GO_IDLE_STATE || cmd->opcode == MMC_GO_INACTIVE_STATE || (cmd->opcode == SD_IO_RW_DIRECT && ((cmd->arg >> 9) & 0x1FFFF) == SDIO_CCCR_ABORT)) cmdr |= SDMMC_CMD_STOP; else if (cmd->opcode != MMC_SEND_STATUS && cmd->data) cmdr |= SDMMC_CMD_PRV_DAT_WAIT; if (cmd->opcode == SD_SWITCH_VOLTAGE) { u32 clk_en_a; /* Special bit makes CMD11 not die */ cmdr |= SDMMC_CMD_VOLT_SWITCH; /* Change state to continue to handle CMD11 weirdness */ WARN_ON(slot->host->state != STATE_SENDING_CMD); slot->host->state = STATE_SENDING_CMD11; /* * We need to disable low power mode (automatic clock stop) * while doing voltage switch so we don't confuse the card, * since stopping the clock is a specific part of the UHS * voltage change dance. * * Note that low power mode (SDMMC_CLKEN_LOW_PWR) will be * unconditionally turned back on in dw_mci_setup_bus() if it's * ever called with a non-zero clock. That shouldn't happen * until the voltage change is all done. */ clk_en_a = mci_readl(host, CLKENA); clk_en_a &= ~(SDMMC_CLKEN_LOW_PWR << slot->id); mci_writel(host, CLKENA, clk_en_a); mci_send_cmd(slot, SDMMC_CMD_UPD_CLK | SDMMC_CMD_PRV_DAT_WAIT, 0); } if (cmd->flags & MMC_RSP_PRESENT) { /* We expect a response, so set this bit */ cmdr |= SDMMC_CMD_RESP_EXP; if (cmd->flags & MMC_RSP_136) cmdr |= SDMMC_CMD_RESP_LONG; } if (cmd->flags & MMC_RSP_CRC) cmdr |= SDMMC_CMD_RESP_CRC; if (cmd->data) { cmdr |= SDMMC_CMD_DAT_EXP; if (cmd->data->flags & MMC_DATA_WRITE) cmdr |= SDMMC_CMD_DAT_WR; } if (!test_bit(DW_MMC_CARD_NO_USE_HOLD, &slot->flags)) cmdr |= SDMMC_CMD_USE_HOLD_REG; return cmdr; } static u32 dw_mci_prep_stop_abort(struct dw_mci *host, struct mmc_command *cmd) { struct mmc_command *stop; u32 cmdr; if (!cmd->data) return 0; stop = &host->stop_abort; cmdr = cmd->opcode; memset(stop, 0, sizeof(struct mmc_command)); if (cmdr == MMC_READ_SINGLE_BLOCK || cmdr == MMC_READ_MULTIPLE_BLOCK || cmdr == MMC_WRITE_BLOCK || cmdr == MMC_WRITE_MULTIPLE_BLOCK || cmdr == MMC_SEND_TUNING_BLOCK || cmdr == MMC_SEND_TUNING_BLOCK_HS200) { stop->opcode = MMC_STOP_TRANSMISSION; stop->arg = 0; stop->flags = MMC_RSP_R1B | MMC_CMD_AC; } else if (cmdr == SD_IO_RW_EXTENDED) { stop->opcode = SD_IO_RW_DIRECT; stop->arg |= (1 << 31) | (0 << 28) | (SDIO_CCCR_ABORT << 9) | ((cmd->arg >> 28) & 0x7); stop->flags = MMC_RSP_SPI_R5 | MMC_RSP_R5 | MMC_CMD_AC; } else { return 0; } cmdr = stop->opcode | SDMMC_CMD_STOP | SDMMC_CMD_RESP_CRC | SDMMC_CMD_RESP_EXP; if (!test_bit(DW_MMC_CARD_NO_USE_HOLD, &host->slot->flags)) cmdr |= SDMMC_CMD_USE_HOLD_REG; return cmdr; } static inline void dw_mci_set_cto(struct dw_mci *host) { unsigned int cto_clks; unsigned int cto_div; unsigned int cto_ms; unsigned long irqflags; cto_clks = mci_readl(host, TMOUT) & 0xff; cto_div = (mci_readl(host, CLKDIV) & 0xff) * 2; if (cto_div == 0) cto_div = 1; cto_ms = DIV_ROUND_UP_ULL((u64)MSEC_PER_SEC * cto_clks * cto_div, host->bus_hz); /* add a bit spare time */ cto_ms += 10; /* * The durations we're working with are fairly short so we have to be * extra careful about synchronization here. Specifically in hardware a * command timeout is _at most_ 5.1 ms, so that means we expect an * interrupt (either command done or timeout) to come rather quickly * after the mci_writel. ...but just in case we have a long interrupt * latency let's add a bit of paranoia. * * In general we'll assume that at least an interrupt will be asserted * in hardware by the time the cto_timer runs. ...and if it hasn't * been asserted in hardware by that time then we'll assume it'll never * come. */ spin_lock_irqsave(&host->irq_lock, irqflags); if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) mod_timer(&host->cto_timer, jiffies + msecs_to_jiffies(cto_ms) + 1); spin_unlock_irqrestore(&host->irq_lock, irqflags); } static void dw_mci_start_command(struct dw_mci *host, struct mmc_command *cmd, u32 cmd_flags) { host->cmd = cmd; dev_vdbg(host->dev, "start command: ARGR=0x%08x CMDR=0x%08x\n", cmd->arg, cmd_flags); mci_writel(host, CMDARG, cmd->arg); wmb(); /* drain writebuffer */ dw_mci_wait_while_busy(host, cmd_flags); mci_writel(host, CMD, cmd_flags | SDMMC_CMD_START); /* response expected command only */ if (cmd_flags & SDMMC_CMD_RESP_EXP) dw_mci_set_cto(host); } static inline void send_stop_abort(struct dw_mci *host, struct mmc_data *data) { struct mmc_command *stop = &host->stop_abort; dw_mci_start_command(host, stop, host->stop_cmdr); } /* DMA interface functions */ static void dw_mci_stop_dma(struct dw_mci *host) { if (host->using_dma) { host->dma_ops->stop(host); host->dma_ops->cleanup(host); } /* Data transfer was stopped by the interrupt handler */ set_bit(EVENT_XFER_COMPLETE, &host->pending_events); } static void dw_mci_dma_cleanup(struct dw_mci *host) { struct mmc_data *data = host->data; if (data && data->host_cookie == COOKIE_MAPPED) { dma_unmap_sg(host->dev, data->sg, data->sg_len, mmc_get_dma_dir(data)); data->host_cookie = COOKIE_UNMAPPED; } } static void dw_mci_idmac_reset(struct dw_mci *host) { u32 bmod = mci_readl(host, BMOD); /* Software reset of DMA */ bmod |= SDMMC_IDMAC_SWRESET; mci_writel(host, BMOD, bmod); } static void dw_mci_idmac_stop_dma(struct dw_mci *host) { u32 temp; /* Disable and reset the IDMAC interface */ temp = mci_readl(host, CTRL); temp &= ~SDMMC_CTRL_USE_IDMAC; temp |= SDMMC_CTRL_DMA_RESET; mci_writel(host, CTRL, temp); /* Stop the IDMAC running */ temp = mci_readl(host, BMOD); temp &= ~(SDMMC_IDMAC_ENABLE | SDMMC_IDMAC_FB); temp |= SDMMC_IDMAC_SWRESET; mci_writel(host, BMOD, temp); } static void dw_mci_dmac_complete_dma(void *arg) { struct dw_mci *host = arg; struct mmc_data *data = host->data; dev_vdbg(host->dev, "DMA complete\n"); if ((host->use_dma == TRANS_MODE_EDMAC) && data && (data->flags & MMC_DATA_READ)) /* Invalidate cache after read */ dma_sync_sg_for_cpu(mmc_dev(host->slot->mmc), data->sg, data->sg_len, DMA_FROM_DEVICE); host->dma_ops->cleanup(host); /* * If the card was removed, data will be NULL. No point in trying to * send the stop command or waiting for NBUSY in this case. */ if (data) { set_bit(EVENT_XFER_COMPLETE, &host->pending_events); tasklet_schedule(&host->tasklet); } } static int dw_mci_idmac_init(struct dw_mci *host) { int i; if (host->dma_64bit_address == 1) { struct idmac_desc_64addr *p; /* Number of descriptors in the ring buffer */ host->ring_size = DESC_RING_BUF_SZ / sizeof(struct idmac_desc_64addr); /* Forward link the descriptor list */ for (i = 0, p = host->sg_cpu; i < host->ring_size - 1; i++, p++) { p->des6 = (host->sg_dma + (sizeof(struct idmac_desc_64addr) * (i + 1))) & 0xffffffff; p->des7 = (u64)(host->sg_dma + (sizeof(struct idmac_desc_64addr) * (i + 1))) >> 32; /* Initialize reserved and buffer size fields to "0" */ p->des0 = 0; p->des1 = 0; p->des2 = 0; p->des3 = 0; } /* Set the last descriptor as the end-of-ring descriptor */ p->des6 = host->sg_dma & 0xffffffff; p->des7 = (u64)host->sg_dma >> 32; p->des0 = IDMAC_DES0_ER; } else { struct idmac_desc *p; /* Number of descriptors in the ring buffer */ host->ring_size = DESC_RING_BUF_SZ / sizeof(struct idmac_desc); /* Forward link the descriptor list */ for (i = 0, p = host->sg_cpu; i < host->ring_size - 1; i++, p++) { p->des3 = cpu_to_le32(host->sg_dma + (sizeof(struct idmac_desc) * (i + 1))); p->des0 = 0; p->des1 = 0; } /* Set the last descriptor as the end-of-ring descriptor */ p->des3 = cpu_to_le32(host->sg_dma); p->des0 = cpu_to_le32(IDMAC_DES0_ER); } dw_mci_idmac_reset(host); if (host->dma_64bit_address == 1) { /* Mask out interrupts - get Tx & Rx complete only */ mci_writel(host, IDSTS64, IDMAC_INT_CLR); mci_writel(host, IDINTEN64, SDMMC_IDMAC_INT_NI | SDMMC_IDMAC_INT_RI | SDMMC_IDMAC_INT_TI); /* Set the descriptor base address */ mci_writel(host, DBADDRL, host->sg_dma & 0xffffffff); mci_writel(host, DBADDRU, (u64)host->sg_dma >> 32); } else { /* Mask out interrupts - get Tx & Rx complete only */ mci_writel(host, IDSTS, IDMAC_INT_CLR); mci_writel(host, IDINTEN, SDMMC_IDMAC_INT_NI | SDMMC_IDMAC_INT_RI | SDMMC_IDMAC_INT_TI); /* Set the descriptor base address */ mci_writel(host, DBADDR, host->sg_dma); } return 0; } static inline int dw_mci_prepare_desc64(struct dw_mci *host, struct mmc_data *data, unsigned int sg_len) { unsigned int desc_len; struct idmac_desc_64addr *desc_first, *desc_last, *desc; u32 val; int i; desc_first = desc_last = desc = host->sg_cpu; for (i = 0; i < sg_len; i++) { unsigned int length = sg_dma_len(&data->sg[i]); u64 mem_addr = sg_dma_address(&data->sg[i]); for ( ; length ; desc++) { desc_len = (length <= DW_MCI_DESC_DATA_LENGTH) ? length : DW_MCI_DESC_DATA_LENGTH; length -= desc_len; /* * Wait for the former clear OWN bit operation * of IDMAC to make sure that this descriptor * isn't still owned by IDMAC as IDMAC's write * ops and CPU's read ops are asynchronous. */ if (readl_poll_timeout_atomic(&desc->des0, val, !(val & IDMAC_DES0_OWN), 10, 100 * USEC_PER_MSEC)) goto err_own_bit; /* * Set the OWN bit and disable interrupts * for this descriptor */ desc->des0 = IDMAC_DES0_OWN | IDMAC_DES0_DIC | IDMAC_DES0_CH; /* Buffer length */ IDMAC_64ADDR_SET_BUFFER1_SIZE(desc, desc_len); /* Physical address to DMA to/from */ desc->des4 = mem_addr & 0xffffffff; desc->des5 = mem_addr >> 32; /* Update physical address for the next desc */ mem_addr += desc_len; /* Save pointer to the last descriptor */ desc_last = desc; } } /* Set first descriptor */ desc_first->des0 |= IDMAC_DES0_FD; /* Set last descriptor */ desc_last->des0 &= ~(IDMAC_DES0_CH | IDMAC_DES0_DIC); desc_last->des0 |= IDMAC_DES0_LD; return 0; err_own_bit: /* restore the descriptor chain as it's polluted */ dev_dbg(host->dev, "descriptor is still owned by IDMAC.\n"); memset(host->sg_cpu, 0, DESC_RING_BUF_SZ); dw_mci_idmac_init(host); return -EINVAL; } static inline int dw_mci_prepare_desc32(struct dw_mci *host, struct mmc_data *data, unsigned int sg_len) { unsigned int desc_len; struct idmac_desc *desc_first, *desc_last, *desc; u32 val; int i; desc_first = desc_last = desc = host->sg_cpu; for (i = 0; i < sg_len; i++) { unsigned int length = sg_dma_len(&data->sg[i]); u32 mem_addr = sg_dma_address(&data->sg[i]); for ( ; length ; desc++) { desc_len = (length <= DW_MCI_DESC_DATA_LENGTH) ? length : DW_MCI_DESC_DATA_LENGTH; length -= desc_len; /* * Wait for the former clear OWN bit operation * of IDMAC to make sure that this descriptor * isn't still owned by IDMAC as IDMAC's write * ops and CPU's read ops are asynchronous. */ if (readl_poll_timeout_atomic(&desc->des0, val, IDMAC_OWN_CLR64(val), 10, 100 * USEC_PER_MSEC)) goto err_own_bit; /* * Set the OWN bit and disable interrupts * for this descriptor */ desc->des0 = cpu_to_le32(IDMAC_DES0_OWN | IDMAC_DES0_DIC | IDMAC_DES0_CH); /* Buffer length */ IDMAC_SET_BUFFER1_SIZE(desc, desc_len); /* Physical address to DMA to/from */ desc->des2 = cpu_to_le32(mem_addr); /* Update physical address for the next desc */ mem_addr += desc_len; /* Save pointer to the last descriptor */ desc_last = desc; } } /* Set first descriptor */ desc_first->des0 |= cpu_to_le32(IDMAC_DES0_FD); /* Set last descriptor */ desc_last->des0 &= cpu_to_le32(~(IDMAC_DES0_CH | IDMAC_DES0_DIC)); desc_last->des0 |= cpu_to_le32(IDMAC_DES0_LD); return 0; err_own_bit: /* restore the descriptor chain as it's polluted */ dev_dbg(host->dev, "descriptor is still owned by IDMAC.\n"); memset(host->sg_cpu, 0, DESC_RING_BUF_SZ); dw_mci_idmac_init(host); return -EINVAL; } static int dw_mci_idmac_start_dma(struct dw_mci *host, unsigned int sg_len) { u32 temp; int ret; if (host->dma_64bit_address == 1) ret = dw_mci_prepare_desc64(host, host->data, sg_len); else ret = dw_mci_prepare_desc32(host, host->data, sg_len); if (ret) goto out; /* drain writebuffer */ wmb(); /* Make sure to reset DMA in case we did PIO before this */ dw_mci_ctrl_reset(host, SDMMC_CTRL_DMA_RESET); dw_mci_idmac_reset(host); /* Select IDMAC interface */ temp = mci_readl(host, CTRL); temp |= SDMMC_CTRL_USE_IDMAC; mci_writel(host, CTRL, temp); /* drain writebuffer */ wmb(); /* Enable the IDMAC */ temp = mci_readl(host, BMOD); temp |= SDMMC_IDMAC_ENABLE | SDMMC_IDMAC_FB; mci_writel(host, BMOD, temp); /* Start it running */ mci_writel(host, PLDMND, 1); out: return ret; } static const struct dw_mci_dma_ops dw_mci_idmac_ops = { .init = dw_mci_idmac_init, .start = dw_mci_idmac_start_dma, .stop = dw_mci_idmac_stop_dma, .complete = dw_mci_dmac_complete_dma, .cleanup = dw_mci_dma_cleanup, }; static void dw_mci_edmac_stop_dma(struct dw_mci *host) { dmaengine_terminate_async(host->dms->ch); } static int dw_mci_edmac_start_dma(struct dw_mci *host, unsigned int sg_len) { struct dma_slave_config cfg; struct dma_async_tx_descriptor *desc = NULL; struct scatterlist *sgl = host->data->sg; static const u32 mszs[] = {1, 4, 8, 16, 32, 64, 128, 256}; u32 sg_elems = host->data->sg_len; u32 fifoth_val; u32 fifo_offset = host->fifo_reg - host->regs; int ret = 0; /* Set external dma config: burst size, burst width */ cfg.dst_addr = host->phy_regs + fifo_offset; cfg.src_addr = cfg.dst_addr; cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; /* Match burst msize with external dma config */ fifoth_val = mci_readl(host, FIFOTH); cfg.dst_maxburst = mszs[(fifoth_val >> 28) & 0x7]; cfg.src_maxburst = cfg.dst_maxburst; if (host->data->flags & MMC_DATA_WRITE) cfg.direction = DMA_MEM_TO_DEV; else cfg.direction = DMA_DEV_TO_MEM; ret = dmaengine_slave_config(host->dms->ch, &cfg); if (ret) { dev_err(host->dev, "Failed to config edmac.\n"); return -EBUSY; } desc = dmaengine_prep_slave_sg(host->dms->ch, sgl, sg_len, cfg.direction, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!desc) { dev_err(host->dev, "Can't prepare slave sg.\n"); return -EBUSY; } /* Set dw_mci_dmac_complete_dma as callback */ desc->callback = dw_mci_dmac_complete_dma; desc->callback_param = (void *)host; dmaengine_submit(desc); /* Flush cache before write */ if (host->data->flags & MMC_DATA_WRITE) dma_sync_sg_for_device(mmc_dev(host->slot->mmc), sgl, sg_elems, DMA_TO_DEVICE); dma_async_issue_pending(host->dms->ch); return 0; } static int dw_mci_edmac_init(struct dw_mci *host) { /* Request external dma channel */ host->dms = kzalloc(sizeof(struct dw_mci_dma_slave), GFP_KERNEL); if (!host->dms) return -ENOMEM; host->dms->ch = dma_request_slave_channel(host->dev, "rx-tx"); if (!host->dms->ch) { dev_err(host->dev, "Failed to get external DMA channel.\n"); kfree(host->dms); host->dms = NULL; return -ENXIO; } return 0; } static void dw_mci_edmac_exit(struct dw_mci *host) { if (host->dms) { if (host->dms->ch) { dma_release_channel(host->dms->ch); host->dms->ch = NULL; } kfree(host->dms); host->dms = NULL; } } static const struct dw_mci_dma_ops dw_mci_edmac_ops = { .init = dw_mci_edmac_init, .exit = dw_mci_edmac_exit, .start = dw_mci_edmac_start_dma, .stop = dw_mci_edmac_stop_dma, .complete = dw_mci_dmac_complete_dma, .cleanup = dw_mci_dma_cleanup, }; static int dw_mci_pre_dma_transfer(struct dw_mci *host, struct mmc_data *data, int cookie) { struct scatterlist *sg; unsigned int i, sg_len; if (data->host_cookie == COOKIE_PRE_MAPPED) return data->sg_len; /* * We don't do DMA on "complex" transfers, i.e. with * non-word-aligned buffers or lengths. Also, we don't bother * with all the DMA setup overhead for short transfers. */ if (data->blocks * data->blksz < DW_MCI_DMA_THRESHOLD) return -EINVAL; if (data->blksz & 3) return -EINVAL; for_each_sg(data->sg, sg, data->sg_len, i) { if (sg->offset & 3 || sg->length & 3) return -EINVAL; } sg_len = dma_map_sg(host->dev, data->sg, data->sg_len, mmc_get_dma_dir(data)); if (sg_len == 0) return -EINVAL; data->host_cookie = cookie; return sg_len; } static void dw_mci_pre_req(struct mmc_host *mmc, struct mmc_request *mrq) { struct dw_mci_slot *slot = mmc_priv(mmc); struct mmc_data *data = mrq->data; if (!slot->host->use_dma || !data) return; /* This data might be unmapped at this time */ data->host_cookie = COOKIE_UNMAPPED; if (dw_mci_pre_dma_transfer(slot->host, mrq->data, COOKIE_PRE_MAPPED) < 0) data->host_cookie = COOKIE_UNMAPPED; } static void dw_mci_post_req(struct mmc_host *mmc, struct mmc_request *mrq, int err) { struct dw_mci_slot *slot = mmc_priv(mmc); struct mmc_data *data = mrq->data; if (!slot->host->use_dma || !data) return; if (data->host_cookie != COOKIE_UNMAPPED) dma_unmap_sg(slot->host->dev, data->sg, data->sg_len, mmc_get_dma_dir(data)); data->host_cookie = COOKIE_UNMAPPED; } static int dw_mci_get_cd(struct mmc_host *mmc) { int present; struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; int gpio_cd = mmc_gpio_get_cd(mmc); /* Use platform get_cd function, else try onboard card detect */ if (((mmc->caps & MMC_CAP_NEEDS_POLL) || !mmc_card_is_removable(mmc))) { present = 1; if (!test_bit(DW_MMC_CARD_PRESENT, &slot->flags)) { if (mmc->caps & MMC_CAP_NEEDS_POLL) { dev_info(&mmc->class_dev, "card is polling.\n"); } else { dev_info(&mmc->class_dev, "card is non-removable.\n"); } set_bit(DW_MMC_CARD_PRESENT, &slot->flags); } return present; } else if (gpio_cd >= 0) present = gpio_cd; else present = (mci_readl(slot->host, CDETECT) & (1 << slot->id)) == 0 ? 1 : 0; spin_lock_bh(&host->lock); if (present && !test_and_set_bit(DW_MMC_CARD_PRESENT, &slot->flags)) dev_dbg(&mmc->class_dev, "card is present\n"); else if (!present && !test_and_clear_bit(DW_MMC_CARD_PRESENT, &slot->flags)) dev_dbg(&mmc->class_dev, "card is not present\n"); spin_unlock_bh(&host->lock); return present; } static void dw_mci_adjust_fifoth(struct dw_mci *host, struct mmc_data *data) { unsigned int blksz = data->blksz; static const u32 mszs[] = {1, 4, 8, 16, 32, 64, 128, 256}; u32 fifo_width = 1 << host->data_shift; u32 blksz_depth = blksz / fifo_width, fifoth_val; u32 msize = 0, rx_wmark = 1, tx_wmark, tx_wmark_invers; int idx = ARRAY_SIZE(mszs) - 1; /* pio should ship this scenario */ if (!host->use_dma) return; tx_wmark = (host->fifo_depth) / 2; tx_wmark_invers = host->fifo_depth - tx_wmark; /* * MSIZE is '1', * if blksz is not a multiple of the FIFO width */ if (blksz % fifo_width) goto done; do { if (!((blksz_depth % mszs[idx]) || (tx_wmark_invers % mszs[idx]))) { msize = idx; rx_wmark = mszs[idx] - 1; break; } } while (--idx > 0); /* * If idx is '0', it won't be tried * Thus, initial values are uesed */ done: fifoth_val = SDMMC_SET_FIFOTH(msize, rx_wmark, tx_wmark); mci_writel(host, FIFOTH, fifoth_val); } static void dw_mci_ctrl_thld(struct dw_mci *host, struct mmc_data *data) { unsigned int blksz = data->blksz; u32 blksz_depth, fifo_depth; u16 thld_size; u8 enable; /* * CDTHRCTL doesn't exist prior to 240A (in fact that register offset is * in the FIFO region, so we really shouldn't access it). */ if (host->verid < DW_MMC_240A || (host->verid < DW_MMC_280A && data->flags & MMC_DATA_WRITE)) return; /* * Card write Threshold is introduced since 2.80a * It's used when HS400 mode is enabled. */ if (data->flags & MMC_DATA_WRITE && !(host->timing != MMC_TIMING_MMC_HS400)) return; if (data->flags & MMC_DATA_WRITE) enable = SDMMC_CARD_WR_THR_EN; else enable = SDMMC_CARD_RD_THR_EN; if (host->timing != MMC_TIMING_MMC_HS200 && host->timing != MMC_TIMING_UHS_SDR104) goto disable; blksz_depth = blksz / (1 << host->data_shift); fifo_depth = host->fifo_depth; if (blksz_depth > fifo_depth) goto disable; /* * If (blksz_depth) >= (fifo_depth >> 1), should be 'thld_size <= blksz' * If (blksz_depth) < (fifo_depth >> 1), should be thld_size = blksz * Currently just choose blksz. */ thld_size = blksz; mci_writel(host, CDTHRCTL, SDMMC_SET_THLD(thld_size, enable)); return; disable: mci_writel(host, CDTHRCTL, 0); } static int dw_mci_submit_data_dma(struct dw_mci *host, struct mmc_data *data) { unsigned long irqflags; int sg_len; u32 temp; host->using_dma = 0; /* If we don't have a channel, we can't do DMA */ if (!host->use_dma) return -ENODEV; sg_len = dw_mci_pre_dma_transfer(host, data, COOKIE_MAPPED); if (sg_len < 0) { host->dma_ops->stop(host); return sg_len; } host->using_dma = 1; if (host->use_dma == TRANS_MODE_IDMAC) dev_vdbg(host->dev, "sd sg_cpu: %#lx sg_dma: %#lx sg_len: %d\n", (unsigned long)host->sg_cpu, (unsigned long)host->sg_dma, sg_len); /* * Decide the MSIZE and RX/TX Watermark. * If current block size is same with previous size, * no need to update fifoth. */ if (host->prev_blksz != data->blksz) dw_mci_adjust_fifoth(host, data); /* Enable the DMA interface */ temp = mci_readl(host, CTRL); temp |= SDMMC_CTRL_DMA_ENABLE; mci_writel(host, CTRL, temp); /* Disable RX/TX IRQs, let DMA handle it */ spin_lock_irqsave(&host->irq_lock, irqflags); temp = mci_readl(host, INTMASK); temp &= ~(SDMMC_INT_RXDR | SDMMC_INT_TXDR); mci_writel(host, INTMASK, temp); spin_unlock_irqrestore(&host->irq_lock, irqflags); if (host->dma_ops->start(host, sg_len)) { host->dma_ops->stop(host); /* We can't do DMA, try PIO for this one */ dev_dbg(host->dev, "%s: fall back to PIO mode for current transfer\n", __func__); return -ENODEV; } return 0; } static void dw_mci_submit_data(struct dw_mci *host, struct mmc_data *data) { unsigned long irqflags; int flags = SG_MITER_ATOMIC; u32 temp; data->error = -EINPROGRESS; WARN_ON(host->data); host->sg = NULL; host->data = data; if (data->flags & MMC_DATA_READ) host->dir_status = DW_MCI_RECV_STATUS; else host->dir_status = DW_MCI_SEND_STATUS; dw_mci_ctrl_thld(host, data); if (dw_mci_submit_data_dma(host, data)) { if (host->data->flags & MMC_DATA_READ) flags |= SG_MITER_TO_SG; else flags |= SG_MITER_FROM_SG; sg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags); host->sg = data->sg; host->part_buf_start = 0; host->part_buf_count = 0; mci_writel(host, RINTSTS, SDMMC_INT_TXDR | SDMMC_INT_RXDR); spin_lock_irqsave(&host->irq_lock, irqflags); temp = mci_readl(host, INTMASK); temp |= SDMMC_INT_TXDR | SDMMC_INT_RXDR; mci_writel(host, INTMASK, temp); spin_unlock_irqrestore(&host->irq_lock, irqflags); temp = mci_readl(host, CTRL); temp &= ~SDMMC_CTRL_DMA_ENABLE; mci_writel(host, CTRL, temp); /* * Use the initial fifoth_val for PIO mode. If wm_algined * is set, we set watermark same as data size. * If next issued data may be transfered by DMA mode, * prev_blksz should be invalidated. */ if (host->wm_aligned) dw_mci_adjust_fifoth(host, data); else mci_writel(host, FIFOTH, host->fifoth_val); host->prev_blksz = 0; } else { /* * Keep the current block size. * It will be used to decide whether to update * fifoth register next time. */ host->prev_blksz = data->blksz; } } static void dw_mci_setup_bus(struct dw_mci_slot *slot, bool force_clkinit) { struct dw_mci *host = slot->host; unsigned int clock = slot->clock; u32 div; u32 clk_en_a; u32 sdmmc_cmd_bits = SDMMC_CMD_UPD_CLK | SDMMC_CMD_PRV_DAT_WAIT; /* We must continue to set bit 28 in CMD until the change is complete */ if (host->state == STATE_WAITING_CMD11_DONE) sdmmc_cmd_bits |= SDMMC_CMD_VOLT_SWITCH; if (!clock) { mci_writel(host, CLKENA, 0); mci_send_cmd(slot, sdmmc_cmd_bits, 0); } else if (clock != host->current_speed || force_clkinit) { div = host->bus_hz / clock; if (host->bus_hz % clock && host->bus_hz > clock) /* * move the + 1 after the divide to prevent * over-clocking the card. */ div += 1; div = (host->bus_hz != clock) ? DIV_ROUND_UP(div, 2) : 0; if ((clock != slot->__clk_old && !test_bit(DW_MMC_CARD_NEEDS_POLL, &slot->flags)) || force_clkinit) { /* Silent the verbose log if calling from PM context */ if (!force_clkinit) dev_info(&slot->mmc->class_dev, "Bus speed (slot %d) = %dHz (slot req %dHz, actual %dHZ div = %d)\n", slot->id, host->bus_hz, clock, div ? ((host->bus_hz / div) >> 1) : host->bus_hz, div); /* * If card is polling, display the message only * one time at boot time. */ if (slot->mmc->caps & MMC_CAP_NEEDS_POLL && slot->mmc->f_min == clock) set_bit(DW_MMC_CARD_NEEDS_POLL, &slot->flags); } /* disable clock */ mci_writel(host, CLKENA, 0); mci_writel(host, CLKSRC, 0); /* inform CIU */ mci_send_cmd(slot, sdmmc_cmd_bits, 0); /* set clock to desired speed */ mci_writel(host, CLKDIV, div); /* inform CIU */ mci_send_cmd(slot, sdmmc_cmd_bits, 0); /* enable clock; only low power if no SDIO */ clk_en_a = SDMMC_CLKEN_ENABLE << slot->id; if (!test_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags)) clk_en_a |= SDMMC_CLKEN_LOW_PWR << slot->id; mci_writel(host, CLKENA, clk_en_a); /* inform CIU */ mci_send_cmd(slot, sdmmc_cmd_bits, 0); /* keep the last clock value that was requested from core */ slot->__clk_old = clock; } host->current_speed = clock; /* Set the current slot bus width */ mci_writel(host, CTYPE, (slot->ctype << slot->id)); } static void __dw_mci_start_request(struct dw_mci *host, struct dw_mci_slot *slot, struct mmc_command *cmd) { struct mmc_request *mrq; struct mmc_data *data; u32 cmdflags; mrq = slot->mrq; host->mrq = mrq; host->pending_events = 0; host->completed_events = 0; host->cmd_status = 0; host->data_status = 0; host->dir_status = 0; data = cmd->data; if (data) { mci_writel(host, TMOUT, 0xFFFFFFFF); mci_writel(host, BYTCNT, data->blksz*data->blocks); mci_writel(host, BLKSIZ, data->blksz); } cmdflags = dw_mci_prepare_command(slot->mmc, cmd); /* this is the first command, send the initialization clock */ if (test_and_clear_bit(DW_MMC_CARD_NEED_INIT, &slot->flags)) cmdflags |= SDMMC_CMD_INIT; if (data) { dw_mci_submit_data(host, data); wmb(); /* drain writebuffer */ } dw_mci_start_command(host, cmd, cmdflags); if (cmd->opcode == SD_SWITCH_VOLTAGE) { unsigned long irqflags; /* * Databook says to fail after 2ms w/ no response, but evidence * shows that sometimes the cmd11 interrupt takes over 130ms. * We'll set to 500ms, plus an extra jiffy just in case jiffies * is just about to roll over. * * We do this whole thing under spinlock and only if the * command hasn't already completed (indicating the the irq * already ran so we don't want the timeout). */ spin_lock_irqsave(&host->irq_lock, irqflags); if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) mod_timer(&host->cmd11_timer, jiffies + msecs_to_jiffies(500) + 1); spin_unlock_irqrestore(&host->irq_lock, irqflags); } host->stop_cmdr = dw_mci_prep_stop_abort(host, cmd); } static void dw_mci_start_request(struct dw_mci *host, struct dw_mci_slot *slot) { struct mmc_request *mrq = slot->mrq; struct mmc_command *cmd; cmd = mrq->sbc ? mrq->sbc : mrq->cmd; __dw_mci_start_request(host, slot, cmd); } /* must be called with host->lock held */ static void dw_mci_queue_request(struct dw_mci *host, struct dw_mci_slot *slot, struct mmc_request *mrq) { dev_vdbg(&slot->mmc->class_dev, "queue request: state=%d\n", host->state); slot->mrq = mrq; if (host->state == STATE_WAITING_CMD11_DONE) { dev_warn(&slot->mmc->class_dev, "Voltage change didn't complete\n"); /* * this case isn't expected to happen, so we can * either crash here or just try to continue on * in the closest possible state */ host->state = STATE_IDLE; } if (host->state == STATE_IDLE) { host->state = STATE_SENDING_CMD; dw_mci_start_request(host, slot); } else { list_add_tail(&slot->queue_node, &host->queue); } } static void dw_mci_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; WARN_ON(slot->mrq); /* * The check for card presence and queueing of the request must be * atomic, otherwise the card could be removed in between and the * request wouldn't fail until another card was inserted. */ if (!dw_mci_get_cd(mmc)) { mrq->cmd->error = -ENOMEDIUM; mmc_request_done(mmc, mrq); return; } spin_lock_bh(&host->lock); dw_mci_queue_request(host, slot, mrq); spin_unlock_bh(&host->lock); } static void dw_mci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct dw_mci_slot *slot = mmc_priv(mmc); const struct dw_mci_drv_data *drv_data = slot->host->drv_data; u32 regs; int ret; switch (ios->bus_width) { case MMC_BUS_WIDTH_4: slot->ctype = SDMMC_CTYPE_4BIT; break; case MMC_BUS_WIDTH_8: slot->ctype = SDMMC_CTYPE_8BIT; break; default: /* set default 1 bit mode */ slot->ctype = SDMMC_CTYPE_1BIT; } regs = mci_readl(slot->host, UHS_REG); /* DDR mode set */ if (ios->timing == MMC_TIMING_MMC_DDR52 || ios->timing == MMC_TIMING_UHS_DDR50 || ios->timing == MMC_TIMING_MMC_HS400) regs |= ((0x1 << slot->id) << 16); else regs &= ~((0x1 << slot->id) << 16); mci_writel(slot->host, UHS_REG, regs); slot->host->timing = ios->timing; /* * Use mirror of ios->clock to prevent race with mmc * core ios update when finding the minimum. */ slot->clock = ios->clock; if (drv_data && drv_data->set_ios) drv_data->set_ios(slot->host, ios); switch (ios->power_mode) { case MMC_POWER_UP: if (!IS_ERR(mmc->supply.vmmc)) { ret = mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, ios->vdd); if (ret) { dev_err(slot->host->dev, "failed to enable vmmc regulator\n"); /*return, if failed turn on vmmc*/ return; } } set_bit(DW_MMC_CARD_NEED_INIT, &slot->flags); regs = mci_readl(slot->host, PWREN); regs |= (1 << slot->id); mci_writel(slot->host, PWREN, regs); break; case MMC_POWER_ON: if (!slot->host->vqmmc_enabled) { if (!IS_ERR(mmc->supply.vqmmc)) { ret = regulator_enable(mmc->supply.vqmmc); if (ret < 0) dev_err(slot->host->dev, "failed to enable vqmmc\n"); else slot->host->vqmmc_enabled = true; } else { /* Keep track so we don't reset again */ slot->host->vqmmc_enabled = true; } /* Reset our state machine after powering on */ dw_mci_ctrl_reset(slot->host, SDMMC_CTRL_ALL_RESET_FLAGS); } /* Adjust clock / bus width after power is up */ dw_mci_setup_bus(slot, false); break; case MMC_POWER_OFF: /* Turn clock off before power goes down */ dw_mci_setup_bus(slot, false); if (!IS_ERR(mmc->supply.vmmc)) mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0); if (!IS_ERR(mmc->supply.vqmmc) && slot->host->vqmmc_enabled) regulator_disable(mmc->supply.vqmmc); slot->host->vqmmc_enabled = false; regs = mci_readl(slot->host, PWREN); regs &= ~(1 << slot->id); mci_writel(slot->host, PWREN, regs); break; default: break; } if (slot->host->state == STATE_WAITING_CMD11_DONE && ios->clock != 0) slot->host->state = STATE_IDLE; } static int dw_mci_card_busy(struct mmc_host *mmc) { struct dw_mci_slot *slot = mmc_priv(mmc); u32 status; /* * Check the busy bit which is low when DAT[3:0] * (the data lines) are 0000 */ status = mci_readl(slot->host, STATUS); return !!(status & SDMMC_STATUS_BUSY); } static int dw_mci_switch_voltage(struct mmc_host *mmc, struct mmc_ios *ios) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; const struct dw_mci_drv_data *drv_data = host->drv_data; u32 uhs; u32 v18 = SDMMC_UHS_18V << slot->id; int ret; if (drv_data && drv_data->switch_voltage) return drv_data->switch_voltage(mmc, ios); /* * Program the voltage. Note that some instances of dw_mmc may use * the UHS_REG for this. For other instances (like exynos) the UHS_REG * does no harm but you need to set the regulator directly. Try both. */ uhs = mci_readl(host, UHS_REG); if (ios->signal_voltage == MMC_SIGNAL_VOLTAGE_330) uhs &= ~v18; else uhs |= v18; if (!IS_ERR(mmc->supply.vqmmc)) { ret = mmc_regulator_set_vqmmc(mmc, ios); if (ret) { dev_dbg(&mmc->class_dev, "Regulator set error %d - %s V\n", ret, uhs & v18 ? "1.8" : "3.3"); return ret; } } mci_writel(host, UHS_REG, uhs); return 0; } static int dw_mci_get_ro(struct mmc_host *mmc) { int read_only; struct dw_mci_slot *slot = mmc_priv(mmc); int gpio_ro = mmc_gpio_get_ro(mmc); /* Use platform get_ro function, else try on board write protect */ if (gpio_ro >= 0) read_only = gpio_ro; else read_only = mci_readl(slot->host, WRTPRT) & (1 << slot->id) ? 1 : 0; dev_dbg(&mmc->class_dev, "card is %s\n", read_only ? "read-only" : "read-write"); return read_only; } static void dw_mci_hw_reset(struct mmc_host *mmc) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; int reset; if (host->use_dma == TRANS_MODE_IDMAC) dw_mci_idmac_reset(host); if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_DMA_RESET | SDMMC_CTRL_FIFO_RESET)) return; /* * According to eMMC spec, card reset procedure: * tRstW >= 1us: RST_n pulse width * tRSCA >= 200us: RST_n to Command time * tRSTH >= 1us: RST_n high period */ reset = mci_readl(host, RST_N); reset &= ~(SDMMC_RST_HWACTIVE << slot->id); mci_writel(host, RST_N, reset); usleep_range(1, 2); reset |= SDMMC_RST_HWACTIVE << slot->id; mci_writel(host, RST_N, reset); usleep_range(200, 300); } static void dw_mci_init_card(struct mmc_host *mmc, struct mmc_card *card) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; /* * Low power mode will stop the card clock when idle. According to the * description of the CLKENA register we should disable low power mode * for SDIO cards if we need SDIO interrupts to work. */ if (mmc->caps & MMC_CAP_SDIO_IRQ) { const u32 clken_low_pwr = SDMMC_CLKEN_LOW_PWR << slot->id; u32 clk_en_a_old; u32 clk_en_a; clk_en_a_old = mci_readl(host, CLKENA); if (card->type == MMC_TYPE_SDIO || card->type == MMC_TYPE_SD_COMBO) { set_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags); clk_en_a = clk_en_a_old & ~clken_low_pwr; } else { clear_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags); clk_en_a = clk_en_a_old | clken_low_pwr; } if (clk_en_a != clk_en_a_old) { mci_writel(host, CLKENA, clk_en_a); mci_send_cmd(slot, SDMMC_CMD_UPD_CLK | SDMMC_CMD_PRV_DAT_WAIT, 0); } } } static void __dw_mci_enable_sdio_irq(struct dw_mci_slot *slot, int enb) { struct dw_mci *host = slot->host; unsigned long irqflags; u32 int_mask; spin_lock_irqsave(&host->irq_lock, irqflags); /* Enable/disable Slot Specific SDIO interrupt */ int_mask = mci_readl(host, INTMASK); if (enb) int_mask |= SDMMC_INT_SDIO(slot->sdio_id); else int_mask &= ~SDMMC_INT_SDIO(slot->sdio_id); mci_writel(host, INTMASK, int_mask); spin_unlock_irqrestore(&host->irq_lock, irqflags); } static void dw_mci_enable_sdio_irq(struct mmc_host *mmc, int enb) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; __dw_mci_enable_sdio_irq(slot, enb); /* Avoid runtime suspending the device when SDIO IRQ is enabled */ if (enb) pm_runtime_get_noresume(host->dev); else pm_runtime_put_noidle(host->dev); } static void dw_mci_ack_sdio_irq(struct mmc_host *mmc) { struct dw_mci_slot *slot = mmc_priv(mmc); __dw_mci_enable_sdio_irq(slot, 1); } static int dw_mci_execute_tuning(struct mmc_host *mmc, u32 opcode) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; const struct dw_mci_drv_data *drv_data = host->drv_data; int err = -EINVAL; if (drv_data && drv_data->execute_tuning) err = drv_data->execute_tuning(slot, opcode); return err; } static int dw_mci_prepare_hs400_tuning(struct mmc_host *mmc, struct mmc_ios *ios) { struct dw_mci_slot *slot = mmc_priv(mmc); struct dw_mci *host = slot->host; const struct dw_mci_drv_data *drv_data = host->drv_data; if (drv_data && drv_data->prepare_hs400_tuning) return drv_data->prepare_hs400_tuning(host, ios); return 0; } static bool dw_mci_reset(struct dw_mci *host) { u32 flags = SDMMC_CTRL_RESET | SDMMC_CTRL_FIFO_RESET; bool ret = false; u32 status = 0; /* * Resetting generates a block interrupt, hence setting * the scatter-gather pointer to NULL. */ if (host->sg) { sg_miter_stop(&host->sg_miter); host->sg = NULL; } if (host->use_dma) flags |= SDMMC_CTRL_DMA_RESET; if (dw_mci_ctrl_reset(host, flags)) { /* * In all cases we clear the RAWINTS * register to clear any interrupts. */ mci_writel(host, RINTSTS, 0xFFFFFFFF); if (!host->use_dma) { ret = true; goto ciu_out; } /* Wait for dma_req to be cleared */ if (readl_poll_timeout_atomic(host->regs + SDMMC_STATUS, status, !(status & SDMMC_STATUS_DMA_REQ), 1, 500 * USEC_PER_MSEC)) { dev_err(host->dev, "%s: Timeout waiting for dma_req to be cleared\n", __func__); goto ciu_out; } /* when using DMA next we reset the fifo again */ if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_FIFO_RESET)) goto ciu_out; } else { /* if the controller reset bit did clear, then set clock regs */ if (!(mci_readl(host, CTRL) & SDMMC_CTRL_RESET)) { dev_err(host->dev, "%s: fifo/dma reset bits didn't clear but ciu was reset, doing clock update\n", __func__); goto ciu_out; } } if (host->use_dma == TRANS_MODE_IDMAC) /* It is also required that we reinit idmac */ dw_mci_idmac_init(host); ret = true; ciu_out: /* After a CTRL reset we need to have CIU set clock registers */ mci_send_cmd(host->slot, SDMMC_CMD_UPD_CLK, 0); return ret; } static const struct mmc_host_ops dw_mci_ops = { .request = dw_mci_request, .pre_req = dw_mci_pre_req, .post_req = dw_mci_post_req, .set_ios = dw_mci_set_ios, .get_ro = dw_mci_get_ro, .get_cd = dw_mci_get_cd, .hw_reset = dw_mci_hw_reset, .enable_sdio_irq = dw_mci_enable_sdio_irq, .ack_sdio_irq = dw_mci_ack_sdio_irq, .execute_tuning = dw_mci_execute_tuning, .card_busy = dw_mci_card_busy, .start_signal_voltage_switch = dw_mci_switch_voltage, .init_card = dw_mci_init_card, .prepare_hs400_tuning = dw_mci_prepare_hs400_tuning, }; static void dw_mci_request_end(struct dw_mci *host, struct mmc_request *mrq) __releases(&host->lock) __acquires(&host->lock) { struct dw_mci_slot *slot; struct mmc_host *prev_mmc = host->slot->mmc; WARN_ON(host->cmd || host->data); host->slot->mrq = NULL; host->mrq = NULL; if (!list_empty(&host->queue)) { slot = list_entry(host->queue.next, struct dw_mci_slot, queue_node); list_del(&slot->queue_node); dev_vdbg(host->dev, "list not empty: %s is next\n", mmc_hostname(slot->mmc)); host->state = STATE_SENDING_CMD; dw_mci_start_request(host, slot); } else { dev_vdbg(host->dev, "list empty\n"); if (host->state == STATE_SENDING_CMD11) host->state = STATE_WAITING_CMD11_DONE; else host->state = STATE_IDLE; } spin_unlock(&host->lock); mmc_request_done(prev_mmc, mrq); spin_lock(&host->lock); } static int dw_mci_command_complete(struct dw_mci *host, struct mmc_command *cmd) { u32 status = host->cmd_status; host->cmd_status = 0; /* Read the response from the card (up to 16 bytes) */ if (cmd->flags & MMC_RSP_PRESENT) { if (cmd->flags & MMC_RSP_136) { cmd->resp[3] = mci_readl(host, RESP0); cmd->resp[2] = mci_readl(host, RESP1); cmd->resp[1] = mci_readl(host, RESP2); cmd->resp[0] = mci_readl(host, RESP3); } else { cmd->resp[0] = mci_readl(host, RESP0); cmd->resp[1] = 0; cmd->resp[2] = 0; cmd->resp[3] = 0; } } if (status & SDMMC_INT_RTO) cmd->error = -ETIMEDOUT; else if ((cmd->flags & MMC_RSP_CRC) && (status & SDMMC_INT_RCRC)) cmd->error = -EILSEQ; else if (status & SDMMC_INT_RESP_ERR) cmd->error = -EIO; else cmd->error = 0; return cmd->error; } static int dw_mci_data_complete(struct dw_mci *host, struct mmc_data *data) { u32 status = host->data_status; if (status & DW_MCI_DATA_ERROR_FLAGS) { if (status & SDMMC_INT_DRTO) { data->error = -ETIMEDOUT; } else if (status & SDMMC_INT_DCRC) { data->error = -EILSEQ; } else if (status & SDMMC_INT_EBE) { if (host->dir_status == DW_MCI_SEND_STATUS) { /* * No data CRC status was returned. * The number of bytes transferred * will be exaggerated in PIO mode. */ data->bytes_xfered = 0; data->error = -ETIMEDOUT; } else if (host->dir_status == DW_MCI_RECV_STATUS) { data->error = -EILSEQ; } } else { /* SDMMC_INT_SBE is included */ data->error = -EILSEQ; } dev_dbg(host->dev, "data error, status 0x%08x\n", status); /* * After an error, there may be data lingering * in the FIFO */ dw_mci_reset(host); } else { data->bytes_xfered = data->blocks * data->blksz; data->error = 0; } return data->error; } static void dw_mci_set_drto(struct dw_mci *host) { unsigned int drto_clks; unsigned int drto_div; unsigned int drto_ms; unsigned long irqflags; drto_clks = mci_readl(host, TMOUT) >> 8; drto_div = (mci_readl(host, CLKDIV) & 0xff) * 2; if (drto_div == 0) drto_div = 1; drto_ms = DIV_ROUND_UP_ULL((u64)MSEC_PER_SEC * drto_clks * drto_div, host->bus_hz); /* add a bit spare time */ drto_ms += 10; spin_lock_irqsave(&host->irq_lock, irqflags); if (!test_bit(EVENT_DATA_COMPLETE, &host->pending_events)) mod_timer(&host->dto_timer, jiffies + msecs_to_jiffies(drto_ms)); spin_unlock_irqrestore(&host->irq_lock, irqflags); } static bool dw_mci_clear_pending_cmd_complete(struct dw_mci *host) { if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) return false; /* * Really be certain that the timer has stopped. This is a bit of * paranoia and could only really happen if we had really bad * interrupt latency and the interrupt routine and timeout were * running concurrently so that the del_timer() in the interrupt * handler couldn't run. */ WARN_ON(del_timer_sync(&host->cto_timer)); clear_bit(EVENT_CMD_COMPLETE, &host->pending_events); return true; } static bool dw_mci_clear_pending_data_complete(struct dw_mci *host) { if (!test_bit(EVENT_DATA_COMPLETE, &host->pending_events)) return false; /* Extra paranoia just like dw_mci_clear_pending_cmd_complete() */ WARN_ON(del_timer_sync(&host->dto_timer)); clear_bit(EVENT_DATA_COMPLETE, &host->pending_events); return true; } static void dw_mci_tasklet_func(unsigned long priv) { struct dw_mci *host = (struct dw_mci *)priv; struct mmc_data *data; struct mmc_command *cmd; struct mmc_request *mrq; enum dw_mci_state state; enum dw_mci_state prev_state; unsigned int err; spin_lock(&host->lock); state = host->state; data = host->data; mrq = host->mrq; do { prev_state = state; switch (state) { case STATE_IDLE: case STATE_WAITING_CMD11_DONE: break; case STATE_SENDING_CMD11: case STATE_SENDING_CMD: if (!dw_mci_clear_pending_cmd_complete(host)) break; cmd = host->cmd; host->cmd = NULL; set_bit(EVENT_CMD_COMPLETE, &host->completed_events); err = dw_mci_command_complete(host, cmd); if (cmd == mrq->sbc && !err) { __dw_mci_start_request(host, host->slot, mrq->cmd); goto unlock; } if (cmd->data && err) { /* * During UHS tuning sequence, sending the stop * command after the response CRC error would * throw the system into a confused state * causing all future tuning phases to report * failure. * * In such case controller will move into a data * transfer state after a response error or * response CRC error. Let's let that finish * before trying to send a stop, so we'll go to * STATE_SENDING_DATA. * * Although letting the data transfer take place * will waste a bit of time (we already know * the command was bad), it can't cause any * errors since it's possible it would have * taken place anyway if this tasklet got * delayed. Allowing the transfer to take place * avoids races and keeps things simple. */ if ((err != -ETIMEDOUT) && (cmd->opcode == MMC_SEND_TUNING_BLOCK)) { state = STATE_SENDING_DATA; continue; } dw_mci_stop_dma(host); send_stop_abort(host, data); state = STATE_SENDING_STOP; break; } if (!cmd->data || err) { dw_mci_request_end(host, mrq); goto unlock; } prev_state = state = STATE_SENDING_DATA; /* fall through */ case STATE_SENDING_DATA: /* * We could get a data error and never a transfer * complete so we'd better check for it here. * * Note that we don't really care if we also got a * transfer complete; stopping the DMA and sending an * abort won't hurt. */ if (test_and_clear_bit(EVENT_DATA_ERROR, &host->pending_events)) { dw_mci_stop_dma(host); if (!(host->data_status & (SDMMC_INT_DRTO | SDMMC_INT_EBE))) send_stop_abort(host, data); state = STATE_DATA_ERROR; break; } if (!test_and_clear_bit(EVENT_XFER_COMPLETE, &host->pending_events)) { /* * If all data-related interrupts don't come * within the given time in reading data state. */ if (host->dir_status == DW_MCI_RECV_STATUS) dw_mci_set_drto(host); break; } set_bit(EVENT_XFER_COMPLETE, &host->completed_events); /* * Handle an EVENT_DATA_ERROR that might have shown up * before the transfer completed. This might not have * been caught by the check above because the interrupt * could have gone off between the previous check and * the check for transfer complete. * * Technically this ought not be needed assuming we * get a DATA_COMPLETE eventually (we'll notice the * error and end the request), but it shouldn't hurt. * * This has the advantage of sending the stop command. */ if (test_and_clear_bit(EVENT_DATA_ERROR, &host->pending_events)) { dw_mci_stop_dma(host); if (!(host->data_status & (SDMMC_INT_DRTO | SDMMC_INT_EBE))) send_stop_abort(host, data); state = STATE_DATA_ERROR; break; } prev_state = state = STATE_DATA_BUSY; /* fall through */ case STATE_DATA_BUSY: if (!dw_mci_clear_pending_data_complete(host)) { /* * If data error interrupt comes but data over * interrupt doesn't come within the given time. * in reading data state. */ if (host->dir_status == DW_MCI_RECV_STATUS) dw_mci_set_drto(host); break; } host->data = NULL; set_bit(EVENT_DATA_COMPLETE, &host->completed_events); err = dw_mci_data_complete(host, data); if (!err) { if (!data->stop || mrq->sbc) { if (mrq->sbc && data->stop) data->stop->error = 0; dw_mci_request_end(host, mrq); goto unlock; } /* stop command for open-ended transfer*/ if (data->stop) send_stop_abort(host, data); } else { /* * If we don't have a command complete now we'll * never get one since we just reset everything; * better end the request. * * If we do have a command complete we'll fall * through to the SENDING_STOP command and * everything will be peachy keen. */ if (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) { host->cmd = NULL; dw_mci_request_end(host, mrq); goto unlock; } } /* * If err has non-zero, * stop-abort command has been already issued. */ prev_state = state = STATE_SENDING_STOP; /* fall through */ case STATE_SENDING_STOP: if (!dw_mci_clear_pending_cmd_complete(host)) break; /* CMD error in data command */ if (mrq->cmd->error && mrq->data) dw_mci_reset(host); host->cmd = NULL; host->data = NULL; if (!mrq->sbc && mrq->stop) dw_mci_command_complete(host, mrq->stop); else host->cmd_status = 0; dw_mci_request_end(host, mrq); goto unlock; case STATE_DATA_ERROR: if (!test_and_clear_bit(EVENT_XFER_COMPLETE, &host->pending_events)) break; state = STATE_DATA_BUSY; break; } } while (state != prev_state); host->state = state; unlock: spin_unlock(&host->lock); } /* push final bytes to part_buf, only use during push */ static void dw_mci_set_part_bytes(struct dw_mci *host, void *buf, int cnt) { memcpy((void *)&host->part_buf, buf, cnt); host->part_buf_count = cnt; } /* append bytes to part_buf, only use during push */ static int dw_mci_push_part_bytes(struct dw_mci *host, void *buf, int cnt) { cnt = min(cnt, (1 << host->data_shift) - host->part_buf_count); memcpy((void *)&host->part_buf + host->part_buf_count, buf, cnt); host->part_buf_count += cnt; return cnt; } /* pull first bytes from part_buf, only use during pull */ static int dw_mci_pull_part_bytes(struct dw_mci *host, void *buf, int cnt) { cnt = min_t(int, cnt, host->part_buf_count); if (cnt) { memcpy(buf, (void *)&host->part_buf + host->part_buf_start, cnt); host->part_buf_count -= cnt; host->part_buf_start += cnt; } return cnt; } /* pull final bytes from the part_buf, assuming it's just been filled */ static void dw_mci_pull_final_bytes(struct dw_mci *host, void *buf, int cnt) { memcpy(buf, &host->part_buf, cnt); host->part_buf_start = cnt; host->part_buf_count = (1 << host->data_shift) - cnt; } static void dw_mci_push_data16(struct dw_mci *host, void *buf, int cnt) { struct mmc_data *data = host->data; int init_cnt = cnt; /* try and push anything in the part_buf */ if (unlikely(host->part_buf_count)) { int len = dw_mci_push_part_bytes(host, buf, cnt); buf += len; cnt -= len; if (host->part_buf_count == 2) { mci_fifo_writew(host->fifo_reg, host->part_buf16); host->part_buf_count = 0; } } #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS if (unlikely((unsigned long)buf & 0x1)) { while (cnt >= 2) { u16 aligned_buf[64]; int len = min(cnt & -2, (int)sizeof(aligned_buf)); int items = len >> 1; int i; /* memcpy from input buffer into aligned buffer */ memcpy(aligned_buf, buf, len); buf += len; cnt -= len; /* push data from aligned buffer into fifo */ for (i = 0; i < items; ++i) mci_fifo_writew(host->fifo_reg, aligned_buf[i]); } } else #endif { u16 *pdata = buf; for (; cnt >= 2; cnt -= 2) mci_fifo_writew(host->fifo_reg, *pdata++); buf = pdata; } /* put anything remaining in the part_buf */ if (cnt) { dw_mci_set_part_bytes(host, buf, cnt); /* Push data if we have reached the expected data length */ if ((data->bytes_xfered + init_cnt) == (data->blksz * data->blocks)) mci_fifo_writew(host->fifo_reg, host->part_buf16); } } static void dw_mci_pull_data16(struct dw_mci *host, void *buf, int cnt) { #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS if (unlikely((unsigned long)buf & 0x1)) { while (cnt >= 2) { /* pull data from fifo into aligned buffer */ u16 aligned_buf[64]; int len = min(cnt & -2, (int)sizeof(aligned_buf)); int items = len >> 1; int i; for (i = 0; i < items; ++i) aligned_buf[i] = mci_fifo_readw(host->fifo_reg); /* memcpy from aligned buffer into output buffer */ memcpy(buf, aligned_buf, len); buf += len; cnt -= len; } } else #endif { u16 *pdata = buf; for (; cnt >= 2; cnt -= 2) *pdata++ = mci_fifo_readw(host->fifo_reg); buf = pdata; } if (cnt) { host->part_buf16 = mci_fifo_readw(host->fifo_reg); dw_mci_pull_final_bytes(host, buf, cnt); } } static void dw_mci_push_data32(struct dw_mci *host, void *buf, int cnt) { struct mmc_data *data = host->data; int init_cnt = cnt; /* try and push anything in the part_buf */ if (unlikely(host->part_buf_count)) { int len = dw_mci_push_part_bytes(host, buf, cnt); buf += len; cnt -= len; if (host->part_buf_count == 4) { mci_fifo_writel(host->fifo_reg, host->part_buf32); host->part_buf_count = 0; } } #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS if (unlikely((unsigned long)buf & 0x3)) { while (cnt >= 4) { u32 aligned_buf[32]; int len = min(cnt & -4, (int)sizeof(aligned_buf)); int items = len >> 2; int i; /* memcpy from input buffer into aligned buffer */ memcpy(aligned_buf, buf, len); buf += len; cnt -= len; /* push data from aligned buffer into fifo */ for (i = 0; i < items; ++i) mci_fifo_writel(host->fifo_reg, aligned_buf[i]); } } else #endif { u32 *pdata = buf; for (; cnt >= 4; cnt -= 4) mci_fifo_writel(host->fifo_reg, *pdata++); buf = pdata; } /* put anything remaining in the part_buf */ if (cnt) { dw_mci_set_part_bytes(host, buf, cnt); /* Push data if we have reached the expected data length */ if ((data->bytes_xfered + init_cnt) == (data->blksz * data->blocks)) mci_fifo_writel(host->fifo_reg, host->part_buf32); } } static void dw_mci_pull_data32(struct dw_mci *host, void *buf, int cnt) { #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS if (unlikely((unsigned long)buf & 0x3)) { while (cnt >= 4) { /* pull data from fifo into aligned buffer */ u32 aligned_buf[32]; int len = min(cnt & -4, (int)sizeof(aligned_buf)); int items = len >> 2; int i; for (i = 0; i < items; ++i) aligned_buf[i] = mci_fifo_readl(host->fifo_reg); /* memcpy from aligned buffer into output buffer */ memcpy(buf, aligned_buf, len); buf += len; cnt -= len; } } else #endif { u32 *pdata = buf; for (; cnt >= 4; cnt -= 4) *pdata++ = mci_fifo_readl(host->fifo_reg); buf = pdata; } if (cnt) { host->part_buf32 = mci_fifo_readl(host->fifo_reg); dw_mci_pull_final_bytes(host, buf, cnt); } } static void dw_mci_push_data64(struct dw_mci *host, void *buf, int cnt) { struct mmc_data *data = host->data; int init_cnt = cnt; /* try and push anything in the part_buf */ if (unlikely(host->part_buf_count)) { int len = dw_mci_push_part_bytes(host, buf, cnt); buf += len; cnt -= len; if (host->part_buf_count == 8) { mci_fifo_writeq(host->fifo_reg, host->part_buf); host->part_buf_count = 0; } } #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS if (unlikely((unsigned long)buf & 0x7)) { while (cnt >= 8) { u64 aligned_buf[16]; int len = min(cnt & -8, (int)sizeof(aligned_buf)); int items = len >> 3; int i; /* memcpy from input buffer into aligned buffer */ memcpy(aligned_buf, buf, len); buf += len; cnt -= len; /* push data from aligned buffer into fifo */ for (i = 0; i < items; ++i) mci_fifo_writeq(host->fifo_reg, aligned_buf[i]); } } else #endif { u64 *pdata = buf; for (; cnt >= 8; cnt -= 8) mci_fifo_writeq(host->fifo_reg, *pdata++); buf = pdata; } /* put anything remaining in the part_buf */ if (cnt) { dw_mci_set_part_bytes(host, buf, cnt); /* Push data if we have reached the expected data length */ if ((data->bytes_xfered + init_cnt) == (data->blksz * data->blocks)) mci_fifo_writeq(host->fifo_reg, host->part_buf); } } static void dw_mci_pull_data64(struct dw_mci *host, void *buf, int cnt) { #ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS if (unlikely((unsigned long)buf & 0x7)) { while (cnt >= 8) { /* pull data from fifo into aligned buffer */ u64 aligned_buf[16]; int len = min(cnt & -8, (int)sizeof(aligned_buf)); int items = len >> 3; int i; for (i = 0; i < items; ++i) aligned_buf[i] = mci_fifo_readq(host->fifo_reg); /* memcpy from aligned buffer into output buffer */ memcpy(buf, aligned_buf, len); buf += len; cnt -= len; } } else #endif { u64 *pdata = buf; for (; cnt >= 8; cnt -= 8) *pdata++ = mci_fifo_readq(host->fifo_reg); buf = pdata; } if (cnt) { host->part_buf = mci_fifo_readq(host->fifo_reg); dw_mci_pull_final_bytes(host, buf, cnt); } } static void dw_mci_pull_data(struct dw_mci *host, void *buf, int cnt) { int len; /* get remaining partial bytes */ len = dw_mci_pull_part_bytes(host, buf, cnt); if (unlikely(len == cnt)) return; buf += len; cnt -= len; /* get the rest of the data */ host->pull_data(host, buf, cnt); } static void dw_mci_read_data_pio(struct dw_mci *host, bool dto) { struct sg_mapping_iter *sg_miter = &host->sg_miter; void *buf; unsigned int offset; struct mmc_data *data = host->data; int shift = host->data_shift; u32 status; unsigned int len; unsigned int remain, fcnt; do { if (!sg_miter_next(sg_miter)) goto done; host->sg = sg_miter->piter.sg; buf = sg_miter->addr; remain = sg_miter->length; offset = 0; do { fcnt = (SDMMC_GET_FCNT(mci_readl(host, STATUS)) << shift) + host->part_buf_count; len = min(remain, fcnt); if (!len) break; dw_mci_pull_data(host, (void *)(buf + offset), len); data->bytes_xfered += len; offset += len; remain -= len; } while (remain); sg_miter->consumed = offset; status = mci_readl(host, MINTSTS); mci_writel(host, RINTSTS, SDMMC_INT_RXDR); /* if the RXDR is ready read again */ } while ((status & SDMMC_INT_RXDR) || (dto && SDMMC_GET_FCNT(mci_readl(host, STATUS)))); if (!remain) { if (!sg_miter_next(sg_miter)) goto done; sg_miter->consumed = 0; } sg_miter_stop(sg_miter); return; done: sg_miter_stop(sg_miter); host->sg = NULL; smp_wmb(); /* drain writebuffer */ set_bit(EVENT_XFER_COMPLETE, &host->pending_events); } static void dw_mci_write_data_pio(struct dw_mci *host) { struct sg_mapping_iter *sg_miter = &host->sg_miter; void *buf; unsigned int offset; struct mmc_data *data = host->data; int shift = host->data_shift; u32 status; unsigned int len; unsigned int fifo_depth = host->fifo_depth; unsigned int remain, fcnt; do { if (!sg_miter_next(sg_miter)) goto done; host->sg = sg_miter->piter.sg; buf = sg_miter->addr; remain = sg_miter->length; offset = 0; do { fcnt = ((fifo_depth - SDMMC_GET_FCNT(mci_readl(host, STATUS))) << shift) - host->part_buf_count; len = min(remain, fcnt); if (!len) break; host->push_data(host, (void *)(buf + offset), len); data->bytes_xfered += len; offset += len; remain -= len; } while (remain); sg_miter->consumed = offset; status = mci_readl(host, MINTSTS); mci_writel(host, RINTSTS, SDMMC_INT_TXDR); } while (status & SDMMC_INT_TXDR); /* if TXDR write again */ if (!remain) { if (!sg_miter_next(sg_miter)) goto done; sg_miter->consumed = 0; } sg_miter_stop(sg_miter); return; done: sg_miter_stop(sg_miter); host->sg = NULL; smp_wmb(); /* drain writebuffer */ set_bit(EVENT_XFER_COMPLETE, &host->pending_events); } static void dw_mci_cmd_interrupt(struct dw_mci *host, u32 status) { del_timer(&host->cto_timer); if (!host->cmd_status) host->cmd_status = status; smp_wmb(); /* drain writebuffer */ set_bit(EVENT_CMD_COMPLETE, &host->pending_events); tasklet_schedule(&host->tasklet); } static void dw_mci_handle_cd(struct dw_mci *host) { struct dw_mci_slot *slot = host->slot; if (slot->mmc->ops->card_event) slot->mmc->ops->card_event(slot->mmc); mmc_detect_change(slot->mmc, msecs_to_jiffies(host->pdata->detect_delay_ms)); } static irqreturn_t dw_mci_interrupt(int irq, void *dev_id) { struct dw_mci *host = dev_id; u32 pending; struct dw_mci_slot *slot = host->slot; unsigned long irqflags; pending = mci_readl(host, MINTSTS); /* read-only mask reg */ if (pending) { /* Check volt switch first, since it can look like an error */ if ((host->state == STATE_SENDING_CMD11) && (pending & SDMMC_INT_VOLT_SWITCH)) { mci_writel(host, RINTSTS, SDMMC_INT_VOLT_SWITCH); pending &= ~SDMMC_INT_VOLT_SWITCH; /* * Hold the lock; we know cmd11_timer can't be kicked * off after the lock is released, so safe to delete. */ spin_lock_irqsave(&host->irq_lock, irqflags); dw_mci_cmd_interrupt(host, pending); spin_unlock_irqrestore(&host->irq_lock, irqflags); del_timer(&host->cmd11_timer); } if (pending & DW_MCI_CMD_ERROR_FLAGS) { spin_lock_irqsave(&host->irq_lock, irqflags); del_timer(&host->cto_timer); mci_writel(host, RINTSTS, DW_MCI_CMD_ERROR_FLAGS); host->cmd_status = pending; smp_wmb(); /* drain writebuffer */ set_bit(EVENT_CMD_COMPLETE, &host->pending_events); spin_unlock_irqrestore(&host->irq_lock, irqflags); } if (pending & DW_MCI_DATA_ERROR_FLAGS) { /* if there is an error report DATA_ERROR */ mci_writel(host, RINTSTS, DW_MCI_DATA_ERROR_FLAGS); host->data_status = pending; smp_wmb(); /* drain writebuffer */ set_bit(EVENT_DATA_ERROR, &host->pending_events); tasklet_schedule(&host->tasklet); } if (pending & SDMMC_INT_DATA_OVER) { spin_lock_irqsave(&host->irq_lock, irqflags); del_timer(&host->dto_timer); mci_writel(host, RINTSTS, SDMMC_INT_DATA_OVER); if (!host->data_status) host->data_status = pending; smp_wmb(); /* drain writebuffer */ if (host->dir_status == DW_MCI_RECV_STATUS) { if (host->sg != NULL) dw_mci_read_data_pio(host, true); } set_bit(EVENT_DATA_COMPLETE, &host->pending_events); tasklet_schedule(&host->tasklet); spin_unlock_irqrestore(&host->irq_lock, irqflags); } if (pending & SDMMC_INT_RXDR) { mci_writel(host, RINTSTS, SDMMC_INT_RXDR); if (host->dir_status == DW_MCI_RECV_STATUS && host->sg) dw_mci_read_data_pio(host, false); } if (pending & SDMMC_INT_TXDR) { mci_writel(host, RINTSTS, SDMMC_INT_TXDR); if (host->dir_status == DW_MCI_SEND_STATUS && host->sg) dw_mci_write_data_pio(host); } if (pending & SDMMC_INT_CMD_DONE) { spin_lock_irqsave(&host->irq_lock, irqflags); mci_writel(host, RINTSTS, SDMMC_INT_CMD_DONE); dw_mci_cmd_interrupt(host, pending); spin_unlock_irqrestore(&host->irq_lock, irqflags); } if (pending & SDMMC_INT_CD) { mci_writel(host, RINTSTS, SDMMC_INT_CD); dw_mci_handle_cd(host); } if (pending & SDMMC_INT_SDIO(slot->sdio_id)) { mci_writel(host, RINTSTS, SDMMC_INT_SDIO(slot->sdio_id)); __dw_mci_enable_sdio_irq(slot, 0); sdio_signal_irq(slot->mmc); } } if (host->use_dma != TRANS_MODE_IDMAC) return IRQ_HANDLED; /* Handle IDMA interrupts */ if (host->dma_64bit_address == 1) { pending = mci_readl(host, IDSTS64); if (pending & (SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI)) { mci_writel(host, IDSTS64, SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI); mci_writel(host, IDSTS64, SDMMC_IDMAC_INT_NI); if (!test_bit(EVENT_DATA_ERROR, &host->pending_events)) host->dma_ops->complete((void *)host); } } else { pending = mci_readl(host, IDSTS); if (pending & (SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI)) { mci_writel(host, IDSTS, SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI); mci_writel(host, IDSTS, SDMMC_IDMAC_INT_NI); if (!test_bit(EVENT_DATA_ERROR, &host->pending_events)) host->dma_ops->complete((void *)host); } } return IRQ_HANDLED; } static int dw_mci_init_slot_caps(struct dw_mci_slot *slot) { struct dw_mci *host = slot->host; const struct dw_mci_drv_data *drv_data = host->drv_data; struct mmc_host *mmc = slot->mmc; int ctrl_id; if (host->pdata->caps) mmc->caps = host->pdata->caps; /* * Support MMC_CAP_ERASE by default. * It needs to use trim/discard/erase commands. */ mmc->caps |= MMC_CAP_ERASE; if (host->pdata->pm_caps) mmc->pm_caps = host->pdata->pm_caps; if (host->dev->of_node) { ctrl_id = of_alias_get_id(host->dev->of_node, "mshc"); if (ctrl_id < 0) ctrl_id = 0; } else { ctrl_id = to_platform_device(host->dev)->id; } if (drv_data && drv_data->caps) { if (ctrl_id >= drv_data->num_caps) { dev_err(host->dev, "invalid controller id %d\n", ctrl_id); return -EINVAL; } mmc->caps |= drv_data->caps[ctrl_id]; } if (host->pdata->caps2) mmc->caps2 = host->pdata->caps2; mmc->f_min = DW_MCI_FREQ_MIN; if (!mmc->f_max) mmc->f_max = DW_MCI_FREQ_MAX; /* Process SDIO IRQs through the sdio_irq_work. */ if (mmc->caps & MMC_CAP_SDIO_IRQ) mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD; return 0; } static int dw_mci_init_slot(struct dw_mci *host) { struct mmc_host *mmc; struct dw_mci_slot *slot; int ret; mmc = mmc_alloc_host(sizeof(struct dw_mci_slot), host->dev); if (!mmc) return -ENOMEM; slot = mmc_priv(mmc); slot->id = 0; slot->sdio_id = host->sdio_id0 + slot->id; slot->mmc = mmc; slot->host = host; host->slot = slot; mmc->ops = &dw_mci_ops; /*if there are external regulators, get them*/ ret = mmc_regulator_get_supply(mmc); if (ret) goto err_host_allocated; if (!mmc->ocr_avail) mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34; ret = mmc_of_parse(mmc); if (ret) goto err_host_allocated; ret = dw_mci_init_slot_caps(slot); if (ret) goto err_host_allocated; /* Useful defaults if platform data is unset. */ if (host->use_dma == TRANS_MODE_IDMAC) { mmc->max_segs = host->ring_size; mmc->max_blk_size = 65535; mmc->max_seg_size = 0x1000; mmc->max_req_size = mmc->max_seg_size * host->ring_size; mmc->max_blk_count = mmc->max_req_size / 512; } else if (host->use_dma == TRANS_MODE_EDMAC) { mmc->max_segs = 64; mmc->max_blk_size = 65535; mmc->max_blk_count = 65535; mmc->max_req_size = mmc->max_blk_size * mmc->max_blk_count; mmc->max_seg_size = mmc->max_req_size; } else { /* TRANS_MODE_PIO */ mmc->max_segs = 64; mmc->max_blk_size = 65535; /* BLKSIZ is 16 bits */ mmc->max_blk_count = 512; mmc->max_req_size = mmc->max_blk_size * mmc->max_blk_count; mmc->max_seg_size = mmc->max_req_size; } dw_mci_get_cd(mmc); ret = mmc_add_host(mmc); if (ret) goto err_host_allocated; #if defined(CONFIG_DEBUG_FS) dw_mci_init_debugfs(slot); #endif return 0; err_host_allocated: mmc_free_host(mmc); return ret; } static void dw_mci_cleanup_slot(struct dw_mci_slot *slot) { /* Debugfs stuff is cleaned up by mmc core */ mmc_remove_host(slot->mmc); slot->host->slot = NULL; mmc_free_host(slot->mmc); } static void dw_mci_init_dma(struct dw_mci *host) { int addr_config; struct device *dev = host->dev; /* * Check tansfer mode from HCON[17:16] * Clear the ambiguous description of dw_mmc databook: * 2b'00: No DMA Interface -> Actually means using Internal DMA block * 2b'01: DesignWare DMA Interface -> Synopsys DW-DMA block * 2b'10: Generic DMA Interface -> non-Synopsys generic DMA block * 2b'11: Non DW DMA Interface -> pio only * Compared to DesignWare DMA Interface, Generic DMA Interface has a * simpler request/acknowledge handshake mechanism and both of them * are regarded as external dma master for dw_mmc. */ host->use_dma = SDMMC_GET_TRANS_MODE(mci_readl(host, HCON)); if (host->use_dma == DMA_INTERFACE_IDMA) { host->use_dma = TRANS_MODE_IDMAC; } else if (host->use_dma == DMA_INTERFACE_DWDMA || host->use_dma == DMA_INTERFACE_GDMA) { host->use_dma = TRANS_MODE_EDMAC; } else { goto no_dma; } /* Determine which DMA interface to use */ if (host->use_dma == TRANS_MODE_IDMAC) { /* * Check ADDR_CONFIG bit in HCON to find * IDMAC address bus width */ addr_config = SDMMC_GET_ADDR_CONFIG(mci_readl(host, HCON)); if (addr_config == 1) { /* host supports IDMAC in 64-bit address mode */ host->dma_64bit_address = 1; dev_info(host->dev, "IDMAC supports 64-bit address mode.\n"); if (!dma_set_mask(host->dev, DMA_BIT_MASK(64))) dma_set_coherent_mask(host->dev, DMA_BIT_MASK(64)); } else { /* host supports IDMAC in 32-bit address mode */ host->dma_64bit_address = 0; dev_info(host->dev, "IDMAC supports 32-bit address mode.\n"); } /* Alloc memory for sg translation */ host->sg_cpu = dmam_alloc_coherent(host->dev, DESC_RING_BUF_SZ, &host->sg_dma, GFP_KERNEL); if (!host->sg_cpu) { dev_err(host->dev, "%s: could not alloc DMA memory\n", __func__); goto no_dma; } host->dma_ops = &dw_mci_idmac_ops; dev_info(host->dev, "Using internal DMA controller.\n"); } else { /* TRANS_MODE_EDMAC: check dma bindings again */ if ((device_property_read_string_array(dev, "dma-names", NULL, 0) < 0) || !device_property_present(dev, "dmas")) { goto no_dma; } host->dma_ops = &dw_mci_edmac_ops; dev_info(host->dev, "Using external DMA controller.\n"); } if (host->dma_ops->init && host->dma_ops->start && host->dma_ops->stop && host->dma_ops->cleanup) { if (host->dma_ops->init(host)) { dev_err(host->dev, "%s: Unable to initialize DMA Controller.\n", __func__); goto no_dma; } } else { dev_err(host->dev, "DMA initialization not found.\n"); goto no_dma; } return; no_dma: dev_info(host->dev, "Using PIO mode.\n"); host->use_dma = TRANS_MODE_PIO; } static void dw_mci_cmd11_timer(struct timer_list *t) { struct dw_mci *host = from_timer(host, t, cmd11_timer); if (host->state != STATE_SENDING_CMD11) { dev_warn(host->dev, "Unexpected CMD11 timeout\n"); return; } host->cmd_status = SDMMC_INT_RTO; set_bit(EVENT_CMD_COMPLETE, &host->pending_events); tasklet_schedule(&host->tasklet); } static void dw_mci_cto_timer(struct timer_list *t) { struct dw_mci *host = from_timer(host, t, cto_timer); unsigned long irqflags; u32 pending; spin_lock_irqsave(&host->irq_lock, irqflags); /* * If somehow we have very bad interrupt latency it's remotely possible * that the timer could fire while the interrupt is still pending or * while the interrupt is midway through running. Let's be paranoid * and detect those two cases. Note that this is paranoia is somewhat * justified because in this function we don't actually cancel the * pending command in the controller--we just assume it will never come. */ pending = mci_readl(host, MINTSTS); /* read-only mask reg */ if (pending & (DW_MCI_CMD_ERROR_FLAGS | SDMMC_INT_CMD_DONE)) { /* The interrupt should fire; no need to act but we can warn */ dev_warn(host->dev, "Unexpected interrupt latency\n"); goto exit; } if (test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) { /* Presumably interrupt handler couldn't delete the timer */ dev_warn(host->dev, "CTO timeout when already completed\n"); goto exit; } /* * Continued paranoia to make sure we're in the state we expect. * This paranoia isn't really justified but it seems good to be safe. */ switch (host->state) { case STATE_SENDING_CMD11: case STATE_SENDING_CMD: case STATE_SENDING_STOP: /* * If CMD_DONE interrupt does NOT come in sending command * state, we should notify the driver to terminate current * transfer and report a command timeout to the core. */ host->cmd_status = SDMMC_INT_RTO; set_bit(EVENT_CMD_COMPLETE, &host->pending_events); tasklet_schedule(&host->tasklet); break; default: dev_warn(host->dev, "Unexpected command timeout, state %d\n", host->state); break; } exit: spin_unlock_irqrestore(&host->irq_lock, irqflags); } static void dw_mci_dto_timer(struct timer_list *t) { struct dw_mci *host = from_timer(host, t, dto_timer); unsigned long irqflags; u32 pending; spin_lock_irqsave(&host->irq_lock, irqflags); /* * The DTO timer is much longer than the CTO timer, so it's even less * likely that we'll these cases, but it pays to be paranoid. */ pending = mci_readl(host, MINTSTS); /* read-only mask reg */ if (pending & SDMMC_INT_DATA_OVER) { /* The interrupt should fire; no need to act but we can warn */ dev_warn(host->dev, "Unexpected data interrupt latency\n"); goto exit; } if (test_bit(EVENT_DATA_COMPLETE, &host->pending_events)) { /* Presumably interrupt handler couldn't delete the timer */ dev_warn(host->dev, "DTO timeout when already completed\n"); goto exit; } /* * Continued paranoia to make sure we're in the state we expect. * This paranoia isn't really justified but it seems good to be safe. */ switch (host->state) { case STATE_SENDING_DATA: case STATE_DATA_BUSY: /* * If DTO interrupt does NOT come in sending data state, * we should notify the driver to terminate current transfer * and report a data timeout to the core. */ host->data_status = SDMMC_INT_DRTO; set_bit(EVENT_DATA_ERROR, &host->pending_events); set_bit(EVENT_DATA_COMPLETE, &host->pending_events); tasklet_schedule(&host->tasklet); break; default: dev_warn(host->dev, "Unexpected data timeout, state %d\n", host->state); break; } exit: spin_unlock_irqrestore(&host->irq_lock, irqflags); } #ifdef CONFIG_OF static struct dw_mci_board *dw_mci_parse_dt(struct dw_mci *host) { struct dw_mci_board *pdata; struct device *dev = host->dev; const struct dw_mci_drv_data *drv_data = host->drv_data; int ret; u32 clock_frequency; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return ERR_PTR(-ENOMEM); /* find reset controller when exist */ pdata->rstc = devm_reset_control_get_optional_exclusive(dev, "reset"); if (IS_ERR(pdata->rstc)) { if (PTR_ERR(pdata->rstc) == -EPROBE_DEFER) return ERR_PTR(-EPROBE_DEFER); } if (device_property_read_u32(dev, "fifo-depth", &pdata->fifo_depth)) dev_info(dev, "fifo-depth property not found, using value of FIFOTH register as default\n"); device_property_read_u32(dev, "card-detect-delay", &pdata->detect_delay_ms); device_property_read_u32(dev, "data-addr", &host->data_addr_override); if (device_property_present(dev, "fifo-watermark-aligned")) host->wm_aligned = true; if (!device_property_read_u32(dev, "clock-frequency", &clock_frequency)) pdata->bus_hz = clock_frequency; if (drv_data && drv_data->parse_dt) { ret = drv_data->parse_dt(host); if (ret) return ERR_PTR(ret); } return pdata; } #else /* CONFIG_OF */ static struct dw_mci_board *dw_mci_parse_dt(struct dw_mci *host) { return ERR_PTR(-EINVAL); } #endif /* CONFIG_OF */ static void dw_mci_enable_cd(struct dw_mci *host) { unsigned long irqflags; u32 temp; /* * No need for CD if all slots have a non-error GPIO * as well as broken card detection is found. */ if (host->slot->mmc->caps & MMC_CAP_NEEDS_POLL) return; if (mmc_gpio_get_cd(host->slot->mmc) < 0) { spin_lock_irqsave(&host->irq_lock, irqflags); temp = mci_readl(host, INTMASK); temp |= SDMMC_INT_CD; mci_writel(host, INTMASK, temp); spin_unlock_irqrestore(&host->irq_lock, irqflags); } } int dw_mci_probe(struct dw_mci *host) { const struct dw_mci_drv_data *drv_data = host->drv_data; int width, i, ret = 0; u32 fifo_size; if (!host->pdata) { host->pdata = dw_mci_parse_dt(host); if (PTR_ERR(host->pdata) == -EPROBE_DEFER) { return -EPROBE_DEFER; } else if (IS_ERR(host->pdata)) { dev_err(host->dev, "platform data not available\n"); return -EINVAL; } } host->biu_clk = devm_clk_get(host->dev, "biu"); if (IS_ERR(host->biu_clk)) { dev_dbg(host->dev, "biu clock not available\n"); } else { ret = clk_prepare_enable(host->biu_clk); if (ret) { dev_err(host->dev, "failed to enable biu clock\n"); return ret; } } host->ciu_clk = devm_clk_get(host->dev, "ciu"); if (IS_ERR(host->ciu_clk)) { dev_dbg(host->dev, "ciu clock not available\n"); host->bus_hz = host->pdata->bus_hz; } else { ret = clk_prepare_enable(host->ciu_clk); if (ret) { dev_err(host->dev, "failed to enable ciu clock\n"); goto err_clk_biu; } if (host->pdata->bus_hz) { ret = clk_set_rate(host->ciu_clk, host->pdata->bus_hz); if (ret) dev_warn(host->dev, "Unable to set bus rate to %uHz\n", host->pdata->bus_hz); } host->bus_hz = clk_get_rate(host->ciu_clk); } if (!host->bus_hz) { dev_err(host->dev, "Platform data must supply bus speed\n"); ret = -ENODEV; goto err_clk_ciu; } if (!IS_ERR(host->pdata->rstc)) { reset_control_assert(host->pdata->rstc); usleep_range(10, 50); reset_control_deassert(host->pdata->rstc); } if (drv_data && drv_data->init) { ret = drv_data->init(host); if (ret) { dev_err(host->dev, "implementation specific init failed\n"); goto err_clk_ciu; } } timer_setup(&host->cmd11_timer, dw_mci_cmd11_timer, 0); timer_setup(&host->cto_timer, dw_mci_cto_timer, 0); timer_setup(&host->dto_timer, dw_mci_dto_timer, 0); spin_lock_init(&host->lock); spin_lock_init(&host->irq_lock); INIT_LIST_HEAD(&host->queue); /* * Get the host data width - this assumes that HCON has been set with * the correct values. */ i = SDMMC_GET_HDATA_WIDTH(mci_readl(host, HCON)); if (!i) { host->push_data = dw_mci_push_data16; host->pull_data = dw_mci_pull_data16; width = 16; host->data_shift = 1; } else if (i == 2) { host->push_data = dw_mci_push_data64; host->pull_data = dw_mci_pull_data64; width = 64; host->data_shift = 3; } else { /* Check for a reserved value, and warn if it is */ WARN((i != 1), "HCON reports a reserved host data width!\n" "Defaulting to 32-bit access.\n"); host->push_data = dw_mci_push_data32; host->pull_data = dw_mci_pull_data32; width = 32; host->data_shift = 2; } /* Reset all blocks */ if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_ALL_RESET_FLAGS)) { ret = -ENODEV; goto err_clk_ciu; } host->dma_ops = host->pdata->dma_ops; dw_mci_init_dma(host); /* Clear the interrupts for the host controller */ mci_writel(host, RINTSTS, 0xFFFFFFFF); mci_writel(host, INTMASK, 0); /* disable all mmc interrupt first */ /* Put in max timeout */ mci_writel(host, TMOUT, 0xFFFFFFFF); /* * FIFO threshold settings RxMark = fifo_size / 2 - 1, * Tx Mark = fifo_size / 2 DMA Size = 8 */ if (!host->pdata->fifo_depth) { /* * Power-on value of RX_WMark is FIFO_DEPTH-1, but this may * have been overwritten by the bootloader, just like we're * about to do, so if you know the value for your hardware, you * should put it in the platform data. */ fifo_size = mci_readl(host, FIFOTH); fifo_size = 1 + ((fifo_size >> 16) & 0xfff); } else { fifo_size = host->pdata->fifo_depth; } host->fifo_depth = fifo_size; host->fifoth_val = SDMMC_SET_FIFOTH(0x2, fifo_size / 2 - 1, fifo_size / 2); mci_writel(host, FIFOTH, host->fifoth_val); /* disable clock to CIU */ mci_writel(host, CLKENA, 0); mci_writel(host, CLKSRC, 0); /* * In 2.40a spec, Data offset is changed. * Need to check the version-id and set data-offset for DATA register. */ host->verid = SDMMC_GET_VERID(mci_readl(host, VERID)); dev_info(host->dev, "Version ID is %04x\n", host->verid); if (host->data_addr_override) host->fifo_reg = host->regs + host->data_addr_override; else if (host->verid < DW_MMC_240A) host->fifo_reg = host->regs + DATA_OFFSET; else host->fifo_reg = host->regs + DATA_240A_OFFSET; tasklet_init(&host->tasklet, dw_mci_tasklet_func, (unsigned long)host); ret = devm_request_irq(host->dev, host->irq, dw_mci_interrupt, host->irq_flags, "dw-mci", host); if (ret) goto err_dmaunmap; /* * Enable interrupts for command done, data over, data empty, * receive ready and error such as transmit, receive timeout, crc error */ mci_writel(host, INTMASK, SDMMC_INT_CMD_DONE | SDMMC_INT_DATA_OVER | SDMMC_INT_TXDR | SDMMC_INT_RXDR | DW_MCI_ERROR_FLAGS); /* Enable mci interrupt */ mci_writel(host, CTRL, SDMMC_CTRL_INT_ENABLE); dev_info(host->dev, "DW MMC controller at irq %d,%d bit host data width,%u deep fifo\n", host->irq, width, fifo_size); /* We need at least one slot to succeed */ ret = dw_mci_init_slot(host); if (ret) { dev_dbg(host->dev, "slot %d init failed\n", i); goto err_dmaunmap; } /* Now that slots are all setup, we can enable card detect */ dw_mci_enable_cd(host); return 0; err_dmaunmap: if (host->use_dma && host->dma_ops->exit) host->dma_ops->exit(host); if (!IS_ERR(host->pdata->rstc)) reset_control_assert(host->pdata->rstc); err_clk_ciu: clk_disable_unprepare(host->ciu_clk); err_clk_biu: clk_disable_unprepare(host->biu_clk); return ret; } EXPORT_SYMBOL(dw_mci_probe); void dw_mci_remove(struct dw_mci *host) { dev_dbg(host->dev, "remove slot\n"); if (host->slot) dw_mci_cleanup_slot(host->slot); mci_writel(host, RINTSTS, 0xFFFFFFFF); mci_writel(host, INTMASK, 0); /* disable all mmc interrupt first */ /* disable clock to CIU */ mci_writel(host, CLKENA, 0); mci_writel(host, CLKSRC, 0); if (host->use_dma && host->dma_ops->exit) host->dma_ops->exit(host); if (!IS_ERR(host->pdata->rstc)) reset_control_assert(host->pdata->rstc); clk_disable_unprepare(host->ciu_clk); clk_disable_unprepare(host->biu_clk); } EXPORT_SYMBOL(dw_mci_remove); #ifdef CONFIG_PM int dw_mci_runtime_suspend(struct device *dev) { struct dw_mci *host = dev_get_drvdata(dev); if (host->use_dma && host->dma_ops->exit) host->dma_ops->exit(host); clk_disable_unprepare(host->ciu_clk); if (host->slot && (mmc_can_gpio_cd(host->slot->mmc) || !mmc_card_is_removable(host->slot->mmc))) clk_disable_unprepare(host->biu_clk); return 0; } EXPORT_SYMBOL(dw_mci_runtime_suspend); int dw_mci_runtime_resume(struct device *dev) { int ret = 0; struct dw_mci *host = dev_get_drvdata(dev); if (host->slot && (mmc_can_gpio_cd(host->slot->mmc) || !mmc_card_is_removable(host->slot->mmc))) { ret = clk_prepare_enable(host->biu_clk); if (ret) return ret; } ret = clk_prepare_enable(host->ciu_clk); if (ret) goto err; if (!dw_mci_ctrl_reset(host, SDMMC_CTRL_ALL_RESET_FLAGS)) { clk_disable_unprepare(host->ciu_clk); ret = -ENODEV; goto err; } if (host->use_dma && host->dma_ops->init) host->dma_ops->init(host); /* * Restore the initial value at FIFOTH register * And Invalidate the prev_blksz with zero */ mci_writel(host, FIFOTH, host->fifoth_val); host->prev_blksz = 0; /* Put in max timeout */ mci_writel(host, TMOUT, 0xFFFFFFFF); mci_writel(host, RINTSTS, 0xFFFFFFFF); mci_writel(host, INTMASK, SDMMC_INT_CMD_DONE | SDMMC_INT_DATA_OVER | SDMMC_INT_TXDR | SDMMC_INT_RXDR | DW_MCI_ERROR_FLAGS); mci_writel(host, CTRL, SDMMC_CTRL_INT_ENABLE); if (host->slot->mmc->pm_flags & MMC_PM_KEEP_POWER) dw_mci_set_ios(host->slot->mmc, &host->slot->mmc->ios); /* Force setup bus to guarantee available clock output */ dw_mci_setup_bus(host->slot, true); /* Now that slots are all setup, we can enable card detect */ dw_mci_enable_cd(host); return 0; err: if (host->slot && (mmc_can_gpio_cd(host->slot->mmc) || !mmc_card_is_removable(host->slot->mmc))) clk_disable_unprepare(host->biu_clk); return ret; } EXPORT_SYMBOL(dw_mci_runtime_resume); #endif /* CONFIG_PM */ static int __init dw_mci_init(void) { pr_info("Synopsys Designware Multimedia Card Interface Driver\n"); return 0; } static void __exit dw_mci_exit(void) { } module_init(dw_mci_init); module_exit(dw_mci_exit); MODULE_DESCRIPTION("DW Multimedia Card Interface driver"); MODULE_AUTHOR("NXP Semiconductor VietNam"); MODULE_AUTHOR("Imagination Technologies Ltd"); MODULE_LICENSE("GPL v2");
gpl-2.0
SayenkoDesign/selectahead
wp-content/plugins/woocommerce-quickbooks-pos-2013/QuickBooks/QBXML/Schema/Object/PaymentMethodQueryRq.php
3453
<?php /** * Schema object for: PaymentMethodQueryRq * * @author "Keith Palmer Jr." <[email protected]> * @license LICENSE.txt * * @package QuickBooks * @subpackage QBXML */ /** * */ require_once 'QuickBooks.php'; /** * */ require_once 'QuickBooks/QBXML/Schema/Object.php'; /** * */ class QuickBooks_QBXML_Schema_Object_PaymentMethodQueryRq extends QuickBooks_QBXML_Schema_Object { protected function &_qbxmlWrapper() { static $wrapper = ''; return $wrapper; } protected function &_dataTypePaths() { static $paths = array ( 'ListID' => 'IDTYPE', 'FullName' => 'STRTYPE', 'MaxReturned' => 'INTTYPE', 'ActiveStatus' => 'ENUMTYPE', 'FromModifiedDate' => 'DATETIMETYPE', 'ToModifiedDate' => 'DATETIMETYPE', 'NameFilter MatchCriterion' => 'ENUMTYPE', 'NameFilter Name' => 'STRTYPE', 'NameRangeFilter FromName' => 'STRTYPE', 'NameRangeFilter ToName' => 'STRTYPE', 'PaymentMethodType' => 'ENUMTYPE', 'IncludeRetElement' => 'STRTYPE', ); return $paths; } protected function &_maxLengthPaths() { static $paths = array ( 'ListID' => 0, 'FullName' => 0, 'MaxReturned' => 0, 'ActiveStatus' => 0, 'FromModifiedDate' => 0, 'ToModifiedDate' => 0, 'NameFilter MatchCriterion' => 0, 'NameFilter Name' => 0, 'NameRangeFilter FromName' => 0, 'NameRangeFilter ToName' => 0, 'PaymentMethodType' => 0, 'IncludeRetElement' => 50, ); return $paths; } protected function &_isOptionalPaths() { static $paths = array ( 'ListID' => false, 'FullName' => false, 'MaxReturned' => true, 'ActiveStatus' => true, 'FromModifiedDate' => true, 'ToModifiedDate' => true, 'NameFilter MatchCriterion' => false, 'NameFilter Name' => false, 'NameRangeFilter FromName' => true, 'NameRangeFilter ToName' => true, 'PaymentMethodType' => true, 'IncludeRetElement' => true, ); } protected function &_sinceVersionPaths() { static $paths = array ( 'ListID' => 999.99, 'FullName' => 999.99, 'MaxReturned' => 0, 'ActiveStatus' => 999.99, 'FromModifiedDate' => 999.99, 'ToModifiedDate' => 999.99, 'NameFilter MatchCriterion' => 999.99, 'NameFilter Name' => 999.99, 'NameRangeFilter FromName' => 999.99, 'NameRangeFilter ToName' => 999.99, 'PaymentMethodType' => 7, 'IncludeRetElement' => 4, ); return $paths; } protected function &_isRepeatablePaths() { static $paths = array ( 'ListID' => true, 'FullName' => true, 'MaxReturned' => false, 'ActiveStatus' => false, 'FromModifiedDate' => false, 'ToModifiedDate' => false, 'NameFilter MatchCriterion' => false, 'NameFilter Name' => false, 'NameRangeFilter FromName' => false, 'NameRangeFilter ToName' => false, 'PaymentMethodType' => true, 'IncludeRetElement' => true, ); return $paths; } /* abstract protected function &_inLocalePaths() { static $paths = array( 'FirstName' => array( 'QBD', 'QBCA', 'QBUK', 'QBAU' ), 'LastName' => array( 'QBD', 'QBCA', 'QBUK', 'QBAU' ), ); return $paths; } */ protected function &_reorderPathsPaths() { static $paths = array ( 0 => 'ListID', 1 => 'FullName', 2 => 'MaxReturned', 3 => 'ActiveStatus', 4 => 'FromModifiedDate', 5 => 'ToModifiedDate', 6 => 'NameFilter MatchCriterion', 7 => 'NameFilter Name', 8 => 'NameRangeFilter FromName', 9 => 'NameRangeFilter ToName', 10 => 'PaymentMethodType', 11 => 'IncludeRetElement', ); return $paths; } } ?>
gpl-2.0
foucse/kamailio
obsolete/rls/rls_mod.h
1178
#ifndef __RLS_MOD_H #define __RLS_MOD_H #include "../../modules/tm/tm_load.h" #include "../../lib/srdb2/db.h" #include "rl_subscription.h" #include "../dialog/dlg_mod.h" #include "rls_data.h" #include <xcap/xcap_client.h> #include "../xcap/xcap_mod.h" extern struct tm_binds tmb; /** min interval for subscription expiration */ extern int rls_min_expiration; /** max interval for subscription expiration */ extern int rls_max_expiration; /* how often test subscriptions for expiration */ extern int rls_expiration_timer_period; /** default expiration timeout */ extern int rls_default_expiration; /** authorization parameters */ extern rls_auth_params_t rls_auth_params; extern int use_db; extern db_con_t* rls_db; /* database connection handle */ extern db_func_t rls_dbf; /* database functions */ extern dlg_func_t dlg_func; extern char *db_url; extern int reduce_xcap_needs; /* allows XCAP simulation with web server if possible */ extern int rls_timer_interval; extern fill_xcap_params_func fill_xcap_params; /* parameters for optimizations */ extern int max_notifications_at_once; extern int max_list_nesting_level; extern int rls_ignore_408_on_notify; #endif
gpl-2.0
stain/jdk8u
src/share/classes/javax/swing/text/DefaultStyledDocument.java
107201
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.text; import java.awt.Color; import java.awt.Font; import java.awt.font.TextAttribute; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.ArrayList; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import javax.swing.event.*; import javax.swing.undo.AbstractUndoableEdit; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoableEdit; import javax.swing.SwingUtilities; import static sun.swing.SwingUtilities2.IMPLIED_CR; /** * A document that can be marked up with character and paragraph * styles in a manner similar to the Rich Text Format. The element * structure for this document represents style crossings for * style runs. These style runs are mapped into a paragraph element * structure (which may reside in some other structure). The * style runs break at paragraph boundaries since logical styles are * assigned to paragraph boundaries. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Timothy Prinzing * @see Document * @see AbstractDocument */ public class DefaultStyledDocument extends AbstractDocument implements StyledDocument { /** * Constructs a styled document. * * @param c the container for the content * @param styles resources and style definitions which may * be shared across documents */ public DefaultStyledDocument(Content c, StyleContext styles) { super(c, styles); listeningStyles = new Vector<Style>(); buffer = new ElementBuffer(createDefaultRoot()); Style defaultStyle = styles.getStyle(StyleContext.DEFAULT_STYLE); setLogicalStyle(0, defaultStyle); } /** * Constructs a styled document with the default content * storage implementation and a shared set of styles. * * @param styles the styles */ public DefaultStyledDocument(StyleContext styles) { this(new GapContent(BUFFER_SIZE_DEFAULT), styles); } /** * Constructs a default styled document. This buffers * input content by a size of <em>BUFFER_SIZE_DEFAULT</em> * and has a style context that is scoped by the lifetime * of the document and is not shared with other documents. */ public DefaultStyledDocument() { this(new GapContent(BUFFER_SIZE_DEFAULT), new StyleContext()); } /** * Gets the default root element. * * @return the root * @see Document#getDefaultRootElement */ public Element getDefaultRootElement() { return buffer.getRootElement(); } /** * Initialize the document to reflect the given element * structure (i.e. the structure reported by the * <code>getDefaultRootElement</code> method. If the * document contained any data it will first be removed. */ protected void create(ElementSpec[] data) { try { if (getLength() != 0) { remove(0, getLength()); } writeLock(); // install the content Content c = getContent(); int n = data.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { ElementSpec es = data[i]; if (es.getLength() > 0) { sb.append(es.getArray(), es.getOffset(), es.getLength()); } } UndoableEdit cEdit = c.insertString(0, sb.toString()); // build the event and element structure int length = sb.length(); DefaultDocumentEvent evnt = new DefaultDocumentEvent(0, length, DocumentEvent.EventType.INSERT); evnt.addEdit(cEdit); buffer.create(length, data, evnt); // update bidi (possibly) super.insertUpdate(evnt, null); // notify the listeners evnt.end(); fireInsertUpdate(evnt); fireUndoableEditUpdate(new UndoableEditEvent(this, evnt)); } catch (BadLocationException ble) { throw new StateInvariantError("problem initializing"); } finally { writeUnlock(); } } /** * Inserts new elements in bulk. This is useful to allow * parsing with the document in an unlocked state and * prepare an element structure modification. This method * takes an array of tokens that describe how to update an * element structure so the time within a write lock can * be greatly reduced in an asynchronous update situation. * <p> * This method is thread safe, although most Swing methods * are not. Please see * <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency * in Swing</A> for more information. * * @param offset the starting offset &gt;= 0 * @param data the element data * @exception BadLocationException for an invalid starting offset */ protected void insert(int offset, ElementSpec[] data) throws BadLocationException { if (data == null || data.length == 0) { return; } try { writeLock(); // install the content Content c = getContent(); int n = data.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { ElementSpec es = data[i]; if (es.getLength() > 0) { sb.append(es.getArray(), es.getOffset(), es.getLength()); } } if (sb.length() == 0) { // Nothing to insert, bail. return; } UndoableEdit cEdit = c.insertString(offset, sb.toString()); // create event and build the element structure int length = sb.length(); DefaultDocumentEvent evnt = new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.INSERT); evnt.addEdit(cEdit); buffer.insert(offset, length, data, evnt); // update bidi (possibly) super.insertUpdate(evnt, null); // notify the listeners evnt.end(); fireInsertUpdate(evnt); fireUndoableEditUpdate(new UndoableEditEvent(this, evnt)); } finally { writeUnlock(); } } /** * Removes an element from this document. * * <p>The element is removed from its parent element, as well as * the text in the range identified by the element. If the * element isn't associated with the document, {@code * IllegalArgumentException} is thrown.</p> * * <p>As empty branch elements are not allowed in the document, if the * element is the sole child, its parent element is removed as well, * recursively. This means that when replacing all the children of a * particular element, new children should be added <em>before</em> * removing old children. * * <p>Element removal results in two events being fired, the * {@code DocumentEvent} for changes in element structure and {@code * UndoableEditEvent} for changes in document content.</p> * * <p>If the element contains end-of-content mark (the last {@code * "\n"} character in document), this character is not removed; * instead, preceding leaf element is extended to cover the * character. If the last leaf already ends with {@code "\n",} it is * included in content removal.</p> * * <p>If the element is {@code null,} {@code NullPointerException} is * thrown. If the element structure would become invalid after the removal, * for example if the element is the document root element, {@code * IllegalArgumentException} is thrown. If the current element structure is * invalid, {@code IllegalStateException} is thrown.</p> * * @param elem the element to remove * @throws NullPointerException if the element is {@code null} * @throws IllegalArgumentException if the element could not be removed * @throws IllegalStateException if the element structure is invalid * * @since 1.7 */ public void removeElement(Element elem) { try { writeLock(); removeElementImpl(elem); } finally { writeUnlock(); } } private void removeElementImpl(Element elem) { if (elem.getDocument() != this) { throw new IllegalArgumentException("element doesn't belong to document"); } BranchElement parent = (BranchElement) elem.getParentElement(); if (parent == null) { throw new IllegalArgumentException("can't remove the root element"); } int startOffset = elem.getStartOffset(); int removeFrom = startOffset; int endOffset = elem.getEndOffset(); int removeTo = endOffset; int lastEndOffset = getLength() + 1; Content content = getContent(); boolean atEnd = false; boolean isComposedText = Utilities.isComposedTextElement(elem); if (endOffset >= lastEndOffset) { // element includes the last "\n" character, needs special handling if (startOffset <= 0) { throw new IllegalArgumentException("can't remove the whole content"); } removeTo = lastEndOffset - 1; // last "\n" must not be removed try { if (content.getString(startOffset - 1, 1).charAt(0) == '\n') { removeFrom--; // preceding leaf ends with "\n", remove it } } catch (BadLocationException ble) { // can't happen throw new IllegalStateException(ble); } atEnd = true; } int length = removeTo - removeFrom; DefaultDocumentEvent dde = new DefaultDocumentEvent(removeFrom, length, DefaultDocumentEvent.EventType.REMOVE); UndoableEdit ue = null; // do not leave empty branch elements while (parent.getElementCount() == 1) { elem = parent; parent = (BranchElement) parent.getParentElement(); if (parent == null) { // shouldn't happen throw new IllegalStateException("invalid element structure"); } } Element[] removed = { elem }; Element[] added = {}; int index = parent.getElementIndex(startOffset); parent.replace(index, 1, added); dde.addEdit(new ElementEdit(parent, index, removed, added)); if (length > 0) { try { ue = content.remove(removeFrom, length); if (ue != null) { dde.addEdit(ue); } } catch (BadLocationException ble) { // can only happen if the element structure is severely broken throw new IllegalStateException(ble); } lastEndOffset -= length; } if (atEnd) { // preceding leaf element should be extended to cover orphaned "\n" Element prevLeaf = parent.getElement(parent.getElementCount() - 1); while ((prevLeaf != null) && !prevLeaf.isLeaf()) { prevLeaf = prevLeaf.getElement(prevLeaf.getElementCount() - 1); } if (prevLeaf == null) { // shouldn't happen throw new IllegalStateException("invalid element structure"); } int prevStartOffset = prevLeaf.getStartOffset(); BranchElement prevParent = (BranchElement) prevLeaf.getParentElement(); int prevIndex = prevParent.getElementIndex(prevStartOffset); Element newElem; newElem = createLeafElement(prevParent, prevLeaf.getAttributes(), prevStartOffset, lastEndOffset); Element[] prevRemoved = { prevLeaf }; Element[] prevAdded = { newElem }; prevParent.replace(prevIndex, 1, prevAdded); dde.addEdit(new ElementEdit(prevParent, prevIndex, prevRemoved, prevAdded)); } postRemoveUpdate(dde); dde.end(); fireRemoveUpdate(dde); if (! (isComposedText && (ue != null))) { // do not fire UndoabeEdit event for composed text edit (unsupported) fireUndoableEditUpdate(new UndoableEditEvent(this, dde)); } } /** * Adds a new style into the logical style hierarchy. Style attributes * resolve from bottom up so an attribute specified in a child * will override an attribute specified in the parent. * * @param nm the name of the style (must be unique within the * collection of named styles). The name may be null if the style * is unnamed, but the caller is responsible * for managing the reference returned as an unnamed style can't * be fetched by name. An unnamed style may be useful for things * like character attribute overrides such as found in a style * run. * @param parent the parent style. This may be null if unspecified * attributes need not be resolved in some other style. * @return the style */ public Style addStyle(String nm, Style parent) { StyleContext styles = (StyleContext) getAttributeContext(); return styles.addStyle(nm, parent); } /** * Removes a named style previously added to the document. * * @param nm the name of the style to remove */ public void removeStyle(String nm) { StyleContext styles = (StyleContext) getAttributeContext(); styles.removeStyle(nm); } /** * Fetches a named style previously added. * * @param nm the name of the style * @return the style */ public Style getStyle(String nm) { StyleContext styles = (StyleContext) getAttributeContext(); return styles.getStyle(nm); } /** * Fetches the list of of style names. * * @return all the style names */ public Enumeration<?> getStyleNames() { return ((StyleContext) getAttributeContext()).getStyleNames(); } /** * Sets the logical style to use for the paragraph at the * given position. If attributes aren't explicitly set * for character and paragraph attributes they will resolve * through the logical style assigned to the paragraph, which * in turn may resolve through some hierarchy completely * independent of the element hierarchy in the document. * <p> * This method is thread safe, although most Swing methods * are not. Please see * <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency * in Swing</A> for more information. * * @param pos the offset from the start of the document &gt;= 0 * @param s the logical style to assign to the paragraph, null if none */ public void setLogicalStyle(int pos, Style s) { Element paragraph = getParagraphElement(pos); if ((paragraph != null) && (paragraph instanceof AbstractElement)) { try { writeLock(); StyleChangeUndoableEdit edit = new StyleChangeUndoableEdit((AbstractElement)paragraph, s); ((AbstractElement)paragraph).setResolveParent(s); int p0 = paragraph.getStartOffset(); int p1 = paragraph.getEndOffset(); DefaultDocumentEvent e = new DefaultDocumentEvent(p0, p1 - p0, DocumentEvent.EventType.CHANGE); e.addEdit(edit); e.end(); fireChangedUpdate(e); fireUndoableEditUpdate(new UndoableEditEvent(this, e)); } finally { writeUnlock(); } } } /** * Fetches the logical style assigned to the paragraph * represented by the given position. * * @param p the location to translate to a paragraph * and determine the logical style assigned &gt;= 0. This * is an offset from the start of the document. * @return the style, null if none */ public Style getLogicalStyle(int p) { Style s = null; Element paragraph = getParagraphElement(p); if (paragraph != null) { AttributeSet a = paragraph.getAttributes(); AttributeSet parent = a.getResolveParent(); if (parent instanceof Style) { s = (Style) parent; } } return s; } /** * Sets attributes for some part of the document. * A write lock is held by this operation while changes * are being made, and a DocumentEvent is sent to the listeners * after the change has been successfully completed. * <p> * This method is thread safe, although most Swing methods * are not. Please see * <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency * in Swing</A> for more information. * * @param offset the offset in the document &gt;= 0 * @param length the length &gt;= 0 * @param s the attributes * @param replace true if the previous attributes should be replaced * before setting the new attributes */ public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) { if (length == 0) { return; } try { writeLock(); DefaultDocumentEvent changes = new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.CHANGE); // split elements that need it buffer.change(offset, length, changes); AttributeSet sCopy = s.copyAttributes(); // PENDING(prinz) - this isn't a very efficient way to iterate int lastEnd; for (int pos = offset; pos < (offset + length); pos = lastEnd) { Element run = getCharacterElement(pos); lastEnd = run.getEndOffset(); if (pos == lastEnd) { // offset + length beyond length of document, bail. break; } MutableAttributeSet attr = (MutableAttributeSet) run.getAttributes(); changes.addEdit(new AttributeUndoableEdit(run, sCopy, replace)); if (replace) { attr.removeAttributes(attr); } attr.addAttributes(s); } changes.end(); fireChangedUpdate(changes); fireUndoableEditUpdate(new UndoableEditEvent(this, changes)); } finally { writeUnlock(); } } /** * Sets attributes for a paragraph. * <p> * This method is thread safe, although most Swing methods * are not. Please see * <A HREF="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html">Concurrency * in Swing</A> for more information. * * @param offset the offset into the paragraph &gt;= 0 * @param length the number of characters affected &gt;= 0 * @param s the attributes * @param replace whether to replace existing attributes, or merge them */ public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace) { try { writeLock(); DefaultDocumentEvent changes = new DefaultDocumentEvent(offset, length, DocumentEvent.EventType.CHANGE); AttributeSet sCopy = s.copyAttributes(); // PENDING(prinz) - this assumes a particular element structure Element section = getDefaultRootElement(); int index0 = section.getElementIndex(offset); int index1 = section.getElementIndex(offset + ((length > 0) ? length - 1 : 0)); boolean isI18N = Boolean.TRUE.equals(getProperty(I18NProperty)); boolean hasRuns = false; for (int i = index0; i <= index1; i++) { Element paragraph = section.getElement(i); MutableAttributeSet attr = (MutableAttributeSet) paragraph.getAttributes(); changes.addEdit(new AttributeUndoableEdit(paragraph, sCopy, replace)); if (replace) { attr.removeAttributes(attr); } attr.addAttributes(s); if (isI18N && !hasRuns) { hasRuns = (attr.getAttribute(TextAttribute.RUN_DIRECTION) != null); } } if (hasRuns) { updateBidi( changes ); } changes.end(); fireChangedUpdate(changes); fireUndoableEditUpdate(new UndoableEditEvent(this, changes)); } finally { writeUnlock(); } } /** * Gets the paragraph element at the offset <code>pos</code>. * A paragraph consists of at least one child Element, which is usually * a leaf. * * @param pos the starting offset &gt;= 0 * @return the element */ public Element getParagraphElement(int pos) { Element e; for (e = getDefaultRootElement(); ! e.isLeaf(); ) { int index = e.getElementIndex(pos); e = e.getElement(index); } if(e != null) return e.getParentElement(); return e; } /** * Gets a character element based on a position. * * @param pos the position in the document &gt;= 0 * @return the element */ public Element getCharacterElement(int pos) { Element e; for (e = getDefaultRootElement(); ! e.isLeaf(); ) { int index = e.getElementIndex(pos); e = e.getElement(index); } return e; } // --- local methods ------------------------------------------------- /** * Updates document structure as a result of text insertion. This * will happen within a write lock. This implementation simply * parses the inserted content for line breaks and builds up a set * of instructions for the element buffer. * * @param chng a description of the document change * @param attr the attributes */ protected void insertUpdate(DefaultDocumentEvent chng, AttributeSet attr) { int offset = chng.getOffset(); int length = chng.getLength(); if (attr == null) { attr = SimpleAttributeSet.EMPTY; } // Paragraph attributes should come from point after insertion. // You really only notice this when inserting at a paragraph // boundary. Element paragraph = getParagraphElement(offset + length); AttributeSet pattr = paragraph.getAttributes(); // Character attributes should come from actual insertion point. Element pParagraph = getParagraphElement(offset); Element run = pParagraph.getElement(pParagraph.getElementIndex (offset)); int endOffset = offset + length; boolean insertingAtBoundry = (run.getEndOffset() == endOffset); AttributeSet cattr = run.getAttributes(); try { Segment s = new Segment(); Vector<ElementSpec> parseBuffer = new Vector<ElementSpec>(); ElementSpec lastStartSpec = null; boolean insertingAfterNewline = false; short lastStartDirection = ElementSpec.OriginateDirection; // Check if the previous character was a newline. if (offset > 0) { getText(offset - 1, 1, s); if (s.array[s.offset] == '\n') { // Inserting after a newline. insertingAfterNewline = true; lastStartDirection = createSpecsForInsertAfterNewline (paragraph, pParagraph, pattr, parseBuffer, offset, endOffset); for(int counter = parseBuffer.size() - 1; counter >= 0; counter--) { ElementSpec spec = parseBuffer.elementAt(counter); if(spec.getType() == ElementSpec.StartTagType) { lastStartSpec = spec; break; } } } } // If not inserting after a new line, pull the attributes for // new paragraphs from the paragraph under the insertion point. if(!insertingAfterNewline) pattr = pParagraph.getAttributes(); getText(offset, length, s); char[] txt = s.array; int n = s.offset + s.count; int lastOffset = s.offset; for (int i = s.offset; i < n; i++) { if (txt[i] == '\n') { int breakOffset = i + 1; parseBuffer.addElement( new ElementSpec(attr, ElementSpec.ContentType, breakOffset - lastOffset)); parseBuffer.addElement( new ElementSpec(null, ElementSpec.EndTagType)); lastStartSpec = new ElementSpec(pattr, ElementSpec. StartTagType); parseBuffer.addElement(lastStartSpec); lastOffset = breakOffset; } } if (lastOffset < n) { parseBuffer.addElement( new ElementSpec(attr, ElementSpec.ContentType, n - lastOffset)); } ElementSpec first = parseBuffer.firstElement(); int docLength = getLength(); // Check for join previous of first content. if(first.getType() == ElementSpec.ContentType && cattr.isEqual(attr)) { first.setDirection(ElementSpec.JoinPreviousDirection); } // Do a join fracture/next for last start spec if necessary. if(lastStartSpec != null) { if(insertingAfterNewline) { lastStartSpec.setDirection(lastStartDirection); } // Join to the fracture if NOT inserting at the end // (fracture only happens when not inserting at end of // paragraph). else if(pParagraph.getEndOffset() != endOffset) { lastStartSpec.setDirection(ElementSpec. JoinFractureDirection); } // Join to next if parent of pParagraph has another // element after pParagraph, and it isn't a leaf. else { Element parent = pParagraph.getParentElement(); int pParagraphIndex = parent.getElementIndex(offset); if((pParagraphIndex + 1) < parent.getElementCount() && !parent.getElement(pParagraphIndex + 1).isLeaf()) { lastStartSpec.setDirection(ElementSpec. JoinNextDirection); } } } // Do a JoinNext for last spec if it is content, it doesn't // already have a direction set, no new paragraphs have been // inserted or a new paragraph has been inserted and its join // direction isn't originate, and the element at endOffset // is a leaf. if(insertingAtBoundry && endOffset < docLength) { ElementSpec last = parseBuffer.lastElement(); if(last.getType() == ElementSpec.ContentType && last.getDirection() != ElementSpec.JoinPreviousDirection && ((lastStartSpec == null && (paragraph == pParagraph || insertingAfterNewline)) || (lastStartSpec != null && lastStartSpec.getDirection() != ElementSpec.OriginateDirection))) { Element nextRun = paragraph.getElement(paragraph. getElementIndex(endOffset)); // Don't try joining to a branch! if(nextRun.isLeaf() && attr.isEqual(nextRun.getAttributes())) { last.setDirection(ElementSpec.JoinNextDirection); } } } // If not inserting at boundary and there is going to be a // fracture, then can join next on last content if cattr // matches the new attributes. else if(!insertingAtBoundry && lastStartSpec != null && lastStartSpec.getDirection() == ElementSpec.JoinFractureDirection) { ElementSpec last = parseBuffer.lastElement(); if(last.getType() == ElementSpec.ContentType && last.getDirection() != ElementSpec.JoinPreviousDirection && attr.isEqual(cattr)) { last.setDirection(ElementSpec.JoinNextDirection); } } // Check for the composed text element. If it is, merge the character attributes // into this element as well. if (Utilities.isComposedTextAttributeDefined(attr)) { MutableAttributeSet mattr = (MutableAttributeSet) attr; mattr.addAttributes(cattr); mattr.addAttribute(AbstractDocument.ElementNameAttribute, AbstractDocument.ContentElementName); // Assure that the composed text element is named properly // and doesn't have the CR attribute defined. mattr.addAttribute(StyleConstants.NameAttribute, AbstractDocument.ContentElementName); if (mattr.isDefined(IMPLIED_CR)) { mattr.removeAttribute(IMPLIED_CR); } } ElementSpec[] spec = new ElementSpec[parseBuffer.size()]; parseBuffer.copyInto(spec); buffer.insert(offset, length, spec, chng); } catch (BadLocationException bl) { } super.insertUpdate( chng, attr ); } /** * This is called by insertUpdate when inserting after a new line. * It generates, in <code>parseBuffer</code>, ElementSpecs that will * position the stack in <code>paragraph</code>.<p> * It returns the direction the last StartSpec should have (this don't * necessarily create the last start spec). */ short createSpecsForInsertAfterNewline(Element paragraph, Element pParagraph, AttributeSet pattr, Vector<ElementSpec> parseBuffer, int offset, int endOffset) { // Need to find the common parent of pParagraph and paragraph. if(paragraph.getParentElement() == pParagraph.getParentElement()) { // The simple (and common) case that pParagraph and // paragraph have the same parent. ElementSpec spec = new ElementSpec(pattr, ElementSpec.EndTagType); parseBuffer.addElement(spec); spec = new ElementSpec(pattr, ElementSpec.StartTagType); parseBuffer.addElement(spec); if(pParagraph.getEndOffset() != endOffset) return ElementSpec.JoinFractureDirection; Element parent = pParagraph.getParentElement(); if((parent.getElementIndex(offset) + 1) < parent.getElementCount()) return ElementSpec.JoinNextDirection; } else { // Will only happen for text with more than 2 levels. // Find the common parent of a paragraph and pParagraph Vector<Element> leftParents = new Vector<Element>(); Vector<Element> rightParents = new Vector<Element>(); Element e = pParagraph; while(e != null) { leftParents.addElement(e); e = e.getParentElement(); } e = paragraph; int leftIndex = -1; while(e != null && (leftIndex = leftParents.indexOf(e)) == -1) { rightParents.addElement(e); e = e.getParentElement(); } if(e != null) { // e identifies the common parent. // Build the ends. for(int counter = 0; counter < leftIndex; counter++) { parseBuffer.addElement(new ElementSpec (null, ElementSpec.EndTagType)); } // And the starts. ElementSpec spec; for(int counter = rightParents.size() - 1; counter >= 0; counter--) { spec = new ElementSpec(rightParents.elementAt(counter).getAttributes(), ElementSpec.StartTagType); if(counter > 0) spec.setDirection(ElementSpec.JoinNextDirection); parseBuffer.addElement(spec); } // If there are right parents, then we generated starts // down the right subtree and there will be an element to // join to. if(rightParents.size() > 0) return ElementSpec.JoinNextDirection; // No right subtree, e.getElement(endOffset) is a // leaf. There will be a facture. return ElementSpec.JoinFractureDirection; } // else: Could throw an exception here, but should never get here! } return ElementSpec.OriginateDirection; } /** * Updates document structure as a result of text removal. * * @param chng a description of the document change */ protected void removeUpdate(DefaultDocumentEvent chng) { super.removeUpdate(chng); buffer.remove(chng.getOffset(), chng.getLength(), chng); } /** * Creates the root element to be used to represent the * default document structure. * * @return the element base */ protected AbstractElement createDefaultRoot() { // grabs a write-lock for this initialization and // abandon it during initialization so in normal // operation we can detect an illegitimate attempt // to mutate attributes. writeLock(); BranchElement section = new SectionElement(); BranchElement paragraph = new BranchElement(section, null); LeafElement brk = new LeafElement(paragraph, null, 0, 1); Element[] buff = new Element[1]; buff[0] = brk; paragraph.replace(0, 0, buff); buff[0] = paragraph; section.replace(0, 0, buff); writeUnlock(); return section; } /** * Gets the foreground color from an attribute set. * * @param attr the attribute set * @return the color */ public Color getForeground(AttributeSet attr) { StyleContext styles = (StyleContext) getAttributeContext(); return styles.getForeground(attr); } /** * Gets the background color from an attribute set. * * @param attr the attribute set * @return the color */ public Color getBackground(AttributeSet attr) { StyleContext styles = (StyleContext) getAttributeContext(); return styles.getBackground(attr); } /** * Gets the font from an attribute set. * * @param attr the attribute set * @return the font */ public Font getFont(AttributeSet attr) { StyleContext styles = (StyleContext) getAttributeContext(); return styles.getFont(attr); } /** * Called when any of this document's styles have changed. * Subclasses may wish to be intelligent about what gets damaged. * * @param style The Style that has changed. */ protected void styleChanged(Style style) { // Only propagate change updated if have content if (getLength() != 0) { // lazily create a ChangeUpdateRunnable if (updateRunnable == null) { updateRunnable = new ChangeUpdateRunnable(); } // We may get a whole batch of these at once, so only // queue the runnable if it is not already pending synchronized(updateRunnable) { if (!updateRunnable.isPending) { SwingUtilities.invokeLater(updateRunnable); updateRunnable.isPending = true; } } } } /** * Adds a document listener for notification of any changes. * * @param listener the listener * @see Document#addDocumentListener */ public void addDocumentListener(DocumentListener listener) { synchronized(listeningStyles) { int oldDLCount = listenerList.getListenerCount (DocumentListener.class); super.addDocumentListener(listener); if (oldDLCount == 0) { if (styleContextChangeListener == null) { styleContextChangeListener = createStyleContextChangeListener(); } if (styleContextChangeListener != null) { StyleContext styles = (StyleContext)getAttributeContext(); List<ChangeListener> staleListeners = AbstractChangeHandler.getStaleListeners(styleContextChangeListener); for (ChangeListener l: staleListeners) { styles.removeChangeListener(l); } styles.addChangeListener(styleContextChangeListener); } updateStylesListeningTo(); } } } /** * Removes a document listener. * * @param listener the listener * @see Document#removeDocumentListener */ public void removeDocumentListener(DocumentListener listener) { synchronized(listeningStyles) { super.removeDocumentListener(listener); if (listenerList.getListenerCount(DocumentListener.class) == 0) { for (int counter = listeningStyles.size() - 1; counter >= 0; counter--) { listeningStyles.elementAt(counter). removeChangeListener(styleChangeListener); } listeningStyles.removeAllElements(); if (styleContextChangeListener != null) { StyleContext styles = (StyleContext)getAttributeContext(); styles.removeChangeListener(styleContextChangeListener); } } } } /** * Returns a new instance of StyleChangeHandler. */ ChangeListener createStyleChangeListener() { return new StyleChangeHandler(this); } /** * Returns a new instance of StyleContextChangeHandler. */ ChangeListener createStyleContextChangeListener() { return new StyleContextChangeHandler(this); } /** * Adds a ChangeListener to new styles, and removes ChangeListener from * old styles. */ void updateStylesListeningTo() { synchronized(listeningStyles) { StyleContext styles = (StyleContext)getAttributeContext(); if (styleChangeListener == null) { styleChangeListener = createStyleChangeListener(); } if (styleChangeListener != null && styles != null) { Enumeration styleNames = styles.getStyleNames(); Vector v = (Vector)listeningStyles.clone(); listeningStyles.removeAllElements(); List<ChangeListener> staleListeners = AbstractChangeHandler.getStaleListeners(styleChangeListener); while (styleNames.hasMoreElements()) { String name = (String)styleNames.nextElement(); Style aStyle = styles.getStyle(name); int index = v.indexOf(aStyle); listeningStyles.addElement(aStyle); if (index == -1) { for (ChangeListener l: staleListeners) { aStyle.removeChangeListener(l); } aStyle.addChangeListener(styleChangeListener); } else { v.removeElementAt(index); } } for (int counter = v.size() - 1; counter >= 0; counter--) { Style aStyle = (Style)v.elementAt(counter); aStyle.removeChangeListener(styleChangeListener); } if (listeningStyles.size() == 0) { styleChangeListener = null; } } } } private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { listeningStyles = new Vector<Style>(); s.defaultReadObject(); // Reinstall style listeners. if (styleContextChangeListener == null && listenerList.getListenerCount(DocumentListener.class) > 0) { styleContextChangeListener = createStyleContextChangeListener(); if (styleContextChangeListener != null) { StyleContext styles = (StyleContext)getAttributeContext(); styles.addChangeListener(styleContextChangeListener); } updateStylesListeningTo(); } } // --- member variables ----------------------------------------------------------- /** * The default size of the initial content buffer. */ public static final int BUFFER_SIZE_DEFAULT = 4096; protected ElementBuffer buffer; /** Styles listening to. */ private transient Vector<Style> listeningStyles; /** Listens to Styles. */ private transient ChangeListener styleChangeListener; /** Listens to Styles. */ private transient ChangeListener styleContextChangeListener; /** Run to create a change event for the document */ private transient ChangeUpdateRunnable updateRunnable; /** * Default root element for a document... maps out the * paragraphs/lines contained. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ protected class SectionElement extends BranchElement { /** * Creates a new SectionElement. */ public SectionElement() { super(null, null); } /** * Gets the name of the element. * * @return the name */ public String getName() { return SectionElementName; } } /** * Specification for building elements. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ public static class ElementSpec { /** * A possible value for getType. This specifies * that this record type is a start tag and * represents markup that specifies the start * of an element. */ public static final short StartTagType = 1; /** * A possible value for getType. This specifies * that this record type is a end tag and * represents markup that specifies the end * of an element. */ public static final short EndTagType = 2; /** * A possible value for getType. This specifies * that this record type represents content. */ public static final short ContentType = 3; /** * A possible value for getDirection. This specifies * that the data associated with this record should * be joined to what precedes it. */ public static final short JoinPreviousDirection = 4; /** * A possible value for getDirection. This specifies * that the data associated with this record should * be joined to what follows it. */ public static final short JoinNextDirection = 5; /** * A possible value for getDirection. This specifies * that the data associated with this record should * be used to originate a new element. This would be * the normal value. */ public static final short OriginateDirection = 6; /** * A possible value for getDirection. This specifies * that the data associated with this record should * be joined to the fractured element. */ public static final short JoinFractureDirection = 7; /** * Constructor useful for markup when the markup will not * be stored in the document. * * @param a the attributes for the element * @param type the type of the element (StartTagType, EndTagType, * ContentType) */ public ElementSpec(AttributeSet a, short type) { this(a, type, null, 0, 0); } /** * Constructor for parsing inside the document when * the data has already been added, but len information * is needed. * * @param a the attributes for the element * @param type the type of the element (StartTagType, EndTagType, * ContentType) * @param len the length &gt;= 0 */ public ElementSpec(AttributeSet a, short type, int len) { this(a, type, null, 0, len); } /** * Constructor for creating a spec externally for batch * input of content and markup into the document. * * @param a the attributes for the element * @param type the type of the element (StartTagType, EndTagType, * ContentType) * @param txt the text for the element * @param offs the offset into the text &gt;= 0 * @param len the length of the text &gt;= 0 */ public ElementSpec(AttributeSet a, short type, char[] txt, int offs, int len) { attr = a; this.type = type; this.data = txt; this.offs = offs; this.len = len; this.direction = OriginateDirection; } /** * Sets the element type. * * @param type the type of the element (StartTagType, EndTagType, * ContentType) */ public void setType(short type) { this.type = type; } /** * Gets the element type. * * @return the type of the element (StartTagType, EndTagType, * ContentType) */ public short getType() { return type; } /** * Sets the direction. * * @param direction the direction (JoinPreviousDirection, * JoinNextDirection) */ public void setDirection(short direction) { this.direction = direction; } /** * Gets the direction. * * @return the direction (JoinPreviousDirection, JoinNextDirection) */ public short getDirection() { return direction; } /** * Gets the element attributes. * * @return the attribute set */ public AttributeSet getAttributes() { return attr; } /** * Gets the array of characters. * * @return the array */ public char[] getArray() { return data; } /** * Gets the starting offset. * * @return the offset &gt;= 0 */ public int getOffset() { return offs; } /** * Gets the length. * * @return the length &gt;= 0 */ public int getLength() { return len; } /** * Converts the element to a string. * * @return the string */ public String toString() { String tlbl = "??"; String plbl = "??"; switch(type) { case StartTagType: tlbl = "StartTag"; break; case ContentType: tlbl = "Content"; break; case EndTagType: tlbl = "EndTag"; break; } switch(direction) { case JoinPreviousDirection: plbl = "JoinPrevious"; break; case JoinNextDirection: plbl = "JoinNext"; break; case OriginateDirection: plbl = "Originate"; break; case JoinFractureDirection: plbl = "Fracture"; break; } return tlbl + ":" + plbl + ":" + getLength(); } private AttributeSet attr; private int len; private short type; private short direction; private int offs; private char[] data; } /** * Class to manage changes to the element * hierarchy. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ public class ElementBuffer implements Serializable { /** * Creates a new ElementBuffer. * * @param root the root element * @since 1.4 */ public ElementBuffer(Element root) { this.root = root; changes = new Vector<ElemChanges>(); path = new Stack<ElemChanges>(); } /** * Gets the root element. * * @return the root element */ public Element getRootElement() { return root; } /** * Inserts new content. * * @param offset the starting offset &gt;= 0 * @param length the length &gt;= 0 * @param data the data to insert * @param de the event capturing this edit */ public void insert(int offset, int length, ElementSpec[] data, DefaultDocumentEvent de) { if (length == 0) { // Nothing was inserted, no structure change. return; } insertOp = true; beginEdits(offset, length); insertUpdate(data); endEdits(de); insertOp = false; } void create(int length, ElementSpec[] data, DefaultDocumentEvent de) { insertOp = true; beginEdits(offset, length); // PENDING(prinz) this needs to be fixed to create a new // root element as well, but requires changes to the // DocumentEvent to inform the views that there is a new // root element. // Recreate the ending fake element to have the correct offsets. Element elem = root; int index = elem.getElementIndex(0); while (! elem.isLeaf()) { Element child = elem.getElement(index); push(elem, index); elem = child; index = elem.getElementIndex(0); } ElemChanges ec = path.peek(); Element child = ec.parent.getElement(ec.index); ec.added.addElement(createLeafElement(ec.parent, child.getAttributes(), getLength(), child.getEndOffset())); ec.removed.addElement(child); while (path.size() > 1) { pop(); } int n = data.length; // Reset the root elements attributes. AttributeSet newAttrs = null; if (n > 0 && data[0].getType() == ElementSpec.StartTagType) { newAttrs = data[0].getAttributes(); } if (newAttrs == null) { newAttrs = SimpleAttributeSet.EMPTY; } MutableAttributeSet attr = (MutableAttributeSet)root. getAttributes(); de.addEdit(new AttributeUndoableEdit(root, newAttrs, true)); attr.removeAttributes(attr); attr.addAttributes(newAttrs); // fold in the specified subtree for (int i = 1; i < n; i++) { insertElement(data[i]); } // pop the remaining path while (path.size() != 0) { pop(); } endEdits(de); insertOp = false; } /** * Removes content. * * @param offset the starting offset &gt;= 0 * @param length the length &gt;= 0 * @param de the event capturing this edit */ public void remove(int offset, int length, DefaultDocumentEvent de) { beginEdits(offset, length); removeUpdate(); endEdits(de); } /** * Changes content. * * @param offset the starting offset &gt;= 0 * @param length the length &gt;= 0 * @param de the event capturing this edit */ public void change(int offset, int length, DefaultDocumentEvent de) { beginEdits(offset, length); changeUpdate(); endEdits(de); } /** * Inserts an update into the document. * * @param data the elements to insert */ protected void insertUpdate(ElementSpec[] data) { // push the path Element elem = root; int index = elem.getElementIndex(offset); while (! elem.isLeaf()) { Element child = elem.getElement(index); push(elem, (child.isLeaf() ? index : index+1)); elem = child; index = elem.getElementIndex(offset); } // Build a copy of the original path. insertPath = new ElemChanges[path.size()]; path.copyInto(insertPath); // Haven't created the fracture yet. createdFracture = false; // Insert the first content. int i; recreateLeafs = false; if(data[0].getType() == ElementSpec.ContentType) { insertFirstContent(data); pos += data[0].getLength(); i = 1; } else { fractureDeepestLeaf(data); i = 0; } // fold in the specified subtree int n = data.length; for (; i < n; i++) { insertElement(data[i]); } // Fracture, if we haven't yet. if(!createdFracture) fracture(-1); // pop the remaining path while (path.size() != 0) { pop(); } // Offset the last index if necessary. if(offsetLastIndex && offsetLastIndexOnReplace) { insertPath[insertPath.length - 1].index++; } // Make sure an edit is going to be created for each of the // original path items that have a change. for(int counter = insertPath.length - 1; counter >= 0; counter--) { ElemChanges change = insertPath[counter]; if(change.parent == fracturedParent) change.added.addElement(fracturedChild); if((change.added.size() > 0 || change.removed.size() > 0) && !changes.contains(change)) { // PENDING(sky): Do I need to worry about order here? changes.addElement(change); } } // An insert at 0 with an initial end implies some elements // will have no children (the bottomost leaf would have length 0) // this will find what element need to be removed and remove it. if (offset == 0 && fracturedParent != null && data[0].getType() == ElementSpec.EndTagType) { int counter = 0; while (counter < data.length && data[counter].getType() == ElementSpec.EndTagType) { counter++; } ElemChanges change = insertPath[insertPath.length - counter - 1]; change.removed.insertElementAt(change.parent.getElement (--change.index), 0); } } /** * Updates the element structure in response to a removal from the * associated sequence in the document. Any elements consumed by the * span of the removal are removed. */ protected void removeUpdate() { removeElements(root, offset, offset + length); } /** * Updates the element structure in response to a change in the * document. */ protected void changeUpdate() { boolean didEnd = split(offset, length); if (! didEnd) { // need to do the other end while (path.size() != 0) { pop(); } split(offset + length, 0); } while (path.size() != 0) { pop(); } } boolean split(int offs, int len) { boolean splitEnd = false; // push the path Element e = root; int index = e.getElementIndex(offs); while (! e.isLeaf()) { push(e, index); e = e.getElement(index); index = e.getElementIndex(offs); } ElemChanges ec = path.peek(); Element child = ec.parent.getElement(ec.index); // make sure there is something to do... if the // offset is already at a boundary then there is // nothing to do. if (child.getStartOffset() < offs && offs < child.getEndOffset()) { // we need to split, now see if the other end is within // the same parent. int index0 = ec.index; int index1 = index0; if (((offs + len) < ec.parent.getEndOffset()) && (len != 0)) { // it's a range split in the same parent index1 = ec.parent.getElementIndex(offs+len); if (index1 == index0) { // it's a three-way split ec.removed.addElement(child); e = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), offs); ec.added.addElement(e); e = createLeafElement(ec.parent, child.getAttributes(), offs, offs + len); ec.added.addElement(e); e = createLeafElement(ec.parent, child.getAttributes(), offs + len, child.getEndOffset()); ec.added.addElement(e); return true; } else { child = ec.parent.getElement(index1); if ((offs + len) == child.getStartOffset()) { // end is already on a boundary index1 = index0; } } splitEnd = true; } // split the first location pos = offs; child = ec.parent.getElement(index0); ec.removed.addElement(child); e = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), pos); ec.added.addElement(e); e = createLeafElement(ec.parent, child.getAttributes(), pos, child.getEndOffset()); ec.added.addElement(e); // pick up things in the middle for (int i = index0 + 1; i < index1; i++) { child = ec.parent.getElement(i); ec.removed.addElement(child); ec.added.addElement(child); } if (index1 != index0) { child = ec.parent.getElement(index1); pos = offs + len; ec.removed.addElement(child); e = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), pos); ec.added.addElement(e); e = createLeafElement(ec.parent, child.getAttributes(), pos, child.getEndOffset()); ec.added.addElement(e); } } return splitEnd; } /** * Creates the UndoableEdit record for the edits made * in the buffer. */ void endEdits(DefaultDocumentEvent de) { int n = changes.size(); for (int i = 0; i < n; i++) { ElemChanges ec = changes.elementAt(i); Element[] removed = new Element[ec.removed.size()]; ec.removed.copyInto(removed); Element[] added = new Element[ec.added.size()]; ec.added.copyInto(added); int index = ec.index; ((BranchElement) ec.parent).replace(index, removed.length, added); ElementEdit ee = new ElementEdit(ec.parent, index, removed, added); de.addEdit(ee); } changes.removeAllElements(); path.removeAllElements(); /* for (int i = 0; i < n; i++) { ElemChanges ec = (ElemChanges) changes.elementAt(i); System.err.print("edited: " + ec.parent + " at: " + ec.index + " removed " + ec.removed.size()); if (ec.removed.size() > 0) { int r0 = ((Element) ec.removed.firstElement()).getStartOffset(); int r1 = ((Element) ec.removed.lastElement()).getEndOffset(); System.err.print("[" + r0 + "," + r1 + "]"); } System.err.print(" added " + ec.added.size()); if (ec.added.size() > 0) { int p0 = ((Element) ec.added.firstElement()).getStartOffset(); int p1 = ((Element) ec.added.lastElement()).getEndOffset(); System.err.print("[" + p0 + "," + p1 + "]"); } System.err.println(""); } */ } /** * Initialize the buffer */ void beginEdits(int offset, int length) { this.offset = offset; this.length = length; this.endOffset = offset + length; pos = offset; if (changes == null) { changes = new Vector<ElemChanges>(); } else { changes.removeAllElements(); } if (path == null) { path = new Stack<ElemChanges>(); } else { path.removeAllElements(); } fracturedParent = null; fracturedChild = null; offsetLastIndex = offsetLastIndexOnReplace = false; } /** * Pushes a new element onto the stack that represents * the current path. * @param record Whether or not the push should be * recorded as an element change or not. * @param isFracture true if pushing on an element that was created * as the result of a fracture. */ void push(Element e, int index, boolean isFracture) { ElemChanges ec = new ElemChanges(e, index, isFracture); path.push(ec); } void push(Element e, int index) { push(e, index, false); } void pop() { ElemChanges ec = path.peek(); path.pop(); if ((ec.added.size() > 0) || (ec.removed.size() > 0)) { changes.addElement(ec); } else if (! path.isEmpty()) { Element e = ec.parent; if(e.getElementCount() == 0) { // if we pushed a branch element that didn't get // used, make sure its not marked as having been added. ec = path.peek(); ec.added.removeElement(e); } } } /** * move the current offset forward by n. */ void advance(int n) { pos += n; } void insertElement(ElementSpec es) { ElemChanges ec = path.peek(); switch(es.getType()) { case ElementSpec.StartTagType: switch(es.getDirection()) { case ElementSpec.JoinNextDirection: // Don't create a new element, use the existing one // at the specified location. Element parent = ec.parent.getElement(ec.index); if(parent.isLeaf()) { // This happens if inserting into a leaf, followed // by a join next where next sibling is not a leaf. if((ec.index + 1) < ec.parent.getElementCount()) parent = ec.parent.getElement(ec.index + 1); else throw new StateInvariantError("Join next to leaf"); } // Not really a fracture, but need to treat it like // one so that content join next will work correctly. // We can do this because there will never be a join // next followed by a join fracture. push(parent, 0, true); break; case ElementSpec.JoinFractureDirection: if(!createdFracture) { // Should always be something on the stack! fracture(path.size() - 1); } // If parent isn't a fracture, fracture will be // fracturedChild. if(!ec.isFracture) { push(fracturedChild, 0, true); } else // Parent is a fracture, use 1st element. push(ec.parent.getElement(0), 0, true); break; default: Element belem = createBranchElement(ec.parent, es.getAttributes()); ec.added.addElement(belem); push(belem, 0); break; } break; case ElementSpec.EndTagType: pop(); break; case ElementSpec.ContentType: int len = es.getLength(); if (es.getDirection() != ElementSpec.JoinNextDirection) { Element leaf = createLeafElement(ec.parent, es.getAttributes(), pos, pos + len); ec.added.addElement(leaf); } else { // JoinNext on tail is only applicable if last element // and attributes come from that of first element. // With a little extra testing it would be possible // to NOT due this again, as more than likely fracture() // created this element. if(!ec.isFracture) { Element first = null; if(insertPath != null) { for(int counter = insertPath.length - 1; counter >= 0; counter--) { if(insertPath[counter] == ec) { if(counter != (insertPath.length - 1)) first = ec.parent.getElement(ec.index); break; } } } if(first == null) first = ec.parent.getElement(ec.index + 1); Element leaf = createLeafElement(ec.parent, first. getAttributes(), pos, first.getEndOffset()); ec.added.addElement(leaf); ec.removed.addElement(first); } else { // Parent was fractured element. Element first = ec.parent.getElement(0); Element leaf = createLeafElement(ec.parent, first. getAttributes(), pos, first.getEndOffset()); ec.added.addElement(leaf); ec.removed.addElement(first); } } pos += len; break; } } /** * Remove the elements from <code>elem</code> in range * <code>rmOffs0</code>, <code>rmOffs1</code>. This uses * <code>canJoin</code> and <code>join</code> to handle joining * the endpoints of the insertion. * * @return true if elem will no longer have any elements. */ boolean removeElements(Element elem, int rmOffs0, int rmOffs1) { if (! elem.isLeaf()) { // update path for changes int index0 = elem.getElementIndex(rmOffs0); int index1 = elem.getElementIndex(rmOffs1); push(elem, index0); ElemChanges ec = path.peek(); // if the range is contained by one element, // we just forward the request if (index0 == index1) { Element child0 = elem.getElement(index0); if(rmOffs0 <= child0.getStartOffset() && rmOffs1 >= child0.getEndOffset()) { // Element totally removed. ec.removed.addElement(child0); } else if(removeElements(child0, rmOffs0, rmOffs1)) { ec.removed.addElement(child0); } } else { // the removal range spans elements. If we can join // the two endpoints, do it. Otherwise we remove the // interior and forward to the endpoints. Element child0 = elem.getElement(index0); Element child1 = elem.getElement(index1); boolean containsOffs1 = (rmOffs1 < elem.getEndOffset()); if (containsOffs1 && canJoin(child0, child1)) { // remove and join for (int i = index0; i <= index1; i++) { ec.removed.addElement(elem.getElement(i)); } Element e = join(elem, child0, child1, rmOffs0, rmOffs1); ec.added.addElement(e); } else { // remove interior and forward int rmIndex0 = index0 + 1; int rmIndex1 = index1 - 1; if (child0.getStartOffset() == rmOffs0 || (index0 == 0 && child0.getStartOffset() > rmOffs0 && child0.getEndOffset() <= rmOffs1)) { // start element completely consumed child0 = null; rmIndex0 = index0; } if (!containsOffs1) { child1 = null; rmIndex1++; } else if (child1.getStartOffset() == rmOffs1) { // end element not touched child1 = null; } if (rmIndex0 <= rmIndex1) { ec.index = rmIndex0; } for (int i = rmIndex0; i <= rmIndex1; i++) { ec.removed.addElement(elem.getElement(i)); } if (child0 != null) { if(removeElements(child0, rmOffs0, rmOffs1)) { ec.removed.insertElementAt(child0, 0); ec.index = index0; } } if (child1 != null) { if(removeElements(child1, rmOffs0, rmOffs1)) { ec.removed.addElement(child1); } } } } // publish changes pop(); // Return true if we no longer have any children. if(elem.getElementCount() == (ec.removed.size() - ec.added.size())) { return true; } } return false; } /** * Can the two given elements be coelesced together * into one element? */ boolean canJoin(Element e0, Element e1) { if ((e0 == null) || (e1 == null)) { return false; } // Don't join a leaf to a branch. boolean leaf0 = e0.isLeaf(); boolean leaf1 = e1.isLeaf(); if(leaf0 != leaf1) { return false; } if (leaf0) { // Only join leaves if the attributes match, otherwise // style information will be lost. return e0.getAttributes().isEqual(e1.getAttributes()); } // Only join non-leafs if the names are equal. This may result // in loss of style information, but this is typically acceptable // for non-leafs. String name0 = e0.getName(); String name1 = e1.getName(); if (name0 != null) { return name0.equals(name1); } if (name1 != null) { return name1.equals(name0); } // Both names null, treat as equal. return true; } /** * Joins the two elements carving out a hole for the * given removed range. */ Element join(Element p, Element left, Element right, int rmOffs0, int rmOffs1) { if (left.isLeaf() && right.isLeaf()) { return createLeafElement(p, left.getAttributes(), left.getStartOffset(), right.getEndOffset()); } else if ((!left.isLeaf()) && (!right.isLeaf())) { // join two branch elements. This copies the children before // the removal range on the left element, and after the removal // range on the right element. The two elements on the edge // are joined if possible and needed. Element to = createBranchElement(p, left.getAttributes()); int ljIndex = left.getElementIndex(rmOffs0); int rjIndex = right.getElementIndex(rmOffs1); Element lj = left.getElement(ljIndex); if (lj.getStartOffset() >= rmOffs0) { lj = null; } Element rj = right.getElement(rjIndex); if (rj.getStartOffset() == rmOffs1) { rj = null; } Vector<Element> children = new Vector<Element>(); // transfer the left for (int i = 0; i < ljIndex; i++) { children.addElement(clone(to, left.getElement(i))); } // transfer the join/middle if (canJoin(lj, rj)) { Element e = join(to, lj, rj, rmOffs0, rmOffs1); children.addElement(e); } else { if (lj != null) { children.addElement(cloneAsNecessary(to, lj, rmOffs0, rmOffs1)); } if (rj != null) { children.addElement(cloneAsNecessary(to, rj, rmOffs0, rmOffs1)); } } // transfer the right int n = right.getElementCount(); for (int i = (rj == null) ? rjIndex : rjIndex + 1; i < n; i++) { children.addElement(clone(to, right.getElement(i))); } // install the children Element[] c = new Element[children.size()]; children.copyInto(c); ((BranchElement)to).replace(0, 0, c); return to; } else { throw new StateInvariantError( "No support to join leaf element with non-leaf element"); } } /** * Creates a copy of this element, with a different * parent. * * @param parent the parent element * @param clonee the element to be cloned * @return the copy */ public Element clone(Element parent, Element clonee) { if (clonee.isLeaf()) { return createLeafElement(parent, clonee.getAttributes(), clonee.getStartOffset(), clonee.getEndOffset()); } Element e = createBranchElement(parent, clonee.getAttributes()); int n = clonee.getElementCount(); Element[] children = new Element[n]; for (int i = 0; i < n; i++) { children[i] = clone(e, clonee.getElement(i)); } ((BranchElement)e).replace(0, 0, children); return e; } /** * Creates a copy of this element, with a different * parent. Children of this element included in the * removal range will be discarded. */ Element cloneAsNecessary(Element parent, Element clonee, int rmOffs0, int rmOffs1) { if (clonee.isLeaf()) { return createLeafElement(parent, clonee.getAttributes(), clonee.getStartOffset(), clonee.getEndOffset()); } Element e = createBranchElement(parent, clonee.getAttributes()); int n = clonee.getElementCount(); ArrayList<Element> childrenList = new ArrayList<Element>(n); for (int i = 0; i < n; i++) { Element elem = clonee.getElement(i); if (elem.getStartOffset() < rmOffs0 || elem.getEndOffset() > rmOffs1) { childrenList.add(cloneAsNecessary(e, elem, rmOffs0, rmOffs1)); } } Element[] children = new Element[childrenList.size()]; children = childrenList.toArray(children); ((BranchElement)e).replace(0, 0, children); return e; } /** * Determines if a fracture needs to be performed. A fracture * can be thought of as moving the right part of a tree to a * new location, where the right part is determined by what has * been inserted. <code>depth</code> is used to indicate a * JoinToFracture is needed to an element at a depth * of <code>depth</code>. Where the root is 0, 1 is the children * of the root... * <p>This will invoke <code>fractureFrom</code> if it is determined * a fracture needs to happen. */ void fracture(int depth) { int cLength = insertPath.length; int lastIndex = -1; boolean needRecreate = recreateLeafs; ElemChanges lastChange = insertPath[cLength - 1]; // Use childAltered to determine when a child has been altered, // that is the point of insertion is less than the element count. boolean childAltered = ((lastChange.index + 1) < lastChange.parent.getElementCount()); int deepestAlteredIndex = (needRecreate) ? cLength : -1; int lastAlteredIndex = cLength - 1; createdFracture = true; // Determine where to start recreating from. // Start at - 2, as first one is indicated by recreateLeafs and // childAltered. for(int counter = cLength - 2; counter >= 0; counter--) { ElemChanges change = insertPath[counter]; if(change.added.size() > 0 || counter == depth) { lastIndex = counter; if(!needRecreate && childAltered) { needRecreate = true; if(deepestAlteredIndex == -1) deepestAlteredIndex = lastAlteredIndex + 1; } } if(!childAltered && change.index < change.parent.getElementCount()) { childAltered = true; lastAlteredIndex = counter; } } if(needRecreate) { // Recreate all children to right of parent starting // at lastIndex. if(lastIndex == -1) lastIndex = cLength - 1; fractureFrom(insertPath, lastIndex, deepestAlteredIndex); } } /** * Recreates the elements to the right of the insertion point. * This starts at <code>startIndex</code> in <code>changed</code>, * and calls duplicate to duplicate existing elements. * This will also duplicate the elements along the insertion * point, until a depth of <code>endFractureIndex</code> is * reached, at which point only the elements to the right of * the insertion point are duplicated. */ void fractureFrom(ElemChanges[] changed, int startIndex, int endFractureIndex) { // Recreate the element representing the inserted index. ElemChanges change = changed[startIndex]; Element child; Element newChild; int changeLength = changed.length; if((startIndex + 1) == changeLength) child = change.parent.getElement(change.index); else child = change.parent.getElement(change.index - 1); if(child.isLeaf()) { newChild = createLeafElement(change.parent, child.getAttributes(), Math.max(endOffset, child.getStartOffset()), child.getEndOffset()); } else { newChild = createBranchElement(change.parent, child.getAttributes()); } fracturedParent = change.parent; fracturedChild = newChild; // Recreate all the elements to the right of the // insertion point. Element parent = newChild; while(++startIndex < endFractureIndex) { boolean isEnd = ((startIndex + 1) == endFractureIndex); boolean isEndLeaf = ((startIndex + 1) == changeLength); // Create the newChild, a duplicate of the elment at // index. This isn't done if isEnd and offsetLastIndex are true // indicating a join previous was done. change = changed[startIndex]; // Determine the child to duplicate, won't have to duplicate // if at end of fracture, or offseting index. if(isEnd) { if(offsetLastIndex || !isEndLeaf) child = null; else child = change.parent.getElement(change.index); } else { child = change.parent.getElement(change.index - 1); } // Duplicate it. if(child != null) { if(child.isLeaf()) { newChild = createLeafElement(parent, child.getAttributes(), Math.max(endOffset, child.getStartOffset()), child.getEndOffset()); } else { newChild = createBranchElement(parent, child.getAttributes()); } } else newChild = null; // Recreate the remaining children (there may be none). int kidsToMove = change.parent.getElementCount() - change.index; Element[] kids; int moveStartIndex; int kidStartIndex = 1; if(newChild == null) { // Last part of fracture. if(isEndLeaf) { kidsToMove--; moveStartIndex = change.index + 1; } else { moveStartIndex = change.index; } kidStartIndex = 0; kids = new Element[kidsToMove]; } else { if(!isEnd) { // Branch. kidsToMove++; moveStartIndex = change.index; } else { // Last leaf, need to recreate part of it. moveStartIndex = change.index + 1; } kids = new Element[kidsToMove]; kids[0] = newChild; } for(int counter = kidStartIndex; counter < kidsToMove; counter++) { Element toMove =change.parent.getElement(moveStartIndex++); kids[counter] = recreateFracturedElement(parent, toMove); change.removed.addElement(toMove); } ((BranchElement)parent).replace(0, 0, kids); parent = newChild; } } /** * Recreates <code>toDuplicate</code>. This is called when an * element needs to be created as the result of an insertion. This * will recurse and create all the children. This is similar to * <code>clone</code>, but deteremines the offsets differently. */ Element recreateFracturedElement(Element parent, Element toDuplicate) { if(toDuplicate.isLeaf()) { return createLeafElement(parent, toDuplicate.getAttributes(), Math.max(toDuplicate.getStartOffset(), endOffset), toDuplicate.getEndOffset()); } // Not a leaf Element newParent = createBranchElement(parent, toDuplicate. getAttributes()); int childCount = toDuplicate.getElementCount(); Element[] newKids = new Element[childCount]; for(int counter = 0; counter < childCount; counter++) { newKids[counter] = recreateFracturedElement(newParent, toDuplicate.getElement(counter)); } ((BranchElement)newParent).replace(0, 0, newKids); return newParent; } /** * Splits the bottommost leaf in <code>path</code>. * This is called from insert when the first element is NOT content. */ void fractureDeepestLeaf(ElementSpec[] specs) { // Split the bottommost leaf. It will be recreated elsewhere. ElemChanges ec = path.peek(); Element child = ec.parent.getElement(ec.index); // Inserts at offset 0 do not need to recreate child (it would // have a length of 0!). if (offset != 0) { Element newChild = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), offset); ec.added.addElement(newChild); } ec.removed.addElement(child); if(child.getEndOffset() != endOffset) recreateLeafs = true; else offsetLastIndex = true; } /** * Inserts the first content. This needs to be separate to handle * joining. */ void insertFirstContent(ElementSpec[] specs) { ElementSpec firstSpec = specs[0]; ElemChanges ec = path.peek(); Element child = ec.parent.getElement(ec.index); int firstEndOffset = offset + firstSpec.getLength(); boolean isOnlyContent = (specs.length == 1); switch(firstSpec.getDirection()) { case ElementSpec.JoinPreviousDirection: if(child.getEndOffset() != firstEndOffset && !isOnlyContent) { // Create the left split part containing new content. Element newE = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), firstEndOffset); ec.added.addElement(newE); ec.removed.addElement(child); // Remainder will be created later. if(child.getEndOffset() != endOffset) recreateLeafs = true; else offsetLastIndex = true; } else { offsetLastIndex = true; offsetLastIndexOnReplace = true; } // else Inserted at end, and is total length. // Update index incase something added/removed. break; case ElementSpec.JoinNextDirection: if(offset != 0) { // Recreate the first element, its offset will have // changed. Element newE = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), offset); ec.added.addElement(newE); // Recreate the second, merge part. We do no checking // to see if JoinNextDirection is valid here! Element nextChild = ec.parent.getElement(ec.index + 1); if(isOnlyContent) newE = createLeafElement(ec.parent, nextChild. getAttributes(), offset, nextChild.getEndOffset()); else newE = createLeafElement(ec.parent, nextChild. getAttributes(), offset, firstEndOffset); ec.added.addElement(newE); ec.removed.addElement(child); ec.removed.addElement(nextChild); } // else nothin to do. // PENDING: if !isOnlyContent could raise here! break; default: // Inserted into middle, need to recreate split left // new content, and split right. if(child.getStartOffset() != offset) { Element newE = createLeafElement(ec.parent, child.getAttributes(), child.getStartOffset(), offset); ec.added.addElement(newE); } ec.removed.addElement(child); // new content Element newE = createLeafElement(ec.parent, firstSpec.getAttributes(), offset, firstEndOffset); ec.added.addElement(newE); if(child.getEndOffset() != endOffset) { // Signals need to recreate right split later. recreateLeafs = true; } else { offsetLastIndex = true; } break; } } Element root; transient int pos; // current position transient int offset; transient int length; transient int endOffset; transient Vector<ElemChanges> changes; transient Stack<ElemChanges> path; transient boolean insertOp; transient boolean recreateLeafs; // For insert. /** For insert, path to inserted elements. */ transient ElemChanges[] insertPath; /** Only for insert, set to true when the fracture has been created. */ transient boolean createdFracture; /** Parent that contains the fractured child. */ transient Element fracturedParent; /** Fractured child. */ transient Element fracturedChild; /** Used to indicate when fracturing that the last leaf should be * skipped. */ transient boolean offsetLastIndex; /** Used to indicate that the parent of the deepest leaf should * offset the index by 1 when adding/removing elements in an * insert. */ transient boolean offsetLastIndexOnReplace; /* * Internal record used to hold element change specifications */ class ElemChanges { ElemChanges(Element parent, int index, boolean isFracture) { this.parent = parent; this.index = index; this.isFracture = isFracture; added = new Vector<Element>(); removed = new Vector<Element>(); } public String toString() { return "added: " + added + "\nremoved: " + removed + "\n"; } Element parent; int index; Vector<Element> added; Vector<Element> removed; boolean isFracture; } } /** * An UndoableEdit used to remember AttributeSet changes to an * Element. */ public static class AttributeUndoableEdit extends AbstractUndoableEdit { public AttributeUndoableEdit(Element element, AttributeSet newAttributes, boolean isReplacing) { super(); this.element = element; this.newAttributes = newAttributes; this.isReplacing = isReplacing; // If not replacing, it may be more efficient to only copy the // changed values... copy = element.getAttributes().copyAttributes(); } /** * Redoes a change. * * @exception CannotRedoException if the change cannot be redone */ public void redo() throws CannotRedoException { super.redo(); MutableAttributeSet as = (MutableAttributeSet)element .getAttributes(); if(isReplacing) as.removeAttributes(as); as.addAttributes(newAttributes); } /** * Undoes a change. * * @exception CannotUndoException if the change cannot be undone */ public void undo() throws CannotUndoException { super.undo(); MutableAttributeSet as = (MutableAttributeSet)element.getAttributes(); as.removeAttributes(as); as.addAttributes(copy); } // AttributeSet containing additional entries, must be non-mutable! protected AttributeSet newAttributes; // Copy of the AttributeSet the Element contained. protected AttributeSet copy; // true if all the attributes in the element were removed first. protected boolean isReplacing; // Efected Element. protected Element element; } /** * UndoableEdit for changing the resolve parent of an Element. */ static class StyleChangeUndoableEdit extends AbstractUndoableEdit { public StyleChangeUndoableEdit(AbstractElement element, Style newStyle) { super(); this.element = element; this.newStyle = newStyle; oldStyle = element.getResolveParent(); } /** * Redoes a change. * * @exception CannotRedoException if the change cannot be redone */ public void redo() throws CannotRedoException { super.redo(); element.setResolveParent(newStyle); } /** * Undoes a change. * * @exception CannotUndoException if the change cannot be undone */ public void undo() throws CannotUndoException { super.undo(); element.setResolveParent(oldStyle); } /** Element to change resolve parent of. */ protected AbstractElement element; /** New style. */ protected Style newStyle; /** Old style, before setting newStyle. */ protected AttributeSet oldStyle; } /** * Base class for style change handlers with support for stale objects detection. */ abstract static class AbstractChangeHandler implements ChangeListener { /* This has an implicit reference to the handler object. */ private class DocReference extends WeakReference<DefaultStyledDocument> { DocReference(DefaultStyledDocument d, ReferenceQueue<DefaultStyledDocument> q) { super(d, q); } /** * Return a reference to the style change handler object. */ ChangeListener getListener() { return AbstractChangeHandler.this; } } /** Class-specific reference queues. */ private final static Map<Class, ReferenceQueue<DefaultStyledDocument>> queueMap = new HashMap<Class, ReferenceQueue<DefaultStyledDocument>>(); /** A weak reference to the document object. */ private DocReference doc; AbstractChangeHandler(DefaultStyledDocument d) { Class c = getClass(); ReferenceQueue<DefaultStyledDocument> q; synchronized (queueMap) { q = queueMap.get(c); if (q == null) { q = new ReferenceQueue<DefaultStyledDocument>(); queueMap.put(c, q); } } doc = new DocReference(d, q); } /** * Return a list of stale change listeners. * * A change listener becomes "stale" when its document is cleaned by GC. */ static List<ChangeListener> getStaleListeners(ChangeListener l) { List<ChangeListener> staleListeners = new ArrayList<ChangeListener>(); ReferenceQueue<DefaultStyledDocument> q = queueMap.get(l.getClass()); if (q != null) { DocReference r; synchronized (q) { while ((r = (DocReference) q.poll()) != null) { staleListeners.add(r.getListener()); } } } return staleListeners; } /** * The ChangeListener wrapper which guards against dead documents. */ public void stateChanged(ChangeEvent e) { DefaultStyledDocument d = doc.get(); if (d != null) { fireStateChanged(d, e); } } /** Run the actual class-specific stateChanged() method. */ abstract void fireStateChanged(DefaultStyledDocument d, ChangeEvent e); } /** * Added to all the Styles. When instances of this receive a * stateChanged method, styleChanged is invoked. */ static class StyleChangeHandler extends AbstractChangeHandler { StyleChangeHandler(DefaultStyledDocument d) { super(d); } void fireStateChanged(DefaultStyledDocument d, ChangeEvent e) { Object source = e.getSource(); if (source instanceof Style) { d.styleChanged((Style) source); } else { d.styleChanged(null); } } } /** * Added to the StyleContext. When the StyleContext changes, this invokes * <code>updateStylesListeningTo</code>. */ static class StyleContextChangeHandler extends AbstractChangeHandler { StyleContextChangeHandler(DefaultStyledDocument d) { super(d); } void fireStateChanged(DefaultStyledDocument d, ChangeEvent e) { d.updateStylesListeningTo(); } } /** * When run this creates a change event for the complete document * and fires it. */ class ChangeUpdateRunnable implements Runnable { boolean isPending = false; public void run() { synchronized(this) { isPending = false; } try { writeLock(); DefaultDocumentEvent dde = new DefaultDocumentEvent(0, getLength(), DocumentEvent.EventType.CHANGE); dde.end(); fireChangedUpdate(dde); } finally { writeUnlock(); } } } }
gpl-2.0
armenrz/adempiere
migration/352a-353a/postgresql/327_BF2319604.sql
282
-- Nov 21, 2008 12:14:32 PM SGT -- [ 2319604 ] Wrong SQL where clause in Inbound Asset Entry window UPDATE AD_Tab SET WhereClause='A_Depreciation_Entry.A_Entry_Type = ''New''',Updated=TO_TIMESTAMP('2008-11-21 12:14:31','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Tab_ID=53166 ;
gpl-2.0
koct9i/linux
drivers/media/radio/radio-keene.c
11425
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2012 Hans Verkuil <[email protected]> */ /* kernel includes */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/input.h> #include <linux/videodev2.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-event.h> #include <linux/usb.h> #include <linux/mutex.h> /* driver and module definitions */ MODULE_AUTHOR("Hans Verkuil <[email protected]>"); MODULE_DESCRIPTION("Keene FM Transmitter driver"); MODULE_LICENSE("GPL"); /* Actually, it advertises itself as a Logitech */ #define USB_KEENE_VENDOR 0x046d #define USB_KEENE_PRODUCT 0x0a0e /* Probably USB_TIMEOUT should be modified in module parameter */ #define BUFFER_LENGTH 8 #define USB_TIMEOUT 500 /* Frequency limits in MHz */ #define FREQ_MIN 76U #define FREQ_MAX 108U #define FREQ_MUL 16000U /* USB Device ID List */ static const struct usb_device_id usb_keene_device_table[] = { {USB_DEVICE_AND_INTERFACE_INFO(USB_KEENE_VENDOR, USB_KEENE_PRODUCT, USB_CLASS_HID, 0, 0) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, usb_keene_device_table); struct keene_device { struct usb_device *usbdev; struct usb_interface *intf; struct video_device vdev; struct v4l2_device v4l2_dev; struct v4l2_ctrl_handler hdl; struct mutex lock; u8 *buffer; unsigned curfreq; u8 tx; u8 pa; bool stereo; bool muted; bool preemph_75_us; }; static inline struct keene_device *to_keene_dev(struct v4l2_device *v4l2_dev) { return container_of(v4l2_dev, struct keene_device, v4l2_dev); } /* Set frequency (if non-0), PA, mute and turn on/off the FM transmitter. */ static int keene_cmd_main(struct keene_device *radio, unsigned freq, bool play) { unsigned short freq_send = freq ? (freq - 76 * 16000) / 800 : 0; int ret; radio->buffer[0] = 0x00; radio->buffer[1] = 0x50; radio->buffer[2] = (freq_send >> 8) & 0xff; radio->buffer[3] = freq_send & 0xff; radio->buffer[4] = radio->pa; /* If bit 4 is set, then tune to the frequency. If bit 3 is set, then unmute; if bit 2 is set, then mute. If bit 1 is set, then enter idle mode; if bit 0 is set, then enter transmit mode. */ radio->buffer[5] = (radio->muted ? 4 : 8) | (play ? 1 : 2) | (freq ? 0x10 : 0); radio->buffer[6] = 0x00; radio->buffer[7] = 0x00; ret = usb_control_msg(radio->usbdev, usb_sndctrlpipe(radio->usbdev, 0), 9, 0x21, 0x200, 2, radio->buffer, BUFFER_LENGTH, USB_TIMEOUT); if (ret < 0) { dev_warn(&radio->vdev.dev, "%s failed (%d)\n", __func__, ret); return ret; } if (freq) radio->curfreq = freq; return 0; } /* Set TX, stereo and preemphasis mode (50 us vs 75 us). */ static int keene_cmd_set(struct keene_device *radio) { int ret; radio->buffer[0] = 0x00; radio->buffer[1] = 0x51; radio->buffer[2] = radio->tx; /* If bit 0 is set, then transmit mono, otherwise stereo. If bit 2 is set, then enable 75 us preemphasis, otherwise it is 50 us. */ radio->buffer[3] = (radio->stereo ? 0 : 1) | (radio->preemph_75_us ? 4 : 0); radio->buffer[4] = 0x00; radio->buffer[5] = 0x00; radio->buffer[6] = 0x00; radio->buffer[7] = 0x00; ret = usb_control_msg(radio->usbdev, usb_sndctrlpipe(radio->usbdev, 0), 9, 0x21, 0x200, 2, radio->buffer, BUFFER_LENGTH, USB_TIMEOUT); if (ret < 0) { dev_warn(&radio->vdev.dev, "%s failed (%d)\n", __func__, ret); return ret; } return 0; } /* Handle unplugging the device. * We call video_unregister_device in any case. * The last function called in this procedure is * usb_keene_device_release. */ static void usb_keene_disconnect(struct usb_interface *intf) { struct keene_device *radio = to_keene_dev(usb_get_intfdata(intf)); mutex_lock(&radio->lock); usb_set_intfdata(intf, NULL); video_unregister_device(&radio->vdev); v4l2_device_disconnect(&radio->v4l2_dev); mutex_unlock(&radio->lock); v4l2_device_put(&radio->v4l2_dev); } static int usb_keene_suspend(struct usb_interface *intf, pm_message_t message) { struct keene_device *radio = to_keene_dev(usb_get_intfdata(intf)); return keene_cmd_main(radio, 0, false); } static int usb_keene_resume(struct usb_interface *intf) { struct keene_device *radio = to_keene_dev(usb_get_intfdata(intf)); mdelay(50); keene_cmd_set(radio); keene_cmd_main(radio, radio->curfreq, true); return 0; } static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *v) { struct keene_device *radio = video_drvdata(file); strscpy(v->driver, "radio-keene", sizeof(v->driver)); strscpy(v->card, "Keene FM Transmitter", sizeof(v->card)); usb_make_path(radio->usbdev, v->bus_info, sizeof(v->bus_info)); v->device_caps = V4L2_CAP_RADIO | V4L2_CAP_MODULATOR; v->capabilities = v->device_caps | V4L2_CAP_DEVICE_CAPS; return 0; } static int vidioc_g_modulator(struct file *file, void *priv, struct v4l2_modulator *v) { struct keene_device *radio = video_drvdata(file); if (v->index > 0) return -EINVAL; strscpy(v->name, "FM", sizeof(v->name)); v->rangelow = FREQ_MIN * FREQ_MUL; v->rangehigh = FREQ_MAX * FREQ_MUL; v->txsubchans = radio->stereo ? V4L2_TUNER_SUB_STEREO : V4L2_TUNER_SUB_MONO; v->capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO; return 0; } static int vidioc_s_modulator(struct file *file, void *priv, const struct v4l2_modulator *v) { struct keene_device *radio = video_drvdata(file); if (v->index > 0) return -EINVAL; radio->stereo = (v->txsubchans == V4L2_TUNER_SUB_STEREO); return keene_cmd_set(radio); } static int vidioc_s_frequency(struct file *file, void *priv, const struct v4l2_frequency *f) { struct keene_device *radio = video_drvdata(file); unsigned freq = f->frequency; if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO) return -EINVAL; freq = clamp(freq, FREQ_MIN * FREQ_MUL, FREQ_MAX * FREQ_MUL); return keene_cmd_main(radio, freq, true); } static int vidioc_g_frequency(struct file *file, void *priv, struct v4l2_frequency *f) { struct keene_device *radio = video_drvdata(file); if (f->tuner != 0) return -EINVAL; f->type = V4L2_TUNER_RADIO; f->frequency = radio->curfreq; return 0; } static int keene_s_ctrl(struct v4l2_ctrl *ctrl) { static const u8 db2tx[] = { /* -15, -12, -9, -6, -3, 0 dB */ 0x03, 0x13, 0x02, 0x12, 0x22, 0x32, /* 3, 6, 9, 12, 15, 18 dB */ 0x21, 0x31, 0x20, 0x30, 0x40, 0x50 }; struct keene_device *radio = container_of(ctrl->handler, struct keene_device, hdl); switch (ctrl->id) { case V4L2_CID_AUDIO_MUTE: radio->muted = ctrl->val; return keene_cmd_main(radio, 0, true); case V4L2_CID_TUNE_POWER_LEVEL: /* To go from dBuV to the register value we apply the following formula: */ radio->pa = (ctrl->val - 71) * 100 / 62; return keene_cmd_main(radio, 0, true); case V4L2_CID_TUNE_PREEMPHASIS: radio->preemph_75_us = ctrl->val == V4L2_PREEMPHASIS_75_uS; return keene_cmd_set(radio); case V4L2_CID_AUDIO_COMPRESSION_GAIN: radio->tx = db2tx[(ctrl->val - (s32)ctrl->minimum) / (s32)ctrl->step]; return keene_cmd_set(radio); } return -EINVAL; } /* File system interface */ static const struct v4l2_file_operations usb_keene_fops = { .owner = THIS_MODULE, .open = v4l2_fh_open, .release = v4l2_fh_release, .poll = v4l2_ctrl_poll, .unlocked_ioctl = video_ioctl2, }; static const struct v4l2_ctrl_ops keene_ctrl_ops = { .s_ctrl = keene_s_ctrl, }; static const struct v4l2_ioctl_ops usb_keene_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_g_modulator = vidioc_g_modulator, .vidioc_s_modulator = vidioc_s_modulator, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_frequency = vidioc_s_frequency, .vidioc_log_status = v4l2_ctrl_log_status, .vidioc_subscribe_event = v4l2_ctrl_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, }; static void usb_keene_video_device_release(struct v4l2_device *v4l2_dev) { struct keene_device *radio = to_keene_dev(v4l2_dev); /* free rest memory */ v4l2_ctrl_handler_free(&radio->hdl); kfree(radio->buffer); kfree(radio); } /* check if the device is present and register with v4l and usb if it is */ static int usb_keene_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct keene_device *radio; struct v4l2_ctrl_handler *hdl; int retval = 0; /* * The Keene FM transmitter USB device has the same USB ID as * the Logitech AudioHub Speaker, but it should ignore the hid. * Check if the name is that of the Keene device. * If not, then someone connected the AudioHub and we shouldn't * attempt to handle this driver. * For reference: the product name of the AudioHub is * "AudioHub Speaker". */ if (dev->product && strcmp(dev->product, "B-LINK USB Audio ")) return -ENODEV; radio = kzalloc(sizeof(struct keene_device), GFP_KERNEL); if (radio) radio->buffer = kmalloc(BUFFER_LENGTH, GFP_KERNEL); if (!radio || !radio->buffer) { dev_err(&intf->dev, "kmalloc for keene_device failed\n"); kfree(radio); retval = -ENOMEM; goto err; } hdl = &radio->hdl; v4l2_ctrl_handler_init(hdl, 4); v4l2_ctrl_new_std(hdl, &keene_ctrl_ops, V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0); v4l2_ctrl_new_std_menu(hdl, &keene_ctrl_ops, V4L2_CID_TUNE_PREEMPHASIS, V4L2_PREEMPHASIS_75_uS, 1, V4L2_PREEMPHASIS_50_uS); v4l2_ctrl_new_std(hdl, &keene_ctrl_ops, V4L2_CID_TUNE_POWER_LEVEL, 84, 118, 1, 118); v4l2_ctrl_new_std(hdl, &keene_ctrl_ops, V4L2_CID_AUDIO_COMPRESSION_GAIN, -15, 18, 3, 0); radio->pa = 118; radio->tx = 0x32; radio->stereo = true; if (hdl->error) { retval = hdl->error; v4l2_ctrl_handler_free(hdl); goto err_v4l2; } retval = v4l2_device_register(&intf->dev, &radio->v4l2_dev); if (retval < 0) { dev_err(&intf->dev, "couldn't register v4l2_device\n"); goto err_v4l2; } mutex_init(&radio->lock); radio->v4l2_dev.ctrl_handler = hdl; radio->v4l2_dev.release = usb_keene_video_device_release; strscpy(radio->vdev.name, radio->v4l2_dev.name, sizeof(radio->vdev.name)); radio->vdev.v4l2_dev = &radio->v4l2_dev; radio->vdev.fops = &usb_keene_fops; radio->vdev.ioctl_ops = &usb_keene_ioctl_ops; radio->vdev.lock = &radio->lock; radio->vdev.release = video_device_release_empty; radio->vdev.vfl_dir = VFL_DIR_TX; radio->usbdev = interface_to_usbdev(intf); radio->intf = intf; usb_set_intfdata(intf, &radio->v4l2_dev); video_set_drvdata(&radio->vdev, radio); /* at least 11ms is needed in order to settle hardware */ msleep(20); keene_cmd_main(radio, 95.16 * FREQ_MUL, false); retval = video_register_device(&radio->vdev, VFL_TYPE_RADIO, -1); if (retval < 0) { dev_err(&intf->dev, "could not register video device\n"); goto err_vdev; } v4l2_ctrl_handler_setup(hdl); dev_info(&intf->dev, "V4L2 device registered as %s\n", video_device_node_name(&radio->vdev)); return 0; err_vdev: v4l2_device_unregister(&radio->v4l2_dev); err_v4l2: kfree(radio->buffer); kfree(radio); err: return retval; } /* USB subsystem interface */ static struct usb_driver usb_keene_driver = { .name = "radio-keene", .probe = usb_keene_probe, .disconnect = usb_keene_disconnect, .id_table = usb_keene_device_table, .suspend = usb_keene_suspend, .resume = usb_keene_resume, .reset_resume = usb_keene_resume, }; module_usb_driver(usb_keene_driver);
gpl-2.0
PIPplware/xbmc
xbmc/cores/RetroPlayer/streams/memory/LinearMemoryStream.h
2099
/* * Copyright (C) 2016-2018 Team Kodi * This file is part of Kodi - https://kodi.tv * * SPDX-License-Identifier: GPL-2.0-or-later * See LICENSES/README.md for more information. */ #pragma once #include "IMemoryStream.h" #include <memory> #include <stdint.h> namespace KODI { namespace RETRO { class CLinearMemoryStream : public IMemoryStream { public: CLinearMemoryStream(); virtual ~CLinearMemoryStream() = default; // partial implementation of IMemoryStream virtual void Init(size_t frameSize, uint64_t maxFrameCount) override; virtual void Reset() override; virtual size_t FrameSize() const override { return m_frameSize; } virtual uint64_t MaxFrameCount() const override { return m_maxFrames; } virtual void SetMaxFrameCount(uint64_t maxFrameCount) override; virtual uint8_t* BeginFrame() override; virtual void SubmitFrame() override; virtual const uint8_t* CurrentFrame() const override; virtual uint64_t FutureFramesAvailable() const override { return 0; } virtual uint64_t AdvanceFrames(uint64_t frameCount) override { return 0; } virtual uint64_t PastFramesAvailable() const override = 0; virtual uint64_t RewindFrames(uint64_t frameCount) override = 0; virtual uint64_t GetFrameCounter() const override { return m_currentFrameHistory; } virtual void SetFrameCounter(uint64_t frameCount) override { m_currentFrameHistory = frameCount; } protected: virtual void SubmitFrameInternal() = 0; virtual void CullPastFrames(uint64_t frameCount) = 0; // Helper function uint64_t BufferSize() const; size_t m_paddedFrameSize; uint64_t m_maxFrames; /** * Simple double-buffering. After XORing the two states, the next becomes * the current, and the current becomes a buffer for the next call to * CGameClient::Serialize(). */ std::unique_ptr<uint32_t[]> m_currentFrame; std::unique_ptr<uint32_t[]> m_nextFrame; bool m_bHasCurrentFrame; bool m_bHasNextFrame; uint64_t m_currentFrameHistory; private: size_t m_frameSize; }; } }
gpl-2.0
isengartz/food
tmp/install_5662784dc4d75/admin/plugins/vmpayment/amazon/fields/ipnurl.php
1639
<?php /** * * Amazon payment plugin * * @author Valerie Isaksen * @version $Id: ipnurl.php 8703 2015-02-15 17:11:16Z alatak $ * @package VirtueMart * @subpackage payment * Copyright (C) 2004-2015 Virtuemart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://virtuemart.net */ // Check to ensure this file is within the rest of the framework defined('JPATH_BASE') or die(); jimport('joomla.form.formfield'); class JFormFieldIpnURL extends JFormField { var $type = 'ipnurl'; protected function getInput() { $cid = vRequest::getvar('cid', NULL, 'array'); if (is_Array($cid)) { $virtuemart_paymentmethod_id = $cid[0]; } else { $virtuemart_paymentmethod_id = $cid; } $http = JURI::root() . 'index.php?option=com_virtuemart&view=vmplg&task=notify&nt=ipn&tmpl=component&pm=' . $virtuemart_paymentmethod_id; $https = str_replace('http://', 'https://', $http); $string = '<div class="' . $this->class . '">'; $string .= '<div class="ipn-sandbox">' . $http . ' <br /></div>'; if (strcmp($https,$http) !==0){ $string .= '<div class="ipn-sandbox">' . vmText::_('VMPAYMENT_AMAZON_OR') . '<br /></div>'; $string .= $https; } $string .= "</div>"; return $string; } }
gpl-2.0
paulalesius/kernel-devel
sound/usb/quirks.c
38888
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/slab.h> #include <linux/usb.h> #include <linux/usb/audio.h> #include <linux/usb/midi.h> #include <sound/control.h> #include <sound/core.h> #include <sound/info.h> #include <sound/pcm.h> #include "usbaudio.h" #include "card.h" #include "mixer.h" #include "mixer_quirks.h" #include "midi.h" #include "quirks.h" #include "helper.h" #include "endpoint.h" #include "pcm.h" #include "clock.h" #include "stream.h" /* * handle the quirks for the contained interfaces */ static int create_composite_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk_comp) { int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber; const struct snd_usb_audio_quirk *quirk; int err; for (quirk = quirk_comp->data; quirk->ifnum >= 0; ++quirk) { iface = usb_ifnum_to_if(chip->dev, quirk->ifnum); if (!iface) continue; if (quirk->ifnum != probed_ifnum && usb_interface_claimed(iface)) continue; err = snd_usb_create_quirk(chip, iface, driver, quirk); if (err < 0) return err; } for (quirk = quirk_comp->data; quirk->ifnum >= 0; ++quirk) { iface = usb_ifnum_to_if(chip->dev, quirk->ifnum); if (!iface) continue; if (quirk->ifnum != probed_ifnum && !usb_interface_claimed(iface)) usb_driver_claim_interface(driver, iface, (void *)-1L); } return 0; } static int ignore_interface_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { return 0; } /* * Allow alignment on audio sub-slot (channel samples) rather than * on audio slots (audio frames) */ static int create_align_transfer_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { chip->txfr_quirk = 1; return 1; /* Continue with creating streams and mixer */ } static int create_any_midi_quirk(struct snd_usb_audio *chip, struct usb_interface *intf, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { return snd_usbmidi_create(chip->card, intf, &chip->midi_list, quirk); } /* * create a stream for an interface with proper descriptors */ static int create_standard_audio_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; int err; if (chip->usb_id == USB_ID(0x1686, 0x00dd)) /* Zoom R16/24 */ chip->tx_length_quirk = 1; alts = &iface->altsetting[0]; altsd = get_iface_desc(alts); err = snd_usb_parse_audio_interface(chip, altsd->bInterfaceNumber); if (err < 0) { usb_audio_err(chip, "cannot setup if %d: error %d\n", altsd->bInterfaceNumber, err); return err; } /* reset the current interface */ usb_set_interface(chip->dev, altsd->bInterfaceNumber, 0); return 0; } /* * create a stream for an endpoint/altsetting without proper descriptors */ static int create_fixed_stream_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { struct audioformat *fp; struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; int stream, err; unsigned *rate_table = NULL; fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL); if (!fp) { usb_audio_err(chip, "cannot memdup\n"); return -ENOMEM; } if (fp->nr_rates > MAX_NR_RATES) { kfree(fp); return -EINVAL; } if (fp->nr_rates > 0) { rate_table = kmemdup(fp->rate_table, sizeof(int) * fp->nr_rates, GFP_KERNEL); if (!rate_table) { kfree(fp); return -ENOMEM; } fp->rate_table = rate_table; } stream = (fp->endpoint & USB_DIR_IN) ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK; err = snd_usb_add_audio_stream(chip, stream, fp); if (err < 0) { kfree(fp); kfree(rate_table); return err; } if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber || fp->altset_idx >= iface->num_altsetting) { kfree(fp); kfree(rate_table); return -EINVAL; } alts = &iface->altsetting[fp->altset_idx]; altsd = get_iface_desc(alts); fp->protocol = altsd->bInterfaceProtocol; if (fp->datainterval == 0) fp->datainterval = snd_usb_parse_datainterval(chip, alts); if (fp->maxpacksize == 0) fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize); usb_set_interface(chip->dev, fp->iface, 0); snd_usb_init_pitch(chip, fp->iface, alts, fp); snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max); return 0; } static int create_auto_pcm_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver) { struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; struct usb_endpoint_descriptor *epd; struct uac1_as_header_descriptor *ashd; struct uac_format_type_i_discrete_descriptor *fmtd; /* * Most Roland/Yamaha audio streaming interfaces have more or less * standard descriptors, but older devices might lack descriptors, and * future ones might change, so ensure that we fail silently if the * interface doesn't look exactly right. */ /* must have a non-zero altsetting for streaming */ if (iface->num_altsetting < 2) return -ENODEV; alts = &iface->altsetting[1]; altsd = get_iface_desc(alts); /* must have an isochronous endpoint for streaming */ if (altsd->bNumEndpoints < 1) return -ENODEV; epd = get_endpoint(alts, 0); if (!usb_endpoint_xfer_isoc(epd)) return -ENODEV; /* must have format descriptors */ ashd = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, UAC_AS_GENERAL); fmtd = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, UAC_FORMAT_TYPE); if (!ashd || ashd->bLength < 7 || !fmtd || fmtd->bLength < 8) return -ENODEV; return create_standard_audio_quirk(chip, iface, driver, NULL); } static int create_yamaha_midi_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, struct usb_host_interface *alts) { static const struct snd_usb_audio_quirk yamaha_midi_quirk = { .type = QUIRK_MIDI_YAMAHA }; struct usb_midi_in_jack_descriptor *injd; struct usb_midi_out_jack_descriptor *outjd; /* must have some valid jack descriptors */ injd = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, USB_MS_MIDI_IN_JACK); outjd = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, USB_MS_MIDI_OUT_JACK); if (!injd && !outjd) return -ENODEV; if (injd && (injd->bLength < 5 || (injd->bJackType != USB_MS_EMBEDDED && injd->bJackType != USB_MS_EXTERNAL))) return -ENODEV; if (outjd && (outjd->bLength < 6 || (outjd->bJackType != USB_MS_EMBEDDED && outjd->bJackType != USB_MS_EXTERNAL))) return -ENODEV; return create_any_midi_quirk(chip, iface, driver, &yamaha_midi_quirk); } static int create_roland_midi_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, struct usb_host_interface *alts) { static const struct snd_usb_audio_quirk roland_midi_quirk = { .type = QUIRK_MIDI_ROLAND }; u8 *roland_desc = NULL; /* might have a vendor-specific descriptor <06 24 F1 02 ...> */ for (;;) { roland_desc = snd_usb_find_csint_desc(alts->extra, alts->extralen, roland_desc, 0xf1); if (!roland_desc) return -ENODEV; if (roland_desc[0] < 6 || roland_desc[3] != 2) continue; return create_any_midi_quirk(chip, iface, driver, &roland_midi_quirk); } } static int create_std_midi_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, struct usb_host_interface *alts) { struct usb_ms_header_descriptor *mshd; struct usb_ms_endpoint_descriptor *msepd; /* must have the MIDIStreaming interface header descriptor*/ mshd = (struct usb_ms_header_descriptor *)alts->extra; if (alts->extralen < 7 || mshd->bLength < 7 || mshd->bDescriptorType != USB_DT_CS_INTERFACE || mshd->bDescriptorSubtype != USB_MS_HEADER) return -ENODEV; /* must have the MIDIStreaming endpoint descriptor*/ msepd = (struct usb_ms_endpoint_descriptor *)alts->endpoint[0].extra; if (alts->endpoint[0].extralen < 4 || msepd->bLength < 4 || msepd->bDescriptorType != USB_DT_CS_ENDPOINT || msepd->bDescriptorSubtype != UAC_MS_GENERAL || msepd->bNumEmbMIDIJack < 1 || msepd->bNumEmbMIDIJack > 16) return -ENODEV; return create_any_midi_quirk(chip, iface, driver, NULL); } static int create_auto_midi_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver) { struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; struct usb_endpoint_descriptor *epd; int err; alts = &iface->altsetting[0]; altsd = get_iface_desc(alts); /* must have at least one bulk/interrupt endpoint for streaming */ if (altsd->bNumEndpoints < 1) return -ENODEV; epd = get_endpoint(alts, 0); if (!usb_endpoint_xfer_bulk(epd) && !usb_endpoint_xfer_int(epd)) return -ENODEV; switch (USB_ID_VENDOR(chip->usb_id)) { case 0x0499: /* Yamaha */ err = create_yamaha_midi_quirk(chip, iface, driver, alts); if (err != -ENODEV) return err; break; case 0x0582: /* Roland */ err = create_roland_midi_quirk(chip, iface, driver, alts); if (err != -ENODEV) return err; break; } return create_std_midi_quirk(chip, iface, driver, alts); } static int create_autodetect_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver) { int err; err = create_auto_pcm_quirk(chip, iface, driver); if (err == -ENODEV) err = create_auto_midi_quirk(chip, iface, driver); return err; } static int create_autodetect_quirks(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber; int ifcount, ifnum, err; err = create_autodetect_quirk(chip, iface, driver); if (err < 0) return err; /* * ALSA PCM playback/capture devices cannot be registered in two steps, * so we have to claim the other corresponding interface here. */ ifcount = chip->dev->actconfig->desc.bNumInterfaces; for (ifnum = 0; ifnum < ifcount; ifnum++) { if (ifnum == probed_ifnum || quirk->ifnum >= 0) continue; iface = usb_ifnum_to_if(chip->dev, ifnum); if (!iface || usb_interface_claimed(iface) || get_iface_desc(iface->altsetting)->bInterfaceClass != USB_CLASS_VENDOR_SPEC) continue; err = create_autodetect_quirk(chip, iface, driver); if (err >= 0) usb_driver_claim_interface(driver, iface, (void *)-1L); } return 0; } /* * Create a stream for an Edirol UA-700/UA-25/UA-4FX interface. * The only way to detect the sample rate is by looking at wMaxPacketSize. */ static int create_uaxx_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { static const struct audioformat ua_format = { .formats = SNDRV_PCM_FMTBIT_S24_3LE, .channels = 2, .fmt_type = UAC_FORMAT_TYPE_I, .altsetting = 1, .altset_idx = 1, .rates = SNDRV_PCM_RATE_CONTINUOUS, }; struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; struct audioformat *fp; int stream, err; /* both PCM and MIDI interfaces have 2 or more altsettings */ if (iface->num_altsetting < 2) return -ENXIO; alts = &iface->altsetting[1]; altsd = get_iface_desc(alts); if (altsd->bNumEndpoints == 2) { static const struct snd_usb_midi_endpoint_info ua700_ep = { .out_cables = 0x0003, .in_cables = 0x0003 }; static const struct snd_usb_audio_quirk ua700_quirk = { .type = QUIRK_MIDI_FIXED_ENDPOINT, .data = &ua700_ep }; static const struct snd_usb_midi_endpoint_info uaxx_ep = { .out_cables = 0x0001, .in_cables = 0x0001 }; static const struct snd_usb_audio_quirk uaxx_quirk = { .type = QUIRK_MIDI_FIXED_ENDPOINT, .data = &uaxx_ep }; const struct snd_usb_audio_quirk *quirk = chip->usb_id == USB_ID(0x0582, 0x002b) ? &ua700_quirk : &uaxx_quirk; return snd_usbmidi_create(chip->card, iface, &chip->midi_list, quirk); } if (altsd->bNumEndpoints != 1) return -ENXIO; fp = kmemdup(&ua_format, sizeof(*fp), GFP_KERNEL); if (!fp) return -ENOMEM; fp->iface = altsd->bInterfaceNumber; fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress; fp->ep_attr = get_endpoint(alts, 0)->bmAttributes; fp->datainterval = 0; fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize); switch (fp->maxpacksize) { case 0x120: fp->rate_max = fp->rate_min = 44100; break; case 0x138: case 0x140: fp->rate_max = fp->rate_min = 48000; break; case 0x258: case 0x260: fp->rate_max = fp->rate_min = 96000; break; default: usb_audio_err(chip, "unknown sample rate\n"); kfree(fp); return -ENXIO; } stream = (fp->endpoint & USB_DIR_IN) ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK; err = snd_usb_add_audio_stream(chip, stream, fp); if (err < 0) { kfree(fp); return err; } usb_set_interface(chip->dev, fp->iface, 0); return 0; } /* * Create a standard mixer for the specified interface. */ static int create_standard_mixer_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { if (quirk->ifnum < 0) return 0; return snd_usb_create_mixer(chip, quirk->ifnum, 0); } /* * audio-interface quirks * * returns zero if no standard audio/MIDI parsing is needed. * returns a positive value if standard audio/midi interfaces are parsed * after this. * returns a negative value at error. */ int snd_usb_create_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { typedef int (*quirk_func_t)(struct snd_usb_audio *, struct usb_interface *, struct usb_driver *, const struct snd_usb_audio_quirk *); static const quirk_func_t quirk_funcs[] = { [QUIRK_IGNORE_INTERFACE] = ignore_interface_quirk, [QUIRK_COMPOSITE] = create_composite_quirk, [QUIRK_AUTODETECT] = create_autodetect_quirks, [QUIRK_MIDI_STANDARD_INTERFACE] = create_any_midi_quirk, [QUIRK_MIDI_FIXED_ENDPOINT] = create_any_midi_quirk, [QUIRK_MIDI_YAMAHA] = create_any_midi_quirk, [QUIRK_MIDI_ROLAND] = create_any_midi_quirk, [QUIRK_MIDI_MIDIMAN] = create_any_midi_quirk, [QUIRK_MIDI_NOVATION] = create_any_midi_quirk, [QUIRK_MIDI_RAW_BYTES] = create_any_midi_quirk, [QUIRK_MIDI_EMAGIC] = create_any_midi_quirk, [QUIRK_MIDI_CME] = create_any_midi_quirk, [QUIRK_MIDI_AKAI] = create_any_midi_quirk, [QUIRK_MIDI_FTDI] = create_any_midi_quirk, [QUIRK_AUDIO_STANDARD_INTERFACE] = create_standard_audio_quirk, [QUIRK_AUDIO_FIXED_ENDPOINT] = create_fixed_stream_quirk, [QUIRK_AUDIO_EDIROL_UAXX] = create_uaxx_quirk, [QUIRK_AUDIO_ALIGN_TRANSFER] = create_align_transfer_quirk, [QUIRK_AUDIO_STANDARD_MIXER] = create_standard_mixer_quirk, }; if (quirk->type < QUIRK_TYPE_COUNT) { return quirk_funcs[quirk->type](chip, iface, driver, quirk); } else { usb_audio_err(chip, "invalid quirk type %d\n", quirk->type); return -ENXIO; } } /* * boot quirks */ #define EXTIGY_FIRMWARE_SIZE_OLD 794 #define EXTIGY_FIRMWARE_SIZE_NEW 483 static int snd_usb_extigy_boot_quirk(struct usb_device *dev, struct usb_interface *intf) { struct usb_host_config *config = dev->actconfig; int err; if (le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_OLD || le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_NEW) { dev_dbg(&dev->dev, "sending Extigy boot sequence...\n"); /* Send message to force it to reconnect with full interface. */ err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev,0), 0x10, 0x43, 0x0001, 0x000a, NULL, 0); if (err < 0) dev_dbg(&dev->dev, "error sending boot message: %d\n", err); err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, sizeof(dev->descriptor)); config = dev->actconfig; if (err < 0) dev_dbg(&dev->dev, "error usb_get_descriptor: %d\n", err); err = usb_reset_configuration(dev); if (err < 0) dev_dbg(&dev->dev, "error usb_reset_configuration: %d\n", err); dev_dbg(&dev->dev, "extigy_boot: new boot length = %d\n", le16_to_cpu(get_cfg_desc(config)->wTotalLength)); return -ENODEV; /* quit this anyway */ } return 0; } static int snd_usb_audigy2nx_boot_quirk(struct usb_device *dev) { u8 buf = 1; snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), 0x2a, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_OTHER, 0, 0, &buf, 1); if (buf == 0) { snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0x29, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_OTHER, 1, 2000, NULL, 0); return -ENODEV; } return 0; } static int snd_usb_fasttrackpro_boot_quirk(struct usb_device *dev) { int err; if (dev->actconfig->desc.bConfigurationValue == 1) { dev_info(&dev->dev, "Fast Track Pro switching to config #2\n"); /* This function has to be available by the usb core module. * if it is not avialable the boot quirk has to be left out * and the configuration has to be set by udev or hotplug * rules */ err = usb_driver_set_configuration(dev, 2); if (err < 0) dev_dbg(&dev->dev, "error usb_driver_set_configuration: %d\n", err); /* Always return an error, so that we stop creating a device that will just be destroyed and recreated with a new configuration */ return -ENODEV; } else dev_info(&dev->dev, "Fast Track Pro config OK\n"); return 0; } /* * C-Media CM106/CM106+ have four 16-bit internal registers that are nicely * documented in the device's data sheet. */ static int snd_usb_cm106_write_int_reg(struct usb_device *dev, int reg, u16 value) { u8 buf[4]; buf[0] = 0x20; buf[1] = value & 0xff; buf[2] = (value >> 8) & 0xff; buf[3] = reg; return snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_SET_CONFIGURATION, USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT, 0, 0, &buf, 4); } static int snd_usb_cm106_boot_quirk(struct usb_device *dev) { /* * Enable line-out driver mode, set headphone source to front * channels, enable stereo mic. */ return snd_usb_cm106_write_int_reg(dev, 2, 0x8004); } /* * C-Media CM6206 is based on CM106 with two additional * registers that are not documented in the data sheet. * Values here are chosen based on sniffing USB traffic * under Windows. */ static int snd_usb_cm6206_boot_quirk(struct usb_device *dev) { int err = 0, reg; int val[] = {0x2004, 0x3000, 0xf800, 0x143f, 0x0000, 0x3000}; for (reg = 0; reg < ARRAY_SIZE(val); reg++) { err = snd_usb_cm106_write_int_reg(dev, reg, val[reg]); if (err < 0) return err; } return err; } /* quirk for Plantronics GameCom 780 with CM6302 chip */ static int snd_usb_gamecon780_boot_quirk(struct usb_device *dev) { /* set the initial volume and don't change; other values are either * too loud or silent due to firmware bug (bko#65251) */ u8 buf[2] = { 0x74, 0xe3 }; return snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT, UAC_FU_VOLUME << 8, 9 << 8, buf, 2); } /* * Novation Twitch DJ controller * Focusrite Novation Saffire 6 USB audio card */ static int snd_usb_novation_boot_quirk(struct usb_device *dev) { /* preemptively set up the device because otherwise the * raw MIDI endpoints are not active */ usb_set_interface(dev, 0, 1); return 0; } /* * This call will put the synth in "USB send" mode, i.e it will send MIDI * messages through USB (this is disabled at startup). The synth will * acknowledge by sending a sysex on endpoint 0x85 and by displaying a USB * sign on its LCD. Values here are chosen based on sniffing USB traffic * under Windows. */ static int snd_usb_accessmusic_boot_quirk(struct usb_device *dev) { int err, actual_length; /* "midi send" enable */ static const u8 seq[] = { 0x4e, 0x73, 0x52, 0x01 }; void *buf = kmemdup(seq, ARRAY_SIZE(seq), GFP_KERNEL); if (!buf) return -ENOMEM; err = usb_interrupt_msg(dev, usb_sndintpipe(dev, 0x05), buf, ARRAY_SIZE(seq), &actual_length, 1000); kfree(buf); if (err < 0) return err; return 0; } /* * Some sound cards from Native Instruments are in fact compliant to the USB * audio standard of version 2 and other approved USB standards, even though * they come up as vendor-specific device when first connected. * * However, they can be told to come up with a new set of descriptors * upon their next enumeration, and the interfaces announced by the new * descriptors will then be handled by the kernel's class drivers. As the * product ID will also change, no further checks are required. */ static int snd_usb_nativeinstruments_boot_quirk(struct usb_device *dev) { int ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), 0xaf, USB_TYPE_VENDOR | USB_RECIP_DEVICE, 1, 0, NULL, 0, 1000); if (ret < 0) return ret; usb_reset_device(dev); /* return -EAGAIN, so the creation of an audio interface for this * temporary device is aborted. The device will reconnect with a * new product ID */ return -EAGAIN; } static void mbox2_setup_48_24_magic(struct usb_device *dev) { u8 srate[3]; u8 temp[12]; /* Choose 48000Hz permanently */ srate[0] = 0x80; srate[1] = 0xbb; srate[2] = 0x00; /* Send the magic! */ snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), 0x01, 0x22, 0x0100, 0x0085, &temp, 0x0003); snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0x81, 0xa2, 0x0100, 0x0085, &srate, 0x0003); snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0x81, 0xa2, 0x0100, 0x0086, &srate, 0x0003); snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0x81, 0xa2, 0x0100, 0x0003, &srate, 0x0003); return; } /* Digidesign Mbox 2 needs to load firmware onboard * and driver must wait a few seconds for initialisation. */ #define MBOX2_FIRMWARE_SIZE 646 #define MBOX2_BOOT_LOADING 0x01 /* Hard coded into the device */ #define MBOX2_BOOT_READY 0x02 /* Hard coded into the device */ static int snd_usb_mbox2_boot_quirk(struct usb_device *dev) { struct usb_host_config *config = dev->actconfig; int err; u8 bootresponse[0x12]; int fwsize; int count; fwsize = le16_to_cpu(get_cfg_desc(config)->wTotalLength); if (fwsize != MBOX2_FIRMWARE_SIZE) { dev_err(&dev->dev, "Invalid firmware size=%d.\n", fwsize); return -ENODEV; } dev_dbg(&dev->dev, "Sending Digidesign Mbox 2 boot sequence...\n"); count = 0; bootresponse[0] = MBOX2_BOOT_LOADING; while ((bootresponse[0] == MBOX2_BOOT_LOADING) && (count < 10)) { msleep(500); /* 0.5 second delay */ snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), /* Control magic - load onboard firmware */ 0x85, 0xc0, 0x0001, 0x0000, &bootresponse, 0x0012); if (bootresponse[0] == MBOX2_BOOT_READY) break; dev_dbg(&dev->dev, "device not ready, resending boot sequence...\n"); count++; } if (bootresponse[0] != MBOX2_BOOT_READY) { dev_err(&dev->dev, "Unknown bootresponse=%d, or timed out, ignoring device.\n", bootresponse[0]); return -ENODEV; } dev_dbg(&dev->dev, "device initialised!\n"); err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, sizeof(dev->descriptor)); config = dev->actconfig; if (err < 0) dev_dbg(&dev->dev, "error usb_get_descriptor: %d\n", err); err = usb_reset_configuration(dev); if (err < 0) dev_dbg(&dev->dev, "error usb_reset_configuration: %d\n", err); dev_dbg(&dev->dev, "mbox2_boot: new boot length = %d\n", le16_to_cpu(get_cfg_desc(config)->wTotalLength)); mbox2_setup_48_24_magic(dev); dev_info(&dev->dev, "Digidesign Mbox 2: 24bit 48kHz"); return 0; /* Successful boot */ } /* * Setup quirks */ #define MAUDIO_SET 0x01 /* parse device_setup */ #define MAUDIO_SET_COMPATIBLE 0x80 /* use only "win-compatible" interfaces */ #define MAUDIO_SET_DTS 0x02 /* enable DTS Digital Output */ #define MAUDIO_SET_96K 0x04 /* 48-96KHz rate if set, 8-48KHz otherwise */ #define MAUDIO_SET_24B 0x08 /* 24bits sample if set, 16bits otherwise */ #define MAUDIO_SET_DI 0x10 /* enable Digital Input */ #define MAUDIO_SET_MASK 0x1f /* bit mask for setup value */ #define MAUDIO_SET_24B_48K_DI 0x19 /* 24bits+48KHz+Digital Input */ #define MAUDIO_SET_24B_48K_NOTDI 0x09 /* 24bits+48KHz+No Digital Input */ #define MAUDIO_SET_16B_48K_DI 0x11 /* 16bits+48KHz+Digital Input */ #define MAUDIO_SET_16B_48K_NOTDI 0x01 /* 16bits+48KHz+No Digital Input */ static int quattro_skip_setting_quirk(struct snd_usb_audio *chip, int iface, int altno) { /* Reset ALL ifaces to 0 altsetting. * Call it for every possible altsetting of every interface. */ usb_set_interface(chip->dev, iface, 0); if (chip->setup & MAUDIO_SET) { if (chip->setup & MAUDIO_SET_COMPATIBLE) { if (iface != 1 && iface != 2) return 1; /* skip all interfaces but 1 and 2 */ } else { unsigned int mask; if (iface == 1 || iface == 2) return 1; /* skip interfaces 1 and 2 */ if ((chip->setup & MAUDIO_SET_96K) && altno != 1) return 1; /* skip this altsetting */ mask = chip->setup & MAUDIO_SET_MASK; if (mask == MAUDIO_SET_24B_48K_DI && altno != 2) return 1; /* skip this altsetting */ if (mask == MAUDIO_SET_24B_48K_NOTDI && altno != 3) return 1; /* skip this altsetting */ if (mask == MAUDIO_SET_16B_48K_NOTDI && altno != 4) return 1; /* skip this altsetting */ } } usb_audio_dbg(chip, "using altsetting %d for interface %d config %d\n", altno, iface, chip->setup); return 0; /* keep this altsetting */ } static int audiophile_skip_setting_quirk(struct snd_usb_audio *chip, int iface, int altno) { /* Reset ALL ifaces to 0 altsetting. * Call it for every possible altsetting of every interface. */ usb_set_interface(chip->dev, iface, 0); if (chip->setup & MAUDIO_SET) { unsigned int mask; if ((chip->setup & MAUDIO_SET_DTS) && altno != 6) return 1; /* skip this altsetting */ if ((chip->setup & MAUDIO_SET_96K) && altno != 1) return 1; /* skip this altsetting */ mask = chip->setup & MAUDIO_SET_MASK; if (mask == MAUDIO_SET_24B_48K_DI && altno != 2) return 1; /* skip this altsetting */ if (mask == MAUDIO_SET_24B_48K_NOTDI && altno != 3) return 1; /* skip this altsetting */ if (mask == MAUDIO_SET_16B_48K_DI && altno != 4) return 1; /* skip this altsetting */ if (mask == MAUDIO_SET_16B_48K_NOTDI && altno != 5) return 1; /* skip this altsetting */ } return 0; /* keep this altsetting */ } static int fasttrackpro_skip_setting_quirk(struct snd_usb_audio *chip, int iface, int altno) { /* Reset ALL ifaces to 0 altsetting. * Call it for every possible altsetting of every interface. */ usb_set_interface(chip->dev, iface, 0); /* possible configuration where both inputs and only one output is *used is not supported by the current setup */ if (chip->setup & (MAUDIO_SET | MAUDIO_SET_24B)) { if (chip->setup & MAUDIO_SET_96K) { if (altno != 3 && altno != 6) return 1; } else if (chip->setup & MAUDIO_SET_DI) { if (iface == 4) return 1; /* no analog input */ if (altno != 2 && altno != 5) return 1; /* enable only altsets 2 and 5 */ } else { if (iface == 5) return 1; /* disable digialt input */ if (altno != 2 && altno != 5) return 1; /* enalbe only altsets 2 and 5 */ } } else { /* keep only 16-Bit mode */ if (altno != 1) return 1; } usb_audio_dbg(chip, "using altsetting %d for interface %d config %d\n", altno, iface, chip->setup); return 0; /* keep this altsetting */ } int snd_usb_apply_interface_quirk(struct snd_usb_audio *chip, int iface, int altno) { /* audiophile usb: skip altsets incompatible with device_setup */ if (chip->usb_id == USB_ID(0x0763, 0x2003)) return audiophile_skip_setting_quirk(chip, iface, altno); /* quattro usb: skip altsets incompatible with device_setup */ if (chip->usb_id == USB_ID(0x0763, 0x2001)) return quattro_skip_setting_quirk(chip, iface, altno); /* fasttrackpro usb: skip altsets incompatible with device_setup */ if (chip->usb_id == USB_ID(0x0763, 0x2012)) return fasttrackpro_skip_setting_quirk(chip, iface, altno); return 0; } int snd_usb_apply_boot_quirk(struct usb_device *dev, struct usb_interface *intf, const struct snd_usb_audio_quirk *quirk) { u32 id = USB_ID(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); switch (id) { case USB_ID(0x041e, 0x3000): /* SB Extigy needs special boot-up sequence */ /* if more models come, this will go to the quirk list. */ return snd_usb_extigy_boot_quirk(dev, intf); case USB_ID(0x041e, 0x3020): /* SB Audigy 2 NX needs its own boot-up magic, too */ return snd_usb_audigy2nx_boot_quirk(dev); case USB_ID(0x10f5, 0x0200): /* C-Media CM106 / Turtle Beach Audio Advantage Roadie */ return snd_usb_cm106_boot_quirk(dev); case USB_ID(0x0d8c, 0x0102): /* C-Media CM6206 / CM106-Like Sound Device */ case USB_ID(0x0ccd, 0x00b1): /* Terratec Aureon 7.1 USB */ return snd_usb_cm6206_boot_quirk(dev); case USB_ID(0x0dba, 0x3000): /* Digidesign Mbox 2 */ return snd_usb_mbox2_boot_quirk(dev); case USB_ID(0x1235, 0x0010): /* Focusrite Novation Saffire 6 USB */ case USB_ID(0x1235, 0x0018): /* Focusrite Novation Twitch */ return snd_usb_novation_boot_quirk(dev); case USB_ID(0x133e, 0x0815): /* Access Music VirusTI Desktop */ return snd_usb_accessmusic_boot_quirk(dev); case USB_ID(0x17cc, 0x1000): /* Komplete Audio 6 */ case USB_ID(0x17cc, 0x1010): /* Traktor Audio 6 */ case USB_ID(0x17cc, 0x1020): /* Traktor Audio 10 */ return snd_usb_nativeinstruments_boot_quirk(dev); case USB_ID(0x0763, 0x2012): /* M-Audio Fast Track Pro USB */ return snd_usb_fasttrackpro_boot_quirk(dev); case USB_ID(0x047f, 0xc010): /* Plantronics Gamecom 780 */ return snd_usb_gamecon780_boot_quirk(dev); } return 0; } /* * check if the device uses big-endian samples */ int snd_usb_is_big_endian_format(struct snd_usb_audio *chip, struct audioformat *fp) { /* it depends on altsetting whether the device is big-endian or not */ switch (chip->usb_id) { case USB_ID(0x0763, 0x2001): /* M-Audio Quattro: captured data only */ if (fp->altsetting == 2 || fp->altsetting == 3 || fp->altsetting == 5 || fp->altsetting == 6) return 1; break; case USB_ID(0x0763, 0x2003): /* M-Audio Audiophile USB */ if (chip->setup == 0x00 || fp->altsetting == 1 || fp->altsetting == 2 || fp->altsetting == 3) return 1; break; case USB_ID(0x0763, 0x2012): /* M-Audio Fast Track Pro */ if (fp->altsetting == 2 || fp->altsetting == 3 || fp->altsetting == 5 || fp->altsetting == 6) return 1; break; } return 0; } /* * For E-Mu 0404USB/0202USB/TrackerPre/0204 sample rate should be set for device, * not for interface. */ enum { EMU_QUIRK_SR_44100HZ = 0, EMU_QUIRK_SR_48000HZ, EMU_QUIRK_SR_88200HZ, EMU_QUIRK_SR_96000HZ, EMU_QUIRK_SR_176400HZ, EMU_QUIRK_SR_192000HZ }; static void set_format_emu_quirk(struct snd_usb_substream *subs, struct audioformat *fmt) { unsigned char emu_samplerate_id = 0; /* When capture is active * sample rate shouldn't be changed * by playback substream */ if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) { if (subs->stream->substream[SNDRV_PCM_STREAM_CAPTURE].interface != -1) return; } switch (fmt->rate_min) { case 48000: emu_samplerate_id = EMU_QUIRK_SR_48000HZ; break; case 88200: emu_samplerate_id = EMU_QUIRK_SR_88200HZ; break; case 96000: emu_samplerate_id = EMU_QUIRK_SR_96000HZ; break; case 176400: emu_samplerate_id = EMU_QUIRK_SR_176400HZ; break; case 192000: emu_samplerate_id = EMU_QUIRK_SR_192000HZ; break; default: emu_samplerate_id = EMU_QUIRK_SR_44100HZ; break; } snd_emuusb_set_samplerate(subs->stream->chip, emu_samplerate_id); subs->pkt_offset_adj = (emu_samplerate_id >= EMU_QUIRK_SR_176400HZ) ? 4 : 0; } void snd_usb_set_format_quirk(struct snd_usb_substream *subs, struct audioformat *fmt) { switch (subs->stream->chip->usb_id) { case USB_ID(0x041e, 0x3f02): /* E-Mu 0202 USB */ case USB_ID(0x041e, 0x3f04): /* E-Mu 0404 USB */ case USB_ID(0x041e, 0x3f0a): /* E-Mu Tracker Pre */ case USB_ID(0x041e, 0x3f19): /* E-Mu 0204 USB */ set_format_emu_quirk(subs, fmt); break; } } bool snd_usb_get_sample_rate_quirk(struct snd_usb_audio *chip) { /* devices which do not support reading the sample rate. */ switch (chip->usb_id) { case USB_ID(0x045E, 0x075D): /* MS Lifecam Cinema */ case USB_ID(0x045E, 0x076D): /* MS Lifecam HD-5000 */ case USB_ID(0x045E, 0x0772): /* MS Lifecam Studio */ case USB_ID(0x045E, 0x0779): /* MS Lifecam HD-3000 */ case USB_ID(0x04D8, 0xFEEA): /* Benchmark DAC1 Pre */ case USB_ID(0x074D, 0x3553): /* Outlaw RR2150 (Micronas UAC3553B) */ return true; } return false; } /* Marantz/Denon USB DACs need a vendor cmd to switch * between PCM and native DSD mode */ static bool is_marantz_denon_dac(unsigned int id) { switch (id) { case USB_ID(0x154e, 0x1003): /* Denon DA-300USB */ case USB_ID(0x154e, 0x3005): /* Marantz HD-DAC1 */ case USB_ID(0x154e, 0x3006): /* Marantz SA-14S1 */ return true; } return false; } int snd_usb_select_mode_quirk(struct snd_usb_substream *subs, struct audioformat *fmt) { struct usb_device *dev = subs->dev; int err; if (is_marantz_denon_dac(subs->stream->chip->usb_id)) { /* First switch to alt set 0, otherwise the mode switch cmd * will not be accepted by the DAC */ err = usb_set_interface(dev, fmt->iface, 0); if (err < 0) return err; mdelay(20); /* Delay needed after setting the interface */ switch (fmt->altsetting) { case 2: /* DSD mode requested */ case 1: /* PCM mode requested */ err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, fmt->altsetting - 1, 1, NULL, 0); if (err < 0) return err; break; } mdelay(20); } return 0; } void snd_usb_endpoint_start_quirk(struct snd_usb_endpoint *ep) { /* * "Playback Design" products send bogus feedback data at the start * of the stream. Ignore them. */ if ((le16_to_cpu(ep->chip->dev->descriptor.idVendor) == 0x23ba) && ep->type == SND_USB_ENDPOINT_TYPE_SYNC) ep->skip_packets = 4; /* * M-Audio Fast Track C400/C600 - when packets are not skipped, real * world latency varies by approx. +/- 50 frames (at 96KHz) each time * the stream is (re)started. When skipping packets 16 at endpoint * start up, the real world latency is stable within +/- 1 frame (also * across power cycles). */ if ((ep->chip->usb_id == USB_ID(0x0763, 0x2030) || ep->chip->usb_id == USB_ID(0x0763, 0x2031)) && ep->type == SND_USB_ENDPOINT_TYPE_DATA) ep->skip_packets = 16; } void snd_usb_set_interface_quirk(struct usb_device *dev) { /* * "Playback Design" products need a 50ms delay after setting the * USB interface. */ if (le16_to_cpu(dev->descriptor.idVendor) == 0x23ba) mdelay(50); } void snd_usb_ctl_msg_quirk(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size) { /* * "Playback Design" products need a 20ms delay after each * class compliant request */ if ((le16_to_cpu(dev->descriptor.idVendor) == 0x23ba) && (requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS) mdelay(20); /* Marantz/Denon devices with USB DAC functionality need a delay * after each class compliant request */ if (is_marantz_denon_dac(USB_ID(le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct))) && (requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS) mdelay(20); /* Zoom R16/24 needs a tiny delay here, otherwise requests like * get/set frequency return as failed despite actually succeeding. */ if ((le16_to_cpu(dev->descriptor.idVendor) == 0x1686) && (le16_to_cpu(dev->descriptor.idProduct) == 0x00dd) && (requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS) mdelay(1); } /* * snd_usb_interface_dsd_format_quirks() is called from format.c to * augment the PCM format bit-field for DSD types. The UAC standards * don't have a designated bit field to denote DSD-capable interfaces, * hence all hardware that is known to support this format has to be * listed here. */ u64 snd_usb_interface_dsd_format_quirks(struct snd_usb_audio *chip, struct audioformat *fp, unsigned int sample_bytes) { /* Playback Designs */ if (le16_to_cpu(chip->dev->descriptor.idVendor) == 0x23ba) { switch (fp->altsetting) { case 1: fp->dsd_dop = true; return SNDRV_PCM_FMTBIT_DSD_U16_LE; case 2: fp->dsd_bitrev = true; return SNDRV_PCM_FMTBIT_DSD_U8; case 3: fp->dsd_bitrev = true; return SNDRV_PCM_FMTBIT_DSD_U16_LE; } } /* XMOS based USB DACs */ switch (chip->usb_id) { case USB_ID(0x20b1, 0x3008): /* iFi Audio micro/nano iDSD */ case USB_ID(0x20b1, 0x2008): /* Matrix Audio X-Sabre */ case USB_ID(0x20b1, 0x300a): /* Matrix Audio Mini-i Pro */ if (fp->altsetting == 2) return SNDRV_PCM_FMTBIT_DSD_U32_BE; break; case USB_ID(0x20b1, 0x000a): /* Gustard DAC-X20U */ case USB_ID(0x20b1, 0x2009): /* DIYINHK DSD DXD 384kHz USB to I2S/DSD */ case USB_ID(0x20b1, 0x2023): /* JLsounds I2SoverUSB */ case USB_ID(0x20b1, 0x3023): /* Aune X1S 32BIT/384 DSD DAC */ if (fp->altsetting == 3) return SNDRV_PCM_FMTBIT_DSD_U32_BE; break; default: break; } /* Denon/Marantz devices with USB DAC functionality */ if (is_marantz_denon_dac(chip->usb_id)) { if (fp->altsetting == 2) return SNDRV_PCM_FMTBIT_DSD_U32_BE; } return 0; }
gpl-2.0
radiaku/decoda
libs/wxWidgets/src/msw/tbar95.cpp
58053
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/tbar95.cpp // Purpose: wxToolBar // Author: Julian Smart // Modified by: // Created: 04/01/98 // RCS-ID: $Id: tbar95.cpp 58446 2009-01-26 23:32:16Z VS $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_TOOLBAR && wxUSE_TOOLBAR_NATIVE && !defined(__SMARTPHONE__) #include "wx/toolbar.h" #ifndef WX_PRECOMP #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly" #include "wx/dynarray.h" #include "wx/frame.h" #include "wx/log.h" #include "wx/intl.h" #include "wx/settings.h" #include "wx/bitmap.h" #include "wx/dcmemory.h" #include "wx/control.h" #include "wx/app.h" // for GetComCtl32Version #include "wx/image.h" #endif #include "wx/sysopt.h" #include "wx/msw/private.h" #if wxUSE_UXTHEME #include "wx/msw/uxtheme.h" #endif // this define controls whether the code for button colours remapping (only // useful for 16 or 256 colour images) is active at all, it's always turned off // for CE where it doesn't compile (and is probably not needed anyhow) and may // also be turned off for other systems if you always use 24bpp images and so // never need it #ifndef __WXWINCE__ #define wxREMAP_BUTTON_COLOURS #endif // !__WXWINCE__ // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // these standard constants are not always defined in compilers headers // Styles #ifndef TBSTYLE_FLAT #define TBSTYLE_LIST 0x1000 #define TBSTYLE_FLAT 0x0800 #endif #ifndef TBSTYLE_TRANSPARENT #define TBSTYLE_TRANSPARENT 0x8000 #endif #ifndef TBSTYLE_TOOLTIPS #define TBSTYLE_TOOLTIPS 0x0100 #endif // Messages #ifndef TB_GETSTYLE #define TB_SETSTYLE (WM_USER + 56) #define TB_GETSTYLE (WM_USER + 57) #endif #ifndef TB_HITTEST #define TB_HITTEST (WM_USER + 69) #endif #ifndef TB_GETMAXSIZE #define TB_GETMAXSIZE (WM_USER + 83) #endif // these values correspond to those used by comctl32.dll #define DEFAULTBITMAPX 16 #define DEFAULTBITMAPY 15 // ---------------------------------------------------------------------------- // wxWin macros // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxToolBar, wxControl) /* TOOLBAR PROPERTIES tool bitmap bitmap2 tooltip longhelp radio (bool) toggle (bool) separator style ( wxNO_BORDER | wxTB_HORIZONTAL) bitmapsize margins packing separation dontattachtoframe */ BEGIN_EVENT_TABLE(wxToolBar, wxToolBarBase) EVT_MOUSE_EVENTS(wxToolBar::OnMouseEvent) EVT_SYS_COLOUR_CHANGED(wxToolBar::OnSysColourChanged) EVT_ERASE_BACKGROUND(wxToolBar::OnEraseBackground) END_EVENT_TABLE() // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- class wxToolBarTool : public wxToolBarToolBase { public: wxToolBarTool(wxToolBar *tbar, int id, const wxString& label, const wxBitmap& bmpNormal, const wxBitmap& bmpDisabled, wxItemKind kind, wxObject *clientData, const wxString& shortHelp, const wxString& longHelp) : wxToolBarToolBase(tbar, id, label, bmpNormal, bmpDisabled, kind, clientData, shortHelp, longHelp) { m_nSepCount = 0; } wxToolBarTool(wxToolBar *tbar, wxControl *control) : wxToolBarToolBase(tbar, control) { m_nSepCount = 1; } virtual void SetLabel(const wxString& label) { if ( label == m_label ) return; wxToolBarToolBase::SetLabel(label); // we need to update the label shown in the toolbar because it has a // pointer to the internal buffer of the old label // // TODO: use TB_SETBUTTONINFO } // set/get the number of separators which we use to cover the space used by // a control in the toolbar void SetSeparatorsCount(size_t count) { m_nSepCount = count; } size_t GetSeparatorsCount() const { return m_nSepCount; } private: size_t m_nSepCount; DECLARE_NO_COPY_CLASS(wxToolBarTool) }; // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxToolBarTool // ---------------------------------------------------------------------------- wxToolBarToolBase *wxToolBar::CreateTool(int id, const wxString& label, const wxBitmap& bmpNormal, const wxBitmap& bmpDisabled, wxItemKind kind, wxObject *clientData, const wxString& shortHelp, const wxString& longHelp) { return new wxToolBarTool(this, id, label, bmpNormal, bmpDisabled, kind, clientData, shortHelp, longHelp); } wxToolBarToolBase *wxToolBar::CreateTool(wxControl *control) { return new wxToolBarTool(this, control); } // ---------------------------------------------------------------------------- // wxToolBar construction // ---------------------------------------------------------------------------- void wxToolBar::Init() { m_hBitmap = 0; m_disabledImgList = NULL; m_nButtons = 0; m_defaultWidth = DEFAULTBITMAPX; m_defaultHeight = DEFAULTBITMAPY; m_pInTool = 0; } bool wxToolBar::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { // common initialisation if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) ) return false; FixupStyle(); // MSW-specific initialisation if ( !MSWCreateToolbar(pos, size) ) return false; wxSetCCUnicodeFormat(GetHwnd()); // workaround for flat toolbar on Windows XP classic style: we have to set // the style after creating the control; doing it at creation time doesn't work #if wxUSE_UXTHEME if ( style & wxTB_FLAT ) { LRESULT style = GetMSWToolbarStyle(); if ( !(style & TBSTYLE_FLAT) ) ::SendMessage(GetHwnd(), TB_SETSTYLE, 0, style | TBSTYLE_FLAT); } #endif // wxUSE_UXTHEME return true; } bool wxToolBar::MSWCreateToolbar(const wxPoint& pos, const wxSize& size) { if ( !MSWCreateControl(TOOLBARCLASSNAME, wxEmptyString, pos, size) ) return false; // toolbar-specific post initialisation ::SendMessage(GetHwnd(), TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0); // Fix a bug on e.g. the Silver theme on WinXP where control backgrounds // are incorrectly drawn, by forcing the background to a specific colour. int majorVersion, minorVersion; wxGetOsVersion(& majorVersion, & minorVersion); if (majorVersion < 6) SetBackgroundColour(GetBackgroundColour()); return true; } void wxToolBar::Recreate() { const HWND hwndOld = GetHwnd(); if ( !hwndOld ) { // we haven't been created yet, no need to recreate return; } // get the position and size before unsubclassing the old toolbar const wxPoint pos = GetPosition(); const wxSize size = GetSize(); UnsubclassWin(); if ( !MSWCreateToolbar(pos, size) ) { // what can we do? wxFAIL_MSG( _T("recreating the toolbar failed") ); return; } // reparent all our children under the new toolbar for ( wxWindowList::compatibility_iterator node = m_children.GetFirst(); node; node = node->GetNext() ) { wxWindow *win = node->GetData(); if ( !win->IsTopLevel() ) ::SetParent(GetHwndOf(win), GetHwnd()); } // only destroy the old toolbar now -- // after all the children had been reparented ::DestroyWindow(hwndOld); // it is for the old bitmap control and can't be used with the new one if ( m_hBitmap ) { ::DeleteObject((HBITMAP) m_hBitmap); m_hBitmap = 0; } if ( m_disabledImgList ) { delete m_disabledImgList; m_disabledImgList = NULL; } Realize(); } wxToolBar::~wxToolBar() { // we must refresh the frame size when the toolbar is deleted but the frame // is not - otherwise toolbar leaves a hole in the place it used to occupy wxFrame *frame = wxDynamicCast(GetParent(), wxFrame); if ( frame && !frame->IsBeingDeleted() ) frame->SendSizeEvent(); if ( m_hBitmap ) ::DeleteObject((HBITMAP) m_hBitmap); delete m_disabledImgList; } wxSize wxToolBar::DoGetBestSize() const { wxSize sizeBest; SIZE size; if ( !::SendMessage(GetHwnd(), TB_GETMAXSIZE, 0, (LPARAM)&size) ) { // maybe an old (< 0x400) Windows version? try to approximate the // toolbar size ourselves sizeBest = GetToolSize(); sizeBest.y += 2 * ::GetSystemMetrics(SM_CYBORDER); // Add borders sizeBest.x *= GetToolsCount(); // reverse horz and vertical components if necessary if ( IsVertical() ) { int t = sizeBest.x; sizeBest.x = sizeBest.y; sizeBest.y = t; } } else // TB_GETMAXSIZE succeeded { // but it could still return an incorrect result due to what appears to // be a bug in old comctl32.dll versions which don't handle controls in // the toolbar correctly, so work around it (see SF patch 1902358) if ( !IsVertical() && wxApp::GetComCtl32Version() < 600 ) { // calculate the toolbar width in alternative way RECT rcFirst, rcLast; if ( ::SendMessage(GetHwnd(), TB_GETITEMRECT, 0, (LPARAM)&rcFirst) && ::SendMessage(GetHwnd(), TB_GETITEMRECT, GetToolsCount() - 1, (LPARAM)&rcLast) ) { const int widthAlt = rcLast.right - rcFirst.left; if ( widthAlt > size.cx ) size.cx = widthAlt; } } sizeBest.x = size.cx; sizeBest.y = size.cy; } if (!IsVertical()) { // Without the extra height, DoGetBestSize can report a size that's // smaller than the actual window, causing windows to overlap slightly // in some circumstances, leading to missing borders (especially noticeable // in AUI layouts). if (!(GetWindowStyle() & wxTB_NODIVIDER)) sizeBest.y += 2; sizeBest.y ++; } CacheBestSize(sizeBest); return sizeBest; } WXDWORD wxToolBar::MSWGetStyle(long style, WXDWORD *exstyle) const { // toolbars never have border, giving one to them results in broken // appearance WXDWORD msStyle = wxControl::MSWGetStyle ( (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle ); if ( !(style & wxTB_NO_TOOLTIPS) ) msStyle |= TBSTYLE_TOOLTIPS; if ( style & (wxTB_FLAT | wxTB_HORZ_LAYOUT) ) { // static as it doesn't change during the program lifetime static const int s_verComCtl = wxApp::GetComCtl32Version(); // comctl32.dll 4.00 doesn't support the flat toolbars and using this // style with 6.00 (part of Windows XP) leads to the toolbar with // incorrect background colour - and not using it still results in the // correct (flat) toolbar, so don't use it there if ( s_verComCtl > 400 && s_verComCtl < 600 ) msStyle |= TBSTYLE_FLAT | TBSTYLE_TRANSPARENT; if ( s_verComCtl >= 470 && style & wxTB_HORZ_LAYOUT ) msStyle |= TBSTYLE_LIST; } if ( style & wxTB_NODIVIDER ) msStyle |= CCS_NODIVIDER; if ( style & wxTB_NOALIGN ) msStyle |= CCS_NOPARENTALIGN; if ( style & wxTB_VERTICAL ) msStyle |= CCS_VERT; if( style & wxTB_BOTTOM ) msStyle |= CCS_BOTTOM; if ( style & wxTB_RIGHT ) msStyle |= CCS_RIGHT; return msStyle; } // ---------------------------------------------------------------------------- // adding/removing tools // ---------------------------------------------------------------------------- bool wxToolBar::DoInsertTool(size_t WXUNUSED(pos), wxToolBarToolBase *tool) { // nothing special to do here - we really create the toolbar buttons in // Realize() later tool->Attach(this); InvalidateBestSize(); return true; } bool wxToolBar::DoDeleteTool(size_t pos, wxToolBarToolBase *tool) { // the main difficulty we have here is with the controls in the toolbars: // as we (sometimes) use several separators to cover up the space used by // them, the indices are not the same for us and the toolbar // first determine the position of the first button to delete: it may be // different from pos if we use several separators to cover the space used // by a control wxToolBarToolsList::compatibility_iterator node; for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool2 = node->GetData(); if ( tool2 == tool ) { // let node point to the next node in the list node = node->GetNext(); break; } if ( tool2->IsControl() ) pos += ((wxToolBarTool *)tool2)->GetSeparatorsCount() - 1; } // now determine the number of buttons to delete and the area taken by them size_t nButtonsToDelete = 1; // get the size of the button we're going to delete RECT r; if ( !::SendMessage(GetHwnd(), TB_GETITEMRECT, pos, (LPARAM)&r) ) { wxLogLastError(_T("TB_GETITEMRECT")); } int width = r.right - r.left; if ( tool->IsControl() ) { nButtonsToDelete = ((wxToolBarTool *)tool)->GetSeparatorsCount(); width *= nButtonsToDelete; tool->GetControl()->Destroy(); } // do delete all buttons m_nButtons -= nButtonsToDelete; while ( nButtonsToDelete-- > 0 ) { if ( !::SendMessage(GetHwnd(), TB_DELETEBUTTON, pos, 0) ) { wxLogLastError(wxT("TB_DELETEBUTTON")); return false; } } tool->Detach(); // and finally reposition all the controls after this button (the toolbar // takes care of all normal items) for ( /* node -> first after deleted */ ; node; node = node->GetNext() ) { wxToolBarToolBase *tool2 = node->GetData(); if ( tool2->IsControl() ) { int x; wxControl *control = tool2->GetControl(); control->GetPosition(&x, NULL); control->Move(x - width, wxDefaultCoord); } } InvalidateBestSize(); return true; } void wxToolBar::CreateDisabledImageList() { if (m_disabledImgList != NULL) { delete m_disabledImgList; m_disabledImgList = NULL; } // as we can't use disabled image list with older versions of comctl32.dll, // don't even bother creating it if ( wxApp::GetComCtl32Version() >= 470 ) { // search for the first disabled button img in the toolbar, if any for ( wxToolBarToolsList::compatibility_iterator node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); wxBitmap bmpDisabled = tool->GetDisabledBitmap(); if ( bmpDisabled.Ok() ) { m_disabledImgList = new wxImageList ( m_defaultWidth, m_defaultHeight, bmpDisabled.GetMask() != NULL, GetToolsCount() ); break; } } // we don't have any disabled bitmaps } } void wxToolBar::AdjustToolBitmapSize() { wxSize s(m_defaultWidth, m_defaultHeight); const wxSize orig_s(s); for ( wxToolBarToolsList::const_iterator i = m_tools.begin(); i != m_tools.end(); ++i ) { const wxBitmap& bmp = (*i)->GetNormalBitmap(); s.IncTo(wxSize(bmp.GetWidth(), bmp.GetHeight())); } if ( s != orig_s ) SetToolBitmapSize(s); } bool wxToolBar::Realize() { const size_t nTools = GetToolsCount(); if ( nTools == 0 ) // nothing to do return true; // make sure tool size is larger enough for all all bitmaps to fit in // (this is consistent with what other ports do): AdjustToolBitmapSize(); #ifdef wxREMAP_BUTTON_COLOURS // don't change the values of these constants, they can be set from the // user code via wxSystemOptions enum { Remap_None = -1, Remap_Bg, Remap_Buttons, Remap_TransparentBg }; // the user-specified option overrides anything, but if it wasn't set, only // remap the buttons on 8bpp displays as otherwise the bitmaps usually look // much worse after remapping static const wxChar *remapOption = wxT("msw.remap"); const int remapValue = wxSystemOptions::HasOption(remapOption) ? wxSystemOptions::GetOptionInt(remapOption) : wxDisplayDepth() <= 8 ? Remap_Buttons : Remap_None; #endif // wxREMAP_BUTTON_COLOURS // delete all old buttons, if any for ( size_t pos = 0; pos < m_nButtons; pos++ ) { if ( !::SendMessage(GetHwnd(), TB_DELETEBUTTON, 0, 0) ) { wxLogDebug(wxT("TB_DELETEBUTTON failed")); } } // First, add the bitmap: we use one bitmap for all toolbar buttons // ---------------------------------------------------------------- wxToolBarToolsList::compatibility_iterator node; int bitmapId = 0; wxSize sizeBmp; if ( HasFlag(wxTB_NOICONS) ) { // no icons, don't leave space for them sizeBmp.x = sizeBmp.y = 0; } else // do show icons { // if we already have a bitmap, we'll replace the existing one -- // otherwise we'll install a new one HBITMAP oldToolBarBitmap = (HBITMAP)m_hBitmap; sizeBmp.x = m_defaultWidth; sizeBmp.y = m_defaultHeight; const wxCoord totalBitmapWidth = m_defaultWidth * wx_truncate_cast(wxCoord, nTools), totalBitmapHeight = m_defaultHeight; // Create a bitmap and copy all the tool bitmaps into it wxMemoryDC dcAllButtons; wxBitmap bitmap(totalBitmapWidth, totalBitmapHeight); dcAllButtons.SelectObject(bitmap); #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue != Remap_TransparentBg ) #endif // wxREMAP_BUTTON_COLOURS { // VZ: why do we hardcode grey colour for CE? dcAllButtons.SetBackground(wxBrush( #ifdef __WXWINCE__ wxColour(0xc0, 0xc0, 0xc0) #else // !__WXWINCE__ GetBackgroundColour() #endif // __WXWINCE__/!__WXWINCE__ )); dcAllButtons.Clear(); } m_hBitmap = bitmap.GetHBITMAP(); HBITMAP hBitmap = (HBITMAP)m_hBitmap; #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Bg ) { dcAllButtons.SelectObject(wxNullBitmap); // Even if we're not remapping the bitmap // content, we still have to remap the background. hBitmap = (HBITMAP)MapBitmap((WXHBITMAP) hBitmap, totalBitmapWidth, totalBitmapHeight); dcAllButtons.SelectObject(bitmap); } #endif // wxREMAP_BUTTON_COLOURS // the button position wxCoord x = 0; // the number of buttons (not separators) int nButtons = 0; CreateDisabledImageList(); for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); if ( tool->IsButton() ) { const wxBitmap& bmp = tool->GetNormalBitmap(); const int w = bmp.GetWidth(); const int h = bmp.GetHeight(); if ( bmp.Ok() ) { int xOffset = wxMax(0, (m_defaultWidth - w)/2); int yOffset = wxMax(0, (m_defaultHeight - h)/2); // notice the last parameter: do use mask dcAllButtons.DrawBitmap(bmp, x + xOffset, yOffset, true); } else { wxFAIL_MSG( _T("invalid tool button bitmap") ); } // also deal with disabled bitmap if we want to use them if ( m_disabledImgList ) { wxBitmap bmpDisabled = tool->GetDisabledBitmap(); #if wxUSE_IMAGE && wxUSE_WXDIB if ( !bmpDisabled.Ok() ) { // no disabled bitmap specified but we still need to // fill the space in the image list with something, so // we grey out the normal bitmap wxImage imgGreyed; wxCreateGreyedImage(bmp.ConvertToImage(), imgGreyed); #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Buttons ) { // we need to have light grey background colour for // MapBitmap() to work correctly for ( int y = 0; y < h; y++ ) { for ( int x = 0; x < w; x++ ) { if ( imgGreyed.IsTransparent(x, y) ) imgGreyed.SetRGB(x, y, wxLIGHT_GREY->Red(), wxLIGHT_GREY->Green(), wxLIGHT_GREY->Blue()); } } } #endif // wxREMAP_BUTTON_COLOURS bmpDisabled = wxBitmap(imgGreyed); } #endif // wxUSE_IMAGE #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Buttons ) MapBitmap(bmpDisabled.GetHBITMAP(), w, h); #endif // wxREMAP_BUTTON_COLOURS m_disabledImgList->Add(bmpDisabled); } // still inc width and number of buttons because otherwise the // subsequent buttons will all be shifted which is rather confusing // (and like this you'd see immediately which bitmap was bad) x += m_defaultWidth; nButtons++; } } dcAllButtons.SelectObject(wxNullBitmap); // don't delete this HBITMAP! bitmap.SetHBITMAP(0); #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Buttons ) { // Map to system colours hBitmap = (HBITMAP)MapBitmap((WXHBITMAP) hBitmap, totalBitmapWidth, totalBitmapHeight); } #endif // wxREMAP_BUTTON_COLOURS bool addBitmap = true; if ( oldToolBarBitmap ) { #ifdef TB_REPLACEBITMAP if ( wxApp::GetComCtl32Version() >= 400 ) { TBREPLACEBITMAP replaceBitmap; replaceBitmap.hInstOld = NULL; replaceBitmap.hInstNew = NULL; replaceBitmap.nIDOld = (UINT) oldToolBarBitmap; replaceBitmap.nIDNew = (UINT) hBitmap; replaceBitmap.nButtons = nButtons; if ( !::SendMessage(GetHwnd(), TB_REPLACEBITMAP, 0, (LPARAM) &replaceBitmap) ) { wxFAIL_MSG(wxT("Could not replace the old bitmap")); } ::DeleteObject(oldToolBarBitmap); // already done addBitmap = false; } else #endif // TB_REPLACEBITMAP { // we can't replace the old bitmap, so we will add another one // (awfully inefficient, but what else to do?) and shift the bitmap // indices accordingly addBitmap = true; bitmapId = m_nButtons; } } if ( addBitmap ) // no old bitmap or we can't replace it { TBADDBITMAP addBitmap; addBitmap.hInst = 0; addBitmap.nID = (UINT) hBitmap; if ( ::SendMessage(GetHwnd(), TB_ADDBITMAP, (WPARAM) nButtons, (LPARAM)&addBitmap) == -1 ) { wxFAIL_MSG(wxT("Could not add bitmap to toolbar")); } } // disable image lists are only supported in comctl32.dll 4.70+ if ( wxApp::GetComCtl32Version() >= 470 ) { HIMAGELIST hil = m_disabledImgList ? GetHimagelistOf(m_disabledImgList) : 0; // notice that we set the image list even if don't have one right // now as we could have it before and need to reset it in this case HIMAGELIST oldImageList = (HIMAGELIST) ::SendMessage(GetHwnd(), TB_SETDISABLEDIMAGELIST, 0, (LPARAM)hil); // delete previous image list if any if ( oldImageList ) ::DeleteObject(oldImageList); } } // don't call SetToolBitmapSize() as we don't want to change the values of // m_defaultWidth/Height if ( !::SendMessage(GetHwnd(), TB_SETBITMAPSIZE, 0, MAKELONG(sizeBmp.x, sizeBmp.y)) ) { wxLogLastError(_T("TB_SETBITMAPSIZE")); } // Next add the buttons and separators // ----------------------------------- TBBUTTON *buttons = new TBBUTTON[nTools]; // this array will hold the indices of all controls in the toolbar wxArrayInt controlIds; bool lastWasRadio = false; int i = 0; for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); // don't add separators to the vertical toolbar with old comctl32.dll // versions as they didn't handle this properly if ( IsVertical() && tool->IsSeparator() && wxApp::GetComCtl32Version() <= 472 ) { continue; } TBBUTTON& button = buttons[i]; wxZeroMemory(button); bool isRadio = false; switch ( tool->GetStyle() ) { case wxTOOL_STYLE_CONTROL: button.idCommand = tool->GetId(); // fall through: create just a separator too case wxTOOL_STYLE_SEPARATOR: button.fsState = TBSTATE_ENABLED; button.fsStyle = TBSTYLE_SEP; break; case wxTOOL_STYLE_BUTTON: if ( !HasFlag(wxTB_NOICONS) ) button.iBitmap = bitmapId; if ( HasFlag(wxTB_TEXT) ) { const wxString& label = tool->GetLabel(); if ( !label.empty() ) button.iString = (int)label.c_str(); } button.idCommand = tool->GetId(); if ( tool->IsEnabled() ) button.fsState |= TBSTATE_ENABLED; if ( tool->IsToggled() ) button.fsState |= TBSTATE_CHECKED; switch ( tool->GetKind() ) { case wxITEM_RADIO: button.fsStyle = TBSTYLE_CHECKGROUP; if ( !lastWasRadio ) { // the first item in the radio group is checked by // default to be consistent with wxGTK and the menu // radio items button.fsState |= TBSTATE_CHECKED; if (tool->Toggle(true)) { DoToggleTool(tool, true); } } else if ( tool->IsToggled() ) { wxToolBarToolsList::compatibility_iterator nodePrev = node->GetPrevious(); int prevIndex = i - 1; while ( nodePrev ) { TBBUTTON& prevButton = buttons[prevIndex]; wxToolBarToolBase *tool = nodePrev->GetData(); if ( !tool->IsButton() || tool->GetKind() != wxITEM_RADIO ) break; if ( tool->Toggle(false) ) DoToggleTool(tool, false); prevButton.fsState &= ~TBSTATE_CHECKED; nodePrev = nodePrev->GetPrevious(); prevIndex--; } } isRadio = true; break; case wxITEM_CHECK: button.fsStyle = TBSTYLE_CHECK; break; case wxITEM_NORMAL: button.fsStyle = TBSTYLE_BUTTON; break; default: wxFAIL_MSG( _T("unexpected toolbar button kind") ); button.fsStyle = TBSTYLE_BUTTON; break; } bitmapId++; break; } lastWasRadio = isRadio; i++; } if ( !::SendMessage(GetHwnd(), TB_ADDBUTTONS, (WPARAM)i, (LPARAM)buttons) ) { wxLogLastError(wxT("TB_ADDBUTTONS")); } delete [] buttons; // Deal with the controls finally // ------------------------------ // adjust the controls size to fit nicely in the toolbar int y = 0; size_t index = 0; for ( node = m_tools.GetFirst(); node; node = node->GetNext(), index++ ) { wxToolBarToolBase *tool = node->GetData(); // we calculate the running y coord for vertical toolbars so we need to // get the items size for all items but for the horizontal ones we // don't need to deal with the non controls bool isControl = tool->IsControl(); if ( !isControl && !IsVertical() ) continue; // note that we use TB_GETITEMRECT and not TB_GETRECT because the // latter only appeared in v4.70 of comctl32.dll RECT r; if ( !::SendMessage(GetHwnd(), TB_GETITEMRECT, index, (LPARAM)(LPRECT)&r) ) { wxLogLastError(wxT("TB_GETITEMRECT")); } if ( !isControl ) { // can only be control if isVertical y += r.bottom - r.top; continue; } wxControl *control = tool->GetControl(); wxSize size = control->GetSize(); // the position of the leftmost controls corner int left = wxDefaultCoord; // TB_SETBUTTONINFO message is only supported by comctl32.dll 4.71+ #ifdef TB_SETBUTTONINFO // available in headers, now check whether it is available now // (during run-time) if ( wxApp::GetComCtl32Version() >= 471 ) { // set the (underlying) separators width to be that of the // control TBBUTTONINFO tbbi; tbbi.cbSize = sizeof(tbbi); tbbi.dwMask = TBIF_SIZE; tbbi.cx = (WORD)size.x; if ( !::SendMessage(GetHwnd(), TB_SETBUTTONINFO, tool->GetId(), (LPARAM)&tbbi) ) { // the id is probably invalid? wxLogLastError(wxT("TB_SETBUTTONINFO")); } } else #endif // comctl32.dll 4.71 // TB_SETBUTTONINFO unavailable { // try adding several separators to fit the controls width int widthSep = r.right - r.left; left = r.left; TBBUTTON tbb; wxZeroMemory(tbb); tbb.idCommand = 0; tbb.fsState = TBSTATE_ENABLED; tbb.fsStyle = TBSTYLE_SEP; size_t nSeparators = size.x / widthSep; for ( size_t nSep = 0; nSep < nSeparators; nSep++ ) { if ( !::SendMessage(GetHwnd(), TB_INSERTBUTTON, index, (LPARAM)&tbb) ) { wxLogLastError(wxT("TB_INSERTBUTTON")); } index++; } // remember the number of separators we used - we'd have to // delete all of them later ((wxToolBarTool *)tool)->SetSeparatorsCount(nSeparators); // adjust the controls width to exactly cover the separators control->SetSize((nSeparators + 1)*widthSep, wxDefaultCoord); } // position the control itself correctly vertically int height = r.bottom - r.top; int diff = height - size.y; if ( diff < 0 ) { // the control is too high, resize to fit control->SetSize(wxDefaultCoord, height - 2); diff = 2; } int top; if ( IsVertical() ) { left = 0; top = y; y += height + 2 * GetMargins().y; } else // horizontal toolbar { if ( left == wxDefaultCoord ) left = r.left; top = r.top; } control->Move(left, top + (diff + 1) / 2); } // the max index is the "real" number of buttons - i.e. counting even the // separators which we added just for aligning the controls m_nButtons = index; if ( !IsVertical() ) { if ( m_maxRows == 0 ) // if not set yet, only one row SetRows(1); } else if ( m_nButtons > 0 ) // vertical non empty toolbar { // if not set yet, have one column m_maxRows = 1; SetRows(m_nButtons); } InvalidateBestSize(); UpdateSize(); return true; } // ---------------------------------------------------------------------------- // message handlers // ---------------------------------------------------------------------------- bool wxToolBar::MSWCommand(WXUINT WXUNUSED(cmd), WXWORD id) { wxToolBarToolBase *tool = FindById((int)id); if ( !tool ) return false; bool toggled = false; // just to suppress warnings LRESULT state = ::SendMessage(GetHwnd(), TB_GETSTATE, id, 0); if ( tool->CanBeToggled() ) { toggled = (state & TBSTATE_CHECKED) != 0; // ignore the event when a radio button is released, as this doesn't // seem to happen at all, and is handled otherwise if ( tool->GetKind() == wxITEM_RADIO && !toggled ) return true; tool->Toggle(toggled); UnToggleRadioGroup(tool); } // Without the two lines of code below, if the toolbar was repainted during // OnLeftClick(), then it could end up without the tool bitmap temporarily // (see http://lists.nongnu.org/archive/html/lmi/2008-10/msg00014.html). // The Update() call bellow ensures that this won't happen, by repainting // invalidated areas of the toolbar immediately. // // To complicate matters, the tool would be drawn in depressed state (this // code is called when mouse button is released, not pressed). That's not // ideal, having the tool pressed for the duration of OnLeftClick() // provides the user with useful visual clue that the app is busy reacting // to the event. So we manually put the tool into pressed state, handle the // event and then finally restore tool's original state. ::SendMessage(GetHwnd(), TB_SETSTATE, id, MAKELONG(state | TBSTATE_PRESSED, 0)); Update(); bool allowLeftClick = OnLeftClick((int)id, toggled); // Restore the unpressed state. Enabled/toggled state might have been // changed since so take care of it. if (tool->IsEnabled()) state |= TBSTATE_ENABLED; else state &= ~TBSTATE_ENABLED; if (tool->IsToggled()) state |= TBSTATE_CHECKED; else state &= ~TBSTATE_CHECKED; ::SendMessage(GetHwnd(), TB_SETSTATE, id, MAKELONG(state, 0)); // OnLeftClick() can veto the button state change - for buttons which // may be toggled only, of couse if ( !allowLeftClick && tool->CanBeToggled() ) { // revert back tool->Toggle(!toggled); ::SendMessage(GetHwnd(), TB_CHECKBUTTON, id, MAKELONG(!toggled, 0)); } return true; } bool wxToolBar::MSWOnNotify(int WXUNUSED(idCtrl), WXLPARAM lParam, WXLPARAM *WXUNUSED(result)) { if( !HasFlag(wxTB_NO_TOOLTIPS) ) { #if wxUSE_TOOLTIPS // First check if this applies to us NMHDR *hdr = (NMHDR *)lParam; // the tooltips control created by the toolbar is sometimes Unicode, even // in an ANSI application - this seems to be a bug in comctl32.dll v5 UINT code = hdr->code; if ( (code != (UINT) TTN_NEEDTEXTA) && (code != (UINT) TTN_NEEDTEXTW) ) return false; HWND toolTipWnd = (HWND)::SendMessage(GetHwnd(), TB_GETTOOLTIPS, 0, 0); if ( toolTipWnd != hdr->hwndFrom ) return false; LPTOOLTIPTEXT ttText = (LPTOOLTIPTEXT)lParam; int id = (int)ttText->hdr.idFrom; wxToolBarToolBase *tool = FindById(id); if ( tool ) return HandleTooltipNotify(code, lParam, tool->GetShortHelp()); #else wxUnusedVar(lParam); #endif } return false; } // ---------------------------------------------------------------------------- // toolbar geometry // ---------------------------------------------------------------------------- void wxToolBar::SetToolBitmapSize(const wxSize& size) { wxToolBarBase::SetToolBitmapSize(size); ::SendMessage(GetHwnd(), TB_SETBITMAPSIZE, 0, MAKELONG(size.x, size.y)); } void wxToolBar::SetRows(int nRows) { if ( nRows == m_maxRows ) { // avoid resizing the frame uselessly return; } // TRUE in wParam means to create at least as many rows, FALSE - // at most as many RECT rect; ::SendMessage(GetHwnd(), TB_SETROWS, MAKEWPARAM(nRows, !(GetWindowStyle() & wxTB_VERTICAL)), (LPARAM) &rect); m_maxRows = nRows; UpdateSize(); } // The button size is bigger than the bitmap size wxSize wxToolBar::GetToolSize() const { // TB_GETBUTTONSIZE is supported from version 4.70 #if defined(_WIN32_IE) && (_WIN32_IE >= 0x300 ) \ && !( defined(__GNUWIN32__) && !wxCHECK_W32API_VERSION( 1, 0 ) ) \ && !defined (__DIGITALMARS__) if ( wxApp::GetComCtl32Version() >= 470 ) { DWORD dw = ::SendMessage(GetHwnd(), TB_GETBUTTONSIZE, 0, 0); return wxSize(LOWORD(dw), HIWORD(dw)); } else #endif // comctl32.dll 4.70+ { // defaults return wxSize(m_defaultWidth + 8, m_defaultHeight + 7); } } static wxToolBarToolBase *GetItemSkippingDummySpacers(const wxToolBarToolsList& tools, size_t index ) { wxToolBarToolsList::compatibility_iterator current = tools.GetFirst(); for ( ; current ; current = current->GetNext() ) { if ( index == 0 ) return current->GetData(); wxToolBarTool *tool = (wxToolBarTool *)current->GetData(); size_t separators = tool->GetSeparatorsCount(); // if it is a normal button, sepcount == 0, so skip 1 item (the button) // otherwise, skip as many items as the separator count, plus the // control itself index -= separators ? separators + 1 : 1; } return 0; } wxToolBarToolBase *wxToolBar::FindToolForPosition(wxCoord x, wxCoord y) const { POINT pt; pt.x = x; pt.y = y; int index = (int)::SendMessage(GetHwnd(), TB_HITTEST, 0, (LPARAM)&pt); // MBN: when the point ( x, y ) is close to the toolbar border // TB_HITTEST returns m_nButtons ( not -1 ) if ( index < 0 || (size_t)index >= m_nButtons ) // it's a separator or there is no tool at all there return (wxToolBarToolBase *)NULL; // when TB_SETBUTTONINFO is available (both during compile- and run-time), // we don't use the dummy separators hack #ifdef TB_SETBUTTONINFO if ( wxApp::GetComCtl32Version() >= 471 ) { return m_tools.Item((size_t)index)->GetData(); } else #endif // TB_SETBUTTONINFO { return GetItemSkippingDummySpacers( m_tools, (size_t) index ); } } void wxToolBar::UpdateSize() { wxPoint pos = GetPosition(); ::SendMessage(GetHwnd(), TB_AUTOSIZE, 0, 0); if (pos != GetPosition()) Move(pos); // In case Realize is called after the initial display (IOW the programmer // may have rebuilt the toolbar) give the frame the option of resizing the // toolbar to full width again, but only if the parent is a frame and the // toolbar is managed by the frame. Otherwise assume that some other // layout mechanism is controlling the toolbar size and leave it alone. wxFrame *frame = wxDynamicCast(GetParent(), wxFrame); if ( frame && frame->GetToolBar() == this ) { frame->SendSizeEvent(); } } // ---------------------------------------------------------------------------- // toolbar styles // --------------------------------------------------------------------------- // get the TBSTYLE of the given toolbar window long wxToolBar::GetMSWToolbarStyle() const { return ::SendMessage(GetHwnd(), TB_GETSTYLE, 0, 0L); } void wxToolBar::SetWindowStyleFlag(long style) { // the style bits whose changes force us to recreate the toolbar static const long MASK_NEEDS_RECREATE = wxTB_TEXT | wxTB_NOICONS; const long styleOld = GetWindowStyle(); wxToolBarBase::SetWindowStyleFlag(style); // don't recreate an empty toolbar: not only this is unnecessary, but it is // also fatal as we'd then try to recreate the toolbar when it's just being // created if ( GetToolsCount() && (style & MASK_NEEDS_RECREATE) != (styleOld & MASK_NEEDS_RECREATE) ) { // to remove the text labels, simply re-realizing the toolbar is enough // but I don't know of any way to add the text to an existing toolbar // other than by recreating it entirely Recreate(); } } // ---------------------------------------------------------------------------- // tool state // ---------------------------------------------------------------------------- void wxToolBar::DoEnableTool(wxToolBarToolBase *tool, bool enable) { ::SendMessage(GetHwnd(), TB_ENABLEBUTTON, (WPARAM)tool->GetId(), (LPARAM)MAKELONG(enable, 0)); } void wxToolBar::DoToggleTool(wxToolBarToolBase *tool, bool toggle) { ::SendMessage(GetHwnd(), TB_CHECKBUTTON, (WPARAM)tool->GetId(), (LPARAM)MAKELONG(toggle, 0)); } void wxToolBar::DoSetToggle(wxToolBarToolBase *WXUNUSED(tool), bool WXUNUSED(toggle)) { // VZ: AFAIK, the button has to be created either with TBSTYLE_CHECK or // without, so we really need to delete the button and recreate it here wxFAIL_MSG( _T("not implemented") ); } void wxToolBar::SetToolNormalBitmap( int id, const wxBitmap& bitmap ) { wxToolBarTool* tool = wx_static_cast(wxToolBarTool*, FindById(id)); if ( tool ) { wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools.")); tool->SetNormalBitmap(bitmap); Realize(); } } void wxToolBar::SetToolDisabledBitmap( int id, const wxBitmap& bitmap ) { wxToolBarTool* tool = wx_static_cast(wxToolBarTool*, FindById(id)); if ( tool ) { wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools.")); tool->SetDisabledBitmap(bitmap); Realize(); } } // ---------------------------------------------------------------------------- // event handlers // ---------------------------------------------------------------------------- // Responds to colour changes, and passes event on to children. void wxToolBar::OnSysColourChanged(wxSysColourChangedEvent& event) { wxRGBToColour(m_backgroundColour, ::GetSysColor(COLOR_BTNFACE)); // Remap the buttons Realize(); // Relayout the toolbar int nrows = m_maxRows; m_maxRows = 0; // otherwise SetRows() wouldn't do anything SetRows(nrows); Refresh(); // let the event propagate further event.Skip(); } void wxToolBar::OnMouseEvent(wxMouseEvent& event) { if (event.Leaving() && m_pInTool) { OnMouseEnter( -1 ); event.Skip(); return; } if ( event.RightDown() ) { // find the tool under the mouse wxCoord x = 0, y = 0; event.GetPosition(&x, &y); wxToolBarToolBase *tool = FindToolForPosition(x, y); OnRightClick(tool ? tool->GetId() : -1, x, y); } else { event.Skip(); } } // This handler is required to allow the toolbar to be set to a non-default // colour: for example, when it must blend in with a notebook page. void wxToolBar::OnEraseBackground(wxEraseEvent& event) { RECT rect = wxGetClientRect(GetHwnd()); HDC hdc = GetHdcOf((*event.GetDC())); int majorVersion, minorVersion; wxGetOsVersion(& majorVersion, & minorVersion); #if wxUSE_UXTHEME // we may need to draw themed colour so that we appear correctly on // e.g. notebook page under XP with themes but only do it if the parent // draws themed background itself if ( !UseBgCol() && !GetParent()->UseBgCol() ) { wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive(); if ( theme ) { HRESULT hr = theme->DrawThemeParentBackground(GetHwnd(), hdc, &rect); if ( hr == S_OK ) return; // it can also return S_FALSE which seems to simply say that it // didn't draw anything but no error really occurred if ( FAILED(hr) ) wxLogApiError(_T("DrawThemeParentBackground(toolbar)"), hr); } } // Only draw a rebar theme on Vista, since it doesn't jive so well with XP if ( !UseBgCol() && majorVersion >= 6 ) { wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive(); if ( theme ) { wxUxThemeHandle hTheme(this, L"REBAR"); RECT r; wxRect rect = GetClientRect(); wxCopyRectToRECT(rect, r); HRESULT hr = theme->DrawThemeBackground(hTheme, hdc, 0, 0, & r, NULL); if ( hr == S_OK ) return; // it can also return S_FALSE which seems to simply say that it // didn't draw anything but no error really occurred if ( FAILED(hr) ) wxLogApiError(_T("DrawThemeBackground(toolbar)"), hr); } } #endif // wxUSE_UXTHEME if ( UseBgCol() || (GetMSWToolbarStyle() & TBSTYLE_TRANSPARENT) ) { // do draw our background // // notice that this 'dumb' implementation may cause flicker for some of // the controls in which case they should intercept wxEraseEvent and // process it themselves somehow AutoHBRUSH hBrush(wxColourToRGB(GetBackgroundColour())); wxCHANGE_HDC_MAP_MODE(hdc, MM_TEXT); ::FillRect(hdc, &rect, hBrush); } else // we have no non default background colour { // let the system do it for us event.Skip(); } } bool wxToolBar::HandleSize(WXWPARAM WXUNUSED(wParam), WXLPARAM lParam) { // calculate our minor dimension ourselves - we're confusing the standard // logic (TB_AUTOSIZE) with our horizontal toolbars and other hacks RECT r; if ( ::SendMessage(GetHwnd(), TB_GETITEMRECT, 0, (LPARAM)&r) ) { int w, h; if ( IsVertical() ) { w = r.right - r.left; if ( m_maxRows ) { w *= (m_nButtons + m_maxRows - 1)/m_maxRows; } h = HIWORD(lParam); } else { w = LOWORD(lParam); if (HasFlag( wxTB_FLAT )) h = r.bottom - r.top - 3; else h = r.bottom - r.top; if ( m_maxRows ) { // FIXME: hardcoded separator line height... h += HasFlag(wxTB_NODIVIDER) ? 4 : 6; h *= m_maxRows; } } if ( MAKELPARAM(w, h) != lParam ) { // size really changed SetSize(w, h); } // message processed return true; } return false; } bool wxToolBar::HandlePaint(WXWPARAM wParam, WXLPARAM lParam) { // erase any dummy separators which were used // for aligning the controls if any here // first of all, are there any controls at all? wxToolBarToolsList::compatibility_iterator node; for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { if ( node->GetData()->IsControl() ) break; } if ( !node ) // no controls, nothing to erase return false; wxSize clientSize = GetClientSize(); int majorVersion, minorVersion; wxGetOsVersion(& majorVersion, & minorVersion); // prepare the DC on which we'll be drawing // prepare the DC on which we'll be drawing wxClientDC dc(this); dc.SetBrush(wxBrush(GetBackgroundColour(), wxSOLID)); dc.SetPen(*wxTRANSPARENT_PEN); RECT r; if ( !::GetUpdateRect(GetHwnd(), &r, FALSE) ) // nothing to redraw anyhow return false; wxRect rectUpdate; wxCopyRECTToRect(r, rectUpdate); dc.SetClippingRegion(rectUpdate); // draw the toolbar tools, separators &c normally wxControl::MSWWindowProc(WM_PAINT, wParam, lParam); // for each control in the toolbar find all the separators intersecting it // and erase them // // NB: this is really the only way to do it as we don't know if a separator // corresponds to a control (i.e. is a dummy one) or a real one // otherwise for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); if ( tool->IsControl() ) { // get the control rect in our client coords wxControl *control = tool->GetControl(); wxRect rectCtrl = control->GetRect(); // iterate over all buttons TBBUTTON tbb; int count = ::SendMessage(GetHwnd(), TB_BUTTONCOUNT, 0, 0); for ( int n = 0; n < count; n++ ) { // is it a separator? if ( !::SendMessage(GetHwnd(), TB_GETBUTTON, n, (LPARAM)&tbb) ) { wxLogDebug(_T("TB_GETBUTTON failed?")); continue; } if ( tbb.fsStyle != TBSTYLE_SEP ) continue; // get the bounding rect of the separator RECT r; if ( !::SendMessage(GetHwnd(), TB_GETITEMRECT, n, (LPARAM)&r) ) { wxLogDebug(_T("TB_GETITEMRECT failed?")); continue; } // does it intersect the control? wxRect rectItem; wxCopyRECTToRect(r, rectItem); if ( rectCtrl.Intersects(rectItem) ) { // yes, do erase it! bool haveRefreshed = false; #if wxUSE_UXTHEME if ( !UseBgCol() && !GetParent()->UseBgCol() ) { // Don't use DrawThemeBackground } else if (!UseBgCol() && majorVersion >= 6 ) { wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive(); if ( theme ) { wxUxThemeHandle hTheme(this, L"REBAR"); RECT clipRect = r; // Draw the whole background since the pattern may be position sensitive; // but clip it to the area of interest. r.left = 0; r.right = clientSize.x; r.top = 0; r.bottom = clientSize.y; HRESULT hr = theme->DrawThemeBackground(hTheme, (HDC) dc.GetHDC(), 0, 0, & r, & clipRect); if ( hr == S_OK ) haveRefreshed = true; } } #endif if (!haveRefreshed) dc.DrawRectangle(rectItem); // Necessary in case we use a no-paint-on-size // style in the parent: the controls can disappear control->Refresh(false); } } } } return true; } void wxToolBar::HandleMouseMove(WXWPARAM WXUNUSED(wParam), WXLPARAM lParam) { wxCoord x = GET_X_LPARAM(lParam), y = GET_Y_LPARAM(lParam); wxToolBarToolBase* tool = FindToolForPosition( x, y ); // cursor left current tool if ( tool != m_pInTool && !tool ) { m_pInTool = 0; OnMouseEnter( -1 ); } // cursor entered a tool if ( tool != m_pInTool && tool ) { m_pInTool = tool; OnMouseEnter( tool->GetId() ); } } WXLRESULT wxToolBar::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) { switch ( nMsg ) { case WM_MOUSEMOVE: // we don't handle mouse moves, so always pass the message to // wxControl::MSWWindowProc (HandleMouseMove just calls OnMouseEnter) HandleMouseMove(wParam, lParam); break; case WM_SIZE: if ( HandleSize(wParam, lParam) ) return 0; break; #ifndef __WXWINCE__ case WM_PAINT: if ( HandlePaint(wParam, lParam) ) return 0; #endif default: break; } return wxControl::MSWWindowProc(nMsg, wParam, lParam); } // ---------------------------------------------------------------------------- // private functions // ---------------------------------------------------------------------------- #ifdef wxREMAP_BUTTON_COLOURS WXHBITMAP wxToolBar::MapBitmap(WXHBITMAP bitmap, int width, int height) { MemoryHDC hdcMem; if ( !hdcMem ) { wxLogLastError(_T("CreateCompatibleDC")); return bitmap; } SelectInHDC bmpInHDC(hdcMem, (HBITMAP)bitmap); if ( !bmpInHDC ) { wxLogLastError(_T("SelectObject")); return bitmap; } wxCOLORMAP *cmap = wxGetStdColourMap(); for ( int i = 0; i < width; i++ ) { for ( int j = 0; j < height; j++ ) { COLORREF pixel = ::GetPixel(hdcMem, i, j); for ( size_t k = 0; k < wxSTD_COL_MAX; k++ ) { COLORREF col = cmap[k].from; if ( abs(GetRValue(pixel) - GetRValue(col)) < 10 && abs(GetGValue(pixel) - GetGValue(col)) < 10 && abs(GetBValue(pixel) - GetBValue(col)) < 10 ) { if ( cmap[k].to != pixel ) ::SetPixel(hdcMem, i, j, cmap[k].to); break; } } } } return bitmap; } #endif // wxREMAP_BUTTON_COLOURS #endif // wxUSE_TOOLBAR
gpl-3.0
enovation/moodle
filter/activitynames/version.php
1206
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Version details * * @package filter * @subpackage activitynames * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2021052500; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2021052500; // Requires this Moodle version $plugin->component = 'filter_activitynames'; // Full name of the plugin (used for diagnostics)
gpl-3.0
newmessage/eathena-project
src/map/buyingstore.c
14965
// Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder #include "../common/cbasetypes.h" #include "../common/db.h" // ARR_FIND #include "../common/showmsg.h" // ShowWarning #include "../common/socket.h" // RBUF* #include "../common/strlib.h" // safestrncpy #include "atcommand.h" // msg_txt #include "battle.h" // battle_config.* #include "buyingstore.h" // struct s_buyingstore #include "clif.h" // clif_buyingstore_* #include "log.h" // log_pick, log_zeny #include "pc.h" // struct map_session_data /// constants (client-side restrictions) #define BUYINGSTORE_MAX_PRICE 99990000 #define BUYINGSTORE_MAX_AMOUNT 9999 /// failure constants for clif functions enum e_buyingstore_failure { BUYINGSTORE_CREATE = 1, // "Failed to open buying store." BUYINGSTORE_CREATE_OVERWEIGHT = 2, // "Total amount of then possessed items exceeds the weight limit by %d. Please re-enter." BUYINGSTORE_TRADE_BUYER_ZENY = 3, // "All items within the buy limit were purchased." BUYINGSTORE_TRADE_BUYER_NO_ITEMS = 4, // "All items were purchased." BUYINGSTORE_TRADE_SELLER_FAILED = 5, // "The deal has failed." BUYINGSTORE_TRADE_SELLER_COUNT = 6, // "The trade failed, because the entered amount of item %s is higher, than the buyer is willing to buy." BUYINGSTORE_TRADE_SELLER_ZENY = 7, // "The trade failed, because the buyer is lacking required balance." BUYINGSTORE_CREATE_NO_INFO = 8, // "No sale (purchase) information available." }; static unsigned int buyingstore_nextid = 0; static const short buyingstore_blankslots[MAX_SLOTS] = { 0 }; // used when checking whether or not an item's card slots are blank /// Returns unique buying store id static unsigned int buyingstore_getuid(void) { return buyingstore_nextid++; } bool buyingstore_setup(struct map_session_data* sd, unsigned char slots) { if( !battle_config.feature_buying_store || sd->state.vending || sd->state.buyingstore || sd->state.trading || slots == 0 ) { return false; } if( sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM) ) {// custom: mute limitation return false; } if( map[sd->bl.m].flag.novending ) {// custom: no vending maps clif_displaymessage(sd->fd, msg_txt(276)); // "You can't open a shop on this map" return false; } if( map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING) ) {// custom: no vending cells clif_displaymessage(sd->fd, msg_txt(204)); // "You can't open a shop on this cell." return false; } if( slots > MAX_BUYINGSTORE_SLOTS ) { ShowWarning("buyingstore_setup: Requested %d slots, but server supports only %d slots.\n", (int)slots, MAX_BUYINGSTORE_SLOTS); slots = MAX_BUYINGSTORE_SLOTS; } sd->buyingstore.slots = slots; clif_buyingstore_open(sd); return true; } void buyingstore_create(struct map_session_data* sd, int zenylimit, unsigned char result, const char* storename, const uint8* itemlist, unsigned int count) { unsigned int i, weight, listidx; struct item_data* id; if( !result || count == 0 ) {// canceled, or no items return; } if( !battle_config.feature_buying_store || pc_istrading(sd) || sd->buyingstore.slots == 0 || count > sd->buyingstore.slots || zenylimit <= 0 || zenylimit > sd->status.zeny || !storename[0] ) {// disabled or invalid input sd->buyingstore.slots = 0; clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0); return; } if( !pc_can_give_items(pc_isGM(sd)) ) {// custom: GM is not allowed to buy (give zeny) sd->buyingstore.slots = 0; clif_displaymessage(sd->fd, msg_txt(246)); clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0); return; } if( sd->sc.data[SC_NOCHAT] && (sd->sc.data[SC_NOCHAT]->val1&MANNER_NOROOM) ) {// custom: mute limitation return; } if( map[sd->bl.m].flag.novending ) {// custom: no vending maps clif_displaymessage(sd->fd, msg_txt(276)); // "You can't open a shop on this map" return; } if( map_getcell(sd->bl.m, sd->bl.x, sd->bl.y, CELL_CHKNOVENDING) ) {// custom: no vending cells clif_displaymessage(sd->fd, msg_txt(204)); // "You can't open a shop on this cell." return; } weight = sd->weight; // check item list for( i = 0; i < count; i++ ) {// itemlist: <name id>.W <amount>.W <price>.L unsigned short nameid, amount; int price, idx; nameid = RBUFW(itemlist,i*8+0); amount = RBUFW(itemlist,i*8+2); price = RBUFL(itemlist,i*8+4); if( ( id = itemdb_exists(nameid) ) == NULL || amount == 0 ) {// invalid input break; } if( price <= 0 || price > BUYINGSTORE_MAX_PRICE ) {// invalid price: unlike vending, items cannot be bought at 0 Zeny break; } if( !id->flag.buyingstore || !itemdb_cantrade_sub(id, pc_isGM(sd), pc_isGM(sd)) || ( idx = pc_search_inventory(sd, nameid) ) == -1 ) {// restrictions: allowed, no character-bound items and at least one must be owned break; } if( sd->status.inventory[idx].amount+amount > BUYINGSTORE_MAX_AMOUNT ) {// too many items of same kind break; } if( i ) {// duplicate check. as the client does this too, only malicious intent should be caught here ARR_FIND( 0, i, listidx, sd->buyingstore.items[listidx].nameid == nameid ); if( listidx != i ) {// duplicate ShowWarning("buyingstore_create: Found duplicate item on buying list (nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n", nameid, amount, sd->status.account_id, sd->status.char_id); break; } } weight+= id->weight*amount; sd->buyingstore.items[i].nameid = nameid; sd->buyingstore.items[i].amount = amount; sd->buyingstore.items[i].price = price; } if( i != count ) {// invalid item/amount/price sd->buyingstore.slots = 0; clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE, 0); return; } if( (sd->max_weight*90)/100 < weight ) {// not able to carry all wanted items without getting overweight (90%) sd->buyingstore.slots = 0; clif_buyingstore_open_failed(sd, BUYINGSTORE_CREATE_OVERWEIGHT, weight); return; } // success sd->state.buyingstore = true; sd->buyer_id = buyingstore_getuid(); sd->buyingstore.zenylimit = zenylimit; sd->buyingstore.slots = i; // store actual amount of items safestrncpy(sd->message, storename, sizeof(sd->message)); clif_buyingstore_myitemlist(sd); clif_buyingstore_entry(sd); } void buyingstore_close(struct map_session_data* sd) { if( sd->state.buyingstore ) { // invalidate data sd->state.buyingstore = false; memset(&sd->buyingstore, 0, sizeof(sd->buyingstore)); // notify other players clif_buyingstore_disappear_entry(sd); } } void buyingstore_open(struct map_session_data* sd, int account_id) { struct map_session_data* pl_sd; if( !battle_config.feature_buying_store || pc_istrading(sd) ) {// not allowed to sell return; } if( !pc_can_give_items(pc_isGM(sd)) ) {// custom: GM is not allowed to sell clif_displaymessage(sd->fd, msg_txt(246)); return; } if( ( pl_sd = map_id2sd(account_id) ) == NULL || !pl_sd->state.buyingstore ) {// not online or not buying return; } if( !searchstore_queryremote(sd, account_id) && ( sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE) ) ) {// out of view range return; } // success clif_buyingstore_itemlist(sd, pl_sd); } void buyingstore_trade(struct map_session_data* sd, int account_id, unsigned int buyer_id, const uint8* itemlist, unsigned int count) { int zeny = 0; unsigned int i, weight, listidx, k; struct map_session_data* pl_sd; if( count == 0 ) {// nothing to do return; } if( !battle_config.feature_buying_store || pc_istrading(sd) ) {// not allowed to sell clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0); return; } if( !pc_can_give_items(pc_isGM(sd)) ) {// custom: GM is not allowed to sell clif_displaymessage(sd->fd, msg_txt(246)); clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0); return; } if( ( pl_sd = map_id2sd(account_id) ) == NULL || !pl_sd->state.buyingstore || pl_sd->buyer_id != buyer_id ) {// not online, not buying or not same store clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0); return; } if( !searchstore_queryremote(sd, account_id) && ( sd->bl.m != pl_sd->bl.m || !check_distance_bl(&sd->bl, &pl_sd->bl, AREA_SIZE) ) ) {// out of view range clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, 0); return; } searchstore_clearremote(sd); if( pl_sd->status.zeny < pl_sd->buyingstore.zenylimit ) {// buyer lost zeny in the mean time? fix the limit pl_sd->buyingstore.zenylimit = pl_sd->status.zeny; } weight = pl_sd->weight; // check item list for( i = 0; i < count; i++ ) {// itemlist: <index>.W <name id>.W <amount>.W unsigned short nameid, amount; int index; index = RBUFW(itemlist,i*6+0)-2; nameid = RBUFW(itemlist,i*6+2); amount = RBUFW(itemlist,i*6+4); if( i ) {// duplicate check. as the client does this too, only malicious intent should be caught here ARR_FIND( 0, i, k, RBUFW(itemlist,k*6+0)-2 == index ); if( k != i ) {// duplicate ShowWarning("buyingstore_trade: Found duplicate item on selling list (prevnameid=%hu, prevamount=%hu, nameid=%hu, amount=%hu, account_id=%d, char_id=%d).\n", RBUFW(itemlist,k*6+2), RBUFW(itemlist,k*6+4), nameid, amount, sd->status.account_id, sd->status.char_id); clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid); return; } } if( index < 0 || index >= ARRAYLENGTH(sd->status.inventory) || sd->inventory_data[index] == NULL || sd->status.inventory[index].nameid != nameid || sd->status.inventory[index].amount < amount ) {// invalid input clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid); return; } if( sd->status.inventory[index].expire_time || !itemdb_cantrade(&sd->status.inventory[index], pc_isGM(sd), pc_isGM(pl_sd)) || memcmp(sd->status.inventory[index].card, buyingstore_blankslots, sizeof(buyingstore_blankslots)) ) {// non-tradable item clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid); return; } ARR_FIND( 0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == nameid ); if( listidx == pl_sd->buyingstore.slots || pl_sd->buyingstore.items[listidx].amount == 0 ) {// there is no such item or the buyer has already bought all of them clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid); return; } if( pl_sd->buyingstore.items[listidx].amount < amount ) {// buyer does not need that much of the item clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_COUNT, nameid); return; } if( pc_checkadditem(pl_sd, nameid, amount) == ADDITEM_OVERAMOUNT ) {// buyer does not have enough space for this item clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid); return; } if( amount*(unsigned int)sd->inventory_data[index]->weight > pl_sd->max_weight-weight ) {// normally this is not supposed to happen, as the total weight is // checked upon creation, but the buyer could have gained items clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_FAILED, nameid); return; } weight+= amount*sd->inventory_data[index]->weight; if( amount*pl_sd->buyingstore.items[listidx].price > pl_sd->buyingstore.zenylimit-zeny ) {// buyer does not have enough zeny clif_buyingstore_trade_failed_seller(sd, BUYINGSTORE_TRADE_SELLER_ZENY, nameid); return; } zeny+= amount*pl_sd->buyingstore.items[listidx].price; } // process item list for( i = 0; i < count; i++ ) {// itemlist: <index>.W <name id>.W <amount>.W unsigned short nameid, amount; int index; index = RBUFW(itemlist,i*6+0)-2; nameid = RBUFW(itemlist,i*6+2); amount = RBUFW(itemlist,i*6+4); ARR_FIND( 0, pl_sd->buyingstore.slots, listidx, pl_sd->buyingstore.items[listidx].nameid == nameid ); zeny = amount*pl_sd->buyingstore.items[listidx].price; // log log_pick(&sd->bl, LOG_TYPE_BUYING_STORE, nameid, -((int)amount), &sd->status.inventory[index]); log_pick(&pl_sd->bl, LOG_TYPE_BUYING_STORE, nameid, amount, &sd->status.inventory[index]); log_zeny(sd, LOG_TYPE_BUYING_STORE, pl_sd, zeny); // move item pc_additem(pl_sd, &sd->status.inventory[index], amount); pc_delitem(sd, index, amount, 1, 0); pl_sd->buyingstore.items[listidx].amount-= amount; // pay up pc_payzeny(pl_sd, zeny); pc_getzeny(sd, zeny); pl_sd->buyingstore.zenylimit-= zeny; // notify clients clif_buyingstore_delete_item(sd, index, amount, pl_sd->buyingstore.items[listidx].price); clif_buyingstore_update_item(pl_sd, nameid, amount); } // check whether or not there is still something to buy ARR_FIND( 0, pl_sd->buyingstore.slots, i, pl_sd->buyingstore.items[i].amount != 0 ); if( i == pl_sd->buyingstore.slots ) {// everything was bought clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_NO_ITEMS); } else if( pl_sd->buyingstore.zenylimit == 0 ) {// zeny limit reached clif_buyingstore_trade_failed_buyer(pl_sd, BUYINGSTORE_TRADE_BUYER_ZENY); } else {// continue buying return; } // cannot continue buying buyingstore_close(pl_sd); // remove auto-trader if( pl_sd->state.autotrade ) { map_quit(pl_sd); } } /// Checks if an item is being bought in given player's buying store. bool buyingstore_search(struct map_session_data* sd, unsigned short nameid) { unsigned int i; if( !sd->state.buyingstore ) {// not buying return false; } ARR_FIND( 0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == nameid && sd->buyingstore.items[i].amount ); if( i == sd->buyingstore.slots ) {// not found return false; } return true; } /// Searches for all items in a buyingstore, that match given ids, price and possible cards. /// @return Whether or not the search should be continued. bool buyingstore_searchall(struct map_session_data* sd, const struct s_search_store_search* s) { unsigned int i, idx; struct s_buyingstore_item* it; if( !sd->state.buyingstore ) {// not buying return true; } for( idx = 0; idx < s->item_count; idx++ ) { ARR_FIND( 0, sd->buyingstore.slots, i, sd->buyingstore.items[i].nameid == s->itemlist[idx] && sd->buyingstore.items[i].amount ); if( i == sd->buyingstore.slots ) {// not found continue; } it = &sd->buyingstore.items[i]; if( s->min_price && s->min_price > (unsigned int)it->price ) {// too low price continue; } if( s->max_price && s->max_price < (unsigned int)it->price ) {// too high price continue; } if( s->card_count ) {// ignore cards, as there cannot be any ; } if( !searchstore_result(s->search_sd, sd->buyer_id, sd->status.account_id, sd->message, it->nameid, it->amount, it->price, buyingstore_blankslots, 0) ) {// result set full return false; } } return true; }
gpl-3.0
ivesbai/server
vendor/ZendFramework/library/Zend/Json/Server/Exception.php
1173
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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 [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Json * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Exception.php 18951 2009-11-12 16:26:19Z alexander $ */ /** Zend_Json_Exception */ require_once 'Zend/Json/Exception.php'; /** * Zend_Json_Server exceptions * * @uses Zend_Json_Exception * @package Zend_Json * @subpackage Server * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Json_Server_Exception extends Zend_Json_Exception { }
agpl-3.0
railsfactory-sriman/knowledgeBase
public/javascripts/i18n/si.js
235
/** Messages for Sinhala (සිංහල) * Exported from translatewiki.net * * Translators: * - Singhalawap */ var I18n = { on_leave_page: "ඔබගේ වෙනස්කිරීම් අහිමිවනු ඇත" };
agpl-3.0
ratliff/server
vendor/ZendFramework/library/Zend/Validate/Db/Abstract.php
4823
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * 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 [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Abstract.php 18951 2009-11-12 16:26:19Z alexander $ */ /** * @see Zend_Validate_Abstract */ require_once 'Zend/Validate/Abstract.php'; /** * Class for Database record validation * * @category Zend * @package Zend_Validate * @uses Zend_Validate_Abstract * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Validate_Db_Abstract extends Zend_Validate_Abstract { /** * Error constants */ const ERROR_NO_RECORD_FOUND = 'noRecordFound'; const ERROR_RECORD_FOUND = 'recordFound'; /** * @var array Message templates */ protected $_messageTemplates = array(self::ERROR_NO_RECORD_FOUND => 'No record matching %value% was found', self::ERROR_RECORD_FOUND => 'A record matching %value% was found'); /** * @var string */ protected $_schema = null; /** * @var string */ protected $_table = ''; /** * @var string */ protected $_field = ''; /** * @var mixed */ protected $_exclude = null; /** * Database adapter to use. If null isValid() will use Zend_Db::getInstance instead * * @var unknown_type */ protected $_adapter = null; /** * Provides basic configuration for use with Zend_Validate_Db Validators * Setting $exclude allows a single record to be excluded from matching. * Exclude can either be a String containing a where clause, or an array with `field` and `value` keys * to define the where clause added to the sql. * A database adapter may optionally be supplied to avoid using the registered default adapter. * * @param string||array $table The database table to validate against, or array with table and schema keys * @param string $field The field to check for a match * @param string||array $exclude An optional where clause or field/value pair to exclude from the query * @param Zend_Db_Adapter_Abstract $adapter An optional database adapter to use. */ public function __construct($table, $field, $exclude = null, Zend_Db_Adapter_Abstract $adapter = null) { if ($adapter !== null) { $this->_adapter = $adapter; } $this->_exclude = $exclude; $this->_field = (string) $field; if (is_array($table)) { $this->_table = (isset($table['table'])) ? $table['table'] : ''; $this->_schema = (isset($table['schema'])) ? $table['schema'] : null; } else { $this->_table = (string) $table; } } /** * Run query and returns matches, or null if no matches are found. * * @param String $value * @return Array when matches are found. */ protected function _query($value) { /** * Check for an adapter being defined. if not, fetch the default adapter. */ if ($this->_adapter === null) { $this->_adapter = Zend_Db_Table_Abstract::getDefaultAdapter(); if (null === $this->_adapter) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('No database adapter present'); } } /** * Build select object */ $select = new Zend_Db_Select($this->_adapter); $select->from($this->_table, array($this->_field), $this->_schema) ->where($this->_adapter->quoteIdentifier($this->_field).' = ?', $value); if ($this->_exclude !== null) { if (is_array($this->_exclude)) { $select->where($this->_adapter->quoteIdentifier($this->_exclude['field']).' != ?', $this->_exclude['value']); } else { $select->where($this->_exclude); } } $select->limit(1); /** * Run query */ $result = $this->_adapter->fetchRow($select, array(), Zend_Db::FETCH_ASSOC); return $result; } }
agpl-3.0
root-mirror/root
interpreter/llvm/src/lib/DebugInfo/CodeView/CodeViewRecordIO.cpp
11857
//===- CodeViewRecordIO.cpp -------------------------------------*- 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 // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h" #include "llvm/DebugInfo/CodeView/CodeView.h" #include "llvm/DebugInfo/CodeView/RecordSerialization.h" #include "llvm/Support/BinaryStreamReader.h" #include "llvm/Support/BinaryStreamWriter.h" using namespace llvm; using namespace llvm::codeview; Error CodeViewRecordIO::beginRecord(Optional<uint32_t> MaxLength) { RecordLimit Limit; Limit.MaxLength = MaxLength; Limit.BeginOffset = getCurrentOffset(); Limits.push_back(Limit); resetStreamedLen(); return Error::success(); } Error CodeViewRecordIO::endRecord() { assert(!Limits.empty() && "Not in a record!"); Limits.pop_back(); // We would like to assert that we actually read / wrote all the bytes that we // expected to for this record, but unfortunately we can't do this. Some // producers such as MASM over-allocate for certain types of records and // commit the extraneous data, so when reading we can't be sure every byte // will have been read. And when writing we over-allocate temporarily since // we don't know how big the record is until we're finished writing it, so // even though we don't commit the extraneous data, we still can't guarantee // we're at the end of the allocated data. if (isStreaming()) { // For streaming mode, add padding to align with 4 byte boundaries for each // record uint32_t Align = getStreamedLen() % 4; if (Align == 0) return Error::success(); int PaddingBytes = 4 - Align; while (PaddingBytes > 0) { char Pad = static_cast<uint8_t>(LF_PAD0 + PaddingBytes); StringRef BytesSR = StringRef(&Pad, sizeof(Pad)); Streamer->EmitBytes(BytesSR); --PaddingBytes; } } return Error::success(); } uint32_t CodeViewRecordIO::maxFieldLength() const { if (isStreaming()) return 0; assert(!Limits.empty() && "Not in a record!"); // The max length of the next field is the minimum of all lengths that would // be allowed by any of the sub-records we're in. In practice, we can only // ever be at most 1 sub-record deep (in a FieldList), but this works for // the general case. uint32_t Offset = getCurrentOffset(); Optional<uint32_t> Min = Limits.front().bytesRemaining(Offset); for (auto X : makeArrayRef(Limits).drop_front()) { Optional<uint32_t> ThisMin = X.bytesRemaining(Offset); if (ThisMin.hasValue()) Min = (Min.hasValue()) ? std::min(*Min, *ThisMin) : *ThisMin; } assert(Min.hasValue() && "Every field must have a maximum length!"); return *Min; } Error CodeViewRecordIO::padToAlignment(uint32_t Align) { if (isReading()) return Reader->padToAlignment(Align); return Writer->padToAlignment(Align); } Error CodeViewRecordIO::skipPadding() { assert(!isWriting() && "Cannot skip padding while writing!"); if (Reader->bytesRemaining() == 0) return Error::success(); uint8_t Leaf = Reader->peek(); if (Leaf < LF_PAD0) return Error::success(); // Leaf is greater than 0xf0. We should advance by the number of bytes in // the low 4 bits. unsigned BytesToAdvance = Leaf & 0x0F; return Reader->skip(BytesToAdvance); } Error CodeViewRecordIO::mapByteVectorTail(ArrayRef<uint8_t> &Bytes, const Twine &Comment) { if (isStreaming()) { emitComment(Comment); Streamer->EmitBinaryData(toStringRef(Bytes)); incrStreamedLen(Bytes.size()); } else if (isWriting()) { if (auto EC = Writer->writeBytes(Bytes)) return EC; } else { if (auto EC = Reader->readBytes(Bytes, Reader->bytesRemaining())) return EC; } return Error::success(); } Error CodeViewRecordIO::mapByteVectorTail(std::vector<uint8_t> &Bytes, const Twine &Comment) { ArrayRef<uint8_t> BytesRef(Bytes); if (auto EC = mapByteVectorTail(BytesRef, Comment)) return EC; if (!isWriting()) Bytes.assign(BytesRef.begin(), BytesRef.end()); return Error::success(); } Error CodeViewRecordIO::mapInteger(TypeIndex &TypeInd, const Twine &Comment) { if (isStreaming()) { emitComment(Comment); Streamer->EmitIntValue(TypeInd.getIndex(), sizeof(TypeInd.getIndex())); incrStreamedLen(sizeof(TypeInd.getIndex())); } else if (isWriting()) { if (auto EC = Writer->writeInteger(TypeInd.getIndex())) return EC; } else { uint32_t I; if (auto EC = Reader->readInteger(I)) return EC; TypeInd.setIndex(I); } return Error::success(); } Error CodeViewRecordIO::mapEncodedInteger(int64_t &Value, const Twine &Comment) { if (isStreaming()) { if (Value >= 0) emitEncodedUnsignedInteger(static_cast<uint64_t>(Value), Comment); else emitEncodedSignedInteger(Value, Comment); } else if (isWriting()) { if (Value >= 0) { if (auto EC = writeEncodedUnsignedInteger(static_cast<uint64_t>(Value))) return EC; } else { if (auto EC = writeEncodedSignedInteger(Value)) return EC; } } else { APSInt N; if (auto EC = consume(*Reader, N)) return EC; Value = N.getExtValue(); } return Error::success(); } Error CodeViewRecordIO::mapEncodedInteger(uint64_t &Value, const Twine &Comment) { if (isStreaming()) emitEncodedUnsignedInteger(Value, Comment); else if (isWriting()) { if (auto EC = writeEncodedUnsignedInteger(Value)) return EC; } else { APSInt N; if (auto EC = consume(*Reader, N)) return EC; Value = N.getZExtValue(); } return Error::success(); } Error CodeViewRecordIO::mapEncodedInteger(APSInt &Value, const Twine &Comment) { if (isStreaming()) { if (Value.isSigned()) emitEncodedSignedInteger(Value.getSExtValue(), Comment); else emitEncodedUnsignedInteger(Value.getZExtValue(), Comment); } else if (isWriting()) { if (Value.isSigned()) return writeEncodedSignedInteger(Value.getSExtValue()); return writeEncodedUnsignedInteger(Value.getZExtValue()); } else return consume(*Reader, Value); return Error::success(); } Error CodeViewRecordIO::mapStringZ(StringRef &Value, const Twine &Comment) { if (isStreaming()) { auto NullTerminatedString = StringRef(Value.data(), Value.size() + 1); emitComment(Comment); Streamer->EmitBytes(NullTerminatedString); incrStreamedLen(NullTerminatedString.size()); } else if (isWriting()) { // Truncate if we attempt to write too much. StringRef S = Value.take_front(maxFieldLength() - 1); if (auto EC = Writer->writeCString(S)) return EC; } else { if (auto EC = Reader->readCString(Value)) return EC; } return Error::success(); } Error CodeViewRecordIO::mapGuid(GUID &Guid, const Twine &Comment) { constexpr uint32_t GuidSize = 16; if (isStreaming()) { StringRef GuidSR = StringRef((reinterpret_cast<const char *>(&Guid)), GuidSize); emitComment(Comment); Streamer->EmitBytes(GuidSR); incrStreamedLen(GuidSize); return Error::success(); } if (maxFieldLength() < GuidSize) return make_error<CodeViewError>(cv_error_code::insufficient_buffer); if (isWriting()) { if (auto EC = Writer->writeBytes(Guid.Guid)) return EC; } else { ArrayRef<uint8_t> GuidBytes; if (auto EC = Reader->readBytes(GuidBytes, GuidSize)) return EC; memcpy(Guid.Guid, GuidBytes.data(), GuidSize); } return Error::success(); } Error CodeViewRecordIO::mapStringZVectorZ(std::vector<StringRef> &Value, const Twine &Comment) { if (!isReading()) { emitComment(Comment); for (auto V : Value) { if (auto EC = mapStringZ(V)) return EC; } uint8_t FinalZero = 0; if (auto EC = mapInteger(FinalZero)) return EC; } else { StringRef S; if (auto EC = mapStringZ(S)) return EC; while (!S.empty()) { Value.push_back(S); if (auto EC = mapStringZ(S)) return EC; }; } return Error::success(); } void CodeViewRecordIO::emitEncodedSignedInteger(const int64_t &Value, const Twine &Comment) { assert(Value < 0 && "Encoded integer is not signed!"); if (Value >= std::numeric_limits<int8_t>::min()) { Streamer->EmitIntValue(LF_CHAR, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 1); incrStreamedLen(3); } else if (Value >= std::numeric_limits<int16_t>::min()) { Streamer->EmitIntValue(LF_SHORT, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 2); incrStreamedLen(4); } else if (Value >= std::numeric_limits<int32_t>::min()) { Streamer->EmitIntValue(LF_LONG, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 4); incrStreamedLen(6); } else { Streamer->EmitIntValue(LF_QUADWORD, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 4); incrStreamedLen(6); } } void CodeViewRecordIO::emitEncodedUnsignedInteger(const uint64_t &Value, const Twine &Comment) { if (Value < LF_NUMERIC) { emitComment(Comment); Streamer->EmitIntValue(Value, 2); incrStreamedLen(2); } else if (Value <= std::numeric_limits<uint16_t>::max()) { Streamer->EmitIntValue(LF_USHORT, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 2); incrStreamedLen(4); } else if (Value <= std::numeric_limits<uint32_t>::max()) { Streamer->EmitIntValue(LF_ULONG, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 4); incrStreamedLen(6); } else { Streamer->EmitIntValue(LF_UQUADWORD, 2); emitComment(Comment); Streamer->EmitIntValue(Value, 8); incrStreamedLen(6); } } Error CodeViewRecordIO::writeEncodedSignedInteger(const int64_t &Value) { assert(Value < 0 && "Encoded integer is not signed!"); if (Value >= std::numeric_limits<int8_t>::min()) { if (auto EC = Writer->writeInteger<uint16_t>(LF_CHAR)) return EC; if (auto EC = Writer->writeInteger<int8_t>(Value)) return EC; } else if (Value >= std::numeric_limits<int16_t>::min()) { if (auto EC = Writer->writeInteger<uint16_t>(LF_SHORT)) return EC; if (auto EC = Writer->writeInteger<int16_t>(Value)) return EC; } else if (Value >= std::numeric_limits<int32_t>::min()) { if (auto EC = Writer->writeInteger<uint16_t>(LF_LONG)) return EC; if (auto EC = Writer->writeInteger<int32_t>(Value)) return EC; } else { if (auto EC = Writer->writeInteger<uint16_t>(LF_QUADWORD)) return EC; if (auto EC = Writer->writeInteger(Value)) return EC; } return Error::success(); } Error CodeViewRecordIO::writeEncodedUnsignedInteger(const uint64_t &Value) { if (Value < LF_NUMERIC) { if (auto EC = Writer->writeInteger<uint16_t>(Value)) return EC; } else if (Value <= std::numeric_limits<uint16_t>::max()) { if (auto EC = Writer->writeInteger<uint16_t>(LF_USHORT)) return EC; if (auto EC = Writer->writeInteger<uint16_t>(Value)) return EC; } else if (Value <= std::numeric_limits<uint32_t>::max()) { if (auto EC = Writer->writeInteger<uint16_t>(LF_ULONG)) return EC; if (auto EC = Writer->writeInteger<uint32_t>(Value)) return EC; } else { if (auto EC = Writer->writeInteger<uint16_t>(LF_UQUADWORD)) return EC; if (auto EC = Writer->writeInteger(Value)) return EC; } return Error::success(); }
lgpl-2.1
root-mirror/root
interpreter/llvm/src/lib/Target/RISCV/RISCVFrameLowering.cpp
15861
//===-- RISCVFrameLowering.cpp - RISCV Frame Information ------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This file contains the RISCV implementation of TargetFrameLowering class. // //===----------------------------------------------------------------------===// #include "RISCVFrameLowering.h" #include "RISCVMachineFunctionInfo.h" #include "RISCVSubtarget.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RegisterScavenging.h" #include "llvm/MC/MCDwarf.h" using namespace llvm; bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const { const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); const MachineFrameInfo &MFI = MF.getFrameInfo(); return MF.getTarget().Options.DisableFramePointerElim(MF) || RegInfo->needsStackRealignment(MF) || MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken(); } // Determines the size of the frame and maximum call frame size. void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const { MachineFrameInfo &MFI = MF.getFrameInfo(); const RISCVRegisterInfo *RI = STI.getRegisterInfo(); // Get the number of bytes to allocate from the FrameInfo. uint64_t FrameSize = MFI.getStackSize(); // Get the alignment. unsigned StackAlign = getStackAlignment(); if (RI->needsStackRealignment(MF)) { unsigned MaxStackAlign = std::max(StackAlign, MFI.getMaxAlignment()); FrameSize += (MaxStackAlign - StackAlign); StackAlign = MaxStackAlign; } // Set Max Call Frame Size uint64_t MaxCallSize = alignTo(MFI.getMaxCallFrameSize(), StackAlign); MFI.setMaxCallFrameSize(MaxCallSize); // Make sure the frame is aligned. FrameSize = alignTo(FrameSize, StackAlign); // Update frame info. MFI.setStackSize(FrameSize); } void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, int64_t Val, MachineInstr::MIFlag Flag) const { MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); const RISCVInstrInfo *TII = STI.getInstrInfo(); if (DestReg == SrcReg && Val == 0) return; if (isInt<12>(Val)) { BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg) .addReg(SrcReg) .addImm(Val) .setMIFlag(Flag); } else if (isInt<32>(Val)) { unsigned Opc = RISCV::ADD; bool isSub = Val < 0; if (isSub) { Val = -Val; Opc = RISCV::SUB; } unsigned ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass); TII->movImm32(MBB, MBBI, DL, ScratchReg, Val, Flag); BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg) .addReg(SrcReg) .addReg(ScratchReg, RegState::Kill) .setMIFlag(Flag); } else { report_fatal_error("adjustReg cannot yet handle adjustments >32 bits"); } } // Returns the register used to hold the frame pointer. static unsigned getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; } // Returns the register used to hold the stack pointer. static unsigned getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; } void RISCVFrameLowering::emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const { assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported"); MachineFrameInfo &MFI = MF.getFrameInfo(); auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); const RISCVRegisterInfo *RI = STI.getRegisterInfo(); const RISCVInstrInfo *TII = STI.getInstrInfo(); MachineBasicBlock::iterator MBBI = MBB.begin(); if (RI->needsStackRealignment(MF) && MFI.hasVarSizedObjects()) { report_fatal_error( "RISC-V backend can't currently handle functions that need stack " "realignment and have variable sized objects"); } unsigned FPReg = getFPReg(STI); unsigned SPReg = getSPReg(STI); // Debug location must be unknown since the first debug location is used // to determine the end of the prologue. DebugLoc DL; // Determine the correct frame layout determineFrameLayout(MF); // FIXME (note copied from Lanai): This appears to be overallocating. Needs // investigation. Get the number of bytes to allocate from the FrameInfo. uint64_t StackSize = MFI.getStackSize(); // Early exit if there is no need to allocate on the stack if (StackSize == 0 && !MFI.adjustsStack()) return; // Allocate space on the stack if necessary. adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup); // Emit ".cfi_def_cfa_offset StackSize" unsigned CFIIndex = MF.addFrameInst( MCCFIInstruction::createDefCfaOffset(nullptr, -StackSize)); BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) .addCFIIndex(CFIIndex); // The frame pointer is callee-saved, and code has been generated for us to // save it to the stack. We need to skip over the storing of callee-saved // registers as the frame pointer must be modified after it has been saved // to the stack, not before. // FIXME: assumes exactly one instruction is used to save each callee-saved // register. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); std::advance(MBBI, CSI.size()); // Iterate over list of callee-saved registers and emit .cfi_offset // directives. for (const auto &Entry : CSI) { int64_t Offset = MFI.getObjectOffset(Entry.getFrameIdx()); unsigned Reg = Entry.getReg(); unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( nullptr, RI->getDwarfRegNum(Reg, true), Offset)); BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) .addCFIIndex(CFIIndex); } // Generate new FP. if (hasFP(MF)) { adjustReg(MBB, MBBI, DL, FPReg, SPReg, StackSize - RVFI->getVarArgsSaveSize(), MachineInstr::FrameSetup); // Emit ".cfi_def_cfa $fp, 0" unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa( nullptr, RI->getDwarfRegNum(FPReg, true), 0)); BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) .addCFIIndex(CFIIndex); // Realign Stack const RISCVRegisterInfo *RI = STI.getRegisterInfo(); if (RI->needsStackRealignment(MF)) { unsigned MaxAlignment = MFI.getMaxAlignment(); const RISCVInstrInfo *TII = STI.getInstrInfo(); if (isInt<12>(-(int)MaxAlignment)) { BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg) .addReg(SPReg) .addImm(-(int)MaxAlignment); } else { unsigned ShiftAmount = countTrailingZeros(MaxAlignment); unsigned VR = MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass); BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR) .addReg(SPReg) .addImm(ShiftAmount); BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg) .addReg(VR) .addImm(ShiftAmount); } } } } void RISCVFrameLowering::emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); const RISCVRegisterInfo *RI = STI.getRegisterInfo(); MachineFrameInfo &MFI = MF.getFrameInfo(); auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); DebugLoc DL = MBBI->getDebugLoc(); const RISCVInstrInfo *TII = STI.getInstrInfo(); unsigned FPReg = getFPReg(STI); unsigned SPReg = getSPReg(STI); // Skip to before the restores of callee-saved registers // FIXME: assumes exactly one instruction is used to restore each // callee-saved register. auto LastFrameDestroy = std::prev(MBBI, MFI.getCalleeSavedInfo().size()); uint64_t StackSize = MFI.getStackSize(); uint64_t FPOffset = StackSize - RVFI->getVarArgsSaveSize(); // Restore the stack pointer using the value of the frame pointer. Only // necessary if the stack pointer was modified, meaning the stack size is // unknown. if (RI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) { assert(hasFP(MF) && "frame pointer should not have been eliminated"); adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset, MachineInstr::FrameDestroy); } if (hasFP(MF)) { // To find the instruction restoring FP from stack. for (auto &I = LastFrameDestroy; I != MBBI; ++I) { if (I->mayLoad() && I->getOperand(0).isReg()) { unsigned DestReg = I->getOperand(0).getReg(); if (DestReg == FPReg) { // If there is frame pointer, after restoring $fp registers, we // need adjust CFA to ($sp - FPOffset). // Emit ".cfi_def_cfa $sp, -FPOffset" unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa( nullptr, RI->getDwarfRegNum(SPReg, true), -FPOffset)); BuildMI(MBB, std::next(I), DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) .addCFIIndex(CFIIndex); break; } } } } // Add CFI directives for callee-saved registers. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); // Iterate over list of callee-saved registers and emit .cfi_restore // directives. for (const auto &Entry : CSI) { unsigned Reg = Entry.getReg(); unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore( nullptr, RI->getDwarfRegNum(Reg, true))); BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) .addCFIIndex(CFIIndex); } // Deallocate stack adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy); // After restoring $sp, we need to adjust CFA to $(sp + 0) // Emit ".cfi_def_cfa_offset 0" unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0)); BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) .addCFIIndex(CFIIndex); } int RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const { const MachineFrameInfo &MFI = MF.getFrameInfo(); const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); // Callee-saved registers should be referenced relative to the stack // pointer (positive offset), otherwise use the frame pointer (negative // offset). const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); int MinCSFI = 0; int MaxCSFI = -1; int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea() + MFI.getOffsetAdjustment(); if (CSI.size()) { MinCSFI = CSI[0].getFrameIdx(); MaxCSFI = CSI[CSI.size() - 1].getFrameIdx(); } if (FI >= MinCSFI && FI <= MaxCSFI) { FrameReg = RISCV::X2; Offset += MF.getFrameInfo().getStackSize(); } else if (RI->needsStackRealignment(MF)) { assert(!MFI.hasVarSizedObjects() && "Unexpected combination of stack realignment and varsized objects"); // If the stack was realigned, the frame pointer is set in order to allow // SP to be restored, but we still access stack objects using SP. FrameReg = RISCV::X2; Offset += MF.getFrameInfo().getStackSize(); } else { FrameReg = RI->getFrameRegister(MF); if (hasFP(MF)) Offset += RVFI->getVarArgsSaveSize(); else Offset += MF.getFrameInfo().getStackSize(); } return Offset; } void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const { TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); // Unconditionally spill RA and FP only if the function uses a frame // pointer. if (hasFP(MF)) { SavedRegs.set(RISCV::X1); SavedRegs.set(RISCV::X8); } // If interrupt is enabled and there are calls in the handler, // unconditionally save all Caller-saved registers and // all FP registers, regardless whether they are used. MachineFrameInfo &MFI = MF.getFrameInfo(); if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) { static const MCPhysReg CSRegs[] = { RISCV::X1, /* ra */ RISCV::X5, RISCV::X6, RISCV::X7, /* t0-t2 */ RISCV::X10, RISCV::X11, /* a0-a1, a2-a7 */ RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0 /* t3-t6 */ }; for (unsigned i = 0; CSRegs[i]; ++i) SavedRegs.set(CSRegs[i]); if (MF.getSubtarget<RISCVSubtarget>().hasStdExtD() || MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) { // If interrupt is enabled, this list contains all FP registers. const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs(); for (unsigned i = 0; Regs[i]; ++i) if (RISCV::FPR32RegClass.contains(Regs[i]) || RISCV::FPR64RegClass.contains(Regs[i])) SavedRegs.set(Regs[i]); } } } void RISCVFrameLowering::processFunctionBeforeFrameFinalized( MachineFunction &MF, RegScavenger *RS) const { const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); MachineFrameInfo &MFI = MF.getFrameInfo(); const TargetRegisterClass *RC = &RISCV::GPRRegClass; // estimateStackSize has been observed to under-estimate the final stack // size, so give ourselves wiggle-room by checking for stack size // representable an 11-bit signed field rather than 12-bits. // FIXME: It may be possible to craft a function with a small stack that // still needs an emergency spill slot for branch relaxation. This case // would currently be missed. if (!isInt<11>(MFI.estimateStackSize(MF))) { int RegScavFI = MFI.CreateStackObject( RegInfo->getSpillSize(*RC), RegInfo->getSpillAlignment(*RC), false); RS->addScavengingFrameIndex(RegScavFI); } } // Not preserve stack space within prologue for outgoing variables when the // function contains variable size objects and let eliminateCallFramePseudoInstr // preserve stack space for it. bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { return !MF.getFrameInfo().hasVarSizedObjects(); } // Eliminate ADJCALLSTACKDOWN, ADJCALLSTACKUP pseudo instructions. MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr( MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const { unsigned SPReg = RISCV::X2; DebugLoc DL = MI->getDebugLoc(); if (!hasReservedCallFrame(MF)) { // If space has not been reserved for a call frame, ADJCALLSTACKDOWN and // ADJCALLSTACKUP must be converted to instructions manipulating the stack // pointer. This is necessary when there is a variable length stack // allocation (e.g. alloca), which means it's not possible to allocate // space for outgoing arguments from within the function prologue. int64_t Amount = MI->getOperand(0).getImm(); if (Amount != 0) { // Ensure the stack remains aligned after adjustment. Amount = alignSPAdjust(Amount); if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN) Amount = -Amount; adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags); } } return MBB.erase(MI); }
lgpl-2.1
PureSwift/libwebsockets
lib/client-parser.c
11688
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2010-2014 Andy Green <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation: * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ #include "private-libwebsockets.h" int libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c) { int callback_action = LWS_CALLBACK_CLIENT_RECEIVE; int handled; struct lws_tokens eff_buf; int m; switch (wsi->lws_rx_parse_state) { case LWS_RXPS_NEW: switch (wsi->ietf_spec_revision) { case 13: wsi->u.ws.opcode = c & 0xf; wsi->u.ws.rsv = (c & 0x70); wsi->u.ws.final = !!((c >> 7) & 1); switch (wsi->u.ws.opcode) { case LWS_WS_OPCODE_07__TEXT_FRAME: case LWS_WS_OPCODE_07__BINARY_FRAME: wsi->u.ws.frame_is_binary = wsi->u.ws.opcode == LWS_WS_OPCODE_07__BINARY_FRAME; break; } wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN; break; default: lwsl_err("unknown spec version %02d\n", wsi->ietf_spec_revision); break; } break; case LWS_RXPS_04_FRAME_HDR_LEN: wsi->u.ws.this_frame_masked = !!(c & 0x80); switch (c & 0x7f) { case 126: /* control frames are not allowed to have big lengths */ if (wsi->u.ws.opcode & 8) goto illegal_ctl_length; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2; break; case 127: /* control frames are not allowed to have big lengths */ if (wsi->u.ws.opcode & 8) goto illegal_ctl_length; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8; break; default: wsi->u.ws.rx_packet_length = c; if (wsi->u.ws.this_frame_masked) wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1; else { if (c) wsi->lws_rx_parse_state = LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } } break; } break; case LWS_RXPS_04_FRAME_HDR_LEN16_2: wsi->u.ws.rx_packet_length = c << 8; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1; break; case LWS_RXPS_04_FRAME_HDR_LEN16_1: wsi->u.ws.rx_packet_length |= c; if (wsi->u.ws.this_frame_masked) wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1; else { if (wsi->u.ws.rx_packet_length) wsi->lws_rx_parse_state = LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } } break; case LWS_RXPS_04_FRAME_HDR_LEN64_8: if (c & 0x80) { lwsl_warn("b63 of length must be zero\n"); /* kill the connection */ return -1; } #if defined __LP64__ wsi->u.ws.rx_packet_length = ((size_t)c) << 56; #else wsi->u.ws.rx_packet_length = 0; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7; break; case LWS_RXPS_04_FRAME_HDR_LEN64_7: #if defined __LP64__ wsi->u.ws.rx_packet_length |= ((size_t)c) << 48; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6; break; case LWS_RXPS_04_FRAME_HDR_LEN64_6: #if defined __LP64__ wsi->u.ws.rx_packet_length |= ((size_t)c) << 40; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5; break; case LWS_RXPS_04_FRAME_HDR_LEN64_5: #if defined __LP64__ wsi->u.ws.rx_packet_length |= ((size_t)c) << 32; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4; break; case LWS_RXPS_04_FRAME_HDR_LEN64_4: wsi->u.ws.rx_packet_length |= ((size_t)c) << 24; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3; break; case LWS_RXPS_04_FRAME_HDR_LEN64_3: wsi->u.ws.rx_packet_length |= ((size_t)c) << 16; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2; break; case LWS_RXPS_04_FRAME_HDR_LEN64_2: wsi->u.ws.rx_packet_length |= ((size_t)c) << 8; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1; break; case LWS_RXPS_04_FRAME_HDR_LEN64_1: wsi->u.ws.rx_packet_length |= (size_t)c; if (wsi->u.ws.this_frame_masked) wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1; else { if (wsi->u.ws.rx_packet_length) wsi->lws_rx_parse_state = LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } } break; case LWS_RXPS_07_COLLECT_FRAME_KEY_1: wsi->u.ws.frame_masking_nonce_04[0] = c; if (c) wsi->u.ws.all_zero_nonce = 0; wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2; break; case LWS_RXPS_07_COLLECT_FRAME_KEY_2: wsi->u.ws.frame_masking_nonce_04[1] = c; if (c) wsi->u.ws.all_zero_nonce = 0; wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3; break; case LWS_RXPS_07_COLLECT_FRAME_KEY_3: wsi->u.ws.frame_masking_nonce_04[2] = c; if (c) wsi->u.ws.all_zero_nonce = 0; wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4; break; case LWS_RXPS_07_COLLECT_FRAME_KEY_4: wsi->u.ws.frame_masking_nonce_04[3] = c; if (c) wsi->u.ws.all_zero_nonce = 0; if (wsi->u.ws.rx_packet_length) wsi->lws_rx_parse_state = LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } break; case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED: if (!wsi->u.ws.rx_user_buffer) { lwsl_err("NULL client rx_user_buffer\n"); return 1; } if ((!wsi->u.ws.this_frame_masked) || wsi->u.ws.all_zero_nonce) wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING + (wsi->u.ws.rx_user_buffer_head++)] = c; else wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING + (wsi->u.ws.rx_user_buffer_head++)] = c ^ wsi->u.ws.frame_masking_nonce_04[ (wsi->u.ws.frame_mask_index++) & 3]; if (--wsi->u.ws.rx_packet_length == 0) { /* spill because we have the whole frame */ wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } /* * if there's no protocol max frame size given, we are * supposed to default to LWS_MAX_SOCKET_IO_BUF */ if (!wsi->protocol->rx_buffer_size && wsi->u.ws.rx_user_buffer_head != LWS_MAX_SOCKET_IO_BUF) break; else if (wsi->protocol->rx_buffer_size && wsi->u.ws.rx_user_buffer_head != wsi->protocol->rx_buffer_size) break; /* spill because we filled our rx buffer */ spill: handled = 0; /* * is this frame a control packet we should take care of at this * layer? If so service it and hide it from the user callback */ switch (wsi->u.ws.opcode) { case LWS_WS_OPCODE_07__CLOSE: /* is this an acknowledgement of our close? */ if (wsi->state == WSI_STATE_AWAITING_CLOSE_ACK) { /* * fine he has told us he is closing too, let's * finish our close */ lwsl_parser("seen server's close ack\n"); return -1; } lwsl_parser("client sees server close len = %d\n", wsi->u.ws.rx_user_buffer_head); /* * parrot the close packet payload back * we do not care about how it went, we are closing * immediately afterwards */ libwebsocket_write(wsi, (unsigned char *) &wsi->u.ws.rx_user_buffer[ LWS_SEND_BUFFER_PRE_PADDING], wsi->u.ws.rx_user_buffer_head, LWS_WRITE_CLOSE); wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY; /* close the connection */ return -1; case LWS_WS_OPCODE_07__PING: lwsl_info("received %d byte ping, sending pong\n", wsi->u.ws.rx_user_buffer_head); if (wsi->u.ws.ping_pending_flag) { /* * there is already a pending ping payload * we should just log and drop */ lwsl_parser("DROP PING since one pending\n"); goto ping_drop; } /* control packets can only be < 128 bytes long */ if (wsi->u.ws.rx_user_buffer_head > 128 - 4) { lwsl_parser("DROP PING payload too large\n"); goto ping_drop; } /* if existing buffer is too small, drop it */ if (wsi->u.ws.ping_payload_buf && wsi->u.ws.ping_payload_alloc < wsi->u.ws.rx_user_buffer_head) lws_free2(wsi->u.ws.ping_payload_buf); /* if no buffer, allocate it */ if (!wsi->u.ws.ping_payload_buf) { wsi->u.ws.ping_payload_buf = lws_malloc(wsi->u.ws.rx_user_buffer_head + LWS_SEND_BUFFER_PRE_PADDING); wsi->u.ws.ping_payload_alloc = wsi->u.ws.rx_user_buffer_head; } /* stash the pong payload */ memcpy(wsi->u.ws.ping_payload_buf + LWS_SEND_BUFFER_PRE_PADDING, &wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING], wsi->u.ws.rx_user_buffer_head); wsi->u.ws.ping_payload_len = wsi->u.ws.rx_user_buffer_head; wsi->u.ws.ping_pending_flag = 1; /* get it sent as soon as possible */ libwebsocket_callback_on_writable(wsi->protocol->owning_server, wsi); ping_drop: wsi->u.ws.rx_user_buffer_head = 0; handled = 1; break; case LWS_WS_OPCODE_07__PONG: lwsl_info("client receied pong\n"); lwsl_hexdump(&wsi->u.ws.rx_user_buffer[ LWS_SEND_BUFFER_PRE_PADDING], wsi->u.ws.rx_user_buffer_head); /* issue it */ callback_action = LWS_CALLBACK_CLIENT_RECEIVE_PONG; break; case LWS_WS_OPCODE_07__CONTINUATION: case LWS_WS_OPCODE_07__TEXT_FRAME: case LWS_WS_OPCODE_07__BINARY_FRAME: break; default: lwsl_parser("Reserved opc 0x%2X\n", wsi->u.ws.opcode); /* * It's something special we can't understand here. * Pass the payload up to the extension's parsing * state machine. */ eff_buf.token = &wsi->u.ws.rx_user_buffer[ LWS_SEND_BUFFER_PRE_PADDING]; eff_buf.token_len = wsi->u.ws.rx_user_buffer_head; if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX, &eff_buf, 0) <= 0) { /* not handle or fail */ lwsl_ext("Unhandled ext opc 0x%x\n", wsi->u.ws.opcode); wsi->u.ws.rx_user_buffer_head = 0; return 0; } handled = 1; break; } /* * No it's real payload, pass it up to the user callback. * It's nicely buffered with the pre-padding taken care of * so it can be sent straight out again using libwebsocket_write */ if (handled) goto already_done; eff_buf.token = &wsi->u.ws.rx_user_buffer[ LWS_SEND_BUFFER_PRE_PADDING]; eff_buf.token_len = wsi->u.ws.rx_user_buffer_head; if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_PAYLOAD_RX, &eff_buf, 0) < 0) /* fail */ return -1; if (eff_buf.token_len <= 0 && callback_action != LWS_CALLBACK_CLIENT_RECEIVE_PONG) goto already_done; eff_buf.token[eff_buf.token_len] = '\0'; if (!wsi->protocol->callback) goto already_done; if (callback_action == LWS_CALLBACK_CLIENT_RECEIVE_PONG) lwsl_info("Client doing pong callback\n"); m = wsi->protocol->callback( wsi->protocol->owning_server, wsi, (enum libwebsocket_callback_reasons)callback_action, wsi->user_space, eff_buf.token, eff_buf.token_len); /* if user code wants to close, let caller know */ if (m) return 1; already_done: wsi->u.ws.rx_user_buffer_head = 0; break; default: lwsl_err("client rx illegal state\n"); return 1; } return 0; illegal_ctl_length: lwsl_warn("Control frame asking for extended length is illegal\n"); /* kill the connection */ return -1; }
lgpl-2.1
amyzheng424/elasticsearch-net
src/Nest/Domain/Mapping/Descriptors/FieldDataFilterDescriptor.cs
893
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { public class FieldDataFilterDescriptor { internal FieldDataFilter Filter { get; private set; } public FieldDataFilterDescriptor() { this.Filter = new FieldDataFilter(); } public FieldDataFilterDescriptor Frequency( Func<FieldDataFrequencyFilterDescriptor, FieldDataFrequencyFilterDescriptor> frequencyFilterSelector) { var selector = frequencyFilterSelector(new FieldDataFrequencyFilterDescriptor()); this.Filter.Frequency = selector.FrequencyFilter; return this; } public FieldDataFilterDescriptor Regex( Func<FieldDataRegexFilterDescriptor, FieldDataRegexFilterDescriptor> regexFilterSelector) { var selector = regexFilterSelector(new FieldDataRegexFilterDescriptor()); this.Filter.Regex = selector.RegexFilter; return this; } } }
apache-2.0
SonyWWS/ATF
Framework/Atf.Gui.WinForms/Controls/SplitButton.cs
14095
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace Sce.Atf.Controls { /// <summary> /// Represents a combination of a standard button on the left and a drop-down button on the right /// that is not limited to Toolstrip</summary> /// <remarks>ToolStripSplitButton is managed only by Toolstrip</remarks> public class SplitButton : Button { /// <summary> /// Constructor</summary> public SplitButton() { AutoSize = true; } /// <summary> /// Sets whether to show split</summary> [DefaultValue(true)] public bool ShowSplit { set { if (value != m_showSplit) { m_showSplit = value; Invalidate(); if (Parent != null) { Parent.PerformLayout(); } } } } private PushButtonState MState { get { return m_state; } set { if (!m_state.Equals(value)) { m_state = value; Invalidate(); } } } /// <summary> /// Gets preferred split button size</summary> /// <param name="proposedSize">Suggested size</param> /// <returns>Preferred size</returns> public override Size GetPreferredSize(Size proposedSize) { Size preferredSize = base.GetPreferredSize(proposedSize); if (m_showSplit && !string.IsNullOrEmpty(Text) && TextRenderer.MeasureText(Text, Font).Width + PushButtonWidth > preferredSize.Width) { return preferredSize + new Size(PushButtonWidth + BorderSize*2, 0); } return preferredSize; } /// <summary> /// Tests if key is a regular input key or a special key that requires preprocessing</summary> /// <param name="keyData">Key to test</param> /// <returns>True iff key is input key</returns> protected override bool IsInputKey(Keys keyData) { if (keyData.Equals(Keys.Down) && m_showSplit) { return true; } else { return base.IsInputKey(keyData); } } /// <summary> /// Raises the GotFocus event</summary> /// <param name="e">A System.EventArgs that contains the event data</param> protected override void OnGotFocus(EventArgs e) { if (!m_showSplit) { base.OnGotFocus(e); return; } if (!MState.Equals(PushButtonState.Pressed) && !MState.Equals(PushButtonState.Disabled)) { MState = PushButtonState.Default; } } /// <summary> /// Raises the KeyDown event</summary> /// <param name="kevent">KeyEventArgs that contains the event data</param> protected override void OnKeyDown(KeyEventArgs kevent) { if (m_showSplit) { if (kevent.KeyCode.Equals(Keys.Down)) { ShowContextMenuStrip(); } else if (kevent.KeyCode.Equals(Keys.Space) && kevent.Modifiers == Keys.None) { MState = PushButtonState.Pressed; } } base.OnKeyDown(kevent); } /// <summary> /// Raises the KeyUp event</summary> /// <param name="kevent">KeyEventArgs that contains the event data</param> protected override void OnKeyUp(KeyEventArgs kevent) { if (kevent.KeyCode.Equals(Keys.Space)) { if (MouseButtons == MouseButtons.None) { MState = PushButtonState.Normal; } } base.OnKeyUp(kevent); } /// <summary> /// Raises the LostFocus event</summary> /// <param name="e">EventArgs that contains the event data</param> protected override void OnLostFocus(EventArgs e) { if (!m_showSplit) { base.OnLostFocus(e); return; } if (!MState.Equals(PushButtonState.Pressed) && !MState.Equals(PushButtonState.Disabled)) { MState = PushButtonState.Normal; } } /// <summary> /// Raises the MouseDown event</summary> /// <param name="e">MouseEventArgs that contains the event data</param> protected override void OnMouseDown(MouseEventArgs e) { if (!m_showSplit) { base.OnMouseDown(e); return; } if (m_dropDownRectangle.Contains(e.Location)) { ShowContextMenuStrip(); } else { MState = PushButtonState.Pressed; } } /// <summary> /// Raises the MouseEnter event</summary> /// <param name="e">EventArgs that contains the event data</param> protected override void OnMouseEnter(EventArgs e) { if (!m_showSplit) { base.OnMouseEnter(e); return; } if (!MState.Equals(PushButtonState.Pressed) && !MState.Equals(PushButtonState.Disabled)) { MState = PushButtonState.Hot; } } /// <summary> /// Raises the MouseLeave event</summary> /// <param name="e">EventArgs that contains the event data</param> protected override void OnMouseLeave(EventArgs e) { if (!m_showSplit) { base.OnMouseLeave(e); return; } if (!MState.Equals(PushButtonState.Pressed) && !MState.Equals(PushButtonState.Disabled)) { if (Focused) { MState = PushButtonState.Default; } else { MState = PushButtonState.Normal; } } } /// <summary> /// Raises the MouseUp event</summary> /// <param name="mevent">MouseEventArgs that contains the event data</param> protected override void OnMouseUp(MouseEventArgs mevent) { if (!m_showSplit) { base.OnMouseUp(mevent); return; } if (ContextMenuStrip == null || !ContextMenuStrip.Visible) { SetButtonDrawState(); if (Bounds.Contains(Parent.PointToClient(Cursor.Position)) && !m_dropDownRectangle.Contains(mevent.Location)) { OnClick(new EventArgs()); } } } /// <summary> /// Raises the Paint event</summary> /// <param name="pevent">PaintEventArgs that contains the event data</param> protected override void OnPaint(PaintEventArgs pevent) { base.OnPaint(pevent); if (!m_showSplit) { return; } Graphics g = pevent.Graphics; Rectangle bounds = ClientRectangle; // draw the button background as according to the current state. if (MState != PushButtonState.Pressed && IsDefault && !Application.RenderWithVisualStyles) { Rectangle backgroundBounds = bounds; backgroundBounds.Inflate(-1, -1); ButtonRenderer.DrawButton(g, backgroundBounds, MState); // button renderer doesnt draw the black frame when themes are off =( g.DrawRectangle(SystemPens.WindowFrame, 0, 0, bounds.Width - 1, bounds.Height - 1); } else { ButtonRenderer.DrawButton(g, bounds, MState); } // calculate the current dropdown rectangle. m_dropDownRectangle = new Rectangle(bounds.Right - PushButtonWidth - 1, BorderSize, PushButtonWidth, bounds.Height - BorderSize*2); int internalBorder = BorderSize; var focusRect = new Rectangle(internalBorder, internalBorder, bounds.Width - m_dropDownRectangle.Width - internalBorder, bounds.Height - (internalBorder*2)); bool drawSplitLine = (MState == PushButtonState.Hot || MState == PushButtonState.Pressed || !Application.RenderWithVisualStyles); if (RightToLeft == RightToLeft.Yes) { m_dropDownRectangle.X = bounds.Left + 1; focusRect.X = m_dropDownRectangle.Right; if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Left + PushButtonWidth, BorderSize, bounds.Left + PushButtonWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Left + PushButtonWidth + 1, BorderSize, bounds.Left + PushButtonWidth + 1, bounds.Bottom - BorderSize); } } else { if (drawSplitLine) { // draw two lines at the edge of the dropdown button g.DrawLine(SystemPens.ButtonShadow, bounds.Right - PushButtonWidth, BorderSize, bounds.Right - PushButtonWidth, bounds.Bottom - BorderSize); g.DrawLine(SystemPens.ButtonFace, bounds.Right - PushButtonWidth - 1, BorderSize, bounds.Right - PushButtonWidth - 1, bounds.Bottom - BorderSize); } } // Draw an arrow in the correct location PaintArrow(g, m_dropDownRectangle); // Figure out how to draw the text TextFormatFlags formatFlags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; // If we dont' use mnemonic, set formatFlag to NoPrefix as this will show ampersand. if (!UseMnemonic) { formatFlags = formatFlags | TextFormatFlags.NoPrefix; } else if (!ShowKeyboardCues) { formatFlags = formatFlags | TextFormatFlags.HidePrefix; } if (!string.IsNullOrEmpty(Text)) { TextRenderer.DrawText(g, Text, Font, focusRect, SystemColors.ControlText, formatFlags); } // draw the focus rectangle. if (MState != PushButtonState.Pressed && Focused) { ControlPaint.DrawFocusRectangle(g, focusRect); } } private void PaintArrow(Graphics g, Rectangle dropDownRect) { var middle = new Point(Convert.ToInt32(dropDownRect.Left + dropDownRect.Width/2), Convert.ToInt32(dropDownRect.Top + dropDownRect.Height/2)); //if the width is odd - favor pushing it over one pixel right. middle.X += (dropDownRect.Width%2); var arrow = new[] { new Point(middle.X - 2, middle.Y - 1), new Point(middle.X + 3, middle.Y - 1), new Point(middle.X, middle.Y + 2) }; g.FillPolygon(SystemBrushes.ControlText, arrow); } private void ShowContextMenuStrip() { if (m_skipNextOpen) { // we were called because we're closing the context menu strip // when clicking the dropdown button. m_skipNextOpen = false; return; } MState = PushButtonState.Pressed; if (ContextMenuStrip != null) { ContextMenuStrip.Closing += ContextMenuStrip_Closing; ContextMenuStrip.Show(this, new Point(0, Height), ToolStripDropDownDirection.BelowRight); } } private void ContextMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) { var cms = sender as ContextMenuStrip; if (cms != null) { cms.Closing -= ContextMenuStrip_Closing; } SetButtonDrawState(); if (e.CloseReason == ToolStripDropDownCloseReason.AppClicked) { m_skipNextOpen = (m_dropDownRectangle.Contains(PointToClient(Cursor.Position))); } } private void SetButtonDrawState() { if (Bounds.Contains(Parent.PointToClient(Cursor.Position))) { MState = PushButtonState.Hot; } else if (Focused) { MState = PushButtonState.Default; } else { MState = PushButtonState.Normal; } } private const int PushButtonWidth = 14; private static readonly int BorderSize = SystemInformation.Border3DSize.Width * 2; private PushButtonState m_state; private bool m_skipNextOpen; private Rectangle m_dropDownRectangle; private bool m_showSplit = true; } }
apache-2.0
carrchang/vaadin
uitest/src/com/vaadin/tests/themes/valo/TestIcon.java
1580
/* * Copyright 2000-2013 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.tests.themes.valo; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.vaadin.server.FontAwesome; import com.vaadin.server.Resource; import com.vaadin.server.ThemeResource; /** * * @since * @author Vaadin Ltd */ public class TestIcon { int iconCount = 0; public TestIcon(int startIndex) { iconCount = startIndex; } public Resource get() { return get(false, 32); } public Resource get(boolean isImage) { return get(isImage, 32); } public Resource get(boolean isImage, int imageSize) { if (!isImage) { if (++iconCount >= ICONS.size()) { iconCount = 0; } return ICONS.get(iconCount); } return new ThemeResource("../runo/icons/" + imageSize + "/document.png"); } static List<FontAwesome> ICONS = Collections.unmodifiableList(Arrays .asList(FontAwesome.values())); }
apache-2.0
eile/ITK
Modules/Filtering/CurvatureFlow/itk-module.cmake
555
set(DOCUMENTATION "This module contains filters that implement variations of Curvature Flow. This is a technique that uses an iterative solution of partial differential equations to implement image denoising image filtering. These classes are typically used as edge-preserving smoothing filters. You may also find the \\\\ref ITKSmoothing and the \\\\ref ITKAnisotropicSmoothing useful as well.") itk_module(ITKCurvatureFlow DEPENDS ITKImageFilterBase ITKFiniteDifference TEST_DEPENDS ITKTestKernel DESCRIPTION "${DOCUMENTATION}" )
apache-2.0
jethac/ATF
Framework/Atf.Gui/Controls/PropertyEditing/PropertyChangedExtensions.cs
1642
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq.Expressions; namespace Sce.Atf.Controls.PropertyEditing { /// <summary> /// Helper to support INotifyPropertyChanged using expression trees and lambda expression.</summary> internal static class PropertyChangedExtensions { public static bool NotifyIfChanged<T>(this PropertyChangedEventHandler handler, ref T field, T value, Expression<Func<T>> memberExpression) { if (memberExpression == null) { throw new ArgumentNullException("memberExpression"); } var body = memberExpression.Body as MemberExpression; if (body == null) { throw new ArgumentException("Lambda must return a property."); } if (EqualityComparer<T>.Default.Equals(field, value)) { return false; } field = value; var vmExpression = body.Expression as ConstantExpression; if (vmExpression != null) { LambdaExpression lambda = Expression.Lambda(vmExpression); Delegate vmFunc = lambda.Compile(); object sender = vmFunc.DynamicInvoke(); if (handler != null) { handler(sender, new PropertyChangedEventArgs(body.Member.Name)); } } return true; } } }
apache-2.0
victorbriz/omim
coding/coding_tests/trie_test.cpp
9466
#include "testing/testing.hpp" #include "coding/trie.hpp" #include "coding/trie_builder.hpp" #include "coding/trie_reader.hpp" #include "coding/byte_stream.hpp" #include "coding/write_to_sink.hpp" #include "base/logging.hpp" #include "std/algorithm.hpp" #include "std/string.hpp" #include "std/vector.hpp" #include "std/cstring.hpp" #include <boost/utility/binary.hpp> namespace { struct ChildNodeInfo { bool m_isLeaf; uint32_t m_size; vector<uint32_t> m_edge; string m_edgeValue; ChildNodeInfo(bool isLeaf, uint32_t size, char const * edge, char const * edgeValue) : m_isLeaf(isLeaf), m_size(size), m_edgeValue(edgeValue) { while (*edge) m_edge.push_back(*edge++); } uint32_t Size() const { return m_size; } bool IsLeaf() const { return m_isLeaf; } uint32_t const * GetEdge() const { return &m_edge[0]; } uint32_t GetEdgeSize() const { return m_edge.size(); } void const * GetEdgeValue() const { return m_edgeValue.data(); } uint32_t GetEdgeValueSize() const { return m_edgeValue.size(); } }; struct KeyValuePair { buffer_vector<trie::TrieChar, 8> m_key; uint32_t m_value; KeyValuePair() {} template <class TString> KeyValuePair(TString const & key, int value) : m_key(key.begin(), key.end()), m_value(value) {} uint32_t GetKeySize() const { return m_key.size(); } trie::TrieChar const * GetKeyData() const { return m_key.data(); } uint32_t GetValue() const { return m_value; } inline void const * value_data() const { return &m_value; } inline size_t value_size() const { return sizeof(m_value); } bool operator == (KeyValuePair const & p) const { return (m_key == p.m_key && m_value == p.m_value); } bool operator < (KeyValuePair const & p) const { return ((m_key != p.m_key) ? m_key < p.m_key : m_value < p.m_value); } void Swap(KeyValuePair & r) { m_key.swap(r.m_key); swap(m_value, r.m_value); } }; string DebugPrint(KeyValuePair const & p) { string keyS = ::DebugPrint(p.m_key); ostringstream out; out << "KVP(" << keyS << ", " << p.m_value << ")"; return out.str(); } struct KeyValuePairBackInserter { vector<KeyValuePair> m_v; template <class TString> void operator()(TString const & s, trie::FixedSizeValueReader<4>::ValueType const & rawValue) { uint32_t value; memcpy(&value, &rawValue, 4); m_v.push_back(KeyValuePair(s, value)); } }; struct MaxValueCalc { using ValueType = uint8_t; ValueType operator() (void const * p, uint32_t size) const { ASSERT_EQUAL(size, 4, ()); uint32_t value; memcpy(&value, p, 4); ASSERT_LESS(value, 256, ()); return static_cast<uint8_t>(value); } }; class CharValueList { public: CharValueList(const string & s) : m_string(s) {} size_t size() const { return m_string.size(); } bool empty() const { return m_string.empty(); } template <typename TSink> void Dump(TSink & sink) const { sink.Write(m_string.data(), m_string.size()); } private: string m_string; }; class Uint32ValueList { public: using TBuffer = vector<uint32_t>; void Append(uint32_t value) { m_values.push_back(value); } uint32_t size() const { return m_values.size(); } bool empty() const { return m_values.empty(); } template <typename TSink> void Dump(TSink & sink) const { sink.Write(m_values.data(), m_values.size() * sizeof(TBuffer::value_type)); } private: TBuffer m_values; }; } // unnamed namespace #define ZENC bits::ZigZagEncode #define MKSC(x) static_cast<signed char>(x) #define MKUC(x) static_cast<uint8_t>(x) UNIT_TEST(TrieBuilder_WriteNode_Smoke) { vector<uint8_t> serial; PushBackByteSink<vector<uint8_t> > sink(serial); ChildNodeInfo children[] = { ChildNodeInfo(true, 1, "1A", "i1"), ChildNodeInfo(false, 2, "B", "ii2"), ChildNodeInfo(false, 3, "zz", ""), ChildNodeInfo(true, 4, "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "i4"), ChildNodeInfo(true, 5, "a", "5z") }; CharValueList valueList("123"); trie::WriteNode(sink, 0, valueList, &children[0], &children[0] + ARRAY_SIZE(children)); uint8_t const expected [] = { BOOST_BINARY(11000101), // Header: [0b11] [0b000101] 3, // Number of values '1', '2', '3', // Values BOOST_BINARY(10000001), // Child 1: header: [+leaf] [-supershort] [2 symbols] MKUC(ZENC(MKSC('1'))), MKUC(ZENC(MKSC('A') - MKSC('1'))), // Child 1: edge 'i', '1', // Child 1: intermediate data 1, // Child 1: size MKUC(64 | ZENC(MKSC('B') - MKSC('1'))), // Child 2: header: [-leaf] [+supershort] 'i', 'i', '2', // Child 2: intermediate data 2, // Child 2: size BOOST_BINARY(00000001), // Child 3: header: [-leaf] [-supershort] [2 symbols] MKUC(ZENC(MKSC('z') - MKSC('B'))), 0, // Child 3: edge 3, // Child 3: size BOOST_BINARY(10111111), // Child 4: header: [+leaf] [-supershort] [>= 63 symbols] 69, // Child 4: edgeSize - 1 MKUC(ZENC(MKSC('a') - MKSC('z'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge 'i', '4', // Child 4: intermediate data 4, // Child 4: size MKUC(BOOST_BINARY(11000000) | ZENC(0)), // Child 5: header: [+leaf] [+supershort] '5', 'z' // Child 5: intermediate data }; TEST_EQUAL(serial, vector<uint8_t>(&expected[0], &expected[0] + ARRAY_SIZE(expected)), ()); } UNIT_TEST(TrieBuilder_Build) { int const base = 3; int const maxLen = 3; vector<string> possibleStrings(1, string()); for (int len = 1; len <= maxLen; ++len) { for (int i = 0, p = static_cast<int>(pow((double) base, len)); i < p; ++i) { string s(len, 'A'); int t = i; for (int l = len - 1; l >= 0; --l, t /= base) s[l] += (t % base); possibleStrings.push_back(s); } } sort(possibleStrings.begin(), possibleStrings.end()); // LOG(LINFO, (possibleStrings)); int const count = static_cast<int>(possibleStrings.size()); for (int i0 = -1; i0 < count; ++i0) for (int i1 = i0; i1 < count; ++i1) for (int i2 = i1; i2 < count; ++i2) { vector<KeyValuePair> v; if (i0 >= 0) v.push_back(KeyValuePair(possibleStrings[i0], i0)); if (i1 >= 0) v.push_back(KeyValuePair(possibleStrings[i1], i1 + 10)); if (i2 >= 0) v.push_back(KeyValuePair(possibleStrings[i2], i2 + 100)); vector<string> vs; for (size_t i = 0; i < v.size(); ++i) vs.push_back(string(v[i].m_key.begin(), v[i].m_key.end())); vector<uint8_t> serial; PushBackByteSink<vector<uint8_t> > sink(serial); trie::Build<PushBackByteSink<vector<uint8_t>>, typename vector<KeyValuePair>::iterator, trie::MaxValueEdgeBuilder<MaxValueCalc>, Uint32ValueList>( sink, v.begin(), v.end(), trie::MaxValueEdgeBuilder<MaxValueCalc>()); reverse(serial.begin(), serial.end()); // LOG(LINFO, (serial.size(), vs)); MemReader memReader = MemReader(&serial[0], serial.size()); using IteratorType = trie::Iterator<trie::FixedSizeValueReader<4>::ValueType, trie::FixedSizeValueReader<1>::ValueType>; unique_ptr<IteratorType> const root(trie::ReadTrie(memReader, trie::FixedSizeValueReader<4>(), trie::FixedSizeValueReader<1>())); vector<KeyValuePair> res; KeyValuePairBackInserter f; trie::ForEachRef(*root, f, vector<trie::TrieChar>()); sort(f.m_v.begin(), f.m_v.end()); TEST_EQUAL(v, f.m_v, ()); uint32_t expectedMaxEdgeValue = 0; for (size_t i = 0; i < v.size(); ++i) if (!v[i].m_key.empty()) expectedMaxEdgeValue = max(expectedMaxEdgeValue, v[i].m_value); uint32_t maxEdgeValue = 0; for (uint32_t i = 0; i < root->m_edge.size(); ++i) maxEdgeValue = max(maxEdgeValue, static_cast<uint32_t>(root->m_edge[i].m_value.m_data[0])); TEST_EQUAL(maxEdgeValue, expectedMaxEdgeValue, (v, f.m_v)); } }
apache-2.0
Quikling/gpdb
src/test/tinc/tincrepo/mpp/gpdb/tests/package/procedural_language/plpgsql_caching/functional/views_redefine_view_teardown.sql
59
drop view v1 cascade; drop function if exists viewfunc();
apache-2.0
rgani/roslyn
src/Features/Core/Portable/CodeFixes/FixAllOccurrences/IFixAllGetFixesService.cs
1008
// 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.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeFixes { internal interface IFixAllGetFixesService : IWorkspaceService { /// <summary> /// Computes the fix all occurrences code fix, brings up the preview changes dialog for the fix and /// returns the code action operations corresponding to the fix. /// </summary> Task<IEnumerable<CodeActionOperation>> GetFixAllOperationsAsync(FixAllContext fixAllContext, bool showPreviewChangesDialog); /// <summary> /// Computes the fix all occurrences code fix and returns the changed solution. /// </summary> Task<Solution> GetFixAllChangedSolutionAsync(FixAllContext fixAllContext); } }
apache-2.0
cleliameneghin/sling
bundles/commons/metrics/src/main/java/org/apache/sling/commons/metrics/Histogram.java
1168
/* * 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.sling.commons.metrics; import org.osgi.annotation.versioning.ProviderType; /** * A metric which calculates the distribution of a value. */ @ProviderType public interface Histogram extends Counting, Metric { /** * Adds a recorded value. * * @param value the length of the value */ void update(long value); }
apache-2.0
hequn8128/flink
flink-runtime/src/main/java/org/apache/flink/runtime/blob/PermanentBlobCache.java
8721
/* * 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.blob; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.BlobServerOptions; import org.apache.flink.configuration.Configuration; import org.apache.flink.util.FileUtils; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import static org.apache.flink.util.Preconditions.checkNotNull; /** * Provides a cache for permanent BLOB files including a per-job ref-counting and a staged cleanup. * * <p>When requesting BLOBs via {@link #getFile(JobID, PermanentBlobKey)}, the cache will first * attempt to serve the file from its local cache. Only if the local cache does not contain the * desired BLOB, it will try to download it from a distributed HA file system (if available) or the * BLOB server. * * <p>If files for a job are not needed any more, they will enter a staged, i.e. deferred, cleanup. * Files may thus still be be accessible upon recovery and do not need to be re-downloaded. */ public class PermanentBlobCache extends AbstractBlobCache implements PermanentBlobService { /** * Job reference counters with a time-to-live (TTL). */ @VisibleForTesting static class RefCount { /** * Number of references to a job. */ public int references = 0; /** * Timestamp in milliseconds when any job data should be cleaned up (no cleanup for * non-positive values). */ public long keepUntil = -1; } /** * Map to store the number of references to a specific job. */ private final Map<JobID, RefCount> jobRefCounters = new HashMap<>(); /** * Time interval (ms) to run the cleanup task; also used as the default TTL. */ private final long cleanupInterval; /** * Timer task to execute the cleanup at regular intervals. */ private final Timer cleanupTimer; /** * Instantiates a new cache for permanent BLOBs which are also available in an HA store. * * @param blobClientConfig * global configuration * @param blobView * (distributed) HA blob store file system to retrieve files from first * @param serverAddress * address of the {@link BlobServer} to use for fetching files from or {@code null} if none yet * @throws IOException * thrown if the (local or distributed) file storage cannot be created or is not usable */ public PermanentBlobCache( final Configuration blobClientConfig, final BlobView blobView, @Nullable final InetSocketAddress serverAddress) throws IOException { super(blobClientConfig, blobView, LoggerFactory.getLogger(PermanentBlobCache.class), serverAddress ); // Initializing the clean up task this.cleanupTimer = new Timer(true); this.cleanupInterval = blobClientConfig.getLong(BlobServerOptions.CLEANUP_INTERVAL) * 1000; this.cleanupTimer.schedule(new PermanentBlobCleanupTask(), cleanupInterval, cleanupInterval); } /** * Registers use of job-related BLOBs. * * <p>Using any other method to access BLOBs, e.g. {@link #getFile}, is only valid within * calls to <tt>registerJob(JobID)</tt> and {@link #releaseJob(JobID)}. * * @param jobId * ID of the job this blob belongs to * * @see #releaseJob(JobID) */ public void registerJob(JobID jobId) { checkNotNull(jobId); synchronized (jobRefCounters) { RefCount ref = jobRefCounters.get(jobId); if (ref == null) { ref = new RefCount(); jobRefCounters.put(jobId, ref); } else { // reset cleanup timeout ref.keepUntil = -1; } ++ref.references; } } /** * Unregisters use of job-related BLOBs and allow them to be released. * * @param jobId * ID of the job this blob belongs to * * @see #registerJob(JobID) */ public void releaseJob(JobID jobId) { checkNotNull(jobId); synchronized (jobRefCounters) { RefCount ref = jobRefCounters.get(jobId); if (ref == null || ref.references == 0) { log.warn("improper use of releaseJob() without a matching number of registerJob() calls for jobId " + jobId); return; } --ref.references; if (ref.references == 0) { ref.keepUntil = System.currentTimeMillis() + cleanupInterval; } } } public int getNumberOfReferenceHolders(JobID jobId) { checkNotNull(jobId); synchronized (jobRefCounters) { RefCount ref = jobRefCounters.get(jobId); if (ref == null) { return 0; } else { return ref.references; } } } /** * Returns the path to a local copy of the file associated with the provided job ID and blob * key. * * <p>We will first attempt to serve the BLOB from the local storage. If the BLOB is not in * there, we will try to download it from the HA store, or directly from the {@link BlobServer}. * * @param jobId * ID of the job this blob belongs to * @param key * blob key associated with the requested file * * @return The path to the file. * * @throws java.io.FileNotFoundException * if the BLOB does not exist; * @throws IOException * if any other error occurs when retrieving the file */ @Override public File getFile(JobID jobId, PermanentBlobKey key) throws IOException { checkNotNull(jobId); return getFileInternal(jobId, key); } /** * Returns a file handle to the file associated with the given blob key on the blob * server. * * @param jobId * ID of the job this blob belongs to (or <tt>null</tt> if job-unrelated) * @param key * identifying the file * * @return file handle to the file * * @throws IOException * if creating the directory fails */ @VisibleForTesting public File getStorageLocation(JobID jobId, BlobKey key) throws IOException { checkNotNull(jobId); return BlobUtils.getStorageLocation(storageDir, jobId, key); } /** * Returns the job reference counters - for testing purposes only! * * @return job reference counters (internal state!) */ @VisibleForTesting Map<JobID, RefCount> getJobRefCounters() { return jobRefCounters; } /** * Cleanup task which is executed periodically to delete BLOBs whose ref-counter reached * <tt>0</tt>. */ class PermanentBlobCleanupTask extends TimerTask { /** * Cleans up BLOBs which are not referenced anymore. */ @Override public void run() { synchronized (jobRefCounters) { Iterator<Map.Entry<JobID, RefCount>> entryIter = jobRefCounters.entrySet().iterator(); final long currentTimeMillis = System.currentTimeMillis(); while (entryIter.hasNext()) { Map.Entry<JobID, RefCount> entry = entryIter.next(); RefCount ref = entry.getValue(); if (ref.references <= 0 && ref.keepUntil > 0 && currentTimeMillis >= ref.keepUntil) { JobID jobId = entry.getKey(); final File localFile = new File(BlobUtils.getStorageLocationPath(storageDir.getAbsolutePath(), jobId)); /* * NOTE: normally it is not required to acquire the write lock to delete the job's * storage directory since there should be no one accessing it with the ref * counter being 0 - acquire it just in case, to always be on the safe side */ readWriteLock.writeLock().lock(); boolean success = false; try { FileUtils.deleteDirectory(localFile); success = true; } catch (Throwable t) { log.warn("Failed to locally delete job directory " + localFile.getAbsolutePath(), t); } finally { readWriteLock.writeLock().unlock(); } // let's only remove this directory from cleanup if the cleanup was successful // (does not need the write lock) if (success) { entryIter.remove(); } } } } } } @Override protected void cancelCleanupTask() { cleanupTimer.cancel(); } }
apache-2.0
kerwinxu/barcodeManager
zxing/zxing.appspot.com/src/com/google/zxing/web/generator/client/EmailGenerator.java
2186
/* * Copyright (C) 2008 ZXing authors * * 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.google.zxing.web.generator.client; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; /** * Generator for email address. * * @author Yohann Coppel */ public final class EmailGenerator implements GeneratorSource { private Grid table; private final TextBox email = new TextBox(); public EmailGenerator(ChangeHandler handler, KeyPressHandler keyListener) { email.addStyleName(StylesDefs.INPUT_FIELD_REQUIRED); email.addChangeHandler(handler); email.addKeyPressHandler(keyListener); } @Override public String getName() { return "Email address"; } @Override public String getText() throws GeneratorException { return "mailto:" + getEmailField(); } private String getEmailField() throws GeneratorException { String input = email.getText(); if (input.length() < 1) { throw new GeneratorException("Email must be present."); } Validators.validateEmail(input); return input; } @Override public Grid getWidget() { if (table != null) { return table; } table = new Grid(1, 2); table.setText(0, 0, "Address"); table.setWidget(0, 1, email); return table; } @Override public void validate(Widget widget) throws GeneratorException { if (widget == email) { getEmailField(); } } @Override public void setFocus() { email.setFocus(true); } }
bsd-2-clause
dblock/rubinius
spec/ruby/shared/kernel/method_missing.rb
3792
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../fixtures/kernel/classes', __FILE__) describe :method_missing_defined_module, :shared => true do describe "for a Module with #method_missing defined" do it "is not called when a defined method is called" do @object.method_public.should == :module_public_method end it "is called when an undefined method is called" do @object.method_undefined.should == :module_method_missing end it "is called when an protected method is called" do @object.method_protected.should == :module_method_missing end it "is called when an private method is called" do @object.method_private.should == :module_method_missing end end end describe :method_missing_module, :shared => true do describe "for a Module" do it "raises a NoMethodError when an undefined method is called" do lambda { @object.method_undefined }.should raise_error(NoMethodError) end it "raises a NoMethodError when a protected method is called" do lambda { @object.method_protected }.should raise_error(NoMethodError) end it "raises a NoMethodError when a private method is called" do lambda { @object.method_private }.should raise_error(NoMethodError) end end end describe :method_missing_defined_class, :shared => true do describe "for a Class with #method_missing defined" do it "is not called when a defined method is called" do @object.method_public.should == :class_public_method end it "is called when an undefined method is called" do @object.method_undefined.should == :class_method_missing end it "is called when an protected method is called" do @object.method_protected.should == :class_method_missing end it "is called when an private method is called" do @object.method_private.should == :class_method_missing end end end describe :method_missing_class, :shared => true do describe "for a Class" do it "raises a NoMethodError when an undefined method is called" do lambda { @object.method_undefined }.should raise_error(NoMethodError) end it "raises a NoMethodError when a protected method is called" do lambda { @object.method_protected }.should raise_error(NoMethodError) end it "raises a NoMethodError when a private method is called" do lambda { @object.method_private }.should raise_error(NoMethodError) end end end describe :method_missing_defined_instance, :shared => true do describe "for an instance with #method_missing defined" do before :each do @instance = @object.new end it "is not called when a defined method is called" do @instance.method_public.should == :instance_public_method end it "is called when an undefined method is called" do @instance.method_undefined.should == :instance_method_missing end it "is called when an protected method is called" do @instance.method_protected.should == :instance_method_missing end it "is called when an private method is called" do @instance.method_private.should == :instance_method_missing end end end describe :method_missing_instance, :shared => true do describe "for an instance" do it "raises a NoMethodError when an undefined method is called" do lambda { @object.new.method_undefined }.should raise_error(NoMethodError) end it "raises a NoMethodError when a protected method is called" do lambda { @object.new.method_protected }.should raise_error(NoMethodError) end it "raises a NoMethodError when a private method is called" do lambda { @object.new.method_private }.should raise_error(NoMethodError) end end end
bsd-3-clause
MichaelTsao/yanpei
web/js/node_modules/leancloud-realtime/node_modules/axios/lib/defaults.js
1867
'use strict'; var utils = require('./utils'); var normalizeHeaderName = require('./helpers/normalizeHeaderName'); var PROTECTION_PREFIX = /^\)\]\}',?\n/; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } module.exports = { transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { data = data.replace(PROTECTION_PREFIX, ''); try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], headers: { common: { 'Accept': 'application/json, text/plain, */*' }, patch: utils.merge(DEFAULT_CONTENT_TYPE), post: utils.merge(DEFAULT_CONTENT_TYPE), put: utils.merge(DEFAULT_CONTENT_TYPE) }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } };
bsd-3-clause
markogresak/DefinitelyTyped
types/node/v14/test/util.ts
12010
import * as util from 'util'; import assert = require('assert'); import { readFile } from 'fs'; { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); util.inspect(["This is nice"], false, null); util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false, showProxy: true, maxArrayLength: 10, breakLength: 20, maxStringLength: 123, compact: true, sorted(a, b) { return b.localeCompare(a); }, getters: false, }); util.inspect(["This is nice"], { colors: true, depth: null, customInspect: false, showProxy: true, maxArrayLength: null, breakLength: Infinity, compact: false, sorted: true, getters: 'set', }); util.inspect(["This is nice"], { compact: 42, }); assert(typeof util.inspect.custom === 'symbol'); util.inspect.replDefaults = { colors: true, }; util.inspect({ [util.inspect.custom]: <util.CustomInspectFunction> ((depth, opts) => opts.stylize('woop', 'module')), }); util.format('%s:%s', 'foo'); util.format('%s:%s', 'foo', 'bar', 'baz'); util.format(1, 2, 3); util.format('%% %s'); util.format(); util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); // util.callbackify class callbackifyTest { static fn(): Promise<void> { assert(arguments.length === 0); return Promise.resolve(); } static fnE(): Promise<void> { assert(arguments.length === 0); return Promise.reject(new Error('fail')); } static fnT1(arg1: string): Promise<void> { assert(arguments.length === 1 && arg1 === 'parameter'); return Promise.resolve(); } static fnT1E(arg1: string): Promise<void> { assert(arguments.length === 1 && arg1 === 'parameter'); return Promise.reject(new Error('fail')); } static fnTResult(): Promise<string> { assert(arguments.length === 0); return Promise.resolve('result'); } static fnTResultE(): Promise<string> { assert(arguments.length === 0); return Promise.reject(new Error('fail')); } static fnT1TResult(arg1: string): Promise<string> { assert(arguments.length === 1 && arg1 === 'parameter'); return Promise.resolve('result'); } static fnT1TResultE(arg1: string): Promise<string> { assert(arguments.length === 1 && arg1 === 'parameter'); return Promise.reject(new Error('fail')); } static test(): void { const cfn = util.callbackify(callbackifyTest.fn); const cfnE = util.callbackify(callbackifyTest.fnE); const cfnT1 = util.callbackify(callbackifyTest.fnT1); const cfnT1E = util.callbackify(callbackifyTest.fnT1E); const cfnTResult = util.callbackify(callbackifyTest.fnTResult); const cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); const cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); const cfnT1TResultE = util.callbackify(callbackifyTest.fnT1TResultE); cfn((err: NodeJS.ErrnoException | null, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); cfnT1('parameter', (err: NodeJS.ErrnoException | null, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); cfnTResult((err: NodeJS.ErrnoException | null, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); cfnT1TResult('parameter', (err: NodeJS.ErrnoException | null, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); } } callbackifyTest.test(); // util.promisify const readPromised = util.promisify(readFile); const sampleRead: Promise<any> = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); const arg0: () => Promise<number> = util.promisify((cb: (err: Error | null, result: number) => void): void => { }); const arg0NoResult: () => Promise<any> = util.promisify((cb: (err: Error | null) => void): void => { }); const arg1: (arg: string) => Promise<number> = util.promisify((arg: string, cb: (err: Error | null, result: number) => void): void => { }); const arg1UnknownError: (arg: string) => Promise<number> = util.promisify((arg: string, cb: (err: Error | null, result: number) => void): void => { }); const arg1NoResult: (arg: string) => Promise<any> = util.promisify((arg: string, cb: (err: Error | null) => void): void => { }); const cbOptionalError: () => Promise<void | {}> = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return assert(typeof util.promisify.custom === 'symbol'); // util.deprecate const foo = () => {}; // $ExpectType () => void util.deprecate(foo, 'foo() is deprecated, use bar() instead'); // $ExpectType <T extends Function>(fn: T, message: string, code?: string | undefined) => T util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); // $ExpectType <T extends Function>(fn: T, message: string, code?: string | undefined) => T util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead', 'DEP0001'); // util.isDeepStrictEqual util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); // util.TextDecoder() const td = new util.TextDecoder(); new util.TextDecoder("utf-8"); new util.TextDecoder("utf-8", { fatal: true }); new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); const ignoreBom: boolean = td.ignoreBOM; const fatal: boolean = td.fatal; const encoding: string = td.encoding; td.decode(new Int8Array(1)); td.decode(new Int16Array(1)); td.decode(new Int32Array(1)); td.decode(new Uint8Array(1)); td.decode(new Uint16Array(1)); td.decode(new Uint32Array(1)); td.decode(new Uint8ClampedArray(1)); td.decode(new Float32Array(1)); td.decode(new Float64Array(1)); td.decode(new DataView(new Int8Array(1).buffer)); td.decode(new ArrayBuffer(1)); td.decode(null); td.decode(null, { stream: true }); td.decode(new Int8Array(1), { stream: true }); const decode: string = td.decode(new Int8Array(1)); // util.TextEncoder() const te = new util.TextEncoder(); const teEncoding: string = te.encoding; const teEncodeRes: Uint8Array = te.encode("TextEncoder"); const encIntoRes: util.EncodeIntoResult = te.encodeInto('asdf', new Uint8Array(16)); // util.types let b: boolean; b = util.types.isBigInt64Array(15); b = util.types.isBigUint64Array(15); b = util.types.isModuleNamespaceObject(15); const f = (v: any) => { if (util.types.isArrayBufferView(v)) { const abv: ArrayBufferView = v; } }; // tslint:disable-next-line:no-construct const maybeBoxed: number | Number = new Number(1); if (util.types.isBoxedPrimitive(maybeBoxed)) { const boxed: Number = maybeBoxed; } const maybeBoxed2: number | Number = 1; if (!util.types.isBoxedPrimitive(maybeBoxed2)) { const boxed: number = maybeBoxed2; } } function testUtilTypes( object: unknown, readonlySetOrArray: ReadonlySet<any> | ReadonlyArray<any>, readonlyMapOrRecord: ReadonlyMap<any, any> | Record<any, any>, ) { if (util.types.isAnyArrayBuffer(object)) { const expected: ArrayBufferLike = object; } if (util.types.isArgumentsObject(object)) { object; // $ExpectType IArguments } if (util.types.isArrayBufferView(object)) { object; // $ExpectType ArrayBufferView } if (util.types.isBigInt64Array(object)) { object; // $ExpectType BigInt64Array } if (util.types.isBigUint64Array(object)) { object; // $ExpectType BigUint64Array } if (util.types.isBooleanObject(object)) { object; // $ExpectType Boolean } if (util.types.isBoxedPrimitive(object)) { object; // $ExpectType String | Number | Boolean | BigInt | Symbol } if (util.types.isDataView(object)) { object; // $ExpectType DataView } if (util.types.isDate(object)) { object; // $ExpectType Date } if (util.types.isFloat32Array(object)) { object; // $ExpectType Float32Array } if (util.types.isFloat64Array(object)) { object; // $ExpectType Float64Array } if (util.types.isGeneratorFunction(object)) { object; // $ExpectType GeneratorFunction } if (util.types.isGeneratorObject(object)) { object; // $ExpectType Generator<unknown, any, unknown> } if (util.types.isInt8Array(object)) { object; // $ExpectType Int8Array } if (util.types.isInt16Array(object)) { object; // $ExpectType Int16Array } if (util.types.isInt32Array(object)) { object; // $ExpectType Int32Array } if (util.types.isMap(object)) { object; // $ExpectType Map<any, any> if (util.types.isMap(readonlyMapOrRecord)) { readonlyMapOrRecord; // $ExpectType ReadonlyMap<any, any> } } if (util.types.isNativeError(object)) { object; // $ExpectType Error ([ new EvalError(), new RangeError(), new ReferenceError(), new SyntaxError(), new TypeError(), new URIError(), ] as const).forEach((nativeError: EvalError | RangeError | ReferenceError | SyntaxError | TypeError | URIError) => { if (!util.types.isNativeError(nativeError)) { nativeError; // $ExpectType never } }); } if (util.types.isNumberObject(object)) { object; // $ExpectType Number } if (util.types.isPromise(object)) { object; // $ExpectType Promise<any> } if (util.types.isRegExp(object)) { object; // $ExpectType RegExp } if (util.types.isSet(object)) { object; // $ExpectType Set<any> if (util.types.isSet(readonlySetOrArray)) { readonlySetOrArray; // $ExpectType ReadonlySet<any> } } if (util.types.isSharedArrayBuffer(object)) { object; // $ExpectType SharedArrayBuffer } if (util.types.isStringObject(object)) { object; // $ExpectType String } if (util.types.isSymbolObject(object)) { object; // $ExpectType Symbol } if (util.types.isTypedArray(object)) { object; // $ExpectType TypedArray } if (util.types.isUint8Array(object)) { object; // $ExpectType Uint8Array } if (util.types.isUint8ClampedArray(object)) { object; // $ExpectType Uint8ClampedArray } if (util.types.isUint16Array(object)) { object; // $ExpectType Uint16Array } if (util.types.isUint32Array(object)) { object; // $ExpectType Uint32Array } if (util.types.isWeakMap(object)) { object; // $ExpectType WeakMap<any, any> } if (util.types.isWeakSet(object)) { object; // $ExpectType WeakSet<any> } }
mit
ibigbug/ant-design
style/README.md
394
# style ant-design 样式库 ## 目录说明 |-- components (定义所有组件样式) |-- core (定义全局样式) |-- mixins (less mixins) |-- themes (皮肤) ## 约定 @css-prefix 变量定义整个样式库的类名前缀,默认为 `ant-`, 各个组件中如要自定义类名前缀,请误重名变量,可参照如下定义: `@btnPrefixClass: ~"@{css-prefix}btn";`
mit
drBenway/siteResearch
vendor/pdepend/pdepend/src/test/resources/files/issues/067/testParserHandlesParameterOptionalIsFalseForAllParameters_1.php
46
<?php function foo($foo, $bar, $foobar) {} ?>
mit
dsebastien/DefinitelyTyped
types/google-protobuf/google/protobuf/type_pb.d.ts
7723
// package: google.protobuf // file: type.proto import * as jspb from "../../index"; import * as google_protobuf_any_pb from "./any_pb"; import * as google_protobuf_source_context_pb from "./source_context_pb"; export class Type extends jspb.Message { getName(): string; setName(value: string): void; clearFieldsList(): void; getFieldsList(): Array<Field>; setFieldsList(value: Array<Field>): void; addFields(value?: Field, index?: number): Field; clearOneofsList(): void; getOneofsList(): Array<string>; setOneofsList(value: Array<string>): void; addOneofs(value: string, index?: number): string; clearOptionsList(): void; getOptionsList(): Array<Option>; setOptionsList(value: Array<Option>): void; addOptions(value?: Option, index?: number): Option; hasSourceContext(): boolean; clearSourceContext(): void; getSourceContext(): google_protobuf_source_context_pb.SourceContext | undefined; setSourceContext(value?: google_protobuf_source_context_pb.SourceContext): void; getSyntax(): Syntax; setSyntax(value: Syntax): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Type.AsObject; static toObject(includeInstance: boolean, msg: Type): Type.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Type, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Type; static deserializeBinaryFromReader(message: Type, reader: jspb.BinaryReader): Type; } export namespace Type { export type AsObject = { name: string, fieldsList: Array<Field.AsObject>, oneofsList: Array<string>, optionsList: Array<Option.AsObject>, sourceContext?: google_protobuf_source_context_pb.SourceContext.AsObject, syntax: Syntax, } } export class Field extends jspb.Message { getKind(): Field.Kind; setKind(value: Field.Kind): void; getCardinality(): Field.Cardinality; setCardinality(value: Field.Cardinality): void; getNumber(): number; setNumber(value: number): void; getName(): string; setName(value: string): void; getTypeUrl(): string; setTypeUrl(value: string): void; getOneofIndex(): number; setOneofIndex(value: number): void; getPacked(): boolean; setPacked(value: boolean): void; clearOptionsList(): void; getOptionsList(): Array<Option>; setOptionsList(value: Array<Option>): void; addOptions(value?: Option, index?: number): Option; getJsonName(): string; setJsonName(value: string): void; getDefaultValue(): string; setDefaultValue(value: string): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Field.AsObject; static toObject(includeInstance: boolean, msg: Field): Field.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Field, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Field; static deserializeBinaryFromReader(message: Field, reader: jspb.BinaryReader): Field; } export namespace Field { export type AsObject = { kind: Kind, cardinality: Cardinality, number: number, name: string, typeUrl: string, oneofIndex: number, packed: boolean, optionsList: Array<Option.AsObject>, jsonName: string, defaultValue: string, } export enum Kind { TYPE_UNKNOWN = 0, TYPE_DOUBLE = 1, TYPE_FLOAT = 2, TYPE_INT64 = 3, TYPE_UINT64 = 4, TYPE_INT32 = 5, TYPE_FIXED64 = 6, TYPE_FIXED32 = 7, TYPE_BOOL = 8, TYPE_STRING = 9, TYPE_GROUP = 10, TYPE_MESSAGE = 11, TYPE_BYTES = 12, TYPE_UINT32 = 13, TYPE_ENUM = 14, TYPE_SFIXED32 = 15, TYPE_SFIXED64 = 16, TYPE_SINT32 = 17, TYPE_SINT64 = 18, } export enum Cardinality { CARDINALITY_UNKNOWN = 0, CARDINALITY_OPTIONAL = 1, CARDINALITY_REQUIRED = 2, CARDINALITY_REPEATED = 3, } } export class Enum extends jspb.Message { getName(): string; setName(value: string): void; clearEnumvalueList(): void; getEnumvalueList(): Array<EnumValue>; setEnumvalueList(value: Array<EnumValue>): void; addEnumvalue(value?: EnumValue, index?: number): EnumValue; clearOptionsList(): void; getOptionsList(): Array<Option>; setOptionsList(value: Array<Option>): void; addOptions(value?: Option, index?: number): Option; hasSourceContext(): boolean; clearSourceContext(): void; getSourceContext(): google_protobuf_source_context_pb.SourceContext | undefined; setSourceContext(value?: google_protobuf_source_context_pb.SourceContext): void; getSyntax(): Syntax; setSyntax(value: Syntax): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Enum.AsObject; static toObject(includeInstance: boolean, msg: Enum): Enum.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Enum, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Enum; static deserializeBinaryFromReader(message: Enum, reader: jspb.BinaryReader): Enum; } export namespace Enum { export type AsObject = { name: string, enumvalueList: Array<EnumValue.AsObject>, optionsList: Array<Option.AsObject>, sourceContext?: google_protobuf_source_context_pb.SourceContext.AsObject, syntax: Syntax, } } export class EnumValue extends jspb.Message { getName(): string; setName(value: string): void; getNumber(): number; setNumber(value: number): void; clearOptionsList(): void; getOptionsList(): Array<Option>; setOptionsList(value: Array<Option>): void; addOptions(value?: Option, index?: number): Option; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): EnumValue.AsObject; static toObject(includeInstance: boolean, msg: EnumValue): EnumValue.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: EnumValue, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): EnumValue; static deserializeBinaryFromReader(message: EnumValue, reader: jspb.BinaryReader): EnumValue; } export namespace EnumValue { export type AsObject = { name: string, number: number, optionsList: Array<Option.AsObject>, } } export class Option extends jspb.Message { getName(): string; setName(value: string): void; hasValue(): boolean; clearValue(): void; getValue(): google_protobuf_any_pb.Any | undefined; setValue(value?: google_protobuf_any_pb.Any): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): Option.AsObject; static toObject(includeInstance: boolean, msg: Option): Option.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: Option, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): Option; static deserializeBinaryFromReader(message: Option, reader: jspb.BinaryReader): Option; } export namespace Option { export type AsObject = { name: string, value?: google_protobuf_any_pb.Any.AsObject, } } export enum Syntax { SYNTAX_PROTO2 = 0, SYNTAX_PROTO3 = 1, }
mit
elbidigital/confd
vendor/src/github.com/aws/aws-sdk-go/service/sqs/api.go
73117
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. // Package sqs provides a client for Amazon Simple Queue Service. package sqs import ( "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) const opAddPermission = "AddPermission" // AddPermissionRequest generates a request for the AddPermission operation. func (c *SQS) AddPermissionRequest(input *AddPermissionInput) (req *request.Request, output *AddPermissionOutput) { op := &request.Operation{ Name: opAddPermission, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &AddPermissionInput{} } req = c.newRequest(op, input, output) output = &AddPermissionOutput{} req.Data = output return } // Adds a permission to a queue for a specific principal (http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#P). // This allows for sharing access to the queue. // // When you create a queue, you have full control access rights for the queue. // Only you (as owner of the queue) can grant or deny permissions to the queue. // For more information about these permissions, see Shared Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html) // in the Amazon SQS Developer Guide. // // AddPermission writes an Amazon SQS-generated policy. If you want to write // your own policy, use SetQueueAttributes to upload your policy. For more information // about writing your own policy, see Using The Access Policy Language (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AccessPolicyLanguage.html) // in the Amazon SQS Developer Guide. // // Some API actions take lists of parameters. These lists are specified using // the param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: &Attribute.1=this // // &Attribute.2=that func (c *SQS) AddPermission(input *AddPermissionInput) (*AddPermissionOutput, error) { req, out := c.AddPermissionRequest(input) err := req.Send() return out, err } const opChangeMessageVisibility = "ChangeMessageVisibility" // ChangeMessageVisibilityRequest generates a request for the ChangeMessageVisibility operation. func (c *SQS) ChangeMessageVisibilityRequest(input *ChangeMessageVisibilityInput) (req *request.Request, output *ChangeMessageVisibilityOutput) { op := &request.Operation{ Name: opChangeMessageVisibility, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ChangeMessageVisibilityInput{} } req = c.newRequest(op, input, output) output = &ChangeMessageVisibilityOutput{} req.Data = output return } // Changes the visibility timeout of a specified message in a queue to a new // value. The maximum allowed timeout value you can set the value to is 12 hours. // This means you can't extend the timeout of a message in an existing queue // to more than a total visibility timeout of 12 hours. (For more information // visibility timeout, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) // in the Amazon SQS Developer Guide.) // // For example, let's say you have a message and its default message visibility // timeout is 30 minutes. You could call ChangeMessageVisiblity with a value // of two hours and the effective timeout would be two hours and 30 minutes. // When that time comes near you could again extend the time out by calling // ChangeMessageVisiblity, but this time the maximum allowed timeout would be // 9 hours and 30 minutes. // // There is a 120,000 limit for the number of inflight messages per queue. // Messages are inflight after they have been received from the queue by a consuming // component, but have not yet been deleted from the queue. If you reach the // 120,000 limit, you will receive an OverLimit error message from Amazon SQS. // To help avoid reaching the limit, you should delete the messages from the // queue after they have been processed. You can also increase the number of // queues you use to process the messages. // // If you attempt to set the VisibilityTimeout to an amount more than the maximum // time left, Amazon SQS returns an error. It will not automatically recalculate // and increase the timeout to the maximum time remaining. Unlike with a queue, // when you change the visibility timeout for a specific message, that timeout // value is applied immediately but is not saved in memory for that message. // If you don't delete a message after it is received, the visibility timeout // for the message the next time it is received reverts to the original timeout // value, not the value you set with the ChangeMessageVisibility action. func (c *SQS) ChangeMessageVisibility(input *ChangeMessageVisibilityInput) (*ChangeMessageVisibilityOutput, error) { req, out := c.ChangeMessageVisibilityRequest(input) err := req.Send() return out, err } const opChangeMessageVisibilityBatch = "ChangeMessageVisibilityBatch" // ChangeMessageVisibilityBatchRequest generates a request for the ChangeMessageVisibilityBatch operation. func (c *SQS) ChangeMessageVisibilityBatchRequest(input *ChangeMessageVisibilityBatchInput) (req *request.Request, output *ChangeMessageVisibilityBatchOutput) { op := &request.Operation{ Name: opChangeMessageVisibilityBatch, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ChangeMessageVisibilityBatchInput{} } req = c.newRequest(op, input, output) output = &ChangeMessageVisibilityBatchOutput{} req.Data = output return } // Changes the visibility timeout of multiple messages. This is a batch version // of ChangeMessageVisibility. The result of the action on each message is reported // individually in the response. You can send up to 10 ChangeMessageVisibility // requests with each ChangeMessageVisibilityBatch action. // // Because the batch request can result in a combination of successful and // unsuccessful actions, you should check for batch errors even when the call // returns an HTTP status code of 200. Some API actions take lists of parameters. // These lists are specified using the param.n notation. Values of n are integers // starting from 1. For example, a parameter list with two elements looks like // this: &Attribute.1=this // // &Attribute.2=that func (c *SQS) ChangeMessageVisibilityBatch(input *ChangeMessageVisibilityBatchInput) (*ChangeMessageVisibilityBatchOutput, error) { req, out := c.ChangeMessageVisibilityBatchRequest(input) err := req.Send() return out, err } const opCreateQueue = "CreateQueue" // CreateQueueRequest generates a request for the CreateQueue operation. func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, output *CreateQueueOutput) { op := &request.Operation{ Name: opCreateQueue, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &CreateQueueInput{} } req = c.newRequest(op, input, output) output = &CreateQueueOutput{} req.Data = output return } // Creates a new queue, or returns the URL of an existing one. When you request // CreateQueue, you provide a name for the queue. To successfully create a new // queue, you must provide a name that is unique within the scope of your own // queues. // // If you delete a queue, you must wait at least 60 seconds before creating // a queue with the same name. // // You may pass one or more attributes in the request. If you do not provide // a value for any attribute, the queue will have the default value for that // attribute. Permitted attributes are the same that can be set using SetQueueAttributes. // // Use GetQueueUrl to get a queue's URL. GetQueueUrl requires only the QueueName // parameter. // // If you provide the name of an existing queue, along with the exact names // and values of all the queue's attributes, CreateQueue returns the queue URL // for the existing queue. If the queue name, attribute names, or attribute // values do not match an existing queue, CreateQueue returns an error. // // Some API actions take lists of parameters. These lists are specified using // the param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: &Attribute.1=this // // &Attribute.2=that func (c *SQS) CreateQueue(input *CreateQueueInput) (*CreateQueueOutput, error) { req, out := c.CreateQueueRequest(input) err := req.Send() return out, err } const opDeleteMessage = "DeleteMessage" // DeleteMessageRequest generates a request for the DeleteMessage operation. func (c *SQS) DeleteMessageRequest(input *DeleteMessageInput) (req *request.Request, output *DeleteMessageOutput) { op := &request.Operation{ Name: opDeleteMessage, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &DeleteMessageInput{} } req = c.newRequest(op, input, output) output = &DeleteMessageOutput{} req.Data = output return } // Deletes the specified message from the specified queue. You specify the message // by using the message's receipt handle and not the message ID you received // when you sent the message. Even if the message is locked by another reader // due to the visibility timeout setting, it is still deleted from the queue. // If you leave a message in the queue for longer than the queue's configured // retention period, Amazon SQS automatically deletes it. // // The receipt handle is associated with a specific instance of receiving // the message. If you receive a message more than once, the receipt handle // you get each time you receive the message is different. When you request // DeleteMessage, if you don't provide the most recently received receipt handle // for the message, the request will still succeed, but the message might not // be deleted. // // It is possible you will receive a message even after you have deleted // it. This might happen on rare occasions if one of the servers storing a copy // of the message is unavailable when you request to delete the message. The // copy remains on the server and might be returned to you again on a subsequent // receive request. You should create your system to be idempotent so that receiving // a particular message more than once is not a problem. func (c *SQS) DeleteMessage(input *DeleteMessageInput) (*DeleteMessageOutput, error) { req, out := c.DeleteMessageRequest(input) err := req.Send() return out, err } const opDeleteMessageBatch = "DeleteMessageBatch" // DeleteMessageBatchRequest generates a request for the DeleteMessageBatch operation. func (c *SQS) DeleteMessageBatchRequest(input *DeleteMessageBatchInput) (req *request.Request, output *DeleteMessageBatchOutput) { op := &request.Operation{ Name: opDeleteMessageBatch, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &DeleteMessageBatchInput{} } req = c.newRequest(op, input, output) output = &DeleteMessageBatchOutput{} req.Data = output return } // Deletes up to ten messages from the specified queue. This is a batch version // of DeleteMessage. The result of the delete action on each message is reported // individually in the response. // // Because the batch request can result in a combination of successful and // unsuccessful actions, you should check for batch errors even when the call // returns an HTTP status code of 200. // // Some API actions take lists of parameters. These lists are specified using // the param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: &Attribute.1=this // // &Attribute.2=that func (c *SQS) DeleteMessageBatch(input *DeleteMessageBatchInput) (*DeleteMessageBatchOutput, error) { req, out := c.DeleteMessageBatchRequest(input) err := req.Send() return out, err } const opDeleteQueue = "DeleteQueue" // DeleteQueueRequest generates a request for the DeleteQueue operation. func (c *SQS) DeleteQueueRequest(input *DeleteQueueInput) (req *request.Request, output *DeleteQueueOutput) { op := &request.Operation{ Name: opDeleteQueue, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &DeleteQueueInput{} } req = c.newRequest(op, input, output) output = &DeleteQueueOutput{} req.Data = output return } // Deletes the queue specified by the queue URL, regardless of whether the queue // is empty. If the specified queue does not exist, Amazon SQS returns a successful // response. // // Use DeleteQueue with care; once you delete your queue, any messages in // the queue are no longer available. // // When you delete a queue, the deletion process takes up to 60 seconds. // Requests you send involving that queue during the 60 seconds might succeed. // For example, a SendMessage request might succeed, but after the 60 seconds, // the queue and that message you sent no longer exist. Also, when you delete // a queue, you must wait at least 60 seconds before creating a queue with the // same name. // // We reserve the right to delete queues that have had no activity for more // than 30 days. For more information, see How Amazon SQS Queues Work (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSConcepts.html) // in the Amazon SQS Developer Guide. func (c *SQS) DeleteQueue(input *DeleteQueueInput) (*DeleteQueueOutput, error) { req, out := c.DeleteQueueRequest(input) err := req.Send() return out, err } const opGetQueueAttributes = "GetQueueAttributes" // GetQueueAttributesRequest generates a request for the GetQueueAttributes operation. func (c *SQS) GetQueueAttributesRequest(input *GetQueueAttributesInput) (req *request.Request, output *GetQueueAttributesOutput) { op := &request.Operation{ Name: opGetQueueAttributes, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &GetQueueAttributesInput{} } req = c.newRequest(op, input, output) output = &GetQueueAttributesOutput{} req.Data = output return } // Gets attributes for the specified queue. The following attributes are supported: // All - returns all values. ApproximateNumberOfMessages - returns the approximate // number of visible messages in a queue. For more information, see Resources // Required to Process Messages (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ApproximateNumber.html) // in the Amazon SQS Developer Guide. ApproximateNumberOfMessagesNotVisible // - returns the approximate number of messages that are not timed-out and not // deleted. For more information, see Resources Required to Process Messages // (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ApproximateNumber.html) // in the Amazon SQS Developer Guide. VisibilityTimeout - returns the visibility // timeout for the queue. For more information about visibility timeout, see // Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) // in the Amazon SQS Developer Guide. CreatedTimestamp - returns the time when // the queue was created (epoch time in seconds). LastModifiedTimestamp - returns // the time when the queue was last changed (epoch time in seconds). Policy // - returns the queue's policy. MaximumMessageSize - returns the limit of // how many bytes a message can contain before Amazon SQS rejects it. MessageRetentionPeriod // - returns the number of seconds Amazon SQS retains a message. QueueArn - // returns the queue's Amazon resource name (ARN). ApproximateNumberOfMessagesDelayed // - returns the approximate number of messages that are pending to be added // to the queue. DelaySeconds - returns the default delay on the queue in seconds. // ReceiveMessageWaitTimeSeconds - returns the time for which a ReceiveMessage // call will wait for a message to arrive. RedrivePolicy - returns the parameters // for dead letter queue functionality of the source queue. For more information // about RedrivePolicy and dead letter queues, see Using Amazon SQS Dead Letter // Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSDeadLetterQueue.html) // in the Amazon SQS Developer Guide. // // Going forward, new attributes might be added. If you are writing code that // calls this action, we recommend that you structure your code so that it can // handle new attributes gracefully. Some API actions take lists of parameters. // These lists are specified using the param.n notation. Values of n are integers // starting from 1. For example, a parameter list with two elements looks like // this: &Attribute.1=this // // &Attribute.2=that func (c *SQS) GetQueueAttributes(input *GetQueueAttributesInput) (*GetQueueAttributesOutput, error) { req, out := c.GetQueueAttributesRequest(input) err := req.Send() return out, err } const opGetQueueUrl = "GetQueueUrl" // GetQueueUrlRequest generates a request for the GetQueueUrl operation. func (c *SQS) GetQueueUrlRequest(input *GetQueueUrlInput) (req *request.Request, output *GetQueueUrlOutput) { op := &request.Operation{ Name: opGetQueueUrl, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &GetQueueUrlInput{} } req = c.newRequest(op, input, output) output = &GetQueueUrlOutput{} req.Data = output return } // Returns the URL of an existing queue. This action provides a simple way to // retrieve the URL of an Amazon SQS queue. // // To access a queue that belongs to another AWS account, use the QueueOwnerAWSAccountId // parameter to specify the account ID of the queue's owner. The queue's owner // must grant you permission to access the queue. For more information about // shared queue access, see AddPermission or go to Shared Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html) // in the Amazon SQS Developer Guide. func (c *SQS) GetQueueUrl(input *GetQueueUrlInput) (*GetQueueUrlOutput, error) { req, out := c.GetQueueUrlRequest(input) err := req.Send() return out, err } const opListDeadLetterSourceQueues = "ListDeadLetterSourceQueues" // ListDeadLetterSourceQueuesRequest generates a request for the ListDeadLetterSourceQueues operation. func (c *SQS) ListDeadLetterSourceQueuesRequest(input *ListDeadLetterSourceQueuesInput) (req *request.Request, output *ListDeadLetterSourceQueuesOutput) { op := &request.Operation{ Name: opListDeadLetterSourceQueues, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ListDeadLetterSourceQueuesInput{} } req = c.newRequest(op, input, output) output = &ListDeadLetterSourceQueuesOutput{} req.Data = output return } // Returns a list of your queues that have the RedrivePolicy queue attribute // configured with a dead letter queue. // // For more information about using dead letter queues, see Using Amazon SQS // Dead Letter Queues (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSDeadLetterQueue.html). func (c *SQS) ListDeadLetterSourceQueues(input *ListDeadLetterSourceQueuesInput) (*ListDeadLetterSourceQueuesOutput, error) { req, out := c.ListDeadLetterSourceQueuesRequest(input) err := req.Send() return out, err } const opListQueues = "ListQueues" // ListQueuesRequest generates a request for the ListQueues operation. func (c *SQS) ListQueuesRequest(input *ListQueuesInput) (req *request.Request, output *ListQueuesOutput) { op := &request.Operation{ Name: opListQueues, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ListQueuesInput{} } req = c.newRequest(op, input, output) output = &ListQueuesOutput{} req.Data = output return } // Returns a list of your queues. The maximum number of queues that can be returned // is 1000. If you specify a value for the optional QueueNamePrefix parameter, // only queues with a name beginning with the specified value are returned. func (c *SQS) ListQueues(input *ListQueuesInput) (*ListQueuesOutput, error) { req, out := c.ListQueuesRequest(input) err := req.Send() return out, err } const opPurgeQueue = "PurgeQueue" // PurgeQueueRequest generates a request for the PurgeQueue operation. func (c *SQS) PurgeQueueRequest(input *PurgeQueueInput) (req *request.Request, output *PurgeQueueOutput) { op := &request.Operation{ Name: opPurgeQueue, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &PurgeQueueInput{} } req = c.newRequest(op, input, output) output = &PurgeQueueOutput{} req.Data = output return } // Deletes the messages in a queue specified by the queue URL. // // When you use the PurgeQueue API, the deleted messages in the queue cannot // be retrieved. When you purge a queue, the message deletion process takes // up to 60 seconds. All messages sent to the queue before calling PurgeQueue // will be deleted; messages sent to the queue while it is being purged may // be deleted. While the queue is being purged, messages sent to the queue before // PurgeQueue was called may be received, but will be deleted within the next // minute. func (c *SQS) PurgeQueue(input *PurgeQueueInput) (*PurgeQueueOutput, error) { req, out := c.PurgeQueueRequest(input) err := req.Send() return out, err } const opReceiveMessage = "ReceiveMessage" // ReceiveMessageRequest generates a request for the ReceiveMessage operation. func (c *SQS) ReceiveMessageRequest(input *ReceiveMessageInput) (req *request.Request, output *ReceiveMessageOutput) { op := &request.Operation{ Name: opReceiveMessage, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ReceiveMessageInput{} } req = c.newRequest(op, input, output) output = &ReceiveMessageOutput{} req.Data = output return } // Retrieves one or more messages, with a maximum limit of 10 messages, from // the specified queue. Long poll support is enabled by using the WaitTimeSeconds // parameter. For more information, see Amazon SQS Long Poll (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html) // in the Amazon SQS Developer Guide. // // Short poll is the default behavior where a weighted random set of machines // is sampled on a ReceiveMessage call. This means only the messages on the // sampled machines are returned. If the number of messages in the queue is // small (less than 1000), it is likely you will get fewer messages than you // requested per ReceiveMessage call. If the number of messages in the queue // is extremely small, you might not receive any messages in a particular ReceiveMessage // response; in which case you should repeat the request. // // For each message returned, the response includes the following: // // Message body // // MD5 digest of the message body. For information about MD5, go to http://www.faqs.org/rfcs/rfc1321.html // (http://www.faqs.org/rfcs/rfc1321.html). // // Message ID you received when you sent the message to the queue. // // Receipt handle. // // Message attributes. // // MD5 digest of the message attributes. // // The receipt handle is the identifier you must provide when deleting the // message. For more information, see Queue and Message Identifiers (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html) // in the Amazon SQS Developer Guide. // // You can provide the VisibilityTimeout parameter in your request, which // will be applied to the messages that Amazon SQS returns in the response. // If you do not include the parameter, the overall visibility timeout for the // queue is used for the returned messages. For more information, see Visibility // Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) // in the Amazon SQS Developer Guide. // // Going forward, new attributes might be added. If you are writing code // that calls this action, we recommend that you structure your code so that // it can handle new attributes gracefully. func (c *SQS) ReceiveMessage(input *ReceiveMessageInput) (*ReceiveMessageOutput, error) { req, out := c.ReceiveMessageRequest(input) err := req.Send() return out, err } const opRemovePermission = "RemovePermission" // RemovePermissionRequest generates a request for the RemovePermission operation. func (c *SQS) RemovePermissionRequest(input *RemovePermissionInput) (req *request.Request, output *RemovePermissionOutput) { op := &request.Operation{ Name: opRemovePermission, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &RemovePermissionInput{} } req = c.newRequest(op, input, output) output = &RemovePermissionOutput{} req.Data = output return } // Revokes any permissions in the queue policy that matches the specified Label // parameter. Only the owner of the queue can remove permissions. func (c *SQS) RemovePermission(input *RemovePermissionInput) (*RemovePermissionOutput, error) { req, out := c.RemovePermissionRequest(input) err := req.Send() return out, err } const opSendMessage = "SendMessage" // SendMessageRequest generates a request for the SendMessage operation. func (c *SQS) SendMessageRequest(input *SendMessageInput) (req *request.Request, output *SendMessageOutput) { op := &request.Operation{ Name: opSendMessage, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &SendMessageInput{} } req = c.newRequest(op, input, output) output = &SendMessageOutput{} req.Data = output return } // Delivers a message to the specified queue. With Amazon SQS, you now have // the ability to send large payload messages that are up to 256KB (262,144 // bytes) in size. To send large payloads, you must use an AWS SDK that supports // SigV4 signing. To verify whether SigV4 is supported for an AWS SDK, check // the SDK release notes. // // The following list shows the characters (in Unicode) allowed in your message, // according to the W3C XML specification. For more information, go to http://www.w3.org/TR/REC-xml/#charsets // (http://www.w3.org/TR/REC-xml/#charsets) If you send any characters not included // in the list, your request will be rejected. // // #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to #x10FFFF] func (c *SQS) SendMessage(input *SendMessageInput) (*SendMessageOutput, error) { req, out := c.SendMessageRequest(input) err := req.Send() return out, err } const opSendMessageBatch = "SendMessageBatch" // SendMessageBatchRequest generates a request for the SendMessageBatch operation. func (c *SQS) SendMessageBatchRequest(input *SendMessageBatchInput) (req *request.Request, output *SendMessageBatchOutput) { op := &request.Operation{ Name: opSendMessageBatch, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &SendMessageBatchInput{} } req = c.newRequest(op, input, output) output = &SendMessageBatchOutput{} req.Data = output return } // Delivers up to ten messages to the specified queue. This is a batch version // of SendMessage. The result of the send action on each message is reported // individually in the response. The maximum allowed individual message size // is 256 KB (262,144 bytes). // // The maximum total payload size (i.e., the sum of all a batch's individual // message lengths) is also 256 KB (262,144 bytes). // // If the DelaySeconds parameter is not specified for an entry, the default // for the queue is used. // // The following list shows the characters (in Unicode) that are allowed in // your message, according to the W3C XML specification. For more information, // go to http://www.faqs.org/rfcs/rfc1321.html (http://www.faqs.org/rfcs/rfc1321.html). // If you send any characters that are not included in the list, your request // will be rejected. #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] // | [#x10000 to #x10FFFF] // // Because the batch request can result in a combination of successful and // unsuccessful actions, you should check for batch errors even when the call // returns an HTTP status code of 200. Some API actions take lists of parameters. // These lists are specified using the param.n notation. Values of n are integers // starting from 1. For example, a parameter list with two elements looks like // this: &Attribute.1=this // // &Attribute.2=that func (c *SQS) SendMessageBatch(input *SendMessageBatchInput) (*SendMessageBatchOutput, error) { req, out := c.SendMessageBatchRequest(input) err := req.Send() return out, err } const opSetQueueAttributes = "SetQueueAttributes" // SetQueueAttributesRequest generates a request for the SetQueueAttributes operation. func (c *SQS) SetQueueAttributesRequest(input *SetQueueAttributesInput) (req *request.Request, output *SetQueueAttributesOutput) { op := &request.Operation{ Name: opSetQueueAttributes, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &SetQueueAttributesInput{} } req = c.newRequest(op, input, output) output = &SetQueueAttributesOutput{} req.Data = output return } // Sets the value of one or more queue attributes. When you change a queue's // attributes, the change can take up to 60 seconds for most of the attributes // to propagate throughout the SQS system. Changes made to the MessageRetentionPeriod // attribute can take up to 15 minutes. // // Going forward, new attributes might be added. If you are writing code that // calls this action, we recommend that you structure your code so that it can // handle new attributes gracefully. func (c *SQS) SetQueueAttributes(input *SetQueueAttributesInput) (*SetQueueAttributesOutput, error) { req, out := c.SetQueueAttributesRequest(input) err := req.Send() return out, err } type AddPermissionInput struct { // The AWS account number of the principal (http://docs.aws.amazon.com/general/latest/gr/glos-chap.html#P) // who will be given permission. The principal must have an AWS account, but // does not need to be signed up for Amazon SQS. For information about locating // the AWS account identification, see Your AWS Identifiers (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AWSCredentials.html) // in the Amazon SQS Developer Guide. AWSAccountIds []*string `locationNameList:"AWSAccountId" type:"list" flattened:"true" required:"true"` // The action the client wants to allow for the specified principal. The following // are valid values: * | SendMessage | ReceiveMessage | DeleteMessage | ChangeMessageVisibility // | GetQueueAttributes | GetQueueUrl. For more information about these actions, // see Understanding Permissions (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html#PermissionTypes) // in the Amazon SQS Developer Guide. // // Specifying SendMessage, DeleteMessage, or ChangeMessageVisibility for the // ActionName.n also grants permissions for the corresponding batch versions // of those actions: SendMessageBatch, DeleteMessageBatch, and ChangeMessageVisibilityBatch. Actions []*string `locationNameList:"ActionName" type:"list" flattened:"true" required:"true"` // The unique identification of the permission you're setting (e.g., AliceSendMessage). // Constraints: Maximum 80 characters; alphanumeric characters, hyphens (-), // and underscores (_) are allowed. Label *string `type:"string" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataAddPermissionInput `json:"-" xml:"-"` } type metadataAddPermissionInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s AddPermissionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s AddPermissionInput) GoString() string { return s.String() } type AddPermissionOutput struct { metadataAddPermissionOutput `json:"-" xml:"-"` } type metadataAddPermissionOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s AddPermissionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s AddPermissionOutput) GoString() string { return s.String() } // This is used in the responses of batch API to give a detailed description // of the result of an action on each entry in the request. type BatchResultErrorEntry struct { // An error code representing why the action failed on this entry. Code *string `type:"string" required:"true"` // The id of an entry in a batch request. Id *string `type:"string" required:"true"` // A message explaining why the action failed on this entry. Message *string `type:"string"` // Whether the error happened due to the sender's fault. SenderFault *bool `type:"boolean" required:"true"` metadataBatchResultErrorEntry `json:"-" xml:"-"` } type metadataBatchResultErrorEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s BatchResultErrorEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s BatchResultErrorEntry) GoString() string { return s.String() } type ChangeMessageVisibilityBatchInput struct { // A list of receipt handles of the messages for which the visibility timeout // must be changed. Entries []*ChangeMessageVisibilityBatchRequestEntry `locationNameList:"ChangeMessageVisibilityBatchRequestEntry" type:"list" flattened:"true" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataChangeMessageVisibilityBatchInput `json:"-" xml:"-"` } type metadataChangeMessageVisibilityBatchInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ChangeMessageVisibilityBatchInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ChangeMessageVisibilityBatchInput) GoString() string { return s.String() } // For each message in the batch, the response contains a ChangeMessageVisibilityBatchResultEntry // tag if the message succeeds or a BatchResultErrorEntry tag if the message // fails. type ChangeMessageVisibilityBatchOutput struct { // A list of BatchResultErrorEntry items. Failed []*BatchResultErrorEntry `locationNameList:"BatchResultErrorEntry" type:"list" flattened:"true" required:"true"` // A list of ChangeMessageVisibilityBatchResultEntry items. Successful []*ChangeMessageVisibilityBatchResultEntry `locationNameList:"ChangeMessageVisibilityBatchResultEntry" type:"list" flattened:"true" required:"true"` metadataChangeMessageVisibilityBatchOutput `json:"-" xml:"-"` } type metadataChangeMessageVisibilityBatchOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ChangeMessageVisibilityBatchOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ChangeMessageVisibilityBatchOutput) GoString() string { return s.String() } // Encloses a receipt handle and an entry id for each message in ChangeMessageVisibilityBatch. // // All of the following parameters are list parameters that must be prefixed // with ChangeMessageVisibilityBatchRequestEntry.n, where n is an integer value // starting with 1. For example, a parameter list for this action might look // like this: // // &ChangeMessageVisibilityBatchRequestEntry.1.Id=change_visibility_msg_2 // // &ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle=Your_Receipt_Handle // // &ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout=45 type ChangeMessageVisibilityBatchRequestEntry struct { // An identifier for this particular receipt handle. This is used to communicate // the result. Note that the Ids of a batch request need to be unique within // the request. Id *string `type:"string" required:"true"` // A receipt handle. ReceiptHandle *string `type:"string" required:"true"` // The new value (in seconds) for the message's visibility timeout. VisibilityTimeout *int64 `type:"integer"` metadataChangeMessageVisibilityBatchRequestEntry `json:"-" xml:"-"` } type metadataChangeMessageVisibilityBatchRequestEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ChangeMessageVisibilityBatchRequestEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ChangeMessageVisibilityBatchRequestEntry) GoString() string { return s.String() } // Encloses the id of an entry in ChangeMessageVisibilityBatch. type ChangeMessageVisibilityBatchResultEntry struct { // Represents a message whose visibility timeout has been changed successfully. Id *string `type:"string" required:"true"` metadataChangeMessageVisibilityBatchResultEntry `json:"-" xml:"-"` } type metadataChangeMessageVisibilityBatchResultEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ChangeMessageVisibilityBatchResultEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ChangeMessageVisibilityBatchResultEntry) GoString() string { return s.String() } type ChangeMessageVisibilityInput struct { // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` // The receipt handle associated with the message whose visibility timeout should // be changed. This parameter is returned by the ReceiveMessage action. ReceiptHandle *string `type:"string" required:"true"` // The new value (in seconds - from 0 to 43200 - maximum 12 hours) for the message's // visibility timeout. VisibilityTimeout *int64 `type:"integer" required:"true"` metadataChangeMessageVisibilityInput `json:"-" xml:"-"` } type metadataChangeMessageVisibilityInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ChangeMessageVisibilityInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ChangeMessageVisibilityInput) GoString() string { return s.String() } type ChangeMessageVisibilityOutput struct { metadataChangeMessageVisibilityOutput `json:"-" xml:"-"` } type metadataChangeMessageVisibilityOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ChangeMessageVisibilityOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ChangeMessageVisibilityOutput) GoString() string { return s.String() } type CreateQueueInput struct { // A map of attributes with their corresponding values. // // The following lists the names, descriptions, and values of the special request // parameters the CreateQueue action uses: // // DelaySeconds - The time in seconds that the delivery of all messages // in the queue will be delayed. An integer from 0 to 900 (15 minutes). The // default for this attribute is 0 (zero). MaximumMessageSize - The limit of // how many bytes a message can contain before Amazon SQS rejects it. An integer // from 1024 bytes (1 KiB) up to 262144 bytes (256 KiB). The default for this // attribute is 262144 (256 KiB). MessageRetentionPeriod - The number of seconds // Amazon SQS retains a message. Integer representing seconds, from 60 (1 minute) // to 1209600 (14 days). The default for this attribute is 345600 (4 days). // Policy - The queue's policy. A valid AWS policy. For more information about // policy structure, see Overview of AWS IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html) // in the Amazon IAM User Guide. ReceiveMessageWaitTimeSeconds - The time for // which a ReceiveMessage call will wait for a message to arrive. An integer // from 0 to 20 (seconds). The default for this attribute is 0. VisibilityTimeout // - The visibility timeout for the queue. An integer from 0 to 43200 (12 hours). // The default for this attribute is 30. For more information about visibility // timeout, see Visibility Timeout (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) // in the Amazon SQS Developer Guide. Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` // The name for the queue to be created. QueueName *string `type:"string" required:"true"` metadataCreateQueueInput `json:"-" xml:"-"` } type metadataCreateQueueInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s CreateQueueInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateQueueInput) GoString() string { return s.String() } // Returns the QueueUrl element of the created queue. type CreateQueueOutput struct { // The URL for the created Amazon SQS queue. QueueUrl *string `type:"string"` metadataCreateQueueOutput `json:"-" xml:"-"` } type metadataCreateQueueOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s CreateQueueOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s CreateQueueOutput) GoString() string { return s.String() } type DeleteMessageBatchInput struct { // A list of receipt handles for the messages to be deleted. Entries []*DeleteMessageBatchRequestEntry `locationNameList:"DeleteMessageBatchRequestEntry" type:"list" flattened:"true" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataDeleteMessageBatchInput `json:"-" xml:"-"` } type metadataDeleteMessageBatchInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteMessageBatchInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteMessageBatchInput) GoString() string { return s.String() } // For each message in the batch, the response contains a DeleteMessageBatchResultEntry // tag if the message is deleted or a BatchResultErrorEntry tag if the message // cannot be deleted. type DeleteMessageBatchOutput struct { // A list of BatchResultErrorEntry items. Failed []*BatchResultErrorEntry `locationNameList:"BatchResultErrorEntry" type:"list" flattened:"true" required:"true"` // A list of DeleteMessageBatchResultEntry items. Successful []*DeleteMessageBatchResultEntry `locationNameList:"DeleteMessageBatchResultEntry" type:"list" flattened:"true" required:"true"` metadataDeleteMessageBatchOutput `json:"-" xml:"-"` } type metadataDeleteMessageBatchOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteMessageBatchOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteMessageBatchOutput) GoString() string { return s.String() } // Encloses a receipt handle and an identifier for it. type DeleteMessageBatchRequestEntry struct { // An identifier for this particular receipt handle. This is used to communicate // the result. Note that the Ids of a batch request need to be unique within // the request. Id *string `type:"string" required:"true"` // A receipt handle. ReceiptHandle *string `type:"string" required:"true"` metadataDeleteMessageBatchRequestEntry `json:"-" xml:"-"` } type metadataDeleteMessageBatchRequestEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteMessageBatchRequestEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteMessageBatchRequestEntry) GoString() string { return s.String() } // Encloses the id an entry in DeleteMessageBatch. type DeleteMessageBatchResultEntry struct { // Represents a successfully deleted message. Id *string `type:"string" required:"true"` metadataDeleteMessageBatchResultEntry `json:"-" xml:"-"` } type metadataDeleteMessageBatchResultEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteMessageBatchResultEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteMessageBatchResultEntry) GoString() string { return s.String() } type DeleteMessageInput struct { // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` // The receipt handle associated with the message to delete. ReceiptHandle *string `type:"string" required:"true"` metadataDeleteMessageInput `json:"-" xml:"-"` } type metadataDeleteMessageInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteMessageInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteMessageInput) GoString() string { return s.String() } type DeleteMessageOutput struct { metadataDeleteMessageOutput `json:"-" xml:"-"` } type metadataDeleteMessageOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteMessageOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteMessageOutput) GoString() string { return s.String() } type DeleteQueueInput struct { // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataDeleteQueueInput `json:"-" xml:"-"` } type metadataDeleteQueueInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteQueueInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteQueueInput) GoString() string { return s.String() } type DeleteQueueOutput struct { metadataDeleteQueueOutput `json:"-" xml:"-"` } type metadataDeleteQueueOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s DeleteQueueOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s DeleteQueueOutput) GoString() string { return s.String() } type GetQueueAttributesInput struct { // A list of attributes to retrieve information for. AttributeNames []*string `locationNameList:"AttributeName" type:"list" flattened:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataGetQueueAttributesInput `json:"-" xml:"-"` } type metadataGetQueueAttributesInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s GetQueueAttributesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetQueueAttributesInput) GoString() string { return s.String() } // A list of returned queue attributes. type GetQueueAttributesOutput struct { // A map of attributes to the respective values. Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` metadataGetQueueAttributesOutput `json:"-" xml:"-"` } type metadataGetQueueAttributesOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s GetQueueAttributesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetQueueAttributesOutput) GoString() string { return s.String() } type GetQueueUrlInput struct { // The name of the queue whose URL must be fetched. Maximum 80 characters; alphanumeric // characters, hyphens (-), and underscores (_) are allowed. QueueName *string `type:"string" required:"true"` // The AWS account ID of the account that created the queue. QueueOwnerAWSAccountId *string `type:"string"` metadataGetQueueUrlInput `json:"-" xml:"-"` } type metadataGetQueueUrlInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s GetQueueUrlInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetQueueUrlInput) GoString() string { return s.String() } // For more information, see Responses (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/UnderstandingResponses.html) // in the Amazon SQS Developer Guide. type GetQueueUrlOutput struct { // The URL for the queue. QueueUrl *string `type:"string"` metadataGetQueueUrlOutput `json:"-" xml:"-"` } type metadataGetQueueUrlOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s GetQueueUrlOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s GetQueueUrlOutput) GoString() string { return s.String() } type ListDeadLetterSourceQueuesInput struct { // The queue URL of a dead letter queue. QueueUrl *string `type:"string" required:"true"` metadataListDeadLetterSourceQueuesInput `json:"-" xml:"-"` } type metadataListDeadLetterSourceQueuesInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ListDeadLetterSourceQueuesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ListDeadLetterSourceQueuesInput) GoString() string { return s.String() } // A list of your dead letter source queues. type ListDeadLetterSourceQueuesOutput struct { // A list of source queue URLs that have the RedrivePolicy queue attribute configured // with a dead letter queue. QueueUrls []*string `locationName:"queueUrls" locationNameList:"QueueUrl" type:"list" flattened:"true" required:"true"` metadataListDeadLetterSourceQueuesOutput `json:"-" xml:"-"` } type metadataListDeadLetterSourceQueuesOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ListDeadLetterSourceQueuesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ListDeadLetterSourceQueuesOutput) GoString() string { return s.String() } type ListQueuesInput struct { // A string to use for filtering the list results. Only those queues whose name // begins with the specified string are returned. QueueNamePrefix *string `type:"string"` metadataListQueuesInput `json:"-" xml:"-"` } type metadataListQueuesInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ListQueuesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ListQueuesInput) GoString() string { return s.String() } // A list of your queues. type ListQueuesOutput struct { // A list of queue URLs, up to 1000 entries. QueueUrls []*string `locationNameList:"QueueUrl" type:"list" flattened:"true"` metadataListQueuesOutput `json:"-" xml:"-"` } type metadataListQueuesOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ListQueuesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ListQueuesOutput) GoString() string { return s.String() } // An Amazon SQS message. type Message struct { // SenderId, SentTimestamp, ApproximateReceiveCount, and/or ApproximateFirstReceiveTimestamp. // SentTimestamp and ApproximateFirstReceiveTimestamp are each returned as an // integer representing the epoch time (http://en.wikipedia.org/wiki/Unix_time) // in milliseconds. Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` // The message's contents (not URL-encoded). Body *string `type:"string"` // An MD5 digest of the non-URL-encoded message body string. MD5OfBody *string `type:"string"` // An MD5 digest of the non-URL-encoded message attribute string. This can be // used to verify that Amazon SQS received the message correctly. Amazon SQS // first URL decodes the message before creating the MD5 digest. For information // about MD5, go to http://www.faqs.org/rfcs/rfc1321.html (http://www.faqs.org/rfcs/rfc1321.html). MD5OfMessageAttributes *string `type:"string"` // Each message attribute consists of a Name, Type, and Value. For more information, // see Message Attribute Items (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html#SQSMessageAttributesNTV). MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` // A unique identifier for the message. Message IDs are considered unique across // all AWS accounts for an extended period of time. MessageId *string `type:"string"` // An identifier associated with the act of receiving the message. A new receipt // handle is returned every time you receive a message. When deleting a message, // you provide the last received receipt handle to delete the message. ReceiptHandle *string `type:"string"` metadataMessage `json:"-" xml:"-"` } type metadataMessage struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s Message) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s Message) GoString() string { return s.String() } // The user-specified message attribute value. For string data types, the value // attribute has the same restrictions on the content as the message body. For // more information, see SendMessage (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html). // // Name, type, and value must not be empty or null. In addition, the message // body should not be empty or null. All parts of the message attribute, including // name, type, and value, are included in the message size restriction, which // is currently 256 KB (262,144 bytes). type MessageAttributeValue struct { // Not implemented. Reserved for future use. BinaryListValues [][]byte `locationName:"BinaryListValue" locationNameList:"BinaryListValue" type:"list" flattened:"true"` // Binary type attributes can store any binary data, for example, compressed // data, encrypted data, or images. BinaryValue []byte `type:"blob"` // Amazon SQS supports the following logical data types: String, Number, and // Binary. In addition, you can append your own custom labels. For more information, // see Message Attribute Data Types (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html#SQSMessageAttributes.DataTypes). DataType *string `type:"string" required:"true"` // Not implemented. Reserved for future use. StringListValues []*string `locationName:"StringListValue" locationNameList:"StringListValue" type:"list" flattened:"true"` // Strings are Unicode with UTF8 binary encoding. For a list of code values, // see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). StringValue *string `type:"string"` metadataMessageAttributeValue `json:"-" xml:"-"` } type metadataMessageAttributeValue struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s MessageAttributeValue) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s MessageAttributeValue) GoString() string { return s.String() } type PurgeQueueInput struct { // The queue URL of the queue to delete the messages from when using the PurgeQueue // API. QueueUrl *string `type:"string" required:"true"` metadataPurgeQueueInput `json:"-" xml:"-"` } type metadataPurgeQueueInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s PurgeQueueInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s PurgeQueueInput) GoString() string { return s.String() } type PurgeQueueOutput struct { metadataPurgeQueueOutput `json:"-" xml:"-"` } type metadataPurgeQueueOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s PurgeQueueOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s PurgeQueueOutput) GoString() string { return s.String() } type ReceiveMessageInput struct { // A list of attributes that need to be returned along with each message. // // The following lists the names and descriptions of the attributes that can // be returned: // // All - returns all values. ApproximateFirstReceiveTimestamp - returns // the time when the message was first received from the queue (epoch time in // milliseconds). ApproximateReceiveCount - returns the number of times a message // has been received from the queue but not deleted. SenderId - returns the // AWS account number (or the IP address, if anonymous access is allowed) of // the sender. SentTimestamp - returns the time when the message was sent to // the queue (epoch time in milliseconds). AttributeNames []*string `locationNameList:"AttributeName" type:"list" flattened:"true"` // The maximum number of messages to return. Amazon SQS never returns more messages // than this value but may return fewer. Values can be from 1 to 10. Default // is 1. // // All of the messages are not necessarily returned. MaxNumberOfMessages *int64 `type:"integer"` // The name of the message attribute, where N is the index. The message attribute // name can contain the following characters: A-Z, a-z, 0-9, underscore (_), // hyphen (-), and period (.). The name must not start or end with a period, // and it should not have successive periods. The name is case sensitive and // must be unique among all attribute names for the message. The name can be // up to 256 characters long. The name cannot start with "AWS." or "Amazon." // (or any variations in casing), because these prefixes are reserved for use // by Amazon Web Services. // // When using ReceiveMessage, you can send a list of attribute names to receive, // or you can return all of the attributes by specifying "All" or ".*" in your // request. You can also use "foo.*" to return all message attributes starting // with the "foo" prefix. MessageAttributeNames []*string `locationNameList:"MessageAttributeName" type:"list" flattened:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` // The duration (in seconds) that the received messages are hidden from subsequent // retrieve requests after being retrieved by a ReceiveMessage request. VisibilityTimeout *int64 `type:"integer"` // The duration (in seconds) for which the call will wait for a message to arrive // in the queue before returning. If a message is available, the call will return // sooner than WaitTimeSeconds. WaitTimeSeconds *int64 `type:"integer"` metadataReceiveMessageInput `json:"-" xml:"-"` } type metadataReceiveMessageInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ReceiveMessageInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ReceiveMessageInput) GoString() string { return s.String() } // A list of received messages. type ReceiveMessageOutput struct { // A list of messages. Messages []*Message `locationNameList:"Message" type:"list" flattened:"true"` metadataReceiveMessageOutput `json:"-" xml:"-"` } type metadataReceiveMessageOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s ReceiveMessageOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s ReceiveMessageOutput) GoString() string { return s.String() } type RemovePermissionInput struct { // The identification of the permission to remove. This is the label added with // the AddPermission action. Label *string `type:"string" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataRemovePermissionInput `json:"-" xml:"-"` } type metadataRemovePermissionInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s RemovePermissionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s RemovePermissionInput) GoString() string { return s.String() } type RemovePermissionOutput struct { metadataRemovePermissionOutput `json:"-" xml:"-"` } type metadataRemovePermissionOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s RemovePermissionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s RemovePermissionOutput) GoString() string { return s.String() } type SendMessageBatchInput struct { // A list of SendMessageBatchRequestEntry items. Entries []*SendMessageBatchRequestEntry `locationNameList:"SendMessageBatchRequestEntry" type:"list" flattened:"true" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataSendMessageBatchInput `json:"-" xml:"-"` } type metadataSendMessageBatchInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SendMessageBatchInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SendMessageBatchInput) GoString() string { return s.String() } // For each message in the batch, the response contains a SendMessageBatchResultEntry // tag if the message succeeds or a BatchResultErrorEntry tag if the message // fails. type SendMessageBatchOutput struct { // A list of BatchResultErrorEntry items with the error detail about each message // that could not be enqueued. Failed []*BatchResultErrorEntry `locationNameList:"BatchResultErrorEntry" type:"list" flattened:"true" required:"true"` // A list of SendMessageBatchResultEntry items. Successful []*SendMessageBatchResultEntry `locationNameList:"SendMessageBatchResultEntry" type:"list" flattened:"true" required:"true"` metadataSendMessageBatchOutput `json:"-" xml:"-"` } type metadataSendMessageBatchOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SendMessageBatchOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SendMessageBatchOutput) GoString() string { return s.String() } // Contains the details of a single Amazon SQS message along with a Id. type SendMessageBatchRequestEntry struct { // The number of seconds for which the message has to be delayed. DelaySeconds *int64 `type:"integer"` // An identifier for the message in this batch. This is used to communicate // the result. Note that the Ids of a batch request need to be unique within // the request. Id *string `type:"string" required:"true"` // Each message attribute consists of a Name, Type, and Value. For more information, // see Message Attribute Items (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html#SQSMessageAttributesNTV). MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` // Body of the message. MessageBody *string `type:"string" required:"true"` metadataSendMessageBatchRequestEntry `json:"-" xml:"-"` } type metadataSendMessageBatchRequestEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SendMessageBatchRequestEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SendMessageBatchRequestEntry) GoString() string { return s.String() } // Encloses a message ID for successfully enqueued message of a SendMessageBatch. type SendMessageBatchResultEntry struct { // An identifier for the message in this batch. Id *string `type:"string" required:"true"` // An MD5 digest of the non-URL-encoded message attribute string. This can be // used to verify that Amazon SQS received the message batch correctly. Amazon // SQS first URL decodes the message before creating the MD5 digest. For information // about MD5, go to http://www.faqs.org/rfcs/rfc1321.html (http://www.faqs.org/rfcs/rfc1321.html). MD5OfMessageAttributes *string `type:"string"` // An MD5 digest of the non-URL-encoded message body string. This can be used // to verify that Amazon SQS received the message correctly. Amazon SQS first // URL decodes the message before creating the MD5 digest. For information about // MD5, go to http://www.faqs.org/rfcs/rfc1321.html (http://www.faqs.org/rfcs/rfc1321.html). MD5OfMessageBody *string `type:"string" required:"true"` // An identifier for the message. MessageId *string `type:"string" required:"true"` metadataSendMessageBatchResultEntry `json:"-" xml:"-"` } type metadataSendMessageBatchResultEntry struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SendMessageBatchResultEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SendMessageBatchResultEntry) GoString() string { return s.String() } type SendMessageInput struct { // The number of seconds (0 to 900 - 15 minutes) to delay a specific message. // Messages with a positive DelaySeconds value become available for processing // after the delay time is finished. If you don't specify a value, the default // value for the queue applies. DelaySeconds *int64 `type:"integer"` // Each message attribute consists of a Name, Type, and Value. For more information, // see Message Attribute Items (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html#SQSMessageAttributesNTV). MessageAttributes map[string]*MessageAttributeValue `locationName:"MessageAttribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` // The message to send. String maximum 256 KB in size. For a list of allowed // characters, see the preceding important note. MessageBody *string `type:"string" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataSendMessageInput `json:"-" xml:"-"` } type metadataSendMessageInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SendMessageInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SendMessageInput) GoString() string { return s.String() } // The MD5OfMessageBody and MessageId elements. type SendMessageOutput struct { // An MD5 digest of the non-URL-encoded message attribute string. This can be // used to verify that Amazon SQS received the message correctly. Amazon SQS // first URL decodes the message before creating the MD5 digest. For information // about MD5, go to http://www.faqs.org/rfcs/rfc1321.html (http://www.faqs.org/rfcs/rfc1321.html). MD5OfMessageAttributes *string `type:"string"` // An MD5 digest of the non-URL-encoded message body string. This can be used // to verify that Amazon SQS received the message correctly. Amazon SQS first // URL decodes the message before creating the MD5 digest. For information about // MD5, go to http://www.faqs.org/rfcs/rfc1321.html (http://www.faqs.org/rfcs/rfc1321.html). MD5OfMessageBody *string `type:"string"` // An element containing the message ID of the message sent to the queue. For // more information, see Queue and Message Identifiers (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/ImportantIdentifiers.html) // in the Amazon SQS Developer Guide. MessageId *string `type:"string"` metadataSendMessageOutput `json:"-" xml:"-"` } type metadataSendMessageOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SendMessageOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SendMessageOutput) GoString() string { return s.String() } type SetQueueAttributesInput struct { // A map of attributes to set. // // The following lists the names, descriptions, and values of the special request // parameters the SetQueueAttributes action uses: // // DelaySeconds - The time in seconds that the delivery of all messages // in the queue will be delayed. An integer from 0 to 900 (15 minutes). The // default for this attribute is 0 (zero). MaximumMessageSize - The limit of // how many bytes a message can contain before Amazon SQS rejects it. An integer // from 1024 bytes (1 KiB) up to 262144 bytes (256 KiB). The default for this // attribute is 262144 (256 KiB). MessageRetentionPeriod - The number of seconds // Amazon SQS retains a message. Integer representing seconds, from 60 (1 minute) // to 1209600 (14 days). The default for this attribute is 345600 (4 days). // Policy - The queue's policy. A valid AWS policy. For more information about // policy structure, see Overview of AWS IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html) // in the Amazon IAM User Guide. ReceiveMessageWaitTimeSeconds - The time for // which a ReceiveMessage call will wait for a message to arrive. An integer // from 0 to 20 (seconds). The default for this attribute is 0. VisibilityTimeout // - The visibility timeout for the queue. An integer from 0 to 43200 (12 hours). // The default for this attribute is 30. For more information about visibility // timeout, see Visibility Timeout in the Amazon SQS Developer Guide. RedrivePolicy // - The parameters for dead letter queue functionality of the source queue. // For more information about RedrivePolicy and dead letter queues, see Using // Amazon SQS Dead Letter Queues in the Amazon SQS Developer Guide. Attributes map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true" required:"true"` // The URL of the Amazon SQS queue to take action on. QueueUrl *string `type:"string" required:"true"` metadataSetQueueAttributesInput `json:"-" xml:"-"` } type metadataSetQueueAttributesInput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SetQueueAttributesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SetQueueAttributesInput) GoString() string { return s.String() } type SetQueueAttributesOutput struct { metadataSetQueueAttributesOutput `json:"-" xml:"-"` } type metadataSetQueueAttributesOutput struct { SDKShapeTraits bool `type:"structure"` } // String returns the string representation func (s SetQueueAttributesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation func (s SetQueueAttributesOutput) GoString() string { return s.String() } const ( // @enum QueueAttributeName QueueAttributeNamePolicy = "Policy" // @enum QueueAttributeName QueueAttributeNameVisibilityTimeout = "VisibilityTimeout" // @enum QueueAttributeName QueueAttributeNameMaximumMessageSize = "MaximumMessageSize" // @enum QueueAttributeName QueueAttributeNameMessageRetentionPeriod = "MessageRetentionPeriod" // @enum QueueAttributeName QueueAttributeNameApproximateNumberOfMessages = "ApproximateNumberOfMessages" // @enum QueueAttributeName QueueAttributeNameApproximateNumberOfMessagesNotVisible = "ApproximateNumberOfMessagesNotVisible" // @enum QueueAttributeName QueueAttributeNameCreatedTimestamp = "CreatedTimestamp" // @enum QueueAttributeName QueueAttributeNameLastModifiedTimestamp = "LastModifiedTimestamp" // @enum QueueAttributeName QueueAttributeNameQueueArn = "QueueArn" // @enum QueueAttributeName QueueAttributeNameApproximateNumberOfMessagesDelayed = "ApproximateNumberOfMessagesDelayed" // @enum QueueAttributeName QueueAttributeNameDelaySeconds = "DelaySeconds" // @enum QueueAttributeName QueueAttributeNameReceiveMessageWaitTimeSeconds = "ReceiveMessageWaitTimeSeconds" // @enum QueueAttributeName QueueAttributeNameRedrivePolicy = "RedrivePolicy" )
mit
mcmil/wuff
examples/RcpApp-3/MyRcpApp/src/main/java/myrcpapp/View.java
435
package myrcpapp; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.part.ViewPart; public class View extends ViewPart { @Override public void createPartControl(final Composite parent) { Text text = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); text.setText("Hello, world!"); } @Override public void setFocus() { } }
mit
atomify/atomify-css
test/fixtures/css/node_modules/rework-clone/node_modules/rework/index.js
42
module.exports = require('./lib/rework');
mit
josephyzhou/nsq
nsqd/test/cluster_test.go
3316
package nsq import ( "fmt" "github.com/bitly/nsq/util" "github.com/bmizerany/assert" "io/ioutil" "log" "os" "strconv" "testing" "time" ) func TestNsqdToLookupd(t *testing.T) { log.SetOutput(ioutil.Discard) defer log.SetOutput(os.Stdout) topicName := "cluster_test" + strconv.Itoa(int(time.Now().Unix())) hostname, err := os.Hostname() if err != nil { t.Fatalf("ERROR: failed to get hostname - %s", err.Error()) } _, err = util.ApiRequest(fmt.Sprintf("http://127.0.0.1:4151/create_topic?topic=%s", topicName)) if err != nil { t.Fatalf(err.Error()) } _, err = util.ApiRequest(fmt.Sprintf("http://127.0.0.1:4151/create_channel?topic=%s&channel=ch", topicName)) if err != nil { t.Fatalf(err.Error()) } // allow some time for nsqd to push info to nsqlookupd time.Sleep(350 * time.Millisecond) data, err := util.ApiRequest("http://127.0.0.1:4161/debug") if err != nil { t.Fatalf(err.Error()) } topicData := data.Get("topic:" + topicName + ":") producers, _ := topicData.Array() assert.Equal(t, len(producers), 1) producer := topicData.GetIndex(0) assert.Equal(t, producer.Get("address").MustString(), hostname) assert.Equal(t, producer.Get("hostname").MustString(), hostname) assert.Equal(t, producer.Get("broadcast_address").MustString(), hostname) assert.Equal(t, producer.Get("tcp_port").MustInt(), 4150) assert.Equal(t, producer.Get("tombstoned").MustBool(), false) channelData := data.Get("channel:" + topicName + ":ch") producers, _ = channelData.Array() assert.Equal(t, len(producers), 1) producer = topicData.GetIndex(0) assert.Equal(t, producer.Get("address").MustString(), hostname) assert.Equal(t, producer.Get("hostname").MustString(), hostname) assert.Equal(t, producer.Get("broadcast_address").MustString(), hostname) assert.Equal(t, producer.Get("tcp_port").MustInt(), 4150) assert.Equal(t, producer.Get("tombstoned").MustBool(), false) data, err = util.ApiRequest("http://127.0.0.1:4161/lookup?topic=" + topicName) if err != nil { t.Fatalf(err.Error()) } producers, _ = data.Get("producers").Array() assert.Equal(t, len(producers), 1) producer = data.Get("producers").GetIndex(0) assert.Equal(t, producer.Get("address").MustString(), hostname) assert.Equal(t, producer.Get("hostname").MustString(), hostname) assert.Equal(t, producer.Get("broadcast_address").MustString(), hostname) assert.Equal(t, producer.Get("tcp_port").MustInt(), 4150) channels, _ := data.Get("channels").Array() assert.Equal(t, len(channels), 1) channel := channels[0].(string) assert.Equal(t, channel, "ch") data, err = util.ApiRequest("http://127.0.0.1:4151/delete_topic?topic=" + topicName) if err != nil { t.Fatalf(err.Error()) } // allow some time for nsqd to push info to nsqlookupd time.Sleep(350 * time.Millisecond) data, err = util.ApiRequest("http://127.0.0.1:4161/lookup?topic=" + topicName) if err != nil { t.Fatalf(err.Error()) } producers, _ = data.Get("producers").Array() assert.Equal(t, len(producers), 0) data, err = util.ApiRequest("http://127.0.0.1:4161/debug") if err != nil { t.Fatalf(err.Error()) } producers, _ = data.Get("topic:" + topicName + ":").Array() assert.Equal(t, len(producers), 0) producers, _ = data.Get("channel:" + topicName + ":ch").Array() assert.Equal(t, len(producers), 0) }
mit
olegsvs/android_kernel_archos_persimmon_3_18
drivers/misc/mediatek/thermal/common/mtk_thermal_dummy.c
699
#include <asm/uaccess.h> /* #include <asm/system.h> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/err.h> #include <mtk_thermal_typedefs.h> /* ************************************ */ /* Definition */ /* ************************************ */ unsigned long (*mtk_thermal_get_gpu_loading_fp)(void) = NULL; /*EXPORT_SYMBOL(mtk_thermal_get_gpu_loading_fp); Should open, but I turn it off for coding style */ /* Init */ static int __init mtk_thermal_platform_init(void) { int err = 0; return err; } /* Exit */ static void __exit mtk_thermal_platform_exit(void) { } module_init(mtk_thermal_platform_init); module_exit(mtk_thermal_platform_exit);
gpl-2.0
shminer/kernel-msm-3.18
drivers/gpu/drm/msm/sde/sde_formats.c
28085
/* Copyright (c) 2015-2016, The Linux Foundation. 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. */ #include <uapi/drm/drm_fourcc.h> #include "sde_kms.h" #include "sde_formats.h" #define SDE_UBWC_META_MACRO_W_H 16 #define SDE_UBWC_META_BLOCK_SIZE 256 #define SDE_MAX_IMG_WIDTH 0x3FFF #define SDE_MAX_IMG_HEIGHT 0x3FFF /** * SDE supported format packing, bpp, and other format * information. * SDE currently only supports interleaved RGB formats * UBWC support for a pixel format is indicated by the flag, * there is additional meta data plane for such formats */ #define INTERLEAVED_RGB_FMT(fmt, a, r, g, b, e0, e1, e2, e3, uc, alpha, \ bp, flg, fm, np) \ { \ .base.pixel_format = DRM_FORMAT_ ## fmt, \ .fetch_planes = SDE_PLANE_INTERLEAVED, \ .alpha_enable = alpha, \ .element = { (e0), (e1), (e2), (e3) }, \ .bits = { g, b, r, a }, \ .chroma_sample = SDE_CHROMA_RGB, \ .unpack_align_msb = 0, \ .unpack_tight = 1, \ .unpack_count = uc, \ .bpp = bp, \ .fetch_mode = fm, \ .flag = flg, \ .num_planes = np \ } #define INTERLEAVED_YUV_FMT(fmt, a, r, g, b, e0, e1, e2, e3, \ alpha, chroma, count, bp, flg, fm, np) \ { \ .base.pixel_format = DRM_FORMAT_ ## fmt, \ .fetch_planes = SDE_PLANE_INTERLEAVED, \ .alpha_enable = alpha, \ .element = { (e0), (e1), (e2), (e3)}, \ .bits = { g, b, r, a }, \ .chroma_sample = chroma, \ .unpack_align_msb = 0, \ .unpack_tight = 1, \ .unpack_count = count, \ .bpp = bp, \ .fetch_mode = fm, \ .flag = flg, \ .num_planes = np \ } #define PSEDUO_YUV_FMT(fmt, a, r, g, b, e0, e1, chroma, flg, fm, np) \ { \ .base.pixel_format = DRM_FORMAT_ ## fmt, \ .fetch_planes = SDE_PLANE_PSEUDO_PLANAR, \ .alpha_enable = false, \ .element = { (e0), (e1), 0, 0 }, \ .bits = { g, b, r, a }, \ .chroma_sample = chroma, \ .unpack_align_msb = 0, \ .unpack_tight = 1, \ .unpack_count = 2, \ .bpp = 2, \ .fetch_mode = fm, \ .flag = flg, \ .num_planes = np \ } #define PLANAR_YUV_FMT(fmt, a, r, g, b, e0, e1, e2, alpha, chroma, bp, \ flg, fm, np) \ { \ .base.pixel_format = DRM_FORMAT_ ## fmt, \ .fetch_planes = SDE_PLANE_PLANAR, \ .alpha_enable = alpha, \ .element = { (e0), (e1), (e2), 0 }, \ .bits = { g, b, r, a }, \ .chroma_sample = chroma, \ .unpack_align_msb = 0, \ .unpack_tight = 1, \ .unpack_count = 1, \ .bpp = bp, \ .fetch_mode = fm, \ .flag = flg, \ .num_planes = np \ } static const struct sde_format sde_format_map[] = { INTERLEAVED_RGB_FMT(ARGB8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C3_ALPHA, 4, true, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(ABGR8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, true, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGBA8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C3_ALPHA, C1_B_Cb, C0_G_Y, C2_R_Cr, 4, true, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGRA8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C3_ALPHA, C2_R_Cr, C0_G_Y, C1_B_Cb, 4, true, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGRX8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C3_ALPHA, C2_R_Cr, C0_G_Y, C1_B_Cb, 4, false, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(XBGR8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, false, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(XRGB8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C3_ALPHA, 4, false, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGBX8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C3_ALPHA, C1_B_Cb, C0_G_Y, C2_R_Cr, 4, false, 4, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGB888, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, 0, 3, false, 3, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGR888, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, 0, 3, false, 3, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGB565, 0, COLOR_5BIT, COLOR_6BIT, COLOR_5BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, 0, 3, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGR565, 0, COLOR_5BIT, COLOR_6BIT, COLOR_5BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, 0, 3, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(ARGB1555, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C3_ALPHA, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(ABGR1555, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGBA5551, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C3_ALPHA, C1_B_Cb, C0_G_Y, C2_R_Cr, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGRA5551, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C3_ALPHA, C2_R_Cr, C0_G_Y, C1_B_Cb, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(XRGB1555, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C3_ALPHA, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(XBGR1555, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGBX5551, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C3_ALPHA, C1_B_Cb, C0_G_Y, C2_R_Cr, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGRX5551, COLOR_ALPHA_1BIT, COLOR_5BIT, COLOR_5BIT, COLOR_5BIT, C3_ALPHA, C2_R_Cr, C0_G_Y, C1_B_Cb, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(ARGB4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C3_ALPHA, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(ABGR4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGBA4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C3_ALPHA, C1_B_Cb, C0_G_Y, C2_R_Cr, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGRA4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C3_ALPHA, C2_R_Cr, C0_G_Y, C1_B_Cb, 4, true, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(XRGB4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C3_ALPHA, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(XBGR4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(RGBX4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C3_ALPHA, C1_B_Cb, C0_G_Y, C2_R_Cr, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), INTERLEAVED_RGB_FMT(BGRX4444, COLOR_ALPHA_4BIT, COLOR_4BIT, COLOR_4BIT, COLOR_4BIT, C3_ALPHA, C2_R_Cr, C0_G_Y, C1_B_Cb, 4, false, 2, 0, SDE_FETCH_LINEAR, 1), PSEDUO_YUV_FMT(NV12, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C2_R_Cr, SDE_CHROMA_420, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), PSEDUO_YUV_FMT(NV21, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C1_B_Cb, SDE_CHROMA_420, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), PSEDUO_YUV_FMT(NV16, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C2_R_Cr, SDE_CHROMA_H2V1, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), PSEDUO_YUV_FMT(NV61, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C1_B_Cb, SDE_CHROMA_H2V1, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), INTERLEAVED_YUV_FMT(VYUY, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C0_G_Y, false, SDE_CHROMA_H2V1, 4, 2, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), INTERLEAVED_YUV_FMT(UYVY, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C0_G_Y, C2_R_Cr, C0_G_Y, false, SDE_CHROMA_H2V1, 4, 2, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), INTERLEAVED_YUV_FMT(YUYV, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C0_G_Y, C1_B_Cb, C0_G_Y, C2_R_Cr, false, SDE_CHROMA_H2V1, 4, 2, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), INTERLEAVED_YUV_FMT(YVYU, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C0_G_Y, C2_R_Cr, C0_G_Y, C1_B_Cb, false, SDE_CHROMA_H2V1, 4, 2, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 2), PLANAR_YUV_FMT(YUV420, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C1_B_Cb, C0_G_Y, false, SDE_CHROMA_420, 1, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 3), PLANAR_YUV_FMT(YVU420, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C2_R_Cr, C0_G_Y, false, SDE_CHROMA_420, 1, SDE_FORMAT_FLAG_YUV, SDE_FETCH_LINEAR, 3), }; /* * UBWC formats table: * This table holds the UBWC formats supported. * If a compression ratio needs to be used for this or any other format, * the data will be passed by user-space. */ static const struct sde_format sde_format_map_ubwc[] = { INTERLEAVED_RGB_FMT(RGB565, 0, COLOR_5BIT, COLOR_6BIT, COLOR_5BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, 0, 3, false, 2, 0, SDE_FETCH_UBWC, 2), INTERLEAVED_RGB_FMT(RGBA8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, true, 4, 0, SDE_FETCH_UBWC, 2), INTERLEAVED_RGB_FMT(RGBX8888, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C2_R_Cr, C0_G_Y, C1_B_Cb, C3_ALPHA, 4, false, 4, 0, SDE_FETCH_UBWC, 2), PSEDUO_YUV_FMT(NV12, 0, COLOR_8BIT, COLOR_8BIT, COLOR_8BIT, C1_B_Cb, C2_R_Cr, SDE_CHROMA_420, SDE_FORMAT_FLAG_YUV, SDE_FETCH_UBWC, 4), }; /* _sde_get_v_h_subsample_rate - Get subsample rates for all formats we support * Note: Not using the drm_format_*_subsampling since we have formats */ static void _sde_get_v_h_subsample_rate( enum sde_chroma_samp_type chroma_sample, uint32_t *v_sample, uint32_t *h_sample) { if (!v_sample || !h_sample) return; switch (chroma_sample) { case SDE_CHROMA_H2V1: *v_sample = 1; *h_sample = 2; break; case SDE_CHROMA_H1V2: *v_sample = 2; *h_sample = 1; break; case SDE_CHROMA_420: *v_sample = 2; *h_sample = 2; break; default: *v_sample = 1; *h_sample = 1; break; } } static int _sde_format_get_plane_sizes_ubwc( const struct sde_format *fmt, const uint32_t width, const uint32_t height, struct sde_hw_fmt_layout *layout) { int i; memset(layout, 0, sizeof(struct sde_hw_fmt_layout)); layout->format = fmt; layout->width = width; layout->height = height; layout->num_planes = fmt->num_planes; if (fmt->base.pixel_format == DRM_FORMAT_NV12) { uint32_t y_stride_alignment, uv_stride_alignment; uint32_t y_height_alignment, uv_height_alignment; uint32_t y_tile_width = 32; uint32_t y_tile_height = 8; uint32_t uv_tile_width = y_tile_width / 2; uint32_t uv_tile_height = y_tile_height; uint32_t y_bpp_numer = 1, y_bpp_denom = 1; uint32_t uv_bpp_numer = 1, uv_bpp_denom = 1; y_stride_alignment = 128; uv_stride_alignment = 64; y_height_alignment = 32; uv_height_alignment = 32; y_bpp_numer = 1; uv_bpp_numer = 2; y_bpp_denom = 1; uv_bpp_denom = 1; layout->num_planes = 4; /* Y bitstream stride and plane size */ layout->plane_pitch[0] = ALIGN(width, y_stride_alignment); layout->plane_pitch[0] = (layout->plane_pitch[0] * y_bpp_numer) / y_bpp_denom; layout->plane_size[0] = ALIGN(layout->plane_pitch[0] * ALIGN(height, y_height_alignment), 4096); /* CbCr bitstream stride and plane size */ layout->plane_pitch[1] = ALIGN(width / 2, uv_stride_alignment); layout->plane_pitch[1] = (layout->plane_pitch[1] * uv_bpp_numer) / uv_bpp_denom; layout->plane_size[1] = ALIGN(layout->plane_pitch[1] * ALIGN(height / 2, uv_height_alignment), 4096); /* Y meta data stride and plane size */ layout->plane_pitch[2] = ALIGN( DIV_ROUND_UP(width, y_tile_width), 64); layout->plane_size[2] = ALIGN(layout->plane_pitch[2] * ALIGN(DIV_ROUND_UP(height, y_tile_height), 16), 4096); /* CbCr meta data stride and plane size */ layout->plane_pitch[3] = ALIGN( DIV_ROUND_UP(width / 2, uv_tile_width), 64); layout->plane_size[3] = ALIGN(layout->plane_pitch[3] * ALIGN(DIV_ROUND_UP(height / 2, uv_tile_height), 16), 4096); } else if (fmt->base.pixel_format == DRM_FORMAT_RGBA8888 || fmt->base.pixel_format == DRM_FORMAT_RGBX8888 || fmt->base.pixel_format == DRM_FORMAT_RGB565) { uint32_t stride_alignment, aligned_bitstream_width; if (fmt->base.pixel_format == DRM_FORMAT_RGB565) stride_alignment = 128; else stride_alignment = 64; layout->num_planes = 3; /* Nothing in plane[1] */ /* RGB bitstream stride and plane size */ aligned_bitstream_width = ALIGN(width, stride_alignment); layout->plane_pitch[0] = aligned_bitstream_width * fmt->bpp; layout->plane_size[0] = ALIGN(fmt->bpp * aligned_bitstream_width * ALIGN(height, 16), 4096); /* RGB meta data stride and plane size */ layout->plane_pitch[2] = ALIGN(DIV_ROUND_UP( aligned_bitstream_width, 16), 64); layout->plane_size[2] = ALIGN(layout->plane_pitch[2] * ALIGN(DIV_ROUND_UP(height, 4), 16), 4096); } else { DRM_ERROR("UBWC format not supported for fmt:0x%X\n", fmt->base.pixel_format); return -EINVAL; } for (i = 0; i < SDE_MAX_PLANES; i++) layout->total_size += layout->plane_size[i]; return 0; } static int _sde_format_get_plane_sizes_linear( const struct sde_format *fmt, const uint32_t width, const uint32_t height, struct sde_hw_fmt_layout *layout) { int i; memset(layout, 0, sizeof(struct sde_hw_fmt_layout)); layout->format = fmt; layout->width = width; layout->height = height; layout->num_planes = fmt->num_planes; /* Due to memset above, only need to set planes of interest */ if (fmt->fetch_planes == SDE_PLANE_INTERLEAVED) { layout->num_planes = 1; layout->plane_size[0] = width * height * layout->format->bpp; layout->plane_pitch[0] = width * layout->format->bpp; } else { uint32_t v_subsample, h_subsample; uint32_t chroma_samp; chroma_samp = fmt->chroma_sample; _sde_get_v_h_subsample_rate(chroma_samp, &v_subsample, &h_subsample); if (width % h_subsample || height % v_subsample) { DRM_ERROR("mismatch in subsample vs dimensions\n"); return -EINVAL; } layout->plane_pitch[0] = width; layout->plane_pitch[1] = width / h_subsample; layout->plane_size[0] = layout->plane_pitch[0] * height; layout->plane_size[1] = layout->plane_pitch[1] * (height / v_subsample); if (fmt->fetch_planes == SDE_PLANE_PSEUDO_PLANAR) { layout->num_planes = 2; layout->plane_size[1] *= 2; layout->plane_pitch[1] *= 2; } else { /* planar */ layout->num_planes = 3; layout->plane_size[2] = layout->plane_size[1]; layout->plane_pitch[2] = layout->plane_pitch[1]; } } for (i = 0; i < SDE_MAX_PLANES; i++) layout->total_size += layout->plane_size[i]; return 0; } static int _sde_format_get_plane_sizes( const struct sde_format *fmt, const uint32_t w, const uint32_t h, struct sde_hw_fmt_layout *layout) { if (!layout || !fmt) { DRM_ERROR("invalid pointer\n"); return -EINVAL; } if ((w > SDE_MAX_IMG_WIDTH) || (h > SDE_MAX_IMG_HEIGHT)) { DRM_ERROR("image dimensions outside max range\n"); return -ERANGE; } if (SDE_FORMAT_IS_UBWC(fmt)) return _sde_format_get_plane_sizes_ubwc(fmt, w, h, layout); return _sde_format_get_plane_sizes_linear(fmt, w, h, layout); } static int _sde_format_populate_addrs_ubwc( int mmu_id, struct drm_framebuffer *fb, struct sde_hw_fmt_layout *layout) { uint32_t base_addr; if (!fb || !layout) { DRM_ERROR("invalid pointers\n"); return -EINVAL; } base_addr = msm_framebuffer_iova(fb, mmu_id, 0); if (!base_addr) { DRM_ERROR("failed to retrieve base addr\n"); return -EFAULT; } /* Per-format logic for verifying active planes */ if (SDE_FORMAT_IS_YUV(layout->format)) { /************************************************/ /* UBWC ** */ /* buffer ** SDE PLANE */ /* format ** */ /************************************************/ /* ------------------- ** -------------------- */ /* | Y meta | ** | Y bitstream | */ /* | data | ** | plane | */ /* ------------------- ** -------------------- */ /* | Y bitstream | ** | CbCr bitstream | */ /* | data | ** | plane | */ /* ------------------- ** -------------------- */ /* | Cbcr metadata | ** | Y meta | */ /* | data | ** | plane | */ /* ------------------- ** -------------------- */ /* | CbCr bitstream | ** | CbCr meta | */ /* | data | ** | plane | */ /* ------------------- ** -------------------- */ /************************************************/ /* configure Y bitstream plane */ layout->plane_addr[0] = base_addr + layout->plane_size[2]; /* configure CbCr bitstream plane */ layout->plane_addr[1] = base_addr + layout->plane_size[0] + layout->plane_size[2] + layout->plane_size[3]; /* configure Y metadata plane */ layout->plane_addr[2] = base_addr; /* configure CbCr metadata plane */ layout->plane_addr[3] = base_addr + layout->plane_size[0] + layout->plane_size[2]; } else { /************************************************/ /* UBWC ** */ /* buffer ** SDE PLANE */ /* format ** */ /************************************************/ /* ------------------- ** -------------------- */ /* | RGB meta | ** | RGB bitstream | */ /* | data | ** | plane | */ /* ------------------- ** -------------------- */ /* | RGB bitstream | ** | NONE | */ /* | data | ** | | */ /* ------------------- ** -------------------- */ /* ** | RGB meta | */ /* ** | plane | */ /* ** -------------------- */ /************************************************/ layout->plane_addr[0] = base_addr + layout->plane_size[2]; layout->plane_addr[1] = 0; layout->plane_addr[2] = base_addr; layout->plane_addr[3] = 0; } return 0; } static int _sde_format_populate_addrs_linear( int mmu_id, struct drm_framebuffer *fb, struct sde_hw_fmt_layout *layout) { unsigned int i; /* Update layout pitches from fb */ for (i = 0; i < layout->num_planes; ++i) { if (layout->plane_pitch[i] != fb->pitches[i]) { SDE_DEBUG("plane %u expected pitch %u, fb %u\n", i, layout->plane_pitch[i], fb->pitches[i]); layout->plane_pitch[i] = fb->pitches[i]; } } /* Populate addresses for simple formats here */ for (i = 0; i < layout->num_planes; ++i) { layout->plane_addr[i] = msm_framebuffer_iova(fb, mmu_id, i); if (!layout->plane_addr[i]) { DRM_ERROR("failed to retrieve base addr\n"); return -EFAULT; } } return 0; } int sde_format_populate_layout( int mmu_id, struct drm_framebuffer *fb, struct sde_hw_fmt_layout *layout) { int ret; if (!fb || !layout) { DRM_ERROR("invalid arguments\n"); return -EINVAL; } if ((fb->width > SDE_MAX_IMG_WIDTH) || (fb->height > SDE_MAX_IMG_HEIGHT)) { DRM_ERROR("image dimensions outside max range\n"); return -ERANGE; } layout->format = to_sde_format(msm_framebuffer_format(fb)); /* Populate the plane sizes etc via get_format */ ret = _sde_format_get_plane_sizes(layout->format, fb->width, fb->height, layout); if (ret) return ret; /* Populate the addresses given the fb */ if (SDE_FORMAT_IS_UBWC(layout->format)) ret = _sde_format_populate_addrs_ubwc(mmu_id, fb, layout); else ret = _sde_format_populate_addrs_linear(mmu_id, fb, layout); return ret; } static void _sde_format_calc_offset_linear(struct sde_hw_fmt_layout *source, u32 x, u32 y) { if ((x == 0) && (y == 0)) return; source->plane_addr[0] += y * source->plane_pitch[0]; if (source->num_planes == 1) { source->plane_addr[0] += x * source->format->bpp; } else { uint32_t xoff, yoff; uint32_t v_subsample = 1; uint32_t h_subsample = 1; _sde_get_v_h_subsample_rate(source->format->chroma_sample, &v_subsample, &h_subsample); xoff = x / h_subsample; yoff = y / v_subsample; source->plane_addr[0] += x; source->plane_addr[1] += xoff + (yoff * source->plane_pitch[1]); if (source->num_planes == 2) /* pseudo planar */ source->plane_addr[1] += xoff; else /* planar */ source->plane_addr[2] += xoff + (yoff * source->plane_pitch[2]); } } int sde_format_populate_layout_with_roi( int mmu_id, struct drm_framebuffer *fb, struct sde_rect *roi, struct sde_hw_fmt_layout *layout) { int ret; ret = sde_format_populate_layout(mmu_id, fb, layout); if (ret || !roi) return ret; if (!roi->w || !roi->h || (roi->x + roi->w > fb->width) || (roi->y + roi->h > fb->height)) { DRM_ERROR("invalid roi=[%d,%d,%d,%d], fb=[%u,%u]\n", roi->x, roi->y, roi->w, roi->h, fb->width, fb->height); ret = -EINVAL; } else if (SDE_FORMAT_IS_LINEAR(layout->format)) { _sde_format_calc_offset_linear(layout, roi->x, roi->y); layout->width = roi->w; layout->height = roi->h; } else if (roi->x || roi->y || (roi->w != fb->width) || (roi->h != fb->height)) { DRM_ERROR("non-linear layout with roi not supported\n"); ret = -EINVAL; } return ret; } int sde_format_check_modified_format( const struct msm_kms *kms, const struct msm_format *msm_fmt, const struct drm_mode_fb_cmd2 *cmd, struct drm_gem_object **bos) { int ret, i, num_base_fmt_planes; const struct sde_format *fmt; struct sde_hw_fmt_layout layout; uint32_t bos_total_size = 0; if (!msm_fmt || !cmd || !bos) { DRM_ERROR("invalid arguments\n"); return -EINVAL; } fmt = to_sde_format(msm_fmt); num_base_fmt_planes = drm_format_num_planes(fmt->base.pixel_format); ret = _sde_format_get_plane_sizes(fmt, cmd->width, cmd->height, &layout); if (ret) return ret; for (i = 0; i < num_base_fmt_planes; i++) { if (!bos[i]) { DRM_ERROR("invalid handle for plane %d\n", i); return -EINVAL; } bos_total_size += bos[i]->size; } if (bos_total_size < layout.total_size) { DRM_ERROR("buffers total size too small %u expected %u\n", bos_total_size, layout.total_size); return -EINVAL; } return 0; } const struct sde_format *sde_get_sde_format_ext( const uint32_t format, const uint64_t *modifiers, const uint32_t modifiers_len) { uint32_t i = 0; uint64_t mod0 = 0; const struct sde_format *fmt = NULL; const struct sde_format *map = NULL; ssize_t map_size = 0; /* * Currently only support exactly zero or one modifier. * All planes used must specify the same modifier. */ if (modifiers_len && !modifiers) { DRM_ERROR("invalid modifiers array\n"); return NULL; } else if (modifiers && modifiers_len && modifiers[0]) { mod0 = modifiers[0]; DBG("plane format modifier 0x%llX", mod0); for (i = 1; i < modifiers_len; i++) { if (modifiers[i] != mod0) { DRM_ERROR("bad fmt mod 0x%llX on plane %d\n", modifiers[i], i); return NULL; } } } switch (mod0) { case 0: map = sde_format_map; map_size = ARRAY_SIZE(sde_format_map); break; case DRM_FORMAT_MOD_QCOM_COMPRESSED: map = sde_format_map_ubwc; map_size = ARRAY_SIZE(sde_format_map_ubwc); DBG("found fmt 0x%X DRM_FORMAT_MOD_QCOM_COMPRESSED", format); break; default: DRM_ERROR("unsupported format modifier %llX\n", mod0); return NULL; } for (i = 0; i < map_size; i++) { if (format == map[i].base.pixel_format) { fmt = &map[i]; break; } } if (fmt == NULL) DRM_ERROR("unsupported fmt 0x%X modifier 0x%llX\n", format, mod0); else DBG("fmt %s mod 0x%llX ubwc %d yuv %d", drm_get_format_name(format), mod0, SDE_FORMAT_IS_UBWC(fmt), SDE_FORMAT_IS_YUV(fmt)); return fmt; } const struct msm_format *sde_get_msm_format( struct msm_kms *kms, const uint32_t format, const uint64_t *modifiers, const uint32_t modifiers_len) { const struct sde_format *fmt = sde_get_sde_format_ext(format, modifiers, modifiers_len); if (fmt) return &fmt->base; return NULL; } uint32_t sde_populate_formats( const struct sde_format_extended *format_list, uint32_t *pixel_formats, uint64_t *pixel_modifiers, uint32_t pixel_formats_max) { uint32_t i, fourcc_format; if (!format_list || !pixel_formats) return 0; for (i = 0, fourcc_format = 0; format_list->fourcc_format && i < pixel_formats_max; ++format_list) { /* verify if listed format is in sde_format_map? */ /* optionally return modified formats */ if (pixel_modifiers) { /* assume same modifier for all fb planes */ pixel_formats[i] = format_list->fourcc_format; pixel_modifiers[i++] = format_list->modifier; } else { /* assume base formats grouped together */ if (fourcc_format != format_list->fourcc_format) { fourcc_format = format_list->fourcc_format; pixel_formats[i++] = fourcc_format; } } } return i; }
gpl-2.0
kgp700/nexroid-sgs4a-jb
arch/arm/mach-msm/smp2p.c
50049
/* arch/arm/mach-msm/smp2p.c * * Copyright (c) 2013, The Linux Foundation. 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. */ #include <linux/list.h> #include <linux/ctype.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/io.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <mach/msm_smem.h> #include <mach/msm_ipc_logging.h> #include "smp2p_private_api.h" #include "smp2p_private.h" #define NUM_LOG_PAGES 3 /** * struct msm_smp2p_out - This structure represents the outbound SMP2P entry. * * @remote_pid: Outbound processor ID. * @name: Entry name. * @out_edge_list: Adds this structure into smp2p_out_list_item::list. * @msm_smp2p_notifier_list: Notifier block head used to notify for open event. * @open_nb: Notifier block used to notify for open event. * @l_smp2p_entry: Pointer to the actual entry in the SMEM item. */ struct msm_smp2p_out { int remote_pid; char name[SMP2P_MAX_ENTRY_NAME]; struct list_head out_edge_list; struct raw_notifier_head msm_smp2p_notifier_list; struct notifier_block *open_nb; uint32_t __iomem *l_smp2p_entry; }; /** * struct smp2p_out_list_item - Maintains the state of outbound edge. * * @out_item_lock_lha1: Lock protecting all elements of the structure. * @list: list of outbound entries (struct msm_smp2p_out). * @smem_edge_out: Pointer to outbound smem item. * @smem_edge_state: State of the outbound edge. * @ops_ptr: Pointer to internal version-specific SMEM item access functions. */ struct smp2p_out_list_item { spinlock_t out_item_lock_lha1; struct list_head list; struct smp2p_smem __iomem *smem_edge_out; enum msm_smp2p_edge_state smem_edge_state; struct smp2p_version_if *ops_ptr; }; static struct smp2p_out_list_item out_list[SMP2P_NUM_PROCS]; static void *log_ctx; static int smp2p_debug_mask = MSM_SMP2P_INFO; module_param_named(debug_mask, smp2p_debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP); /** * struct smp2p_in - Represents the entry on remote processor. * * @name: Name of the entry. * @remote_pid: Outbound processor ID. * @in_edge_list: Adds this structure into smp2p_in_list_item::list. * @in_notifier_list: List for notifier block for entry opening/updates. * @prev_entry_val: Previous value of the entry. * @entry_ptr: Points to the current value in smem item. * @notifier_count: Counts the number of notifier registered per pid,entry. */ struct smp2p_in { int remote_pid; char name[SMP2P_MAX_ENTRY_NAME]; struct list_head in_edge_list; struct raw_notifier_head in_notifier_list; uint32_t prev_entry_val; uint32_t __iomem *entry_ptr; uint32_t notifier_count; }; /** * struct smp2p_in_list_item - Maintains the inbound edge state. * * @in_item_lock_lhb1: Lock protecting all elements of the structure. * @list: List head for the entries on remote processor. * @smem_edge_in: Pointer to the remote smem item. */ struct smp2p_in_list_item { spinlock_t in_item_lock_lhb1; struct list_head list; struct smp2p_smem __iomem *smem_edge_in; uint32_t item_size; uint32_t safe_total_entries; }; static struct smp2p_in_list_item in_list[SMP2P_NUM_PROCS]; /** * SMEM Item access function interface. * * This interface is used to help isolate the implementation of * the functionality from any changes in the shared data structures * that may happen as versions are changed. * * @is_supported: True if this version is supported by SMP2P * @negotiate_features: Returns (sub)set of supported features * @find_entry: Finds existing / next empty entry * @create_entry: Creates a new entry * @read_entry: Reads the value of an entry * @write_entry: Writes a new value to an entry * @modify_entry: Does a read/modify/write of an entry * validate_size: Verifies the size of the remote SMEM item to ensure that * an invalid item size doesn't result in an out-of-bounds * memory access. */ struct smp2p_version_if { /* common functions */ bool is_supported; uint32_t (*negotiate_features)(uint32_t features); void (*find_entry)(struct smp2p_smem __iomem *item, uint32_t entries_total, char *name, uint32_t **entry_ptr, int *empty_spot); /* outbound entry functions */ int (*create_entry)(struct msm_smp2p_out *); int (*read_entry)(struct msm_smp2p_out *, uint32_t *); int (*write_entry)(struct msm_smp2p_out *, uint32_t); int (*modify_entry)(struct msm_smp2p_out *, uint32_t, uint32_t); /* inbound entry functions */ struct smp2p_smem __iomem *(*validate_size)(int remote_pid, struct smp2p_smem __iomem *, uint32_t); }; static int smp2p_do_negotiation(int remote_pid, struct smp2p_out_list_item *p); static void smp2p_send_interrupt(int remote_pid); /* v0 (uninitialized SMEM item) interface functions */ static uint32_t smp2p_negotiate_features_v0(uint32_t features); static void smp2p_find_entry_v0(struct smp2p_smem __iomem *item, uint32_t entries_total, char *name, uint32_t **entry_ptr, int *empty_spot); static int smp2p_out_create_v0(struct msm_smp2p_out *); static int smp2p_out_read_v0(struct msm_smp2p_out *, uint32_t *); static int smp2p_out_write_v0(struct msm_smp2p_out *, uint32_t); static int smp2p_out_modify_v0(struct msm_smp2p_out *, uint32_t, uint32_t); static struct smp2p_smem __iomem *smp2p_in_validate_size_v0(int remote_pid, struct smp2p_smem __iomem *smem_item, uint32_t size); /* v1 interface functions */ static uint32_t smp2p_negotiate_features_v1(uint32_t features); static void smp2p_find_entry_v1(struct smp2p_smem __iomem *item, uint32_t entries_total, char *name, uint32_t **entry_ptr, int *empty_spot); static int smp2p_out_create_v1(struct msm_smp2p_out *); static int smp2p_out_read_v1(struct msm_smp2p_out *, uint32_t *); static int smp2p_out_write_v1(struct msm_smp2p_out *, uint32_t); static int smp2p_out_modify_v1(struct msm_smp2p_out *, uint32_t, uint32_t); static struct smp2p_smem __iomem *smp2p_in_validate_size_v1(int remote_pid, struct smp2p_smem __iomem *smem_item, uint32_t size); /* Version interface functions */ static struct smp2p_version_if version_if[] = { [0] = { .negotiate_features = smp2p_negotiate_features_v0, .find_entry = smp2p_find_entry_v0, .create_entry = smp2p_out_create_v0, .read_entry = smp2p_out_read_v0, .write_entry = smp2p_out_write_v0, .modify_entry = smp2p_out_modify_v0, .validate_size = smp2p_in_validate_size_v0, }, [1] = { .is_supported = true, .negotiate_features = smp2p_negotiate_features_v1, .find_entry = smp2p_find_entry_v1, .create_entry = smp2p_out_create_v1, .read_entry = smp2p_out_read_v1, .write_entry = smp2p_out_write_v1, .modify_entry = smp2p_out_modify_v1, .validate_size = smp2p_in_validate_size_v1, }, }; /* interrupt configuration (filled by device tree) */ static struct smp2p_interrupt_config smp2p_int_cfgs[SMP2P_NUM_PROCS] = { [SMP2P_MODEM_PROC].name = "modem", [SMP2P_AUDIO_PROC].name = "lpass", [SMP2P_WIRELESS_PROC].name = "wcnss", [SMP2P_REMOTE_MOCK_PROC].name = "mock", }; /** * smp2p_get_log_ctx - Return log context for other SMP2P modules. * * @returns: Log context or NULL if none. */ void *smp2p_get_log_ctx(void) { return log_ctx; } /** * smp2p_get_debug_mask - Return debug mask. * * @returns: Current debug mask. */ int smp2p_get_debug_mask(void) { return smp2p_debug_mask; } /** * smp2p_interrupt_config - Return interrupt configuration. * * @returns interrupt configuration array for usage by debugfs. */ struct smp2p_interrupt_config *smp2p_get_interrupt_config(void) { return smp2p_int_cfgs; } /** * smp2p_pid_to_name - Lookup name for remote pid. * * @returns: name (may be NULL). */ const char *smp2p_pid_to_name(int remote_pid) { if (remote_pid >= SMP2P_NUM_PROCS) return NULL; return smp2p_int_cfgs[remote_pid].name; } /** * smp2p_get_in_item - Return pointer to remote smem item. * * @remote_pid: Processor ID of the remote system. * @returns: Pointer to inbound SMEM item * * This is used by debugfs to print the smem items. */ struct smp2p_smem __iomem *smp2p_get_in_item(int remote_pid) { void *ret = NULL; unsigned long flags; spin_lock_irqsave(&in_list[remote_pid].in_item_lock_lhb1, flags); if (remote_pid < SMP2P_NUM_PROCS) ret = in_list[remote_pid].smem_edge_in; spin_unlock_irqrestore(&in_list[remote_pid].in_item_lock_lhb1, flags); return ret; } /** * smp2p_get_out_item - Return pointer to outbound SMEM item. * * @remote_pid: Processor ID of remote system. * @state: Edge state of the outbound SMEM item. * @returns: Pointer to outbound (remote) SMEM item. */ struct smp2p_smem __iomem *smp2p_get_out_item(int remote_pid, int *state) { void *ret = NULL; unsigned long flags; spin_lock_irqsave(&out_list[remote_pid].out_item_lock_lha1, flags); if (remote_pid < SMP2P_NUM_PROCS) { ret = out_list[remote_pid].smem_edge_out; if (state) *state = out_list[remote_pid].smem_edge_state; } spin_unlock_irqrestore(&out_list[remote_pid].out_item_lock_lha1, flags); return ret; } /** * smp2p_get_smem_item_id - Return the proper SMEM item ID. * * @write_id: Processor that will write to the item. * @read_id: Processor that will read from the item. * @returns: SMEM ID */ static int smp2p_get_smem_item_id(int write_pid, int read_pid) { int ret = -EINVAL; switch (write_pid) { case SMP2P_APPS_PROC: ret = SMEM_SMP2P_APPS_BASE + read_pid; break; case SMP2P_MODEM_PROC: ret = SMEM_SMP2P_MODEM_BASE + read_pid; break; case SMP2P_AUDIO_PROC: ret = SMEM_SMP2P_AUDIO_BASE + read_pid; break; case SMP2P_WIRELESS_PROC: ret = SMEM_SMP2P_WIRLESS_BASE + read_pid; break; case SMP2P_POWER_PROC: ret = SMEM_SMP2P_POWER_BASE + read_pid; break; } return ret; } /** * Return pointer to SMEM item owned by the local processor. * * @remote_pid: Remote processor ID * @returns: NULL for failure; otherwise pointer to SMEM item * * Must be called with out_item_lock_lha1 locked for mock proc. */ static void *smp2p_get_local_smem_item(int remote_pid) { struct smp2p_smem __iomem *item_ptr = NULL; if (remote_pid < SMP2P_REMOTE_MOCK_PROC) { unsigned size; int smem_id; /* lookup or allocate SMEM item */ smem_id = smp2p_get_smem_item_id(SMP2P_APPS_PROC, remote_pid); if (smem_id >= 0) { item_ptr = smem_get_entry(smem_id, &size); if (!item_ptr) { size = sizeof(struct smp2p_smem_item); item_ptr = smem_alloc2(smem_id, size); } } } else if (remote_pid == SMP2P_REMOTE_MOCK_PROC) { /* * This path is only used during unit testing so * the GFP_ATOMIC allocation should not be a * concern. */ if (!out_list[SMP2P_REMOTE_MOCK_PROC].smem_edge_out) item_ptr = kzalloc( sizeof(struct smp2p_smem_item), GFP_ATOMIC); } return item_ptr; } /** * smp2p_get_remote_smem_item - Return remote SMEM item. * * @remote_pid: Remote processor ID * @out_item: Pointer to the output item structure * @returns: NULL for failure; otherwise pointer to SMEM item * * Return pointer to SMEM item owned by the remote processor. * * Note that this function does an SMEM lookup which uses a remote spinlock, * so this function should not be called more than necessary. * * Must be called with out_item_lock_lha1 and in_item_lock_lhb1 locked. */ static void *smp2p_get_remote_smem_item(int remote_pid, struct smp2p_out_list_item *out_item) { void *item_ptr = NULL; unsigned size; if (!out_item) return item_ptr; if (remote_pid < SMP2P_REMOTE_MOCK_PROC) { int smem_id; smem_id = smp2p_get_smem_item_id(remote_pid, SMP2P_APPS_PROC); if (smem_id >= 0) item_ptr = smem_get_entry(smem_id, &size); } else if (remote_pid == SMP2P_REMOTE_MOCK_PROC) { item_ptr = msm_smp2p_get_remote_mock_smem_item(&size); } item_ptr = out_item->ops_ptr->validate_size(remote_pid, item_ptr, size); return item_ptr; } /** * smp2p_negotiate_features_v0 - Initial feature negotiation. * * @features: Inbound feature set. * @returns: Supported features (will be a same/subset of @features). */ static uint32_t smp2p_negotiate_features_v1(uint32_t features) { /* no supported features */ return 0; } /** * smp2p_find_entry_v1 - Search for an entry in SMEM item. * * @item: Pointer to the smem item. * @entries_total: Total number of entries in @item. * @name: Name of the entry. * @entry_ptr: Set to pointer of entry if found, NULL otherwise. * @empty_spot: If non-null, set to the value of the next empty entry. * * Searches for entry @name in the SMEM item. If found, a pointer * to the item is returned. If it isn't found, the first empty * index is returned in @empty_spot. */ static void smp2p_find_entry_v1(struct smp2p_smem __iomem *item, uint32_t entries_total, char *name, uint32_t **entry_ptr, int *empty_spot) { int i; struct smp2p_entry_v1 *pos; if (!item || !name || !entry_ptr) { SMP2P_ERR("%s: invalid arguments %p, %p, %p\n", __func__, item, name, entry_ptr); return; } *entry_ptr = NULL; if (empty_spot) *empty_spot = -1; pos = (struct smp2p_entry_v1 *)(char *)(item + 1); for (i = 0; i < entries_total; i++, ++pos) { if (pos->name[0]) { if (!strncmp(pos->name, name, SMP2P_MAX_ENTRY_NAME)) { *entry_ptr = &pos->entry; break; } } else if (empty_spot && *empty_spot < 0) { *empty_spot = i; } } } /** * smp2p_out_create_v1 - Creates a outbound SMP2P entry. * * @out_entry: Pointer to the SMP2P entry structure. * @returns: 0 on success, standard Linux error code otherwise. * * Must be called with out_item_lock_lha1 locked. */ static int smp2p_out_create_v1(struct msm_smp2p_out *out_entry) { struct smp2p_smem __iomem *smp2p_h_ptr; struct smp2p_out_list_item *p_list; uint32_t *state_entry_ptr; uint32_t empty_spot; uint32_t entries_total; uint32_t entries_valid; if (!out_entry) return -EINVAL; p_list = &out_list[out_entry->remote_pid]; if (p_list->smem_edge_state != SMP2P_EDGE_STATE_OPENED) { SMP2P_ERR("%s: item '%s':%d opened - wrong create called\n", __func__, out_entry->name, out_entry->remote_pid); return -ENODEV; } smp2p_h_ptr = p_list->smem_edge_out; entries_total = SMP2P_GET_ENT_TOTAL(smp2p_h_ptr->valid_total_ent); entries_valid = SMP2P_GET_ENT_VALID(smp2p_h_ptr->valid_total_ent); p_list->ops_ptr->find_entry(smp2p_h_ptr, entries_total, out_entry->name, &state_entry_ptr, &empty_spot); if (state_entry_ptr) { /* re-use existing entry */ out_entry->l_smp2p_entry = state_entry_ptr; SMP2P_DBG("%s: item '%s':%d reused\n", __func__, out_entry->name, out_entry->remote_pid); } else if (entries_valid >= entries_total) { /* need to allocate entry, but not more space */ SMP2P_ERR("%s: no space for item '%s':%d\n", __func__, out_entry->name, out_entry->remote_pid); return -ENOMEM; } else { /* allocate a new entry */ struct smp2p_entry_v1 *entry_ptr; entry_ptr = (struct smp2p_entry_v1 *)((char *)(smp2p_h_ptr + 1) + empty_spot * sizeof(struct smp2p_entry_v1)); strlcpy(entry_ptr->name, out_entry->name, sizeof(entry_ptr->name)); out_entry->l_smp2p_entry = &entry_ptr->entry; ++entries_valid; SMP2P_DBG("%s: item '%s':%d fully created as entry %d of %d\n", __func__, out_entry->name, out_entry->remote_pid, entries_valid, entries_total); SMP2P_SET_ENT_VALID(smp2p_h_ptr->valid_total_ent, entries_valid); smp2p_send_interrupt(out_entry->remote_pid); } raw_notifier_call_chain(&out_entry->msm_smp2p_notifier_list, SMP2P_OPEN, 0); return 0; } /** * smp2p_out_read_v1 - Read the data from an outbound entry. * * @out_entry: Pointer to the SMP2P entry structure. * @data: Out pointer, the data is available in this argument on success. * @returns: 0 on success, standard Linux error code otherwise. * * Must be called with out_item_lock_lha1 locked. */ static int smp2p_out_read_v1(struct msm_smp2p_out *out_entry, uint32_t *data) { struct smp2p_smem __iomem *smp2p_h_ptr; uint32_t remote_pid; if (!out_entry) return -EINVAL; smp2p_h_ptr = out_list[out_entry->remote_pid].smem_edge_out; remote_pid = SMP2P_GET_REMOTE_PID(smp2p_h_ptr->rem_loc_proc_id); if (remote_pid != out_entry->remote_pid) return -EINVAL; if (out_entry->l_smp2p_entry) { *data = readl_relaxed(out_entry->l_smp2p_entry); } else { SMP2P_ERR("%s: '%s':%d not yet OPEN\n", __func__, out_entry->name, remote_pid); return -ENODEV; } return 0; } /** * smp2p_out_write_v1 - Writes an outbound entry value. * * @out_entry: Pointer to the SMP2P entry structure. * @data: The data to be written. * @returns: 0 on success, standard Linux error code otherwise. * * Must be called with out_item_lock_lha1 locked. */ static int smp2p_out_write_v1(struct msm_smp2p_out *out_entry, uint32_t data) { struct smp2p_smem __iomem *smp2p_h_ptr; uint32_t remote_pid; if (!out_entry) return -EINVAL; smp2p_h_ptr = out_list[out_entry->remote_pid].smem_edge_out; remote_pid = SMP2P_GET_REMOTE_PID(smp2p_h_ptr->rem_loc_proc_id); if (remote_pid != out_entry->remote_pid) return -EINVAL; if (out_entry->l_smp2p_entry) { writel_relaxed(data, out_entry->l_smp2p_entry); smp2p_send_interrupt(remote_pid); } else { SMP2P_ERR("%s: '%s':%d not yet OPEN\n", __func__, out_entry->name, remote_pid); return -ENODEV; } return 0; } /** * smp2p_out_modify_v1 - Modifies and outbound value. * * @set_mask: Mask containing the bits that needs to be set. * @clear_mask: Mask containing the bits that needs to be cleared. * @returns: 0 on success, standard Linux error code otherwise. * * The clear mask is applied first, so if a bit is set in both clear and * set mask, the result will be that the bit is set. * * Must be called with out_item_lock_lha1 locked. */ static int smp2p_out_modify_v1(struct msm_smp2p_out *out_entry, uint32_t set_mask, uint32_t clear_mask) { struct smp2p_smem __iomem *smp2p_h_ptr; uint32_t remote_pid; if (!out_entry) return -EINVAL; smp2p_h_ptr = out_list[out_entry->remote_pid].smem_edge_out; remote_pid = SMP2P_GET_REMOTE_PID(smp2p_h_ptr->rem_loc_proc_id); if (remote_pid != out_entry->remote_pid) return -EINVAL; if (out_entry->l_smp2p_entry) { uint32_t curr_value; curr_value = readl_relaxed(out_entry->l_smp2p_entry); writel_relaxed((curr_value & ~clear_mask) | set_mask, out_entry->l_smp2p_entry); } else { SMP2P_ERR("%s: '%s':%d not yet OPEN\n", __func__, out_entry->name, remote_pid); return -ENODEV; } smp2p_send_interrupt(remote_pid); return 0; } /** * smp2p_in_validate_size_v1 - Size validation for version 1. * * @remote_pid: Remote processor ID. * @smem_item: Pointer to the inbound SMEM item. * @size: Size of the SMEM item. * @returns: Validated smem_item pointer (or NULL if size is too small). * * Validates we don't end up with out-of-bounds array access due to invalid * smem item size. If out-of-bound array access can't be avoided, then an * error message is printed and NULL is returned to prevent usage of the * item. * * Must be called with in_item_lock_lhb1 locked. */ static struct smp2p_smem __iomem *smp2p_in_validate_size_v1(int remote_pid, struct smp2p_smem __iomem *smem_item, uint32_t size) { uint32_t total_entries; unsigned expected_size; struct smp2p_smem __iomem *item_ptr; struct smp2p_in_list_item *in_item; if (remote_pid >= SMP2P_NUM_PROCS || !smem_item) return NULL; in_item = &in_list[remote_pid]; item_ptr = (struct smp2p_smem __iomem *)smem_item; total_entries = SMP2P_GET_ENT_TOTAL(item_ptr->valid_total_ent); if (total_entries > 0) { in_item->safe_total_entries = total_entries; in_item->item_size = size; expected_size = sizeof(struct smp2p_smem) + (total_entries * sizeof(struct smp2p_entry_v1)); if (size < expected_size) { unsigned new_size; new_size = size; new_size -= sizeof(struct smp2p_smem); new_size /= sizeof(struct smp2p_entry_v1); in_item->safe_total_entries = new_size; SMP2P_ERR( "%s pid %d item too small for %d entries; expected: %d actual: %d; reduced to %d entries\n", __func__, remote_pid, total_entries, expected_size, size, new_size); } } else { /* * Total entries is 0, so the entry is still being initialized * or is invalid. Either way, treat it as if the item does * not exist yet. */ in_item->safe_total_entries = 0; in_item->item_size = 0; } return item_ptr; } /** * smp2p_negotiate_features_v0 - Initial feature negotiation. * * @features: Inbound feature set. * @returns: 0 (no features supported for v0). */ static uint32_t smp2p_negotiate_features_v0(uint32_t features) { /* no supported features */ return 0; } /** * smp2p_find_entry_v0 - Stub function. * * @item: Pointer to the smem item. * @entries_total: Total number of entries in @item. * @name: Name of the entry. * @entry_ptr: Set to pointer of entry if found, NULL otherwise. * @empty_spot: If non-null, set to the value of the next empty entry. * * Entries cannot be searched for until item negotiation has been completed. */ static void smp2p_find_entry_v0(struct smp2p_smem __iomem *item, uint32_t entries_total, char *name, uint32_t **entry_ptr, int *empty_spot) { if (entry_ptr) *entry_ptr = NULL; if (empty_spot) *empty_spot = -1; SMP2P_ERR("%s: invalid - item negotiation incomplete\n", __func__); } /** * smp2p_out_create_v0 - Initial creation function. * * @out_entry: Pointer to the SMP2P entry structure. * @returns: 0 on success, standard Linux error code otherwise. * * If the outbound SMEM item negotiation is not complete, then * this function is called to start the negotiation process. * Eventually when the negotiation process is complete, this * function pointer is switched with the appropriate function * for the version of SMP2P being created. * * Must be called with out_item_lock_lha1 locked. */ static int smp2p_out_create_v0(struct msm_smp2p_out *out_entry) { int edge_state; struct smp2p_out_list_item *item_ptr; if (!out_entry) return -EINVAL; edge_state = out_list[out_entry->remote_pid].smem_edge_state; switch (edge_state) { case SMP2P_EDGE_STATE_CLOSED: /* start negotiation */ item_ptr = &out_list[out_entry->remote_pid]; edge_state = smp2p_do_negotiation(out_entry->remote_pid, item_ptr); break; case SMP2P_EDGE_STATE_OPENING: /* still negotiating */ break; case SMP2P_EDGE_STATE_OPENED: SMP2P_ERR("%s: item '%s':%d opened - wrong create called\n", __func__, out_entry->name, out_entry->remote_pid); break; default: SMP2P_ERR("%s: item '%s':%d invalid SMEM item state %d\n", __func__, out_entry->name, out_entry->remote_pid, edge_state); break; } return 0; } /** * smp2p_out_read_v0 - Stub function. * * @out_entry: Pointer to the SMP2P entry structure. * @data: Out pointer, the data is available in this argument on success. * @returns: -ENODEV */ static int smp2p_out_read_v0(struct msm_smp2p_out *out_entry, uint32_t *data) { SMP2P_ERR("%s: item '%s':%d not OPEN\n", __func__, out_entry->name, out_entry->remote_pid); return -ENODEV; } /** * smp2p_out_write_v0 - Stub function. * * @out_entry: Pointer to the SMP2P entry structure. * @data: The data to be written. * @returns: -ENODEV */ static int smp2p_out_write_v0(struct msm_smp2p_out *out_entry, uint32_t data) { SMP2P_ERR("%s: item '%s':%d not yet OPEN\n", __func__, out_entry->name, out_entry->remote_pid); return -ENODEV; } /** * smp2p_out_modify_v0 - Stub function. * * @set_mask: Mask containing the bits that needs to be set. * @clear_mask: Mask containing the bits that needs to be cleared. * @returns: -ENODEV */ static int smp2p_out_modify_v0(struct msm_smp2p_out *out_entry, uint32_t set_mask, uint32_t clear_mask) { SMP2P_ERR("%s: item '%s':%d not yet OPEN\n", __func__, out_entry->name, out_entry->remote_pid); return -ENODEV; } /** * smp2p_in_validate_size_v0 - Stub function. * * @remote_pid: Remote processor ID. * @smem_item: Pointer to the inbound SMEM item. * @size: Size of the SMEM item. * @returns: Validated smem_item pointer (or NULL if size is too small). * * Validates we don't end up with out-of-bounds array access due to invalid * smem item size. If out-of-bound array access can't be avoided, then an * error message is printed and NULL is returned to prevent usage of the * item. * * Must be called with in_item_lock_lhb1 locked. */ static struct smp2p_smem __iomem *smp2p_in_validate_size_v0(int remote_pid, struct smp2p_smem __iomem *smem_item, uint32_t size) { struct smp2p_in_list_item *in_item; if (remote_pid >= SMP2P_NUM_PROCS || !smem_item) return NULL; in_item = &in_list[remote_pid]; if (size < sizeof(struct smp2p_smem)) { SMP2P_ERR( "%s pid %d item size too small; expected: %d actual: %d\n", __func__, remote_pid, sizeof(struct smp2p_smem), size); smem_item = NULL; in_item->item_size = 0; } else { in_item->item_size = size; } return smem_item; } /** * smp2p_init_header - Initializes the header of the smem item. * * @header_ptr: Pointer to the smp2p header. * @local_pid: Local processor ID. * @remote_pid: Remote processor ID. * @feature: Features of smp2p implementation. * @version: Version of smp2p implementation. * * Initializes the header as defined in the protocol specification. */ void smp2p_init_header(struct smp2p_smem __iomem *header_ptr, int local_pid, int remote_pid, uint32_t features, uint32_t version) { header_ptr->magic = SMP2P_MAGIC; SMP2P_SET_LOCAL_PID(header_ptr->rem_loc_proc_id, local_pid); SMP2P_SET_REMOTE_PID(header_ptr->rem_loc_proc_id, remote_pid); SMP2P_SET_FEATURES(header_ptr->feature_version, features); SMP2P_SET_ENT_TOTAL(header_ptr->valid_total_ent, SMP2P_MAX_ENTRY); SMP2P_SET_ENT_VALID(header_ptr->valid_total_ent, 0); header_ptr->reserved = 0; /* ensure that all fields are valid before version is written */ wmb(); SMP2P_SET_VERSION(header_ptr->feature_version, version); } /** * smp2p_do_negotiation - Implements negotiation algorithm. * * @remote_pid: Remote processor ID. * @out_item: Pointer to the outbound list item. * @returns: 0 on success, standard Linux error code otherwise. * * Must be called with out_item_lock_lha1 locked. Will internally lock * in_item_lock_lhb1. */ static int smp2p_do_negotiation(int remote_pid, struct smp2p_out_list_item *out_item) { struct smp2p_smem __iomem *r_smem_ptr; struct smp2p_smem __iomem *l_smem_ptr; uint32_t r_version; uint32_t r_feature; uint32_t l_version, l_feature; int prev_state; if (remote_pid >= SMP2P_NUM_PROCS || !out_item) return -EINVAL; if (out_item->smem_edge_state == SMP2P_EDGE_STATE_FAILED) return -EPERM; prev_state = out_item->smem_edge_state; /* create local item */ if (!out_item->smem_edge_out) { out_item->smem_edge_out = smp2p_get_local_smem_item(remote_pid); if (!out_item->smem_edge_out) { SMP2P_ERR( "%s unable to allocate SMEM item for pid %d\n", __func__, remote_pid); return -ENODEV; } out_item->smem_edge_state = SMP2P_EDGE_STATE_OPENING; } l_smem_ptr = out_item->smem_edge_out; /* retrieve remote side and version */ spin_lock(&in_list[remote_pid].in_item_lock_lhb1); r_smem_ptr = smp2p_get_remote_smem_item(remote_pid, out_item); spin_unlock(&in_list[remote_pid].in_item_lock_lhb1); r_version = 0; if (r_smem_ptr) { r_version = SMP2P_GET_VERSION(r_smem_ptr->feature_version); r_feature = SMP2P_GET_FEATURES(r_smem_ptr->feature_version); } if (r_version == 0) { /* * Either remote side doesn't exist, or is in the * process of being initialized (the version is set last). * * In either case, treat as if the other side doesn't exist * and write out our maximum supported version. */ r_smem_ptr = NULL; r_version = ARRAY_SIZE(version_if) - 1; r_feature = ~0U; } /* find maximum supported version and feature set */ l_version = min(r_version, ARRAY_SIZE(version_if) - 1); for (; l_version > 0; --l_version) { if (!version_if[l_version].is_supported) continue; /* found valid version */ l_feature = version_if[l_version].negotiate_features(~0U); if (l_version == r_version) l_feature &= r_feature; break; } if (l_version == 0) { SMP2P_ERR( "%s: negotiation failure pid %d: RV %d RF %x\n", __func__, remote_pid, r_version, r_feature ); SMP2P_SET_VERSION(l_smem_ptr->feature_version, SMP2P_EDGE_STATE_FAILED); smp2p_send_interrupt(remote_pid); out_item->smem_edge_state = SMP2P_EDGE_STATE_FAILED; return -EPERM; } /* update header and notify remote side */ smp2p_init_header(l_smem_ptr, SMP2P_APPS_PROC, remote_pid, l_feature, l_version); smp2p_send_interrupt(remote_pid); /* handle internal state changes */ if (r_smem_ptr && l_version == r_version && l_feature == r_feature) { struct msm_smp2p_out *pos; /* negotiation complete */ out_item->smem_edge_state = SMP2P_EDGE_STATE_OPENED; out_item->ops_ptr = &version_if[l_version]; SMP2P_INFO( "%s: negotiation complete pid %d: State %d->%d F0x%08x\n", __func__, remote_pid, prev_state, out_item->smem_edge_state, l_feature); /* create any pending outbound entries */ list_for_each_entry(pos, &out_item->list, out_edge_list) { out_item->ops_ptr->create_entry(pos); } /* update inbound edge */ spin_lock(&in_list[remote_pid].in_item_lock_lhb1); (void)out_item->ops_ptr->validate_size(remote_pid, r_smem_ptr, in_list[remote_pid].item_size); in_list[remote_pid].smem_edge_in = r_smem_ptr; spin_unlock(&in_list[remote_pid].in_item_lock_lhb1); } else { SMP2P_INFO("%s: negotiation pid %d: State %d->%d F0x%08x\n", __func__, remote_pid, prev_state, out_item->smem_edge_state, l_feature); } return 0; } /** * msm_smp2p_out_open - Opens an outbound entry. * * @remote_pid: Outbound processor ID. * @name: Name of the entry. * @open_notifier: Notifier block for the open notification. * @handle: Handle to the smem entry structure. * @returns: 0 on success, standard Linux error code otherwise. * * Opens an outbound entry with the name specified by entry, from the * local processor to the remote processor(remote_pid). If the entry, remote_pid * and open_notifier are valid, then handle will be set and zero will be * returned. The smem item that holds this entry will be created if it has * not been created according to the version negotiation algorithm. * The open_notifier will be used to notify the clients about the * availability of the entry. */ int msm_smp2p_out_open(int remote_pid, const char *name, struct notifier_block *open_notifier, struct msm_smp2p_out **handle) { struct msm_smp2p_out *out_entry; struct msm_smp2p_out *pos; int ret = 0; unsigned long flags; if (handle) *handle = NULL; if (remote_pid >= SMP2P_NUM_PROCS || !name || !open_notifier || !handle) return -EINVAL; /* Allocate the smp2p object and node */ out_entry = kzalloc(sizeof(*out_entry), GFP_KERNEL); if (!out_entry) return -ENOMEM; /* Handle duplicate registration */ spin_lock_irqsave(&out_list[remote_pid].out_item_lock_lha1, flags); list_for_each_entry(pos, &out_list[remote_pid].list, out_edge_list) { if (!strcmp(pos->name, name)) { spin_unlock_irqrestore( &out_list[remote_pid].out_item_lock_lha1, flags); kfree(out_entry); SMP2P_ERR("%s: duplicate registration '%s':%d\n", __func__, name, remote_pid); return -EBUSY; } } out_entry->remote_pid = remote_pid; RAW_INIT_NOTIFIER_HEAD(&out_entry->msm_smp2p_notifier_list); strlcpy(out_entry->name, name, SMP2P_MAX_ENTRY_NAME); out_entry->open_nb = open_notifier; raw_notifier_chain_register(&out_entry->msm_smp2p_notifier_list, out_entry->open_nb); list_add(&out_entry->out_edge_list, &out_list[remote_pid].list); ret = out_list[remote_pid].ops_ptr->create_entry(out_entry); if (ret) { list_del(&out_entry->out_edge_list); raw_notifier_chain_unregister( &out_entry->msm_smp2p_notifier_list, out_entry->open_nb); spin_unlock_irqrestore( &out_list[remote_pid].out_item_lock_lha1, flags); kfree(out_entry); SMP2P_ERR("%s: unable to open '%s':%d error %d\n", __func__, name, remote_pid, ret); return ret; } spin_unlock_irqrestore(&out_list[remote_pid].out_item_lock_lha1, flags); *handle = out_entry; return 0; } EXPORT_SYMBOL(msm_smp2p_out_open); /** * msm_smp2p_out_close - Closes the handle to an outbound entry. * * @handle: Pointer to smp2p out entry handle. * @returns: 0 on success, standard Linux error code otherwise. * * The actual entry will not be deleted and can be re-opened at a later * time. The handle will be set to NULL. */ int msm_smp2p_out_close(struct msm_smp2p_out **handle) { unsigned long flags; struct msm_smp2p_out *out_entry; struct smp2p_out_list_item *out_item; if (!handle || !*handle) return -EINVAL; out_entry = *handle; *handle = NULL; out_item = &out_list[out_entry->remote_pid]; spin_lock_irqsave(&out_item->out_item_lock_lha1, flags); list_del(&out_entry->out_edge_list); raw_notifier_chain_unregister(&out_entry->msm_smp2p_notifier_list, out_entry->open_nb); spin_unlock_irqrestore(&out_item->out_item_lock_lha1, flags); kfree(out_entry); return 0; } EXPORT_SYMBOL(msm_smp2p_out_close); /** * msm_smp2p_out_read - Allows reading the entry. * * @handle: Handle to the smem entry structure. * @data: Out pointer that holds the read data. * @returns: 0 on success, standard Linux error code otherwise. * * Allows reading of the outbound entry for read-modify-write * operation. */ int msm_smp2p_out_read(struct msm_smp2p_out *handle, uint32_t *data) { int ret = -EINVAL; unsigned long flags; struct smp2p_out_list_item *out_item; if (!handle || !data) return ret; out_item = &out_list[handle->remote_pid]; spin_lock_irqsave(&out_item->out_item_lock_lha1, flags); ret = out_item->ops_ptr->read_entry(handle, data); spin_unlock_irqrestore(&out_item->out_item_lock_lha1, flags); return ret; } EXPORT_SYMBOL(msm_smp2p_out_read); /** * msm_smp2p_out_write - Allows writing to the entry. * * @handle: Handle to smem entry structure. * @data: Data that has to be written. * @returns: 0 on success, standard Linux error code otherwise. * * Writes a new value to the output entry. Multiple back-to-back writes * may overwrite previous writes before the remote processor get a chance * to see them leading to ABA race condition. The client must implement * their own synchronization mechanism (such as echo mechanism) if this is * not acceptable. */ int msm_smp2p_out_write(struct msm_smp2p_out *handle, uint32_t data) { int ret = -EINVAL; unsigned long flags; struct smp2p_out_list_item *out_item; if (!handle) return ret; out_item = &out_list[handle->remote_pid]; spin_lock_irqsave(&out_item->out_item_lock_lha1, flags); ret = out_item->ops_ptr->write_entry(handle, data); spin_unlock_irqrestore(&out_item->out_item_lock_lha1, flags); return ret; } EXPORT_SYMBOL(msm_smp2p_out_write); /** * msm_smp2p_out_modify - Modifies the entry. * * @handle: Handle to the smem entry structure. * @set_mask: Specifies the bits that needs to be set. * @clear_mask: Specifies the bits that needs to be cleared. * @returns: 0 on success, standard Linux error code otherwise. * * The modification is done by doing a bitwise AND of clear mask followed by * the bit wise OR of set mask. The clear bit mask is applied first to the * data, so if a bit is set in both the clear mask and the set mask, then in * the result is a set bit. Multiple back-to-back modifications may overwrite * previous values before the remote processor gets a chance to see them * leading to ABA race condition. The client must implement their own * synchronization mechanism (such as echo mechanism) if this is not * acceptable. */ int msm_smp2p_out_modify(struct msm_smp2p_out *handle, uint32_t set_mask, uint32_t clear_mask) { int ret = -EINVAL; unsigned long flags; struct smp2p_out_list_item *out_item; if (!handle) return ret; out_item = &out_list[handle->remote_pid]; spin_lock_irqsave(&out_item->out_item_lock_lha1, flags); ret = out_item->ops_ptr->modify_entry(handle, set_mask, clear_mask); spin_unlock_irqrestore(&out_item->out_item_lock_lha1, flags); return ret; } EXPORT_SYMBOL(msm_smp2p_out_modify); /** * msm_smp2p_in_read - Read an entry on a remote processor. * * @remote_pid: Processor ID of the remote processor. * @name: Name of the entry that is to be read. * @data: Output pointer, the value will be placed here if successful. * @returns: 0 on success, standard Linux error code otherwise. */ int msm_smp2p_in_read(int remote_pid, const char *name, uint32_t *data) { unsigned long flags; struct smp2p_out_list_item *out_item; uint32_t *entry_ptr; if (remote_pid >= SMP2P_NUM_PROCS) return -EINVAL; out_item = &out_list[remote_pid]; spin_lock_irqsave(&out_item->out_item_lock_lha1, flags); spin_lock(&in_list[remote_pid].in_item_lock_lhb1); if (in_list[remote_pid].smem_edge_in) out_item->ops_ptr->find_entry( in_list[remote_pid].smem_edge_in, in_list[remote_pid].safe_total_entries, (char *)name, &entry_ptr, NULL); spin_unlock(&in_list[remote_pid].in_item_lock_lhb1); spin_unlock_irqrestore(&out_item->out_item_lock_lha1, flags); if (!entry_ptr) return -ENODEV; *data = readl_relaxed(entry_ptr); return 0; } EXPORT_SYMBOL(msm_smp2p_in_read); /** * msm_smp2p_in_register - Notifies the change in value of the entry. * * @pid: Remote processor ID. * @name: Name of the entry. * @in_notifier: Notifier block used to notify about the event. * @returns: 0 on success, standard Linux error code otherwise. * * Register for change notifications for a remote entry. If the remote entry * does not exist yet, then the registration request will be held until the * remote side opens. Once the entry is open, then the SMP2P_OPEN notification * will be sent. Any changes to the entry will trigger a call to the notifier * block with an SMP2P_ENTRY_UPDATE event and the data field will point to an * msm_smp2p_update_notif structure containing the current and previous value. */ int msm_smp2p_in_register(int pid, const char *name, struct notifier_block *in_notifier) { struct smp2p_in *pos; struct smp2p_in *in = NULL; int ret; unsigned long flags; struct msm_smp2p_update_notif data; uint32_t *entry_ptr; if (pid >= SMP2P_NUM_PROCS || !name || !in_notifier) return -EINVAL; /* Pre-allocate before spinlock since we will likely needed it */ in = kzalloc(sizeof(*in), GFP_KERNEL); if (!in) return -ENOMEM; /* Search for existing entry */ spin_lock_irqsave(&out_list[pid].out_item_lock_lha1, flags); spin_lock(&in_list[pid].in_item_lock_lhb1); list_for_each_entry(pos, &in_list[pid].list, in_edge_list) { if (!strncmp(pos->name, name, SMP2P_MAX_ENTRY_NAME)) { kfree(in); in = pos; break; } } /* Create and add it to the list */ if (!in->notifier_count) { in->remote_pid = pid; strlcpy(in->name, name, SMP2P_MAX_ENTRY_NAME); RAW_INIT_NOTIFIER_HEAD(&in->in_notifier_list); list_add(&in->in_edge_list, &in_list[pid].list); } ret = raw_notifier_chain_register(&in->in_notifier_list, in_notifier); if (ret) { if (!in->notifier_count) { list_del(&in->in_edge_list); kfree(in); } SMP2P_DBG("%s: '%s':%d failed %d\n", __func__, name, pid, ret); goto bail; } in->notifier_count++; if (out_list[pid].smem_edge_state == SMP2P_EDGE_STATE_OPENED) { out_list[pid].ops_ptr->find_entry( in_list[pid].smem_edge_in, in_list[pid].safe_total_entries, (char *)name, &entry_ptr, NULL); if (entry_ptr) { in->entry_ptr = entry_ptr; in->prev_entry_val = readl_relaxed(entry_ptr); data.previous_value = in->prev_entry_val; data.current_value = in->prev_entry_val; in_notifier->notifier_call(in_notifier, SMP2P_OPEN, (void *)&data); } } SMP2P_DBG("%s: '%s':%d registered\n", __func__, name, pid); bail: spin_unlock(&in_list[pid].in_item_lock_lhb1); spin_unlock_irqrestore(&out_list[pid].out_item_lock_lha1, flags); return ret; } EXPORT_SYMBOL(msm_smp2p_in_register); /** * msm_smp2p_in_unregister - Unregister the notifier for remote entry. * * @remote_pid: Processor Id of the remote processor. * @name: The name of the entry. * @in_notifier: Notifier block passed during registration. * @returns: 0 on success, standard Linux error code otherwise. */ int msm_smp2p_in_unregister(int remote_pid, const char *name, struct notifier_block *in_notifier) { struct smp2p_in *pos; struct smp2p_in *in = NULL; int ret = -ENODEV; unsigned long flags; if (remote_pid >= SMP2P_NUM_PROCS || !name || !in_notifier) return -EINVAL; spin_lock_irqsave(&in_list[remote_pid].in_item_lock_lhb1, flags); list_for_each_entry(pos, &in_list[remote_pid].list, in_edge_list) { if (!strncmp(pos->name, name, SMP2P_MAX_ENTRY_NAME)) { in = pos; break; } } if (!in) goto fail; ret = raw_notifier_chain_unregister(&pos->in_notifier_list, in_notifier); if (ret == 0) { pos->notifier_count--; if (!pos->notifier_count) { list_del(&pos->in_edge_list); kfree(pos); ret = 0; } } else { SMP2P_ERR("%s: unregister failure '%s':%d\n", __func__, name, remote_pid); ret = -ENODEV; } fail: spin_unlock_irqrestore(&in_list[remote_pid].in_item_lock_lhb1, flags); return ret; } EXPORT_SYMBOL(msm_smp2p_in_unregister); /** * smp2p_send_interrupt - Send interrupt to remote system. * * @remote_pid: Processor ID of the remote system * * Must be called with out_item_lock_lha1 locked. */ static void smp2p_send_interrupt(int remote_pid) { if (smp2p_int_cfgs[remote_pid].name) SMP2P_DBG("SMP2P Int Apps->%s(%d)\n", smp2p_int_cfgs[remote_pid].name, remote_pid); ++smp2p_int_cfgs[remote_pid].out_interrupt_count; if (remote_pid != SMP2P_REMOTE_MOCK_PROC && smp2p_int_cfgs[remote_pid].out_int_mask) { /* flush any pending writes before triggering interrupt */ wmb(); writel_relaxed(smp2p_int_cfgs[remote_pid].out_int_mask, smp2p_int_cfgs[remote_pid].out_int_ptr); } else { smp2p_remote_mock_rx_interrupt(); } } /** * smp2p_in_edge_notify - Notifies the entry changed on remote processor. * * @pid: Processor ID of the remote processor. * * This function is invoked on an incoming interrupt, it scans * the list of the clients registered for the entries on the remote * processor and notifies them if the data changes. * * Note: Edge state must be OPENED to avoid a race condition with * out_list[pid].ops_ptr->find_entry. */ static void smp2p_in_edge_notify(int pid) { struct smp2p_in *pos; uint32_t *entry_ptr; unsigned long flags; struct smp2p_smem __iomem *smem_h_ptr; uint32_t curr_data; struct msm_smp2p_update_notif data; spin_lock_irqsave(&in_list[pid].in_item_lock_lhb1, flags); smem_h_ptr = in_list[pid].smem_edge_in; if (!smem_h_ptr) { SMP2P_DBG("%s: No remote SMEM item for pid %d\n", __func__, pid); spin_unlock_irqrestore(&in_list[pid].in_item_lock_lhb1, flags); return; } list_for_each_entry(pos, &in_list[pid].list, in_edge_list) { if (pos->entry_ptr == NULL) { /* entry not open - try to open it */ out_list[pid].ops_ptr->find_entry(smem_h_ptr, in_list[pid].safe_total_entries, pos->name, &entry_ptr, NULL); if (entry_ptr) { pos->entry_ptr = entry_ptr; pos->prev_entry_val = 0; data.previous_value = 0; data.current_value = readl_relaxed(entry_ptr); raw_notifier_call_chain( &pos->in_notifier_list, SMP2P_OPEN, (void *)&data); } } if (pos->entry_ptr != NULL) { /* send update notification */ curr_data = readl_relaxed(pos->entry_ptr); if (curr_data != pos->prev_entry_val) { data.previous_value = pos->prev_entry_val; data.current_value = curr_data; pos->prev_entry_val = curr_data; raw_notifier_call_chain( &pos->in_notifier_list, SMP2P_ENTRY_UPDATE, (void *)&data); } } } spin_unlock_irqrestore(&in_list[pid].in_item_lock_lhb1, flags); } /** * smp2p_interrupt_handler - Incoming interrupt handler. * * @irq: Interrupt ID * @data: Edge * @returns: IRQ_HANDLED or IRQ_NONE for invalid interrupt */ static irqreturn_t smp2p_interrupt_handler(int irq, void *data) { unsigned long flags; uint32_t remote_pid = (uint32_t)data; if (remote_pid >= SMP2P_NUM_PROCS) { SMP2P_ERR("%s: invalid interrupt pid %d\n", __func__, remote_pid); return IRQ_NONE; } if (smp2p_int_cfgs[remote_pid].name) SMP2P_DBG("SMP2P Int %s(%d)->Apps\n", smp2p_int_cfgs[remote_pid].name, remote_pid); spin_lock_irqsave(&out_list[remote_pid].out_item_lock_lha1, flags); ++smp2p_int_cfgs[remote_pid].in_interrupt_count; if (out_list[remote_pid].smem_edge_state != SMP2P_EDGE_STATE_OPENED) smp2p_do_negotiation(remote_pid, &out_list[remote_pid]); if (out_list[remote_pid].smem_edge_state == SMP2P_EDGE_STATE_OPENED) { spin_unlock_irqrestore(&out_list[remote_pid].out_item_lock_lha1, flags); smp2p_in_edge_notify(remote_pid); } else { spin_unlock_irqrestore(&out_list[remote_pid].out_item_lock_lha1, flags); } return IRQ_HANDLED; } /** * smp2p_reset_mock_edge - Reinitializes the mock edge. * * @returns: 0 on success, -EAGAIN to retry later. * * Reinitializes the mock edge to initial power-up state values. */ int smp2p_reset_mock_edge(void) { const int rpid = SMP2P_REMOTE_MOCK_PROC; unsigned long flags; int ret = 0; spin_lock_irqsave(&out_list[rpid].out_item_lock_lha1, flags); spin_lock(&in_list[rpid].in_item_lock_lhb1); if (!list_empty(&out_list[rpid].list) || !list_empty(&in_list[rpid].list)) { ret = -EAGAIN; goto fail; } kfree(out_list[rpid].smem_edge_out); out_list[rpid].smem_edge_out = NULL; out_list[rpid].ops_ptr = &version_if[0]; out_list[rpid].smem_edge_state = SMP2P_EDGE_STATE_CLOSED; in_list[rpid].smem_edge_in = NULL; in_list[rpid].item_size = 0; in_list[rpid].safe_total_entries = 0; fail: spin_unlock(&in_list[rpid].in_item_lock_lhb1); spin_unlock_irqrestore(&out_list[rpid].out_item_lock_lha1, flags); return ret; } /** * msm_smp2p_interrupt_handler - Triggers incoming interrupt. * * @remote_pid: Remote processor ID * * This function is used with the remote mock infrastructure * used for testing. It simulates triggering of interrupt in * a testing environment. */ void msm_smp2p_interrupt_handler(int remote_pid) { smp2p_interrupt_handler(0, (void *)remote_pid); } /** * msm_smp2p_probe - Device tree probe function. * * @pdev: Pointer to device tree data. * @returns: 0 on success; -ENODEV otherwise */ static int __devinit msm_smp2p_probe(struct platform_device *pdev) { struct resource *r; void *irq_out_ptr = NULL; char *key; uint32_t edge; int ret; struct device_node *node; uint32_t irq_bitmask; uint32_t irq_line; node = pdev->dev.of_node; key = "qcom,remote-pid"; ret = of_property_read_u32(node, key, &edge); if (ret) { SMP2P_ERR("%s: missing edge '%s'\n", __func__, key); goto fail; } r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!r) { SMP2P_ERR("%s: failed gathering irq-reg resource for edge %d\n" , __func__, edge); goto fail; } irq_out_ptr = ioremap_nocache(r->start, resource_size(r)); if (!irq_out_ptr) { SMP2P_ERR("%s: failed remap from phys to virt for edge %d\n", __func__, edge); return -ENOMEM; } key = "qcom,irq-bitmask"; ret = of_property_read_u32(node, key, &irq_bitmask); if (ret) goto missing_key; key = "interrupts"; irq_line = platform_get_irq(pdev, 0); if (irq_line == -ENXIO) goto missing_key; ret = request_irq(irq_line, smp2p_interrupt_handler, IRQF_TRIGGER_RISING, "smp2p", (void *)edge); if (ret < 0) { SMP2P_ERR("%s: request_irq() failed on %d (edge %d)\n", __func__, irq_line, edge); goto fail; } ret = enable_irq_wake(irq_line); if (ret < 0) SMP2P_ERR("%s: enable_irq_wake() failed on %d (edge %d)\n", __func__, irq_line, edge); /* * Set entry (keep is_configured last to prevent usage before * initialization). */ smp2p_int_cfgs[edge].in_int_id = irq_line; smp2p_int_cfgs[edge].out_int_mask = irq_bitmask; smp2p_int_cfgs[edge].out_int_ptr = irq_out_ptr; smp2p_int_cfgs[edge].is_configured = true; return 0; missing_key: SMP2P_ERR("%s: missing '%s' for edge %d\n", __func__, key, edge); fail: if (irq_out_ptr) iounmap(irq_out_ptr); return -ENODEV; } static struct of_device_id msm_smp2p_match_table[] = { { .compatible = "qcom,smp2p" }, {}, }; static struct platform_driver msm_smp2p_driver = { .probe = msm_smp2p_probe, .driver = { .name = "msm_smp2p", .owner = THIS_MODULE, .of_match_table = msm_smp2p_match_table, }, }; /** * msm_smp2p_init - Initialization function for the module. * * @returns: 0 on success, standard Linux error code otherwise. */ static int __init msm_smp2p_init(void) { int i; int rc; for (i = 0; i < SMP2P_NUM_PROCS; i++) { spin_lock_init(&out_list[i].out_item_lock_lha1); INIT_LIST_HEAD(&out_list[i].list); out_list[i].smem_edge_out = NULL; out_list[i].smem_edge_state = SMP2P_EDGE_STATE_CLOSED; out_list[i].ops_ptr = &version_if[0]; spin_lock_init(&in_list[i].in_item_lock_lhb1); INIT_LIST_HEAD(&in_list[i].list); in_list[i].smem_edge_in = NULL; } log_ctx = ipc_log_context_create(NUM_LOG_PAGES, "smp2p"); if (!log_ctx) SMP2P_ERR("%s: unable to create log context\n", __func__); rc = platform_driver_register(&msm_smp2p_driver); if (rc) { SMP2P_ERR("%s: msm_smp2p_driver register failed %d\n", __func__, rc); return rc; } return 0; } module_init(msm_smp2p_init); MODULE_DESCRIPTION("MSM Shared Memory Point to Point"); MODULE_LICENSE("GPL v2");
gpl-2.0
BPI-SINOVOIP/BPI-Mainline-kernel
linux-4.19/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
50329
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * Copyright(c) 2013 - 2014 Intel Mobile Communications GmbH * Copyright(c) 2015 - 2017 Intel Deutschland GmbH * * 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. * * 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, * USA * * The full GNU General Public License is included in this distribution * in the file called COPYING. * * Contact Information: * Intel Linux Wireless <[email protected]> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * Copyright(c) 2013 - 2014 Intel Mobile Communications GmbH * Copyright(c) 2015 - 2017 Intel Deutschland GmbH * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include <linux/etherdevice.h> #include <net/mac80211.h> #include "iwl-io.h" #include "iwl-prph.h" #include "fw-api.h" #include "mvm.h" #include "time-event.h" const u8 iwl_mvm_ac_to_tx_fifo[] = { IWL_MVM_TX_FIFO_VO, IWL_MVM_TX_FIFO_VI, IWL_MVM_TX_FIFO_BE, IWL_MVM_TX_FIFO_BK, }; const u8 iwl_mvm_ac_to_gen2_tx_fifo[] = { IWL_GEN2_EDCA_TX_FIFO_VO, IWL_GEN2_EDCA_TX_FIFO_VI, IWL_GEN2_EDCA_TX_FIFO_BE, IWL_GEN2_EDCA_TX_FIFO_BK, }; struct iwl_mvm_mac_iface_iterator_data { struct iwl_mvm *mvm; struct ieee80211_vif *vif; unsigned long available_mac_ids[BITS_TO_LONGS(NUM_MAC_INDEX_DRIVER)]; unsigned long available_tsf_ids[BITS_TO_LONGS(NUM_TSF_IDS)]; enum iwl_tsf_id preferred_tsf; bool found_vif; }; struct iwl_mvm_hw_queues_iface_iterator_data { struct ieee80211_vif *exclude_vif; unsigned long used_hw_queues; }; static void iwl_mvm_mac_tsf_id_iter(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_mvm_mac_iface_iterator_data *data = _data; struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); u16 min_bi; /* Skip the interface for which we are trying to assign a tsf_id */ if (vif == data->vif) return; /* * The TSF is a hardware/firmware resource, there are 4 and * the driver should assign and free them as needed. However, * there are cases where 2 MACs should share the same TSF ID * for the purpose of clock sync, an optimization to avoid * clock drift causing overlapping TBTTs/DTIMs for a GO and * client in the system. * * The firmware will decide according to the MAC type which * will be the master and slave. Clients that need to sync * with a remote station will be the master, and an AP or GO * will be the slave. * * Depending on the new interface type it can be slaved to * or become the master of an existing interface. */ switch (data->vif->type) { case NL80211_IFTYPE_STATION: /* * The new interface is a client, so if the one we're iterating * is an AP, and the beacon interval of the AP is a multiple or * divisor of the beacon interval of the client, the same TSF * should be used to avoid drift between the new client and * existing AP. The existing AP will get drift updates from the * new client context in this case. */ if (vif->type != NL80211_IFTYPE_AP || data->preferred_tsf != NUM_TSF_IDS || !test_bit(mvmvif->tsf_id, data->available_tsf_ids)) break; min_bi = min(data->vif->bss_conf.beacon_int, vif->bss_conf.beacon_int); if (!min_bi) break; if ((data->vif->bss_conf.beacon_int - vif->bss_conf.beacon_int) % min_bi == 0) { data->preferred_tsf = mvmvif->tsf_id; return; } break; case NL80211_IFTYPE_AP: /* * The new interface is AP/GO, so if its beacon interval is a * multiple or a divisor of the beacon interval of an existing * interface, it should get drift updates from an existing * client or use the same TSF as an existing GO. There's no * drift between TSFs internally but if they used different * TSFs then a new client MAC could update one of them and * cause drift that way. */ if ((vif->type != NL80211_IFTYPE_AP && vif->type != NL80211_IFTYPE_STATION) || data->preferred_tsf != NUM_TSF_IDS || !test_bit(mvmvif->tsf_id, data->available_tsf_ids)) break; min_bi = min(data->vif->bss_conf.beacon_int, vif->bss_conf.beacon_int); if (!min_bi) break; if ((data->vif->bss_conf.beacon_int - vif->bss_conf.beacon_int) % min_bi == 0) { data->preferred_tsf = mvmvif->tsf_id; return; } break; default: /* * For all other interface types there's no need to * take drift into account. Either they're exclusive * like IBSS and monitor, or we don't care much about * their TSF (like P2P Device), but we won't be able * to share the TSF resource. */ break; } /* * Unless we exited above, we can't share the TSF resource * that the virtual interface we're iterating over is using * with the new one, so clear the available bit and if this * was the preferred one, reset that as well. */ __clear_bit(mvmvif->tsf_id, data->available_tsf_ids); if (data->preferred_tsf == mvmvif->tsf_id) data->preferred_tsf = NUM_TSF_IDS; } /* * Get the mask of the queues used by the vif */ u32 iwl_mvm_mac_get_queues_mask(struct ieee80211_vif *vif) { u32 qmask = 0, ac; if (vif->type == NL80211_IFTYPE_P2P_DEVICE) return BIT(IWL_MVM_OFFCHANNEL_QUEUE); for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { if (vif->hw_queue[ac] != IEEE80211_INVAL_HW_QUEUE) qmask |= BIT(vif->hw_queue[ac]); } if (vif->type == NL80211_IFTYPE_AP || vif->type == NL80211_IFTYPE_ADHOC) qmask |= BIT(vif->cab_queue); return qmask; } static void iwl_mvm_iface_hw_queues_iter(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_mvm_hw_queues_iface_iterator_data *data = _data; /* exclude the given vif */ if (vif == data->exclude_vif) return; data->used_hw_queues |= iwl_mvm_mac_get_queues_mask(vif); } unsigned long iwl_mvm_get_used_hw_queues(struct iwl_mvm *mvm, struct ieee80211_vif *exclude_vif) { struct iwl_mvm_hw_queues_iface_iterator_data data = { .exclude_vif = exclude_vif, .used_hw_queues = BIT(IWL_MVM_OFFCHANNEL_QUEUE) | BIT(mvm->aux_queue) | BIT(IWL_MVM_DQA_GCAST_QUEUE), }; lockdep_assert_held(&mvm->mutex); /* mark all VIF used hw queues */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_RESUME_ALL, iwl_mvm_iface_hw_queues_iter, &data); return data.used_hw_queues; } static void iwl_mvm_mac_iface_iterator(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_mvm_mac_iface_iterator_data *data = _data; struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); /* Iterator may already find the interface being added -- skip it */ if (vif == data->vif) { data->found_vif = true; return; } /* Mark MAC IDs as used by clearing the available bit, and * (below) mark TSFs as used if their existing use is not * compatible with the new interface type. * No locking or atomic bit operations are needed since the * data is on the stack of the caller function. */ __clear_bit(mvmvif->id, data->available_mac_ids); /* find a suitable tsf_id */ iwl_mvm_mac_tsf_id_iter(_data, mac, vif); } void iwl_mvm_mac_ctxt_recalc_tsf_id(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mvm_mac_iface_iterator_data data = { .mvm = mvm, .vif = vif, .available_tsf_ids = { (1 << NUM_TSF_IDS) - 1 }, /* no preference yet */ .preferred_tsf = NUM_TSF_IDS, }; ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_RESUME_ALL, iwl_mvm_mac_tsf_id_iter, &data); if (data.preferred_tsf != NUM_TSF_IDS) mvmvif->tsf_id = data.preferred_tsf; else if (!test_bit(mvmvif->tsf_id, data.available_tsf_ids)) mvmvif->tsf_id = find_first_bit(data.available_tsf_ids, NUM_TSF_IDS); } int iwl_mvm_mac_ctxt_init(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mvm_mac_iface_iterator_data data = { .mvm = mvm, .vif = vif, .available_mac_ids = { (1 << NUM_MAC_INDEX_DRIVER) - 1 }, .available_tsf_ids = { (1 << NUM_TSF_IDS) - 1 }, /* no preference yet */ .preferred_tsf = NUM_TSF_IDS, .found_vif = false, }; u32 ac; int ret, i, queue_limit; unsigned long used_hw_queues; lockdep_assert_held(&mvm->mutex); /* * Allocate a MAC ID and a TSF for this MAC, along with the queues * and other resources. */ /* * Before the iterator, we start with all MAC IDs and TSFs available. * * During iteration, all MAC IDs are cleared that are in use by other * virtual interfaces, and all TSF IDs are cleared that can't be used * by this new virtual interface because they're used by an interface * that can't share it with the new one. * At the same time, we check if there's a preferred TSF in the case * that we should share it with another interface. */ /* Currently, MAC ID 0 should be used only for the managed/IBSS vif */ switch (vif->type) { case NL80211_IFTYPE_ADHOC: break; case NL80211_IFTYPE_STATION: if (!vif->p2p) break; /* fall through */ default: __clear_bit(0, data.available_mac_ids); } ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_RESUME_ALL, iwl_mvm_mac_iface_iterator, &data); used_hw_queues = iwl_mvm_get_used_hw_queues(mvm, vif); /* * In the case we're getting here during resume, it's similar to * firmware restart, and with RESUME_ALL the iterator will find * the vif being added already. * We don't want to reassign any IDs in either case since doing * so would probably assign different IDs (as interfaces aren't * necessarily added in the same order), but the old IDs were * preserved anyway, so skip ID assignment for both resume and * recovery. */ if (data.found_vif) return 0; /* Therefore, in recovery, we can't get here */ if (WARN_ON_ONCE(test_bit(IWL_MVM_STATUS_IN_HW_RESTART, &mvm->status))) return -EBUSY; mvmvif->id = find_first_bit(data.available_mac_ids, NUM_MAC_INDEX_DRIVER); if (mvmvif->id == NUM_MAC_INDEX_DRIVER) { IWL_ERR(mvm, "Failed to init MAC context - no free ID!\n"); ret = -EIO; goto exit_fail; } if (data.preferred_tsf != NUM_TSF_IDS) mvmvif->tsf_id = data.preferred_tsf; else mvmvif->tsf_id = find_first_bit(data.available_tsf_ids, NUM_TSF_IDS); if (mvmvif->tsf_id == NUM_TSF_IDS) { IWL_ERR(mvm, "Failed to init MAC context - no free TSF!\n"); ret = -EIO; goto exit_fail; } mvmvif->color = 0; INIT_LIST_HEAD(&mvmvif->time_event_data.list); mvmvif->time_event_data.id = TE_MAX; /* No need to allocate data queues to P2P Device MAC.*/ if (vif->type == NL80211_IFTYPE_P2P_DEVICE) { for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) vif->hw_queue[ac] = IEEE80211_INVAL_HW_QUEUE; return 0; } /* * queues in mac80211 almost entirely independent of * the ones here - no real limit */ queue_limit = IEEE80211_MAX_QUEUES; BUILD_BUG_ON(IEEE80211_MAX_QUEUES > BITS_PER_BYTE * sizeof(mvm->hw_queue_to_mac80211[0])); /* * Find available queues, and allocate them to the ACs. When in * DQA-mode they aren't really used, and this is done only so the * mac80211 ieee80211_check_queues() function won't fail */ for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { u8 queue = find_first_zero_bit(&used_hw_queues, queue_limit); if (queue >= queue_limit) { IWL_ERR(mvm, "Failed to allocate queue\n"); ret = -EIO; goto exit_fail; } __set_bit(queue, &used_hw_queues); vif->hw_queue[ac] = queue; } /* Allocate the CAB queue for softAP and GO interfaces */ if (vif->type == NL80211_IFTYPE_AP || vif->type == NL80211_IFTYPE_ADHOC) { /* * For TVQM this will be overwritten later with the FW assigned * queue value (when queue is enabled). */ mvmvif->cab_queue = IWL_MVM_DQA_GCAST_QUEUE; vif->cab_queue = IWL_MVM_DQA_GCAST_QUEUE; } else { vif->cab_queue = IEEE80211_INVAL_HW_QUEUE; } mvmvif->bcast_sta.sta_id = IWL_MVM_INVALID_STA; mvmvif->mcast_sta.sta_id = IWL_MVM_INVALID_STA; mvmvif->ap_sta_id = IWL_MVM_INVALID_STA; for (i = 0; i < NUM_IWL_MVM_SMPS_REQ; i++) mvmvif->smps_requests[i] = IEEE80211_SMPS_AUTOMATIC; return 0; exit_fail: memset(mvmvif, 0, sizeof(struct iwl_mvm_vif)); memset(vif->hw_queue, IEEE80211_INVAL_HW_QUEUE, sizeof(vif->hw_queue)); vif->cab_queue = IEEE80211_INVAL_HW_QUEUE; return ret; } static void iwl_mvm_ack_rates(struct iwl_mvm *mvm, struct ieee80211_vif *vif, enum nl80211_band band, u8 *cck_rates, u8 *ofdm_rates) { struct ieee80211_supported_band *sband; unsigned long basic = vif->bss_conf.basic_rates; int lowest_present_ofdm = 100; int lowest_present_cck = 100; u8 cck = 0; u8 ofdm = 0; int i; sband = mvm->hw->wiphy->bands[band]; for_each_set_bit(i, &basic, BITS_PER_LONG) { int hw = sband->bitrates[i].hw_value; if (hw >= IWL_FIRST_OFDM_RATE) { ofdm |= BIT(hw - IWL_FIRST_OFDM_RATE); if (lowest_present_ofdm > hw) lowest_present_ofdm = hw; } else { BUILD_BUG_ON(IWL_FIRST_CCK_RATE != 0); cck |= BIT(hw); if (lowest_present_cck > hw) lowest_present_cck = hw; } } /* * Now we've got the basic rates as bitmaps in the ofdm and cck * variables. This isn't sufficient though, as there might not * be all the right rates in the bitmap. E.g. if the only basic * rates are 5.5 Mbps and 11 Mbps, we still need to add 1 Mbps * and 6 Mbps because the 802.11-2007 standard says in 9.6: * * [...] a STA responding to a received frame shall transmit * its Control Response frame [...] at the highest rate in the * BSSBasicRateSet parameter that is less than or equal to the * rate of the immediately previous frame in the frame exchange * sequence ([...]) and that is of the same modulation class * ([...]) as the received frame. If no rate contained in the * BSSBasicRateSet parameter meets these conditions, then the * control frame sent in response to a received frame shall be * transmitted at the highest mandatory rate of the PHY that is * less than or equal to the rate of the received frame, and * that is of the same modulation class as the received frame. * * As a consequence, we need to add all mandatory rates that are * lower than all of the basic rates to these bitmaps. */ if (IWL_RATE_24M_INDEX < lowest_present_ofdm) ofdm |= IWL_RATE_BIT_MSK(24) >> IWL_FIRST_OFDM_RATE; if (IWL_RATE_12M_INDEX < lowest_present_ofdm) ofdm |= IWL_RATE_BIT_MSK(12) >> IWL_FIRST_OFDM_RATE; /* 6M already there or needed so always add */ ofdm |= IWL_RATE_BIT_MSK(6) >> IWL_FIRST_OFDM_RATE; /* * CCK is a bit more complex with DSSS vs. HR/DSSS vs. ERP. * Note, however: * - if no CCK rates are basic, it must be ERP since there must * be some basic rates at all, so they're OFDM => ERP PHY * (or we're in 5 GHz, and the cck bitmap will never be used) * - if 11M is a basic rate, it must be ERP as well, so add 5.5M * - if 5.5M is basic, 1M and 2M are mandatory * - if 2M is basic, 1M is mandatory * - if 1M is basic, that's the only valid ACK rate. * As a consequence, it's not as complicated as it sounds, just add * any lower rates to the ACK rate bitmap. */ if (IWL_RATE_11M_INDEX < lowest_present_cck) cck |= IWL_RATE_BIT_MSK(11) >> IWL_FIRST_CCK_RATE; if (IWL_RATE_5M_INDEX < lowest_present_cck) cck |= IWL_RATE_BIT_MSK(5) >> IWL_FIRST_CCK_RATE; if (IWL_RATE_2M_INDEX < lowest_present_cck) cck |= IWL_RATE_BIT_MSK(2) >> IWL_FIRST_CCK_RATE; /* 1M already there or needed so always add */ cck |= IWL_RATE_BIT_MSK(1) >> IWL_FIRST_CCK_RATE; *cck_rates = cck; *ofdm_rates = ofdm; } static void iwl_mvm_mac_ctxt_set_ht_flags(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_mac_ctx_cmd *cmd) { /* for both sta and ap, ht_operation_mode hold the protection_mode */ u8 protection_mode = vif->bss_conf.ht_operation_mode & IEEE80211_HT_OP_MODE_PROTECTION; /* The fw does not distinguish between ht and fat */ u32 ht_flag = MAC_PROT_FLG_HT_PROT | MAC_PROT_FLG_FAT_PROT; IWL_DEBUG_RATE(mvm, "protection mode set to %d\n", protection_mode); /* * See section 9.23.3.1 of IEEE 80211-2012. * Nongreenfield HT STAs Present is not supported. */ switch (protection_mode) { case IEEE80211_HT_OP_MODE_PROTECTION_NONE: break; case IEEE80211_HT_OP_MODE_PROTECTION_NONMEMBER: case IEEE80211_HT_OP_MODE_PROTECTION_NONHT_MIXED: cmd->protection_flags |= cpu_to_le32(ht_flag); break; case IEEE80211_HT_OP_MODE_PROTECTION_20MHZ: /* Protect when channel wider than 20MHz */ if (vif->bss_conf.chandef.width > NL80211_CHAN_WIDTH_20) cmd->protection_flags |= cpu_to_le32(ht_flag); break; default: IWL_ERR(mvm, "Illegal protection mode %d\n", protection_mode); break; } } static void iwl_mvm_mac_ctxt_cmd_common(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_mac_ctx_cmd *cmd, const u8 *bssid_override, u32 action) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct ieee80211_chanctx_conf *chanctx; bool ht_enabled = !!(vif->bss_conf.ht_operation_mode & IEEE80211_HT_OP_MODE_PROTECTION); u8 cck_ack_rates, ofdm_ack_rates; const u8 *bssid = bssid_override ?: vif->bss_conf.bssid; int i; cmd->id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)); cmd->action = cpu_to_le32(action); switch (vif->type) { case NL80211_IFTYPE_STATION: if (vif->p2p) cmd->mac_type = cpu_to_le32(FW_MAC_TYPE_P2P_STA); else cmd->mac_type = cpu_to_le32(FW_MAC_TYPE_BSS_STA); break; case NL80211_IFTYPE_AP: cmd->mac_type = cpu_to_le32(FW_MAC_TYPE_GO); break; case NL80211_IFTYPE_MONITOR: cmd->mac_type = cpu_to_le32(FW_MAC_TYPE_LISTENER); break; case NL80211_IFTYPE_P2P_DEVICE: cmd->mac_type = cpu_to_le32(FW_MAC_TYPE_P2P_DEVICE); break; case NL80211_IFTYPE_ADHOC: cmd->mac_type = cpu_to_le32(FW_MAC_TYPE_IBSS); break; default: WARN_ON_ONCE(1); } cmd->tsf_id = cpu_to_le32(mvmvif->tsf_id); memcpy(cmd->node_addr, vif->addr, ETH_ALEN); if (bssid) memcpy(cmd->bssid_addr, bssid, ETH_ALEN); else eth_broadcast_addr(cmd->bssid_addr); rcu_read_lock(); chanctx = rcu_dereference(vif->chanctx_conf); iwl_mvm_ack_rates(mvm, vif, chanctx ? chanctx->def.chan->band : NL80211_BAND_2GHZ, &cck_ack_rates, &ofdm_ack_rates); rcu_read_unlock(); cmd->cck_rates = cpu_to_le32((u32)cck_ack_rates); cmd->ofdm_rates = cpu_to_le32((u32)ofdm_ack_rates); cmd->cck_short_preamble = cpu_to_le32(vif->bss_conf.use_short_preamble ? MAC_FLG_SHORT_PREAMBLE : 0); cmd->short_slot = cpu_to_le32(vif->bss_conf.use_short_slot ? MAC_FLG_SHORT_SLOT : 0); cmd->filter_flags = cpu_to_le32(MAC_FILTER_ACCEPT_GRP); for (i = 0; i < IEEE80211_NUM_ACS; i++) { u8 txf = iwl_mvm_mac_ac_to_tx_fifo(mvm, i); cmd->ac[txf].cw_min = cpu_to_le16(mvmvif->queue_params[i].cw_min); cmd->ac[txf].cw_max = cpu_to_le16(mvmvif->queue_params[i].cw_max); cmd->ac[txf].edca_txop = cpu_to_le16(mvmvif->queue_params[i].txop * 32); cmd->ac[txf].aifsn = mvmvif->queue_params[i].aifs; cmd->ac[txf].fifos_mask = BIT(txf); } if (vif->bss_conf.qos) cmd->qos_flags |= cpu_to_le32(MAC_QOS_FLG_UPDATE_EDCA); if (vif->bss_conf.use_cts_prot) cmd->protection_flags |= cpu_to_le32(MAC_PROT_FLG_TGG_PROTECT); IWL_DEBUG_RATE(mvm, "use_cts_prot %d, ht_operation_mode %d\n", vif->bss_conf.use_cts_prot, vif->bss_conf.ht_operation_mode); if (vif->bss_conf.chandef.width != NL80211_CHAN_WIDTH_20_NOHT) cmd->qos_flags |= cpu_to_le32(MAC_QOS_FLG_TGN); if (ht_enabled) iwl_mvm_mac_ctxt_set_ht_flags(mvm, vif, cmd); } static int iwl_mvm_mac_ctxt_send_cmd(struct iwl_mvm *mvm, struct iwl_mac_ctx_cmd *cmd) { int ret = iwl_mvm_send_cmd_pdu(mvm, MAC_CONTEXT_CMD, 0, sizeof(*cmd), cmd); if (ret) IWL_ERR(mvm, "Failed to send MAC context (action:%d): %d\n", le32_to_cpu(cmd->action), ret); return ret; } static int iwl_mvm_mac_ctxt_cmd_sta(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action, bool force_assoc_off, const u8 *bssid_override) { struct iwl_mac_ctx_cmd cmd = {}; struct iwl_mac_data_sta *ctxt_sta; WARN_ON(vif->type != NL80211_IFTYPE_STATION); /* Fill the common data for all mac context types */ iwl_mvm_mac_ctxt_cmd_common(mvm, vif, &cmd, bssid_override, action); if (vif->p2p) { struct ieee80211_p2p_noa_attr *noa = &vif->bss_conf.p2p_noa_attr; cmd.p2p_sta.ctwin = cpu_to_le32(noa->oppps_ctwindow & IEEE80211_P2P_OPPPS_CTWINDOW_MASK); ctxt_sta = &cmd.p2p_sta.sta; } else { ctxt_sta = &cmd.sta; } /* We need the dtim_period to set the MAC as associated */ if (vif->bss_conf.assoc && vif->bss_conf.dtim_period && !force_assoc_off) { u32 dtim_offs; /* * The DTIM count counts down, so when it is N that means N * more beacon intervals happen until the DTIM TBTT. Therefore * add this to the current time. If that ends up being in the * future, the firmware will handle it. * * Also note that the system_timestamp (which we get here as * "sync_device_ts") and TSF timestamp aren't at exactly the * same offset in the frame -- the TSF is at the first symbol * of the TSF, the system timestamp is at signal acquisition * time. This means there's an offset between them of at most * a few hundred microseconds (24 * 8 bits + PLCP time gives * 384us in the longest case), this is currently not relevant * as the firmware wakes up around 2ms before the TBTT. */ dtim_offs = vif->bss_conf.sync_dtim_count * vif->bss_conf.beacon_int; /* convert TU to usecs */ dtim_offs *= 1024; ctxt_sta->dtim_tsf = cpu_to_le64(vif->bss_conf.sync_tsf + dtim_offs); ctxt_sta->dtim_time = cpu_to_le32(vif->bss_conf.sync_device_ts + dtim_offs); ctxt_sta->assoc_beacon_arrive_time = cpu_to_le32(vif->bss_conf.sync_device_ts); IWL_DEBUG_INFO(mvm, "DTIM TBTT is 0x%llx/0x%x, offset %d\n", le64_to_cpu(ctxt_sta->dtim_tsf), le32_to_cpu(ctxt_sta->dtim_time), dtim_offs); ctxt_sta->is_assoc = cpu_to_le32(1); } else { ctxt_sta->is_assoc = cpu_to_le32(0); /* Allow beacons to pass through as long as we are not * associated, or we do not have dtim period information. */ cmd.filter_flags |= cpu_to_le32(MAC_FILTER_IN_BEACON); } ctxt_sta->bi = cpu_to_le32(vif->bss_conf.beacon_int); ctxt_sta->bi_reciprocal = cpu_to_le32(iwl_mvm_reciprocal(vif->bss_conf.beacon_int)); ctxt_sta->dtim_interval = cpu_to_le32(vif->bss_conf.beacon_int * vif->bss_conf.dtim_period); ctxt_sta->dtim_reciprocal = cpu_to_le32(iwl_mvm_reciprocal(vif->bss_conf.beacon_int * vif->bss_conf.dtim_period)); ctxt_sta->listen_interval = cpu_to_le32(mvm->hw->conf.listen_interval); ctxt_sta->assoc_id = cpu_to_le32(vif->bss_conf.aid); if (vif->probe_req_reg && vif->bss_conf.assoc && vif->p2p) cmd.filter_flags |= cpu_to_le32(MAC_FILTER_IN_PROBE_REQUEST); if (vif->bss_conf.assoc && vif->bss_conf.he_support && !iwlwifi_mod_params.disable_11ax) cmd.filter_flags |= cpu_to_le32(MAC_FILTER_IN_11AX); return iwl_mvm_mac_ctxt_send_cmd(mvm, &cmd); } static int iwl_mvm_mac_ctxt_cmd_listener(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action) { struct iwl_mac_ctx_cmd cmd = {}; u32 tfd_queue_msk = BIT(mvm->snif_queue); int ret; WARN_ON(vif->type != NL80211_IFTYPE_MONITOR); iwl_mvm_mac_ctxt_cmd_common(mvm, vif, &cmd, NULL, action); cmd.filter_flags = cpu_to_le32(MAC_FILTER_IN_PROMISC | MAC_FILTER_IN_CONTROL_AND_MGMT | MAC_FILTER_IN_BEACON | MAC_FILTER_IN_PROBE_REQUEST | MAC_FILTER_IN_CRC32); ieee80211_hw_set(mvm->hw, RX_INCLUDES_FCS); /* Allocate sniffer station */ ret = iwl_mvm_allocate_int_sta(mvm, &mvm->snif_sta, tfd_queue_msk, vif->type, IWL_STA_GENERAL_PURPOSE); if (ret) return ret; return iwl_mvm_mac_ctxt_send_cmd(mvm, &cmd); } static int iwl_mvm_mac_ctxt_cmd_ibss(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mac_ctx_cmd cmd = {}; WARN_ON(vif->type != NL80211_IFTYPE_ADHOC); iwl_mvm_mac_ctxt_cmd_common(mvm, vif, &cmd, NULL, action); cmd.filter_flags = cpu_to_le32(MAC_FILTER_IN_BEACON | MAC_FILTER_IN_PROBE_REQUEST); /* cmd.ibss.beacon_time/cmd.ibss.beacon_tsf are curently ignored */ cmd.ibss.bi = cpu_to_le32(vif->bss_conf.beacon_int); cmd.ibss.bi_reciprocal = cpu_to_le32(iwl_mvm_reciprocal(vif->bss_conf.beacon_int)); /* TODO: Assumes that the beacon id == mac context id */ cmd.ibss.beacon_template = cpu_to_le32(mvmvif->id); return iwl_mvm_mac_ctxt_send_cmd(mvm, &cmd); } struct iwl_mvm_go_iterator_data { bool go_active; }; static void iwl_mvm_go_iterator(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_mvm_go_iterator_data *data = _data; struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); if (vif->type == NL80211_IFTYPE_AP && vif->p2p && mvmvif->ap_ibss_active) data->go_active = true; } static int iwl_mvm_mac_ctxt_cmd_p2p_device(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action) { struct iwl_mac_ctx_cmd cmd = {}; struct iwl_mvm_go_iterator_data data = {}; WARN_ON(vif->type != NL80211_IFTYPE_P2P_DEVICE); iwl_mvm_mac_ctxt_cmd_common(mvm, vif, &cmd, NULL, action); cmd.protection_flags |= cpu_to_le32(MAC_PROT_FLG_TGG_PROTECT); /* Override the filter flags to accept only probe requests */ cmd.filter_flags = cpu_to_le32(MAC_FILTER_IN_PROBE_REQUEST); /* * This flag should be set to true when the P2P Device is * discoverable and there is at least another active P2P GO. Settings * this flag will allow the P2P Device to be discoverable on other * channels in addition to its listen channel. * Note that this flag should not be set in other cases as it opens the * Rx filters on all MAC and increases the number of interrupts. */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_RESUME_ALL, iwl_mvm_go_iterator, &data); cmd.p2p_dev.is_disc_extended = cpu_to_le32(data.go_active ? 1 : 0); return iwl_mvm_mac_ctxt_send_cmd(mvm, &cmd); } static void iwl_mvm_mac_ctxt_set_tim(struct iwl_mvm *mvm, __le32 *tim_index, __le32 *tim_size, u8 *beacon, u32 frame_size) { u32 tim_idx; struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)beacon; /* The index is relative to frame start but we start looking at the * variable-length part of the beacon. */ tim_idx = mgmt->u.beacon.variable - beacon; /* Parse variable-length elements of beacon to find WLAN_EID_TIM */ while ((tim_idx < (frame_size - 2)) && (beacon[tim_idx] != WLAN_EID_TIM)) tim_idx += beacon[tim_idx+1] + 2; /* If TIM field was found, set variables */ if ((tim_idx < (frame_size - 1)) && (beacon[tim_idx] == WLAN_EID_TIM)) { *tim_index = cpu_to_le32(tim_idx); *tim_size = cpu_to_le32((u32)beacon[tim_idx + 1]); } else { IWL_WARN(mvm, "Unable to find TIM Element in beacon\n"); } } static u32 iwl_mvm_find_ie_offset(u8 *beacon, u8 eid, u32 frame_size) { struct ieee80211_mgmt *mgmt = (void *)beacon; const u8 *ie; if (WARN_ON_ONCE(frame_size <= (mgmt->u.beacon.variable - beacon))) return 0; frame_size -= mgmt->u.beacon.variable - beacon; ie = cfg80211_find_ie(eid, mgmt->u.beacon.variable, frame_size); if (!ie) return 0; return ie - beacon; } static u8 iwl_mvm_mac_ctxt_get_lowest_rate(struct ieee80211_tx_info *info, struct ieee80211_vif *vif) { u8 rate; if (info->band == NL80211_BAND_5GHZ || vif->p2p) rate = IWL_FIRST_OFDM_RATE; else rate = IWL_FIRST_CCK_RATE; return rate; } static void iwl_mvm_mac_ctxt_set_tx(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct sk_buff *beacon, struct iwl_tx_cmd *tx) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct ieee80211_tx_info *info; u8 rate; u32 tx_flags; info = IEEE80211_SKB_CB(beacon); /* Set up TX command fields */ tx->len = cpu_to_le16((u16)beacon->len); tx->sta_id = mvmvif->bcast_sta.sta_id; tx->life_time = cpu_to_le32(TX_CMD_LIFE_TIME_INFINITE); tx_flags = TX_CMD_FLG_SEQ_CTL | TX_CMD_FLG_TSF; tx_flags |= iwl_mvm_bt_coex_tx_prio(mvm, (void *)beacon->data, info, 0) << TX_CMD_FLG_BT_PRIO_POS; tx->tx_flags = cpu_to_le32(tx_flags); if (!fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_BEACON_ANT_SELECTION)) { mvm->mgmt_last_antenna_idx = iwl_mvm_next_antenna(mvm, iwl_mvm_get_valid_tx_ant(mvm), mvm->mgmt_last_antenna_idx); } tx->rate_n_flags = cpu_to_le32(BIT(mvm->mgmt_last_antenna_idx) << RATE_MCS_ANT_POS); rate = iwl_mvm_mac_ctxt_get_lowest_rate(info, vif); tx->rate_n_flags |= cpu_to_le32(iwl_mvm_mac80211_idx_to_hwrate(rate)); if (rate == IWL_FIRST_CCK_RATE) tx->rate_n_flags |= cpu_to_le32(RATE_MCS_CCK_MSK); } static int iwl_mvm_mac_ctxt_send_beacon_cmd(struct iwl_mvm *mvm, struct sk_buff *beacon, void *data, int len) { struct iwl_host_cmd cmd = { .id = BEACON_TEMPLATE_CMD, .flags = CMD_ASYNC, }; cmd.len[0] = len; cmd.data[0] = data; cmd.dataflags[0] = 0; cmd.len[1] = beacon->len; cmd.data[1] = beacon->data; cmd.dataflags[1] = IWL_HCMD_DFL_DUP; return iwl_mvm_send_cmd(mvm, &cmd); } static int iwl_mvm_mac_ctxt_send_beacon_v6(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct sk_buff *beacon) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mac_beacon_cmd_v6 beacon_cmd = {}; iwl_mvm_mac_ctxt_set_tx(mvm, vif, beacon, &beacon_cmd.tx); beacon_cmd.template_id = cpu_to_le32((u32)mvmvif->id); if (vif->type == NL80211_IFTYPE_AP) iwl_mvm_mac_ctxt_set_tim(mvm, &beacon_cmd.tim_idx, &beacon_cmd.tim_size, beacon->data, beacon->len); return iwl_mvm_mac_ctxt_send_beacon_cmd(mvm, beacon, &beacon_cmd, sizeof(beacon_cmd)); } static int iwl_mvm_mac_ctxt_send_beacon_v7(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct sk_buff *beacon) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mac_beacon_cmd_v7 beacon_cmd = {}; iwl_mvm_mac_ctxt_set_tx(mvm, vif, beacon, &beacon_cmd.tx); beacon_cmd.template_id = cpu_to_le32((u32)mvmvif->id); if (vif->type == NL80211_IFTYPE_AP) iwl_mvm_mac_ctxt_set_tim(mvm, &beacon_cmd.tim_idx, &beacon_cmd.tim_size, beacon->data, beacon->len); beacon_cmd.csa_offset = cpu_to_le32(iwl_mvm_find_ie_offset(beacon->data, WLAN_EID_CHANNEL_SWITCH, beacon->len)); beacon_cmd.ecsa_offset = cpu_to_le32(iwl_mvm_find_ie_offset(beacon->data, WLAN_EID_EXT_CHANSWITCH_ANN, beacon->len)); return iwl_mvm_mac_ctxt_send_beacon_cmd(mvm, beacon, &beacon_cmd, sizeof(beacon_cmd)); } static int iwl_mvm_mac_ctxt_send_beacon_v9(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct sk_buff *beacon) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(beacon); struct iwl_mac_beacon_cmd beacon_cmd = {}; u8 rate = iwl_mvm_mac_ctxt_get_lowest_rate(info, vif); u16 flags; flags = iwl_mvm_mac80211_idx_to_hwrate(rate); if (rate == IWL_FIRST_CCK_RATE) flags |= IWL_MAC_BEACON_CCK; beacon_cmd.flags = cpu_to_le16(flags); beacon_cmd.byte_cnt = cpu_to_le16((u16)beacon->len); beacon_cmd.template_id = cpu_to_le32((u32)mvmvif->id); if (vif->type == NL80211_IFTYPE_AP) iwl_mvm_mac_ctxt_set_tim(mvm, &beacon_cmd.tim_idx, &beacon_cmd.tim_size, beacon->data, beacon->len); beacon_cmd.csa_offset = cpu_to_le32(iwl_mvm_find_ie_offset(beacon->data, WLAN_EID_CHANNEL_SWITCH, beacon->len)); beacon_cmd.ecsa_offset = cpu_to_le32(iwl_mvm_find_ie_offset(beacon->data, WLAN_EID_EXT_CHANSWITCH_ANN, beacon->len)); return iwl_mvm_mac_ctxt_send_beacon_cmd(mvm, beacon, &beacon_cmd, sizeof(beacon_cmd)); } static int iwl_mvm_mac_ctxt_send_beacon(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct sk_buff *beacon) { if (WARN_ON(!beacon)) return -EINVAL; if (!fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_CSA_AND_TBTT_OFFLOAD)) return iwl_mvm_mac_ctxt_send_beacon_v6(mvm, vif, beacon); if (fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_NEW_BEACON_TEMPLATE)) return iwl_mvm_mac_ctxt_send_beacon_v9(mvm, vif, beacon); return iwl_mvm_mac_ctxt_send_beacon_v7(mvm, vif, beacon); } /* The beacon template for the AP/GO/IBSS has changed and needs update */ int iwl_mvm_mac_ctxt_beacon_changed(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct sk_buff *beacon; int ret; WARN_ON(vif->type != NL80211_IFTYPE_AP && vif->type != NL80211_IFTYPE_ADHOC); beacon = ieee80211_beacon_get_template(mvm->hw, vif, NULL); if (!beacon) return -ENOMEM; ret = iwl_mvm_mac_ctxt_send_beacon(mvm, vif, beacon); dev_kfree_skb(beacon); return ret; } struct iwl_mvm_mac_ap_iterator_data { struct iwl_mvm *mvm; struct ieee80211_vif *vif; u32 beacon_device_ts; u16 beacon_int; }; /* Find the beacon_device_ts and beacon_int for a managed interface */ static void iwl_mvm_mac_ap_iterator(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_mvm_mac_ap_iterator_data *data = _data; if (vif->type != NL80211_IFTYPE_STATION || !vif->bss_conf.assoc) return; /* Station client has higher priority over P2P client*/ if (vif->p2p && data->beacon_device_ts) return; data->beacon_device_ts = vif->bss_conf.sync_device_ts; data->beacon_int = vif->bss_conf.beacon_int; } /* * Fill the specific data for mac context of type AP of P2P GO */ static void iwl_mvm_mac_ctxt_cmd_fill_ap(struct iwl_mvm *mvm, struct ieee80211_vif *vif, struct iwl_mac_ctx_cmd *cmd, struct iwl_mac_data_ap *ctxt_ap, bool add) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mvm_mac_ap_iterator_data data = { .mvm = mvm, .vif = vif, .beacon_device_ts = 0 }; /* in AP mode, the MCAST FIFO takes the EDCA params from VO */ cmd->ac[IWL_MVM_TX_FIFO_VO].fifos_mask |= BIT(IWL_MVM_TX_FIFO_MCAST); /* * in AP mode, pass probe requests and beacons from other APs * (needed for ht protection); when there're no any associated * station don't ask FW to pass beacons to prevent unnecessary * wake-ups. */ cmd->filter_flags |= cpu_to_le32(MAC_FILTER_IN_PROBE_REQUEST); if (mvmvif->ap_assoc_sta_count || !mvm->drop_bcn_ap_mode) { cmd->filter_flags |= cpu_to_le32(MAC_FILTER_IN_BEACON); IWL_DEBUG_HC(mvm, "Asking FW to pass beacons\n"); } else { IWL_DEBUG_HC(mvm, "No need to receive beacons\n"); } ctxt_ap->bi = cpu_to_le32(vif->bss_conf.beacon_int); ctxt_ap->bi_reciprocal = cpu_to_le32(iwl_mvm_reciprocal(vif->bss_conf.beacon_int)); ctxt_ap->dtim_interval = cpu_to_le32(vif->bss_conf.beacon_int * vif->bss_conf.dtim_period); ctxt_ap->dtim_reciprocal = cpu_to_le32(iwl_mvm_reciprocal(vif->bss_conf.beacon_int * vif->bss_conf.dtim_period)); if (!fw_has_api(&mvm->fw->ucode_capa, IWL_UCODE_TLV_API_STA_TYPE)) ctxt_ap->mcast_qid = cpu_to_le32(vif->cab_queue); /* * Only set the beacon time when the MAC is being added, when we * just modify the MAC then we should keep the time -- the firmware * can otherwise have a "jumping" TBTT. */ if (add) { /* * If there is a station/P2P client interface which is * associated, set the AP's TBTT far enough from the station's * TBTT. Otherwise, set it to the current system time */ ieee80211_iterate_active_interfaces_atomic( mvm->hw, IEEE80211_IFACE_ITER_RESUME_ALL, iwl_mvm_mac_ap_iterator, &data); if (data.beacon_device_ts) { u32 rand = (prandom_u32() % (64 - 36)) + 36; mvmvif->ap_beacon_time = data.beacon_device_ts + ieee80211_tu_to_usec(data.beacon_int * rand / 100); } else { mvmvif->ap_beacon_time = iwl_read_prph(mvm->trans, DEVICE_SYSTEM_TIME_REG); } } ctxt_ap->beacon_time = cpu_to_le32(mvmvif->ap_beacon_time); ctxt_ap->beacon_tsf = 0; /* unused */ /* TODO: Assume that the beacon id == mac context id */ ctxt_ap->beacon_template = cpu_to_le32(mvmvif->id); } static int iwl_mvm_mac_ctxt_cmd_ap(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action) { struct iwl_mac_ctx_cmd cmd = {}; WARN_ON(vif->type != NL80211_IFTYPE_AP || vif->p2p); /* Fill the common data for all mac context types */ iwl_mvm_mac_ctxt_cmd_common(mvm, vif, &cmd, NULL, action); /* Fill the data specific for ap mode */ iwl_mvm_mac_ctxt_cmd_fill_ap(mvm, vif, &cmd, &cmd.ap, action == FW_CTXT_ACTION_ADD); return iwl_mvm_mac_ctxt_send_cmd(mvm, &cmd); } static int iwl_mvm_mac_ctxt_cmd_go(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action) { struct iwl_mac_ctx_cmd cmd = {}; struct ieee80211_p2p_noa_attr *noa = &vif->bss_conf.p2p_noa_attr; WARN_ON(vif->type != NL80211_IFTYPE_AP || !vif->p2p); /* Fill the common data for all mac context types */ iwl_mvm_mac_ctxt_cmd_common(mvm, vif, &cmd, NULL, action); /* Fill the data specific for GO mode */ iwl_mvm_mac_ctxt_cmd_fill_ap(mvm, vif, &cmd, &cmd.go.ap, action == FW_CTXT_ACTION_ADD); cmd.go.ctwin = cpu_to_le32(noa->oppps_ctwindow & IEEE80211_P2P_OPPPS_CTWINDOW_MASK); cmd.go.opp_ps_enabled = cpu_to_le32(!!(noa->oppps_ctwindow & IEEE80211_P2P_OPPPS_ENABLE_BIT)); return iwl_mvm_mac_ctxt_send_cmd(mvm, &cmd); } static int iwl_mvm_mac_ctx_send(struct iwl_mvm *mvm, struct ieee80211_vif *vif, u32 action, bool force_assoc_off, const u8 *bssid_override) { switch (vif->type) { case NL80211_IFTYPE_STATION: return iwl_mvm_mac_ctxt_cmd_sta(mvm, vif, action, force_assoc_off, bssid_override); break; case NL80211_IFTYPE_AP: if (!vif->p2p) return iwl_mvm_mac_ctxt_cmd_ap(mvm, vif, action); else return iwl_mvm_mac_ctxt_cmd_go(mvm, vif, action); break; case NL80211_IFTYPE_MONITOR: return iwl_mvm_mac_ctxt_cmd_listener(mvm, vif, action); case NL80211_IFTYPE_P2P_DEVICE: return iwl_mvm_mac_ctxt_cmd_p2p_device(mvm, vif, action); case NL80211_IFTYPE_ADHOC: return iwl_mvm_mac_ctxt_cmd_ibss(mvm, vif, action); default: break; } return -EOPNOTSUPP; } int iwl_mvm_mac_ctxt_add(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); int ret; if (WARN_ONCE(mvmvif->uploaded, "Adding active MAC %pM/%d\n", vif->addr, ieee80211_vif_type_p2p(vif))) return -EIO; ret = iwl_mvm_mac_ctx_send(mvm, vif, FW_CTXT_ACTION_ADD, true, NULL); if (ret) return ret; /* will only do anything at resume from D3 time */ iwl_mvm_set_last_nonqos_seq(mvm, vif); mvmvif->uploaded = true; return 0; } int iwl_mvm_mac_ctxt_changed(struct iwl_mvm *mvm, struct ieee80211_vif *vif, bool force_assoc_off, const u8 *bssid_override) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); if (WARN_ONCE(!mvmvif->uploaded, "Changing inactive MAC %pM/%d\n", vif->addr, ieee80211_vif_type_p2p(vif))) return -EIO; return iwl_mvm_mac_ctx_send(mvm, vif, FW_CTXT_ACTION_MODIFY, force_assoc_off, bssid_override); } int iwl_mvm_mac_ctxt_remove(struct iwl_mvm *mvm, struct ieee80211_vif *vif) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mac_ctx_cmd cmd; int ret; if (WARN_ONCE(!mvmvif->uploaded, "Removing inactive MAC %pM/%d\n", vif->addr, ieee80211_vif_type_p2p(vif))) return -EIO; memset(&cmd, 0, sizeof(cmd)); cmd.id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color)); cmd.action = cpu_to_le32(FW_CTXT_ACTION_REMOVE); ret = iwl_mvm_send_cmd_pdu(mvm, MAC_CONTEXT_CMD, 0, sizeof(cmd), &cmd); if (ret) { IWL_ERR(mvm, "Failed to remove MAC context: %d\n", ret); return ret; } mvmvif->uploaded = false; if (vif->type == NL80211_IFTYPE_MONITOR) { __clear_bit(IEEE80211_HW_RX_INCLUDES_FCS, mvm->hw->flags); iwl_mvm_dealloc_snif_sta(mvm); } return 0; } static void iwl_mvm_csa_count_down(struct iwl_mvm *mvm, struct ieee80211_vif *csa_vif, u32 gp2, bool tx_success) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(csa_vif); /* Don't start to countdown from a failed beacon */ if (!tx_success && !mvmvif->csa_countdown) return; mvmvif->csa_countdown = true; if (!ieee80211_csa_is_complete(csa_vif)) { int c = ieee80211_csa_update_counter(csa_vif); iwl_mvm_mac_ctxt_beacon_changed(mvm, csa_vif); if (csa_vif->p2p && !iwl_mvm_te_scheduled(&mvmvif->time_event_data) && gp2 && tx_success) { u32 rel_time = (c + 1) * csa_vif->bss_conf.beacon_int - IWL_MVM_CHANNEL_SWITCH_TIME_GO; u32 apply_time = gp2 + rel_time * 1024; iwl_mvm_schedule_csa_period(mvm, csa_vif, IWL_MVM_CHANNEL_SWITCH_TIME_GO - IWL_MVM_CHANNEL_SWITCH_MARGIN, apply_time); } } else if (!iwl_mvm_te_scheduled(&mvmvif->time_event_data)) { /* we don't have CSA NoA scheduled yet, switch now */ ieee80211_csa_finish(csa_vif); RCU_INIT_POINTER(mvm->csa_vif, NULL); } } void iwl_mvm_rx_beacon_notif(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb) { struct iwl_rx_packet *pkt = rxb_addr(rxb); struct iwl_extended_beacon_notif *beacon = (void *)pkt->data; struct iwl_mvm_tx_resp *beacon_notify_hdr; struct ieee80211_vif *csa_vif; struct ieee80211_vif *tx_blocked_vif; struct agg_tx_status *agg_status; u16 status; lockdep_assert_held(&mvm->mutex); beacon_notify_hdr = &beacon->beacon_notify_hdr; mvm->ap_last_beacon_gp2 = le32_to_cpu(beacon->gp2); mvm->ibss_manager = beacon->ibss_mgr_status != 0; agg_status = iwl_mvm_get_agg_status(mvm, beacon_notify_hdr); status = le16_to_cpu(agg_status->status) & TX_STATUS_MSK; IWL_DEBUG_RX(mvm, "beacon status %#x retries:%d tsf:0x%16llX gp2:0x%X rate:%d\n", status, beacon_notify_hdr->failure_frame, le64_to_cpu(beacon->tsf), mvm->ap_last_beacon_gp2, le32_to_cpu(beacon_notify_hdr->initial_rate)); csa_vif = rcu_dereference_protected(mvm->csa_vif, lockdep_is_held(&mvm->mutex)); if (unlikely(csa_vif && csa_vif->csa_active)) iwl_mvm_csa_count_down(mvm, csa_vif, mvm->ap_last_beacon_gp2, (status == TX_STATUS_SUCCESS)); tx_blocked_vif = rcu_dereference_protected(mvm->csa_tx_blocked_vif, lockdep_is_held(&mvm->mutex)); if (unlikely(tx_blocked_vif)) { struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(tx_blocked_vif); /* * The channel switch is started and we have blocked the * stations. If this is the first beacon (the timeout wasn't * set), set the unblock timeout, otherwise countdown */ if (!mvm->csa_tx_block_bcn_timeout) mvm->csa_tx_block_bcn_timeout = IWL_MVM_CS_UNBLOCK_TX_TIMEOUT; else mvm->csa_tx_block_bcn_timeout--; /* Check if the timeout is expired, and unblock tx */ if (mvm->csa_tx_block_bcn_timeout == 0) { iwl_mvm_modify_all_sta_disable_tx(mvm, mvmvif, false); RCU_INIT_POINTER(mvm->csa_tx_blocked_vif, NULL); } } } static void iwl_mvm_beacon_loss_iterator(void *_data, u8 *mac, struct ieee80211_vif *vif) { struct iwl_missed_beacons_notif *missed_beacons = _data; struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif); struct iwl_mvm *mvm = mvmvif->mvm; struct iwl_fw_dbg_trigger_missed_bcon *bcon_trig; struct iwl_fw_dbg_trigger_tlv *trigger; u32 stop_trig_missed_bcon, stop_trig_missed_bcon_since_rx; u32 rx_missed_bcon, rx_missed_bcon_since_rx; if (mvmvif->id != (u16)le32_to_cpu(missed_beacons->mac_id)) return; rx_missed_bcon = le32_to_cpu(missed_beacons->consec_missed_beacons); rx_missed_bcon_since_rx = le32_to_cpu(missed_beacons->consec_missed_beacons_since_last_rx); /* * TODO: the threshold should be adjusted based on latency conditions, * and/or in case of a CS flow on one of the other AP vifs. */ if (le32_to_cpu(missed_beacons->consec_missed_beacons_since_last_rx) > IWL_MVM_MISSED_BEACONS_THRESHOLD) ieee80211_beacon_loss(vif); if (!iwl_fw_dbg_trigger_enabled(mvm->fw, FW_DBG_TRIGGER_MISSED_BEACONS)) return; trigger = iwl_fw_dbg_get_trigger(mvm->fw, FW_DBG_TRIGGER_MISSED_BEACONS); bcon_trig = (void *)trigger->data; stop_trig_missed_bcon = le32_to_cpu(bcon_trig->stop_consec_missed_bcon); stop_trig_missed_bcon_since_rx = le32_to_cpu(bcon_trig->stop_consec_missed_bcon_since_rx); /* TODO: implement start trigger */ if (!iwl_fw_dbg_trigger_check_stop(&mvm->fwrt, ieee80211_vif_to_wdev(vif), trigger)) return; if (rx_missed_bcon_since_rx >= stop_trig_missed_bcon_since_rx || rx_missed_bcon >= stop_trig_missed_bcon) iwl_fw_dbg_collect_trig(&mvm->fwrt, trigger, NULL); } void iwl_mvm_rx_missed_beacons_notif(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb) { struct iwl_rx_packet *pkt = rxb_addr(rxb); struct iwl_missed_beacons_notif *mb = (void *)pkt->data; IWL_DEBUG_INFO(mvm, "missed bcn mac_id=%u, consecutive=%u (%u, %u, %u)\n", le32_to_cpu(mb->mac_id), le32_to_cpu(mb->consec_missed_beacons), le32_to_cpu(mb->consec_missed_beacons_since_last_rx), le32_to_cpu(mb->num_recvd_beacons), le32_to_cpu(mb->num_expected_beacons)); ieee80211_iterate_active_interfaces_atomic(mvm->hw, IEEE80211_IFACE_ITER_NORMAL, iwl_mvm_beacon_loss_iterator, mb); } void iwl_mvm_rx_stored_beacon_notif(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb) { struct iwl_rx_packet *pkt = rxb_addr(rxb); struct iwl_stored_beacon_notif *sb = (void *)pkt->data; struct ieee80211_rx_status rx_status; struct sk_buff *skb; u32 size = le32_to_cpu(sb->byte_count); if (size == 0) return; skb = alloc_skb(size, GFP_ATOMIC); if (!skb) { IWL_ERR(mvm, "alloc_skb failed\n"); return; } /* update rx_status according to the notification's metadata */ memset(&rx_status, 0, sizeof(rx_status)); rx_status.mactime = le64_to_cpu(sb->tsf); /* TSF as indicated by the firmware is at INA time */ rx_status.flag |= RX_FLAG_MACTIME_PLCP_START; rx_status.device_timestamp = le32_to_cpu(sb->system_time); rx_status.band = (sb->band & cpu_to_le16(RX_RES_PHY_FLAGS_BAND_24)) ? NL80211_BAND_2GHZ : NL80211_BAND_5GHZ; rx_status.freq = ieee80211_channel_to_frequency(le16_to_cpu(sb->channel), rx_status.band); /* copy the data */ skb_put_data(skb, sb->data, size); memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status)); /* pass it as regular rx to mac80211 */ ieee80211_rx_napi(mvm->hw, NULL, skb, NULL); } void iwl_mvm_channel_switch_noa_notif(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb) { struct iwl_rx_packet *pkt = rxb_addr(rxb); struct iwl_channel_switch_noa_notif *notif = (void *)pkt->data; struct ieee80211_vif *csa_vif; struct iwl_mvm_vif *mvmvif; int len = iwl_rx_packet_payload_len(pkt); u32 id_n_color; if (WARN_ON_ONCE(len < sizeof(*notif))) return; rcu_read_lock(); csa_vif = rcu_dereference(mvm->csa_vif); if (WARN_ON(!csa_vif || !csa_vif->csa_active)) goto out_unlock; id_n_color = le32_to_cpu(notif->id_and_color); mvmvif = iwl_mvm_vif_from_mac80211(csa_vif); if (WARN(FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color) != id_n_color, "channel switch noa notification on unexpected vif (csa_vif=%d, notif=%d)", FW_CMD_ID_AND_COLOR(mvmvif->id, mvmvif->color), id_n_color)) goto out_unlock; IWL_DEBUG_INFO(mvm, "Channel Switch Started Notification\n"); schedule_delayed_work(&mvm->cs_tx_unblock_dwork, msecs_to_jiffies(IWL_MVM_CS_UNBLOCK_TX_TIMEOUT * csa_vif->bss_conf.beacon_int)); ieee80211_csa_finish(csa_vif); rcu_read_unlock(); RCU_INIT_POINTER(mvm->csa_vif, NULL); return; out_unlock: rcu_read_unlock(); }
gpl-2.0
nsberrow/pi.parklands.co.za
wp-content/plugins/googleappslogin-enterprise/core/Google/Signer/PEM.php
1783
<?php /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Updated by Dan Lester 2014 * */ require_once realpath(dirname(__FILE__) . '/../../../autoload.php'); /** * Signs data with PEM key (e.g. taken from new JSON files). * * @author Dan Lester <[email protected]> */ class GoogleGAL_Signer_PEM extends GoogleGAL_Signer_Abstract { // OpenSSL private key resource private $privateKey; // Creates a new signer from a PEM text string public function __construct($pem, $password) { if (!function_exists('openssl_x509_read')) { throw new GoogleGAL_Exception( 'The Google PHP API library needs the openssl PHP extension' ); } $this->privateKey = $pem; if (!$this->privateKey) { throw new GoogleGAL_Auth_Exception("Unable to load private key"); } } public function __destruct() { } public function sign($data) { if (version_compare(PHP_VERSION, '5.3.0') < 0) { throw new GoogleGAL_Auth_Exception( "PHP 5.3.0 or higher is required to use service accounts." ); } $hash = defined("OPENSSL_ALGO_SHA256") ? OPENSSL_ALGO_SHA256 : "sha256"; if (!openssl_sign($data, $signature, $this->privateKey, $hash)) { throw new GoogleGAL_Auth_Exception("Unable to sign data"); } return $signature; } }
gpl-2.0
AftonTroll/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/notifications/blocks/UserNoteBlock.java
7212
package org.wordpress.android.ui.notifications.blocks; import android.content.Context; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.TextView; import org.json.JSONObject; import org.wordpress.android.R; import org.wordpress.android.util.JSONUtils; import org.wordpress.android.util.GravatarUtils; import org.wordpress.android.widgets.WPNetworkImageView; /** * A block that displays information about a User (such as a user that liked a post) */ public class UserNoteBlock extends NoteBlock { private final OnGravatarClickedListener mGravatarClickedListener; private int mAvatarSz; public interface OnGravatarClickedListener { // userId is currently unused, but will be handy once a profile view is added to the app public void onGravatarClicked(long siteId, long userId, String siteUrl); } public UserNoteBlock( Context context, JSONObject noteObject, OnNoteBlockTextClickListener onNoteBlockTextClickListener, OnGravatarClickedListener onGravatarClickedListener) { super(noteObject, onNoteBlockTextClickListener); if (context != null) { setAvatarSize(context.getResources().getDimensionPixelSize(R.dimen.notifications_avatar_sz)); } mGravatarClickedListener = onGravatarClickedListener; } void setAvatarSize(int size) { mAvatarSz = size; } int getAvatarSize() { return mAvatarSz; } @Override public BlockType getBlockType() { return BlockType.USER; } @Override public int getLayoutResourceId() { return R.layout.note_block_user; } @Override public View configureView(View view) { final UserActionNoteBlockHolder noteBlockHolder = (UserActionNoteBlockHolder)view.getTag(); noteBlockHolder.nameTextView.setText(getNoteText().toString()); String linkedText = null; if (hasUserUrlAndTitle()) { linkedText = getUserBlogTitle(); } else if (hasUserUrl()) { linkedText = getUserUrl(); } if (!TextUtils.isEmpty(linkedText)) { noteBlockHolder.urlTextView.setText(linkedText); noteBlockHolder.urlTextView.setVisibility(View.VISIBLE); } else { noteBlockHolder.urlTextView.setVisibility(View.GONE); } if (hasUserBlogTagline()) { noteBlockHolder.taglineTextView.setText(getUserBlogTagline()); noteBlockHolder.taglineTextView.setVisibility(View.VISIBLE); } else { noteBlockHolder.taglineTextView.setVisibility(View.GONE); } if (hasImageMediaItem()) { String imageUrl = GravatarUtils.fixGravatarUrl(getNoteMediaItem().optString("url", ""), getAvatarSize()); noteBlockHolder.avatarImageView.setImageUrl(imageUrl, WPNetworkImageView.ImageType.AVATAR); if (!TextUtils.isEmpty(getUserUrl())) { noteBlockHolder.avatarImageView.setOnTouchListener(mOnGravatarTouchListener); noteBlockHolder.rootView.setEnabled(true); noteBlockHolder.rootView.setOnClickListener(mOnClickListener); } else { noteBlockHolder.avatarImageView.setOnTouchListener(null); noteBlockHolder.rootView.setEnabled(false); noteBlockHolder.rootView.setOnClickListener(null); } } else { noteBlockHolder.avatarImageView.showDefaultGravatarImage(); noteBlockHolder.avatarImageView.setOnTouchListener(null); } return view; } private final View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { showBlogPreview(); } }; @Override public Object getViewHolder(View view) { return new UserActionNoteBlockHolder(view); } private class UserActionNoteBlockHolder { private final View rootView; private final TextView nameTextView; private final TextView urlTextView; private final TextView taglineTextView; private final WPNetworkImageView avatarImageView; public UserActionNoteBlockHolder(View view) { rootView = view.findViewById(R.id.user_block_root_view); nameTextView = (TextView)view.findViewById(R.id.user_name); urlTextView = (TextView)view.findViewById(R.id.user_blog_url); taglineTextView = (TextView)view.findViewById(R.id.user_blog_tagline); avatarImageView = (WPNetworkImageView)view.findViewById(R.id.user_avatar); } } String getUserUrl() { return JSONUtils.queryJSON(getNoteData(), "meta.links.home", ""); } private String getUserBlogTitle() { return JSONUtils.queryJSON(getNoteData(), "meta.titles.home", ""); } private String getUserBlogTagline() { return JSONUtils.queryJSON(getNoteData(), "meta.titles.tagline", ""); } private boolean hasUserUrl() { return !TextUtils.isEmpty(getUserUrl()); } private boolean hasUserUrlAndTitle() { return hasUserUrl() && !TextUtils.isEmpty(getUserBlogTitle()); } private boolean hasUserBlogTagline() { return !TextUtils.isEmpty(getUserBlogTagline()); } final View.OnTouchListener mOnGravatarTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int animationDuration = 150; if (event.getAction() == MotionEvent.ACTION_DOWN) { v.animate() .scaleX(0.9f) .scaleY(0.9f) .alpha(0.5f) .setDuration(animationDuration) .setInterpolator(new DecelerateInterpolator()); } else if (event.getActionMasked() == MotionEvent.ACTION_UP || event.getActionMasked() == MotionEvent.ACTION_CANCEL) { v.animate() .scaleX(1.0f) .scaleY(1.0f) .alpha(1.0f) .setDuration(animationDuration) .setInterpolator(new DecelerateInterpolator()); if (event.getActionMasked() == MotionEvent.ACTION_UP && mGravatarClickedListener != null) { // Fire the listener, which will load the site preview for the user's site // In the future we can use this to load a 'profile view' (currently in R&D) showBlogPreview(); } } return true; } }; private void showBlogPreview() { long siteId = Long.valueOf(JSONUtils.queryJSON(getNoteData(), "meta.ids.site", 0)); long userId = Long.valueOf(JSONUtils.queryJSON(getNoteData(), "meta.ids.user", 0)); String siteUrl = getUserUrl(); if (mGravatarClickedListener != null) { mGravatarClickedListener.onGravatarClicked(siteId, userId, siteUrl); } } }
gpl-2.0
ptsmonteiro/XPAirbusSystems
usr/include/Widgets/XPWidgets.h
23571
#ifndef _XPWidgets_h_ #define _XPWidgets_h_ /* * Copyright 2005-2012 Sandy Barbour and Ben Supnik * * All rights reserved. See license.txt for usage. * * X-Plane SDK Version: 2.1.1 * */ /* * WIDGETS - THEORY OF OPERATION AND NOTES * * Widgets are persistent view 'objects' for X-Plane. A widget is an object * referenced by its opaque handle (widget ID) and the APIs in this file. You * cannot access the widget's guts directly. Every Widget has the following * intrinsic data: * * - A bounding box defined in global screen coordinates with 0,0 in the * bottom left and +y = up, +x = right. * * - A visible box, which is the intersection of the bounding box with the * widget's parents visible box. * * - Zero or one parent widgets. (Always zero if the widget is a root widget. * * * - Zero or more child widgets. * * - Whether the widget is a root. Root widgets are the top level plugin * windows. * * - Whether the widget is visible. * * - A text string descriptor, whose meaning varies from widget to widget. * * - An arbitrary set of 32 bit integral properties defined by 32-bit integral * keys. This is how specific widgets * * store specific data. * * - A list of widget callbacks proc that implements the widgets behaviors. * * The Widgets library sends messages to widgets to request specific behaviors * or notify the widget of things. * * Widgets may have more than one callback function, in which case messages * are sent to the most recently added callback function until the message is * handled. Messages may also be sent to parents or children; see the * XPWidgetDefs.h header file for the different widget message dispatching * functions. By adding a callback function to a window you can 'subclass' * its behavior. * * A set of standard widgets are provided that serve common UI purposes. You * can also customize or implement entirely custom widgets. * * Widgets are different than other view hierarchies (most notably Win32, * which they bear a striking resemblance to) in the following ways: * * - Not all behavior can be patched. State that is managed by the XPWidgets * DLL and not by individual widgets cannot be customized. * * - All coordinates are in global screen coordinates. Coordinates are not * relative to an enclosing widget, nor are they relative to a display window. * * * - Widget messages are always dispatched synchronously, and there is no * concept of scheduling an update or a dirty region. Messages originate from * X-Plane as the sim cycle goes by. Since x-plane is constantly redrawing, * so are widgets; there is no need to mark a part of a widget as 'needing * redrawing' because redrawing happens frequently whether the widget needs it * or not. * * - Any widget may be a 'root' widget, causing it to be drawn; there is no * relationship between widget class and rootness. Root widgets are * imlemented as XPLMDisply windows. * */ #include "XPWidgetDefs.h" #ifdef __cplusplus extern "C" { #endif /*************************************************************************** * WIDGET CREATION AND MANAGEMENT ***************************************************************************/ /* * * */ /* * XPCreateWidget * * This function creates a new widget and returns the new widget's ID to you. * If the widget creation fails for some reason, it returns NULL. Widget * creation will fail either if you pass a bad class ID or if there is not * adequate memory. * * Input Parameters: * * - Top, left, bottom, and right in global screen coordinates defining the * widget's location on the screen. * * - inVisible is 1 if the widget should be drawn, 0 to start the widget as * hidden. * * - inDescriptor is a null terminated string that will become the widget's * descriptor. * * - inIsRoot is 1 if this is going to be a root widget, 0 if it will not be. * * - inContainer is the ID of this widget's container. It must be 0 for a * root widget. for a non-root widget, pass the widget ID of the widget to * place this widget within. If this widget is not going to start inside * another widget, pass 0; this new widget will then just be floating off in * space (and will not be drawn until it is placed in a widget. * * - inClass is the class of the widget to draw. Use one of the predefined * class-IDs to create a standard widget. * * A note on widget embedding: a widget is only called (and will be drawn, * etc.) if it is placed within a widget that will be called. Root widgets * are always called. So it is possible to have whole chains of widgets that * are simply not called. You can preconstruct widget trees and then place * them into root widgets later to activate them if you wish. * */ WIDGET_API XPWidgetID XPCreateWidget( int inLeft, int inTop, int inRight, int inBottom, int inVisible, const char * inDescriptor, int inIsRoot, XPWidgetID inContainer, XPWidgetClass inClass); /* * XPCreateCustomWidget * * This function is the same as XPCreateWidget except that instead of passing * a class ID, you pass your widget callback function pointer defining the * widget. Use this function to define a custom widget. All parameters are * the same as XPCreateWidget, except that the widget class has been replaced * with the widget function. * */ WIDGET_API XPWidgetID XPCreateCustomWidget( int inLeft, int inTop, int inRight, int inBottom, int inVisible, const char * inDescriptor, int inIsRoot, XPWidgetID inContainer, XPWidgetFunc_t inCallback); /* * XPDestroyWidget * * This class destroys a widget. Pass in the ID of the widget to kill. If * you pass 1 for inDestroyChilren, the widget's children will be destroyed * first, then this widget will be destroyed. (Furthermore, the widget's * children will be destroyed with the inDestroyChildren flag set to 1, so the * destruction will recurse down the widget tree.) If you pass 0 for this * flag, the child widgets will simply end up with their parent set to 0. * */ WIDGET_API void XPDestroyWidget( XPWidgetID inWidget, int inDestroyChildren); /* * XPSendMessageToWidget * * This sends any message to a widget. You should probably not go around * simulating the predefined messages that the widgets library defines for * you. You may however define custom messages for your widgets and send them * with this method. * * This method supports several dispatching patterns; see XPDispatchMode for * more info. The function returns 1 if the message was handled, 0 if it was * not. * * For each widget that receives the message (see the dispatching modes), each * widget function from the most recently installed to the oldest one * receives the message in order until it is handled. * */ WIDGET_API int XPSendMessageToWidget( XPWidgetID inWidget, XPWidgetMessage inMessage, XPDispatchMode inMode, intptr_t inParam1, intptr_t inParam2); /*************************************************************************** * WIDGET POSITIONING AND VISIBILITY ***************************************************************************/ /* * * */ /* * XPPlaceWidgetWithin * * This function changes which container a widget resides in. You may NOT use * this function on a root widget! inSubWidget is the widget that will be * moved. Pass a widget ID in inContainer to make inSubWidget be a child of * inContainer. It will become the last/closest widget in the container. * Pass 0 to remove the widget from any container. Any call to this other * than passing the widget ID of the old parent of the affected widget will * cause the widget to be removed from its old parent. Placing a widget within * its own parent simply makes it the last widget. * * NOTE: this routine does not reposition the sub widget in global * coordinates. If the container has layout management code, it will * reposition the subwidget for you, otherwise you must do it with * SetWidgetGeometry. * */ WIDGET_API void XPPlaceWidgetWithin( XPWidgetID inSubWidget, XPWidgetID inContainer); /* * XPCountChildWidgets * * This routine returns the number of widgets another widget contains. * */ WIDGET_API int XPCountChildWidgets( XPWidgetID inWidget); /* * XPGetNthChildWidget * * This routine returns the widget ID of a child widget by index. Indexes are * 0 based, from 0 to one minus the number of widgets in the parent, * inclusive. If the index is invalid, 0 is returned. * */ WIDGET_API XPWidgetID XPGetNthChildWidget( XPWidgetID inWidget, int inIndex); /* * XPGetParentWidget * * This routine returns the parent of a widget, or 0 if the widget has no * parent. Root widgets never have parents and therefore always return 0. * */ WIDGET_API XPWidgetID XPGetParentWidget( XPWidgetID inWidget); /* * XPShowWidget * * This routine makes a widget visible if it is not already. Note that if a * widget is not in a rooted widget hierarchy or one of its parents is not * visible, it will still not be visible to the user. * */ WIDGET_API void XPShowWidget( XPWidgetID inWidget); /* * XPHideWidget * * Makes a widget invisible. See XPShowWidget for considerations of when a * widget might not be visible despite its own visibility state. * */ WIDGET_API void XPHideWidget( XPWidgetID inWidget); /* * XPIsWidgetVisible * * This returns 1 if a widget is visible, 0 if it is not. Note that this * routine takes into consideration whether a parent is invisible. Use this * routine to tell if the user can see the widget. * */ WIDGET_API int XPIsWidgetVisible( XPWidgetID inWidget); /* * XPFindRootWidget * * XPFindRootWidget returns the Widget ID of the root widget that contains the * passed in widget or NULL if the passed in widget is not in a rooted * hierarchy. * */ WIDGET_API XPWidgetID XPFindRootWidget( XPWidgetID inWidget); /* * XPBringRootWidgetToFront * * This routine makes the specified widget be in the front most widget * hierarchy. If this widget is a root widget, its widget hierarchy comes to * front, otherwise the widget's root is brought to the front. If this widget * is not in an active widget hiearchy (e.g. there is no root widget at the * top of the tree), this routine does nothing. * */ WIDGET_API void XPBringRootWidgetToFront( XPWidgetID inWidget); /* * XPIsWidgetInFront * * This routine returns true if this widget's hierarchy is the front most * hierarchy. It returns false if the widget's hierarchy is not in front, or * if the widget is not in a rooted hierarchy. * */ WIDGET_API int XPIsWidgetInFront( XPWidgetID inWidget); /* * XPGetWidgetGeometry * * This routine returns the bounding box of a widget in global coordinates. * Pass NULL for any parameter you are not interested in. * */ WIDGET_API void XPGetWidgetGeometry( XPWidgetID inWidget, int * outLeft, /* Can be NULL */ int * outTop, /* Can be NULL */ int * outRight, /* Can be NULL */ int * outBottom); /* Can be NULL */ /* * XPSetWidgetGeometry * * This function changes the bounding box of a widget. * */ WIDGET_API void XPSetWidgetGeometry( XPWidgetID inWidget, int inLeft, int inTop, int inRight, int inBottom); /* * XPGetWidgetForLocation * * Given a widget and a location, this routine returns the widget ID of the * child of that widget that owns that location. If inRecursive is true then * this will return a child of a child of a widget as it tries to find the * deepest widget at that location. If inVisibleOnly is true, then only * visible widgets are considered, otherwise all widgets are considered. The * widget ID passed for inContainer will be returned if the location is in * that widget but not in a child widget. 0 is returned if the location is * not in the container. * * NOTE: if a widget's geometry extends outside its parents geometry, it will * not be returned by this call for mouse locations outside the parent * geometry. The parent geometry limits the child's eligibility for mouse * location. * */ WIDGET_API XPWidgetID XPGetWidgetForLocation( XPWidgetID inContainer, int inXOffset, int inYOffset, int inRecursive, int inVisibleOnly); /* * XPGetWidgetExposedGeometry * * This routine returns the bounds of the area of a widget that is completely * within its parent widgets. Since a widget's bounding box can be outside * its parent, part of its area will not be elligible for mouse clicks and * should not draw. Use XPGetWidgetGeometry to find out what area defines * your widget's shape, but use this routine to find out what area to actually * draw into. Note that the widget library does not use OpenGL clipping to * keep frame rates up, although you could use it internally. * */ WIDGET_API void XPGetWidgetExposedGeometry( XPWidgetID inWidgetID, int * outLeft, /* Can be NULL */ int * outTop, /* Can be NULL */ int * outRight, /* Can be NULL */ int * outBottom); /* Can be NULL */ /*************************************************************************** * ACCESSING WIDGET DATA ***************************************************************************/ /* * * */ /* * XPSetWidgetDescriptor * * Every widget has a descriptor, which is a text string. What the text * string is used for varies from widget to widget; for example, a push * button's text is its descriptor, a caption shows its descriptor, and a text * field's descriptor is the text being edited. In other words, the usage for * the text varies from widget to widget, but this API provides a universal * and convenient way to get at it. While not all UI widgets need their * descriptor, many do. * */ WIDGET_API void XPSetWidgetDescriptor( XPWidgetID inWidget, const char * inDescriptor); /* * XPGetWidgetDescriptor * * This routine returns the widget's descriptor. Pass in the length of the * buffer you are going to receive the descriptor in. The descriptor will be * null terminated for you. This routine returns the length of the actual * descriptor; if you pass NULL for outDescriptor, you can get the * descriptor's length without getting its text. If the length of the * descriptor exceeds your buffer length, the buffer will not be null * terminated (this routine has 'strncpy' semantics). * */ WIDGET_API int XPGetWidgetDescriptor( XPWidgetID inWidget, char * outDescriptor, int inMaxDescLength); /* * XPSetWidgetProperty * * This function sets a widget's property. Properties are arbitrary values * associated by a widget by ID. * */ WIDGET_API void XPSetWidgetProperty( XPWidgetID inWidget, XPWidgetPropertyID inProperty, intptr_t inValue); /* * XPGetWidgetProperty * * This routine returns the value of a widget's property, or 0 if the property * is not defined. If you need to know whether the property is defined, pass * a pointer to an int for inExists; the existence of that property will be * returned in the int. Pass NULL for inExists if you do not need this * information. * */ WIDGET_API intptr_t XPGetWidgetProperty( XPWidgetID inWidget, XPWidgetPropertyID inProperty, int * inExists); /* Can be NULL */ /*************************************************************************** * KEYBOARD MANAGEMENT ***************************************************************************/ /* * * */ /* * XPSetKeyboardFocus * * XPSetKeyboardFocus controls which widget will receive keystrokes. Pass the * Widget ID of the widget to get the keys. Note that if the widget does not * care about keystrokes, they will go to the parent widget, and if no widget * cares about them, they go to X-Plane. * * If you set the keyboard focus to Widget ID 0, X-Plane gets keyboard focus. * * This routine returns the widget ID that ended up with keyboard focus, or 0 * for x-plane. * * Keyboard focus is not changed if the new widget will not accept it. For * setting to x-plane, keyboard focus is always accepted. * * * */ WIDGET_API XPWidgetID XPSetKeyboardFocus( XPWidgetID inWidget); /* * XPLoseKeyboardFocus * * This causes the specified widget to lose focus; focus is passed to its * parent, or the next parent that will accept it. This routine does nothing * if this widget does not have focus. * */ WIDGET_API void XPLoseKeyboardFocus( XPWidgetID inWidget); /* * XPGetWidgetWithFocus * * This routine returns the widget that has keyboard focus, or 0 if X-Plane * has keyboard focus or some other plugin window that does not have widgets * has focus. * */ WIDGET_API XPWidgetID XPGetWidgetWithFocus(void); /*************************************************************************** * CREATING CUSTOM WIDGETS ***************************************************************************/ /* * * */ /* * XPAddWidgetCallback * * This function adds a new widget callback to a widget. This widget callback * supercedes any existing ones and will receive messages first; if it does * not handle messages they will go on to be handled by pre-existing widgets. * * The widget function will remain on the widget for the life of the widget. * The creation message will be sent to the new callback immediately with the * widget ID, and the destruction message will be sent before the other widget * function receives a destruction message. * * This provides a way to 'subclass' an existing widget. By providing a * second hook that only handles certain widget messages, you can customize or * extend widget behavior. * */ WIDGET_API void XPAddWidgetCallback( XPWidgetID inWidget, XPWidgetFunc_t inNewCallback); /* * XPGetWidgetClassFunc * * Given a widget class, this function returns the callbacks that power that * widget class. * */ WIDGET_API XPWidgetFunc_t XPGetWidgetClassFunc( XPWidgetClass inWidgetClass); #ifdef __cplusplus } #endif #endif
gpl-2.0
ingted/resource-agents
rgmanager/src/resources/postgres-8.sh
6052
#!/bin/bash # # Copyright (C) 1997-2003 Sistina Software, Inc. All rights reserved. # Copyright (C) 2004-2011 Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # 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. # export LC_ALL=C export LANG=C export PATH=/bin:/sbin:/usr/bin:/usr/sbin . $(dirname $0)/ocf-shellfuncs . $(dirname $0)/utils/config-utils.sh . $(dirname $0)/utils/messages.sh . $(dirname $0)/utils/ra-skelet.sh declare PSQL_POSTMASTER="/usr/bin/postmaster" declare PSQL_CTL="/usr/bin/pg_ctl" declare PSQL_pid_file="`generate_name_for_pid_file`" declare PSQL_conf_dir="`generate_name_for_conf_dir`" declare PSQL_gen_config_file="$PSQL_conf_dir/postgresql.conf" declare PSQL_kill_timeout="5" declare PSQL_stop_timeout="15" if [ -z "$OCF_RESKEY_startup_wait" ]; then OCF_RESKEY_startup_wait=10 fi verify_all() { clog_service_verify $CLOG_INIT if [ -z "$OCF_RESKEY_name" ]; then clog_service_verify $CLOG_FAILED "Invalid Name Of Service" return $OCF_ERR_ARGS fi if [ -z "$OCF_RESKEY_service_name" ]; then clog_service_verify $CLOG_FAILED_NOT_CHILD return $OCF_ERR_ARGS fi if [ -z "$OCF_RESKEY_config_file" ]; then clog_check_file_exist $CLOG_FAILED_INVALID "$OCF_RESKEY_config_file" clog_service_verify $CLOG_FAILED return $OCF_ERR_ARGS fi if [ ! -r "$OCF_RESKEY_config_file" ]; then clog_check_file_exist $CLOG_FAILED_NOT_READABLE $OCF_RESKEY_config_file clog_service_verify $CLOG_FAILED return $OCF_ERR_ARGS fi if [ -z "$OCF_RESKEY_postmaster_user" ]; then clog_servicer_verify $CLOG_FAILED "Invalid User" return $OCF_ERR_ARGS fi clog_service_verify $CLOG_SUCCEED return 0 } generate_config_file() { declare original_file="$1" declare generated_file="$2" declare ip_addressess="$3" declare ip_comma=""; if [ -f "$generated_file" ]; then sha1_verify "$generated_file" if [ $? -ne 0 ]; then clog_check_sha1 $CLOG_FAILED return 0 fi fi clog_generate_config $CLOG_INIT "$original_file" "$generated_file" declare x=1 for i in $ip_addressess; do i=`echo $i | sed -e 's/\/.*$//'` if [ $x -eq 1 ]; then x=0 ip_comma=$i else ip_comma=$ip_comma,$i fi done generate_configTemplate "$generated_file" "$1" echo "external_pid_file = '$PSQL_pid_file'" >> "$generated_file" echo "listen_addresses = '$ip_comma'" >> "$generated_file" echo >> "$generated_file" sed 's/^[[:space:]]*external_pid_file/### external_pid_file/i;s/^[[:space:]]*listen_addresses/### listen_addresses/i' < "$original_file" >> "$generated_file" sha1_addToFile "$generated_file" clog_generate_config $CLOG_SUCCEED "$original_file" "$generated_file" return 0; } start() { declare pguser_group declare count=0 clog_service_start $CLOG_INIT create_pid_directory create_conf_directory "$PSQL_conf_dir" check_pid_file "$PSQL_pid_file" if [ $? -ne 0 ]; then clog_check_pid $CLOG_FAILED "$PSQL_pid_file" clog_service_start $CLOG_FAILED return $OCF_ERR_GENERIC fi # # Create an empty PID file for the postgres user and # change it to be owned by the postgres user so that # postmaster doesn't complain. # pguser_group=`groups $OCF_RESKEY_postmaster_user | cut -f3 -d ' '` touch $PSQL_pid_file chown $OCF_RESKEY_postmaster_user.$pguser_group $PSQL_pid_file clog_looking_for $CLOG_INIT "IP Addresses" get_service_ip_keys "$OCF_RESKEY_service_name" ip_addresses=`build_ip_list` if [ -z "$ip_addresses" ]; then clog_looking_for $CLOG_FAILED_NOT_FOUND "IP Addresses" return $OCF_ERR_GENERIC fi clog_looking_for $CLOG_SUCCEED "IP Addresses" generate_config_file "$OCF_RESKEY_config_file" "$PSQL_gen_config_file" "$ip_addresses" su - "$OCF_RESKEY_postmaster_user" -c "$PSQL_POSTMASTER -c config_file=\"$PSQL_gen_config_file\" \ $OCF_RESKEY_postmaster_options" &> /dev/null & # We need to sleep briefly to allow pg_ctl to detect that we've started. # We need to fetch "-D /path/to/pgsql/data" from $OCF_RESKEY_postmaster_options until [ "$count" -gt "$OCF_RESKEY_startup_wait" ] || [ `su - "$OCF_RESKEY_postmaster_user" -c \ "$PSQL_CTL status $OCF_RESKEY_postmaster_options" &> /dev/null; echo $?` = '0' ] do sleep 1 let count=$count+1 done if [ "$count" -gt "$OCF_RESKEY_startup_wait" ]; then clog_service_start $CLOG_FAILED return $OCF_ERR_GENERIC fi clog_service_start $CLOG_SUCCEED return 0; } stop() { clog_service_stop $CLOG_INIT ## Send -INT to close connections and stop. -QUIT is used if -INT signal does not stop process. stop_generic_sigkill "$PSQL_pid_file" "$PSQL_stop_timeout" "$PSQL_kill_timeout" "-INT" if [ $? -ne 0 ]; then clog_service_stop $CLOG_FAILED return $OCF_ERR_GENERIC fi clog_service_stop $CLOG_SUCCEED return 0; } status() { clog_service_status $CLOG_INIT status_check_pid "$PSQL_pid_file" if [ $? -ne 0 ]; then clog_service_status $CLOG_FAILED "$PSQL_pid_file" return $OCF_ERR_GENERIC fi clog_service_status $CLOG_SUCCEED return 0 } case $1 in meta-data) cat `echo $0 | sed 's/^\(.*\)\.sh$/\1.metadata/'` exit 0 ;; validate-all) verify_all exit $? ;; start) verify_all && start exit $? ;; stop) verify_all && stop exit $? ;; status|monitor) verify_all status exit $? ;; restart) verify_all stop start exit $? ;; *) echo "Usage: $0 {start|stop|status|monitor|restart|meta-data|validate-all}" exit $OCF_ERR_UNIMPLEMENTED ;; esac
gpl-2.0
Zentyal/samba
selftest/selftesthelpers.py
6229
#!/usr/bin/python # This script generates a list of testsuites that should be run as part of # the Samba 4 test suite. # The output of this script is parsed by selftest.pl, which then decides # which of the tests to actually run. It will, for example, skip all tests # listed in selftest/skip or only run a subset during "make quicktest". # The idea is that this script outputs all of the tests of Samba 4, not # just those that are known to pass, and list those that should be skipped # or are known to fail in selftest/skip or selftest/knownfail. This makes it # very easy to see what functionality is still missing in Samba 4 and makes # it possible to run the testsuite against other servers, such as Samba 3 or # Windows that have a different set of features. # The syntax for a testsuite is "-- TEST --" on a single line, followed # by the name of the test, the environment it needs and the command to run, all # three separated by newlines. All other lines in the output are considered # comments. import os import subprocess import sys def srcdir(): return os.path.normpath(os.getenv("SRCDIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))) def source4dir(): return os.path.normpath(os.path.join(srcdir(), "source4")) def source3dir(): return os.path.normpath(os.path.join(srcdir(), "source3")) def bindir(): return os.path.normpath(os.getenv("BINDIR", "./bin")) def binpath(name): return os.path.join(bindir(), name) # Split perl variable to allow $PERL to be set to e.g. "perl -W" perl = os.getenv("PERL", "perl").split() if subprocess.call(perl + ["-e", "eval require Test::More;"]) == 0: has_perl_test_more = True else: has_perl_test_more = False python = os.getenv("PYTHON", "python") tap2subunit = python + " " + os.path.join(srcdir(), "selftest", "tap2subunit") def valgrindify(cmdline): """Run a command under valgrind, if $VALGRIND was set.""" valgrind = os.getenv("VALGRIND") if valgrind is None: return cmdline return valgrind + " " + cmdline def plantestsuite(name, env, cmdline): """Plan a test suite. :param name: Testsuite name :param env: Environment to run the testsuite in :param cmdline: Command line to run """ print "-- TEST --" print name print env if isinstance(cmdline, list): cmdline = " ".join(cmdline) if "$LISTOPT" in cmdline: raise AssertionError("test %s supports --list, but not --load-list" % name) print cmdline + " 2>&1 " + " | " + add_prefix(name, env) def add_prefix(prefix, env, support_list=False): if support_list: listopt = "$LISTOPT " else: listopt = "" return "%s/selftest/filter-subunit %s--fail-on-empty --prefix=\"%s.\" --suffix=\"(%s)\"" % (srcdir(), listopt, prefix, env) def plantestsuite_loadlist(name, env, cmdline): print "-- TEST-LOADLIST --" if env == "none": fullname = name else: fullname = "%s(%s)" % (name, env) print fullname print env if isinstance(cmdline, list): cmdline = " ".join(cmdline) support_list = ("$LISTOPT" in cmdline) if not "$LISTOPT" in cmdline: raise AssertionError("loadlist test %s does not support not --list" % name) if not "$LOADLIST" in cmdline: raise AssertionError("loadlist test %s does not support --load-list" % name) print ("%s | %s" % (cmdline.replace("$LOADLIST", ""), add_prefix(name, env, support_list))).replace("$LISTOPT", "--list") print cmdline.replace("$LISTOPT", "") + " 2>&1 " + " | " + add_prefix(name, env, False) def skiptestsuite(name, reason): """Indicate that a testsuite was skipped. :param name: Test suite name :param reason: Reason the test suite was skipped """ # FIXME: Report this using subunit, but re-adjust the testsuite count somehow print >>sys.stderr, "skipping %s (%s)" % (name, reason) def planperltestsuite(name, path): """Run a perl test suite. :param name: Name of the test suite :param path: Path to the test runner """ if has_perl_test_more: plantestsuite(name, "none", "%s %s | %s" % (" ".join(perl), path, tap2subunit)) else: skiptestsuite(name, "Test::More not available") def planpythontestsuite(env, module, name=None, extra_path=[]): if name is None: name = module pypath = list(extra_path) args = [python, "-m", "samba.subunit.run", "$LISTOPT", "$LOADLIST", module] if pypath: args.insert(0, "PYTHONPATH=%s" % ":".join(["$PYTHONPATH"] + pypath)) plantestsuite_loadlist(name, env, args) def get_env_torture_options(): ret = [] if not os.getenv("SELFTEST_VERBOSE"): ret.append("--option=torture:progress=no") if os.getenv("SELFTEST_QUICK"): ret.append("--option=torture:quick=yes") return ret samba4srcdir = source4dir() samba3srcdir = source3dir() bbdir = os.path.join(srcdir(), "testprogs/blackbox") configuration = "--configfile=$SMB_CONF_PATH" smbtorture4 = binpath("smbtorture") smbtorture4_testsuite_list = subprocess.Popen([smbtorture4, "--list-suites"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate("")[0].splitlines() smbtorture4_options = [ configuration, "--option=\'fss:sequence timeout=1\'", "--maximum-runtime=$SELFTEST_MAXTIME", "--basedir=$SELFTEST_TMPDIR", "--format=subunit" ] + get_env_torture_options() def plansmbtorture4testsuite(name, env, options, target, modname=None): if modname is None: modname = "samba4.%s" % name if isinstance(options, list): options = " ".join(options) options = " ".join(smbtorture4_options + ["--target=%s" % target]) + " " + options cmdline = "%s $LISTOPT $LOADLIST %s %s" % (valgrindify(smbtorture4), options, name) plantestsuite_loadlist(modname, env, cmdline) def smbtorture4_testsuites(prefix): return filter(lambda x: x.startswith(prefix), smbtorture4_testsuite_list) smbclient3 = binpath('smbclient') smbtorture3 = binpath('smbtorture3') ntlm_auth3 = binpath('ntlm_auth') net = binpath('net') scriptdir = os.path.join(srcdir(), "script/tests") wbinfo = binpath('wbinfo') dbwrap_tool = binpath('dbwrap_tool') vfstest = binpath('vfstest')
gpl-3.0
mixerp/mixerp
src/FrontEnd/Scripts/semantic-ui/components/icon.css
43375
/*! * # Semantic UI 2.1.3 - Icon * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ /******************************* Icon *******************************/ @font-face { font-family: 'Icons'; src: url("/Scripts/semantic-ui/themes/default/assets/fonts/icons.eot"); src: url("/Scripts/semantic-ui/themes/default/assets/fonts/icons.eot?#iefix") format('embedded-opentype'), url("/Scripts/semantic-ui/themes/default/assets/fonts/icons.woff2") format('woff2'), url("/Scripts/semantic-ui/themes/default/assets/fonts/icons.woff") format('woff'), url("/Scripts/semantic-ui/themes/default/assets/fonts/icons.ttf") format('truetype'), url("/Scripts/semantic-ui/themes/default/assets/fonts/icons.svg#icons") format('svg'); font-style: normal; font-weight: normal; font-variant: normal; text-decoration: inherit; text-transform: none; } i.icon { display: inline-block; opacity: 1; margin: 0em 0.25rem 0em 0em; width: 1.18em; height: 1em; font-family: 'Icons'; font-style: normal; font-weight: normal; text-decoration: inherit; text-align: center; speak: none; font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; -webkit-backface-visibility: hidden; backface-visibility: hidden; } i.icon:before { background: none !important; } /******************************* Types *******************************/ /*-------------- Loading ---------------*/ i.icon.loading { height: 1em; line-height: 1; -webkit-animation: icon-loading 2s linear infinite; animation: icon-loading 2s linear infinite; } @-webkit-keyframes icon-loading { from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes icon-loading { from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } /******************************* States *******************************/ i.icon.hover { opacity: 1 !important; } i.icon.active { opacity: 1 !important; } i.emphasized.icon { opacity: 1 !important; } i.disabled.icon { opacity: 0.45 !important; } /******************************* Variations *******************************/ /*------------------- Fitted --------------------*/ i.fitted.icon { width: auto; margin: 0em; } /*------------------- Link --------------------*/ i.link.icon { cursor: pointer; opacity: 0.8; -webkit-transition: opacity 0.1s ease; transition: opacity 0.1s ease; } i.link.icon:hover { opacity: 1 !important; } /*------------------- Circular --------------------*/ i.circular.icon { border-radius: 500em !important; line-height: 1 !important; padding: 0.5em 0.5em !important; box-shadow: 0em 0em 0em 0.1em rgba(0, 0, 0, 0.1) inset; width: 2em !important; height: 2em !important; } i.circular.inverted.icon { border: none; box-shadow: none; } /*------------------- Flipped --------------------*/ i.flipped.icon, i.horizontally.flipped.icon { -webkit-transform: scale(-1, 1); -ms-transform: scale(-1, 1); transform: scale(-1, 1); } i.vertically.flipped.icon { -webkit-transform: scale(1, -1); -ms-transform: scale(1, -1); transform: scale(1, -1); } /*------------------- Rotated --------------------*/ i.rotated.icon, i.right.rotated.icon, i.clockwise.rotated.icon { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } i.left.rotated.icon, i.counterclockwise.rotated.icon { -webkit-transform: rotate(-90deg); -ms-transform: rotate(-90deg); transform: rotate(-90deg); } /*------------------- Bordered --------------------*/ i.bordered.icon { line-height: 1; vertical-align: baseline; width: 2em; height: 2em; padding: 0.5em 0.41em !important; box-shadow: 0em 0em 0em 0.1em rgba(0, 0, 0, 0.1) inset; } i.bordered.inverted.icon { border: none; box-shadow: none; } /*------------------- Inverted --------------------*/ /* Inverted Shapes */ i.inverted.bordered.icon, i.inverted.circular.icon { background-color: #1b1c1d !important; color: #ffffff !important; } i.inverted.icon { color: #ffffff; } /*------------------- Colors --------------------*/ /* Red */ i.red.icon { color: #db2828 !important; } i.inverted.red.icon { color: #ff695e !important; } i.inverted.bordered.red.icon, i.inverted.circular.red.icon { background-color: #db2828 !important; color: #ffffff !important; } /* Orange */ i.orange.icon { color: #f2711c !important; } i.inverted.orange.icon { color: #ff851b !important; } i.inverted.bordered.orange.icon, i.inverted.circular.orange.icon { background-color: #f2711c !important; color: #ffffff !important; } /* Yellow */ i.yellow.icon { color: #fbbd08 !important; } i.inverted.yellow.icon { color: #ffe21f !important; } i.inverted.bordered.yellow.icon, i.inverted.circular.yellow.icon { background-color: #fbbd08 !important; color: #ffffff !important; } /* Olive */ i.olive.icon { color: #b5cc18 !important; } i.inverted.olive.icon { color: #d9e778 !important; } i.inverted.bordered.olive.icon, i.inverted.circular.olive.icon { background-color: #b5cc18 !important; color: #ffffff !important; } /* Green */ i.green.icon { color: #21ba45 !important; } i.inverted.green.icon { color: #2ecc40 !important; } i.inverted.bordered.green.icon, i.inverted.circular.green.icon { background-color: #21ba45 !important; color: #ffffff !important; } /* Teal */ i.teal.icon { color: #00b5ad !important; } i.inverted.teal.icon { color: #6dffff !important; } i.inverted.bordered.teal.icon, i.inverted.circular.teal.icon { background-color: #00b5ad !important; color: #ffffff !important; } /* Blue */ i.blue.icon { color: #2185d0 !important; } i.inverted.blue.icon { color: #54c8ff !important; } i.inverted.bordered.blue.icon, i.inverted.circular.blue.icon { background-color: #2185d0 !important; color: #ffffff !important; } /* Violet */ i.violet.icon { color: #6435c9 !important; } i.inverted.violet.icon { color: #a291fb !important; } i.inverted.bordered.violet.icon, i.inverted.circular.violet.icon { background-color: #6435c9 !important; color: #ffffff !important; } /* Purple */ i.purple.icon { color: #a333c8 !important; } i.inverted.purple.icon { color: #dc73ff !important; } i.inverted.bordered.purple.icon, i.inverted.circular.purple.icon { background-color: #a333c8 !important; color: #ffffff !important; } /* Pink */ i.pink.icon { color: #e03997 !important; } i.inverted.pink.icon { color: #ff8edf !important; } i.inverted.bordered.pink.icon, i.inverted.circular.pink.icon { background-color: #e03997 !important; color: #ffffff !important; } /* Brown */ i.brown.icon { color: #a5673f !important; } i.inverted.brown.icon { color: #d67c1c !important; } i.inverted.bordered.brown.icon, i.inverted.circular.brown.icon { background-color: #a5673f !important; color: #ffffff !important; } /* Grey */ i.grey.icon { color: #767676 !important; } i.inverted.grey.icon { color: #dcddde !important; } i.inverted.bordered.grey.icon, i.inverted.circular.grey.icon { background-color: #767676 !important; color: #ffffff !important; } /* Black */ i.black.icon { color: #1b1c1d !important; } i.inverted.black.icon { color: #545454 !important; } i.inverted.bordeblack.black.icon, i.inverted.circular.black.icon { background-color: #1b1c1d !important; color: #ffffff !important; } /*------------------- Sizes --------------------*/ i.mini.icon, i.mini.icons { line-height: 1; font-size: 0.71428571rem; } i.tiny.icon, i.tiny.icons { line-height: 1; font-size: 0.85714286rem; } i.small.icon, i.small.icons { line-height: 1; font-size: 0.92857143em; } i.icon, i.icons { font-size: 1em; } i.large.icon, i.large.icons { line-height: 1; vertical-align: middle; font-size: 1.5em; } i.big.icon, i.big.icons { line-height: 1; vertical-align: middle; font-size: 2em; } i.huge.icon, i.huge.icons { line-height: 1; vertical-align: middle; font-size: 4em; } i.massive.icon, i.massive.icons { line-height: 1; vertical-align: middle; font-size: 8em; } /******************************* Groups *******************************/ i.icons { display: inline-block; position: relative; line-height: 1; } i.icons .icon { position: absolute; top: 50%; left: 50%; -webkit-transform: translateX(-50%) translateY(-50%); -ms-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); margin: 0em; margin: 0; } i.icons .icon:first-child { position: static; width: auto; height: auto; vertical-align: top; -webkit-transform: none; -ms-transform: none; transform: none; margin-right: 0.25rem; } /* Corner Icon */ i.icons .corner.icon { top: auto; left: auto; right: 0; bottom: 0; -webkit-transform: none; -ms-transform: none; transform: none; font-size: 0.45em; text-shadow: -1px -1px 0 #ffffff, 1px -1px 0 #ffffff, -1px 1px 0 #ffffff, 1px 1px 0 #ffffff; } i.icons .inverted.corner.icon { text-shadow: -1px -1px 0 #1b1c1d, 1px -1px 0 #1b1c1d, -1px 1px 0 #1b1c1d, 1px 1px 0 #1b1c1d; } /* * Font Awesome 4.3.0 by @davegandy - http://fontawesome.io - @fontawesome * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) */ /******************************* Semantic-UI integration of font-awesome : ///class names are separated i.icon.circle => i.icon.circle i.icon.circle-o => i.icon.circle.outline //abbreviation are replaced by full letters: i.icon.ellipsis-h => i.icon.ellipsis.horizontal i.icon.ellipsis-v => i.icon.ellipsis.vertical .alpha => .i.icon.alphabet .asc => .i.icon.ascending .desc => .i.icon.descending .alt =>.alternate ASCII order is conserved for easier maintenance. Icons that only have one style 'outline', 'square' etc do not require this class for instance `lemon icon` not `lemon outline icon` since there is only one lemon *******************************/ /******************************* Icons *******************************/ /* Web Content */ i.icon.search:before { content: "\f002"; } i.icon.mail.outline:before { content: "\f003"; } i.icon.external:before { content: "\f08e"; } i.icon.signal:before { content: "\f012"; } i.icon.setting:before { content: "\f013"; } i.icon.home:before { content: "\f015"; } i.icon.inbox:before { content: "\f01c"; } i.icon.browser:before { content: "\f022"; } i.icon.tag:before { content: "\f02b"; } i.icon.tags:before { content: "\f02c"; } i.icon.calendar:before { content: "\f073"; } i.icon.comment:before { content: "\f075"; } i.icon.comments:before { content: "\f086"; } i.icon.shop:before { content: "\f07a"; } i.icon.privacy:before { content: "\f084"; } i.icon.settings:before { content: "\f085"; } i.icon.trophy:before { content: "\f091"; } i.icon.payment:before { content: "\f09d"; } i.icon.feed:before { content: "\f09e"; } i.icon.alarm.outline:before { content: "\f0a2"; } i.icon.tasks:before { content: "\f0ae"; } i.icon.cloud:before { content: "\f0c2"; } i.icon.lab:before { content: "\f0c3"; } i.icon.mail:before { content: "\f0e0"; } i.icon.idea:before { content: "\f0eb"; } i.icon.dashboard:before { content: "\f0e4"; } i.icon.sitemap:before { content: "\f0e8"; } i.icon.alarm:before { content: "\f0f3"; } i.icon.terminal:before { content: "\f120"; } i.icon.code:before { content: "\f121"; } i.icon.protect:before { content: "\f132"; } i.icon.calendar.outline:before { content: "\f133"; } i.icon.ticket:before { content: "\f145"; } i.icon.external.square:before { content: "\f14c"; } i.icon.map:before { content: "\f14e"; } i.icon.bug:before { content: "\f188"; } i.icon.mail.square:before { content: "\f199"; } i.icon.history:before { content: "\f1da"; } i.icon.options:before { content: "\f1de"; } i.icon.comment.outline:before { content: "\f0e5"; } i.icon.comments.outline:before { content: "\f0e6"; } i.icon.text.telephone:before { content: "\f1e4"; } i.icon.find:before { content: "\f1e5"; } i.icon.wifi:before { content: "\f1eb"; } i.icon.alarm.slash:before { content: "\f1f6"; } i.icon.alarm.slash.outline:before { content: "\f1f7"; } i.icon.copyright:before { content: "\f1f9"; } i.icon.at:before { content: "\f1fa"; } i.icon.eyedropper:before { content: "\f1fb"; } i.icon.paint.brush:before { content: "\f1fc"; } i.icon.heartbeat:before { content: "\f21e"; } /* User Actions */ i.icon.download:before { content: "\f019"; } i.icon.repeat:before { content: "\f01e"; } i.icon.refresh:before { content: "\f021"; } i.icon.lock:before { content: "\f023"; } i.icon.bookmark:before { content: "\f02e"; } i.icon.print:before { content: "\f02f"; } i.icon.write:before { content: "\f040"; } i.icon.theme:before { content: "\f043"; } i.icon.adjust:before { content: "\f042"; } i.icon.edit:before { content: "\f044"; } i.icon.external.share:before { content: "\f045"; } i.icon.ban:before { content: "\f05e"; } i.icon.mail.forward:before { content: "\f064"; } i.icon.share:before { content: "\f064"; } i.icon.expand:before { content: "\f065"; } i.icon.compress:before { content: "\f066"; } i.icon.unhide:before { content: "\f06e"; } i.icon.hide:before { content: "\f070"; } i.icon.random:before { content: "\f074"; } i.icon.retweet:before { content: "\f079"; } i.icon.sign.out:before { content: "\f08b"; } i.icon.pin:before { content: "\f08d"; } i.icon.sign.in:before { content: "\f090"; } i.icon.upload:before { content: "\f093"; } i.icon.call:before { content: "\f095"; } i.icon.call.square:before { content: "\f098"; } i.icon.remove.bookmark:before { content: "\f097"; } i.icon.unlock:before { content: "\f09c"; } i.icon.configure:before { content: "\f0ad"; } i.icon.filter:before { content: "\f0b0"; } i.icon.wizard:before { content: "\f0d0"; } i.icon.undo:before { content: "\f0e2"; } i.icon.exchange:before { content: "\f0ec"; } i.icon.cloud.download:before { content: "\f0ed"; } i.icon.cloud.upload:before { content: "\f0ee"; } i.icon.reply:before { content: "\f112"; } i.icon.reply.all:before { content: "\f122"; } i.icon.erase:before { content: "\f12d"; } i.icon.unlock.alternate:before { content: "\f13e"; } i.icon.archive:before { content: "\f187"; } i.icon.translate:before { content: "\f1ab"; } i.icon.recycle:before { content: "\f1b8"; } i.icon.send:before { content: "\f1d8"; } i.icon.send.outline:before { content: "\f1d9"; } i.icon.share.alternate:before { content: "\f1e0"; } i.icon.share.alternate.square:before { content: "\f1e1"; } i.icon.wait:before { content: "\f017"; } i.icon.write.square:before { content: "\f14b"; } i.icon.share.square:before { content: "\f14d"; } i.icon.add.to.cart:before { content: "\f217"; } i.icon.in.cart:before { content: "\f218"; } i.icon.add.user:before { content: "\f234"; } i.icon.remove.user:before { content: "\f235"; } /* Messages */ i.icon.help.circle:before { content: "\f059"; } i.icon.info.circle:before { content: "\f05a"; } i.icon.warning:before { content: "\f12a"; } i.icon.warning.circle:before { content: "\f06a"; } i.icon.warning.sign:before { content: "\f071"; } i.icon.help:before { content: "\f128"; } i.icon.info:before { content: "\f129"; } i.icon.announcement:before { content: "\f0a1"; } i.icon.birthday:before { content: "\f1fd"; } /* Users */ i.icon.users:before { content: "\f0c0"; } i.icon.doctor:before { content: "\f0f0"; } i.icon.child:before { content: "\f1ae"; } i.icon.user:before { content: "\f007"; } i.icon.handicap:before { content: "\f193"; } i.icon.student:before { content: "\f19d"; } i.icon.spy:before { content: "\f21b"; } /* Gender & Sexuality */ i.icon.female:before { content: "\f182"; } i.icon.male:before { content: "\f183"; } i.icon.woman:before { content: "\f221"; } i.icon.man:before { content: "\f222"; } i.icon.non.binary.transgender:before { content: "\f223"; } i.icon.intergender:before { content: "\f224"; } i.icon.transgender:before { content: "\f225"; } i.icon.lesbian:before { content: "\f226"; } i.icon.gay:before { content: "\f227"; } i.icon.heterosexual:before { content: "\f228"; } i.icon.other.gender:before { content: "\f229"; } i.icon.other.gender.vertical:before { content: "\f22a"; } i.icon.other.gender.horizontal:before { content: "\f22b"; } i.icon.neuter:before { content: "\f22c"; } /* View Adjustment */ i.icon.grid.layout:before { content: "\f00a"; } i.icon.list.layout:before { content: "\f00b"; } i.icon.block.layout:before { content: "\f009"; } i.icon.zoom:before { content: "\f00e"; } i.icon.zoom.out:before { content: "\f010"; } i.icon.resize.vertical:before { content: "\f07d"; } i.icon.resize.horizontal:before { content: "\f07e"; } i.icon.maximize:before { content: "\f0b2"; } i.icon.crop:before { content: "\f125"; } /* Literal Objects */ i.icon.cocktail:before { content: "\f000"; } i.icon.road:before { content: "\f018"; } i.icon.flag:before { content: "\f024"; } i.icon.book:before { content: "\f02d"; } i.icon.gift:before { content: "\f06b"; } i.icon.leaf:before { content: "\f06c"; } i.icon.fire:before { content: "\f06d"; } i.icon.plane:before { content: "\f072"; } i.icon.magnet:before { content: "\f076"; } i.icon.legal:before { content: "\f0e3"; } i.icon.lemon:before { content: "\f094"; } i.icon.world:before { content: "\f0ac"; } i.icon.travel:before { content: "\f0b1"; } i.icon.shipping:before { content: "\f0d1"; } i.icon.money:before { content: "\f0d6"; } i.icon.lightning:before { content: "\f0e7"; } i.icon.rain:before { content: "\f0e9"; } i.icon.treatment:before { content: "\f0f1"; } i.icon.suitcase:before { content: "\f0f2"; } i.icon.bar:before { content: "\f0fc"; } i.icon.flag.outline:before { content: "\f11d"; } i.icon.flag.checkered:before { content: "\f11e"; } i.icon.puzzle:before { content: "\f12e"; } i.icon.fire.extinguisher:before { content: "\f134"; } i.icon.rocket:before { content: "\f135"; } i.icon.anchor:before { content: "\f13d"; } i.icon.bullseye:before { content: "\f140"; } i.icon.sun:before { content: "\f185"; } i.icon.moon:before { content: "\f186"; } i.icon.fax:before { content: "\f1ac"; } i.icon.life.ring:before { content: "\f1cd"; } i.icon.bomb:before { content: "\f1e2"; } i.icon.soccer:before { content: "\f1e3"; } i.icon.calculator:before { content: "\f1ec"; } i.icon.diamond:before { content: "\f219"; } /* Shapes */ i.icon.crosshairs:before { content: "\f05b"; } i.icon.asterisk:before { content: "\f069"; } i.icon.certificate:before { content: "\f0a3"; } i.icon.circle:before { content: "\f111"; } i.icon.quote.left:before { content: "\f10d"; } i.icon.quote.right:before { content: "\f10e"; } i.icon.ellipsis.horizontal:before { content: "\f141"; } i.icon.ellipsis.vertical:before { content: "\f142"; } i.icon.cube:before { content: "\f1b2"; } i.icon.cubes:before { content: "\f1b3"; } i.icon.circle.notched:before { content: "\f1ce"; } i.icon.circle.thin:before { content: "\f1db"; } i.icon.square.outline:before { content: "\f096"; } i.icon.square:before { content: "\f0c8"; } /* Item Selection */ i.icon.checkmark:before { content: "\f00c"; } i.icon.remove:before { content: "\f00d"; } i.icon.checkmark.box:before { content: "\f046"; } i.icon.move:before { content: "\f047"; } i.icon.add.circle:before { content: "\f055"; } i.icon.minus.circle:before { content: "\f056"; } i.icon.remove.circle:before { content: "\f057"; } i.icon.check.circle:before { content: "\f058"; } i.icon.remove.circle.outline:before { content: "\f05c"; } i.icon.check.circle.outline:before { content: "\f05d"; } i.icon.plus:before { content: "\f067"; } i.icon.minus:before { content: "\f068"; } i.icon.add.square:before { content: "\f0fe"; } i.icon.radio:before { content: "\f10c"; } i.icon.selected.radio:before { content: "\f192"; } i.icon.minus.square:before { content: "\f146"; } i.icon.minus.square.outline:before { content: "\f147"; } i.icon.check.square:before { content: "\f14a"; } i.icon.plus.square.outline:before { content: "\f196"; } i.icon.toggle.off:before { content: "\f204"; } i.icon.toggle.on:before { content: "\f205"; } /* Media */ i.icon.film:before { content: "\f008"; } i.icon.sound:before { content: "\f025"; } i.icon.photo:before { content: "\f030"; } i.icon.bar.chart:before { content: "\f080"; } i.icon.camera.retro:before { content: "\f083"; } i.icon.newspaper:before { content: "\f1ea"; } i.icon.area.chart:before { content: "\f1fe"; } i.icon.pie.chart:before { content: "\f200"; } i.icon.line.chart:before { content: "\f201"; } /* Pointers */ i.icon.arrow.circle.outline.down:before { content: "\f01a"; } i.icon.arrow.circle.outline.up:before { content: "\f01b"; } i.icon.chevron.left:before { content: "\f053"; } i.icon.chevron.right:before { content: "\f054"; } i.icon.arrow.left:before { content: "\f060"; } i.icon.arrow.right:before { content: "\f061"; } i.icon.arrow.up:before { content: "\f062"; } i.icon.arrow.down:before { content: "\f063"; } i.icon.chevron.up:before { content: "\f077"; } i.icon.chevron.down:before { content: "\f078"; } i.icon.pointing.right:before { content: "\f0a4"; } i.icon.pointing.left:before { content: "\f0a5"; } i.icon.pointing.up:before { content: "\f0a6"; } i.icon.pointing.down:before { content: "\f0a7"; } i.icon.arrow.circle.left:before { content: "\f0a8"; } i.icon.arrow.circle.right:before { content: "\f0a9"; } i.icon.arrow.circle.up:before { content: "\f0aa"; } i.icon.arrow.circle.down:before { content: "\f0ab"; } i.icon.caret.down:before { content: "\f0d7"; } i.icon.caret.up:before { content: "\f0d8"; } i.icon.caret.left:before { content: "\f0d9"; } i.icon.caret.right:before { content: "\f0da"; } i.icon.angle.double.left:before { content: "\f100"; } i.icon.angle.double.right:before { content: "\f101"; } i.icon.angle.double.up:before { content: "\f102"; } i.icon.angle.double.down:before { content: "\f103"; } i.icon.angle.left:before { content: "\f104"; } i.icon.angle.right:before { content: "\f105"; } i.icon.angle.up:before { content: "\f106"; } i.icon.angle.down:before { content: "\f107"; } i.icon.chevron.circle.left:before { content: "\f137"; } i.icon.chevron.circle.right:before { content: "\f138"; } i.icon.chevron.circle.up:before { content: "\f139"; } i.icon.chevron.circle.down:before { content: "\f13a"; } i.icon.toggle.down:before { content: "\f150"; } i.icon.toggle.up:before { content: "\f151"; } i.icon.toggle.right:before { content: "\f152"; } i.icon.long.arrow.down:before { content: "\f175"; } i.icon.long.arrow.up:before { content: "\f176"; } i.icon.long.arrow.left:before { content: "\f177"; } i.icon.long.arrow.right:before { content: "\f178"; } i.icon.arrow.circle.outline.right:before { content: "\f18e"; } i.icon.arrow.circle.outline.left:before { content: "\f190"; } i.icon.toggle.left:before { content: "\f191"; } /* Computer */ i.icon.power:before { content: "\f011"; } i.icon.trash:before { content: "\f1f8"; } i.icon.trash.outline:before { content: "\f014"; } i.icon.disk.outline:before { content: "\f0a0"; } i.icon.desktop:before { content: "\f108"; } i.icon.laptop:before { content: "\f109"; } i.icon.tablet:before { content: "\f10a"; } i.icon.mobile:before { content: "\f10b"; } i.icon.game:before { content: "\f11b"; } i.icon.keyboard:before { content: "\f11c"; } i.icon.plug:before { content: "\f1e6"; } /* File System */ i.icon.folder:before { content: "\f07b"; } i.icon.folder.open:before { content: "\f07c"; } i.icon.level.up:before { content: "\f148"; } i.icon.level.down:before { content: "\f149"; } i.icon.file:before { content: "\f15b"; } i.icon.file.outline:before { content: "\f016"; } i.icon.file.text:before { content: "\f15c"; } i.icon.file.text.outline:before { content: "\f0f6"; } i.icon.folder.outline:before { content: "\f114"; } i.icon.folder.open.outline:before { content: "\f115"; } i.icon.file.pdf.outline:before { content: "\f1c1"; } i.icon.file.word.outline:before { content: "\f1c2"; } i.icon.file.excel.outline:before { content: "\f1c3"; } i.icon.file.powerpoint.outline:before { content: "\f1c4"; } i.icon.file.image.outline:before { content: "\f1c5"; } i.icon.file.archive.outline:before { content: "\f1c6"; } i.icon.file.audio.outline:before { content: "\f1c7"; } i.icon.file.video.outline:before { content: "\f1c8"; } i.icon.file.code.outline:before { content: "\f1c9"; } /* Technologies */ i.icon.barcode:before { content: "\f02a"; } i.icon.qrcode:before { content: "\f029"; } i.icon.fork:before { content: "\f126"; } i.icon.html5:before { content: "\f13b"; } i.icon.css3:before { content: "\f13c"; } i.icon.rss:before { content: "\f09e"; } i.icon.rss.square:before { content: "\f143"; } i.icon.openid:before { content: "\f19b"; } i.icon.database:before { content: "\f1c0"; } i.icon.server:before { content: "\f233"; } /* Rating */ i.icon.heart:before { content: "\f004"; } i.icon.star:before { content: "\f005"; } i.icon.empty.star:before { content: "\f006"; } i.icon.thumbs.outline.up:before { content: "\f087"; } i.icon.thumbs.outline.down:before { content: "\f088"; } i.icon.star.half:before { content: "\f089"; } i.icon.empty.heart:before { content: "\f08a"; } i.icon.smile:before { content: "\f118"; } i.icon.frown:before { content: "\f119"; } i.icon.meh:before { content: "\f11a"; } i.icon.star.half.empty:before { content: "\f123"; } i.icon.thumbs.up:before { content: "\f164"; } i.icon.thumbs.down:before { content: "\f165"; } /* Audio */ i.icon.music:before { content: "\f001"; } i.icon.video.play.outline:before { content: "\f01d"; } i.icon.volume.off:before { content: "\f026"; } i.icon.volume.down:before { content: "\f027"; } i.icon.volume.up:before { content: "\f028"; } i.icon.record:before { content: "\f03d"; } i.icon.step.backward:before { content: "\f048"; } i.icon.fast.backward:before { content: "\f049"; } i.icon.backward:before { content: "\f04a"; } i.icon.play:before { content: "\f04b"; } i.icon.pause:before { content: "\f04c"; } i.icon.stop:before { content: "\f04d"; } i.icon.forward:before { content: "\f04e"; } i.icon.fast.forward:before { content: "\f050"; } i.icon.step.forward:before { content: "\f051"; } i.icon.eject:before { content: "\f052"; } i.icon.unmute:before { content: "\f130"; } i.icon.mute:before { content: "\f131"; } i.icon.video.play:before { content: "\f144"; } i.icon.closed.captioning:before { content: "\f20a"; } /* Map, Locations, & Transportation */ i.icon.marker:before { content: "\f041"; } i.icon.coffee:before { content: "\f0f4"; } i.icon.food:before { content: "\f0f5"; } i.icon.building.outline:before { content: "\f0f7"; } i.icon.hospital:before { content: "\f0f8"; } i.icon.emergency:before { content: "\f0f9"; } i.icon.first.aid:before { content: "\f0fa"; } i.icon.military:before { content: "\f0fb"; } i.icon.h:before { content: "\f0fd"; } i.icon.location.arrow:before { content: "\f124"; } i.icon.space.shuttle:before { content: "\f197"; } i.icon.university:before { content: "\f19c"; } i.icon.building:before { content: "\f1ad"; } i.icon.paw:before { content: "\f1b0"; } i.icon.spoon:before { content: "\f1b1"; } i.icon.car:before { content: "\f1b9"; } i.icon.taxi:before { content: "\f1ba"; } i.icon.tree:before { content: "\f1bb"; } i.icon.bicycle:before { content: "\f206"; } i.icon.bus:before { content: "\f207"; } i.icon.ship:before { content: "\f21a"; } i.icon.motorcycle:before { content: "\f21c"; } i.icon.street.view:before { content: "\f21d"; } i.icon.hotel:before { content: "\f236"; } i.icon.train:before { content: "\f238"; } i.icon.subway:before { content: "\f239"; } /* Tables */ i.icon.table:before { content: "\f0ce"; } i.icon.columns:before { content: "\f0db"; } i.icon.sort:before { content: "\f0dc"; } i.icon.sort.ascending:before { content: "\f0de"; } i.icon.sort.descending:before { content: "\f0dd"; } i.icon.sort.alphabet.ascending:before { content: "\f15d"; } i.icon.sort.alphabet.descending:before { content: "\f15e"; } i.icon.sort.content.ascending:before { content: "\f160"; } i.icon.sort.content.descending:before { content: "\f161"; } i.icon.sort.numeric.ascending:before { content: "\f162"; } i.icon.sort.numeric.descending:before { content: "\f163"; } /* Text Editor */ i.icon.font:before { content: "\f031"; } i.icon.bold:before { content: "\f032"; } i.icon.italic:before { content: "\f033"; } i.icon.text.height:before { content: "\f034"; } i.icon.text.width:before { content: "\f035"; } i.icon.align.left:before { content: "\f036"; } i.icon.align.center:before { content: "\f037"; } i.icon.align.right:before { content: "\f038"; } i.icon.align.justify:before { content: "\f039"; } i.icon.list:before { content: "\f03a"; } i.icon.outdent:before { content: "\f03b"; } i.icon.indent:before { content: "\f03c"; } i.icon.linkify:before { content: "\f0c1"; } i.icon.cut:before { content: "\f0c4"; } i.icon.copy:before { content: "\f0c5"; } i.icon.attach:before { content: "\f0c6"; } i.icon.save:before { content: "\f0c7"; } i.icon.content:before { content: "\f0c9"; } i.icon.unordered.list:before { content: "\f0ca"; } i.icon.ordered.list:before { content: "\f0cb"; } i.icon.strikethrough:before { content: "\f0cc"; } i.icon.underline:before { content: "\f0cd"; } i.icon.paste:before { content: "\f0ea"; } i.icon.unlink:before { content: "\f127"; } i.icon.superscript:before { content: "\f12b"; } i.icon.subscript:before { content: "\f12c"; } i.icon.header:before { content: "\f1dc"; } i.icon.paragraph:before { content: "\f1dd"; } /* Currency */ i.icon.euro:before { content: "\f153"; } i.icon.pound:before { content: "\f154"; } i.icon.dollar:before { content: "\f155"; } i.icon.rupee:before { content: "\f156"; } i.icon.yen:before { content: "\f157"; } i.icon.ruble:before { content: "\f158"; } i.icon.won:before { content: "\f159"; } i.icon.lira:before { content: "\f195"; } i.icon.shekel:before { content: "\f20b"; } /* Payment Options */ i.icon.paypal:before { content: "\f1ed"; } i.icon.paypal.card:before { content: "\f1f4"; } i.icon.google.wallet:before { content: "\f1ee"; } i.icon.visa:before { content: "\f1f0"; } i.icon.mastercard:before { content: "\f1f1"; } i.icon.discover:before { content: "\f1f2"; } i.icon.american.express:before { content: "\f1f3"; } i.icon.stripe:before { content: "\f1f5"; } /* Networks and Websites*/ i.icon.twitter.square:before { content: "\f081"; } i.icon.facebook.square:before { content: "\f082"; } i.icon.linkedin.square:before { content: "\f08c"; } i.icon.github.square:before { content: "\f092"; } i.icon.twitter:before { content: "\f099"; } i.icon.facebook:before { content: "\f09a"; } i.icon.github:before { content: "\f09b"; } i.icon.pinterest:before { content: "\f0d2"; } i.icon.pinterest.square:before { content: "\f0d3"; } i.icon.google.plus.square:before { content: "\f0d4"; } i.icon.google.plus:before { content: "\f0d5"; } i.icon.linkedin:before { content: "\f0e1"; } i.icon.github.alternate:before { content: "\f113"; } i.icon.maxcdn:before { content: "\f136"; } i.icon.bitcoin:before { content: "\f15a"; } i.icon.youtube.square:before { content: "\f166"; } i.icon.youtube:before { content: "\f167"; } i.icon.xing:before { content: "\f168"; } i.icon.xing.square:before { content: "\f169"; } i.icon.youtube.play:before { content: "\f16a"; } i.icon.dropbox:before { content: "\f16b"; } i.icon.stack.overflow:before { content: "\f16c"; } i.icon.instagram:before { content: "\f16d"; } i.icon.flickr:before { content: "\f16e"; } i.icon.adn:before { content: "\f170"; } i.icon.bitbucket:before { content: "\f171"; } i.icon.bitbucket.square:before { content: "\f172"; } i.icon.tumblr:before { content: "\f173"; } i.icon.tumblr.square:before { content: "\f174"; } i.icon.apple:before { content: "\f179"; } i.icon.windows:before { content: "\f17a"; } i.icon.android:before { content: "\f17b"; } i.icon.linux:before { content: "\f17c"; } i.icon.dribbble:before { content: "\f17d"; } i.icon.skype:before { content: "\f17e"; } i.icon.foursquare:before { content: "\f180"; } i.icon.trello:before { content: "\f181"; } i.icon.gittip:before { content: "\f184"; } i.icon.vk:before { content: "\f189"; } i.icon.weibo:before { content: "\f18a"; } i.icon.renren:before { content: "\f18b"; } i.icon.pagelines:before { content: "\f18c"; } i.icon.stack.exchange:before { content: "\f18d"; } i.icon.vimeo:before { content: "\f194"; } i.icon.slack:before { content: "\f198"; } i.icon.wordpress:before { content: "\f19a"; } i.icon.yahoo:before { content: "\f19e"; } i.icon.google:before { content: "\f1a0"; } i.icon.reddit:before { content: "\f1a1"; } i.icon.reddit.square:before { content: "\f1a2"; } i.icon.stumbleupon.circle:before { content: "\f1a3"; } i.icon.stumbleupon:before { content: "\f1a4"; } i.icon.delicious:before { content: "\f1a5"; } i.icon.digg:before { content: "\f1a6"; } i.icon.pied.piper:before { content: "\f1a7"; } i.icon.pied.piper.alternate:before { content: "\f1a8"; } i.icon.drupal:before { content: "\f1a9"; } i.icon.joomla:before { content: "\f1aa"; } i.icon.behance:before { content: "\f1b4"; } i.icon.behance.square:before { content: "\f1b5"; } i.icon.steam:before { content: "\f1b6"; } i.icon.steam.square:before { content: "\f1b7"; } i.icon.spotify:before { content: "\f1bc"; } i.icon.deviantart:before { content: "\f1bd"; } i.icon.soundcloud:before { content: "\f1be"; } i.icon.vine:before { content: "\f1ca"; } i.icon.codepen:before { content: "\f1cb"; } i.icon.jsfiddle:before { content: "\f1cc"; } i.icon.rebel:before { content: "\f1d0"; } i.icon.empire:before { content: "\f1d1"; } i.icon.git.square:before { content: "\f1d2"; } i.icon.git:before { content: "\f1d3"; } i.icon.hacker.news:before { content: "\f1d4"; } i.icon.tencent.weibo:before { content: "\f1d5"; } i.icon.qq:before { content: "\f1d6"; } i.icon.wechat:before { content: "\f1d7"; } i.icon.slideshare:before { content: "\f1e7"; } i.icon.twitch:before { content: "\f1e8"; } i.icon.yelp:before { content: "\f1e9"; } i.icon.lastfm:before { content: "\f202"; } i.icon.lastfm.square:before { content: "\f203"; } i.icon.ioxhost:before { content: "\f208"; } i.icon.angellist:before { content: "\f209"; } i.icon.meanpath:before { content: "\f20c"; } i.icon.buysellads:before { content: "\f20d"; } i.icon.connectdevelop:before { content: "\f20e"; } i.icon.dashcube:before { content: "\f210"; } i.icon.forumbee:before { content: "\f211"; } i.icon.leanpub:before { content: "\f212"; } i.icon.sellsy:before { content: "\f213"; } i.icon.shirtsinbulk:before { content: "\f214"; } i.icon.simplybuilt:before { content: "\f215"; } i.icon.skyatlas:before { content: "\f216"; } i.icon.whatsapp:before { content: "\f232"; } i.icon.viacoin:before { content: "\f237"; } i.icon.medium:before { content: "\f23a"; } /******************************* Aliases *******************************/ i.icon.like:before { content: "\f004"; } i.icon.favorite:before { content: "\f005"; } i.icon.video:before { content: "\f008"; } i.icon.check:before { content: "\f00c"; } i.icon.close:before { content: "\f00d"; } i.icon.cancel:before { content: "\f00d"; } i.icon.delete:before { content: "\f00d"; } i.icon.x:before { content: "\f00d"; } i.icon.user.times:before { content: "\f235"; } i.icon.user.close:before { content: "\f235"; } i.icon.user.cancel:before { content: "\f235"; } i.icon.user.delete:before { content: "\f235"; } i.icon.user.x:before { content: "\f235"; } i.icon.zoom.in:before { content: "\f00e"; } i.icon.magnify:before { content: "\f00e"; } i.icon.shutdown:before { content: "\f011"; } i.icon.clock:before { content: "\f017"; } i.icon.time:before { content: "\f017"; } i.icon.play.circle.outline:before { content: "\f01d"; } i.icon.headphone:before { content: "\f025"; } i.icon.camera:before { content: "\f030"; } i.icon.video.camera:before { content: "\f03d"; } i.icon.picture:before { content: "\f03e"; } i.icon.pencil:before { content: "\f040"; } i.icon.compose:before { content: "\f040"; } i.icon.point:before { content: "\f041"; } i.icon.tint:before { content: "\f043"; } i.icon.signup:before { content: "\f044"; } i.icon.plus.circle:before { content: "\f055"; } i.icon.dont:before { content: "\f05e"; } i.icon.minimize:before { content: "\f066"; } i.icon.add:before { content: "\f067"; } i.icon.eye:before { content: "\f06e"; } i.icon.attention:before { content: "\f06a"; } i.icon.cart:before { content: "\f07a"; } i.icon.shuffle:before { content: "\f074"; } i.icon.talk:before { content: "\f075"; } i.icon.chat:before { content: "\f075"; } i.icon.shopping.cart:before { content: "\f07a"; } i.icon.bar.graph:before { content: "\f080"; } i.icon.area.graph:before { content: "\f1fe"; } i.icon.pie.graph:before { content: "\f200"; } i.icon.line.graph:before { content: "\f201"; } i.icon.key:before { content: "\f084"; } i.icon.cogs:before { content: "\f085"; } i.icon.discussions:before { content: "\f086"; } i.icon.like.outline:before { content: "\f087"; } i.icon.dislike.outline:before { content: "\f088"; } i.icon.heart.outline:before { content: "\f08a"; } i.icon.log.out:before { content: "\f08b"; } i.icon.thumb.tack:before { content: "\f08d"; } i.icon.winner:before { content: "\f091"; } i.icon.bookmark.outline:before { content: "\f097"; } i.icon.phone:before { content: "\f095"; } i.icon.phone.square:before { content: "\f098"; } i.icon.credit.card:before { content: "\f09d"; } i.icon.hdd.outline:before { content: "\f0a0"; } i.icon.bullhorn:before { content: "\f0a1"; } i.icon.bell:before { content: "\f0f3"; } i.icon.bell.outline:before { content: "\f0a2"; } i.icon.bell.slash:before { content: "\f1f6"; } i.icon.bell.slash.outline:before { content: "\f1f7"; } i.icon.hand.outline.right:before { content: "\f0a4"; } i.icon.hand.outline.left:before { content: "\f0a5"; } i.icon.hand.outline.up:before { content: "\f0a6"; } i.icon.hand.outline.down:before { content: "\f0a7"; } i.icon.globe:before { content: "\f0ac"; } i.icon.wrench:before { content: "\f0ad"; } i.icon.briefcase:before { content: "\f0b1"; } i.icon.group:before { content: "\f0c0"; } i.icon.flask:before { content: "\f0c3"; } i.icon.sidebar:before { content: "\f0c9"; } i.icon.bars:before { content: "\f0c9"; } i.icon.list.ul:before { content: "\f0ca"; } i.icon.list.ol:before { content: "\f0cb"; } i.icon.numbered.list:before { content: "\f0cb"; } i.icon.magic:before { content: "\f0d0"; } i.icon.truck:before { content: "\f0d1"; } i.icon.currency:before { content: "\f0d6"; } i.icon.triangle.down:before { content: "\f0d7"; } i.icon.dropdown:before { content: "\f0d7"; } i.icon.triangle.up:before { content: "\f0d8"; } i.icon.triangle.left:before { content: "\f0d9"; } i.icon.triangle.right:before { content: "\f0da"; } i.icon.envelope:before { content: "\f0e0"; } i.icon.conversation:before { content: "\f0e6"; } i.icon.umbrella:before { content: "\f0e9"; } i.icon.lightbulb:before { content: "\f0eb"; } i.icon.ambulance:before { content: "\f0f9"; } i.icon.medkit:before { content: "\f0fa"; } i.icon.fighter.jet:before { content: "\f0fb"; } i.icon.beer:before { content: "\f0fc"; } i.icon.plus.square:before { content: "\f0fe"; } i.icon.computer:before { content: "\f108"; } i.icon.circle.outline:before { content: "\f10c"; } i.icon.intersex:before { content: "\f10c"; } i.icon.asexual:before { content: "\f10c"; } i.icon.spinner:before { content: "\f110"; } i.icon.gamepad:before { content: "\f11b"; } i.icon.star.half.full:before { content: "\f123"; } i.icon.question:before { content: "\f128"; } i.icon.eraser:before { content: "\f12d"; } i.icon.microphone:before { content: "\f130"; } i.icon.microphone.slash:before { content: "\f131"; } i.icon.shield:before { content: "\f132"; } i.icon.target:before { content: "\f140"; } i.icon.play.circle:before { content: "\f144"; } i.icon.pencil.square:before { content: "\f14b"; } i.icon.compass:before { content: "\f14e"; } i.icon.amex:before { content: "\f1f3"; } i.icon.eur:before { content: "\f153"; } i.icon.gbp:before { content: "\f154"; } i.icon.usd:before { content: "\f155"; } i.icon.inr:before { content: "\f156"; } i.icon.cny:before, i.icon.rmb:before, i.icon.jpy:before { content: "\f157"; } i.icon.rouble:before, i.icon.rub:before { content: "\f158"; } i.icon.krw:before { content: "\f159"; } i.icon.btc:before { content: "\f15a"; } i.icon.sheqel:before, i.icon.ils:before { content: "\f20b"; } i.icon.try:before { content: "\f195"; } i.icon.zip:before { content: "\f187"; } i.icon.dot.circle.outline:before { content: "\f192"; } i.icon.sliders:before { content: "\f1de"; } i.icon.wi-fi:before { content: "\f1eb"; } i.icon.graduation:before { content: "\f19d"; } i.icon.weixin:before { content: "\f1d7"; } i.icon.binoculars:before { content: "\f1e5"; } i.icon.gratipay:before { content: "\f184"; } i.icon.genderless:before { content: "\f1db"; } i.icon.teletype:before { content: "\f1e4"; } i.icon.power.cord:before { content: "\f1e6"; } i.icon.tty:before { content: "\f1e4"; } i.icon.cc:before { content: "\f20a"; } i.icon.plus.cart:before { content: "\f217"; } i.icon.arrow.down.cart:before { content: "\f218"; } i.icon.detective:before { content: "\f21b"; } i.icon.venus:before { content: "\f221"; } i.icon.mars:before { content: "\f222"; } i.icon.mercury:before { content: "\f223"; } i.icon.venus.double:before { content: "\f226"; } i.icon.female.homosexual:before { content: "\f226"; } i.icon.mars.double:before { content: "\f227"; } i.icon.male.homosexual:before { content: "\f227"; } i.icon.venus.mars:before { content: "\f228"; } i.icon.mars.stroke:before { content: "\f229"; } i.icon.mars.alternate:before { content: "\f229"; } i.icon.mars.vertical:before { content: "\f22a"; } i.icon.mars.horizontal:before { content: "\f22b"; } i.icon.mars.stroke.vertical:before { content: "\f22a"; } i.icon.mars.stroke.horizontal:before { content: "\f22b"; } i.icon.facebook.official { content: "\f230"; } i.icon.pinterest.official { content: "\f231"; } i.icon.bed:before { content: "\f236"; } /******************************* Site Overrides *******************************/
gpl-3.0
orlera/introsde
lab09/Server/src/introsde/document/ws/PeopleImpl.java
1425
package introsde.document.ws; import introsde.document.model.LifeStatus; import introsde.document.model.Person; import java.util.List; import javax.jws.WebService; //Service Implementation @WebService(endpointInterface = "introsde.document.ws.People", serviceName="PeopleService") public class PeopleImpl implements People { @Override public Person readPerson(int id) { System.out.println("---> Reading Person by id = "+id); Person p = Person.getPersonById(id); if (p!=null) { System.out.println("---> Found Person by id = "+id+" => "+p.getName()); } else { System.out.println("---> Didn't find any Person with id = "+id); } return p; } @Override public List<Person> getPeople() { return Person.getAll(); } @Override public int addPerson(Person person) { Person.savePerson(person); return person.getIdPerson(); } @Override public int updatePerson(Person person) { Person.updatePerson(person); return person.getIdPerson(); } @Override public int deletePerson(int id) { Person p = Person.getPersonById(id); if (p!=null) { Person.removePerson(p); return 0; } else { return -1; } } @Override public int updatePersonHP(int id, LifeStatus hp) { LifeStatus ls = LifeStatus.getLifeStatusById(hp.getIdMeasure()); if (ls.getPerson().getIdPerson() == id) { LifeStatus.updateLifeStatus(hp); return hp.getIdMeasure(); } else { return -1; } } }
gpl-3.0
gwq5210/litlib
thirdparty/sources/boost_1_60_0/doc/html/boost_asio/reference/basic_datagram_socket/send/overload1.html
7465
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_datagram_socket::send (1 of 3 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../send.html" title="basic_datagram_socket::send"> <link rel="prev" href="../send.html" title="basic_datagram_socket::send"> <link rel="next" href="overload2.html" title="basic_datagram_socket::send (2 of 3 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../send.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_datagram_socket.send.overload1"></a><a class="link" href="overload1.html" title="basic_datagram_socket::send (1 of 3 overloads)">basic_datagram_socket::send (1 of 3 overloads)</a> </h5></div></div></div> <p> Send some data on a connected socket. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="../../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">send</span><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">);</span> </pre> <p> This function is used to send data on the datagram socket. The function call will block until the data has been sent successfully or an error occurs. </p> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload1.h0"></a> <span class="phrase"><a name="boost_asio.reference.basic_datagram_socket.send.overload1.parameters"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_datagram_socket.send.overload1.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl class="variablelist"> <dt><span class="term">buffers</span></dt> <dd><p> One ore more data buffers to be sent on the socket. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload1.h1"></a> <span class="phrase"><a name="boost_asio.reference.basic_datagram_socket.send.overload1.return_value"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_datagram_socket.send.overload1.return_value">Return Value</a> </h6> <p> The number of bytes sent. </p> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload1.h2"></a> <span class="phrase"><a name="boost_asio.reference.basic_datagram_socket.send.overload1.exceptions"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_datagram_socket.send.overload1.exceptions">Exceptions</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl class="variablelist"> <dt><span class="term">boost::system::system_error</span></dt> <dd><p> Thrown on failure. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload1.h3"></a> <span class="phrase"><a name="boost_asio.reference.basic_datagram_socket.send.overload1.remarks"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_datagram_socket.send.overload1.remarks">Remarks</a> </h6> <p> The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected datagram socket. </p> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload1.h4"></a> <span class="phrase"><a name="boost_asio.reference.basic_datagram_socket.send.overload1.example"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_datagram_socket.send.overload1.example">Example</a> </h6> <p> To send a single data buffer use the <a class="link" href="../../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> function as follows: </p> <pre class="programlisting"><span class="identifier">socket</span><span class="special">.</span><span class="identifier">send</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">buffer</span><span class="special">(</span><span class="identifier">data</span><span class="special">,</span> <span class="identifier">size</span><span class="special">));</span> </pre> <p> See the <a class="link" href="../../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../send.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
gpl-3.0
happyjack27/autoredistrict
src/org/apache/commons/math3/linear/FieldDecompositionSolver.java
3261
/* * 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.commons.math3.linear; import org.apache.commons.math3.FieldElement; /** * Interface handling decomposition algorithms that can solve A &times; X = B. * <p>Decomposition algorithms decompose an A matrix has a product of several specific * matrices from which they can solve A &times; X = B in least squares sense: they find X * such that ||A &times; X - B|| is minimal.</p> * <p>Some solvers like {@link FieldLUDecomposition} can only find the solution for * square matrices and when the solution is an exact linear solution, i.e. when * ||A &times; X - B|| is exactly 0. Other solvers can also find solutions * with non-square matrix A and with non-null minimal norm. If an exact linear * solution exists it is also the minimal norm solution.</p> * * @param <T> the type of the field elements * @since 2.0 */ public interface FieldDecompositionSolver<T extends FieldElement<T>> { /** Solve the linear equation A &times; X = B for matrices A. * <p>The A matrix is implicit, it is provided by the underlying * decomposition algorithm.</p> * @param b right-hand side of the equation A &times; X = B * @return a vector X that minimizes the two norm of A &times; X - B * @throws org.apache.commons.math3.exception.DimensionMismatchException * if the matrices dimensions do not match. * @throws SingularMatrixException * if the decomposed matrix is singular. */ FieldVector<T> solve(final FieldVector<T> b); /** Solve the linear equation A &times; X = B for matrices A. * <p>The A matrix is implicit, it is provided by the underlying * decomposition algorithm.</p> * @param b right-hand side of the equation A &times; X = B * @return a matrix X that minimizes the two norm of A &times; X - B * @throws org.apache.commons.math3.exception.DimensionMismatchException * if the matrices dimensions do not match. * @throws SingularMatrixException * if the decomposed matrix is singular. */ FieldMatrix<T> solve(final FieldMatrix<T> b); /** * Check if the decomposed matrix is non-singular. * @return true if the decomposed matrix is non-singular */ boolean isNonSingular(); /** Get the inverse (or pseudo-inverse) of the decomposed matrix. * @return inverse matrix * @throws SingularMatrixException * if the decomposed matrix is singular. */ FieldMatrix<T> getInverse(); }
gpl-3.0
micaherne/moodle
question/type/calculated/lib.php
1284
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Serve question type files * * @since 2.0 * @package qtype * @subpackage calculated * @copyright Dongsheng Cai <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Checks file access for calculated questions. */ function qtype_calculated_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) { global $CFG; require_once($CFG->libdir . '/questionlib.php'); question_pluginfile($course, $context, 'qtype_calculated', $filearea, $args, $forcedownload); }
gpl-3.0
RomeroMalaquias/rsyslog
tests/libdbi-basic-vg.sh
852
#!/bin/bash # This file is part of the rsyslog project, released under GPLv3 # this test is currently not included in the testbench as libdbi # itself seems to have a memory leak echo =============================================================================== echo \[libdbi-basic.sh\]: basic test for libdbi-basic functionality via mysql . $srcdir/diag.sh init mysql --user=rsyslog --password=testbench < testsuites/mysql-truncate.sql . $srcdir/diag.sh startup-vg-noleak libdbi-basic.conf . $srcdir/diag.sh injectmsg 0 5000 . $srcdir/diag.sh shutdown-when-empty . $srcdir/diag.sh wait-shutdown-vg . $srcdir/diag.sh check-exit-vg # note "-s" is requried to suppress the select "field header" mysql -s --user=rsyslog --password=testbench < testsuites/mysql-select-msg.sql > rsyslog.out.log . $srcdir/diag.sh seq-check 0 4999 . $srcdir/diag.sh exit
gpl-3.0
genome/genome
lib/perl/Genome/Model/Tools/Sx/Trim.pm
254
package Genome::Model::Tools::Sx::Trim; use strict; use warnings; use Genome; use Data::Dumper 'Dumper'; class Genome::Model::Tools::Sx::Trim { is => 'Command::Tree', is_abstract => 1, }; sub help_brief { return 'Trim sequences'; } 1;
lgpl-3.0