code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* bnx2.c: QLogic NX2 network driver. * * Copyright (c) 2009-2014 QLogic Corporation * * 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. * * Written by: Michael Chan (mchan@broadcom.com) */ #include <linux/version.h> #if (LINUX_VERSION_CODE < 0x020612) #include <linux/config.h> #endif #if (LINUX_VERSION_CODE < 0x020500) #if defined(CONFIG_MODVERSIONS) && defined(MODULE) && ! defined(MODVERSIONS) #define MODVERSIONS #include <linux/modversions.h> #endif #endif #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #if (LINUX_VERSION_CODE >= 0x020600) #include <linux/moduleparam.h> #endif #include <linux/stringify.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #if (LINUX_VERSION_CODE >= 0x020600) #include <linux/dma-mapping.h> #endif #include <linux/bitops.h> #include <asm/io.h> #include <asm/irq.h> #include <linux/delay.h> #include <asm/byteorder.h> #include <asm/page.h> #include <linux/time.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/if_vlan.h> #if defined(CONFIG_VLAN_8021Q) || defined(CONFIG_VLAN_8021Q_MODULE) #define BCM_VLAN 1 #endif #ifdef NETIF_F_TSO #include <net/ip.h> #include <net/tcp.h> #include <net/checksum.h> #define BCM_TSO 1 #endif #if (LINUX_VERSION_CODE >= 0x020600) #include <linux/workqueue.h> #endif #ifndef BNX2_BOOT_DISK #include <linux/crc32.h> #endif #include <linux/prefetch.h> #include <linux/cache.h> #include <linux/zlib.h> #if (LINUX_VERSION_CODE >= 0x20617) && !defined(NETIF_F_MULTI_QUEUE) #include <linux/log2.h> #endif #ifdef HAVE_AER #include <linux/aer.h> #endif #if (LINUX_VERSION_CODE >= 0x020610) #define BCM_CNIC 1 #include "cnic_if.h" #endif #include "bnx2_compat0.h" #include "bnx2_compat.h" #include "bnx2.h" #include "bnx2_fw.h" #include "bnx2_fw2.h" #define DRV_MODULE_NAME "bnx2" #define DRV_MODULE_VERSION "2.2.4f.v60.10" #define DRV_MODULE_RELDATE "May 21, 2014" #define RUN_AT(x) (jiffies + (x)) /* Time in jiffies before concluding the transmitter is hung. */ #if defined(__VMKLNX__) /* On VMware ESX there is a possibility that that netdev watchdog thread * runs before the reset task if the machine is loaded. If this occurs * too many times, these premature watchdog triggers will cause a PSOD * on a VMware ESX beta build */ #define TX_TIMEOUT (20*HZ) #else #define TX_TIMEOUT (5*HZ) #endif /* defined(__VMKLNX__) */ #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) #include "cnic_register.h" static int bnx2_registered_cnic_adapter; #endif /* defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000)*/ static char version[] __devinitdata = "QLogic NetXtreme II Gigabit Ethernet Driver " DRV_MODULE_NAME " v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n"; MODULE_AUTHOR("Michael Chan <mchan@broadcom.com>"); MODULE_DESCRIPTION("QLogic NetXtreme II BCM5706/5708/5709/5716 Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_MODULE_VERSION); static int disable_msi = 0; static int debug; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) /* BNX2X_UPSTREAM */ module_param(debug, int, 0); MODULE_PARM_DESC(debug, " Default debug msglevel"); #endif #if (LINUX_VERSION_CODE >= 0x20600) module_param(disable_msi, int, 0); MODULE_PARM_DESC(disable_msi, "Disable Message Signaled Interrupt (MSI)"); #endif static int stop_on_tx_timeout = 0; module_param(stop_on_tx_timeout, int, 0); MODULE_PARM_DESC(stop_on_tx_timeout, "For debugging purposes, prevent a chip " " reset when a tx timeout occurs"); #if defined(__VMKLNX__) static int psod_on_tx_timeout; module_param(psod_on_tx_timeout, int, 0); MODULE_PARM_DESC(psod_on_tx_timeout, "For debugging purposes, crash the system " " when a tx timeout occurs"); static int disable_msi_1shot = 0; module_param(disable_msi_1shot, int, 0); MODULE_PARM_DESC(disable_msi_1shot, "For debugging purposes, disable 1shot " " MSI mode if set to value of 1"); #if (VMWARE_ESX_DDK_VERSION >= 55000) static int disable_fw_dmp; module_param(disable_fw_dmp, int, 0); MODULE_PARM_DESC(disable_fw_dmp, "For debugging purposes, disable firmware " "dump feature when set to value of 1"); #endif #endif #define BNX2_MAX_NIC 32 #ifdef BNX2_ENABLE_NETQUEUE #define BNX2_OPTION_UNSET -1 #define BNX2_OPTION_ZERO 0 #define BNX2_NETQUEUE_ENABLED(bp) ((force_netq_param[bp->index] > 1) || \ (force_netq_param[bp->index] == \ BNX2_OPTION_UNSET)) #define BNX2_NETQUEUE_DISABLED(bp) (force_netq_param[bp->index] == 0) static int __devinitdata force_netq_param[BNX2_MAX_NIC+1] = { [0 ... BNX2_MAX_NIC] = BNX2_OPTION_UNSET }; static unsigned int num_force_netq; module_param_array_named(force_netq, force_netq_param, int, &num_force_netq, 0); MODULE_PARM_DESC(force_netq, "Option used for 5709/5716 only: " "Enforce the number of NetQueues per port " "(allowed values: -1 to 7 queues: " "1-7 will force the number of NetQueues for the " " given device, " "0 to disable NetQueue, " "-1 to use the default driver NetQueues value) " "[Maximum supported NIC's = 32] " "[example usage: force_net=-1,0,1,2: " "This corresponds to the first 5709/5716 to use " "the default number of NetQueues, " "disable NetQueue on the second 5709/5716, " "use 1 NetQueue on the third 5709/5716" "use 2 NetQueues on the fourth 5709/5716]"); #endif /* BNX2_ENABLE_NETQUEUE */ #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) #include <vmklinux_9/vmklinux_dump.h> #define BNX2_DUMPNAME "bnx2_fwdmp" static vmklnx_DumpFileHandle bnx2_fwdmp_dh; static void *fwdmp_va_ptr; static struct bnx2 *fwdmp_bp_ptr[BNX2_MAX_NIC]; static VMK_ReturnStatus bnx2_fwdmp_callback(void *cookie, vmk_Bool liveDump); #endif typedef enum { BCM5706 = 0, NC370T, NC370I, BCM5706S, NC370F, BCM5708, BCM5708S, BCM5709, BCM5709S, BCM5716, BCM5716S, } board_t; /* indexed by board_t, above */ static struct { char *name; } board_info[] __devinitdata = { { "QLogic NetXtreme II BCM5706 1000Base-T" }, { "HP NC370T Multifunction Gigabit Server Adapter" }, { "HP NC370i Multifunction Gigabit Server Adapter" }, { "QLogic NetXtreme II BCM5706 1000Base-SX" }, { "HP NC370F Multifunction Gigabit Server Adapter" }, { "QLogic NetXtreme II BCM5708 1000Base-T" }, { "QLogic NetXtreme II BCM5708 1000Base-SX" }, { "QLogic NetXtreme II BCM5709 1000Base-T" }, { "QLogic NetXtreme II BCM5709 1000Base-SX" }, { "QLogic NetXtreme II BCM5716 1000Base-T" }, { "QLogic NetXtreme II BCM5716 1000Base-SX" }, }; static DEFINE_PCI_DEVICE_TABLE(bnx2_pci_tbl) = { { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, PCI_VENDOR_ID_HP, 0x3101, 0, 0, NC370T }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, PCI_VENDOR_ID_HP, 0x3106, 0, 0, NC370I }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5706 }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5708, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5708 }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706S, PCI_VENDOR_ID_HP, 0x3102, 0, 0, NC370F }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5706S, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5706S }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5708S, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5708S }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5709, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5709 }, { PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_NX2_5709S, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5709S }, { PCI_VENDOR_ID_BROADCOM, 0x163b, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5716 }, { PCI_VENDOR_ID_BROADCOM, 0x163c, PCI_ANY_ID, PCI_ANY_ID, 0, 0, BCM5716S }, { 0, } }; static const struct flash_spec flash_table[] = { #define BUFFERED_FLAGS (BNX2_NV_BUFFERED | BNX2_NV_TRANSLATE) #define NONBUFFERED_FLAGS (BNX2_NV_WREN) /* Slow EEPROM */ {0x00000000, 0x40830380, 0x009f0081, 0xa184a053, 0xaf000400, BUFFERED_FLAGS, SEEPROM_PAGE_BITS, SEEPROM_PAGE_SIZE, SEEPROM_BYTE_ADDR_MASK, SEEPROM_TOTAL_SIZE, "EEPROM - slow"}, /* Expansion entry 0001 */ {0x08000002, 0x4b808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 0001"}, /* Saifun SA25F010 (non-buffered flash) */ /* strap, cfg1, & write1 need updates */ {0x04000001, 0x47808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, SAIFUN_FLASH_BASE_TOTAL_SIZE*2, "Non-buffered flash (128kB)"}, /* Saifun SA25F020 (non-buffered flash) */ /* strap, cfg1, & write1 need updates */ {0x0c000003, 0x4f808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, SAIFUN_FLASH_BASE_TOTAL_SIZE*4, "Non-buffered flash (256kB)"}, /* Expansion entry 0100 */ {0x11000000, 0x53808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 0100"}, /* Entry 0101: ST M45PE10 (non-buffered flash, TetonII B0) */ {0x19000002, 0x5b808201, 0x000500db, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, ST_MICRO_FLASH_PAGE_BITS, ST_MICRO_FLASH_PAGE_SIZE, ST_MICRO_FLASH_BYTE_ADDR_MASK, ST_MICRO_FLASH_BASE_TOTAL_SIZE*2, "Entry 0101: ST M45PE10 (128kB non-bufferred)"}, /* Entry 0110: ST M45PE20 (non-buffered flash)*/ {0x15000001, 0x57808201, 0x000500db, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, ST_MICRO_FLASH_PAGE_BITS, ST_MICRO_FLASH_PAGE_SIZE, ST_MICRO_FLASH_BYTE_ADDR_MASK, ST_MICRO_FLASH_BASE_TOTAL_SIZE*4, "Entry 0110: ST M45PE20 (256kB non-bufferred)"}, /* Saifun SA25F005 (non-buffered flash) */ /* strap, cfg1, & write1 need updates */ {0x1d000003, 0x5f808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, SAIFUN_FLASH_BASE_TOTAL_SIZE, "Non-buffered flash (64kB)"}, /* Fast EEPROM */ {0x22000000, 0x62808380, 0x009f0081, 0xa184a053, 0xaf000400, BUFFERED_FLAGS, SEEPROM_PAGE_BITS, SEEPROM_PAGE_SIZE, SEEPROM_BYTE_ADDR_MASK, SEEPROM_TOTAL_SIZE, "EEPROM - fast"}, /* Expansion entry 1001 */ {0x2a000002, 0x6b808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1001"}, /* Expansion entry 1010 */ {0x26000001, 0x67808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1010"}, /* ATMEL AT45DB011B (buffered flash) */ {0x2e000003, 0x6e808273, 0x00570081, 0x68848353, 0xaf000400, BUFFERED_FLAGS, BUFFERED_FLASH_PAGE_BITS, BUFFERED_FLASH_PAGE_SIZE, BUFFERED_FLASH_BYTE_ADDR_MASK, BUFFERED_FLASH_TOTAL_SIZE, "Buffered flash (128kB)"}, /* Expansion entry 1100 */ {0x33000000, 0x73808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1100"}, /* Expansion entry 1101 */ {0x3b000002, 0x7b808201, 0x00050081, 0x03840253, 0xaf020406, NONBUFFERED_FLAGS, SAIFUN_FLASH_PAGE_BITS, SAIFUN_FLASH_PAGE_SIZE, SAIFUN_FLASH_BYTE_ADDR_MASK, 0, "Entry 1101"}, /* Ateml Expansion entry 1110 */ {0x37000001, 0x76808273, 0x00570081, 0x68848353, 0xaf000400, BUFFERED_FLAGS, BUFFERED_FLASH_PAGE_BITS, BUFFERED_FLASH_PAGE_SIZE, BUFFERED_FLASH_BYTE_ADDR_MASK, 0, "Entry 1110 (Atmel)"}, /* ATMEL AT45DB021B (buffered flash) */ {0x3f000003, 0x7e808273, 0x00570081, 0x68848353, 0xaf000400, BUFFERED_FLAGS, BUFFERED_FLASH_PAGE_BITS, BUFFERED_FLASH_PAGE_SIZE, BUFFERED_FLASH_BYTE_ADDR_MASK, BUFFERED_FLASH_TOTAL_SIZE*2, "Buffered flash (256kB)"}, }; static const struct flash_spec flash_5709 = { .flags = BNX2_NV_BUFFERED, .page_bits = BCM5709_FLASH_PAGE_BITS, .page_size = BCM5709_FLASH_PAGE_SIZE, .addr_mask = BCM5709_FLASH_BYTE_ADDR_MASK, .total_size = BUFFERED_FLASH_TOTAL_SIZE*2, .name = "5709 Buffered flash (256kB)", }; MODULE_DEVICE_TABLE(pci, bnx2_pci_tbl); #if !defined(__VMKLNX__) static void bnx2_init_napi(struct bnx2 *bp); static void bnx2_del_napi(struct bnx2 *bp); #else static void __devinit bnx2_init_napi(struct bnx2 *bp); static void __devexit bnx2_del_napi(struct bnx2 *bp); #endif static void bnx2_set_rx_ring_size(struct bnx2 *bp, u32 size); #if defined(__VMKLNX__) static int bnx2_tx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget, int check_queue); #endif /* defined(__VMKLNX__) */ #if defined(BNX2_ENABLE_NETQUEUE) static int bnx2_netqueue_ops(vmknetddi_queueops_op_t op, void *args); static void bnx2_stop_netqueue_hw(struct bnx2 *bp); static void bnx2_start_netqueue_hw(struct bnx2 *bp); static void bnx2_netqueue_service_bnx2_msix(struct bnx2_napi *bnapi); static int bnx2_netqueue_is_avail(struct bnx2 *bp); static void bnx2_close_netqueue_hw(struct bnx2 *bp); static void bnx2_init_netqueue_hw(struct bnx2 *bp); static int bnx2_open_netqueue_hw(struct bnx2 *bp); static void bnx2_netqueue_flush_all(struct bnx2 *bp); static int bnx2_netqueue_open_started(struct bnx2 *bp); static void bnx2_close_netqueue(struct bnx2 *bp); static void bnx2_start_netqueue(struct bnx2 *bp); static void bnx2_stop_netqueue(struct bnx2 *bp); static void bnx2_force_stop_netqueue(struct bnx2 * bp); static inline u16 bnx2_get_hw_tx_cons(struct bnx2_napi *bnapi); static inline u16 bnx2_get_hw_rx_cons(struct bnx2_napi *bnapi); #ifdef BNX2_DEBUG static u32 bnx2_read_ctx(struct bnx2 *bp, u32 offset); #endif static int bnx2_netq_alloc_tx_queue(struct bnx2 *bp, struct bnx2_napi *bnapi, int index); #define TRUE 1 #define FALSE 0 #define for_each_nondefault_rx_queue(bp, var) \ for (var = 1; var < bp->num_rx_rings; var++) #define for_each_nondefault_tx_queue(bp, var) \ for (var = 1; var < bp->num_tx_rings; var++) #define is_multi(bp) (bp->num_rx_ring > 1) #endif /* defined(BNX2_ENABLE_NETQUEUE) */ #ifdef BNX2_BOOT_DISK u32 ether_crc_le(size_t len, unsigned char const *p) { u32 crc = ~0; int i; #define CRCPOLY_LE 0xedb88320 while (len--) { crc ^= *p++; for (i = 0; i < 8; i++) crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0); } return crc; } #endif static inline u32 bnx2_tx_avail(struct bnx2 *bp, struct bnx2_tx_ring_info *txr) { u32 diff; /* Tell compiler to fetch tx_prod and tx_cons from memory. */ barrier(); /* The ring uses 256 indices for 255 entries, one of them * needs to be skipped. */ diff = txr->tx_prod - txr->tx_cons; if (unlikely(diff >= BNX2_TX_DESC_CNT)) { diff &= 0xffff; if (diff == BNX2_TX_DESC_CNT) diff = BNX2_MAX_TX_DESC_CNT; } return bp->tx_ring_size - diff; } static u32 bnx2_reg_rd_ind(struct bnx2 *bp, u32 offset) { u32 val; spin_lock_bh(&bp->indirect_lock); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, offset); val = BNX2_RD(bp, BNX2_PCICFG_REG_WINDOW); spin_unlock_bh(&bp->indirect_lock); return val; } static void bnx2_reg_wr_ind(struct bnx2 *bp, u32 offset, u32 val) { spin_lock_bh(&bp->indirect_lock); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, offset); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW, val); spin_unlock_bh(&bp->indirect_lock); } #if defined(__VMKLNX__) static void bnx2_reg_wr_ind_cfg(struct bnx2 *bp, u32 offset, u32 val) { struct pci_dev *pdev = bp->pdev; spin_lock_bh(&bp->indirect_lock); pci_write_config_dword(pdev, BNX2_PCICFG_REG_WINDOW_ADDRESS, offset); pci_write_config_dword(pdev, BNX2_PCICFG_REG_WINDOW, val); spin_unlock_bh(&bp->indirect_lock); } #endif /* defined(__VMKLNX__) */ static void bnx2_shmem_wr(struct bnx2 *bp, u32 offset, u32 val) { bnx2_reg_wr_ind(bp, bp->shmem_base + offset, val); } static u32 bnx2_shmem_rd(struct bnx2 *bp, u32 offset) { return bnx2_reg_rd_ind(bp, bp->shmem_base + offset); } static void bnx2_ctx_wr(struct bnx2 *bp, u32 cid_addr, u32 offset, u32 val) { offset += cid_addr; spin_lock_bh(&bp->indirect_lock); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { int i; BNX2_WR(bp, BNX2_CTX_CTX_DATA, val); BNX2_WR(bp, BNX2_CTX_CTX_CTRL, offset | BNX2_CTX_CTX_CTRL_WRITE_REQ); for (i = 0; i < 5; i++) { val = BNX2_RD(bp, BNX2_CTX_CTX_CTRL); if ((val & BNX2_CTX_CTX_CTRL_WRITE_REQ) == 0) break; udelay(5); } } else { BNX2_WR(bp, BNX2_CTX_DATA_ADR, offset); BNX2_WR(bp, BNX2_CTX_DATA, val); } spin_unlock_bh(&bp->indirect_lock); } #ifdef BCM_CNIC static int bnx2_drv_ctl(struct net_device *dev, struct drv_ctl_info *info) { struct bnx2 *bp = netdev_priv(dev); struct drv_ctl_io *io = &info->data.io; switch (info->cmd) { case DRV_CTL_IO_WR_CMD: bnx2_reg_wr_ind(bp, io->offset, io->data); break; case DRV_CTL_IO_RD_CMD: io->data = bnx2_reg_rd_ind(bp, io->offset); break; case DRV_CTL_CTX_WR_CMD: bnx2_ctx_wr(bp, io->cid_addr, io->offset, io->data); break; default: return -EINVAL; } return 0; } static void bnx2_setup_cnic_irq_info(struct bnx2 *bp) { struct cnic_eth_dev *cp = &bp->cnic_eth_dev; struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; int sb_id; if (bp->flags & BNX2_FLAG_USING_MSIX) { cp->drv_state |= CNIC_DRV_STATE_USING_MSIX; bnapi->cnic_present = 0; sb_id = bp->irq_nvecs; cp->irq_arr[0].irq_flags |= CNIC_IRQ_FL_MSIX; } else { cp->drv_state &= ~CNIC_DRV_STATE_USING_MSIX; bnapi->cnic_tag = bnapi->last_status_idx; bnapi->cnic_present = 1; sb_id = 0; cp->irq_arr[0].irq_flags &= ~CNIC_IRQ_FL_MSIX; } cp->irq_arr[0].vector = bp->irq_tbl[sb_id].vector; cp->irq_arr[0].status_blk = (void *) ((unsigned long) bnapi->status_blk.msi + (BNX2_SBLK_MSIX_ALIGN_SIZE * sb_id)); cp->irq_arr[0].status_blk_num = sb_id; cp->num_irq = 1; } static int bnx2_register_cnic(struct net_device *dev, struct cnic_ops *ops, void *data) { struct bnx2 *bp = netdev_priv(dev); struct cnic_eth_dev *cp = &bp->cnic_eth_dev; if (ops == NULL) return -EINVAL; if (cp->drv_state & CNIC_DRV_STATE_REGD) return -EBUSY; if (!bnx2_reg_rd_ind(bp, BNX2_FW_MAX_ISCSI_CONN)) return -ENODEV; bp->cnic_data = data; rcu_assign_pointer(bp->cnic_ops, ops); cp->num_irq = 0; cp->drv_state = CNIC_DRV_STATE_REGD; bnx2_setup_cnic_irq_info(bp); return 0; } static int bnx2_unregister_cnic(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; struct cnic_eth_dev *cp = &bp->cnic_eth_dev; mutex_lock(&bp->cnic_lock); cp->drv_state = 0; bnapi->cnic_present = 0; RCU_INIT_POINTER(bp->cnic_ops, NULL); mutex_unlock(&bp->cnic_lock); synchronize_rcu(); return 0; } #if defined(BNX2_INBOX) struct cnic_eth_dev *bnx2_cnic_probe(struct net_device *dev) #else /* !defined(BNX2_INBOX) */ static struct cnic_eth_dev *bnx2_cnic_probe2(struct net_device *dev) #endif /* defined(BNX2_INBOX) */ { struct bnx2 *bp = netdev_priv(dev); struct cnic_eth_dev *cp = &bp->cnic_eth_dev; if (!cp->max_iscsi_conn) return NULL; cp->version = CNIC_ETH_DEV_VER; cp->drv_owner = THIS_MODULE; cp->chip_id = bp->chip_id; cp->pdev = bp->pdev; cp->io_base = bp->regview; cp->drv_ctl = bnx2_drv_ctl; cp->drv_register_cnic = bnx2_register_cnic; cp->drv_unregister_cnic = bnx2_unregister_cnic; return cp; } static void bnx2_cnic_stop(struct bnx2 *bp) { struct cnic_ops *c_ops; struct cnic_ctl_info info; mutex_lock(&bp->cnic_lock); c_ops = rcu_dereference_protected(bp->cnic_ops, lockdep_is_held(&bp->cnic_lock)); if (c_ops) { info.cmd = CNIC_CTL_STOP_CMD; #if defined(__VMKLNX__) VMKAPI_MODULE_CALL_VOID(c_ops->cnic_owner->moduleID, c_ops->cnic_ctl, bp->cnic_data, &info); #else c_ops->cnic_ctl(bp->cnic_data, &info); #endif } mutex_unlock(&bp->cnic_lock); } static void bnx2_cnic_start(struct bnx2 *bp) { struct cnic_ops *c_ops; struct cnic_ctl_info info; mutex_lock(&bp->cnic_lock); c_ops = rcu_dereference_protected(bp->cnic_ops, lockdep_is_held(&bp->cnic_lock)); if (c_ops) { if (!(bp->flags & BNX2_FLAG_USING_MSIX)) { struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; bnapi->cnic_tag = bnapi->last_status_idx; } info.cmd = CNIC_CTL_START_CMD; #if defined(__VMKLNX__) VMKAPI_MODULE_CALL_VOID(c_ops->cnic_owner->moduleID, c_ops->cnic_ctl, bp->cnic_data, &info); #else c_ops->cnic_ctl(bp->cnic_data, &info); #endif } mutex_unlock(&bp->cnic_lock); } #else static void bnx2_cnic_stop(struct bnx2 *bp) { } static void bnx2_cnic_start(struct bnx2 *bp) { } #endif static int bnx2_read_phy(struct bnx2 *bp, u32 reg, u32 *val) { u32 val1; int i, ret; if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 &= ~BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } val1 = (bp->phy_addr << 21) | (reg << 16) | BNX2_EMAC_MDIO_COMM_COMMAND_READ | BNX2_EMAC_MDIO_COMM_DISEXT | BNX2_EMAC_MDIO_COMM_START_BUSY; BNX2_WR(bp, BNX2_EMAC_MDIO_COMM, val1); for (i = 0; i < 50; i++) { udelay(10); val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_COMM); if (!(val1 & BNX2_EMAC_MDIO_COMM_START_BUSY)) { udelay(5); val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_COMM); val1 &= BNX2_EMAC_MDIO_COMM_DATA; break; } } if (val1 & BNX2_EMAC_MDIO_COMM_START_BUSY) { *val = 0x0; ret = -EBUSY; } else { *val = val1; ret = 0; } if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 |= BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } return ret; } static int bnx2_write_phy(struct bnx2 *bp, u32 reg, u32 val) { u32 val1; int i, ret; if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 &= ~BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } val1 = (bp->phy_addr << 21) | (reg << 16) | val | BNX2_EMAC_MDIO_COMM_COMMAND_WRITE | BNX2_EMAC_MDIO_COMM_START_BUSY | BNX2_EMAC_MDIO_COMM_DISEXT; BNX2_WR(bp, BNX2_EMAC_MDIO_COMM, val1); for (i = 0; i < 50; i++) { udelay(10); val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_COMM); if (!(val1 & BNX2_EMAC_MDIO_COMM_START_BUSY)) { udelay(5); break; } } if (val1 & BNX2_EMAC_MDIO_COMM_START_BUSY) ret = -EBUSY; else ret = 0; if (bp->phy_flags & BNX2_PHY_FLAG_INT_MODE_AUTO_POLLING) { val1 = BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); val1 |= BNX2_EMAC_MDIO_MODE_AUTO_POLL; BNX2_WR(bp, BNX2_EMAC_MDIO_MODE, val1); BNX2_RD(bp, BNX2_EMAC_MDIO_MODE); udelay(40); } return ret; } static void bnx2_disable_int(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi; for (i = 0; i < bp->irq_nvecs; i++) { bnapi = &bp->bnx2_napi[i]; BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_MASK_INT); } BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD); } static void bnx2_enable_int(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi; for (i = 0; i < bp->irq_nvecs; i++) { bnapi = &bp->bnx2_napi[i]; BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | BNX2_PCICFG_INT_ACK_CMD_MASK_INT | bnapi->last_status_idx); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); } BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW); } static void bnx2_disable_int_sync(struct bnx2 *bp) { int i; atomic_inc(&bp->intr_sem); if (!netif_running(bp->dev)) return; bnx2_disable_int(bp); for (i = 0; i < bp->irq_nvecs; i++) #if (LINUX_VERSION_CODE >= 0x2051c) synchronize_irq(bp->irq_tbl[i].vector); #else synchronize_irq(); #endif } static void bnx2_napi_disable(struct bnx2 *bp) { #ifdef BNX2_NEW_NAPI int i; for (i = 0; i < bp->irq_nvecs; i++) napi_disable(&bp->bnx2_napi[i].napi); #else netif_poll_disable(bp->dev); #endif } static void bnx2_napi_enable(struct bnx2 *bp) { #ifdef BNX2_NEW_NAPI int i; for (i = 0; i < bp->irq_nvecs; i++) napi_enable(&bp->bnx2_napi[i].napi); #else netif_poll_enable(bp->dev); #endif } #if defined(BNX2_ENABLE_NETQUEUE) static void bnx2_netqueue_tx_flush_queue(struct bnx2_napi *bnapi, struct bnx2_tx_ring_info *txr) { struct bnx2 *bp = bnapi->bp; rmb(); if ((bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons) || (bnapi->tx_packets_sent != bnapi->tx_packets_processed)) { bnx2_tx_int(bp, bnapi, 100, 0); msleep(1); rmb(); } } static void bnx2_netqueue_tx_flush(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; /* Flush default ring */ bnapi = &bp->bnx2_napi[0]; txr = &bnapi->tx_ring; bnx2_netqueue_tx_flush_queue(bnapi, txr); netdev_info(bp->dev, "flushed default TX queue\n"); /* Flush NetQ rings */ for_each_nondefault_tx_queue(bp, i) { bnapi = &bp->bnx2_napi[i]; txr = &bnapi->tx_ring; rmb(); bnx2_netqueue_tx_flush_queue(bnapi, txr); netdev_info(bp->dev, "flushed TX queue %d\n", i); } } static void bnx2_netif_stop(struct bnx2 *bp, bool stop_cnic) { if (stop_cnic) { #if defined(BNX2_ENABLE_NETQUEUE) /* Note that queues allocated MUST be read before they * got reset during stop_nequeue */ int tx_queues_allocated = bp->n_tx_queues_allocated; int rx_queues_allocated = bp->n_rx_queues_allocated; bnx2_stop_netqueue(bp); if (rx_queues_allocated == 0 && tx_queues_allocated == bp->num_tx_rings - 1) /* to avoid repeated callbacks from ESX host, * we need to skip invalidating state in no * rx queues are allocated. */ bp->skip_invalidate_tx_netq = tx_queues_allocated; else vmknetddi_queueops_invalidate_state(bp->dev); #endif bnx2_cnic_stop(bp); } if (netif_running(bp->dev)) { bnx2_napi_disable(bp); bnx2_disable_int_sync(bp); netif_carrier_off(bp->dev); /* prevent tx timeout */ netif_tx_disable(bp->dev); } rmb(); #if defined(BNX2_ENABLE_NETQUEUE) if (bnx2_netqueue_open_started(bp)) bnx2_netqueue_tx_flush(bp); if (stop_cnic) { /* if for whatever the reason, netqueue failed to stop in case of chip getting stuck, we should force the netqueue to stop since chip will go thru full reset afterward. */ if (bnx2_netqueue_is_avail(bp)) bnx2_force_stop_netqueue(bp); } #endif /* defined(BNX2_ENABLE_NETQUEUE) */ } #else static void bnx2_netif_stop(struct bnx2 *bp, bool stop_cnic) { if (stop_cnic) bnx2_cnic_stop(bp); if (netif_running(bp->dev)) { bnx2_napi_disable(bp); bnx2_disable_int_sync(bp); netif_carrier_off(bp->dev); /* prevent tx timeout */ netif_tx_disable(bp->dev); } } #endif static void bnx2_netif_start(struct bnx2 *bp, bool start_cnic) { #if defined(__VMKLNX__) && defined(BNX2_ENABLE_NETQUEUE) if (start_cnic && bnx2_netqueue_is_avail(bp)) { bnx2_start_netqueue(bp); /* we might have skipped invalidating netq state * when stopping netq earlier to avoid repeated * callbacks from ESX host. If so, we need to * manually allocate the tx queues accordingly. */ if (bp->skip_invalidate_tx_netq) { int index; for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if (bnx2_netq_alloc_tx_queue(bp, bnapi, index) != VMKNETDDI_QUEUEOPS_OK) break; } BUG_ON(index - 1 != bp->skip_invalidate_tx_netq); bp->skip_invalidate_tx_netq = 0; } } #endif if (atomic_dec_and_test(&bp->intr_sem)) { if (netif_running(bp->dev)) { netif_tx_wake_all_queues(bp->dev); spin_lock_bh(&bp->phy_lock); if (bp->link_up) netif_carrier_on(bp->dev); spin_unlock_bh(&bp->phy_lock); bnx2_napi_enable(bp); bnx2_enable_int(bp); if (start_cnic) bnx2_cnic_start(bp); } } } static void bnx2_free_tx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_tx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; if (txr->tx_desc_ring) { #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, TXBD_RING_SIZE, txr->tx_desc_ring, txr->tx_desc_mapping); #else pci_free_consistent(bp->pdev, TXBD_RING_SIZE, txr->tx_desc_ring, txr->tx_desc_mapping); #endif txr->tx_desc_ring = NULL; } kfree(txr->tx_buf_ring); txr->tx_buf_ring = NULL; } } static void bnx2_free_rx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_rx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; int j; for (j = 0; j < bp->rx_max_ring; j++) { if (rxr->rx_desc_ring[j]) #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, RXBD_RING_SIZE, rxr->rx_desc_ring[j], rxr->rx_desc_mapping[j]); #else pci_free_consistent(bp->pdev, RXBD_RING_SIZE, rxr->rx_desc_ring[j], rxr->rx_desc_mapping[j]); #endif rxr->rx_desc_ring[j] = NULL; } vfree(rxr->rx_buf_ring); rxr->rx_buf_ring = NULL; for (j = 0; j < bp->rx_max_pg_ring; j++) { if (rxr->rx_pg_desc_ring[j]) #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, RXBD_RING_SIZE, rxr->rx_pg_desc_ring[j], rxr->rx_pg_desc_mapping[j]); #else pci_free_consistent(bp->pdev, RXBD_RING_SIZE, rxr->rx_pg_desc_ring[j], rxr->rx_pg_desc_mapping[j]); #endif rxr->rx_pg_desc_ring[j] = NULL; } vfree(rxr->rx_pg_ring); rxr->rx_pg_ring = NULL; } } static int bnx2_alloc_tx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_tx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; txr->tx_buf_ring = kmalloc(SW_TXBD_RING_SIZE, GFP_KERNEL); if (txr->tx_buf_ring == NULL) return -ENOMEM; memset(txr->tx_buf_ring, 0, SW_TXBD_RING_SIZE); txr->tx_desc_ring = #if (LINUX_VERSION_CODE >= 0x02061b) dma_alloc_coherent(&bp->pdev->dev, TXBD_RING_SIZE, &txr->tx_desc_mapping, GFP_KERNEL); #else pci_alloc_consistent(bp->pdev, TXBD_RING_SIZE, &txr->tx_desc_mapping); #endif if (txr->tx_desc_ring == NULL) return -ENOMEM; } return 0; } static int bnx2_alloc_rx_mem(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_rx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; int j; rxr->rx_buf_ring = vmalloc(SW_RXBD_RING_SIZE * bp->rx_max_ring); if (rxr->rx_buf_ring == NULL) return -ENOMEM; memset(rxr->rx_buf_ring, 0, SW_RXBD_RING_SIZE * bp->rx_max_ring); for (j = 0; j < bp->rx_max_ring; j++) { rxr->rx_desc_ring[j] = #if (LINUX_VERSION_CODE >= 0x02061b) dma_alloc_coherent(&bp->pdev->dev, RXBD_RING_SIZE, &rxr->rx_desc_mapping[j], GFP_KERNEL); #else pci_alloc_consistent(bp->pdev, RXBD_RING_SIZE, &rxr->rx_desc_mapping[j]); #endif if (rxr->rx_desc_ring[j] == NULL) return -ENOMEM; } if (bp->rx_pg_ring_size) { rxr->rx_pg_ring = vmalloc(SW_RXPG_RING_SIZE * bp->rx_max_pg_ring); if (rxr->rx_pg_ring == NULL) return -ENOMEM; memset(rxr->rx_pg_ring, 0, SW_RXPG_RING_SIZE * bp->rx_max_pg_ring); } for (j = 0; j < bp->rx_max_pg_ring; j++) { rxr->rx_pg_desc_ring[j] = #if (LINUX_VERSION_CODE >= 0x02061b) dma_alloc_coherent(&bp->pdev->dev, RXBD_RING_SIZE, &rxr->rx_pg_desc_mapping[j], GFP_KERNEL); #else pci_alloc_consistent(bp->pdev, RXBD_RING_SIZE, &rxr->rx_pg_desc_mapping[j]); #endif if (rxr->rx_pg_desc_ring[j] == NULL) return -ENOMEM; } } return 0; } static void bnx2_free_mem(struct bnx2 *bp) { int i; struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; bnx2_free_tx_mem(bp); bnx2_free_rx_mem(bp); for (i = 0; i < bp->ctx_pages; i++) { if (bp->ctx_blk[i]) { #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, BNX2_PAGE_SIZE, bp->ctx_blk[i], bp->ctx_blk_mapping[i]); #else pci_free_consistent(bp->pdev, BNX2_PAGE_SIZE, bp->ctx_blk[i], bp->ctx_blk_mapping[i]); #endif bp->ctx_blk[i] = NULL; } } if (bnapi->status_blk.msi) { #if (LINUX_VERSION_CODE >= 0x02061b) dma_free_coherent(&bp->pdev->dev, bp->status_stats_size, bnapi->status_blk.msi, bp->status_blk_mapping); #else pci_free_consistent(bp->pdev, bp->status_stats_size, bnapi->status_blk.msi, bp->status_blk_mapping); #endif bnapi->status_blk.msi = NULL; bp->stats_blk = NULL; } } static int bnx2_alloc_mem(struct bnx2 *bp) { int i, status_blk_size, err; struct bnx2_napi *bnapi; void *status_blk; /* Combine status and statistics blocks into one allocation. */ status_blk_size = L1_CACHE_ALIGN(sizeof(struct status_block)); #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_MSIX_CAP) status_blk_size = L1_CACHE_ALIGN(BNX2_MAX_MSIX_HW_VEC * BNX2_SBLK_MSIX_ALIGN_SIZE); #endif bp->status_stats_size = status_blk_size + sizeof(struct statistics_block); #if (LINUX_VERSION_CODE >= 0x02061b) status_blk = dma_alloc_coherent(&bp->pdev->dev, bp->status_stats_size, &bp->status_blk_mapping, GFP_KERNEL); #else status_blk = pci_alloc_consistent(bp->pdev, bp->status_stats_size, &bp->status_blk_mapping); #endif if (status_blk == NULL) goto alloc_mem_err; memset(status_blk, 0, bp->status_stats_size); bnapi = &bp->bnx2_napi[0]; bnapi->status_blk.msi = status_blk; bnapi->hw_tx_cons_ptr = &bnapi->status_blk.msi->status_tx_quick_consumer_index0; bnapi->hw_rx_cons_ptr = &bnapi->status_blk.msi->status_rx_quick_consumer_index0; if (bp->flags & BNX2_FLAG_MSIX_CAP) { for (i = 1; i < bp->irq_nvecs; i++) { struct status_block_msix *sblk; bnapi = &bp->bnx2_napi[i]; sblk = (status_blk + BNX2_SBLK_MSIX_ALIGN_SIZE * i); bnapi->status_blk.msix = sblk; bnapi->hw_tx_cons_ptr = &sblk->status_tx_quick_consumer_index; bnapi->hw_rx_cons_ptr = &sblk->status_rx_quick_consumer_index; bnapi->int_num = i << 24; } } bp->stats_blk = status_blk + status_blk_size; bp->stats_blk_mapping = bp->status_blk_mapping + status_blk_size; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { /* NetQ uses CID 100, so we need 16K of context memory */ #if defined(BNX2_ENABLE_NETQUEUE) bp->ctx_pages = 0x4000 / BNX2_PAGE_SIZE; #else /* !defined(__VMKLNX__) */ bp->ctx_pages = 0x2000 / BNX2_PAGE_SIZE; #endif /* defined(__VMKLNX__) */ if (bp->ctx_pages == 0) bp->ctx_pages = 1; for (i = 0; i < bp->ctx_pages; i++) { #if (LINUX_VERSION_CODE >= 0x02061b) bp->ctx_blk[i] = dma_alloc_coherent(&bp->pdev->dev, BNX2_PAGE_SIZE, &bp->ctx_blk_mapping[i], GFP_KERNEL); #else bp->ctx_blk[i] = pci_alloc_consistent(bp->pdev, BNX2_PAGE_SIZE, &bp->ctx_blk_mapping[i]); #endif if (bp->ctx_blk[i] == NULL) goto alloc_mem_err; } } err = bnx2_alloc_rx_mem(bp); if (err) goto alloc_mem_err; err = bnx2_alloc_tx_mem(bp); if (err) goto alloc_mem_err; return 0; alloc_mem_err: bnx2_free_mem(bp); return -ENOMEM; } static void bnx2_report_fw_link(struct bnx2 *bp) { u32 fw_link_status = 0; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return; if (bp->link_up) { u32 bmsr; switch (bp->line_speed) { case SPEED_10: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_10HALF; else fw_link_status = BNX2_LINK_STATUS_10FULL; break; case SPEED_100: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_100HALF; else fw_link_status = BNX2_LINK_STATUS_100FULL; break; case SPEED_1000: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_1000HALF; else fw_link_status = BNX2_LINK_STATUS_1000FULL; break; case SPEED_2500: if (bp->duplex == DUPLEX_HALF) fw_link_status = BNX2_LINK_STATUS_2500HALF; else fw_link_status = BNX2_LINK_STATUS_2500FULL; break; } fw_link_status |= BNX2_LINK_STATUS_LINK_UP; if (bp->autoneg) { fw_link_status |= BNX2_LINK_STATUS_AN_ENABLED; bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); if (!(bmsr & BMSR_ANEGCOMPLETE) || bp->phy_flags & BNX2_PHY_FLAG_PARALLEL_DETECT) fw_link_status |= BNX2_LINK_STATUS_PARALLEL_DET; else fw_link_status |= BNX2_LINK_STATUS_AN_COMPLETE; } } else fw_link_status = BNX2_LINK_STATUS_LINK_DOWN; bnx2_shmem_wr(bp, BNX2_LINK_STATUS, fw_link_status); } static char * bnx2_xceiver_str(struct bnx2 *bp) { return (bp->phy_port == PORT_FIBRE) ? "SerDes" : ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) ? "Remote Copper" : "Copper"); } static void bnx2_report_link(struct bnx2 *bp) { if (bp->link_up) { netif_carrier_on(bp->dev); netdev_info(bp->dev, "NIC %s Link is Up, %d Mbps %s duplex", bnx2_xceiver_str(bp), bp->line_speed, bp->duplex == DUPLEX_FULL ? "full" : "half"); if (bp->flow_ctrl) { if (bp->flow_ctrl & FLOW_CTRL_RX) { pr_cont(", receive "); if (bp->flow_ctrl & FLOW_CTRL_TX) pr_cont("& transmit "); } else { pr_cont(", transmit "); } pr_cont("flow control ON"); } pr_cont("\n"); } else { netif_carrier_off(bp->dev); netdev_err(bp->dev, "NIC %s Link is Down\n", bnx2_xceiver_str(bp)); } bnx2_report_fw_link(bp); } static void bnx2_resolve_flow_ctrl(struct bnx2 *bp) { u32 local_adv, remote_adv; bp->flow_ctrl = 0; if ((bp->autoneg & (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) != (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) { if (bp->duplex == DUPLEX_FULL) { bp->flow_ctrl = bp->req_flow_ctrl; } return; } if (bp->duplex != DUPLEX_FULL) { return; } if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5708)) { u32 val; bnx2_read_phy(bp, BCM5708S_1000X_STAT1, &val); if (val & BCM5708S_1000X_STAT1_TX_PAUSE) bp->flow_ctrl |= FLOW_CTRL_TX; if (val & BCM5708S_1000X_STAT1_RX_PAUSE) bp->flow_ctrl |= FLOW_CTRL_RX; return; } bnx2_read_phy(bp, bp->mii_adv, &local_adv); bnx2_read_phy(bp, bp->mii_lpa, &remote_adv); if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { u32 new_local_adv = 0; u32 new_remote_adv = 0; if (local_adv & ADVERTISE_1000XPAUSE) new_local_adv |= ADVERTISE_PAUSE_CAP; if (local_adv & ADVERTISE_1000XPSE_ASYM) new_local_adv |= ADVERTISE_PAUSE_ASYM; if (remote_adv & ADVERTISE_1000XPAUSE) new_remote_adv |= ADVERTISE_PAUSE_CAP; if (remote_adv & ADVERTISE_1000XPSE_ASYM) new_remote_adv |= ADVERTISE_PAUSE_ASYM; local_adv = new_local_adv; remote_adv = new_remote_adv; } /* See Table 28B-3 of 802.3ab-1999 spec. */ if (local_adv & ADVERTISE_PAUSE_CAP) { if(local_adv & ADVERTISE_PAUSE_ASYM) { if (remote_adv & ADVERTISE_PAUSE_CAP) { bp->flow_ctrl = FLOW_CTRL_TX | FLOW_CTRL_RX; } else if (remote_adv & ADVERTISE_PAUSE_ASYM) { bp->flow_ctrl = FLOW_CTRL_RX; } } else { if (remote_adv & ADVERTISE_PAUSE_CAP) { bp->flow_ctrl = FLOW_CTRL_TX | FLOW_CTRL_RX; } } } else if (local_adv & ADVERTISE_PAUSE_ASYM) { if ((remote_adv & ADVERTISE_PAUSE_CAP) && (remote_adv & ADVERTISE_PAUSE_ASYM)) { bp->flow_ctrl = FLOW_CTRL_TX; } } } static int bnx2_5709s_linkup(struct bnx2 *bp) { u32 val, speed; bp->link_up = 1; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_GP_STATUS); bnx2_read_phy(bp, MII_BNX2_GP_TOP_AN_STATUS1, &val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); if ((bp->autoneg & AUTONEG_SPEED) == 0) { bp->line_speed = bp->req_line_speed; bp->duplex = bp->req_duplex; return 0; } speed = val & MII_BNX2_GP_TOP_AN_SPEED_MSK; switch (speed) { case MII_BNX2_GP_TOP_AN_SPEED_10: bp->line_speed = SPEED_10; break; case MII_BNX2_GP_TOP_AN_SPEED_100: bp->line_speed = SPEED_100; break; case MII_BNX2_GP_TOP_AN_SPEED_1G: case MII_BNX2_GP_TOP_AN_SPEED_1GKV: bp->line_speed = SPEED_1000; break; case MII_BNX2_GP_TOP_AN_SPEED_2_5G: bp->line_speed = SPEED_2500; break; } if (val & MII_BNX2_GP_TOP_AN_FD) bp->duplex = DUPLEX_FULL; else bp->duplex = DUPLEX_HALF; return 0; } static int bnx2_5708s_linkup(struct bnx2 *bp) { u32 val; bp->link_up = 1; bnx2_read_phy(bp, BCM5708S_1000X_STAT1, &val); switch (val & BCM5708S_1000X_STAT1_SPEED_MASK) { case BCM5708S_1000X_STAT1_SPEED_10: bp->line_speed = SPEED_10; break; case BCM5708S_1000X_STAT1_SPEED_100: bp->line_speed = SPEED_100; break; case BCM5708S_1000X_STAT1_SPEED_1G: bp->line_speed = SPEED_1000; break; case BCM5708S_1000X_STAT1_SPEED_2G5: bp->line_speed = SPEED_2500; break; } if (val & BCM5708S_1000X_STAT1_FD) bp->duplex = DUPLEX_FULL; else bp->duplex = DUPLEX_HALF; return 0; } static int bnx2_5706s_linkup(struct bnx2 *bp) { u32 bmcr, local_adv, remote_adv, common; bp->link_up = 1; bp->line_speed = SPEED_1000; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_FULLDPLX) { bp->duplex = DUPLEX_FULL; } else { bp->duplex = DUPLEX_HALF; } if (!(bmcr & BMCR_ANENABLE)) { return 0; } bnx2_read_phy(bp, bp->mii_adv, &local_adv); bnx2_read_phy(bp, bp->mii_lpa, &remote_adv); common = local_adv & remote_adv; if (common & (ADVERTISE_1000XHALF | ADVERTISE_1000XFULL)) { if (common & ADVERTISE_1000XFULL) { bp->duplex = DUPLEX_FULL; } else { bp->duplex = DUPLEX_HALF; } } return 0; } static int bnx2_copper_linkup(struct bnx2 *bp) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_ANENABLE) { u32 local_adv, remote_adv, common; bnx2_read_phy(bp, MII_CTRL1000, &local_adv); bnx2_read_phy(bp, MII_STAT1000, &remote_adv); common = local_adv & (remote_adv >> 2); if (common & ADVERTISE_1000FULL) { bp->line_speed = SPEED_1000; bp->duplex = DUPLEX_FULL; } else if (common & ADVERTISE_1000HALF) { bp->line_speed = SPEED_1000; bp->duplex = DUPLEX_HALF; } else { bnx2_read_phy(bp, bp->mii_adv, &local_adv); bnx2_read_phy(bp, bp->mii_lpa, &remote_adv); common = local_adv & remote_adv; if (common & ADVERTISE_100FULL) { bp->line_speed = SPEED_100; bp->duplex = DUPLEX_FULL; } else if (common & ADVERTISE_100HALF) { bp->line_speed = SPEED_100; bp->duplex = DUPLEX_HALF; } else if (common & ADVERTISE_10FULL) { bp->line_speed = SPEED_10; bp->duplex = DUPLEX_FULL; } else if (common & ADVERTISE_10HALF) { bp->line_speed = SPEED_10; bp->duplex = DUPLEX_HALF; } else { bp->line_speed = 0; bp->link_up = 0; } } } else { if (bmcr & BMCR_SPEED100) { bp->line_speed = SPEED_100; } else { bp->line_speed = SPEED_10; } if (bmcr & BMCR_FULLDPLX) { bp->duplex = DUPLEX_FULL; } else { bp->duplex = DUPLEX_HALF; } } return 0; } static void bnx2_init_rx_context(struct bnx2 *bp, u32 cid) { u32 val, rx_cid_addr = GET_CID_ADDR(cid); val = BNX2_L2CTX_CTX_TYPE_CTX_BD_CHN_TYPE_VALUE; val |= BNX2_L2CTX_CTX_TYPE_SIZE_L2; val |= 0x02 << 8; if (bp->flow_ctrl & FLOW_CTRL_TX) val |= BNX2_L2CTX_FLOW_CTRL_ENABLE; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_CTX_TYPE, val); } static void bnx2_init_all_rx_contexts(struct bnx2 *bp) { int i; u32 cid; for (i = 0, cid = RX_CID; i < bp->num_rx_rings; i++, cid++) { if (i == 1) cid = RX_RSS_CID; bnx2_init_rx_context(bp, cid); } } static void bnx2_set_mac_link(struct bnx2 *bp) { u32 val; BNX2_WR(bp, BNX2_EMAC_TX_LENGTHS, 0x2620); if (bp->link_up && (bp->line_speed == SPEED_1000) && (bp->duplex == DUPLEX_HALF)) { BNX2_WR(bp, BNX2_EMAC_TX_LENGTHS, 0x26ff); } /* Configure the EMAC mode register. */ val = BNX2_RD(bp, BNX2_EMAC_MODE); val &= ~(BNX2_EMAC_MODE_PORT | BNX2_EMAC_MODE_HALF_DUPLEX | BNX2_EMAC_MODE_MAC_LOOP | BNX2_EMAC_MODE_FORCE_LINK | BNX2_EMAC_MODE_25G_MODE); if (bp->link_up) { switch (bp->line_speed) { case SPEED_10: if (BNX2_CHIP(bp) != BNX2_CHIP_5706) { val |= BNX2_EMAC_MODE_PORT_MII_10M; break; } /* fall through */ case SPEED_100: val |= BNX2_EMAC_MODE_PORT_MII; break; case SPEED_2500: val |= BNX2_EMAC_MODE_25G_MODE; /* fall through */ case SPEED_1000: val |= BNX2_EMAC_MODE_PORT_GMII; break; } } else { val |= BNX2_EMAC_MODE_PORT_GMII; } /* Set the MAC to operate in the appropriate duplex mode. */ if (bp->duplex == DUPLEX_HALF) val |= BNX2_EMAC_MODE_HALF_DUPLEX; BNX2_WR(bp, BNX2_EMAC_MODE, val); /* Enable/disable rx PAUSE. */ bp->rx_mode &= ~BNX2_EMAC_RX_MODE_FLOW_EN; if (bp->flow_ctrl & FLOW_CTRL_RX) bp->rx_mode |= BNX2_EMAC_RX_MODE_FLOW_EN; BNX2_WR(bp, BNX2_EMAC_RX_MODE, bp->rx_mode); /* Enable/disable tx PAUSE. */ val = BNX2_RD(bp, BNX2_EMAC_TX_MODE); val &= ~BNX2_EMAC_TX_MODE_FLOW_EN; if (bp->flow_ctrl & FLOW_CTRL_TX) val |= BNX2_EMAC_TX_MODE_FLOW_EN; BNX2_WR(bp, BNX2_EMAC_TX_MODE, val); /* Acknowledge the interrupt. */ BNX2_WR(bp, BNX2_EMAC_STATUS, BNX2_EMAC_STATUS_LINK_CHANGE); bnx2_init_all_rx_contexts(bp); } static void bnx2_enable_bmsr1(struct bnx2 *bp) { if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5709)) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_GP_STATUS); } static void bnx2_disable_bmsr1(struct bnx2 *bp) { if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5709)) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); } static int bnx2_test_and_enable_2g5(struct bnx2 *bp) { u32 up1; int ret = 1; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return 0; if (bp->autoneg & AUTONEG_SPEED) bp->advertising |= ADVERTISED_2500baseX_Full; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_OVER1G); bnx2_read_phy(bp, bp->mii_up1, &up1); if (!(up1 & BCM5708S_UP1_2G5)) { up1 |= BCM5708S_UP1_2G5; bnx2_write_phy(bp, bp->mii_up1, up1); ret = 0; } if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); return ret; } static int bnx2_test_and_disable_2g5(struct bnx2 *bp) { u32 up1; int ret = 0; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return 0; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_OVER1G); bnx2_read_phy(bp, bp->mii_up1, &up1); if (up1 & BCM5708S_UP1_2G5) { up1 &= ~BCM5708S_UP1_2G5; bnx2_write_phy(bp, bp->mii_up1, up1); ret = 1; } if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); return ret; } static void bnx2_enable_forced_2g5(struct bnx2 *bp) { u32 uninitialized_var(bmcr); int err; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { u32 val; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_SERDES_DIG); if (!bnx2_read_phy(bp, MII_BNX2_SERDES_DIG_MISC1, &val)) { val &= ~MII_BNX2_SD_MISC1_FORCE_MSK; val |= MII_BNX2_SD_MISC1_FORCE | MII_BNX2_SD_MISC1_FORCE_2_5G; bnx2_write_phy(bp, MII_BNX2_SERDES_DIG_MISC1, val); } bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); } else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) { err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (!err) bmcr |= BCM5708S_BMCR_FORCE_2500; } else { return; } if (err) return; if (bp->autoneg & AUTONEG_SPEED) { bmcr &= ~BMCR_ANENABLE; if (bp->req_duplex == DUPLEX_FULL) bmcr |= BMCR_FULLDPLX; } bnx2_write_phy(bp, bp->mii_bmcr, bmcr); } static void bnx2_disable_forced_2g5(struct bnx2 *bp) { u32 uninitialized_var(bmcr); int err; if (!(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) return; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { u32 val; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_SERDES_DIG); if (!bnx2_read_phy(bp, MII_BNX2_SERDES_DIG_MISC1, &val)) { val &= ~MII_BNX2_SD_MISC1_FORCE; bnx2_write_phy(bp, MII_BNX2_SERDES_DIG_MISC1, val); } bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); } else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) { err = bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (!err) bmcr &= ~BCM5708S_BMCR_FORCE_2500; } else { return; } if (err) return; if (bp->autoneg & AUTONEG_SPEED) bmcr |= BMCR_SPEED1000 | BMCR_ANENABLE | BMCR_ANRESTART; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); } static void bnx2_5706s_force_link_dn(struct bnx2 *bp, int start) { u32 val; bnx2_write_phy(bp, MII_BNX2_DSP_ADDRESS, MII_EXPAND_SERDES_CTL); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &val); if (start) bnx2_write_phy(bp, MII_BNX2_DSP_RW_PORT, val & 0xff0f); else bnx2_write_phy(bp, MII_BNX2_DSP_RW_PORT, val | 0xc0); } static int bnx2_set_link(struct bnx2 *bp) { u32 bmsr; u8 link_up; if (bp->loopback == MAC_LOOPBACK || bp->loopback == PHY_LOOPBACK) { bp->link_up = 1; return 0; } if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return 0; link_up = bp->link_up; bnx2_enable_bmsr1(bp); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_disable_bmsr1(bp); if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (BNX2_CHIP(bp) == BNX2_CHIP_5706)) { u32 val, an_dbg; if (bp->phy_flags & BNX2_PHY_FLAG_FORCED_DOWN) { bnx2_5706s_force_link_dn(bp, 0); bp->phy_flags &= ~BNX2_PHY_FLAG_FORCED_DOWN; } val = BNX2_RD(bp, BNX2_EMAC_STATUS); bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_AN_DBG); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); if ((val & BNX2_EMAC_STATUS_LINK) && !(an_dbg & MISC_SHDW_AN_DBG_NOSYNC)) bmsr |= BMSR_LSTATUS; else bmsr &= ~BMSR_LSTATUS; } if (bmsr & BMSR_LSTATUS) { bp->link_up = 1; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { if (BNX2_CHIP(bp) == BNX2_CHIP_5706) bnx2_5706s_linkup(bp); else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) bnx2_5708s_linkup(bp); else if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_5709s_linkup(bp); } else { bnx2_copper_linkup(bp); } bnx2_resolve_flow_ctrl(bp); } else { if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (bp->autoneg & AUTONEG_SPEED)) bnx2_disable_forced_2g5(bp); if (bp->phy_flags & BNX2_PHY_FLAG_PARALLEL_DETECT) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bmcr |= BMCR_ANENABLE; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); bp->phy_flags &= ~BNX2_PHY_FLAG_PARALLEL_DETECT; } bp->link_up = 0; } if (bp->link_up != link_up) { bnx2_report_link(bp); } bnx2_set_mac_link(bp); return 0; } static int bnx2_reset_phy(struct bnx2 *bp) { int i; u32 reg; bnx2_write_phy(bp, bp->mii_bmcr, BMCR_RESET); #define PHY_RESET_MAX_WAIT 100 for (i = 0; i < PHY_RESET_MAX_WAIT; i++) { udelay(10); bnx2_read_phy(bp, bp->mii_bmcr, &reg); if (!(reg & BMCR_RESET)) { udelay(20); break; } } if (i == PHY_RESET_MAX_WAIT) { return -EBUSY; } return 0; } static u32 bnx2_phy_get_pause_adv(struct bnx2 *bp) { u32 adv = 0; if ((bp->req_flow_ctrl & (FLOW_CTRL_RX | FLOW_CTRL_TX)) == (FLOW_CTRL_RX | FLOW_CTRL_TX)) { if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { adv = ADVERTISE_1000XPAUSE; } else { adv = ADVERTISE_PAUSE_CAP; } } else if (bp->req_flow_ctrl & FLOW_CTRL_TX) { if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { adv = ADVERTISE_1000XPSE_ASYM; } else { adv = ADVERTISE_PAUSE_ASYM; } } else if (bp->req_flow_ctrl & FLOW_CTRL_RX) { if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { adv = ADVERTISE_1000XPAUSE | ADVERTISE_1000XPSE_ASYM; } else { adv = ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM; } } return adv; } static int bnx2_fw_sync(struct bnx2 *, u32, int, int); static int bnx2_setup_remote_phy(struct bnx2 *bp, u8 port) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 speed_arg = 0, pause_adv; pause_adv = bnx2_phy_get_pause_adv(bp); if (bp->autoneg & AUTONEG_SPEED) { speed_arg |= BNX2_NETLINK_SET_LINK_ENABLE_AUTONEG; if (bp->advertising & ADVERTISED_10baseT_Half) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_10HALF; if (bp->advertising & ADVERTISED_10baseT_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_10FULL; if (bp->advertising & ADVERTISED_100baseT_Half) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_100HALF; if (bp->advertising & ADVERTISED_100baseT_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_100FULL; if (bp->advertising & ADVERTISED_1000baseT_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_1GFULL; if (bp->advertising & ADVERTISED_2500baseX_Full) speed_arg |= BNX2_NETLINK_SET_LINK_SPEED_2G5FULL; } else { if (bp->req_line_speed == SPEED_2500) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_2G5FULL; else if (bp->req_line_speed == SPEED_1000) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_1GFULL; else if (bp->req_line_speed == SPEED_100) { if (bp->req_duplex == DUPLEX_FULL) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_100FULL; else speed_arg = BNX2_NETLINK_SET_LINK_SPEED_100HALF; } else if (bp->req_line_speed == SPEED_10) { if (bp->req_duplex == DUPLEX_FULL) speed_arg = BNX2_NETLINK_SET_LINK_SPEED_10FULL; else speed_arg = BNX2_NETLINK_SET_LINK_SPEED_10HALF; } } if (pause_adv & (ADVERTISE_1000XPAUSE | ADVERTISE_PAUSE_CAP)) speed_arg |= BNX2_NETLINK_SET_LINK_FC_SYM_PAUSE; if (pause_adv & (ADVERTISE_1000XPSE_ASYM | ADVERTISE_PAUSE_ASYM)) speed_arg |= BNX2_NETLINK_SET_LINK_FC_ASYM_PAUSE; if (port == PORT_TP) speed_arg |= BNX2_NETLINK_SET_LINK_PHY_APP_REMOTE | BNX2_NETLINK_SET_LINK_ETH_AT_WIRESPEED; bnx2_shmem_wr(bp, BNX2_DRV_MB_ARG0, speed_arg); spin_unlock_bh(&bp->phy_lock); bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_CMD_SET_LINK, 1, 0); spin_lock_bh(&bp->phy_lock); return 0; } static int bnx2_setup_serdes_phy(struct bnx2 *bp, u8 port) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 adv, bmcr; u32 new_adv = 0; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return bnx2_setup_remote_phy(bp, port); if (!(bp->autoneg & AUTONEG_SPEED)) { u32 new_bmcr; int force_link_down = 0; if (bp->req_line_speed == SPEED_2500) { if (!bnx2_test_and_enable_2g5(bp)) force_link_down = 1; } else if (bp->req_line_speed == SPEED_1000) { if (bnx2_test_and_disable_2g5(bp)) force_link_down = 1; } bnx2_read_phy(bp, bp->mii_adv, &adv); adv &= ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF); bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); new_bmcr = bmcr & ~BMCR_ANENABLE; new_bmcr |= BMCR_SPEED1000; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (bp->req_line_speed == SPEED_2500) bnx2_enable_forced_2g5(bp); else if (bp->req_line_speed == SPEED_1000) { bnx2_disable_forced_2g5(bp); new_bmcr &= ~0x2000; } } else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) { if (bp->req_line_speed == SPEED_2500) new_bmcr |= BCM5708S_BMCR_FORCE_2500; else new_bmcr = bmcr & ~BCM5708S_BMCR_FORCE_2500; } if (bp->req_duplex == DUPLEX_FULL) { adv |= ADVERTISE_1000XFULL; new_bmcr |= BMCR_FULLDPLX; } else { adv |= ADVERTISE_1000XHALF; new_bmcr &= ~BMCR_FULLDPLX; } if ((new_bmcr != bmcr) || (force_link_down)) { /* Force a link down visible on the other side */ if (bp->link_up) { bnx2_write_phy(bp, bp->mii_adv, adv & ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF)); bnx2_write_phy(bp, bp->mii_bmcr, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); bp->link_up = 0; netif_carrier_off(bp->dev); bnx2_write_phy(bp, bp->mii_bmcr, new_bmcr); bnx2_report_link(bp); } bnx2_write_phy(bp, bp->mii_adv, adv); bnx2_write_phy(bp, bp->mii_bmcr, new_bmcr); } else { bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } bnx2_test_and_enable_2g5(bp); if (bp->advertising & ADVERTISED_1000baseT_Full) new_adv |= ADVERTISE_1000XFULL; new_adv |= bnx2_phy_get_pause_adv(bp); bnx2_read_phy(bp, bp->mii_adv, &adv); bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bp->serdes_an_pending = 0; if ((adv != new_adv) || ((bmcr & BMCR_ANENABLE) == 0)) { /* Force a link down visible on the other side */ if (bp->link_up) { bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK); spin_unlock_bh(&bp->phy_lock); bnx2_msleep(20); spin_lock_bh(&bp->phy_lock); } bnx2_write_phy(bp, bp->mii_adv, new_adv); bnx2_write_phy(bp, bp->mii_bmcr, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); /* Speed up link-up time when the link partner * does not autonegotiate which is very common * in blade servers. Some blade servers use * IPMI for kerboard input and it's important * to minimize link disruptions. Autoneg. involves * exchanging base pages plus 3 next pages and * normally completes in about 120 msec. */ bp->current_interval = BNX2_SERDES_AN_TIMEOUT; bp->serdes_an_pending = 1; mod_timer(&bp->timer, jiffies + bp->current_interval); } else { bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } #define ETHTOOL_ALL_FIBRE_SPEED \ (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) ? \ (ADVERTISED_2500baseX_Full | ADVERTISED_1000baseT_Full) :\ (ADVERTISED_1000baseT_Full) #define ETHTOOL_ALL_COPPER_SPEED \ (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \ ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \ ADVERTISED_1000baseT_Full) #define PHY_ALL_10_100_SPEED (ADVERTISE_10HALF | ADVERTISE_10FULL | \ ADVERTISE_100HALF | ADVERTISE_100FULL | ADVERTISE_CSMA) #define PHY_ALL_1000_SPEED (ADVERTISE_1000HALF | ADVERTISE_1000FULL) static void bnx2_set_default_remote_link(struct bnx2 *bp) { u32 link; if (bp->phy_port == PORT_TP) link = bnx2_shmem_rd(bp, BNX2_RPHY_COPPER_LINK); else link = bnx2_shmem_rd(bp, BNX2_RPHY_SERDES_LINK); if (link & BNX2_NETLINK_SET_LINK_ENABLE_AUTONEG) { bp->req_line_speed = 0; bp->autoneg |= AUTONEG_SPEED; bp->advertising = ADVERTISED_Autoneg; if (link & BNX2_NETLINK_SET_LINK_SPEED_10HALF) bp->advertising |= ADVERTISED_10baseT_Half; if (link & BNX2_NETLINK_SET_LINK_SPEED_10FULL) bp->advertising |= ADVERTISED_10baseT_Full; if (link & BNX2_NETLINK_SET_LINK_SPEED_100HALF) bp->advertising |= ADVERTISED_100baseT_Half; if (link & BNX2_NETLINK_SET_LINK_SPEED_100FULL) bp->advertising |= ADVERTISED_100baseT_Full; if (link & BNX2_NETLINK_SET_LINK_SPEED_1GFULL) bp->advertising |= ADVERTISED_1000baseT_Full; if (link & BNX2_NETLINK_SET_LINK_SPEED_2G5FULL) bp->advertising |= ADVERTISED_2500baseX_Full; } else { bp->autoneg = 0; bp->advertising = 0; bp->req_duplex = DUPLEX_FULL; if (link & BNX2_NETLINK_SET_LINK_SPEED_10) { bp->req_line_speed = SPEED_10; if (link & BNX2_NETLINK_SET_LINK_SPEED_10HALF) bp->req_duplex = DUPLEX_HALF; } if (link & BNX2_NETLINK_SET_LINK_SPEED_100) { bp->req_line_speed = SPEED_100; if (link & BNX2_NETLINK_SET_LINK_SPEED_100HALF) bp->req_duplex = DUPLEX_HALF; } if (link & BNX2_NETLINK_SET_LINK_SPEED_1GFULL) bp->req_line_speed = SPEED_1000; if (link & BNX2_NETLINK_SET_LINK_SPEED_2G5FULL) bp->req_line_speed = SPEED_2500; } } static void bnx2_set_default_link(struct bnx2 *bp) { if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { bnx2_set_default_remote_link(bp); return; } bp->autoneg = AUTONEG_SPEED | AUTONEG_FLOW_CTRL; bp->req_line_speed = 0; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { u32 reg; bp->advertising = ETHTOOL_ALL_FIBRE_SPEED | ADVERTISED_Autoneg; reg = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_CONFIG); reg &= BNX2_PORT_HW_CFG_CFG_DFLT_LINK_MASK; if (reg == BNX2_PORT_HW_CFG_CFG_DFLT_LINK_1G) { bp->autoneg = 0; bp->req_line_speed = bp->line_speed = SPEED_1000; bp->req_duplex = DUPLEX_FULL; } } else bp->advertising = ETHTOOL_ALL_COPPER_SPEED | ADVERTISED_Autoneg; } static void bnx2_send_heart_beat(struct bnx2 *bp) { u32 msg; u32 addr; spin_lock(&bp->indirect_lock); msg = (u32) (++bp->fw_drv_pulse_wr_seq & BNX2_DRV_PULSE_SEQ_MASK); addr = bp->shmem_base + BNX2_DRV_PULSE_MB; BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, addr); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW, msg); spin_unlock(&bp->indirect_lock); } static void bnx2_remote_phy_event(struct bnx2 *bp) { u32 msg; u8 link_up = bp->link_up; u8 old_port; msg = bnx2_shmem_rd(bp, BNX2_LINK_STATUS); if (msg & BNX2_LINK_STATUS_HEART_BEAT_EXPIRED) bnx2_send_heart_beat(bp); msg &= ~BNX2_LINK_STATUS_HEART_BEAT_EXPIRED; if ((msg & BNX2_LINK_STATUS_LINK_UP) == BNX2_LINK_STATUS_LINK_DOWN) bp->link_up = 0; else { u32 speed; bp->link_up = 1; speed = msg & BNX2_LINK_STATUS_SPEED_MASK; bp->duplex = DUPLEX_FULL; switch (speed) { case BNX2_LINK_STATUS_10HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_10FULL: bp->line_speed = SPEED_10; break; case BNX2_LINK_STATUS_100HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_100BASE_T4: /* fall through */ case BNX2_LINK_STATUS_100FULL: bp->line_speed = SPEED_100; break; case BNX2_LINK_STATUS_1000HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_1000FULL: bp->line_speed = SPEED_1000; break; case BNX2_LINK_STATUS_2500HALF: bp->duplex = DUPLEX_HALF; /* fall through */ case BNX2_LINK_STATUS_2500FULL: bp->line_speed = SPEED_2500; break; default: bp->line_speed = 0; break; } bp->flow_ctrl = 0; if ((bp->autoneg & (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) != (AUTONEG_SPEED | AUTONEG_FLOW_CTRL)) { if (bp->duplex == DUPLEX_FULL) bp->flow_ctrl = bp->req_flow_ctrl; } else { if (msg & BNX2_LINK_STATUS_TX_FC_ENABLED) bp->flow_ctrl |= FLOW_CTRL_TX; if (msg & BNX2_LINK_STATUS_RX_FC_ENABLED) bp->flow_ctrl |= FLOW_CTRL_RX; } old_port = bp->phy_port; if (msg & BNX2_LINK_STATUS_SERDES_LINK) bp->phy_port = PORT_FIBRE; else bp->phy_port = PORT_TP; if (old_port != bp->phy_port) bnx2_set_default_link(bp); } if (bp->link_up != link_up) bnx2_report_link(bp); bnx2_set_mac_link(bp); } static int bnx2_set_remote_link(struct bnx2 *bp) { u32 evt_code; spin_lock(&bp->indirect_lock); BNX2_WR(bp, BNX2_PCICFG_REG_WINDOW_ADDRESS, bp->shmem_base + BNX2_FW_EVT_CODE_MB); evt_code = BNX2_RD(bp, BNX2_PCICFG_REG_WINDOW); spin_unlock(&bp->indirect_lock); switch (evt_code) { case BNX2_FW_EVT_CODE_LINK_EVENT: bnx2_remote_phy_event(bp); break; case BNX2_FW_EVT_CODE_SW_TIMER_EXPIRATION_EVENT: default: bnx2_send_heart_beat(bp); break; } return 0; } static int bnx2_setup_copper_phy(struct bnx2 *bp) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 bmcr; u32 new_bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bp->autoneg & AUTONEG_SPEED) { u32 adv_reg, adv1000_reg; u32 new_adv = 0; u32 new_adv1000 = 0; bnx2_read_phy(bp, bp->mii_adv, &adv_reg); adv_reg &= (PHY_ALL_10_100_SPEED | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM); bnx2_read_phy(bp, MII_CTRL1000, &adv1000_reg); adv1000_reg &= PHY_ALL_1000_SPEED; new_adv = ethtool_adv_to_mii_adv_t(bp->advertising); new_adv |= ADVERTISE_CSMA; new_adv |= bnx2_phy_get_pause_adv(bp); new_adv1000 |= ethtool_adv_to_mii_ctrl1000_t(bp->advertising); if ((adv1000_reg != new_adv1000) || (adv_reg != new_adv) || ((bmcr & BMCR_ANENABLE) == 0)) { bnx2_write_phy(bp, bp->mii_adv, new_adv); bnx2_write_phy(bp, MII_CTRL1000, new_adv1000); bnx2_write_phy(bp, bp->mii_bmcr, BMCR_ANRESTART | BMCR_ANENABLE); } else if (bp->link_up) { /* Flow ctrl may have changed from auto to forced */ /* or vice-versa. */ bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } new_bmcr = 0; if (bp->req_line_speed == SPEED_100) { new_bmcr |= BMCR_SPEED100; } if (bp->req_duplex == DUPLEX_FULL) { new_bmcr |= BMCR_FULLDPLX; } if (new_bmcr != bmcr) { u32 bmsr; bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); if (bmsr & BMSR_LSTATUS) { /* Force link down */ bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK); spin_unlock_bh(&bp->phy_lock); bnx2_msleep(50); spin_lock_bh(&bp->phy_lock); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr, &bmsr); } bnx2_write_phy(bp, bp->mii_bmcr, new_bmcr); /* Normally, the new speed is setup after the link has * gone down and up again. In some cases, link will not go * down so we need to set up the new speed here. */ if (bmsr & BMSR_LSTATUS) { bp->line_speed = bp->req_line_speed; bp->duplex = bp->req_duplex; bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } } else { bnx2_resolve_flow_ctrl(bp); bnx2_set_mac_link(bp); } return 0; } static int bnx2_setup_phy(struct bnx2 *bp, u8 port) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { if (bp->loopback == MAC_LOOPBACK) return 0; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { return bnx2_setup_serdes_phy(bp, port); } else { return bnx2_setup_copper_phy(bp); } } static int bnx2_init_5709s_phy(struct bnx2 *bp, int reset_phy) { u32 val; bp->mii_bmcr = MII_BMCR + 0x10; bp->mii_bmsr = MII_BMSR + 0x10; bp->mii_bmsr1 = MII_BNX2_GP_TOP_AN_STATUS1; bp->mii_adv = MII_ADVERTISE + 0x10; bp->mii_lpa = MII_LPA + 0x10; bp->mii_up1 = MII_BNX2_OVER1G_UP1; bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_AER); bnx2_write_phy(bp, MII_BNX2_AER_AER, MII_BNX2_AER_AER_AN_MMD); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); if (reset_phy) bnx2_reset_phy(bp); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_SERDES_DIG); bnx2_read_phy(bp, MII_BNX2_SERDES_DIG_1000XCTL1, &val); val &= ~MII_BNX2_SD_1000XCTL1_AUTODET; val |= MII_BNX2_SD_1000XCTL1_FIBER; /* NEMO temp. FIX */ if (bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG) & 0x80000000) val |= (1 << 3); bnx2_write_phy(bp, MII_BNX2_SERDES_DIG_1000XCTL1, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_OVER1G); bnx2_read_phy(bp, MII_BNX2_OVER1G_UP1, &val); if (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) val |= BCM5708S_UP1_2G5; else val &= ~BCM5708S_UP1_2G5; bnx2_write_phy(bp, MII_BNX2_OVER1G_UP1, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_BAM_NXTPG); bnx2_read_phy(bp, MII_BNX2_BAM_NXTPG_CTL, &val); val |= MII_BNX2_NXTPG_CTL_T2 | MII_BNX2_NXTPG_CTL_BAM; bnx2_write_phy(bp, MII_BNX2_BAM_NXTPG_CTL, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_CL73_USERB0); val = MII_BNX2_CL73_BAM_EN | MII_BNX2_CL73_BAM_STA_MGR_EN | MII_BNX2_CL73_BAM_NP_AFT_BP_EN; bnx2_write_phy(bp, MII_BNX2_CL73_BAM_CTL1, val); bnx2_write_phy(bp, MII_BNX2_BLK_ADDR, MII_BNX2_BLK_ADDR_COMBO_IEEEB0); return 0; } static int bnx2_init_5708s_phy(struct bnx2 *bp, int reset_phy) { u32 val; if (reset_phy) bnx2_reset_phy(bp); bp->mii_up1 = BCM5708S_UP1; bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG3); bnx2_write_phy(bp, BCM5708S_DIG_3_0, BCM5708S_DIG_3_0_USE_IEEE); bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG); bnx2_read_phy(bp, BCM5708S_1000X_CTL1, &val); val |= BCM5708S_1000X_CTL1_FIBER_MODE | BCM5708S_1000X_CTL1_AUTODET_EN; bnx2_write_phy(bp, BCM5708S_1000X_CTL1, val); bnx2_read_phy(bp, BCM5708S_1000X_CTL2, &val); val |= BCM5708S_1000X_CTL2_PLLEL_DET_EN; bnx2_write_phy(bp, BCM5708S_1000X_CTL2, val); if (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) { bnx2_read_phy(bp, BCM5708S_UP1, &val); val |= BCM5708S_UP1_2G5; bnx2_write_phy(bp, BCM5708S_UP1, val); } if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B1)) { /* increase tx signal amplitude */ bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_TX_MISC); bnx2_read_phy(bp, BCM5708S_TX_ACTL1, &val); val &= ~BCM5708S_TX_ACTL1_DRIVER_VCM; bnx2_write_phy(bp, BCM5708S_TX_ACTL1, val); bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG); } val = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_CONFIG) & BNX2_PORT_HW_CFG_CFG_TXCTL3_MASK; if (val) { u32 is_backplane; is_backplane = bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG); if (is_backplane & BNX2_SHARED_HW_CFG_PHY_BACKPLANE) { bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_TX_MISC); bnx2_write_phy(bp, BCM5708S_TX_ACTL3, val); bnx2_write_phy(bp, BCM5708S_BLK_ADDR, BCM5708S_BLK_ADDR_DIG); } } return 0; } static int bnx2_init_5706s_phy(struct bnx2 *bp, int reset_phy) { if (reset_phy) bnx2_reset_phy(bp); bp->phy_flags &= ~BNX2_PHY_FLAG_PARALLEL_DETECT; if (BNX2_CHIP(bp) == BNX2_CHIP_5706) BNX2_WR(bp, BNX2_MISC_GP_HW_CTL0, 0x300); if (bp->dev->mtu > 1500) { u32 val; /* Set extended packet length bit */ bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, (val & 0xfff8) | 0x4000); bnx2_write_phy(bp, 0x1c, 0x6c00); bnx2_read_phy(bp, 0x1c, &val); bnx2_write_phy(bp, 0x1c, (val & 0x3ff) | 0xec02); } else { u32 val; bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val & ~0x4007); bnx2_write_phy(bp, 0x1c, 0x6c00); bnx2_read_phy(bp, 0x1c, &val); bnx2_write_phy(bp, 0x1c, (val & 0x3fd) | 0xec00); } return 0; } static int bnx2_init_copper_phy(struct bnx2 *bp, int reset_phy) { u32 val; if (reset_phy) bnx2_reset_phy(bp); if (bp->phy_flags & BNX2_PHY_FLAG_CRC_FIX) { bnx2_write_phy(bp, 0x18, 0x0c00); bnx2_write_phy(bp, 0x17, 0x000a); bnx2_write_phy(bp, 0x15, 0x310b); bnx2_write_phy(bp, 0x17, 0x201f); bnx2_write_phy(bp, 0x15, 0x9506); bnx2_write_phy(bp, 0x17, 0x401f); bnx2_write_phy(bp, 0x15, 0x14e2); bnx2_write_phy(bp, 0x18, 0x0400); } if (bp->phy_flags & BNX2_PHY_FLAG_DIS_EARLY_DAC) { bnx2_write_phy(bp, MII_BNX2_DSP_ADDRESS, MII_BNX2_DSP_EXPAND_REG | 0x8); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &val); val &= ~(1 << 8); bnx2_write_phy(bp, MII_BNX2_DSP_RW_PORT, val); } if (bp->dev->mtu > 1500) { /* Set extended packet length bit */ bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val | 0x4000); bnx2_read_phy(bp, 0x10, &val); bnx2_write_phy(bp, 0x10, val | 0x1); } else { bnx2_write_phy(bp, 0x18, 0x7); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val & ~0x4007); bnx2_read_phy(bp, 0x10, &val); bnx2_write_phy(bp, 0x10, val & ~0x1); } /* ethernet@wirespeed & auto-mdix*/ bnx2_write_phy(bp, 0x18, 0x7007); bnx2_read_phy(bp, 0x18, &val); bnx2_write_phy(bp, 0x18, val | (1 << 15) | (1 << 4) | (1 << 9)); return 0; } static int bnx2_init_phy(struct bnx2 *bp, int reset_phy) __releases(&bp->phy_lock) __acquires(&bp->phy_lock) { u32 val; int rc = 0; bp->phy_flags &= ~BNX2_PHY_FLAG_INT_MODE_MASK; bp->phy_flags |= BNX2_PHY_FLAG_INT_MODE_LINK_READY; bp->mii_bmcr = MII_BMCR; bp->mii_bmsr = MII_BMSR; bp->mii_bmsr1 = MII_BMSR; bp->mii_adv = MII_ADVERTISE; bp->mii_lpa = MII_LPA; BNX2_WR(bp, BNX2_EMAC_ATTENTION_ENA, BNX2_EMAC_ATTENTION_ENA_LINK); if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) goto setup_phy; bnx2_read_phy(bp, MII_PHYSID1, &val); bp->phy_id = val << 16; bnx2_read_phy(bp, MII_PHYSID2, &val); bp->phy_id |= val & 0xffff; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { if (BNX2_CHIP(bp) == BNX2_CHIP_5706) rc = bnx2_init_5706s_phy(bp, reset_phy); else if (BNX2_CHIP(bp) == BNX2_CHIP_5708) rc = bnx2_init_5708s_phy(bp, reset_phy); else if (BNX2_CHIP(bp) == BNX2_CHIP_5709) rc = bnx2_init_5709s_phy(bp, reset_phy); } else { rc = bnx2_init_copper_phy(bp, reset_phy); } setup_phy: if (!rc) rc = bnx2_setup_phy(bp, bp->phy_port); return rc; } static int bnx2_set_mac_loopback(struct bnx2 *bp) { u32 mac_mode; mac_mode = BNX2_RD(bp, BNX2_EMAC_MODE); mac_mode &= ~BNX2_EMAC_MODE_PORT; mac_mode |= BNX2_EMAC_MODE_MAC_LOOP | BNX2_EMAC_MODE_FORCE_LINK; BNX2_WR(bp, BNX2_EMAC_MODE, mac_mode); bp->link_up = 1; return 0; } static int bnx2_test_link(struct bnx2 *); static int bnx2_set_phy_loopback(struct bnx2 *bp) { u32 mac_mode; int rc, i; spin_lock_bh(&bp->phy_lock); rc = bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK | BMCR_FULLDPLX | BMCR_SPEED1000); spin_unlock_bh(&bp->phy_lock); if (rc) return rc; for (i = 0; i < 10; i++) { if (bnx2_test_link(bp) == 0) break; bnx2_msleep(100); } mac_mode = BNX2_RD(bp, BNX2_EMAC_MODE); mac_mode &= ~(BNX2_EMAC_MODE_PORT | BNX2_EMAC_MODE_HALF_DUPLEX | BNX2_EMAC_MODE_MAC_LOOP | BNX2_EMAC_MODE_FORCE_LINK | BNX2_EMAC_MODE_25G_MODE); mac_mode |= BNX2_EMAC_MODE_PORT_GMII; BNX2_WR(bp, BNX2_EMAC_MODE, mac_mode); bp->link_up = 1; return 0; } static void bnx2_dump_mcp_state(struct bnx2 *bp) { struct net_device *dev = bp->dev; u32 mcp_p0, mcp_p1; netdev_err(dev, "<--- start MCP states dump --->\n"); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { mcp_p0 = BNX2_MCP_STATE_P0; mcp_p1 = BNX2_MCP_STATE_P1; } else { mcp_p0 = BNX2_MCP_STATE_P0_5708; mcp_p1 = BNX2_MCP_STATE_P1_5708; } netdev_err(dev, "DEBUG: MCP_STATE_P0[%08x] MCP_STATE_P1[%08x]\n", bnx2_reg_rd_ind(bp, mcp_p0), bnx2_reg_rd_ind(bp, mcp_p1)); netdev_err(dev, "DEBUG: MCP mode[%08x] state[%08x] evt_mask[%08x]\n", bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_MODE), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_STATE), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_EVENT_MASK)); netdev_err(dev, "DEBUG: pc[%08x] pc[%08x] instr[%08x]\n", bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER), bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_INSTRUCTION)); netdev_err(dev, "DEBUG: shmem states:\n"); netdev_err(dev, "DEBUG: drv_mb[%08x] fw_mb[%08x] link_status[%08x]", bnx2_shmem_rd(bp, BNX2_DRV_MB), bnx2_shmem_rd(bp, BNX2_FW_MB), bnx2_shmem_rd(bp, BNX2_LINK_STATUS)); pr_cont(" drv_pulse_mb[%08x]\n", bnx2_shmem_rd(bp, BNX2_DRV_PULSE_MB)); netdev_err(dev, "DEBUG: dev_info_signature[%08x] reset_type[%08x]", bnx2_shmem_rd(bp, BNX2_DEV_INFO_SIGNATURE), bnx2_shmem_rd(bp, BNX2_BC_STATE_RESET_TYPE)); pr_cont(" condition[%08x]\n", bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION)); DP_SHMEM_LINE(bp, BNX2_BC_STATE_RESET_TYPE); DP_SHMEM_LINE(bp, 0x3cc); DP_SHMEM_LINE(bp, 0x3dc); DP_SHMEM_LINE(bp, 0x3ec); netdev_err(dev, "DEBUG: 0x3fc[%08x]\n", bnx2_shmem_rd(bp, 0x3fc)); netdev_err(dev, "<--- end MCP states dump --->\n"); } static int bnx2_fw_sync(struct bnx2 *bp, u32 msg_data, int ack, int silent) { int i; u32 val; bp->fw_wr_seq++; msg_data |= bp->fw_wr_seq; bnx2_shmem_wr(bp, BNX2_DRV_MB, msg_data); if (!ack) return 0; /* wait for an acknowledgement. */ for (i = 0; i < (BNX2_FW_ACK_TIME_OUT_MS / 10); i++) { bnx2_msleep(10); val = bnx2_shmem_rd(bp, BNX2_FW_MB); if ((val & BNX2_FW_MSG_ACK) == (msg_data & BNX2_DRV_MSG_SEQ)) break; } if ((msg_data & BNX2_DRV_MSG_DATA) == BNX2_DRV_MSG_DATA_WAIT0) return 0; /* If we timed out, inform the firmware that this is the case. */ if ((val & BNX2_FW_MSG_ACK) != (msg_data & BNX2_DRV_MSG_SEQ)) { msg_data &= ~BNX2_DRV_MSG_CODE; msg_data |= BNX2_DRV_MSG_CODE_FW_TIMEOUT; bnx2_shmem_wr(bp, BNX2_DRV_MB, msg_data); if (!silent) { pr_err("fw sync timeout, reset code = %x\n", msg_data); bnx2_dump_mcp_state(bp); } return -EBUSY; } if ((val & BNX2_FW_MSG_STATUS_MASK) != BNX2_FW_MSG_STATUS_OK) return -EIO; return 0; } static int bnx2_init_5709_context(struct bnx2 *bp) { int i, ret = 0; u32 val; val = BNX2_CTX_COMMAND_ENABLED | BNX2_CTX_COMMAND_MEM_INIT | (1 << 12); val |= (BNX2_PAGE_BITS - 8) << 16; BNX2_WR(bp, BNX2_CTX_COMMAND, val); for (i = 0; i < 10; i++) { val = BNX2_RD(bp, BNX2_CTX_COMMAND); if (!(val & BNX2_CTX_COMMAND_MEM_INIT)) break; udelay(2); } if (val & BNX2_CTX_COMMAND_MEM_INIT) return -EBUSY; for (i = 0; i < bp->ctx_pages; i++) { int j; if (bp->ctx_blk[i]) memset(bp->ctx_blk[i], 0, BNX2_PAGE_SIZE); else return -ENOMEM; BNX2_WR(bp, BNX2_CTX_HOST_PAGE_TBL_DATA0, (bp->ctx_blk_mapping[i] & 0xffffffff) | BNX2_CTX_HOST_PAGE_TBL_DATA0_VALID); BNX2_WR(bp, BNX2_CTX_HOST_PAGE_TBL_DATA1, (u64) bp->ctx_blk_mapping[i] >> 32); BNX2_WR(bp, BNX2_CTX_HOST_PAGE_TBL_CTRL, i | BNX2_CTX_HOST_PAGE_TBL_CTRL_WRITE_REQ); for (j = 0; j < 10; j++) { val = BNX2_RD(bp, BNX2_CTX_HOST_PAGE_TBL_CTRL); if (!(val & BNX2_CTX_HOST_PAGE_TBL_CTRL_WRITE_REQ)) break; udelay(5); } if (val & BNX2_CTX_HOST_PAGE_TBL_CTRL_WRITE_REQ) { ret = -EBUSY; break; } } return ret; } static void bnx2_init_context(struct bnx2 *bp) { u32 vcid; vcid = 96; while (vcid) { u32 vcid_addr, pcid_addr, offset; int i; vcid--; if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { u32 new_vcid; vcid_addr = GET_PCID_ADDR(vcid); if (vcid & 0x8) { new_vcid = 0x60 + (vcid & 0xf0) + (vcid & 0x7); } else { new_vcid = vcid; } pcid_addr = GET_PCID_ADDR(new_vcid); } else { vcid_addr = GET_CID_ADDR(vcid); pcid_addr = vcid_addr; } for (i = 0; i < (CTX_SIZE / PHY_CTX_SIZE); i++) { vcid_addr += (i << PHY_CTX_SHIFT); pcid_addr += (i << PHY_CTX_SHIFT); BNX2_WR(bp, BNX2_CTX_VIRT_ADDR, vcid_addr); BNX2_WR(bp, BNX2_CTX_PAGE_TBL, pcid_addr); /* Zero out the context. */ for (offset = 0; offset < PHY_CTX_SIZE; offset += 4) bnx2_ctx_wr(bp, vcid_addr, offset, 0); } } } static int bnx2_alloc_bad_rbuf(struct bnx2 *bp) { u16 *good_mbuf; u32 good_mbuf_cnt; u32 val; good_mbuf = kmalloc(512 * sizeof(u16), GFP_KERNEL); if (good_mbuf == NULL) return -ENOMEM; BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_SET_BITS_RX_MBUF_ENABLE); good_mbuf_cnt = 0; /* Allocate a bunch of mbufs and save the good ones in an array. */ val = bnx2_reg_rd_ind(bp, BNX2_RBUF_STATUS1); while (val & BNX2_RBUF_STATUS1_FREE_COUNT) { bnx2_reg_wr_ind(bp, BNX2_RBUF_COMMAND, BNX2_RBUF_COMMAND_ALLOC_REQ); val = bnx2_reg_rd_ind(bp, BNX2_RBUF_FW_BUF_ALLOC); val &= BNX2_RBUF_FW_BUF_ALLOC_VALUE; /* The addresses with Bit 9 set are bad memory blocks. */ if (!(val & (1 << 9))) { good_mbuf[good_mbuf_cnt] = (u16) val; good_mbuf_cnt++; } val = bnx2_reg_rd_ind(bp, BNX2_RBUF_STATUS1); } /* Free the good ones back to the mbuf pool thus discarding * all the bad ones. */ while (good_mbuf_cnt) { good_mbuf_cnt--; val = good_mbuf[good_mbuf_cnt]; val = (val << 9) | val | 1; bnx2_reg_wr_ind(bp, BNX2_RBUF_FW_BUF_FREE, val); } kfree(good_mbuf); return 0; } static void bnx2_set_mac_addr(struct bnx2 *bp, u8 *mac_addr, u32 pos) { u32 val; val = (mac_addr[0] << 8) | mac_addr[1]; BNX2_WR(bp, BNX2_EMAC_MAC_MATCH0 + (pos * 8), val); val = (mac_addr[2] << 24) | (mac_addr[3] << 16) | (mac_addr[4] << 8) | mac_addr[5]; BNX2_WR(bp, BNX2_EMAC_MAC_MATCH1 + (pos * 8), val); } static inline int bnx2_alloc_rx_page(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, u16 index, gfp_t gfp) { dma_addr_t mapping; struct bnx2_sw_pg *rx_pg = &rxr->rx_pg_ring[index]; struct bnx2_rx_bd *rxbd = &rxr->rx_pg_desc_ring[BNX2_RX_RING(index)][BNX2_RX_IDX(index)]; struct page *page = alloc_page(gfp); if (!page) return -ENOMEM; #if (LINUX_VERSION_CODE >= 0x02061b) mapping = dma_map_page(&bp->pdev->dev, page, 0, PAGE_SIZE, PCI_DMA_FROMDEVICE); if (dma_mapping_error(&bp->pdev->dev, mapping)) { #else mapping = pci_map_page(bp->pdev, page, 0, PAGE_SIZE, PCI_DMA_FROMDEVICE); if (pci_dma_mapping_error(mapping)) { #endif __free_page(page); return -EIO; } rx_pg->page = page; dma_unmap_addr_set(rx_pg, mapping, mapping); rxbd->rx_bd_haddr_hi = (u64) mapping >> 32; rxbd->rx_bd_haddr_lo = (u64) mapping & 0xffffffff; return 0; } static void bnx2_free_rx_page(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, u16 index) { struct bnx2_sw_pg *rx_pg = &rxr->rx_pg_ring[index]; struct page *page = rx_pg->page; if (!page) return; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(rx_pg, mapping), PAGE_SIZE, PCI_DMA_FROMDEVICE); #else pci_unmap_page(bp->pdev, dma_unmap_addr(rx_pg, mapping), PAGE_SIZE, PCI_DMA_FROMDEVICE); #endif __free_page(page); rx_pg->page = NULL; } static inline int bnx2_alloc_rx_skb(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, u16 index, gfp_t gfp) { struct sk_buff *skb; struct bnx2_sw_bd *rx_buf = &rxr->rx_buf_ring[index]; dma_addr_t mapping; struct bnx2_rx_bd *rxbd = &rxr->rx_desc_ring[BNX2_RX_RING(index)][BNX2_RX_IDX(index)]; unsigned long align; skb = __netdev_alloc_skb(bp->dev, bp->rx_buf_size, gfp); if (skb == NULL) { return -ENOMEM; } if (unlikely((align = (unsigned long) skb->data & (BNX2_RX_ALIGN - 1)))) skb_reserve(skb, BNX2_RX_ALIGN - align); #if (LINUX_VERSION_CODE >= 0x02061b) mapping = dma_map_single(&bp->pdev->dev, skb->data, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); if (dma_mapping_error(&bp->pdev->dev, mapping)) { #else mapping = pci_map_single(bp->pdev, skb->data, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); if (pci_dma_mapping_error(mapping)) { #endif dev_kfree_skb(skb); return -EIO; } rx_buf->skb = skb; rx_buf->desc = (struct l2_fhdr *) skb->data; dma_unmap_addr_set(rx_buf, mapping, mapping); rxbd->rx_bd_haddr_hi = (u64) mapping >> 32; rxbd->rx_bd_haddr_lo = (u64) mapping & 0xffffffff; rxr->rx_prod_bseq += bp->rx_buf_use_size; return 0; } static int bnx2_phy_event_is_set(struct bnx2 *bp, struct bnx2_napi *bnapi, u32 event) { struct status_block *sblk = bnapi->status_blk.msi; u32 new_link_state, old_link_state; int is_set = 1; new_link_state = sblk->status_attn_bits & event; old_link_state = sblk->status_attn_bits_ack & event; if (new_link_state != old_link_state) { if (new_link_state) BNX2_WR(bp, BNX2_PCICFG_STATUS_BIT_SET_CMD, event); else BNX2_WR(bp, BNX2_PCICFG_STATUS_BIT_CLEAR_CMD, event); } else is_set = 0; return is_set; } static void bnx2_phy_int(struct bnx2 *bp, struct bnx2_napi *bnapi) { spin_lock(&bp->phy_lock); if (bnx2_phy_event_is_set(bp, bnapi, STATUS_ATTN_BITS_LINK_STATE)) bnx2_set_link(bp); if (bnx2_phy_event_is_set(bp, bnapi, STATUS_ATTN_BITS_TIMER_ABORT)) bnx2_set_remote_link(bp); spin_unlock(&bp->phy_lock); } static inline u16 bnx2_get_hw_tx_cons(struct bnx2_napi *bnapi) { u16 cons; /* Tell compiler that status block fields can change. */ barrier(); cons = *bnapi->hw_tx_cons_ptr; barrier(); if (unlikely((cons & BNX2_MAX_TX_DESC_CNT) == BNX2_MAX_TX_DESC_CNT)) cons++; return cons; } static int #if defined(__VMKLNX__) bnx2_tx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget, int check_queue) #else bnx2_tx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget) #endif { struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; u16 hw_cons, sw_cons, sw_ring_cons; #ifndef BCM_HAVE_MULTI_QUEUE int tx_pkt = 0; #else int tx_pkt = 0, index; struct netdev_queue *txq; index = (bnapi - bp->bnx2_napi); txq = netdev_get_tx_queue(bp->dev, index); #endif hw_cons = bnx2_get_hw_tx_cons(bnapi); sw_cons = txr->tx_cons; while (sw_cons != hw_cons) { struct bnx2_sw_tx_bd *tx_buf; struct sk_buff *skb; int i, last; sw_ring_cons = BNX2_TX_RING_IDX(sw_cons); tx_buf = &txr->tx_buf_ring[sw_ring_cons]; skb = tx_buf->skb; /* prefetch skb_end_pointer() to speedup skb_shinfo(skb) */ prefetch(&skb->end); #ifdef BCM_TSO /* partial BD completions possible with TSO packets */ if (tx_buf->is_gso) { u16 last_idx, last_ring_idx; last_idx = sw_cons + tx_buf->nr_frags + 1; last_ring_idx = sw_ring_cons + tx_buf->nr_frags + 1; if (unlikely(last_ring_idx >= BNX2_MAX_TX_DESC_CNT)) { last_idx++; } if (((s16) ((s16) last_idx - (s16) hw_cons)) > 0) { break; } } #endif #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #else pci_unmap_single(bp->pdev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #endif tx_buf->skb = NULL; last = tx_buf->nr_frags; for (i = 0; i < last; i++) { struct bnx2_sw_tx_bd *tx_buf; sw_cons = BNX2_NEXT_TX_BD(sw_cons); tx_buf = &txr->tx_buf_ring[BNX2_TX_RING_IDX(sw_cons)]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, #else pci_unmap_page(bp->pdev, #endif dma_unmap_addr(tx_buf, mapping), skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); } sw_cons = BNX2_NEXT_TX_BD(sw_cons); dev_kfree_skb(skb); #if defined(BNX2_ENABLE_NETQUEUE) bnapi->stats.tx_packets++; bnapi->stats.tx_bytes += skb->len; bnapi->tx_packets_processed++; wmb(); #endif tx_pkt++; if (tx_pkt == budget) break; if (hw_cons == sw_cons) hw_cons = bnx2_get_hw_tx_cons(bnapi); } txr->hw_tx_cons = hw_cons; txr->tx_cons = sw_cons; /* Need to make the tx_cons update visible to bnx2_start_xmit() * before checking for netif_tx_queue_stopped(). Without the * memory barrier, there is a small possibility that bnx2_start_xmit() * will miss it and cause the queue to be stopped forever. */ smp_mb(); #if defined(BNX2_ENABLE_NETQUEUE) if ((!check_queue) || (bp->netq_state & BNX2_NETQ_SUSPENDED)) return tx_pkt; #endif #ifndef BCM_HAVE_MULTI_QUEUE if (unlikely(netif_queue_stopped(bp->dev)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) { netif_tx_lock(bp->dev); if ((netif_queue_stopped(bp->dev)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) netif_wake_queue(bp->dev); netif_tx_unlock(bp->dev); } #else if (unlikely(netif_tx_queue_stopped(txq)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) { __netif_tx_lock(txq, smp_processor_id()); if ((netif_tx_queue_stopped(txq)) && (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh)) netif_tx_wake_queue(txq); __netif_tx_unlock(txq); } #endif return tx_pkt; } static void bnx2_reuse_rx_skb_pages(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, struct sk_buff *skb, int count) { struct bnx2_sw_pg *cons_rx_pg, *prod_rx_pg; struct bnx2_rx_bd *cons_bd, *prod_bd; int i; u16 hw_prod, prod; u16 cons = rxr->rx_pg_cons; cons_rx_pg = &rxr->rx_pg_ring[cons]; /* The caller was unable to allocate a new page to replace the * last one in the frags array, so we need to recycle that page * and then free the skb. */ if (skb) { struct page *page; struct skb_shared_info *shinfo; shinfo = skb_shinfo(skb); shinfo->nr_frags--; page = skb_frag_page(&shinfo->frags[shinfo->nr_frags]); __skb_frag_set_page(&shinfo->frags[shinfo->nr_frags], NULL); cons_rx_pg->page = page; dev_kfree_skb(skb); } hw_prod = rxr->rx_pg_prod; for (i = 0; i < count; i++) { prod = BNX2_RX_PG_RING_IDX(hw_prod); prod_rx_pg = &rxr->rx_pg_ring[prod]; cons_rx_pg = &rxr->rx_pg_ring[cons]; cons_bd = &rxr->rx_pg_desc_ring[BNX2_RX_RING(cons)] [BNX2_RX_IDX(cons)]; prod_bd = &rxr->rx_pg_desc_ring[BNX2_RX_RING(prod)] [BNX2_RX_IDX(prod)]; if (prod != cons) { prod_rx_pg->page = cons_rx_pg->page; cons_rx_pg->page = NULL; dma_unmap_addr_set(prod_rx_pg, mapping, dma_unmap_addr(cons_rx_pg, mapping)); prod_bd->rx_bd_haddr_hi = cons_bd->rx_bd_haddr_hi; prod_bd->rx_bd_haddr_lo = cons_bd->rx_bd_haddr_lo; } cons = BNX2_RX_PG_RING_IDX(BNX2_NEXT_RX_BD(cons)); hw_prod = BNX2_NEXT_RX_BD(hw_prod); } rxr->rx_pg_prod = hw_prod; rxr->rx_pg_cons = cons; } static inline void bnx2_reuse_rx_skb(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, struct sk_buff *skb, u16 cons, u16 prod) { struct bnx2_sw_bd *cons_rx_buf, *prod_rx_buf; struct bnx2_rx_bd *cons_bd, *prod_bd; cons_rx_buf = &rxr->rx_buf_ring[cons]; prod_rx_buf = &rxr->rx_buf_ring[prod]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_sync_single_for_device(&bp->pdev->dev, #else pci_dma_sync_single_for_device(bp->pdev, #endif dma_unmap_addr(cons_rx_buf, mapping), BNX2_RX_OFFSET + BNX2_RX_COPY_THRESH, PCI_DMA_FROMDEVICE); rxr->rx_prod_bseq += bp->rx_buf_use_size; prod_rx_buf->skb = skb; prod_rx_buf->desc = (struct l2_fhdr *) skb->data; if (cons == prod) return; dma_unmap_addr_set(prod_rx_buf, mapping, dma_unmap_addr(cons_rx_buf, mapping)); cons_bd = &rxr->rx_desc_ring[BNX2_RX_RING(cons)][BNX2_RX_IDX(cons)]; prod_bd = &rxr->rx_desc_ring[BNX2_RX_RING(prod)][BNX2_RX_IDX(prod)]; prod_bd->rx_bd_haddr_hi = cons_bd->rx_bd_haddr_hi; prod_bd->rx_bd_haddr_lo = cons_bd->rx_bd_haddr_lo; } static int bnx2_rx_skb(struct bnx2 *bp, struct bnx2_rx_ring_info *rxr, struct sk_buff *skb, unsigned int len, unsigned int hdr_len, dma_addr_t dma_addr, u32 ring_idx) { int err; u16 prod = ring_idx & 0xffff; err = bnx2_alloc_rx_skb(bp, rxr, prod, GFP_ATOMIC); if (unlikely(err)) { bnx2_reuse_rx_skb(bp, rxr, skb, (u16) (ring_idx >> 16), prod); if (hdr_len) { unsigned int raw_len = len + 4; int pages = PAGE_ALIGN(raw_len - hdr_len) >> PAGE_SHIFT; bnx2_reuse_rx_skb_pages(bp, rxr, NULL, pages); } return err; } skb_reserve(skb, BNX2_RX_OFFSET); #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, dma_addr, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); #else pci_unmap_single(bp->pdev, dma_addr, bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); #endif if (hdr_len == 0) { skb_put(skb, len); return 0; } else { unsigned int i, frag_len, frag_size, pages; struct bnx2_sw_pg *rx_pg; u16 pg_cons = rxr->rx_pg_cons; u16 pg_prod = rxr->rx_pg_prod; frag_size = len + 4 - hdr_len; pages = PAGE_ALIGN(frag_size) >> PAGE_SHIFT; skb_put(skb, hdr_len); for (i = 0; i < pages; i++) { dma_addr_t mapping_old; frag_len = min(frag_size, (unsigned int) PAGE_SIZE); if (unlikely(frag_len <= 4)) { unsigned int tail = 4 - frag_len; rxr->rx_pg_cons = pg_cons; rxr->rx_pg_prod = pg_prod; bnx2_reuse_rx_skb_pages(bp, rxr, NULL, pages - i); skb->len -= tail; if (i == 0) { skb->tail -= tail; } else { skb_frag_t *frag = &skb_shinfo(skb)->frags[i - 1]; skb_frag_size_sub(frag, tail); skb->data_len -= tail; } return 0; } rx_pg = &rxr->rx_pg_ring[pg_cons]; /* Don't unmap yet. If we're unable to allocate a new * page, we need to recycle the page and the DMA addr. */ mapping_old = dma_unmap_addr(rx_pg, mapping); if (i == pages - 1) frag_len -= 4; bnx2_skb_fill_page_desc(skb, i, rx_pg->page, 0, frag_len); rx_pg->page = NULL; err = bnx2_alloc_rx_page(bp, rxr, BNX2_RX_PG_RING_IDX(pg_prod), GFP_ATOMIC); if (unlikely(err)) { rxr->rx_pg_cons = pg_cons; rxr->rx_pg_prod = pg_prod; bnx2_reuse_rx_skb_pages(bp, rxr, skb, pages - i); return err; } #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, mapping_old, PAGE_SIZE, PCI_DMA_FROMDEVICE); #else pci_unmap_page(bp->pdev, mapping_old, PAGE_SIZE, PCI_DMA_FROMDEVICE); #endif frag_size -= frag_len; skb->data_len += frag_len; skb->truesize += PAGE_SIZE; skb->len += frag_len; pg_prod = BNX2_NEXT_RX_BD(pg_prod); pg_cons = BNX2_RX_PG_RING_IDX(BNX2_NEXT_RX_BD(pg_cons)); } rxr->rx_pg_prod = pg_prod; rxr->rx_pg_cons = pg_cons; } return 0; } static inline u16 bnx2_get_hw_rx_cons(struct bnx2_napi *bnapi) { u16 cons; /* Tell compiler that status block fields can change. */ barrier(); cons = *bnapi->hw_rx_cons_ptr; barrier(); if (unlikely((cons & BNX2_MAX_RX_DESC_CNT) == BNX2_MAX_RX_DESC_CNT)) cons++; return cons; } static int bnx2_rx_int(struct bnx2 *bp, struct bnx2_napi *bnapi, int budget) { struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; u16 hw_cons, sw_cons, sw_ring_cons, sw_prod, sw_ring_prod; struct l2_fhdr *rx_hdr; int rx_pkt = 0, pg_ring_used = 0; #if defined(BNX2_ENABLE_NETQUEUE) int index = (bnapi - bp->bnx2_napi); #endif hw_cons = bnx2_get_hw_rx_cons(bnapi); sw_cons = rxr->rx_cons; sw_prod = rxr->rx_prod; /* Memory barrier necessary as speculative reads of the rx * buffer can be ahead of the index in the status block */ rmb(); while (sw_cons != hw_cons) { unsigned int len, hdr_len; u32 status; struct bnx2_sw_bd *rx_buf, *next_rx_buf; struct sk_buff *skb; dma_addr_t dma_addr; u16 vtag = 0; int hw_vlan __maybe_unused = 0; u16 next_ring_idx; sw_ring_cons = BNX2_RX_RING_IDX(sw_cons); sw_ring_prod = BNX2_RX_RING_IDX(sw_prod); rx_buf = &rxr->rx_buf_ring[sw_ring_cons]; skb = rx_buf->skb; prefetchw(skb); next_ring_idx = BNX2_RX_RING_IDX(BNX2_NEXT_RX_BD(sw_cons)); next_rx_buf = &rxr->rx_buf_ring[next_ring_idx]; prefetch(next_rx_buf->desc); rx_buf->skb = NULL; dma_addr = dma_unmap_addr(rx_buf, mapping); #if (LINUX_VERSION_CODE >= 0x02061b) dma_sync_single_for_cpu(&bp->pdev->dev, dma_addr, #else pci_dma_sync_single_for_cpu(bp->pdev, dma_addr, #endif BNX2_RX_OFFSET + BNX2_RX_COPY_THRESH, PCI_DMA_FROMDEVICE); rx_hdr = rx_buf->desc; len = rx_hdr->l2_fhdr_pkt_len; status = rx_hdr->l2_fhdr_status; hdr_len = 0; if (status & L2_FHDR_STATUS_SPLIT) { hdr_len = rx_hdr->l2_fhdr_ip_xsum; pg_ring_used = 1; } else if (len > bp->rx_jumbo_thresh) { hdr_len = bp->rx_jumbo_thresh; pg_ring_used = 1; } if (unlikely(status & (L2_FHDR_ERRORS_BAD_CRC | L2_FHDR_ERRORS_PHY_DECODE | L2_FHDR_ERRORS_ALIGNMENT | L2_FHDR_ERRORS_TOO_SHORT | L2_FHDR_ERRORS_GIANT_FRAME))) { #if defined(BNX2_ENABLE_NETQUEUE) bnapi->stats.rx_errors++; if (status & L2_FHDR_ERRORS_BAD_CRC) bnapi->stats.rx_crc_errors++; if (status & (L2_FHDR_ERRORS_TOO_SHORT | L2_FHDR_ERRORS_GIANT_FRAME)) bnapi->stats.rx_frame_errors++; #endif bnx2_reuse_rx_skb(bp, rxr, skb, sw_ring_cons, sw_ring_prod); if (pg_ring_used) { int pages; pages = PAGE_ALIGN(len - hdr_len) >> PAGE_SHIFT; bnx2_reuse_rx_skb_pages(bp, rxr, NULL, pages); } goto next_rx; } len -= 4; if (len <= bp->rx_copy_thresh) { struct sk_buff *new_skb; new_skb = netdev_alloc_skb(bp->dev, len + 6); if (new_skb == NULL) { bnx2_reuse_rx_skb(bp, rxr, skb, sw_ring_cons, sw_ring_prod); goto next_rx; } /* aligned copy */ #if (LINUX_VERSION_CODE >= 0x20616) skb_copy_from_linear_data_offset(skb, BNX2_RX_OFFSET - 6, new_skb->data, len + 6); #else memcpy(new_skb->data, skb->data + BNX2_RX_OFFSET - 6, len + 6); #endif skb_reserve(new_skb, 6); skb_put(new_skb, len); bnx2_reuse_rx_skb(bp, rxr, skb, sw_ring_cons, sw_ring_prod); skb = new_skb; } else if (unlikely(bnx2_rx_skb(bp, rxr, skb, len, hdr_len, dma_addr, (sw_ring_cons << 16) | sw_ring_prod))) goto next_rx; if ((status & L2_FHDR_STATUS_L2_VLAN_TAG) && !(bp->rx_mode & BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG)) { vtag = rx_hdr->l2_fhdr_vlan_tag; #ifdef NEW_VLAN __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vtag); #else #ifdef BCM_VLAN if (bp->vlgrp) hw_vlan = 1; else #endif { struct vlan_ethhdr *ve = (struct vlan_ethhdr *) __skb_push(skb, 4); bcm_memmove(ve, skb->data + 4, ETH_ALEN * 2); ve->h_vlan_proto = htons(ETH_P_8021Q); ve->h_vlan_TCI = htons(vtag); len += 4; } #endif } skb->protocol = eth_type_trans(skb, bp->dev); if ((len > (bp->dev->mtu + ETH_HLEN)) && (ntohs(skb->protocol) != 0x8100)) { dev_kfree_skb(skb); goto next_rx; } skb->ip_summed = CHECKSUM_NONE; if (bp->rx_csum && (status & (L2_FHDR_STATUS_TCP_SEGMENT | L2_FHDR_STATUS_UDP_DATAGRAM))) { if (likely((status & (L2_FHDR_ERRORS_TCP_XSUM | L2_FHDR_ERRORS_UDP_XSUM)) == 0)) skb->ip_summed = CHECKSUM_UNNECESSARY; } #ifdef NETIF_F_RXHASH if ((bp->dev->features & NETIF_F_RXHASH) && ((status & L2_FHDR_STATUS_USE_RXHASH) == L2_FHDR_STATUS_USE_RXHASH)) skb->rxhash = rx_hdr->l2_fhdr_hash; #endif skb_record_rx_queue(skb, bnapi - &bp->bnx2_napi[0]); #if defined(BNX2_ENABLE_NETQUEUE) vmknetddi_queueops_set_skb_queueid(skb, VMKNETDDI_QUEUEOPS_MK_RX_QUEUEID(index)); #endif #if defined(NETIF_F_GRO) && defined(BNX2_NEW_NAPI) #if defined(BCM_VLAN) && !defined(NEW_VLAN) if (hw_vlan) vlan_gro_receive(&bnapi->napi, bp->vlgrp, vtag, skb); else #endif napi_gro_receive(&bnapi->napi, skb); #else #ifdef BCM_VLAN if (hw_vlan) vlan_hwaccel_receive_skb(skb, bp->vlgrp, vtag); else #endif netif_receive_skb(skb); #endif #if (LINUX_VERSION_CODE < 0x02061b) || defined(__VMKLNX__) bp->dev->last_rx = jiffies; #endif rx_pkt++; #if defined(BNX2_ENABLE_NETQUEUE) /* Update queue specific stats */ bnapi->stats.rx_packets++; bnapi->stats.rx_bytes += len; #endif next_rx: sw_cons = BNX2_NEXT_RX_BD(sw_cons); sw_prod = BNX2_NEXT_RX_BD(sw_prod); if ((rx_pkt == budget)) break; /* Refresh hw_cons to see if there is new work */ if (sw_cons == hw_cons) { hw_cons = bnx2_get_hw_rx_cons(bnapi); rmb(); } } rxr->rx_cons = sw_cons; rxr->rx_prod = sw_prod; if (pg_ring_used) BNX2_WR16(bp, rxr->rx_pg_bidx_addr, rxr->rx_pg_prod); BNX2_WR16(bp, rxr->rx_bidx_addr, sw_prod); BNX2_WR(bp, rxr->rx_bseq_addr, rxr->rx_prod_bseq); mmiowb(); return rx_pkt; } #ifdef CONFIG_PCI_MSI /* MSI ISR - The only difference between this and the INTx ISR * is that the MSI interrupt is always serviced. */ static irqreturn_t #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_msi(int irq, void *dev_instance) #else bnx2_msi(int irq, void *dev_instance, struct pt_regs *regs) #endif { struct bnx2_napi *bnapi = dev_instance; struct bnx2 *bp = bnapi->bp; prefetch(bnapi->status_blk.msi); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, #if defined(__VMKLNX__) bnapi->int_num | #endif BNX2_PCICFG_INT_ACK_CMD_USE_INT_HC_PARAM | BNX2_PCICFG_INT_ACK_CMD_MASK_INT); /* Return here if interrupt is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; #ifdef BNX2_NEW_NAPI napi_schedule(&bnapi->napi); #else netif_rx_schedule(bp->dev); #endif return IRQ_HANDLED; } static irqreturn_t #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_msi_1shot(int irq, void *dev_instance) #else bnx2_msi_1shot(int irq, void *dev_instance, struct pt_regs *regs) #endif { struct bnx2_napi *bnapi = dev_instance; struct bnx2 *bp = bnapi->bp; prefetch(bnapi->status_blk.msi); /* Return here if interrupt is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; #ifdef BNX2_NEW_NAPI napi_schedule(&bnapi->napi); #else netif_rx_schedule(bp->dev); #endif return IRQ_HANDLED; } #endif static irqreturn_t #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_interrupt(int irq, void *dev_instance) #else bnx2_interrupt(int irq, void *dev_instance, struct pt_regs *regs) #endif { struct bnx2_napi *bnapi = dev_instance; struct bnx2 *bp = bnapi->bp; struct status_block *sblk = bnapi->status_blk.msi; /* When using INTx, it is possible for the interrupt to arrive * at the CPU before the status block posted prior to the * interrupt. Reading a register will flush the status block. * When using MSI, the MSI message will always complete after * the status block write. */ if ((sblk->status_idx == bnapi->last_status_idx) && (BNX2_RD(bp, BNX2_PCICFG_MISC_STATUS) & BNX2_PCICFG_MISC_STATUS_INTA_VALUE)) return IRQ_NONE; BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_USE_INT_HC_PARAM | BNX2_PCICFG_INT_ACK_CMD_MASK_INT); /* Read back to deassert IRQ immediately to avoid too many * spurious interrupts. */ BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD); /* Return here if interrupt is shared and is disabled. */ if (unlikely(atomic_read(&bp->intr_sem) != 0)) return IRQ_HANDLED; #ifdef BNX2_NEW_NAPI if (napi_schedule_prep(&bnapi->napi)) { bnapi->last_status_idx = sblk->status_idx; __napi_schedule(&bnapi->napi); } #else if (netif_rx_schedule_prep(bp->dev)) { bnapi->last_status_idx = sblk->status_idx; __netif_rx_schedule(bp->dev); } #endif return IRQ_HANDLED; } static inline int bnx2_has_fast_work(struct bnx2_napi *bnapi) { struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; if ((bnx2_get_hw_rx_cons(bnapi) != rxr->rx_cons) || (bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons)) return 1; return 0; } #define STATUS_ATTN_EVENTS (STATUS_ATTN_BITS_LINK_STATE | \ STATUS_ATTN_BITS_TIMER_ABORT) static inline int bnx2_has_work(struct bnx2_napi *bnapi) { struct status_block *sblk = bnapi->status_blk.msi; if (bnx2_has_fast_work(bnapi)) return 1; #ifdef BCM_CNIC if (bnapi->cnic_present && (bnapi->cnic_tag != sblk->status_idx)) return 1; #endif if ((sblk->status_attn_bits & STATUS_ATTN_EVENTS) != (sblk->status_attn_bits_ack & STATUS_ATTN_EVENTS)) return 1; return 0; } #ifdef CONFIG_PCI_MSI static void bnx2_chk_missed_msi(struct bnx2 *bp) { struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; u32 msi_ctrl; if (bnx2_has_work(bnapi)) { msi_ctrl = BNX2_RD(bp, BNX2_PCICFG_MSI_CONTROL); if (!(msi_ctrl & BNX2_PCICFG_MSI_CONTROL_ENABLE)) return; if (bnapi->last_status_idx == bp->idle_chk_status_idx) { BNX2_WR(bp, BNX2_PCICFG_MSI_CONTROL, msi_ctrl & ~BNX2_PCICFG_MSI_CONTROL_ENABLE); BNX2_WR(bp, BNX2_PCICFG_MSI_CONTROL, msi_ctrl); #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_msi(bp->irq_tbl[0].vector, bnapi); #else bnx2_msi(bp->irq_tbl[0].vector, bnapi, NULL); #endif } } bp->idle_chk_status_idx = bnapi->last_status_idx; } #endif #ifdef BCM_CNIC static void bnx2_poll_cnic(struct bnx2 *bp, struct bnx2_napi *bnapi) { struct cnic_ops *c_ops; if (!bnapi->cnic_present) return; rcu_read_lock(); c_ops = rcu_dereference(bp->cnic_ops); if (c_ops) bnapi->cnic_tag = c_ops->cnic_handler(bp->cnic_data, bnapi->status_blk.msi); rcu_read_unlock(); } #endif #ifdef BNX2_NEW_NAPI static void bnx2_poll_link(struct bnx2 *bp, struct bnx2_napi *bnapi) { struct status_block *sblk = bnapi->status_blk.msi; u32 status_attn_bits = sblk->status_attn_bits; u32 status_attn_bits_ack = sblk->status_attn_bits_ack; if ((status_attn_bits & STATUS_ATTN_EVENTS) != (status_attn_bits_ack & STATUS_ATTN_EVENTS)) { bnx2_phy_int(bp, bnapi); /* This is needed to take care of transient status * during link changes. */ BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); } } static int bnx2_poll_work(struct bnx2 *bp, struct bnx2_napi *bnapi, int work_done, int budget) { struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; if (bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons) #if defined(__VMKLNX__) bnx2_tx_int(bp, bnapi, 0, 1); #else bnx2_tx_int(bp, bnapi, 0); #endif if (bnx2_get_hw_rx_cons(bnapi) != rxr->rx_cons) work_done += bnx2_rx_int(bp, bnapi, budget - work_done); #if defined(__VMKLNX__) wmb(); #endif return work_done; } static int bnx2_poll_msix(struct napi_struct *napi, int budget) { struct bnx2_napi *bnapi = container_of(napi, struct bnx2_napi, napi); struct bnx2 *bp = bnapi->bp; int work_done = 0; struct status_block_msix *sblk = bnapi->status_blk.msix; while (1) { work_done = bnx2_poll_work(bp, bnapi, work_done, budget); if (unlikely(work_done >= budget)) break; bnapi->last_status_idx = sblk->status_idx; /* status idx must be read before checking for more work. */ rmb(); if (likely(!bnx2_has_fast_work(bnapi))) { napi_complete(napi); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, bnapi->int_num | BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); break; } } return work_done; } static int bnx2_poll(struct napi_struct *napi, int budget) { struct bnx2_napi *bnapi = container_of(napi, struct bnx2_napi, napi); struct bnx2 *bp = bnapi->bp; int work_done = 0; struct status_block *sblk = bnapi->status_blk.msi; while (1) { bnx2_poll_link(bp, bnapi); work_done = bnx2_poll_work(bp, bnapi, work_done, budget); #if defined(BNX2_ENABLE_NETQUEUE) if (bnx2_netqueue_is_avail(bp) && bnx2_netqueue_open_started(bp)) bnx2_netqueue_service_bnx2_msix(bnapi); #endif #ifdef BCM_CNIC bnx2_poll_cnic(bp, bnapi); #endif /* bnapi->last_status_idx is used below to tell the hw how * much work has been processed, so we must read it before * checking for more work. */ bnapi->last_status_idx = sblk->status_idx; if (unlikely(work_done >= budget)) break; rmb(); if (likely(!bnx2_has_work(bnapi))) { napi_complete(napi); if (likely(bp->flags & BNX2_FLAG_USING_MSI_OR_MSIX)) { BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); break; } BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | BNX2_PCICFG_INT_ACK_CMD_MASK_INT | bnapi->last_status_idx); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); break; } } return work_done; } #else static int bnx2_poll(struct net_device *dev, int *budget) { struct bnx2 *bp = netdev_priv(dev); struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; struct status_block *sblk = bnapi->status_blk.msi; u32 status_attn_bits = sblk->status_attn_bits; u32 status_attn_bits_ack = sblk->status_attn_bits_ack; if ((status_attn_bits & STATUS_ATTN_EVENTS) != (status_attn_bits_ack & STATUS_ATTN_EVENTS)) { bnx2_phy_int(bp, bnapi); /* This is needed to take care of transient status * during link changes. */ BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); } if (bnx2_get_hw_tx_cons(bnapi) != txr->hw_tx_cons) #if defined(__VMKLNX__) bnx2_tx_int(bp, bnapi, 0, 1); #else bnx2_tx_int(bp, bnapi, 0); #endif if (bnx2_get_hw_rx_cons(bnapi) != rxr->rx_cons) { int orig_budget = *budget; int work_done; if (orig_budget > dev->quota) orig_budget = dev->quota; work_done = bnx2_rx_int(bp, bnapi, orig_budget); *budget -= work_done; dev->quota -= work_done; } #ifdef BCM_CNIC bnx2_poll_cnic(bp, bnapi); #endif bnapi->last_status_idx = sblk->status_idx; rmb(); if (!bnx2_has_work(bnapi)) { netif_rx_complete(dev); if (likely(bp->flags & BNX2_FLAG_USING_MSI_OR_MSIX)) { BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); return 0; } BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | BNX2_PCICFG_INT_ACK_CMD_MASK_INT | bnapi->last_status_idx); BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_INDEX_VALID | bnapi->last_status_idx); return 0; } return 1; } #endif /* Called with rtnl_lock from vlan functions and also netif_tx_lock * from set_multicast. */ static void bnx2_set_rx_mode(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); u32 rx_mode, sort_mode; #ifdef BCM_HAVE_SET_RX_MODE #if (LINUX_VERSION_CODE >= 0x2061f) struct netdev_hw_addr *ha; #else struct dev_addr_list *uc_ptr; #endif #endif int i; if (!netif_running(dev)) return; spin_lock_bh(&bp->phy_lock); rx_mode = bp->rx_mode & ~(BNX2_EMAC_RX_MODE_PROMISCUOUS | BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG); sort_mode = 1 | BNX2_RPM_SORT_USER0_BC_EN; #ifdef NEW_VLAN if (!(dev->features & NETIF_F_HW_VLAN_CTAG_RX) && (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN)) rx_mode |= BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG; #else #ifdef BCM_VLAN if (!bp->vlgrp && (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN)) rx_mode |= BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG; #else if (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN) rx_mode |= BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG; #endif #endif if (dev->flags & IFF_PROMISC) { /* Promiscuous mode. */ rx_mode |= BNX2_EMAC_RX_MODE_PROMISCUOUS; sort_mode |= BNX2_RPM_SORT_USER0_PROM_EN | BNX2_RPM_SORT_USER0_PROM_VLAN; } else if (dev->flags & IFF_ALLMULTI) { for (i = 0; i < NUM_MC_HASH_REGISTERS; i++) { BNX2_WR(bp, BNX2_EMAC_MULTICAST_HASH0 + (i * 4), 0xffffffff); } sort_mode |= BNX2_RPM_SORT_USER0_MC_EN; } else { /* Accept one or more multicast(s). */ #ifndef BCM_NEW_NETDEV_HW_ADDR struct dev_mc_list *mclist; #endif u32 mc_filter[NUM_MC_HASH_REGISTERS]; u32 regidx; u32 bit; u32 crc; memset(mc_filter, 0, 4 * NUM_MC_HASH_REGISTERS); #ifdef BCM_NEW_NETDEV_HW_ADDR netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(ETH_ALEN, ha->addr); #else netdev_for_each_mc_addr(mclist, dev) { crc = ether_crc_le(ETH_ALEN, mclist->dmi_addr); #endif bit = crc & 0xff; regidx = (bit & 0xe0) >> 5; bit &= 0x1f; mc_filter[regidx] |= (1 << bit); } for (i = 0; i < NUM_MC_HASH_REGISTERS; i++) { BNX2_WR(bp, BNX2_EMAC_MULTICAST_HASH0 + (i * 4), mc_filter[i]); } sort_mode |= BNX2_RPM_SORT_USER0_MC_HSH_EN; } #ifdef BCM_HAVE_SET_RX_MODE if (netdev_uc_count(dev) > BNX2_MAX_UNICAST_ADDRESSES) { rx_mode |= BNX2_EMAC_RX_MODE_PROMISCUOUS; sort_mode |= BNX2_RPM_SORT_USER0_PROM_EN | BNX2_RPM_SORT_USER0_PROM_VLAN; } else if (!(dev->flags & IFF_PROMISC)) { #if (LINUX_VERSION_CODE < 0x2061f) uc_ptr = dev->uc_list; /* Add all entries into to the match filter list */ for (i = 0; i < dev->uc_count; i++) { bnx2_set_mac_addr(bp, uc_ptr->da_addr, i + BNX2_START_UNICAST_ADDRESS_INDEX); sort_mode |= (1 << (i + BNX2_START_UNICAST_ADDRESS_INDEX)); uc_ptr = uc_ptr->next; } #else i = 0; netdev_for_each_uc_addr(ha, dev) { bnx2_set_mac_addr(bp, ha->addr, i + BNX2_START_UNICAST_ADDRESS_INDEX); sort_mode |= (1 << (i + BNX2_START_UNICAST_ADDRESS_INDEX)); i++; } #endif } #endif if (rx_mode != bp->rx_mode) { bp->rx_mode = rx_mode; BNX2_WR(bp, BNX2_EMAC_RX_MODE, rx_mode); } BNX2_WR(bp, BNX2_RPM_SORT_USER0, 0x0); BNX2_WR(bp, BNX2_RPM_SORT_USER0, sort_mode); BNX2_WR(bp, BNX2_RPM_SORT_USER0, sort_mode | BNX2_RPM_SORT_USER0_ENA); spin_unlock_bh(&bp->phy_lock); } #define FW_BUF_SIZE 0x10000 static int bnx2_gunzip_init(struct bnx2 *bp) { if ((bp->gunzip_buf = vmalloc(FW_BUF_SIZE)) == NULL) goto gunzip_nomem1; if ((bp->strm = kmalloc(sizeof(*bp->strm), GFP_KERNEL)) == NULL) goto gunzip_nomem2; bp->strm->workspace = kmalloc(zlib_inflate_workspacesize(), GFP_KERNEL); if (bp->strm->workspace == NULL) goto gunzip_nomem3; return 0; gunzip_nomem3: kfree(bp->strm); bp->strm = NULL; gunzip_nomem2: vfree(bp->gunzip_buf); bp->gunzip_buf = NULL; gunzip_nomem1: netdev_err(bp->dev, "Cannot allocate firmware buffer for " "uncompression.\n"); return -ENOMEM; } static void bnx2_gunzip_end(struct bnx2 *bp) { kfree(bp->strm->workspace); kfree(bp->strm); bp->strm = NULL; if (bp->gunzip_buf) { vfree(bp->gunzip_buf); bp->gunzip_buf = NULL; } } static int bnx2_gunzip(struct bnx2 *bp, const u8 *zbuf, int len, void **outbuf, int *outlen) { int rc; bp->strm->next_in = zbuf; bp->strm->avail_in = len; bp->strm->next_out = bp->gunzip_buf; bp->strm->avail_out = FW_BUF_SIZE; rc = zlib_inflateInit2(bp->strm, -MAX_WBITS); if (rc != Z_OK) return rc; rc = zlib_inflate(bp->strm, Z_FINISH); *outlen = FW_BUF_SIZE - bp->strm->avail_out; *outbuf = bp->gunzip_buf; if ((rc != Z_OK) && (rc != Z_STREAM_END)) netdev_err(bp->dev, "Firmware decompression error: %s\n", bp->strm->msg); zlib_inflateEnd(bp->strm); if (rc == Z_STREAM_END) return 0; return rc; } #if defined(__VMKLNX__) struct bnx2_cpus_scratch_debug { u32 offset; /* Scratch pad offset to firmware version */ char *name; /* Name of the CPU */ }; #define BNX2_SCRATCH_FW_VERSION_OFFSET 0x10 #define BNX2_TPAT_SCRATCH_FW_VERSION_OFFSET 0x410 static void bnx2_print_fw_versions(struct bnx2 *bp) { /* Array of the firmware offset's + CPU strings */ const struct bnx2_cpus_scratch_debug cpus_scratch[] = { { .offset = BNX2_TXP_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "TXP" }, { .offset = BNX2_TPAT_SCRATCH + BNX2_TPAT_SCRATCH_FW_VERSION_OFFSET, .name = "TPAT" }, { .offset = BNX2_RXP_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "RXP" }, { .offset = BNX2_COM_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "COM" }, { .offset = BNX2_CP_SCRATCH + BNX2_SCRATCH_FW_VERSION_OFFSET, .name = "CP" }, /* There is no versioning for MCP firmware */ }; int i; netdev_info(bp->dev, "CPU fw versions: "); for (i = 0; i < ARRAY_SIZE(cpus_scratch); i++) { /* The FW versions are 11 bytes long + 1 extra byte for * the NULL termination */ char version[12]; int j; /* Copy 4 bytes at a time */ for (j = 0; j < sizeof(version); j += 4) { u32 val; val = bnx2_reg_rd_ind(bp, cpus_scratch[i].offset + j); val = be32_to_cpu(val); memcpy(&version[j], &val, sizeof(val)); } /* Force a NULL terminiated string */ version[11] = '\0'; printk("%s: '%s' ", cpus_scratch[i].name, version); } printk("\n"); } #endif static u32 rv2p_fw_fixup(u32 rv2p_proc, int idx, u32 loc, u32 rv2p_code) { switch (idx) { case RV2P_P1_FIXUP_PAGE_SIZE_IDX: rv2p_code &= ~RV2P_BD_PAGE_SIZE_MSK; rv2p_code |= RV2P_BD_PAGE_SIZE; break; } return rv2p_code; } static void load_rv2p_fw(struct bnx2 *bp, __le32 *rv2p_code, u32 rv2p_code_len, u32 rv2p_proc, u32 fixup_loc) { __le32 *rv2p_code_start = rv2p_code; int i; u32 val, cmd, addr; if (rv2p_proc == RV2P_PROC1) { cmd = BNX2_RV2P_PROC1_ADDR_CMD_RDWR; addr = BNX2_RV2P_PROC1_ADDR_CMD; } else { cmd = BNX2_RV2P_PROC2_ADDR_CMD_RDWR; addr = BNX2_RV2P_PROC2_ADDR_CMD; } for (i = 0; i < rv2p_code_len; i += 8) { BNX2_WR(bp, BNX2_RV2P_INSTR_HIGH, le32_to_cpu(*rv2p_code)); rv2p_code++; BNX2_WR(bp, BNX2_RV2P_INSTR_LOW, le32_to_cpu(*rv2p_code)); rv2p_code++; val = (i / 8) | cmd; BNX2_WR(bp, addr, val); } rv2p_code = rv2p_code_start; if (fixup_loc && ((fixup_loc * 4) < rv2p_code_len)) { u32 code; code = le32_to_cpu(*(rv2p_code + fixup_loc - 1)); BNX2_WR(bp, BNX2_RV2P_INSTR_HIGH, code); code = le32_to_cpu(*(rv2p_code + fixup_loc)); code = rv2p_fw_fixup(rv2p_proc, 0, fixup_loc, code); BNX2_WR(bp, BNX2_RV2P_INSTR_LOW, code); val = (fixup_loc / 2) | cmd; BNX2_WR(bp, addr, val); } /* Reset the processor, un-stall is done later. */ if (rv2p_proc == RV2P_PROC1) { BNX2_WR(bp, BNX2_RV2P_COMMAND, BNX2_RV2P_COMMAND_PROC1_RESET); } else { BNX2_WR(bp, BNX2_RV2P_COMMAND, BNX2_RV2P_COMMAND_PROC2_RESET); } } static int load_cpu_fw(struct bnx2 *bp, const struct cpu_reg *cpu_reg, struct fw_info *fw) { u32 offset; u32 val; int rc; /* Halt the CPU. */ val = bnx2_reg_rd_ind(bp, cpu_reg->mode); val |= cpu_reg->mode_value_halt; bnx2_reg_wr_ind(bp, cpu_reg->mode, val); bnx2_reg_wr_ind(bp, cpu_reg->state, cpu_reg->state_value_clear); /* Load the Text area. */ offset = cpu_reg->spad_base + (fw->text_addr - cpu_reg->mips_view_base); if (fw->gz_text) { u32 text_len; void *text; rc = bnx2_gunzip(bp, fw->gz_text, fw->gz_text_len, &text, &text_len); if (rc) return rc; fw->text = text; } if (fw->text) { int j; for (j = 0; j < (fw->text_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, le32_to_cpu(fw->text[j])); } } /* Load the Data area. */ offset = cpu_reg->spad_base + (fw->data_addr - cpu_reg->mips_view_base); if (fw->data) { int j; for (j = 0; j < (fw->data_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, fw->data[j]); } } /* Load the SBSS area. */ offset = cpu_reg->spad_base + (fw->sbss_addr - cpu_reg->mips_view_base); if (fw->sbss_len) { int j; for (j = 0; j < (fw->sbss_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, 0); } } /* Load the BSS area. */ offset = cpu_reg->spad_base + (fw->bss_addr - cpu_reg->mips_view_base); if (fw->bss_len) { int j; for (j = 0; j < (fw->bss_len/4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, 0); } } /* Load the Read-Only area. */ offset = cpu_reg->spad_base + (fw->rodata_addr - cpu_reg->mips_view_base); if (fw->rodata) { int j; for (j = 0; j < (fw->rodata_len / 4); j++, offset += 4) { bnx2_reg_wr_ind(bp, offset, fw->rodata[j]); } } /* Clear the pre-fetch instruction. */ bnx2_reg_wr_ind(bp, cpu_reg->inst, 0); bnx2_reg_wr_ind(bp, cpu_reg->pc, fw->start_addr); /* Start the CPU. */ val = bnx2_reg_rd_ind(bp, cpu_reg->mode); val &= ~cpu_reg->mode_value_halt; bnx2_reg_wr_ind(bp, cpu_reg->state, cpu_reg->state_value_clear); bnx2_reg_wr_ind(bp, cpu_reg->mode, val); return 0; } static int bnx2_init_cpus(struct bnx2 *bp) { struct fw_info *fw; int rc = 0, rv2p_len; void *text; const void *rv2p; u32 text_len, fixup_loc; if ((rc = bnx2_gunzip_init(bp)) != 0) return rc; /* Initialize the RV2P processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A1)) { rv2p = bnx2_xi90_rv2p_proc1; rv2p_len = sizeof(bnx2_xi90_rv2p_proc1); fixup_loc = XI90_RV2P_PROC1_MAX_BD_PAGE_LOC; } else { rv2p = bnx2_xi_rv2p_proc1; rv2p_len = sizeof(bnx2_xi_rv2p_proc1); fixup_loc = XI_RV2P_PROC1_MAX_BD_PAGE_LOC; } } else { rv2p = bnx2_rv2p_proc1; rv2p_len = sizeof(bnx2_rv2p_proc1); fixup_loc = RV2P_PROC1_MAX_BD_PAGE_LOC; } rc = bnx2_gunzip(bp, rv2p, rv2p_len, &text, &text_len); if (rc) goto init_cpu_err; load_rv2p_fw(bp, text, text_len, RV2P_PROC1, fixup_loc); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5709_A1)) { rv2p = bnx2_xi90_rv2p_proc2; rv2p_len = sizeof(bnx2_xi90_rv2p_proc2); fixup_loc = XI90_RV2P_PROC2_MAX_BD_PAGE_LOC; } else { rv2p = bnx2_xi_rv2p_proc2; rv2p_len = sizeof(bnx2_xi_rv2p_proc2); fixup_loc = XI_RV2P_PROC2_MAX_BD_PAGE_LOC; } } else { rv2p = bnx2_rv2p_proc2; rv2p_len = sizeof(bnx2_rv2p_proc2); fixup_loc = RV2P_PROC2_MAX_BD_PAGE_LOC; } rc = bnx2_gunzip(bp, rv2p, rv2p_len, &text, &text_len); if (rc) goto init_cpu_err; load_rv2p_fw(bp, text, text_len, RV2P_PROC2, fixup_loc); /* Initialize the RX Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_rxp_fw_09; else fw = &bnx2_rxp_fw_06; rc = load_cpu_fw(bp, &cpu_reg_rxp, fw); if (rc) goto init_cpu_err; /* Initialize the TX Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_txp_fw_09; else fw = &bnx2_txp_fw_06; rc = load_cpu_fw(bp, &cpu_reg_txp, fw); if (rc) goto init_cpu_err; /* Initialize the TX Patch-up Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_tpat_fw_09; else fw = &bnx2_tpat_fw_06; rc = load_cpu_fw(bp, &cpu_reg_tpat, fw); if (rc) goto init_cpu_err; /* Initialize the Completion Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_com_fw_09; else fw = &bnx2_com_fw_06; rc = load_cpu_fw(bp, &cpu_reg_com, fw); if (rc) goto init_cpu_err; /* Initialize the Command Processor. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) fw = &bnx2_cp_fw_09; else fw = &bnx2_cp_fw_06; rc = load_cpu_fw(bp, &cpu_reg_cp, fw); if (rc) goto init_cpu_err; #if defined(__VMKLNX__) bnx2_print_fw_versions(bp); #endif init_cpu_err: bnx2_gunzip_end(bp); return rc; } static void bnx2_setup_wol(struct bnx2 *bp) { int i; u32 val, wol_msg; if (bp->wol) { u32 advertising; u8 autoneg; autoneg = bp->autoneg; advertising = bp->advertising; if (bp->phy_port == PORT_TP) { bp->autoneg = AUTONEG_SPEED; bp->advertising = ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | ADVERTISED_Autoneg; } spin_lock_bh(&bp->phy_lock); bnx2_setup_phy(bp, bp->phy_port); spin_unlock_bh(&bp->phy_lock); bp->autoneg = autoneg; bp->advertising = advertising; bnx2_set_mac_addr(bp, bp->dev->dev_addr, 0); val = BNX2_RD(bp, BNX2_EMAC_MODE); /* Enable port mode. */ val &= ~BNX2_EMAC_MODE_PORT; val |= BNX2_EMAC_MODE_MPKT_RCVD | BNX2_EMAC_MODE_ACPI_RCVD | BNX2_EMAC_MODE_MPKT; if (bp->phy_port == PORT_TP) { val |= BNX2_EMAC_MODE_PORT_MII; } else { val |= BNX2_EMAC_MODE_PORT_GMII; if (bp->line_speed == SPEED_2500) val |= BNX2_EMAC_MODE_25G_MODE; } BNX2_WR(bp, BNX2_EMAC_MODE, val); /* receive all multicast */ for (i = 0; i < NUM_MC_HASH_REGISTERS; i++) { BNX2_WR(bp, BNX2_EMAC_MULTICAST_HASH0 + (i * 4), 0xffffffff); } BNX2_WR(bp, BNX2_EMAC_RX_MODE, BNX2_EMAC_RX_MODE_SORT_MODE); val = 1 | BNX2_RPM_SORT_USER0_BC_EN | BNX2_RPM_SORT_USER0_MC_EN; BNX2_WR(bp, BNX2_RPM_SORT_USER0, 0x0); BNX2_WR(bp, BNX2_RPM_SORT_USER0, val); BNX2_WR(bp, BNX2_RPM_SORT_USER0, val | BNX2_RPM_SORT_USER0_ENA); /* Need to enable EMAC and RPM for WOL. */ BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_SET_BITS_RX_PARSER_MAC_ENABLE | BNX2_MISC_ENABLE_SET_BITS_TX_HEADER_Q_ENABLE | BNX2_MISC_ENABLE_SET_BITS_EMAC_ENABLE); val = BNX2_RD(bp, BNX2_RPM_CONFIG); val &= ~BNX2_RPM_CONFIG_ACPI_ENA; BNX2_WR(bp, BNX2_RPM_CONFIG, val); wol_msg = BNX2_DRV_MSG_CODE_SUSPEND_WOL; } else { wol_msg = BNX2_DRV_MSG_CODE_SUSPEND_NO_WOL; } if (!(bp->flags & BNX2_FLAG_NO_WOL)) bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT3 | wol_msg, 1, 0); } static int bnx2_set_power_state(struct bnx2 *bp, pci_power_t state) { switch (state) { case PCI_D0: { u32 val; pci_enable_wake(bp->pdev, PCI_D0, false); pci_set_power_state(bp->pdev, PCI_D0); val = BNX2_RD(bp, BNX2_EMAC_MODE); val |= BNX2_EMAC_MODE_MPKT_RCVD | BNX2_EMAC_MODE_ACPI_RCVD; val &= ~BNX2_EMAC_MODE_MPKT; BNX2_WR(bp, BNX2_EMAC_MODE, val); val = BNX2_RD(bp, BNX2_RPM_CONFIG); val &= ~BNX2_RPM_CONFIG_ACPI_ENA; BNX2_WR(bp, BNX2_RPM_CONFIG, val); break; } case PCI_D3hot: { bnx2_setup_wol(bp); pci_wake_from_d3(bp->pdev, bp->wol); if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1)) { if (bp->wol) pci_set_power_state(bp->pdev, PCI_D3hot); } else { pci_set_power_state(bp->pdev, PCI_D3hot); } /* No more memory access after this point until * device is brought back to D0. */ break; } default: return -EINVAL; } return 0; } static int bnx2_acquire_nvram_lock(struct bnx2 *bp) { u32 val; int j; /* Request access to the flash interface. */ BNX2_WR(bp, BNX2_NVM_SW_ARB, BNX2_NVM_SW_ARB_ARB_REQ_SET2); for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { val = BNX2_RD(bp, BNX2_NVM_SW_ARB); if (val & BNX2_NVM_SW_ARB_ARB_ARB2) break; udelay(5); } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_release_nvram_lock(struct bnx2 *bp) { int j; u32 val; /* Relinquish nvram interface. */ BNX2_WR(bp, BNX2_NVM_SW_ARB, BNX2_NVM_SW_ARB_ARB_REQ_CLR2); for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { val = BNX2_RD(bp, BNX2_NVM_SW_ARB); if (!(val & BNX2_NVM_SW_ARB_ARB_ARB2)) break; udelay(5); } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_enable_nvram_write(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, val | BNX2_MISC_CFG_NVM_WR_EN_PCI); if (bp->flash_info->flags & BNX2_NV_WREN) { int j; BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_WREN | BNX2_NVM_COMMAND_DOIT); for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { udelay(5); val = BNX2_RD(bp, BNX2_NVM_COMMAND); if (val & BNX2_NVM_COMMAND_DONE) break; } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; } return 0; } static void bnx2_disable_nvram_write(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, val & ~BNX2_MISC_CFG_NVM_WR_EN); } static void bnx2_enable_nvram_access(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_NVM_ACCESS_ENABLE); /* Enable both bits, even on read. */ BNX2_WR(bp, BNX2_NVM_ACCESS_ENABLE, val | BNX2_NVM_ACCESS_ENABLE_EN | BNX2_NVM_ACCESS_ENABLE_WR_EN); } static void bnx2_disable_nvram_access(struct bnx2 *bp) { u32 val; val = BNX2_RD(bp, BNX2_NVM_ACCESS_ENABLE); /* Disable both bits, even after read. */ BNX2_WR(bp, BNX2_NVM_ACCESS_ENABLE, val & ~(BNX2_NVM_ACCESS_ENABLE_EN | BNX2_NVM_ACCESS_ENABLE_WR_EN)); } static int bnx2_nvram_erase_page(struct bnx2 *bp, u32 offset) { u32 cmd; int j; if (bp->flash_info->flags & BNX2_NV_BUFFERED) /* Buffered flash, no erase needed */ return 0; /* Build an erase command */ cmd = BNX2_NVM_COMMAND_ERASE | BNX2_NVM_COMMAND_WR | BNX2_NVM_COMMAND_DOIT; /* Need to clear DONE bit separately. */ BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); /* Address of the NVRAM to read from. */ BNX2_WR(bp, BNX2_NVM_ADDR, offset & BNX2_NVM_ADDR_NVM_ADDR_VALUE); /* Issue an erase command. */ BNX2_WR(bp, BNX2_NVM_COMMAND, cmd); /* Wait for completion. */ for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { u32 val; udelay(5); val = BNX2_RD(bp, BNX2_NVM_COMMAND); if (val & BNX2_NVM_COMMAND_DONE) break; } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_nvram_read_dword(struct bnx2 *bp, u32 offset, u8 *ret_val, u32 cmd_flags) { u32 cmd; int j; /* Build the command word. */ cmd = BNX2_NVM_COMMAND_DOIT | cmd_flags; /* Calculate an offset of a buffered flash, not needed for 5709. */ if (bp->flash_info->flags & BNX2_NV_TRANSLATE) { offset = ((offset / bp->flash_info->page_size) << bp->flash_info->page_bits) + (offset % bp->flash_info->page_size); } /* Need to clear DONE bit separately. */ BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); /* Address of the NVRAM to read from. */ BNX2_WR(bp, BNX2_NVM_ADDR, offset & BNX2_NVM_ADDR_NVM_ADDR_VALUE); /* Issue a read command. */ BNX2_WR(bp, BNX2_NVM_COMMAND, cmd); /* Wait for completion. */ for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { u32 val; udelay(5); val = BNX2_RD(bp, BNX2_NVM_COMMAND); if (val & BNX2_NVM_COMMAND_DONE) { __be32 v = cpu_to_be32(BNX2_RD(bp, BNX2_NVM_READ)); memcpy(ret_val, &v, 4); break; } } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_nvram_write_dword(struct bnx2 *bp, u32 offset, u8 *val, u32 cmd_flags) { u32 cmd; __be32 val32; int j; /* Build the command word. */ cmd = BNX2_NVM_COMMAND_DOIT | BNX2_NVM_COMMAND_WR | cmd_flags; /* Calculate an offset of a buffered flash, not needed for 5709. */ if (bp->flash_info->flags & BNX2_NV_TRANSLATE) { offset = ((offset / bp->flash_info->page_size) << bp->flash_info->page_bits) + (offset % bp->flash_info->page_size); } /* Need to clear DONE bit separately. */ BNX2_WR(bp, BNX2_NVM_COMMAND, BNX2_NVM_COMMAND_DONE); memcpy(&val32, val, 4); /* Write the data. */ BNX2_WR(bp, BNX2_NVM_WRITE, be32_to_cpu(val32)); /* Address of the NVRAM to write to. */ BNX2_WR(bp, BNX2_NVM_ADDR, offset & BNX2_NVM_ADDR_NVM_ADDR_VALUE); /* Issue the write command. */ BNX2_WR(bp, BNX2_NVM_COMMAND, cmd); /* Wait for completion. */ for (j = 0; j < NVRAM_TIMEOUT_COUNT; j++) { udelay(5); if (BNX2_RD(bp, BNX2_NVM_COMMAND) & BNX2_NVM_COMMAND_DONE) break; } if (j >= NVRAM_TIMEOUT_COUNT) return -EBUSY; return 0; } static int bnx2_init_nvram(struct bnx2 *bp) { u32 val; int j, entry_count, rc = 0; const struct flash_spec *flash; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { bp->flash_info = &flash_5709; goto get_flash_size; } /* Determine the selected interface. */ val = BNX2_RD(bp, BNX2_NVM_CFG1); entry_count = ARRAY_SIZE(flash_table); if (val & 0x40000000) { /* Flash interface has been reconfigured */ for (j = 0, flash = &flash_table[0]; j < entry_count; j++, flash++) { if ((val & FLASH_BACKUP_STRAP_MASK) == (flash->config1 & FLASH_BACKUP_STRAP_MASK)) { bp->flash_info = flash; break; } } } else { u32 mask; /* Not yet been reconfigured */ if (val & (1 << 23)) mask = FLASH_BACKUP_STRAP_MASK; else mask = FLASH_STRAP_MASK; for (j = 0, flash = &flash_table[0]; j < entry_count; j++, flash++) { if ((val & mask) == (flash->strapping & mask)) { bp->flash_info = flash; /* Request access to the flash interface. */ if ((rc = bnx2_acquire_nvram_lock(bp)) != 0) return rc; /* Enable access to flash interface */ bnx2_enable_nvram_access(bp); /* Reconfigure the flash interface */ BNX2_WR(bp, BNX2_NVM_CFG1, flash->config1); BNX2_WR(bp, BNX2_NVM_CFG2, flash->config2); BNX2_WR(bp, BNX2_NVM_CFG3, flash->config3); BNX2_WR(bp, BNX2_NVM_WRITE1, flash->write1); /* Disable access to flash interface */ bnx2_disable_nvram_access(bp); bnx2_release_nvram_lock(bp); break; } } } /* if (val & 0x40000000) */ if (j == entry_count) { bp->flash_info = NULL; pr_alert("Unknown flash/EEPROM type\n"); return -ENODEV; } get_flash_size: val = bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG2); val &= BNX2_SHARED_HW_CFG2_NVM_SIZE_MASK; if (val) bp->flash_size = val; else bp->flash_size = bp->flash_info->total_size; return rc; } static int bnx2_nvram_read(struct bnx2 *bp, u32 offset, u8 *ret_buf, int buf_size) { int rc = 0; u32 cmd_flags, offset32, len32, extra; if (buf_size == 0) return 0; /* Request access to the flash interface. */ if ((rc = bnx2_acquire_nvram_lock(bp)) != 0) return rc; /* Enable access to flash interface */ bnx2_enable_nvram_access(bp); len32 = buf_size; offset32 = offset; extra = 0; cmd_flags = 0; if (offset32 & 3) { u8 buf[4]; u32 pre_len; offset32 &= ~3; pre_len = 4 - (offset & 3); if (pre_len >= len32) { pre_len = len32; cmd_flags = BNX2_NVM_COMMAND_FIRST | BNX2_NVM_COMMAND_LAST; } else { cmd_flags = BNX2_NVM_COMMAND_FIRST; } rc = bnx2_nvram_read_dword(bp, offset32, buf, cmd_flags); if (rc) return rc; memcpy(ret_buf, buf + (offset & 3), pre_len); offset32 += 4; ret_buf += pre_len; len32 -= pre_len; } if (len32 & 3) { extra = 4 - (len32 & 3); len32 = (len32 + 4) & ~3; } if (len32 == 4) { u8 buf[4]; if (cmd_flags) cmd_flags = BNX2_NVM_COMMAND_LAST; else cmd_flags = BNX2_NVM_COMMAND_FIRST | BNX2_NVM_COMMAND_LAST; rc = bnx2_nvram_read_dword(bp, offset32, buf, cmd_flags); memcpy(ret_buf, buf, 4 - extra); } else if (len32 > 0) { u8 buf[4]; /* Read the first word. */ if (cmd_flags) cmd_flags = 0; else cmd_flags = BNX2_NVM_COMMAND_FIRST; rc = bnx2_nvram_read_dword(bp, offset32, ret_buf, cmd_flags); /* Advance to the next dword. */ offset32 += 4; ret_buf += 4; len32 -= 4; while (len32 > 4 && rc == 0) { rc = bnx2_nvram_read_dword(bp, offset32, ret_buf, 0); /* Advance to the next dword. */ offset32 += 4; ret_buf += 4; len32 -= 4; } if (rc) return rc; cmd_flags = BNX2_NVM_COMMAND_LAST; rc = bnx2_nvram_read_dword(bp, offset32, buf, cmd_flags); memcpy(ret_buf, buf, 4 - extra); } /* Disable access to flash interface */ bnx2_disable_nvram_access(bp); bnx2_release_nvram_lock(bp); return rc; } static int bnx2_nvram_write(struct bnx2 *bp, u32 offset, u8 *data_buf, int buf_size) { u32 written, offset32, len32; u8 *buf, start[4], end[4], *align_buf = NULL, *flash_buffer = NULL; int rc = 0; int align_start, align_end; buf = data_buf; offset32 = offset; len32 = buf_size; align_start = align_end = 0; if ((align_start = (offset32 & 3))) { offset32 &= ~3; len32 += align_start; if (len32 < 4) len32 = 4; if ((rc = bnx2_nvram_read(bp, offset32, start, 4))) return rc; } if (len32 & 3) { align_end = 4 - (len32 & 3); len32 += align_end; if ((rc = bnx2_nvram_read(bp, offset32 + len32 - 4, end, 4))) return rc; } if (align_start || align_end) { align_buf = kmalloc(len32, GFP_KERNEL); if (align_buf == NULL) return -ENOMEM; if (align_start) { memcpy(align_buf, start, 4); } if (align_end) { memcpy(align_buf + len32 - 4, end, 4); } memcpy(align_buf + align_start, data_buf, buf_size); buf = align_buf; } if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { flash_buffer = kmalloc(264, GFP_KERNEL); if (flash_buffer == NULL) { rc = -ENOMEM; goto nvram_write_end; } } written = 0; while ((written < len32) && (rc == 0)) { u32 page_start, page_end, data_start, data_end; u32 addr, cmd_flags; int i; /* Find the page_start addr */ page_start = offset32 + written; page_start -= (page_start % bp->flash_info->page_size); /* Find the page_end addr */ page_end = page_start + bp->flash_info->page_size; /* Find the data_start addr */ data_start = (written == 0) ? offset32 : page_start; /* Find the data_end addr */ data_end = (page_end > offset32 + len32) ? (offset32 + len32) : page_end; /* Request access to the flash interface. */ if ((rc = bnx2_acquire_nvram_lock(bp)) != 0) goto nvram_write_end; /* Enable access to flash interface */ bnx2_enable_nvram_access(bp); cmd_flags = BNX2_NVM_COMMAND_FIRST; if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { int j; /* Read the whole page into the buffer * (non-buffer flash only) */ for (j = 0; j < bp->flash_info->page_size; j += 4) { if (j == (bp->flash_info->page_size - 4)) { cmd_flags |= BNX2_NVM_COMMAND_LAST; } rc = bnx2_nvram_read_dword(bp, page_start + j, &flash_buffer[j], cmd_flags); if (rc) goto nvram_write_end; cmd_flags = 0; } } /* Enable writes to flash interface (unlock write-protect) */ if ((rc = bnx2_enable_nvram_write(bp)) != 0) goto nvram_write_end; /* Loop to write back the buffer data from page_start to * data_start */ i = 0; if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { /* Erase the page */ if ((rc = bnx2_nvram_erase_page(bp, page_start)) != 0) goto nvram_write_end; /* Re-enable the write again for the actual write */ bnx2_enable_nvram_write(bp); for (addr = page_start; addr < data_start; addr += 4, i += 4) { rc = bnx2_nvram_write_dword(bp, addr, &flash_buffer[i], cmd_flags); if (rc != 0) goto nvram_write_end; cmd_flags = 0; } } /* Loop to write the new data from data_start to data_end */ for (addr = data_start; addr < data_end; addr += 4, i += 4) { if ((addr == page_end - 4) || ((bp->flash_info->flags & BNX2_NV_BUFFERED) && (addr == data_end - 4))) { cmd_flags |= BNX2_NVM_COMMAND_LAST; } rc = bnx2_nvram_write_dword(bp, addr, buf, cmd_flags); if (rc != 0) goto nvram_write_end; cmd_flags = 0; buf += 4; } /* Loop to write back the buffer data from data_end * to page_end */ if (!(bp->flash_info->flags & BNX2_NV_BUFFERED)) { for (addr = data_end; addr < page_end; addr += 4, i += 4) { if (addr == page_end-4) { cmd_flags = BNX2_NVM_COMMAND_LAST; } rc = bnx2_nvram_write_dword(bp, addr, &flash_buffer[i], cmd_flags); if (rc != 0) goto nvram_write_end; cmd_flags = 0; } } /* Disable writes to flash interface (lock write-protect) */ bnx2_disable_nvram_write(bp); /* Disable access to flash interface */ bnx2_disable_nvram_access(bp); bnx2_release_nvram_lock(bp); /* Increment written */ written += data_end - data_start; } nvram_write_end: kfree(flash_buffer); kfree(align_buf); return rc; } static void bnx2_init_fw_cap(struct bnx2 *bp) { u32 val, sig = 0; bp->phy_flags &= ~BNX2_PHY_FLAG_REMOTE_PHY_CAP; bp->flags &= ~BNX2_FLAG_CAN_KEEP_VLAN; if (!(bp->flags & BNX2_FLAG_ASF_ENABLE)) bp->flags |= BNX2_FLAG_CAN_KEEP_VLAN; val = bnx2_shmem_rd(bp, BNX2_FW_CAP_MB); if ((val & BNX2_FW_CAP_SIGNATURE_MASK) != BNX2_FW_CAP_SIGNATURE) return; if ((val & BNX2_FW_CAP_CAN_KEEP_VLAN) == BNX2_FW_CAP_CAN_KEEP_VLAN) { bp->flags |= BNX2_FLAG_CAN_KEEP_VLAN; sig |= BNX2_DRV_ACK_CAP_SIGNATURE | BNX2_FW_CAP_CAN_KEEP_VLAN; } if ((bp->phy_flags & BNX2_PHY_FLAG_SERDES) && (val & BNX2_FW_CAP_REMOTE_PHY_CAPABLE)) { u32 link; bp->phy_flags |= BNX2_PHY_FLAG_REMOTE_PHY_CAP; link = bnx2_shmem_rd(bp, BNX2_LINK_STATUS); if (link & BNX2_LINK_STATUS_SERDES_LINK) bp->phy_port = PORT_FIBRE; else bp->phy_port = PORT_TP; sig |= BNX2_DRV_ACK_CAP_SIGNATURE | BNX2_FW_CAP_REMOTE_PHY_CAPABLE; } if (netif_running(bp->dev) && sig) bnx2_shmem_wr(bp, BNX2_DRV_ACK_CAP_MB, sig); } #if defined(__VMKLNX__) static void bnx2_setup_msix_tbl_cfg(struct bnx2 *bp) { bnx2_reg_wr_ind_cfg(bp, BNX2_PCI_GRC_WINDOW_ADDR, BNX2_PCI_GRC_WINDOW_ADDR_SEP_WIN); bnx2_reg_wr_ind_cfg(bp, BNX2_PCI_GRC_WINDOW2_ADDR, BNX2_MSIX_TABLE_ADDR); bnx2_reg_wr_ind_cfg(bp, BNX2_PCI_GRC_WINDOW3_ADDR, BNX2_MSIX_PBA_ADDR); } #endif /* defined(__VMKLNX__) */ static void bnx2_setup_msix_tbl(struct bnx2 *bp) { BNX2_WR(bp, BNX2_PCI_GRC_WINDOW_ADDR, BNX2_PCI_GRC_WINDOW_ADDR_SEP_WIN); BNX2_WR(bp, BNX2_PCI_GRC_WINDOW2_ADDR, BNX2_MSIX_TABLE_ADDR); BNX2_WR(bp, BNX2_PCI_GRC_WINDOW3_ADDR, BNX2_MSIX_PBA_ADDR); } static int bnx2_reset_chip(struct bnx2 *bp, u32 reset_code) { u32 val; int i, rc = 0; u8 old_port; /* Wait for the current PCI transaction to complete before * issuing a reset. */ if ((BNX2_CHIP(bp) == BNX2_CHIP_5706) || (BNX2_CHIP(bp) == BNX2_CHIP_5708)) { BNX2_WR(bp, BNX2_MISC_ENABLE_CLR_BITS, BNX2_MISC_ENABLE_CLR_BITS_TX_DMA_ENABLE | BNX2_MISC_ENABLE_CLR_BITS_DMA_ENGINE_ENABLE | BNX2_MISC_ENABLE_CLR_BITS_RX_DMA_ENABLE | BNX2_MISC_ENABLE_CLR_BITS_HOST_COALESCE_ENABLE); val = BNX2_RD(bp, BNX2_MISC_ENABLE_CLR_BITS); udelay(5); } else { /* 5709 */ val = BNX2_RD(bp, BNX2_MISC_NEW_CORE_CTL); val &= ~BNX2_MISC_NEW_CORE_CTL_DMA_ENABLE; BNX2_WR(bp, BNX2_MISC_NEW_CORE_CTL, val); val = BNX2_RD(bp, BNX2_MISC_NEW_CORE_CTL); for (i = 0; i < 100; i++) { bnx2_msleep(1); val = BNX2_RD(bp, BNX2_PCICFG_DEVICE_CONTROL); if (!(val & BNX2_PCICFG_DEVICE_STATUS_NO_PEND)) break; } } /* Wait for the firmware to tell us it is ok to issue a reset. */ bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT0 | reset_code, 1, 1); /* Deposit a driver reset signature so the firmware knows that * this is a soft reset. */ bnx2_shmem_wr(bp, BNX2_DRV_RESET_SIGNATURE, BNX2_DRV_RESET_SIGNATURE_MAGIC); #if defined(__VMKLNX__) #if (LINUX_VERSION_CODE >= 0x020611) pci_save_state(bp->pdev); #endif #endif /* defined(__VMKLNX__) */ /* Do a dummy read to force the chip to complete all current transaction * before we issue a reset. */ val = BNX2_RD(bp, BNX2_MISC_ID); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { BNX2_WR(bp, BNX2_MISC_COMMAND, BNX2_MISC_COMMAND_SW_RESET); BNX2_RD(bp, BNX2_MISC_COMMAND); udelay(5); val = BNX2_PCICFG_MISC_CONFIG_REG_WINDOW_ENA | BNX2_PCICFG_MISC_CONFIG_TARGET_MB_WORD_SWAP; BNX2_WR(bp, BNX2_PCICFG_MISC_CONFIG, val); } else { val = BNX2_PCICFG_MISC_CONFIG_CORE_RST_REQ | BNX2_PCICFG_MISC_CONFIG_REG_WINDOW_ENA | BNX2_PCICFG_MISC_CONFIG_TARGET_MB_WORD_SWAP; /* Chip reset. */ BNX2_WR(bp, BNX2_PCICFG_MISC_CONFIG, val); /* Reading back any register after chip reset will hang the * bus on 5706 A0 and A1. The msleep below provides plenty * of margin for write posting. */ if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1)) bnx2_msleep(20); /* Reset takes approximate 30 usec */ for (i = 0; i < 10; i++) { val = BNX2_RD(bp, BNX2_PCICFG_MISC_CONFIG); if ((val & (BNX2_PCICFG_MISC_CONFIG_CORE_RST_REQ | BNX2_PCICFG_MISC_CONFIG_CORE_RST_BSY)) == 0) break; udelay(10); } if (val & (BNX2_PCICFG_MISC_CONFIG_CORE_RST_REQ | BNX2_PCICFG_MISC_CONFIG_CORE_RST_BSY)) { pr_err("Chip reset did not complete\n"); return -EBUSY; } } #if defined(__VMKLNX__) if (bp->flags & BNX2_FLAG_USING_MSIX) bnx2_setup_msix_tbl_cfg(bp); #if (LINUX_VERSION_CODE >= 0x020611) pci_restore_state(bp->pdev); #endif #endif /* defined(__VMKLNX__) */ /* Make sure byte swapping is properly configured. */ val = BNX2_RD(bp, BNX2_PCI_SWAP_DIAG0); if (val != 0x01020304) { pr_err("Chip not in correct endian mode\n"); return -ENODEV; } /* Wait for the firmware to finish its initialization. */ rc = bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT1 | reset_code, 1, 0); if (rc) return rc; spin_lock_bh(&bp->phy_lock); old_port = bp->phy_port; bnx2_init_fw_cap(bp); if ((bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) && old_port != bp->phy_port) bnx2_set_default_remote_link(bp); spin_unlock_bh(&bp->phy_lock); if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { /* Adjust the voltage regular to two steps lower. The default * of this register is 0x0000000e. */ BNX2_WR(bp, BNX2_MISC_VREG_CONTROL, 0x000000fa); /* Remove bad rbuf memory from the free pool. */ rc = bnx2_alloc_bad_rbuf(bp); } if (bp->flags & BNX2_FLAG_USING_MSIX) { bnx2_setup_msix_tbl(bp); /* Prevent MSIX table reads and write from timing out */ BNX2_WR(bp, BNX2_MISC_ECO_HW_CTL, BNX2_MISC_ECO_HW_CTL_LARGE_GRC_TMOUT_EN); } return rc; } static int bnx2_init_chip(struct bnx2 *bp) { u32 val, mtu; int rc, i; /* Make sure the interrupt is not active. */ BNX2_WR(bp, BNX2_PCICFG_INT_ACK_CMD, BNX2_PCICFG_INT_ACK_CMD_MASK_INT); val = BNX2_DMA_CONFIG_DATA_BYTE_SWAP | BNX2_DMA_CONFIG_DATA_WORD_SWAP | #ifdef __BIG_ENDIAN BNX2_DMA_CONFIG_CNTL_BYTE_SWAP | #endif BNX2_DMA_CONFIG_CNTL_WORD_SWAP | DMA_READ_CHANS << 12 | DMA_WRITE_CHANS << 16; val |= (0x2 << 20) | (1 << 11); if ((bp->flags & BNX2_FLAG_PCIX) && (bp->bus_speed_mhz == 133)) val |= (1 << 23); if ((BNX2_CHIP(bp) == BNX2_CHIP_5706) && (BNX2_CHIP_ID(bp) != BNX2_CHIP_ID_5706_A0) && !(bp->flags & BNX2_FLAG_PCIX)) val |= BNX2_DMA_CONFIG_CNTL_PING_PONG_DMA; BNX2_WR(bp, BNX2_DMA_CONFIG, val); if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { val = BNX2_RD(bp, BNX2_TDMA_CONFIG); val |= BNX2_TDMA_CONFIG_ONE_DMA; BNX2_WR(bp, BNX2_TDMA_CONFIG, val); } if (bp->flags & BNX2_FLAG_PCIX) { u16 val16; pci_read_config_word(bp->pdev, bp->pcix_cap + PCI_X_CMD, &val16); pci_write_config_word(bp->pdev, bp->pcix_cap + PCI_X_CMD, val16 & ~PCI_X_CMD_ERO); } BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_SET_BITS_HOST_COALESCE_ENABLE | BNX2_MISC_ENABLE_STATUS_BITS_RX_V2P_ENABLE | BNX2_MISC_ENABLE_STATUS_BITS_CONTEXT_ENABLE); /* Initialize context mapping and zero out the quick contexts. The * context block must have already been enabled. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { rc = bnx2_init_5709_context(bp); if (rc) return rc; } else bnx2_init_context(bp); if ((rc = bnx2_init_cpus(bp)) != 0) return rc; bnx2_init_nvram(bp); bnx2_set_mac_addr(bp, bp->dev->dev_addr, 0); val = BNX2_RD(bp, BNX2_MQ_CONFIG); val &= ~BNX2_MQ_CONFIG_KNL_BYP_BLK_SIZE; val |= BNX2_MQ_CONFIG_KNL_BYP_BLK_SIZE_256; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { val |= BNX2_MQ_CONFIG_BIN_MQ_MODE; if (BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Ax) val |= BNX2_MQ_CONFIG_HALT_DIS; } BNX2_WR(bp, BNX2_MQ_CONFIG, val); val = 0x10000 + (MAX_CID_CNT * MB_KERNEL_CTX_SIZE); BNX2_WR(bp, BNX2_MQ_KNL_BYP_WIND_START, val); BNX2_WR(bp, BNX2_MQ_KNL_WIND_END, val); val = (BNX2_PAGE_BITS - 8) << 24; BNX2_WR(bp, BNX2_RV2P_CONFIG, val); /* Configure page size. */ val = BNX2_RD(bp, BNX2_TBDR_CONFIG); val &= ~BNX2_TBDR_CONFIG_PAGE_SIZE; val |= (BNX2_PAGE_BITS - 8) << 24 | 0x40; BNX2_WR(bp, BNX2_TBDR_CONFIG, val); val = bp->mac_addr[0] + (bp->mac_addr[1] << 8) + (bp->mac_addr[2] << 16) + bp->mac_addr[3] + (bp->mac_addr[4] << 8) + (bp->mac_addr[5] << 16); BNX2_WR(bp, BNX2_EMAC_BACKOFF_SEED, val); /* Program the MTU. Also include 4 bytes for CRC32. */ mtu = bp->dev->mtu; val = mtu + ETH_HLEN + ETH_FCS_LEN; if (val > (MAX_ETHERNET_PACKET_SIZE + 4)) val |= BNX2_EMAC_RX_MTU_SIZE_JUMBO_ENA; BNX2_WR(bp, BNX2_EMAC_RX_MTU_SIZE, val); if (mtu < 1500) mtu = 1500; bnx2_reg_wr_ind(bp, BNX2_RBUF_CONFIG, BNX2_RBUF_CONFIG_VAL(mtu)); bnx2_reg_wr_ind(bp, BNX2_RBUF_CONFIG2, BNX2_RBUF_CONFIG2_VAL(mtu)); bnx2_reg_wr_ind(bp, BNX2_RBUF_CONFIG3, BNX2_RBUF_CONFIG3_VAL(mtu)); memset(bp->bnx2_napi[0].status_blk.msi, 0, bp->status_stats_size); for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) bp->bnx2_napi[i].last_status_idx = 0; bp->idle_chk_status_idx = 0xffff; bp->rx_mode = BNX2_EMAC_RX_MODE_SORT_MODE; /* Set up how to generate a link change interrupt. */ BNX2_WR(bp, BNX2_EMAC_ATTENTION_ENA, BNX2_EMAC_ATTENTION_ENA_LINK); BNX2_WR(bp, BNX2_HC_STATUS_ADDR_L, (u64) bp->status_blk_mapping & 0xffffffff); BNX2_WR(bp, BNX2_HC_STATUS_ADDR_H, (u64) bp->status_blk_mapping >> 32); BNX2_WR(bp, BNX2_HC_STATISTICS_ADDR_L, (u64) bp->stats_blk_mapping & 0xffffffff); BNX2_WR(bp, BNX2_HC_STATISTICS_ADDR_H, (u64) bp->stats_blk_mapping >> 32); BNX2_WR(bp, BNX2_HC_TX_QUICK_CONS_TRIP, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_RX_QUICK_CONS_TRIP, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_COMP_PROD_TRIP, (bp->comp_prod_trip_int << 16) | bp->comp_prod_trip); BNX2_WR(bp, BNX2_HC_TX_TICKS, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, BNX2_HC_RX_TICKS, (bp->rx_ticks_int << 16) | bp->rx_ticks); BNX2_WR(bp, BNX2_HC_COM_TICKS, (bp->com_ticks_int << 16) | bp->com_ticks); BNX2_WR(bp, BNX2_HC_CMD_TICKS, (bp->cmd_ticks_int << 16) | bp->cmd_ticks); if (bp->flags & BNX2_FLAG_BROKEN_STATS) BNX2_WR(bp, BNX2_HC_STATS_TICKS, 0); else BNX2_WR(bp, BNX2_HC_STATS_TICKS, bp->stats_ticks); BNX2_WR(bp, BNX2_HC_STAT_COLLECT_TICKS, 0xbb8); /* 3ms */ if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1) val = BNX2_HC_CONFIG_COLLECT_STATS; else { val = BNX2_HC_CONFIG_RX_TMR_MODE | BNX2_HC_CONFIG_TX_TMR_MODE | BNX2_HC_CONFIG_COLLECT_STATS; } if (bp->flags & BNX2_FLAG_USING_MSIX) { BNX2_WR(bp, BNX2_HC_MSIX_BIT_VECTOR, BNX2_HC_MSIX_BIT_VECTOR_VAL); val |= BNX2_HC_CONFIG_SB_ADDR_INC_128B; } if (bp->flags & BNX2_FLAG_ONE_SHOT_MSI) val |= BNX2_HC_CONFIG_ONE_SHOT | BNX2_HC_CONFIG_USE_INT_PARAM; BNX2_WR(bp, BNX2_HC_CONFIG, val); if (bp->rx_ticks < 25) bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 1); else bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 0); for (i = 1; i < bp->irq_nvecs; i++) { u32 base = ((i - 1) * BNX2_HC_SB_CONFIG_SIZE) + BNX2_HC_SB_CONFIG_1; BNX2_WR(bp, base, BNX2_HC_SB_CONFIG_1_TX_TMR_MODE | BNX2_HC_SB_CONFIG_1_RX_TMR_MODE | BNX2_HC_SB_CONFIG_1_ONE_SHOT); BNX2_WR(bp, base + BNX2_HC_TX_QUICK_CONS_TRIP_OFF, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_TX_TICKS_OFF, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, base + BNX2_HC_RX_QUICK_CONS_TRIP_OFF, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_RX_TICKS_OFF, (bp->rx_ticks_int << 16) | bp->rx_ticks); } /* Clear internal stats counters. */ BNX2_WR(bp, BNX2_HC_COMMAND, BNX2_HC_COMMAND_CLR_STAT_NOW); BNX2_WR(bp, BNX2_HC_ATTN_BITS_ENABLE, STATUS_ATTN_EVENTS); /* Initialize the receive filter. */ bnx2_set_rx_mode(bp->dev); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { val = BNX2_RD(bp, BNX2_MISC_NEW_CORE_CTL); val |= BNX2_MISC_NEW_CORE_CTL_DMA_ENABLE; BNX2_WR(bp, BNX2_MISC_NEW_CORE_CTL, val); } rc = bnx2_fw_sync(bp, BNX2_DRV_MSG_DATA_WAIT2 | BNX2_DRV_MSG_CODE_RESET, 1, 0); BNX2_WR(bp, BNX2_MISC_ENABLE_SET_BITS, BNX2_MISC_ENABLE_DEFAULT); BNX2_RD(bp, BNX2_MISC_ENABLE_SET_BITS); udelay(20); bp->hc_cmd = BNX2_RD(bp, BNX2_HC_COMMAND); return rc; } static void bnx2_clear_ring_states(struct bnx2 *bp) { struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; struct bnx2_rx_ring_info *rxr; int i; for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) { bnapi = &bp->bnx2_napi[i]; txr = &bnapi->tx_ring; rxr = &bnapi->rx_ring; txr->tx_cons = 0; txr->hw_tx_cons = 0; rxr->rx_prod_bseq = 0; rxr->rx_prod = 0; rxr->rx_cons = 0; rxr->rx_pg_prod = 0; rxr->rx_pg_cons = 0; } } static void bnx2_init_tx_context(struct bnx2 *bp, u32 cid, struct bnx2_tx_ring_info *txr) { u32 val, offset0, offset1, offset2, offset3; u32 cid_addr = GET_CID_ADDR(cid); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { offset0 = BNX2_L2CTX_TYPE_XI; offset1 = BNX2_L2CTX_CMD_TYPE_XI; offset2 = BNX2_L2CTX_TBDR_BHADDR_HI_XI; offset3 = BNX2_L2CTX_TBDR_BHADDR_LO_XI; } else { offset0 = BNX2_L2CTX_TYPE; offset1 = BNX2_L2CTX_CMD_TYPE; offset2 = BNX2_L2CTX_TBDR_BHADDR_HI; offset3 = BNX2_L2CTX_TBDR_BHADDR_LO; } val = BNX2_L2CTX_TYPE_TYPE_L2 | BNX2_L2CTX_TYPE_SIZE_L2; bnx2_ctx_wr(bp, cid_addr, offset0, val); val = BNX2_L2CTX_CMD_TYPE_TYPE_L2 | (8 << 16); bnx2_ctx_wr(bp, cid_addr, offset1, val); val = (u64) txr->tx_desc_mapping >> 32; bnx2_ctx_wr(bp, cid_addr, offset2, val); val = (u64) txr->tx_desc_mapping & 0xffffffff; bnx2_ctx_wr(bp, cid_addr, offset3, val); } static void bnx2_init_tx_ring(struct bnx2 *bp, int ring_num) { struct bnx2_tx_bd *txbd; u32 cid = TX_CID; struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; bnapi = &bp->bnx2_napi[ring_num]; txr = &bnapi->tx_ring; if (ring_num == 0) cid = TX_CID; else cid = TX_TSS_CID + ring_num - 1; bp->tx_wake_thresh = bp->tx_ring_size / 2; txbd = &txr->tx_desc_ring[BNX2_MAX_TX_DESC_CNT]; txbd->tx_bd_haddr_hi = (u64) txr->tx_desc_mapping >> 32; txbd->tx_bd_haddr_lo = (u64) txr->tx_desc_mapping & 0xffffffff; txr->tx_prod = 0; txr->tx_prod_bseq = 0; txr->tx_bidx_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_TX_HOST_BIDX; txr->tx_bseq_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_TX_HOST_BSEQ; bnx2_init_tx_context(bp, cid, txr); } static void bnx2_init_rxbd_rings(struct bnx2_rx_bd *rx_ring[], dma_addr_t dma[], u32 buf_size, int num_rings) { int i; struct bnx2_rx_bd *rxbd; for (i = 0; i < num_rings; i++) { int j; rxbd = &rx_ring[i][0]; for (j = 0; j < BNX2_MAX_RX_DESC_CNT; j++, rxbd++) { rxbd->rx_bd_len = buf_size; rxbd->rx_bd_flags = RX_BD_FLAGS_START | RX_BD_FLAGS_END; } if (i == (num_rings - 1)) j = 0; else j = i + 1; rxbd->rx_bd_haddr_hi = (u64) dma[j] >> 32; rxbd->rx_bd_haddr_lo = (u64) dma[j] & 0xffffffff; } } static void bnx2_init_rx_ring(struct bnx2 *bp, int ring_num) { int i; u16 prod, ring_prod; u32 cid, rx_cid_addr, val; struct bnx2_napi *bnapi = &bp->bnx2_napi[ring_num]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; if (ring_num == 0) cid = RX_CID; else cid = RX_RSS_CID + ring_num - 1; rx_cid_addr = GET_CID_ADDR(cid); bnx2_init_rxbd_rings(rxr->rx_desc_ring, rxr->rx_desc_mapping, bp->rx_buf_use_size, bp->rx_max_ring); bnx2_init_rx_context(bp, cid); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { val = BNX2_RD(bp, BNX2_MQ_MAP_L2_5); BNX2_WR(bp, BNX2_MQ_MAP_L2_5, val | BNX2_MQ_MAP_L2_5_ARM); #if defined(BNX2_ENABLE_NETQUEUE) /* Set in the RX context the proper CID location * for the completion */ if(BNX2_NETQUEUE_ENABLED(bp)) bnx2_ctx_wr(bp, rx_cid_addr, 0x04, 1 << 16); #endif } bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_PG_BUF_SIZE, 0); if (bp->rx_pg_ring_size) { bnx2_init_rxbd_rings(rxr->rx_pg_desc_ring, rxr->rx_pg_desc_mapping, PAGE_SIZE, bp->rx_max_pg_ring); val = (bp->rx_buf_use_size << 16) | PAGE_SIZE; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_PG_BUF_SIZE, val); bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_RBDC_KEY, BNX2_L2CTX_RBDC_JUMBO_KEY - ring_num); val = (u64) rxr->rx_pg_desc_mapping[0] >> 32; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_PG_BDHADDR_HI, val); val = (u64) rxr->rx_pg_desc_mapping[0] & 0xffffffff; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_PG_BDHADDR_LO, val); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) BNX2_WR(bp, BNX2_MQ_MAP_L2_3, BNX2_MQ_MAP_L2_3_DEFAULT); } val = (u64) rxr->rx_desc_mapping[0] >> 32; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_BDHADDR_HI, val); val = (u64) rxr->rx_desc_mapping[0] & 0xffffffff; bnx2_ctx_wr(bp, rx_cid_addr, BNX2_L2CTX_NX_BDHADDR_LO, val); ring_prod = prod = rxr->rx_pg_prod; for (i = 0; i < bp->rx_pg_ring_size; i++) { if (bnx2_alloc_rx_page(bp, rxr, ring_prod, GFP_KERNEL) < 0) { netdev_warn(bp->dev, "init'ed rx page ring %d with %d/%d pages only\n", ring_num, i, bp->rx_pg_ring_size); break; } prod = BNX2_NEXT_RX_BD(prod); ring_prod = BNX2_RX_PG_RING_IDX(prod); } rxr->rx_pg_prod = prod; ring_prod = prod = rxr->rx_prod; for (i = 0; i < bp->rx_ring_size; i++) { if (bnx2_alloc_rx_skb(bp, rxr, ring_prod, GFP_KERNEL) < 0) { netdev_warn(bp->dev, "init'ed rx ring %d with %d/%d skbs only\n", ring_num, i, bp->rx_ring_size); break; } prod = BNX2_NEXT_RX_BD(prod); ring_prod = BNX2_RX_RING_IDX(prod); } rxr->rx_prod = prod; rxr->rx_bidx_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_HOST_BDIDX; rxr->rx_bseq_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_HOST_BSEQ; rxr->rx_pg_bidx_addr = MB_GET_CID_ADDR(cid) + BNX2_L2CTX_HOST_PG_BDIDX; BNX2_WR16(bp, rxr->rx_pg_bidx_addr, rxr->rx_pg_prod); BNX2_WR16(bp, rxr->rx_bidx_addr, prod); BNX2_WR(bp, rxr->rx_bseq_addr, rxr->rx_prod_bseq); } static void bnx2_init_all_rings(struct bnx2 *bp) { int i; #if !defined(BNX2_ENABLE_NETQUEUE) u32 val; #endif bnx2_clear_ring_states(bp); BNX2_WR(bp, BNX2_TSCH_TSS_CFG, 0); for (i = 0; i < bp->num_tx_rings; i++) bnx2_init_tx_ring(bp, i); if (bp->num_tx_rings > 1) BNX2_WR(bp, BNX2_TSCH_TSS_CFG, ((bp->num_tx_rings - 1) << 24) | (TX_TSS_CID << 7)); BNX2_WR(bp, BNX2_RLUP_RSS_CONFIG, 0); bnx2_reg_wr_ind(bp, BNX2_RXP_SCRATCH_RSS_TBL_SZ, 0); for (i = 0; i < bp->num_rx_rings; i++) bnx2_init_rx_ring(bp, i); #if !defined(BNX2_ENABLE_NETQUEUE) if (bp->num_rx_rings > 1) { u32 tbl_32 = 0; for (i = 0; i < BNX2_RXP_SCRATCH_RSS_TBL_MAX_ENTRIES; i++) { int shift = (i % 8) << 2; tbl_32 |= (i % (bp->num_rx_rings - 1)) << shift; if ((i % 8) == 7) { BNX2_WR(bp, BNX2_RLUP_RSS_DATA, tbl_32); BNX2_WR(bp, BNX2_RLUP_RSS_COMMAND, (i >> 3) | BNX2_RLUP_RSS_COMMAND_RSS_WRITE_MASK | BNX2_RLUP_RSS_COMMAND_WRITE | BNX2_RLUP_RSS_COMMAND_HASH_MASK); tbl_32 = 0; } } val = BNX2_RLUP_RSS_CONFIG_IPV4_RSS_TYPE_ALL_XI | BNX2_RLUP_RSS_CONFIG_IPV6_RSS_TYPE_ALL_XI; BNX2_WR(bp, BNX2_RLUP_RSS_CONFIG, val); } #endif } static u32 bnx2_find_max_ring(u32 ring_size, u32 max_size) { u32 max, num_rings = 1; while (ring_size > BNX2_MAX_RX_DESC_CNT) { ring_size -= BNX2_MAX_RX_DESC_CNT; num_rings++; } /* round to next power of 2 */ max = max_size; while ((max & num_rings) == 0) max >>= 1; if (num_rings != max) max <<= 1; return max; } static void bnx2_set_rx_ring_size(struct bnx2 *bp, u32 size) { u32 rx_size, rx_space; /* 8 for CRC and VLAN */ rx_size = bp->dev->mtu + ETH_HLEN + BNX2_RX_OFFSET + 8; rx_space = SKB_DATA_ALIGN(rx_size + BNX2_RX_ALIGN) + NET_SKB_PAD + sizeof(struct skb_shared_info); bp->rx_copy_thresh = BNX2_RX_COPY_THRESH; bp->rx_pg_ring_size = 0; bp->rx_max_pg_ring = 0; bp->rx_max_pg_ring_idx = 0; #if !defined(__VMKLNX__) if ((rx_space > PAGE_SIZE) && !(bp->flags & BNX2_FLAG_JUMBO_BROKEN)) { int pages = PAGE_ALIGN(bp->dev->mtu - 40) >> PAGE_SHIFT; u32 jumbo_size = size * pages; if (jumbo_size > BNX2_MAX_TOTAL_RX_PG_DESC_CNT) jumbo_size = BNX2_MAX_TOTAL_RX_PG_DESC_CNT; bp->rx_pg_ring_size = jumbo_size; bp->rx_max_pg_ring = bnx2_find_max_ring(jumbo_size, BNX2_MAX_RX_PG_RINGS); bp->rx_max_pg_ring_idx = (bp->rx_max_pg_ring * BNX2_RX_DESC_CNT) - 1; rx_size = BNX2_RX_COPY_THRESH + BNX2_RX_OFFSET; bp->rx_copy_thresh = 0; } #endif bp->rx_buf_use_size = rx_size; /* hw alignment */ bp->rx_buf_size = bp->rx_buf_use_size + BNX2_RX_ALIGN; bp->rx_jumbo_thresh = rx_size - BNX2_RX_OFFSET; bp->rx_ring_size = size; bp->rx_max_ring = bnx2_find_max_ring(size, BNX2_MAX_RX_RINGS); bp->rx_max_ring_idx = (bp->rx_max_ring * BNX2_RX_DESC_CNT) - 1; } static void bnx2_free_tx_skbs(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_tx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; int j; if (txr->tx_buf_ring == NULL) continue; for (j = 0; j < BNX2_TX_DESC_CNT; ) { struct bnx2_sw_tx_bd *tx_buf = &txr->tx_buf_ring[j]; struct sk_buff *skb = tx_buf->skb; int k, last; if (skb == NULL) { j = BNX2_NEXT_TX_BD(j); continue; } #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, #else pci_unmap_single(bp->pdev, #endif dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); tx_buf->skb = NULL; last = tx_buf->nr_frags; j = BNX2_NEXT_TX_BD(j); for (k = 0; k < last; k++, j = BNX2_NEXT_TX_BD(j)) { tx_buf = &txr->tx_buf_ring[BNX2_TX_RING_IDX(j)]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, #else pci_unmap_page(bp->pdev, #endif dma_unmap_addr(tx_buf, mapping), skb_frag_size(&skb_shinfo(skb)->frags[k]), PCI_DMA_TODEVICE); } dev_kfree_skb(skb); } } } static void bnx2_free_rx_skbs(struct bnx2 *bp) { int i; for (i = 0; i < bp->num_rx_rings; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; int j; if (rxr->rx_buf_ring == NULL) return; for (j = 0; j < bp->rx_max_ring_idx; j++) { struct bnx2_sw_bd *rx_buf = &rxr->rx_buf_ring[j]; struct sk_buff *skb = rx_buf->skb; if (skb == NULL) continue; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, #else pci_unmap_single(bp->pdev, #endif dma_unmap_addr(rx_buf, mapping), bp->rx_buf_use_size, PCI_DMA_FROMDEVICE); rx_buf->skb = NULL; dev_kfree_skb(skb); } for (j = 0; j < bp->rx_max_pg_ring_idx; j++) bnx2_free_rx_page(bp, rxr, j); } } static void bnx2_free_skbs(struct bnx2 *bp) { bnx2_free_tx_skbs(bp); bnx2_free_rx_skbs(bp); } static int bnx2_reset_nic(struct bnx2 *bp, u32 reset_code) { int rc; rc = bnx2_reset_chip(bp, reset_code); bnx2_free_skbs(bp); if (rc) return rc; if ((rc = bnx2_init_chip(bp)) != 0) return rc; bnx2_init_all_rings(bp); return 0; } static int bnx2_init_nic(struct bnx2 *bp, int reset_phy) { int rc; if ((rc = bnx2_reset_nic(bp, BNX2_DRV_MSG_CODE_RESET)) != 0) return rc; spin_lock_bh(&bp->phy_lock); bnx2_init_phy(bp, reset_phy); bnx2_set_link(bp); if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) bnx2_remote_phy_event(bp); spin_unlock_bh(&bp->phy_lock); return 0; } static int bnx2_shutdown_chip(struct bnx2 *bp) { u32 reset_code; if (bp->flags & BNX2_FLAG_NO_WOL) reset_code = BNX2_DRV_MSG_CODE_UNLOAD_LNK_DN; else if (bp->wol) reset_code = BNX2_DRV_MSG_CODE_SUSPEND_WOL; else reset_code = BNX2_DRV_MSG_CODE_SUSPEND_NO_WOL; return bnx2_reset_chip(bp, reset_code); } static int bnx2_test_registers(struct bnx2 *bp) { int ret; int i, is_5709; static const struct { u16 offset; u16 flags; #define BNX2_FL_NOT_5709 1 u32 rw_mask; u32 ro_mask; } reg_tbl[] = { { 0x006c, 0, 0x00000000, 0x0000003f }, { 0x0090, 0, 0xffffffff, 0x00000000 }, { 0x0094, 0, 0x00000000, 0x00000000 }, { 0x0404, BNX2_FL_NOT_5709, 0x00003f00, 0x00000000 }, { 0x0418, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x041c, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0420, BNX2_FL_NOT_5709, 0x00000000, 0x80ffffff }, { 0x0424, BNX2_FL_NOT_5709, 0x00000000, 0x00000000 }, { 0x0428, BNX2_FL_NOT_5709, 0x00000000, 0x00000001 }, { 0x0450, BNX2_FL_NOT_5709, 0x00000000, 0x0000ffff }, { 0x0454, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0458, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0808, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0854, BNX2_FL_NOT_5709, 0x00000000, 0xffffffff }, { 0x0868, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x086c, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x0870, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x0874, BNX2_FL_NOT_5709, 0x00000000, 0x77777777 }, { 0x0c00, BNX2_FL_NOT_5709, 0x00000000, 0x00000001 }, { 0x0c04, BNX2_FL_NOT_5709, 0x00000000, 0x03ff0001 }, { 0x0c08, BNX2_FL_NOT_5709, 0x0f0ff073, 0x00000000 }, { 0x1000, 0, 0x00000000, 0x00000001 }, { 0x1004, BNX2_FL_NOT_5709, 0x00000000, 0x000f0001 }, { 0x1408, 0, 0x01c00800, 0x00000000 }, { 0x149c, 0, 0x8000ffff, 0x00000000 }, { 0x14a8, 0, 0x00000000, 0x000001ff }, { 0x14ac, 0, 0x0fffffff, 0x10000000 }, { 0x14b0, 0, 0x00000002, 0x00000001 }, { 0x14b8, 0, 0x00000000, 0x00000000 }, { 0x14c0, 0, 0x00000000, 0x00000009 }, { 0x14c4, 0, 0x00003fff, 0x00000000 }, { 0x14cc, 0, 0x00000000, 0x00000001 }, { 0x14d0, 0, 0xffffffff, 0x00000000 }, { 0x1800, 0, 0x00000000, 0x00000001 }, { 0x1804, 0, 0x00000000, 0x00000003 }, { 0x2800, 0, 0x00000000, 0x00000001 }, { 0x2804, 0, 0x00000000, 0x00003f01 }, { 0x2808, 0, 0x0f3f3f03, 0x00000000 }, { 0x2810, 0, 0xffff0000, 0x00000000 }, { 0x2814, 0, 0xffff0000, 0x00000000 }, { 0x2818, 0, 0xffff0000, 0x00000000 }, { 0x281c, 0, 0xffff0000, 0x00000000 }, { 0x2834, 0, 0xffffffff, 0x00000000 }, { 0x2840, 0, 0x00000000, 0xffffffff }, { 0x2844, 0, 0x00000000, 0xffffffff }, { 0x2848, 0, 0xffffffff, 0x00000000 }, { 0x284c, 0, 0xf800f800, 0x07ff07ff }, { 0x2c00, 0, 0x00000000, 0x00000011 }, { 0x2c04, 0, 0x00000000, 0x00030007 }, { 0x3c00, 0, 0x00000000, 0x00000001 }, { 0x3c04, 0, 0x00000000, 0x00070000 }, { 0x3c08, 0, 0x00007f71, 0x07f00000 }, { 0x3c0c, 0, 0x1f3ffffc, 0x00000000 }, { 0x3c10, 0, 0xffffffff, 0x00000000 }, { 0x3c14, 0, 0x00000000, 0xffffffff }, { 0x3c18, 0, 0x00000000, 0xffffffff }, { 0x3c1c, 0, 0xfffff000, 0x00000000 }, { 0x3c20, 0, 0xffffff00, 0x00000000 }, { 0x5004, 0, 0x00000000, 0x0000007f }, { 0x5008, 0, 0x0f0007ff, 0x00000000 }, { 0x5c00, 0, 0x00000000, 0x00000001 }, { 0x5c04, 0, 0x00000000, 0x0003000f }, { 0x5c08, 0, 0x00000003, 0x00000000 }, { 0x5c0c, 0, 0x0000fff8, 0x00000000 }, { 0x5c10, 0, 0x00000000, 0xffffffff }, { 0x5c80, 0, 0x00000000, 0x0f7113f1 }, { 0x5c84, 0, 0x00000000, 0x0000f333 }, { 0x5c88, 0, 0x00000000, 0x00077373 }, { 0x5c8c, 0, 0x00000000, 0x0007f737 }, { 0x6808, 0, 0x0000ff7f, 0x00000000 }, { 0x680c, 0, 0xffffffff, 0x00000000 }, { 0x6810, 0, 0xffffffff, 0x00000000 }, { 0x6814, 0, 0xffffffff, 0x00000000 }, { 0x6818, 0, 0xffffffff, 0x00000000 }, { 0x681c, 0, 0xffffffff, 0x00000000 }, { 0x6820, 0, 0x00ff00ff, 0x00000000 }, { 0x6824, 0, 0x00ff00ff, 0x00000000 }, { 0x6828, 0, 0x00ff00ff, 0x00000000 }, { 0x682c, 0, 0x03ff03ff, 0x00000000 }, { 0x6830, 0, 0x03ff03ff, 0x00000000 }, { 0x6834, 0, 0x03ff03ff, 0x00000000 }, { 0x6838, 0, 0x03ff03ff, 0x00000000 }, { 0x683c, 0, 0x0000ffff, 0x00000000 }, { 0x6840, 0, 0x00000ff0, 0x00000000 }, { 0x6844, 0, 0x00ffff00, 0x00000000 }, { 0x684c, 0, 0xffffffff, 0x00000000 }, { 0x6850, 0, 0x7f7f7f7f, 0x00000000 }, { 0x6854, 0, 0x7f7f7f7f, 0x00000000 }, { 0x6858, 0, 0x7f7f7f7f, 0x00000000 }, { 0x685c, 0, 0x7f7f7f7f, 0x00000000 }, { 0x6908, 0, 0x00000000, 0x0001ff0f }, { 0x690c, 0, 0x00000000, 0x0ffe00f0 }, { 0xffff, 0, 0x00000000, 0x00000000 }, }; ret = 0; is_5709 = 0; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) is_5709 = 1; for (i = 0; reg_tbl[i].offset != 0xffff; i++) { u32 offset, rw_mask, ro_mask, save_val, val; u16 flags = reg_tbl[i].flags; if (is_5709 && (flags & BNX2_FL_NOT_5709)) continue; offset = (u32) reg_tbl[i].offset; rw_mask = reg_tbl[i].rw_mask; ro_mask = reg_tbl[i].ro_mask; save_val = readl(bp->regview + offset); writel(0, bp->regview + offset); val = readl(bp->regview + offset); if ((val & rw_mask) != 0) { goto reg_test_err; } if ((val & ro_mask) != (save_val & ro_mask)) { goto reg_test_err; } writel(0xffffffff, bp->regview + offset); val = readl(bp->regview + offset); if ((val & rw_mask) != rw_mask) { goto reg_test_err; } if ((val & ro_mask) != (save_val & ro_mask)) { goto reg_test_err; } writel(save_val, bp->regview + offset); continue; reg_test_err: writel(save_val, bp->regview + offset); ret = -ENODEV; break; } return ret; } static int bnx2_do_mem_test(struct bnx2 *bp, u32 start, u32 size) { static const u32 test_pattern[] = { 0x00000000, 0xffffffff, 0x55555555, 0xaaaaaaaa , 0xaa55aa55, 0x55aa55aa }; int i; for (i = 0; i < sizeof(test_pattern) / 4; i++) { u32 offset; for (offset = 0; offset < size; offset += 4) { bnx2_reg_wr_ind(bp, start + offset, test_pattern[i]); if (bnx2_reg_rd_ind(bp, start + offset) != test_pattern[i]) { return -ENODEV; } } } return 0; } static int bnx2_test_memory(struct bnx2 *bp) { int ret = 0; int i; static struct mem_entry { u32 offset; u32 len; } mem_tbl_5706[] = { { 0x60000, 0x4000 }, { 0xa0000, 0x3000 }, { 0xe0000, 0x4000 }, { 0x120000, 0x4000 }, { 0x1a0000, 0x4000 }, { 0x160000, 0x4000 }, { 0xffffffff, 0 }, }, mem_tbl_5709[] = { { 0x60000, 0x4000 }, { 0xa0000, 0x3000 }, { 0xe0000, 0x4000 }, { 0x120000, 0x4000 }, { 0x1a0000, 0x4000 }, { 0xffffffff, 0 }, }; struct mem_entry *mem_tbl; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) mem_tbl = mem_tbl_5709; else mem_tbl = mem_tbl_5706; for (i = 0; mem_tbl[i].offset != 0xffffffff; i++) { if ((ret = bnx2_do_mem_test(bp, mem_tbl[i].offset, mem_tbl[i].len)) != 0) { return ret; } } return ret; } #define BNX2_MAC_LOOPBACK 0 #define BNX2_PHY_LOOPBACK 1 static int bnx2_run_loopback(struct bnx2 *bp, int loopback_mode) { unsigned int pkt_size, num_pkts, i; struct sk_buff *skb, *rx_skb; unsigned char *packet; u16 rx_start_idx, rx_idx; dma_addr_t map; struct bnx2_tx_bd *txbd; struct bnx2_sw_bd *rx_buf; struct l2_fhdr *rx_hdr; int ret = -ENODEV; struct bnx2_napi *bnapi = &bp->bnx2_napi[0], *tx_napi; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; struct bnx2_rx_ring_info *rxr = &bnapi->rx_ring; tx_napi = bnapi; txr = &tx_napi->tx_ring; rxr = &bnapi->rx_ring; if (loopback_mode == BNX2_MAC_LOOPBACK) { bp->loopback = MAC_LOOPBACK; bnx2_set_mac_loopback(bp); } else if (loopback_mode == BNX2_PHY_LOOPBACK) { if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return 0; bp->loopback = PHY_LOOPBACK; bnx2_set_phy_loopback(bp); } else return -EINVAL; pkt_size = min(bp->dev->mtu + ETH_HLEN, bp->rx_jumbo_thresh - 4); skb = netdev_alloc_skb(bp->dev, pkt_size); if (!skb) return -ENOMEM; packet = skb_put(skb, pkt_size); memcpy(packet, bp->dev->dev_addr, 6); memset(packet + 6, 0x0, 8); for (i = 14; i < pkt_size; i++) packet[i] = (unsigned char) (i & 0xff); #if (LINUX_VERSION_CODE >= 0x02061b) map = dma_map_single(&bp->pdev->dev, skb->data, pkt_size, PCI_DMA_TODEVICE); if (dma_mapping_error(&bp->pdev->dev, map)) { #else map = pci_map_single(bp->pdev, skb->data, pkt_size, PCI_DMA_TODEVICE); if (pci_dma_mapping_error(map)) { #endif dev_kfree_skb(skb); return -EIO; } BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); udelay(5); rx_start_idx = bnx2_get_hw_rx_cons(bnapi); num_pkts = 0; txbd = &txr->tx_desc_ring[BNX2_TX_RING_IDX(txr->tx_prod)]; txbd->tx_bd_haddr_hi = (u64) map >> 32; txbd->tx_bd_haddr_lo = (u64) map & 0xffffffff; txbd->tx_bd_mss_nbytes = pkt_size; txbd->tx_bd_vlan_tag_flags = TX_BD_FLAGS_START | TX_BD_FLAGS_END; num_pkts++; txr->tx_prod = BNX2_NEXT_TX_BD(txr->tx_prod); txr->tx_prod_bseq += pkt_size; BNX2_WR16(bp, txr->tx_bidx_addr, txr->tx_prod); BNX2_WR(bp, txr->tx_bseq_addr, txr->tx_prod_bseq); udelay(100); BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW_WO_INT); BNX2_RD(bp, BNX2_HC_COMMAND); udelay(5); #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, map, pkt_size, PCI_DMA_TODEVICE); #else pci_unmap_single(bp->pdev, map, pkt_size, PCI_DMA_TODEVICE); #endif dev_kfree_skb(skb); if (bnx2_get_hw_tx_cons(tx_napi) != txr->tx_prod) goto loopback_test_done; rx_idx = bnx2_get_hw_rx_cons(bnapi); if (rx_idx != rx_start_idx + num_pkts) { goto loopback_test_done; } rx_buf = &rxr->rx_buf_ring[rx_start_idx]; rx_skb = rx_buf->skb; rx_hdr = rx_buf->desc; skb_reserve(rx_skb, BNX2_RX_OFFSET); #if (LINUX_VERSION_CODE >= 0x02061b) dma_sync_single_for_cpu(&bp->pdev->dev, #else pci_dma_sync_single_for_cpu(bp->pdev, #endif dma_unmap_addr(rx_buf, mapping), bp->rx_buf_size, PCI_DMA_FROMDEVICE); if (rx_hdr->l2_fhdr_status & (L2_FHDR_ERRORS_BAD_CRC | L2_FHDR_ERRORS_PHY_DECODE | L2_FHDR_ERRORS_ALIGNMENT | L2_FHDR_ERRORS_TOO_SHORT | L2_FHDR_ERRORS_GIANT_FRAME)) { goto loopback_test_done; } if ((rx_hdr->l2_fhdr_pkt_len - 4) != pkt_size) { goto loopback_test_done; } for (i = 14; i < pkt_size; i++) { if (*(rx_skb->data + i) != (unsigned char) (i & 0xff)) { goto loopback_test_done; } } ret = 0; loopback_test_done: bp->loopback = 0; return ret; } #define BNX2_MAC_LOOPBACK_FAILED 1 #define BNX2_PHY_LOOPBACK_FAILED 2 #define BNX2_LOOPBACK_FAILED (BNX2_MAC_LOOPBACK_FAILED | \ BNX2_PHY_LOOPBACK_FAILED) static int bnx2_test_loopback(struct bnx2 *bp) { int rc = 0; if (!netif_running(bp->dev)) return BNX2_LOOPBACK_FAILED; bnx2_reset_nic(bp, BNX2_DRV_MSG_CODE_RESET); spin_lock_bh(&bp->phy_lock); bnx2_init_phy(bp, 1); spin_unlock_bh(&bp->phy_lock); if (bnx2_run_loopback(bp, BNX2_MAC_LOOPBACK)) rc |= BNX2_MAC_LOOPBACK_FAILED; if (bnx2_run_loopback(bp, BNX2_PHY_LOOPBACK)) rc |= BNX2_PHY_LOOPBACK_FAILED; return rc; } #define NVRAM_SIZE 0x200 #define CRC32_RESIDUAL 0xdebb20e3 static int bnx2_test_nvram(struct bnx2 *bp) { __be32 buf[NVRAM_SIZE / 4]; u8 *data = (u8 *) buf; int rc = 0; u32 magic, csum; if ((rc = bnx2_nvram_read(bp, 0, data, 4)) != 0) goto test_nvram_done; magic = be32_to_cpu(buf[0]); if (magic != 0x669955aa) { rc = -ENODEV; goto test_nvram_done; } if ((rc = bnx2_nvram_read(bp, 0x100, data, NVRAM_SIZE)) != 0) goto test_nvram_done; csum = ether_crc_le(0x100, data); if (csum != CRC32_RESIDUAL) { rc = -ENODEV; goto test_nvram_done; } csum = ether_crc_le(0x100, data + 0x100); if (csum != CRC32_RESIDUAL) { rc = -ENODEV; } test_nvram_done: return rc; } static int bnx2_test_link(struct bnx2 *bp) { u32 bmsr; if (!netif_running(bp->dev)) return -ENODEV; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { int i; for (i = 0; i < 6 && !bp->link_up; i++) { if (bnx2_msleep_interruptible(500)) break; } if (bp->link_up) return 0; return -ENODEV; } spin_lock_bh(&bp->phy_lock); bnx2_enable_bmsr1(bp); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_read_phy(bp, bp->mii_bmsr1, &bmsr); bnx2_disable_bmsr1(bp); spin_unlock_bh(&bp->phy_lock); if (bmsr & BMSR_LSTATUS) { return 0; } return -ENODEV; } static int bnx2_test_intr(struct bnx2 *bp) { int i; u16 status_idx; if (!netif_running(bp->dev)) return -ENODEV; status_idx = BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD) & 0xffff; /* This register is not touched during run-time. */ BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_COAL_NOW); BNX2_RD(bp, BNX2_HC_COMMAND); for (i = 0; i < 10; i++) { if ((BNX2_RD(bp, BNX2_PCICFG_INT_ACK_CMD) & 0xffff) != status_idx) { break; } bnx2_msleep_interruptible(10); } if (i < 10) return 0; return -ENODEV; } /* Determining link for parallel detection. */ static int bnx2_5706_serdes_has_link(struct bnx2 *bp) { u32 mode_ctl, an_dbg, exp; if (bp->phy_flags & BNX2_PHY_FLAG_NO_PARALLEL) return 0; bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_MODE_CTL); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &mode_ctl); if (!(mode_ctl & MISC_SHDW_MODE_CTL_SIG_DET)) return 0; bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_AN_DBG); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &an_dbg); if (an_dbg & (MISC_SHDW_AN_DBG_NOSYNC | MISC_SHDW_AN_DBG_RUDI_INVALID)) return 0; bnx2_write_phy(bp, MII_BNX2_DSP_ADDRESS, MII_EXPAND_REG1); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &exp); bnx2_read_phy(bp, MII_BNX2_DSP_RW_PORT, &exp); if (exp & MII_EXPAND_REG1_RUDI_C) /* receiving CONFIG */ return 0; return 1; } static void bnx2_5706_serdes_timer(struct bnx2 *bp) { int check_link = 1; spin_lock(&bp->phy_lock); if (bp->serdes_an_pending) { bp->serdes_an_pending--; check_link = 0; } else if ((bp->link_up == 0) && (bp->autoneg & AUTONEG_SPEED)) { u32 bmcr; bp->current_interval = BNX2_TIMER_INTERVAL; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_ANENABLE) { if (bnx2_5706_serdes_has_link(bp)) { bmcr &= ~BMCR_ANENABLE; bmcr |= BMCR_SPEED1000 | BMCR_FULLDPLX; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); bp->phy_flags |= BNX2_PHY_FLAG_PARALLEL_DETECT; } } } else if ((bp->link_up) && (bp->autoneg & AUTONEG_SPEED) && (bp->phy_flags & BNX2_PHY_FLAG_PARALLEL_DETECT)) { u32 phy2; bnx2_write_phy(bp, 0x17, 0x0f01); bnx2_read_phy(bp, 0x15, &phy2); if (phy2 & 0x20) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bmcr |= BMCR_ANENABLE; bnx2_write_phy(bp, bp->mii_bmcr, bmcr); bp->phy_flags &= ~BNX2_PHY_FLAG_PARALLEL_DETECT; } } else bp->current_interval = BNX2_TIMER_INTERVAL; if (check_link) { u32 val; bnx2_write_phy(bp, MII_BNX2_MISC_SHADOW, MISC_SHDW_AN_DBG); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &val); bnx2_read_phy(bp, MII_BNX2_MISC_SHADOW, &val); if (bp->link_up && (val & MISC_SHDW_AN_DBG_NOSYNC)) { if (!(bp->phy_flags & BNX2_PHY_FLAG_FORCED_DOWN)) { bnx2_5706s_force_link_dn(bp, 1); bp->phy_flags |= BNX2_PHY_FLAG_FORCED_DOWN; } else bnx2_set_link(bp); } else if (!bp->link_up && !(val & MISC_SHDW_AN_DBG_NOSYNC)) bnx2_set_link(bp); } spin_unlock(&bp->phy_lock); } static void bnx2_5708_serdes_timer(struct bnx2 *bp) { if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return; if ((bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) == 0) { bp->serdes_an_pending = 0; return; } spin_lock(&bp->phy_lock); if (bp->serdes_an_pending) bp->serdes_an_pending--; else if ((bp->link_up == 0) && (bp->autoneg & AUTONEG_SPEED)) { u32 bmcr; bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); if (bmcr & BMCR_ANENABLE) { bnx2_enable_forced_2g5(bp); bp->current_interval = BNX2_SERDES_FORCED_TIMEOUT; } else { bnx2_disable_forced_2g5(bp); bp->serdes_an_pending = 2; bp->current_interval = BNX2_TIMER_INTERVAL; } } else bp->current_interval = BNX2_TIMER_INTERVAL; spin_unlock(&bp->phy_lock); } static void bnx2_timer(unsigned long data) { struct bnx2 *bp = (struct bnx2 *) data; if (!netif_running(bp->dev)) return; if (atomic_read(&bp->intr_sem) != 0) goto bnx2_restart_timer; #ifdef CONFIG_PCI_MSI if ((bp->flags & (BNX2_FLAG_USING_MSI | BNX2_FLAG_ONE_SHOT_MSI)) == BNX2_FLAG_USING_MSI) bnx2_chk_missed_msi(bp); #endif bnx2_send_heart_beat(bp); bp->stats_blk->stat_FwRxDrop = bnx2_reg_rd_ind(bp, BNX2_FW_RX_DROP_COUNT); /* workaround occasional corrupted counters */ if ((bp->flags & BNX2_FLAG_BROKEN_STATS) && bp->stats_ticks) BNX2_WR(bp, BNX2_HC_COMMAND, bp->hc_cmd | BNX2_HC_COMMAND_STATS_NOW); if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { if (BNX2_CHIP(bp) == BNX2_CHIP_5706) bnx2_5706_serdes_timer(bp); else bnx2_5708_serdes_timer(bp); } bnx2_restart_timer: mod_timer(&bp->timer, jiffies + bp->current_interval); } static int bnx2_request_irq(struct bnx2 *bp) { unsigned long flags; struct bnx2_irq *irq; int rc = 0, i; if (bp->flags & BNX2_FLAG_USING_MSI_OR_MSIX) flags = 0; else flags = IRQF_SHARED; #if defined(__VMKLNX__) /* * In ESX, bnx2 will setup int mode during .probe time. However, the dev->name * will be finalized only when pci_announce_device is done. So, we assign * irq->name here instead of in bnx2_setup_int_mode. */ strcpy(bp->irq_tbl[0].name, bp->dev->name); if (bp->flags & BNX2_FLAG_USING_MSIX) { for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) { snprintf(bp->irq_tbl[i].name, sizeof(bp->irq_tbl[i].name), "%s-%d", bp->dev->name, i); } } #endif for (i = 0; i < bp->irq_nvecs; i++) { irq = &bp->irq_tbl[i]; rc = request_irq(irq->vector, irq->handler, flags, irq->name, &bp->bnx2_napi[i]); if (rc) break; irq->requested = 1; } return rc; } #if defined(__VMKLNX__) /* disable MSI/MSIX */ static void bnx2_disable_msi(struct bnx2 *bp) { #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_USING_MSI) pci_disable_msi(bp->pdev); else if (bp->flags & BNX2_FLAG_USING_MSIX) pci_disable_msix(bp->pdev); bp->flags &= ~(BNX2_FLAG_USING_MSI_OR_MSIX | BNX2_FLAG_ONE_SHOT_MSI); #endif } #endif /* defined(__VMKLNX__) */ static void __bnx2_free_irq(struct bnx2 *bp) { struct bnx2_irq *irq; int i; for (i = 0; i < bp->irq_nvecs; i++) { irq = &bp->irq_tbl[i]; if (irq->requested) free_irq(irq->vector, &bp->bnx2_napi[i]); irq->requested = 0; } } static void bnx2_free_irq(struct bnx2 *bp) { __bnx2_free_irq(bp); #if !defined(__VMKLNX__) #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_USING_MSI) pci_disable_msi(bp->pdev); else if (bp->flags & BNX2_FLAG_USING_MSIX) pci_disable_msix(bp->pdev); bp->flags &= ~(BNX2_FLAG_USING_MSI_OR_MSIX | BNX2_FLAG_ONE_SHOT_MSI); #endif #endif /* __VMKLNX__ */ } #ifdef CONFIG_PCI_MSI static void bnx2_enable_msix(struct bnx2 *bp, int msix_vecs) { #ifdef BNX2_NEW_NAPI int i, total_vecs, rc; struct msix_entry msix_ent[BNX2_MAX_MSIX_VEC]; #if !defined(__VMKLNX__) struct net_device *dev = bp->dev; const int len = sizeof(bp->irq_tbl[0].name); #endif bnx2_setup_msix_tbl(bp); BNX2_WR(bp, BNX2_PCI_MSIX_CONTROL, BNX2_MAX_MSIX_HW_VEC - 1); BNX2_WR(bp, BNX2_PCI_MSIX_TBL_OFF_BIR, BNX2_PCI_GRC_WINDOW2_BASE); BNX2_WR(bp, BNX2_PCI_MSIX_PBA_OFF_BIT, BNX2_PCI_GRC_WINDOW3_BASE); /* Need to flush the previous three writes to ensure MSI-X * is setup properly */ BNX2_RD(bp, BNX2_PCI_MSIX_CONTROL); for (i = 0; i < BNX2_MAX_MSIX_VEC; i++) { msix_ent[i].entry = i; msix_ent[i].vector = 0; } total_vecs = msix_vecs; #ifdef BCM_CNIC total_vecs++; #endif rc = -ENOSPC; while (total_vecs >= BNX2_MIN_MSIX_VEC) { rc = pci_enable_msix(bp->pdev, msix_ent, total_vecs); if (rc <= 0) break; if (rc > 0) total_vecs = rc; } if (rc != 0) return; msix_vecs = total_vecs; #ifdef BCM_CNIC msix_vecs--; #endif bp->irq_nvecs = msix_vecs; bp->flags |= BNX2_FLAG_USING_MSIX | BNX2_FLAG_ONE_SHOT_MSI; #if defined(__VMKLNX__) if (disable_msi_1shot) bp->flags &= ~BNX2_FLAG_ONE_SHOT_MSI; #endif for (i = 0; i < total_vecs; i++) { bp->irq_tbl[i].vector = msix_ent[i].vector; #if !defined(__VMKLNX__) snprintf(bp->irq_tbl[i].name, len, "%s-%d", dev->name, i); bp->irq_tbl[i].handler = bnx2_msi_1shot; #else if (disable_msi_1shot) bp->irq_tbl[i].handler = bnx2_msi; else bp->irq_tbl[i].handler = bnx2_msi_1shot; #endif } #endif } #endif static int bnx2_setup_int_mode(struct bnx2 *bp, int dis_msi) { #ifdef CONFIG_PCI_MSI #if defined(BNX2_ENABLE_NETQUEUE) int cpus = num_online_cpus(); int msix_vecs = min(cpus, 4); if (force_netq_param[bp->index] != BNX2_OPTION_UNSET) msix_vecs = min(force_netq_param[bp->index], RX_MAX_RSS_RINGS); /* Once is for the default queuue */ msix_vecs += 1; #else #if defined(__VMKLNX__) /* If NetQueue is not enable then force the number of queues to 1 */ int msix_vecs = 1; #else int cpus = num_online_cpus(); int msix_vecs; #endif /* defined(__VMKLNX__) */ #endif #endif #if !defined(__VMKLNX__) if (!bp->num_req_rx_rings) msix_vecs = max(cpus + 1, bp->num_req_tx_rings); else if (!bp->num_req_tx_rings) msix_vecs = max(cpus, bp->num_req_rx_rings); else msix_vecs = max(bp->num_req_rx_rings, bp->num_req_tx_rings); msix_vecs = min(msix_vecs, RX_MAX_RINGS); #endif bp->irq_tbl[0].handler = bnx2_interrupt; #if !defined(__VMKLNX__) strcpy(bp->irq_tbl[0].name, bp->dev->name); #endif bp->irq_nvecs = 1; bp->irq_tbl[0].vector = bp->pdev->irq; #ifdef CONFIG_PCI_MSI if ((bp->flags & BNX2_FLAG_MSIX_CAP) && !dis_msi) bnx2_enable_msix(bp, msix_vecs); if ((bp->flags & BNX2_FLAG_MSI_CAP) && !dis_msi && !(bp->flags & BNX2_FLAG_USING_MSIX)) { if (pci_enable_msi(bp->pdev) == 0) { bp->flags |= BNX2_FLAG_USING_MSI; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { bp->flags |= BNX2_FLAG_ONE_SHOT_MSI; bp->irq_tbl[0].handler = bnx2_msi_1shot; #if defined(__VMKLNX__) if (disable_msi_1shot) { bp->flags &= ~BNX2_FLAG_ONE_SHOT_MSI; bp->irq_tbl[0].handler = bnx2_msi; } #endif } else bp->irq_tbl[0].handler = bnx2_msi; bp->irq_tbl[0].vector = bp->pdev->irq; } } #endif #ifndef BCM_HAVE_MULTI_QUEUE bp->num_tx_rings = 1; bp->num_rx_rings = bp->irq_nvecs; #else #if defined(__VMKLNX__) #if defined(BNX2_ENABLE_NETQUEUE) bp->num_tx_rings = bp->irq_nvecs; bp->dev->real_num_tx_queues = bp->num_tx_rings; #else bp->num_tx_rings = 1; #endif bp->num_rx_rings = bp->irq_nvecs; #else if (!bp->num_req_tx_rings) bp->num_tx_rings = rounddown_pow_of_two(bp->irq_nvecs); else bp->num_tx_rings = min(bp->irq_nvecs, bp->num_req_tx_rings); if (!bp->num_req_rx_rings) bp->num_rx_rings = bp->irq_nvecs; else bp->num_rx_rings = min(bp->irq_nvecs, bp->num_req_rx_rings); #endif netif_set_real_num_tx_queues(bp->dev, bp->num_tx_rings); #endif return netif_set_real_num_rx_queues(bp->dev, bp->num_rx_rings); } /* Called with rtnl_lock */ static int bnx2_open(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); int rc; netif_carrier_off(dev); bnx2_disable_int(bp); #if !(defined __VMKLNX__) rc = bnx2_setup_int_mode(bp, disable_msi); if (rc) goto open_err; bnx2_init_napi(bp); #endif /* !(defined __VMKLNX__) */ rc = bnx2_alloc_mem(bp); if (rc) goto open_err; rc = bnx2_request_irq(bp); if (rc) goto open_err; rc = bnx2_init_nic(bp, 1); if (rc) goto open_err; #ifdef BNX2_NEW_NAPI bnx2_napi_enable(bp); #endif mod_timer(&bp->timer, jiffies + bp->current_interval); atomic_set(&bp->intr_sem, 0); memset(bp->temp_stats_blk, 0, sizeof(struct statistics_block)); bnx2_enable_int(bp); #ifdef CONFIG_PCI_MSI if (bp->flags & BNX2_FLAG_USING_MSI) { /* Test MSI to make sure it is working * If MSI test fails, go back to INTx mode */ if (bnx2_test_intr(bp) != 0) { netdev_warn(bp->dev, "No interrupt was generated using MSI, switching to INTx mode. Please report this failure to the PCI maintainer and include system chipset information.\n"); #ifdef BNX2_NEW_NAPI bnx2_napi_disable(bp); #endif bnx2_disable_int(bp); bnx2_free_irq(bp); #if defined(__VMKLNX__) bnx2_disable_msi(bp); #endif bnx2_setup_int_mode(bp, 1); rc = bnx2_init_nic(bp, 0); if (!rc) rc = bnx2_request_irq(bp); if (rc) { del_timer_sync(&bp->timer); goto open_err; } #ifdef BNX2_NEW_NAPI bnx2_napi_enable(bp); #endif bnx2_enable_int(bp); } } if (bp->flags & BNX2_FLAG_USING_MSI) netdev_info(dev, "using MSI\n"); else if (bp->flags & BNX2_FLAG_USING_MSIX) netdev_info(dev, "using MSIX\n"); #endif #if defined(BNX2_ENABLE_NETQUEUE) if (bnx2_netqueue_is_avail(bp)) bnx2_open_netqueue_hw(bp); #endif netif_tx_start_all_queues(dev); #if defined(__VMKLNX__) if (bp->cnic_eth_dev.drv_state & CNIC_DRV_STATE_REGD) { bnx2_setup_cnic_irq_info(bp); bnx2_cnic_start(bp); } #endif return 0; open_err: bnx2_free_skbs(bp); bnx2_free_irq(bp); bnx2_free_mem(bp); #if !defined(__VMKLNX__) bnx2_del_napi(bp); #endif /* !(defined __VMKLNX__) */ return rc; } static void #if defined(INIT_DELAYED_WORK_DEFERRABLE) || defined(INIT_WORK_NAR) || defined(INIT_DEFERRABLE_WORK) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) bnx2_reset_task(struct work_struct *work) #else bnx2_reset_task(void *data) #endif { #if defined(INIT_DELAYED_WORK_DEFERRABLE) || defined(INIT_WORK_NAR) || defined(INIT_DEFERRABLE_WORK) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) struct bnx2 *bp = container_of(work, struct bnx2, reset_task); #else struct bnx2 *bp = data; #endif int rc; u16 pcicmd; rtnl_lock(); if (!netif_running(bp->dev)) { rtnl_unlock(); return; } bnx2_netif_stop(bp, true); pci_read_config_word(bp->pdev, PCI_COMMAND, &pcicmd); if (!(pcicmd & PCI_COMMAND_MEMORY)) { /* in case PCI block has reset */ pci_restore_state(bp->pdev); pci_save_state(bp->pdev); } rc = bnx2_init_nic(bp, 1); if (rc) { netdev_err(bp->dev, "failed to reset NIC, closing\n"); bnx2_napi_enable(bp); dev_close(bp->dev); #if defined(__VMKLNX__) #if (VMWARE_ESX_DDK_VERSION >= 41000) /* PR 533926 * This is a workaround to sync device status in dev->flags and * dev->gflags. It is needed to avoid PSOD (due to double dev_close) * on reboot. */ bp->dev->gflags &= ~IFF_DEV_IS_OPEN; #endif #endif rtnl_unlock(); return; } atomic_set(&bp->intr_sem, 1); bnx2_netif_start(bp, true); rtnl_unlock(); } #define BNX2_FTQ_ENTRY(ftq) { __stringify(ftq##FTQ_CTL), BNX2_##ftq##FTQ_CTL } static const struct ftq_reg { char *name; u32 off; } ftq_arr[] = { BNX2_FTQ_ENTRY(RV2P_P), BNX2_FTQ_ENTRY(RV2P_T), BNX2_FTQ_ENTRY(RV2P_M), BNX2_FTQ_ENTRY(TBDR_), BNX2_FTQ_ENTRY(TSCH_), BNX2_FTQ_ENTRY(TDMA_), BNX2_FTQ_ENTRY(TXP_), BNX2_FTQ_ENTRY(TPAT_), BNX2_FTQ_ENTRY(TAS_), BNX2_FTQ_ENTRY(RXP_C), BNX2_FTQ_ENTRY(RXP_), BNX2_FTQ_ENTRY(RLUP_), BNX2_FTQ_ENTRY(COM_COMXQ_), BNX2_FTQ_ENTRY(COM_COMTQ_), BNX2_FTQ_ENTRY(COM_COMQ_), BNX2_FTQ_ENTRY(CP_CPQ_), BNX2_FTQ_ENTRY(RDMA_), BNX2_FTQ_ENTRY(CSCH_CH_), BNX2_FTQ_ENTRY(MCP_MCPQ_), }; static void bnx2_dump_ftq(struct bnx2 *bp) { int i; u32 reg, bdidx, cid, valid; struct net_device *dev = bp->dev; netdev_err(dev, "<--- start FTQ dump --->\n"); for (i = 0; i < ARRAY_SIZE(ftq_arr); i++) netdev_err(dev, "%s %08x\n", ftq_arr[i].name, bnx2_reg_rd_ind(bp, ftq_arr[i].off)); netdev_err(dev, "CPU states:\n"); for (reg = BNX2_TXP_CPU_MODE; reg <= BNX2_CP_CPU_MODE; reg += 0x40000) netdev_err(dev, "%06x mode %x state %x evt_mask %x pc %x pc %x instr %x\n", reg, bnx2_reg_rd_ind(bp, reg), bnx2_reg_rd_ind(bp, reg + 4), bnx2_reg_rd_ind(bp, reg + 8), bnx2_reg_rd_ind(bp, reg + 0x1c), bnx2_reg_rd_ind(bp, reg + 0x1c), bnx2_reg_rd_ind(bp, reg + 0x20)); netdev_err(dev, "<--- end FTQ dump --->\n"); netdev_err(dev, "<--- start TBDC dump --->\n"); netdev_err(dev, "TBDC free cnt: %ld\n", BNX2_RD(bp, BNX2_TBDC_STATUS) & BNX2_TBDC_STATUS_FREE_CNT); netdev_err(dev, "LINE CID BIDX CMD VALIDS\n"); for (i = 0; i < 0x20; i++) { int j = 0; BNX2_WR(bp, BNX2_TBDC_BD_ADDR, i); BNX2_WR(bp, BNX2_TBDC_CAM_OPCODE, BNX2_TBDC_CAM_OPCODE_OPCODE_CAM_READ); BNX2_WR(bp, BNX2_TBDC_COMMAND, BNX2_TBDC_COMMAND_CMD_REG_ARB); while ((BNX2_RD(bp, BNX2_TBDC_COMMAND) & BNX2_TBDC_COMMAND_CMD_REG_ARB) && j < 100) j++; cid = BNX2_RD(bp, BNX2_TBDC_CID); bdidx = BNX2_RD(bp, BNX2_TBDC_BIDX); valid = BNX2_RD(bp, BNX2_TBDC_CAM_OPCODE); netdev_err(dev, "%02x %06x %04lx %02x [%x]\n", i, cid, bdidx & BNX2_TBDC_BDIDX_BDIDX, bdidx >> 24, (valid >> 8) & 0x0ff); } netdev_err(dev, "<--- end TBDC dump --->\n"); } static void bnx2_dump_state(struct bnx2 *bp) { struct net_device *dev = bp->dev; u32 val1, val2; pci_read_config_dword(bp->pdev, PCI_COMMAND, &val1); netdev_err(dev, "DEBUG: intr_sem[%x] PCI_CMD[%08x]\n", atomic_read(&bp->intr_sem), val1); pci_read_config_dword(bp->pdev, bp->pm_cap + PCI_PM_CTRL, &val1); pci_read_config_dword(bp->pdev, BNX2_PCICFG_MISC_CONFIG, &val2); netdev_err(dev, "DEBUG: PCI_PM[%08x] PCI_MISC_CFG[%08x]\n", val1, val2); netdev_err(dev, "DEBUG: EMAC_TX_STATUS[%08x] EMAC_RX_STATUS[%08x]\n", BNX2_RD(bp, BNX2_EMAC_TX_STATUS), BNX2_RD(bp, BNX2_EMAC_RX_STATUS)); netdev_err(dev, "DEBUG: RPM_MGMT_PKT_CTRL[%08x]\n", BNX2_RD(bp, BNX2_RPM_MGMT_PKT_CTRL)); netdev_err(dev, "DEBUG: HC_STATS_INTERRUPT_STATUS[%08x]\n", BNX2_RD(bp, BNX2_HC_STATS_INTERRUPT_STATUS)); if (bp->flags & BNX2_FLAG_USING_MSIX) { int i; netdev_err(dev, "DEBUG: PBA[%08x]\n", BNX2_RD(bp, BNX2_PCI_GRC_WINDOW3_BASE)); netdev_err(dev, "DEBUG: MSIX table:\n"); val1 = BNX2_PCI_GRC_WINDOW2_BASE; for (i = 0; i < bp->irq_nvecs; i++) { netdev_err(dev, "DEBUG: [%d]: %08x %08x %08x %08x\n", i, BNX2_RD(bp, val1), BNX2_RD(bp, val1 + 4), BNX2_RD(bp, val1 + 8), BNX2_RD(bp, val1 + 12)); val1 += 16; } } } static void bnx2_tx_timeout(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); bnx2_dump_ftq(bp); bnx2_dump_state(bp); bnx2_dump_mcp_state(bp); #if defined(__VMKLNX__) if (psod_on_tx_timeout) { msleep(100); BUG_ON(1); return; } #endif if (stop_on_tx_timeout) { netdev_err(dev, "prevent chip reset during tx timeout\n"); return; } /* This allows the netif to be shutdown gracefully before resetting */ #if (LINUX_VERSION_CODE >= 0x20600) schedule_work(&bp->reset_task); #else schedule_task(&bp->reset_task); #endif } #if defined(BCM_VLAN) && !defined(NEW_VLAN) /* Called with rtnl_lock */ static void bnx2_vlan_rx_register(struct net_device *dev, struct vlan_group *vlgrp) { struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif if (netif_running(dev)) bnx2_netif_stop(bp, false); bp->vlgrp = vlgrp; if (netif_running(dev)) { bnx2_set_rx_mode(dev); if (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN) bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_KEEP_VLAN_UPDATE, 0, 1); bnx2_netif_start(bp, false); } #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif } #if (LINUX_VERSION_CODE < 0x20616) /* Called with rtnl_lock */ static void bnx2_vlan_rx_kill_vid(struct net_device *dev, uint16_t vid) { struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif if (netif_running(dev)) bnx2_netif_stop(bp, false); vlan_group_set_device(bp->vlgrp, vid, NULL); if (!netif_running(dev)) { #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif return; } bnx2_set_rx_mode(dev); if (bp->flags & BNX2_FLAG_CAN_KEEP_VLAN) bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_KEEP_VLAN_UPDATE, 0, 1); bnx2_netif_start(bp, false); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif } #endif #endif /* Called with netif_tx_lock. * bnx2_tx_int() runs without netif_tx_lock unless it needs to call * netif_wake_queue(). */ static netdev_tx_t bnx2_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); dma_addr_t mapping; struct bnx2_tx_bd *txbd; struct bnx2_sw_tx_bd *tx_buf; u32 len, vlan_tag_flags, last_frag, mss; u16 prod, ring_prod; int i; #ifndef BCM_HAVE_MULTI_QUEUE struct bnx2_napi *bnapi = &bp->bnx2_napi[0]; struct bnx2_tx_ring_info *txr = &bnapi->tx_ring; #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* Drop the packet if the queue has been stopped */ if (unlikely(netif_queue_stopped(dev))) { dev_kfree_skb(skb); return NETDEV_TX_OK; } #endif #else struct bnx2_napi *bnapi; struct bnx2_tx_ring_info *txr; struct netdev_queue *txq; /* Determine which tx ring we will be placed on */ i = skb_get_queue_mapping(skb); bnapi = &bp->bnx2_napi[i]; txr = &bnapi->tx_ring; txq = netdev_get_tx_queue(dev, i); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION < 50000) /* Drop the packet if the queue has been stopped */ if (unlikely(netif_tx_queue_stopped(txq))) { dev_kfree_skb(skb); return NETDEV_TX_OK; } #endif #endif if (unlikely(bnx2_tx_avail(bp, txr) < (skb_shinfo(skb)->nr_frags + 1))) { #ifndef BCM_HAVE_MULTI_QUEUE netif_stop_queue(dev); #else netif_tx_stop_queue(txq); #endif netdev_err(dev, "BUG! Tx ring full when queue awake!\n"); return NETDEV_TX_BUSY; } len = skb_headlen(skb); prod = txr->tx_prod; ring_prod = BNX2_TX_RING_IDX(prod); vlan_tag_flags = 0; if (skb->ip_summed == CHECKSUM_PARTIAL) { vlan_tag_flags |= TX_BD_FLAGS_TCP_UDP_CKSUM; } #ifdef BCM_VLAN #ifdef NEW_VLAN if (vlan_tx_tag_present(skb)) { #else if (bp->vlgrp && vlan_tx_tag_present(skb)) { #endif vlan_tag_flags |= (TX_BD_FLAGS_VLAN_TAG | (vlan_tx_tag_get(skb) << 16)); } #endif #ifdef BCM_TSO if ((mss = skb_shinfo(skb)->gso_size)) { u32 tcp_opt_len; struct iphdr *iph; tcp_opt_len = tcp_optlen(skb); if (skb_transport_offset(skb) + tcp_opt_len + sizeof(struct tcphdr) + mss >= skb->len) goto abort_tso; vlan_tag_flags |= TX_BD_FLAGS_SW_LSO; #ifndef BCM_NO_TSO6 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) { u32 tcp_off = skb_transport_offset(skb) - sizeof(struct ipv6hdr) - ETH_HLEN; vlan_tag_flags |= ((tcp_opt_len >> 2) << 8) | TX_BD_FLAGS_SW_FLAGS; if (likely(tcp_off == 0)) vlan_tag_flags &= ~TX_BD_FLAGS_TCP6_OFF0_MSK; else { tcp_off >>= 3; vlan_tag_flags |= ((tcp_off & 0x3) << TX_BD_FLAGS_TCP6_OFF0_SHL) | ((tcp_off & 0x10) << TX_BD_FLAGS_TCP6_OFF4_SHL); mss |= (tcp_off & 0xc) << TX_BD_TCP6_OFF2_SHL; } } else #endif { iph = ip_hdr(skb); if (tcp_opt_len || (iph->ihl > 5)) { vlan_tag_flags |= ((iph->ihl - 5) + (tcp_opt_len >> 2)) << 8; } } } else abort_tso: #endif { mss = 0; } #if (LINUX_VERSION_CODE >= 0x02061b) mapping = dma_map_single(&bp->pdev->dev, skb->data, len, PCI_DMA_TODEVICE); if (dma_mapping_error(&bp->pdev->dev, mapping)) { #else mapping = pci_map_single(bp->pdev, skb->data, len, PCI_DMA_TODEVICE); if (pci_dma_mapping_error(mapping)) { #endif dev_kfree_skb(skb); return NETDEV_TX_OK; } tx_buf = &txr->tx_buf_ring[ring_prod]; tx_buf->skb = skb; dma_unmap_addr_set(tx_buf, mapping, mapping); txbd = &txr->tx_desc_ring[ring_prod]; txbd->tx_bd_haddr_hi = (u64) mapping >> 32; txbd->tx_bd_haddr_lo = (u64) mapping & 0xffffffff; txbd->tx_bd_mss_nbytes = len | (mss << 16); txbd->tx_bd_vlan_tag_flags = vlan_tag_flags | TX_BD_FLAGS_START; last_frag = skb_shinfo(skb)->nr_frags; tx_buf->nr_frags = last_frag; tx_buf->is_gso = skb_is_gso(skb); for (i = 0; i < last_frag; i++) { const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; prod = BNX2_NEXT_TX_BD(prod); ring_prod = BNX2_TX_RING_IDX(prod); txbd = &txr->tx_desc_ring[ring_prod]; len = skb_frag_size(frag); mapping = skb_frag_dma_map(&bp->pdev->dev, frag, 0, len, DMA_TO_DEVICE); #if (LINUX_VERSION_CODE >= 0x02061b) if (dma_mapping_error(&bp->pdev->dev, mapping)) #else if (pci_dma_mapping_error(mapping)) #endif goto dma_error; dma_unmap_addr_set(&txr->tx_buf_ring[ring_prod], mapping, mapping); txbd->tx_bd_haddr_hi = (u64) mapping >> 32; txbd->tx_bd_haddr_lo = (u64) mapping & 0xffffffff; txbd->tx_bd_mss_nbytes = len | (mss << 16); txbd->tx_bd_vlan_tag_flags = vlan_tag_flags; } txbd->tx_bd_vlan_tag_flags |= TX_BD_FLAGS_END; /* Sync BD data before updating TX mailbox */ wmb(); prod = BNX2_NEXT_TX_BD(prod); txr->tx_prod_bseq += skb->len; BNX2_WR16(bp, txr->tx_bidx_addr, prod); BNX2_WR(bp, txr->tx_bseq_addr, txr->tx_prod_bseq); mmiowb(); txr->tx_prod = prod; #if (LINUX_VERSION_CODE <= 0x2061e) || defined(__VMKLNX__) dev->trans_start = jiffies; #endif #if defined(BNX2_ENABLE_NETQUEUE) bnapi->tx_packets_sent++; wmb(); #endif if (unlikely(bnx2_tx_avail(bp, txr) <= MAX_SKB_FRAGS)) { #ifndef BCM_HAVE_MULTI_QUEUE netif_stop_queue(dev); #else netif_tx_stop_queue(txq); #endif /* netif_tx_stop_queue() must be done before checking * tx index in bnx2_tx_avail() below, because in * bnx2_tx_int(), we update tx index before checking for * netif_tx_queue_stopped(). */ smp_mb(); if (bnx2_tx_avail(bp, txr) > bp->tx_wake_thresh) #ifndef BCM_HAVE_MULTI_QUEUE netif_wake_queue(dev); #else netif_tx_wake_queue(txq); #endif } return NETDEV_TX_OK; dma_error: /* save value of frag that failed */ last_frag = i; /* start back at beginning and unmap skb */ prod = txr->tx_prod; ring_prod = BNX2_TX_RING_IDX(prod); tx_buf = &txr->tx_buf_ring[ring_prod]; tx_buf->skb = NULL; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_single(&bp->pdev->dev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #else pci_unmap_single(bp->pdev, dma_unmap_addr(tx_buf, mapping), skb_headlen(skb), PCI_DMA_TODEVICE); #endif /* unmap remaining mapped pages */ for (i = 0; i < last_frag; i++) { prod = BNX2_NEXT_TX_BD(prod); ring_prod = BNX2_TX_RING_IDX(prod); tx_buf = &txr->tx_buf_ring[ring_prod]; #if (LINUX_VERSION_CODE >= 0x02061b) dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(tx_buf, mapping), #else pci_unmap_page(bp->pdev, dma_unmap_addr(tx_buf, mapping), #endif skb_frag_size(&skb_shinfo(skb)->frags[i]), PCI_DMA_TODEVICE); } dev_kfree_skb(skb); return NETDEV_TX_OK; } /* Called with rtnl_lock */ static int bnx2_close(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) bnx2_cnic_stop(bp); #endif /* defined(__VMKLNX__) */ bnx2_disable_int_sync(bp); #ifdef BNX2_NEW_NAPI bnx2_napi_disable(bp); #endif netif_tx_disable(bp->dev); #if defined(BNX2_ENABLE_NETQUEUE) bnx2_close_netqueue(bp); #endif /* BNX2_ENABLE_NETQUEUE */ del_timer_sync(&bp->timer); #if defined(BNX2_ENABLE_NETQUEUE) if (bp->reset_failed == 0) bnx2_shutdown_chip(bp); #else /* BNX2_ENABLE_NETQUEUE */ bnx2_shutdown_chip(bp); #endif /* BNX2_ENABLE_NETQUEUE */ bnx2_free_irq(bp); bnx2_free_skbs(bp); bnx2_free_mem(bp); #if !defined(__VMKLNX__) bnx2_del_napi(bp); #endif bp->link_up = 0; netif_carrier_off(bp->dev); return 0; } static void bnx2_save_stats(struct bnx2 *bp) { u32 *hw_stats = (u32 *) bp->stats_blk; u32 *temp_stats = (u32 *) bp->temp_stats_blk; int i; /* The 1st 10 counters are 64-bit counters */ for (i = 0; i < 20; i += 2) { u32 hi; u64 lo; hi = temp_stats[i] + hw_stats[i]; lo = (u64) temp_stats[i + 1] + (u64) hw_stats[i + 1]; if (lo > 0xffffffff) hi++; temp_stats[i] = hi; temp_stats[i + 1] = lo & 0xffffffff; } for ( ; i < sizeof(struct statistics_block) / 4; i++) temp_stats[i] += hw_stats[i]; } #define GET_64BIT_NET_STATS64(ctr) \ (unsigned long) ((unsigned long) (ctr##_hi) << 32) + \ (unsigned long) (ctr##_lo) #define GET_64BIT_NET_STATS32(ctr) \ (ctr##_lo) #if (BITS_PER_LONG == 64) #define GET_64BIT_NET_STATS(ctr) \ GET_64BIT_NET_STATS64(bp->stats_blk->ctr) + \ GET_64BIT_NET_STATS64(bp->temp_stats_blk->ctr) #else #define GET_64BIT_NET_STATS(ctr) \ GET_64BIT_NET_STATS32(bp->stats_blk->ctr) + \ GET_64BIT_NET_STATS32(bp->temp_stats_blk->ctr) #endif #define GET_32BIT_NET_STATS(ctr) \ (unsigned long) (bp->stats_blk->ctr + \ bp->temp_stats_blk->ctr) static struct net_device_stats * bnx2_get_stats(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); struct net_device_stats *net_stats = &bp->net_stats; if (bp->stats_blk == NULL) return net_stats; net_stats->rx_packets = GET_64BIT_NET_STATS(stat_IfHCInUcastPkts) + GET_64BIT_NET_STATS(stat_IfHCInMulticastPkts) + GET_64BIT_NET_STATS(stat_IfHCInBroadcastPkts); net_stats->tx_packets = GET_64BIT_NET_STATS(stat_IfHCOutUcastPkts) + GET_64BIT_NET_STATS(stat_IfHCOutMulticastPkts) + GET_64BIT_NET_STATS(stat_IfHCOutBroadcastPkts); net_stats->rx_bytes = GET_64BIT_NET_STATS(stat_IfHCInOctets); net_stats->tx_bytes = GET_64BIT_NET_STATS(stat_IfHCOutOctets); net_stats->multicast = GET_64BIT_NET_STATS(stat_IfHCInMulticastPkts); net_stats->collisions = GET_32BIT_NET_STATS(stat_EtherStatsCollisions); net_stats->rx_length_errors = GET_32BIT_NET_STATS(stat_EtherStatsUndersizePkts) + GET_32BIT_NET_STATS(stat_EtherStatsOverrsizePkts); net_stats->rx_over_errors = GET_32BIT_NET_STATS(stat_IfInFTQDiscards) + GET_32BIT_NET_STATS(stat_IfInMBUFDiscards); net_stats->rx_frame_errors = GET_32BIT_NET_STATS(stat_Dot3StatsAlignmentErrors); net_stats->rx_crc_errors = GET_32BIT_NET_STATS(stat_Dot3StatsFCSErrors); net_stats->rx_errors = net_stats->rx_length_errors + net_stats->rx_over_errors + net_stats->rx_frame_errors + net_stats->rx_crc_errors; net_stats->tx_aborted_errors = GET_32BIT_NET_STATS(stat_Dot3StatsExcessiveCollisions) + GET_32BIT_NET_STATS(stat_Dot3StatsLateCollisions); if ((BNX2_CHIP(bp) == BNX2_CHIP_5706) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0)) net_stats->tx_carrier_errors = 0; else { net_stats->tx_carrier_errors = GET_32BIT_NET_STATS(stat_Dot3StatsCarrierSenseErrors); } net_stats->tx_errors = GET_32BIT_NET_STATS(stat_emac_tx_stat_dot3statsinternalmactransmiterrors) + net_stats->tx_aborted_errors + net_stats->tx_carrier_errors; net_stats->rx_missed_errors = GET_32BIT_NET_STATS(stat_IfInFTQDiscards) + GET_32BIT_NET_STATS(stat_IfInMBUFDiscards) + GET_32BIT_NET_STATS(stat_FwRxDrop); return net_stats; } /* All ethtool functions called with rtnl_lock */ static int bnx2_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct bnx2 *bp = netdev_priv(dev); int support_serdes = 0, support_copper = 0; cmd->supported = SUPPORTED_Autoneg; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { support_serdes = 1; support_copper = 1; } else if (bp->phy_port == PORT_FIBRE) support_serdes = 1; else support_copper = 1; if (support_serdes) { cmd->supported |= SUPPORTED_1000baseT_Full | SUPPORTED_FIBRE; if (bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE) cmd->supported |= SUPPORTED_2500baseX_Full; } if (support_copper) { cmd->supported |= SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_1000baseT_Full | SUPPORTED_TP; } spin_lock_bh(&bp->phy_lock); cmd->port = bp->phy_port; cmd->advertising = bp->advertising; if (bp->autoneg & AUTONEG_SPEED) { cmd->autoneg = AUTONEG_ENABLE; } else { cmd->autoneg = AUTONEG_DISABLE; } if (netif_carrier_ok(dev)) { ethtool_cmd_speed_set(cmd, bp->line_speed); cmd->duplex = bp->duplex; } else { ethtool_cmd_speed_set(cmd, -1); cmd->duplex = -1; } spin_unlock_bh(&bp->phy_lock); cmd->transceiver = XCVR_INTERNAL; cmd->phy_address = bp->phy_addr; return 0; } static int bnx2_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct bnx2 *bp = netdev_priv(dev); u8 autoneg = bp->autoneg; u8 req_duplex = bp->req_duplex; u16 req_line_speed = bp->req_line_speed; u32 advertising = bp->advertising; int err = -EINVAL; spin_lock_bh(&bp->phy_lock); if (cmd->port != PORT_TP && cmd->port != PORT_FIBRE) goto err_out_unlock; if (cmd->port != bp->phy_port && !(bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP)) goto err_out_unlock; /* If device is down, we can store the settings only if the user * is setting the currently active port. */ if (!netif_running(dev) && cmd->port != bp->phy_port) goto err_out_unlock; if (cmd->autoneg == AUTONEG_ENABLE) { autoneg |= AUTONEG_SPEED; advertising = cmd->advertising; if (cmd->port == PORT_TP) { advertising &= ETHTOOL_ALL_COPPER_SPEED; if (!advertising) advertising = ETHTOOL_ALL_COPPER_SPEED; } else { advertising &= ETHTOOL_ALL_FIBRE_SPEED; if (!advertising) advertising = ETHTOOL_ALL_FIBRE_SPEED; } advertising |= ADVERTISED_Autoneg; } else { if (cmd->port == PORT_FIBRE) { if ((cmd->speed != SPEED_1000 && cmd->speed != SPEED_2500) || (cmd->duplex != DUPLEX_FULL)) goto err_out_unlock; if (cmd->speed == SPEED_2500 && !(bp->phy_flags & BNX2_PHY_FLAG_2_5G_CAPABLE)) goto err_out_unlock; } else if (cmd->speed == SPEED_1000 || cmd->speed == SPEED_2500) goto err_out_unlock; autoneg &= ~AUTONEG_SPEED; req_line_speed = cmd->speed; req_duplex = cmd->duplex; advertising = 0; } bp->autoneg = autoneg; bp->advertising = advertising; bp->req_line_speed = req_line_speed; bp->req_duplex = req_duplex; err = 0; /* If device is down, the new settings will be picked up when it is * brought up. */ if (netif_running(dev)) err = bnx2_setup_phy(bp, cmd->port); err_out_unlock: spin_unlock_bh(&bp->phy_lock); return err; } static void bnx2_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct bnx2 *bp = netdev_priv(dev); #if !defined(__VMKLNX__) strcpy(info->driver, DRV_MODULE_NAME); strcpy(info->version, DRV_MODULE_VERSION); strcpy(info->bus_info, pci_name(bp->pdev)); strcpy(info->fw_version, bp->fw_version); #else /* defined (__VMKLNX__) */ strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version)); strlcpy(info->bus_info, pci_name(bp->pdev), sizeof(info->bus_info)); strlcpy(info->fw_version, bp->fw_version, sizeof(info->fw_version)); #endif /* !defined(__VMKLNX__) */ #if defined(VMWARE_ESX_DDK_VERSION) && \ (VMWARE_ESX_DDK_VERSION >= 35000) && (VMWARE_ESX_DDK_VERSION < 40000) info->eedump_len = bnx2_get_eeprom_len(dev); #endif } #define BNX2_REGDUMP_LEN (32 * 1024) static int bnx2_get_regs_len(struct net_device *dev) { return BNX2_REGDUMP_LEN; } static void bnx2_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *_p) { u32 *p = _p, i, offset; u8 *orig_p = _p; struct bnx2 *bp = netdev_priv(dev); static const u32 reg_boundaries[] = { 0x0000, 0x0098, 0x0400, 0x045c, 0x0800, 0x0880, 0x0c00, 0x0c10, 0x0c30, 0x0d08, 0x1000, 0x101c, 0x1040, 0x1048, 0x1080, 0x10a4, 0x1400, 0x1490, 0x1498, 0x14f0, 0x1500, 0x155c, 0x1580, 0x15dc, 0x1600, 0x1658, 0x1680, 0x16d8, 0x1800, 0x1820, 0x1840, 0x1854, 0x1880, 0x1894, 0x1900, 0x1984, 0x1c00, 0x1c0c, 0x1c40, 0x1c54, 0x1c80, 0x1c94, 0x1d00, 0x1d84, 0x2000, 0x2030, 0x23c0, 0x2400, 0x2800, 0x2820, 0x2830, 0x2850, 0x2b40, 0x2c10, 0x2fc0, 0x3058, 0x3c00, 0x3c94, 0x4000, 0x4010, 0x4080, 0x4090, 0x43c0, 0x4458, 0x4c00, 0x4c18, 0x4c40, 0x4c54, 0x4fc0, 0x5010, 0x53c0, 0x5444, 0x5c00, 0x5c18, 0x5c80, 0x5c90, 0x5fc0, 0x6000, 0x6400, 0x6428, 0x6800, 0x6848, 0x684c, 0x6860, 0x6888, 0x6910, 0x8000 }; regs->version = 0; memset(p, 0, BNX2_REGDUMP_LEN); if (!netif_running(bp->dev)) return; i = 0; offset = reg_boundaries[0]; p += offset; while (offset < BNX2_REGDUMP_LEN) { *p++ = BNX2_RD(bp, offset); offset += 4; if (offset == reg_boundaries[i + 1]) { offset = reg_boundaries[i + 2]; p = (u32 *) (orig_p + offset); i += 2; } } } static void bnx2_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct bnx2 *bp = netdev_priv(dev); if (bp->flags & BNX2_FLAG_NO_WOL) { wol->supported = 0; wol->wolopts = 0; } else { wol->supported = WAKE_MAGIC; if (bp->wol) wol->wolopts = WAKE_MAGIC; else wol->wolopts = 0; } memset(&wol->sopass, 0, sizeof(wol->sopass)); } static int bnx2_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { struct bnx2 *bp = netdev_priv(dev); if (wol->wolopts & ~WAKE_MAGIC) return -EINVAL; if (wol->wolopts & WAKE_MAGIC) { if (bp->flags & BNX2_FLAG_NO_WOL) return -EINVAL; bp->wol = 1; } else { bp->wol = 0; } device_set_wakeup_enable(&bp->pdev->dev, bp->wol); return 0; } static u32 bnx2_get_msglevel(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); return bp->msg_enable; } static void bnx2_set_msglevel(struct net_device *dev, u32 value) { struct bnx2 *bp = netdev_priv(dev); bp->msg_enable = value; } static int bnx2_nway_reset(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); u32 bmcr; if (!netif_running(dev)) return -EAGAIN; if (!(bp->autoneg & AUTONEG_SPEED)) { return -EINVAL; } spin_lock_bh(&bp->phy_lock); if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) { int rc; rc = bnx2_setup_remote_phy(bp, bp->phy_port); spin_unlock_bh(&bp->phy_lock); return rc; } /* Force a link down visible on the other side */ if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { bnx2_write_phy(bp, bp->mii_bmcr, BMCR_LOOPBACK); spin_unlock_bh(&bp->phy_lock); bnx2_msleep(20); spin_lock_bh(&bp->phy_lock); bp->current_interval = BNX2_SERDES_AN_TIMEOUT; bp->serdes_an_pending = 1; mod_timer(&bp->timer, jiffies + bp->current_interval); } bnx2_read_phy(bp, bp->mii_bmcr, &bmcr); bmcr &= ~BMCR_LOOPBACK; bnx2_write_phy(bp, bp->mii_bmcr, bmcr | BMCR_ANRESTART | BMCR_ANENABLE); spin_unlock_bh(&bp->phy_lock); return 0; } static u32 bnx2_get_link(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); return bp->link_up; } #if (LINUX_VERSION_CODE >= 0x20418) || \ (defined(VMWARE_ESX_DDK_VERSION) && \ ((VMWARE_ESX_DDK_VERSION >= 35000) && (VMWARE_ESX_DDK_VERSION < 40000))) static int bnx2_get_eeprom_len(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); if (bp->flash_info == NULL) return 0; return (int) bp->flash_size; } #endif #ifdef ETHTOOL_GEEPROM static int bnx2_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *eebuf) { struct bnx2 *bp = netdev_priv(dev); int rc; /* parameters already validated in ethtool_get_eeprom */ rc = bnx2_nvram_read(bp, eeprom->offset, eebuf, eeprom->len); return rc; } #endif #ifdef ETHTOOL_SEEPROM static int bnx2_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *eebuf) { struct bnx2 *bp = netdev_priv(dev); int rc; /* parameters already validated in ethtool_set_eeprom */ rc = bnx2_nvram_write(bp, eeprom->offset, eebuf, eeprom->len); return rc; } #endif static int bnx2_get_coalesce(struct net_device *dev, struct ethtool_coalesce *coal) { struct bnx2 *bp = netdev_priv(dev); memset(coal, 0, sizeof(struct ethtool_coalesce)); coal->rx_coalesce_usecs = bp->rx_ticks; coal->rx_max_coalesced_frames = bp->rx_quick_cons_trip; coal->rx_coalesce_usecs_irq = bp->rx_ticks_int; coal->rx_max_coalesced_frames_irq = bp->rx_quick_cons_trip_int; coal->tx_coalesce_usecs = bp->tx_ticks; coal->tx_max_coalesced_frames = bp->tx_quick_cons_trip; coal->tx_coalesce_usecs_irq = bp->tx_ticks_int; coal->tx_max_coalesced_frames_irq = bp->tx_quick_cons_trip_int; coal->stats_block_coalesce_usecs = bp->stats_ticks; return 0; } static int bnx2_set_coalesce(struct net_device *dev, struct ethtool_coalesce *coal) { struct bnx2 *bp = netdev_priv(dev); uint32_t i; bp->rx_ticks = (u16) coal->rx_coalesce_usecs; if (bp->rx_ticks > 0x3ff) bp->rx_ticks = 0x3ff; bp->rx_quick_cons_trip = (u16) coal->rx_max_coalesced_frames; if (bp->rx_quick_cons_trip > 0xff) bp->rx_quick_cons_trip = 0xff; bp->rx_ticks_int = (u16) coal->rx_coalesce_usecs_irq; if (bp->rx_ticks_int > 0x3ff) bp->rx_ticks_int = 0x3ff; bp->rx_quick_cons_trip_int = (u16) coal->rx_max_coalesced_frames_irq; if (bp->rx_quick_cons_trip_int > 0xff) bp->rx_quick_cons_trip_int = 0xff; bp->tx_ticks = (u16) coal->tx_coalesce_usecs; if (bp->tx_ticks > 0x3ff) bp->tx_ticks = 0x3ff; bp->tx_quick_cons_trip = (u16) coal->tx_max_coalesced_frames; if (bp->tx_quick_cons_trip > 0xff) bp->tx_quick_cons_trip = 0xff; bp->tx_ticks_int = (u16) coal->tx_coalesce_usecs_irq; if (bp->tx_ticks_int > 0x3ff) bp->tx_ticks_int = 0x3ff; bp->tx_quick_cons_trip_int = (u16) coal->tx_max_coalesced_frames_irq; if (bp->tx_quick_cons_trip_int > 0xff) bp->tx_quick_cons_trip_int = 0xff; bp->stats_ticks = coal->stats_block_coalesce_usecs; if (bp->flags & BNX2_FLAG_BROKEN_STATS) { if (bp->stats_ticks != 0 && bp->stats_ticks != USEC_PER_SEC) bp->stats_ticks = USEC_PER_SEC; } if (bp->stats_ticks > BNX2_HC_STATS_TICKS_HC_STAT_TICKS) bp->stats_ticks = BNX2_HC_STATS_TICKS_HC_STAT_TICKS; bp->stats_ticks &= BNX2_HC_STATS_TICKS_HC_STAT_TICKS; if (netif_running(bp->dev)) { #if (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000)) BNX2_WR(bp, BNX2_HC_TX_QUICK_CONS_TRIP, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_RX_QUICK_CONS_TRIP, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, BNX2_HC_TX_TICKS, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, BNX2_HC_RX_TICKS, (bp->rx_ticks_int << 16) | bp->rx_ticks); if (bp->flags & BNX2_FLAG_BROKEN_STATS) BNX2_WR(bp, BNX2_HC_STATS_TICKS, 0); else BNX2_WR(bp, BNX2_HC_STATS_TICKS, bp->stats_ticks); if (bp->rx_ticks < 25) bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 1); else bnx2_reg_wr_ind(bp, BNX2_FW_RX_LOW_LATENCY, 0); for (i = 1; i < bp->irq_nvecs; i++) { u32 base = ((i - 1) * BNX2_HC_SB_CONFIG_SIZE) + BNX2_HC_SB_CONFIG_1; BNX2_WR(bp, base, BNX2_HC_SB_CONFIG_1_TX_TMR_MODE | BNX2_HC_SB_CONFIG_1_RX_TMR_MODE | BNX2_HC_SB_CONFIG_1_ONE_SHOT); BNX2_WR(bp, base + BNX2_HC_TX_QUICK_CONS_TRIP_OFF, (bp->tx_quick_cons_trip_int << 16) | bp->tx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_TX_TICKS_OFF, (bp->tx_ticks_int << 16) | bp->tx_ticks); BNX2_WR(bp, base + BNX2_HC_RX_QUICK_CONS_TRIP_OFF, (bp->rx_quick_cons_trip_int << 16) | bp->rx_quick_cons_trip); BNX2_WR(bp, base + BNX2_HC_RX_TICKS_OFF, (bp->rx_ticks_int << 16) | bp->rx_ticks); } #else bnx2_netif_stop(bp, true); bnx2_init_nic(bp, 0); bnx2_netif_start(bp, true); #endif /* defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) */ } return 0; } static void bnx2_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct bnx2 *bp = netdev_priv(dev); ering->rx_max_pending = BNX2_MAX_TOTAL_RX_DESC_CNT; ering->rx_jumbo_max_pending = BNX2_MAX_TOTAL_RX_PG_DESC_CNT; ering->rx_pending = bp->rx_ring_size; ering->rx_jumbo_pending = bp->rx_pg_ring_size; ering->tx_max_pending = BNX2_MAX_TX_DESC_CNT; ering->tx_pending = bp->tx_ring_size; } static int bnx2_change_ring_size(struct bnx2 *bp, u32 rx, u32 tx, bool reset_irq) { int rc = 0; #if defined(__VMKLNX__) if(bp->reset_failed) { netdev_err(bp->dev, "Previous error detected preventing MTU " "change\n"); return -EIO; } #endif /* defined(__VMKLNX__) */ if (netif_running(bp->dev)) { /* Reset will erase chipset stats; save them */ bnx2_save_stats(bp); bnx2_netif_stop(bp, true); #if defined(__VMKLNX__) rc = bnx2_reset_chip(bp, BNX2_DRV_MSG_CODE_RESET); /* Did the chip reset fail ? */ if (rc != 0) { netdev_err(bp->dev, "chip reset failed during MTU " "change\n"); bp->reset_failed = 1; goto error; } bnx2_free_irq(bp); #else /* !defined(__VMKLNX__) */ bnx2_reset_chip(bp, BNX2_DRV_MSG_CODE_RESET); if (reset_irq) { bnx2_free_irq(bp); bnx2_del_napi(bp); } else { __bnx2_free_irq(bp); } #endif /* defined(__VMKLNX__) */ bnx2_free_skbs(bp); bnx2_free_mem(bp); } bnx2_set_rx_ring_size(bp, rx); bp->tx_ring_size = tx; if (netif_running(bp->dev)) { if (reset_irq) { rc = bnx2_setup_int_mode(bp, disable_msi); bnx2_init_napi(bp); } if (!rc) rc = bnx2_alloc_mem(bp); #if defined(BNX2_ENABLE_NETQUEUE) if (rc) { netdev_err(bp->dev, "failed alloc mem during MTU " "change\n"); goto error; } rc = bnx2_request_irq(bp); if (rc) { netdev_err(bp->dev, "failed request irq during MTU " "change %d\n", rc); goto error; } rc = bnx2_init_nic(bp, 0); if (rc) { netdev_err(bp->dev, "failed init nic during MTU " "change\n"); goto error; } #else /* !defined(BNX2_ENABLE_NETQUEUE) */ if (!rc) rc = bnx2_request_irq(bp); if (!rc) rc = bnx2_init_nic(bp, 0); if (rc) { bnx2_napi_enable(bp); dev_close(bp->dev); #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION == 41000) /* PR 533926 * This is a workaround to sync device status in dev->flags and * dev->gflags. It is needed to avoid PSOD (due to double dev_close) * on reboot. In ESX5.0, the return value of this function will be * checked by NICSetMTU, where gflags will be updated appropriately. */ bp->dev->gflags &= ~IFF_DEV_IS_OPEN; #endif return rc; } #endif /* defined(BNX2_ENABLE_NETQUEUE) */ #ifdef BCM_CNIC mutex_lock(&bp->cnic_lock); /* Let cnic know about the new status block. */ if (bp->cnic_eth_dev.drv_state & CNIC_DRV_STATE_REGD) bnx2_setup_cnic_irq_info(bp); mutex_unlock(&bp->cnic_lock); #endif bnx2_netif_start(bp, true); } return 0; #if defined(__VMKLNX__) error: netif_carrier_off(bp->dev); return rc; #endif /* defined(__VMKLNX__) */ } static int bnx2_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ering) { struct bnx2 *bp = netdev_priv(dev); int rc; if ((ering->rx_pending > BNX2_MAX_TOTAL_RX_DESC_CNT) || (ering->tx_pending > BNX2_MAX_TX_DESC_CNT) || (ering->tx_pending <= MAX_SKB_FRAGS)) { return -EINVAL; } rc = bnx2_change_ring_size(bp, ering->rx_pending, ering->tx_pending, false); return rc; } static void bnx2_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct bnx2 *bp = netdev_priv(dev); epause->autoneg = ((bp->autoneg & AUTONEG_FLOW_CTRL) != 0); epause->rx_pause = ((bp->flow_ctrl & FLOW_CTRL_RX) != 0); epause->tx_pause = ((bp->flow_ctrl & FLOW_CTRL_TX) != 0); } static int bnx2_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause) { struct bnx2 *bp = netdev_priv(dev); bp->req_flow_ctrl = 0; if (epause->rx_pause) bp->req_flow_ctrl |= FLOW_CTRL_RX; if (epause->tx_pause) bp->req_flow_ctrl |= FLOW_CTRL_TX; if (epause->autoneg) { bp->autoneg |= AUTONEG_FLOW_CTRL; } else { bp->autoneg &= ~AUTONEG_FLOW_CTRL; } if (netif_running(dev)) { spin_lock_bh(&bp->phy_lock); bnx2_setup_phy(bp, bp->phy_port); spin_unlock_bh(&bp->phy_lock); } return 0; } #ifndef NEW_ETHTOOL static u32 bnx2_get_rx_csum(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); return bp->rx_csum; } static int bnx2_set_rx_csum(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); bp->rx_csum = data; return 0; } #ifdef BCM_TSO static int bnx2_set_tso(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); if (data) { dev->features |= NETIF_F_TSO | NETIF_F_TSO_ECN; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) dev->features |= NETIF_F_TSO6; } else dev->features &= ~(NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN); return 0; } #endif #endif static struct { char string[ETH_GSTRING_LEN]; } bnx2_stats_str_arr[] = { { "rx_bytes" }, { "rx_error_bytes" }, { "tx_bytes" }, { "tx_error_bytes" }, { "rx_ucast_packets" }, { "rx_mcast_packets" }, { "rx_bcast_packets" }, { "tx_ucast_packets" }, { "tx_mcast_packets" }, { "tx_bcast_packets" }, { "tx_mac_errors" }, { "tx_carrier_errors" }, { "rx_crc_errors" }, { "rx_align_errors" }, { "tx_single_collisions" }, { "tx_multi_collisions" }, { "tx_deferred" }, { "tx_excess_collisions" }, { "tx_late_collisions" }, { "tx_total_collisions" }, { "rx_fragments" }, { "rx_jabbers" }, { "rx_undersize_packets" }, { "rx_oversize_packets" }, { "rx_64_byte_packets" }, { "rx_65_to_127_byte_packets" }, { "rx_128_to_255_byte_packets" }, { "rx_256_to_511_byte_packets" }, { "rx_512_to_1023_byte_packets" }, { "rx_1024_to_1522_byte_packets" }, { "rx_1523_to_9022_byte_packets" }, { "tx_64_byte_packets" }, { "tx_65_to_127_byte_packets" }, { "tx_128_to_255_byte_packets" }, { "tx_256_to_511_byte_packets" }, { "tx_512_to_1023_byte_packets" }, { "tx_1024_to_1522_byte_packets" }, { "tx_1523_to_9022_byte_packets" }, { "rx_xon_frames" }, { "rx_xoff_frames" }, { "tx_xon_frames" }, { "tx_xoff_frames" }, { "rx_mac_ctrl_frames" }, { "rx_filtered_packets" }, { "rx_ftq_discards" }, { "rx_discards" }, { "rx_fw_discards" }, #if defined(BNX2_ENABLE_NETQUEUE) { "[0] rx_packets" }, { "[0] rx_bytes" }, { "[0] rx_errors" }, { "[0] tx_packets" }, { "[0] tx_bytes" }, { "[1] rx_packets" }, { "[1] rx_bytes" }, { "[1] rx_errors" }, { "[1] tx_packets" }, { "[1] tx_bytes" }, { "[2] rx_packets" }, { "[2] rx_bytes" }, { "[2] rx_errors" }, { "[2] tx_packets" }, { "[2] tx_bytes" }, { "[3] rx_packets" }, { "[3] rx_bytes" }, { "[3] rx_errors" }, { "[3] tx_packets" }, { "[3] tx_bytes" }, { "[4] rx_packets" }, { "[4] rx_bytes" }, { "[4] rx_errors" }, { "[4] tx_packets" }, { "[4] tx_bytes" }, { "[5] rx_packets" }, { "[5] rx_bytes" }, { "[5] rx_errors" }, { "[5] tx_packets" }, { "[5] tx_bytes" }, { "[6] rx_packets" }, { "[6] rx_bytes" }, { "[6] rx_errors" }, { "[6] tx_packets" }, { "[6] tx_bytes" }, { "[7] rx_packets" }, { "[7] rx_bytes" }, { "[7] rx_errors" }, { "[7] tx_packets" }, { "[7] tx_bytes" }, { "[8] rx_packets" }, { "[8] rx_bytes" }, { "[8] rx_errors" }, { "[8] tx_packets" }, { "[8] tx_bytes" }, #endif }; #define BNX2_NUM_STATS ARRAY_SIZE(bnx2_stats_str_arr) #if defined(BNX2_ENABLE_NETQUEUE) #define BNX2_NUM_NETQ_STATS 45 #endif #define STATS_OFFSET32(offset_name) (offsetof(struct statistics_block, offset_name) / 4) static const unsigned long bnx2_stats_offset_arr[BNX2_NUM_STATS] = { STATS_OFFSET32(stat_IfHCInOctets_hi), STATS_OFFSET32(stat_IfHCInBadOctets_hi), STATS_OFFSET32(stat_IfHCOutOctets_hi), STATS_OFFSET32(stat_IfHCOutBadOctets_hi), STATS_OFFSET32(stat_IfHCInUcastPkts_hi), STATS_OFFSET32(stat_IfHCInMulticastPkts_hi), STATS_OFFSET32(stat_IfHCInBroadcastPkts_hi), STATS_OFFSET32(stat_IfHCOutUcastPkts_hi), STATS_OFFSET32(stat_IfHCOutMulticastPkts_hi), STATS_OFFSET32(stat_IfHCOutBroadcastPkts_hi), STATS_OFFSET32(stat_emac_tx_stat_dot3statsinternalmactransmiterrors), STATS_OFFSET32(stat_Dot3StatsCarrierSenseErrors), STATS_OFFSET32(stat_Dot3StatsFCSErrors), STATS_OFFSET32(stat_Dot3StatsAlignmentErrors), STATS_OFFSET32(stat_Dot3StatsSingleCollisionFrames), STATS_OFFSET32(stat_Dot3StatsMultipleCollisionFrames), STATS_OFFSET32(stat_Dot3StatsDeferredTransmissions), STATS_OFFSET32(stat_Dot3StatsExcessiveCollisions), STATS_OFFSET32(stat_Dot3StatsLateCollisions), STATS_OFFSET32(stat_EtherStatsCollisions), STATS_OFFSET32(stat_EtherStatsFragments), STATS_OFFSET32(stat_EtherStatsJabbers), STATS_OFFSET32(stat_EtherStatsUndersizePkts), STATS_OFFSET32(stat_EtherStatsOverrsizePkts), STATS_OFFSET32(stat_EtherStatsPktsRx64Octets), STATS_OFFSET32(stat_EtherStatsPktsRx65Octetsto127Octets), STATS_OFFSET32(stat_EtherStatsPktsRx128Octetsto255Octets), STATS_OFFSET32(stat_EtherStatsPktsRx256Octetsto511Octets), STATS_OFFSET32(stat_EtherStatsPktsRx512Octetsto1023Octets), STATS_OFFSET32(stat_EtherStatsPktsRx1024Octetsto1522Octets), STATS_OFFSET32(stat_EtherStatsPktsRx1523Octetsto9022Octets), STATS_OFFSET32(stat_EtherStatsPktsTx64Octets), STATS_OFFSET32(stat_EtherStatsPktsTx65Octetsto127Octets), STATS_OFFSET32(stat_EtherStatsPktsTx128Octetsto255Octets), STATS_OFFSET32(stat_EtherStatsPktsTx256Octetsto511Octets), STATS_OFFSET32(stat_EtherStatsPktsTx512Octetsto1023Octets), STATS_OFFSET32(stat_EtherStatsPktsTx1024Octetsto1522Octets), STATS_OFFSET32(stat_EtherStatsPktsTx1523Octetsto9022Octets), STATS_OFFSET32(stat_XonPauseFramesReceived), STATS_OFFSET32(stat_XoffPauseFramesReceived), STATS_OFFSET32(stat_OutXonSent), STATS_OFFSET32(stat_OutXoffSent), STATS_OFFSET32(stat_MacControlFramesReceived), STATS_OFFSET32(stat_IfInFramesL2FilterDiscards), STATS_OFFSET32(stat_IfInFTQDiscards), STATS_OFFSET32(stat_IfInMBUFDiscards), STATS_OFFSET32(stat_FwRxDrop), }; /* stat_IfHCInBadOctets and stat_Dot3StatsCarrierSenseErrors are * skipped because of errata. */ static u8 bnx2_5706_stats_len_arr[BNX2_NUM_STATS] = { 8,0,8,8,8,8,8,8,8,8, 4,0,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4, }; static u8 bnx2_5708_stats_len_arr[BNX2_NUM_STATS] = { 8,0,8,8,8,8,8,8,8,8, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4,4,4, 4,4,4,4,4,4,4, }; #define BNX2_NUM_TESTS 6 static struct { char string[ETH_GSTRING_LEN]; } bnx2_tests_str_arr[BNX2_NUM_TESTS] = { { "register_test (offline)" }, { "memory_test (offline)" }, { "loopback_test (offline)" }, { "nvram_test (online)" }, { "interrupt_test (online)" }, { "link_test (online)" }, }; #ifdef ETHTOOL_GFLAGS static int bnx2_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_TEST: return BNX2_NUM_TESTS; case ETH_SS_STATS: return BNX2_NUM_STATS; default: return -EOPNOTSUPP; } } #else static int bnx2_self_test_count(struct net_device *dev) { return BNX2_NUM_TESTS; } #endif static void bnx2_self_test(struct net_device *dev, struct ethtool_test *etest, u64 *buf) { struct bnx2 *bp = netdev_priv(dev); memset(buf, 0, sizeof(u64) * BNX2_NUM_TESTS); if (etest->flags & ETH_TEST_FL_OFFLINE) { int i; bnx2_netif_stop(bp, true); bnx2_reset_chip(bp, BNX2_DRV_MSG_CODE_DIAG); bnx2_free_skbs(bp); if (bnx2_test_registers(bp) != 0) { buf[0] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if (bnx2_test_memory(bp) != 0) { buf[1] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if ((buf[2] = bnx2_test_loopback(bp)) != 0) etest->flags |= ETH_TEST_FL_FAILED; if (!netif_running(bp->dev)) bnx2_shutdown_chip(bp); else { bnx2_init_nic(bp, 1); bnx2_netif_start(bp, true); } /* wait for link up */ for (i = 0; i < 7; i++) { if (bp->link_up) break; bnx2_msleep_interruptible(1000); } } if (bnx2_test_nvram(bp) != 0) { buf[3] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if (bnx2_test_intr(bp) != 0) { buf[4] = 1; etest->flags |= ETH_TEST_FL_FAILED; } if (bnx2_test_link(bp) != 0) { buf[5] = 1; etest->flags |= ETH_TEST_FL_FAILED; } } static void bnx2_get_strings(struct net_device *dev, u32 stringset, u8 *buf) { switch (stringset) { case ETH_SS_STATS: memcpy(buf, bnx2_stats_str_arr, sizeof(bnx2_stats_str_arr)); break; case ETH_SS_TEST: memcpy(buf, bnx2_tests_str_arr, sizeof(bnx2_tests_str_arr)); break; } } #ifndef ETHTOOL_GFLAGS static int bnx2_get_stats_count(struct net_device *dev) { return BNX2_NUM_STATS; } #endif static void bnx2_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *buf) { struct bnx2 *bp = netdev_priv(dev); int i; u32 *hw_stats = (u32 *) bp->stats_blk; u32 *temp_stats = (u32 *) bp->temp_stats_blk; u8 *stats_len_arr = NULL; if (hw_stats == NULL) { memset(buf, 0, sizeof(u64) * BNX2_NUM_STATS); return; } if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A2) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0)) stats_len_arr = bnx2_5706_stats_len_arr; else stats_len_arr = bnx2_5708_stats_len_arr; #if defined(BNX2_ENABLE_NETQUEUE) for (i = 0; i < BNX2_NUM_STATS - BNX2_NUM_NETQ_STATS; i++) { #else for (i = 0; i < BNX2_NUM_STATS; i++) { #endif unsigned long offset; if (stats_len_arr[i] == 0) { /* skip this counter */ buf[i] = 0; continue; } offset = bnx2_stats_offset_arr[i]; if (stats_len_arr[i] == 4) { /* 4-byte counter */ buf[i] = (u64) *(hw_stats + offset) + *(temp_stats + offset); continue; } /* 8-byte counter */ buf[i] = (((u64) *(hw_stats + offset)) << 32) + *(hw_stats + offset + 1) + (((u64) *(temp_stats + offset)) << 32) + *(temp_stats + offset + 1); } #if defined(BNX2_ENABLE_NETQUEUE) /* Copy over the NetQ specific statistics */ { int j; for (j = 0; j < BNX2_MAX_MSIX_VEC; j++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[j]; buf[i + (j*5) + 0] = (u64) (bnapi->stats.rx_packets); buf[i + (j*5) + 1] = (u64) (bnapi->stats.rx_bytes); buf[i + (j*5) + 2] = (u64) (bnapi->stats.rx_errors); buf[i + (j*5) + 3] = (u64) (bnapi->stats.tx_packets); buf[i + (j*5) + 4] = (u64) (bnapi->stats.tx_bytes); } } #endif } #if (LINUX_VERSION_CODE < 0x30000) static int bnx2_phys_id(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); int i; u32 save; if (data == 0) data = 2; save = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, BNX2_MISC_CFG_LEDMODE_MAC); for (i = 0; i < (data * 2); i++) { if ((i % 2) == 0) { BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE); } else { BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE | BNX2_EMAC_LED_1000MB_OVERRIDE | BNX2_EMAC_LED_100MB_OVERRIDE | BNX2_EMAC_LED_10MB_OVERRIDE | BNX2_EMAC_LED_TRAFFIC_OVERRIDE | BNX2_EMAC_LED_TRAFFIC); } bnx2_msleep_interruptible(500); if (signal_pending(current)) break; } BNX2_WR(bp, BNX2_EMAC_LED, 0); BNX2_WR(bp, BNX2_MISC_CFG, save); return 0; } #else static int bnx2_set_phys_id(struct net_device *dev, enum ethtool_phys_id_state state) { struct bnx2 *bp = netdev_priv(dev); switch (state) { case ETHTOOL_ID_ACTIVE: bp->leds_save = BNX2_RD(bp, BNX2_MISC_CFG); BNX2_WR(bp, BNX2_MISC_CFG, BNX2_MISC_CFG_LEDMODE_MAC); return 1; /* cycle on/off once per second */ case ETHTOOL_ID_ON: BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE | BNX2_EMAC_LED_1000MB_OVERRIDE | BNX2_EMAC_LED_100MB_OVERRIDE | BNX2_EMAC_LED_10MB_OVERRIDE | BNX2_EMAC_LED_TRAFFIC_OVERRIDE | BNX2_EMAC_LED_TRAFFIC); break; case ETHTOOL_ID_OFF: BNX2_WR(bp, BNX2_EMAC_LED, BNX2_EMAC_LED_OVERRIDE); break; case ETHTOOL_ID_INACTIVE: BNX2_WR(bp, BNX2_EMAC_LED, 0); BNX2_WR(bp, BNX2_MISC_CFG, bp->leds_save); break; } return 0; } #endif #if (LINUX_VERSION_CODE >= 0x20418) && !defined(NEW_ETHTOOL) static int bnx2_set_tx_csum(struct net_device *dev, u32 data) { struct bnx2 *bp = netdev_priv(dev); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) #if (LINUX_VERSION_CODE < 0x2060c) return bnx2_set_tx_hw_csum(dev, data); #elif (LINUX_VERSION_CODE >= 0x20617) return ethtool_op_set_tx_ipv6_csum(dev, data); #else return ethtool_op_set_tx_hw_csum(dev, data); #endif else return ethtool_op_set_tx_csum(dev, data); } #endif #if defined(NETIF_F_RXHASH) && !defined(NEW_ETHTOOL) #if (LINUX_VERSION_CODE >= 0x20624) static int bnx2_set_flags(struct net_device *dev, u32 data) { return ethtool_op_set_flags(dev, data, ETH_FLAG_RXHASH); } #else static int bnx2_set_flags(struct net_device *dev, u32 data) { if (data & (ETH_FLAG_LRO | ETH_FLAG_NTUPLE)) return -EOPNOTSUPP; if (data & ETH_FLAG_RXHASH) dev->features |= NETIF_F_RXHASH; else dev->features &= ~NETIF_F_RXHASH; return 0; } #endif #endif #ifdef HAVE_FIX_FEATURES static netdev_features_t bnx2_fix_features(struct net_device *dev, netdev_features_t features) { struct bnx2 *bp = netdev_priv(dev); if (!(bp->flags & BNX2_FLAG_CAN_KEEP_VLAN)) features |= NETIF_F_HW_VLAN_CTAG_RX; return features; } static int bnx2_set_features(struct net_device *dev, netdev_features_t features) { struct bnx2 *bp = netdev_priv(dev); /* TSO with VLAN tag won't work with current firmware */ if (features & NETIF_F_HW_VLAN_CTAG_TX) dev->vlan_features |= (dev->hw_features & NETIF_F_ALL_TSO); else dev->vlan_features &= ~NETIF_F_ALL_TSO; if ((!!(features & NETIF_F_HW_VLAN_CTAG_RX) != !!(bp->rx_mode & BNX2_EMAC_RX_MODE_KEEP_VLAN_TAG)) && netif_running(dev)) { bnx2_netif_stop(bp, false); dev->features = features; bnx2_set_rx_mode(dev); bnx2_fw_sync(bp, BNX2_DRV_MSG_CODE_KEEP_VLAN_UPDATE, 0, 1); bnx2_netif_start(bp, false); return 1; } return 0; } #endif #if defined(ETHTOOL_GCHANNELS) && !defined(GET_ETHTOOL_OP_EXT) static void bnx2_get_channels(struct net_device *dev, struct ethtool_channels *channels) { struct bnx2 *bp = netdev_priv(dev); u32 max_rx_rings = 1; u32 max_tx_rings = 1; if ((bp->flags & BNX2_FLAG_MSIX_CAP) && !disable_msi) { max_rx_rings = RX_MAX_RINGS; max_tx_rings = TX_MAX_RINGS; } channels->max_rx = max_rx_rings; channels->max_tx = max_tx_rings; channels->max_other = 0; channels->max_combined = 0; channels->rx_count = bp->num_rx_rings; channels->tx_count = bp->num_tx_rings; channels->other_count = 0; channels->combined_count = 0; } static int bnx2_set_channels(struct net_device *dev, struct ethtool_channels *channels) { struct bnx2 *bp = netdev_priv(dev); u32 max_rx_rings = 1; u32 max_tx_rings = 1; int rc = 0; if ((bp->flags & BNX2_FLAG_MSIX_CAP) && !disable_msi) { max_rx_rings = RX_MAX_RINGS; max_tx_rings = TX_MAX_RINGS; } if (channels->rx_count > max_rx_rings || channels->tx_count > max_tx_rings) return -EINVAL; bp->num_req_rx_rings = channels->rx_count; bp->num_req_tx_rings = channels->tx_count; if (netif_running(dev)) rc = bnx2_change_ring_size(bp, bp->rx_ring_size, bp->tx_ring_size, true); return rc; } #endif static struct ethtool_ops bnx2_ethtool_ops = { .get_settings = bnx2_get_settings, .set_settings = bnx2_set_settings, .get_drvinfo = bnx2_get_drvinfo, .get_regs_len = bnx2_get_regs_len, .get_regs = bnx2_get_regs, .get_wol = bnx2_get_wol, .set_wol = bnx2_set_wol, .get_msglevel = bnx2_get_msglevel, .set_msglevel = bnx2_set_msglevel, .nway_reset = bnx2_nway_reset, .get_link = bnx2_get_link, #if (LINUX_VERSION_CODE >= 0x20418) .get_eeprom_len = bnx2_get_eeprom_len, #endif #ifdef ETHTOOL_GEEPROM .get_eeprom = bnx2_get_eeprom, #endif #ifdef ETHTOOL_SEEPROM .set_eeprom = bnx2_set_eeprom, #endif .get_coalesce = bnx2_get_coalesce, .set_coalesce = bnx2_set_coalesce, .get_ringparam = bnx2_get_ringparam, .set_ringparam = bnx2_set_ringparam, .get_pauseparam = bnx2_get_pauseparam, .set_pauseparam = bnx2_set_pauseparam, #ifndef NEW_ETHTOOL .get_rx_csum = bnx2_get_rx_csum, .set_rx_csum = bnx2_set_rx_csum, .get_tx_csum = ethtool_op_get_tx_csum, #if (LINUX_VERSION_CODE >= 0x20418) .set_tx_csum = bnx2_set_tx_csum, #endif .get_sg = ethtool_op_get_sg, .set_sg = ethtool_op_set_sg, #ifdef BCM_TSO .get_tso = ethtool_op_get_tso, .set_tso = bnx2_set_tso, #endif #endif #ifndef ETHTOOL_GFLAGS .self_test_count = bnx2_self_test_count, #endif .self_test = bnx2_self_test, .get_strings = bnx2_get_strings, #if (LINUX_VERSION_CODE < 0x30000) .phys_id = bnx2_phys_id, #else .set_phys_id = bnx2_set_phys_id, #endif #ifndef ETHTOOL_GFLAGS .get_stats_count = bnx2_get_stats_count, #endif .get_ethtool_stats = bnx2_get_ethtool_stats, #ifdef ETHTOOL_GPERMADDR #if (LINUX_VERSION_CODE < 0x020617) .get_perm_addr = ethtool_op_get_perm_addr, #endif #endif #ifdef ETHTOOL_GFLAGS .get_sset_count = bnx2_get_sset_count, #endif #if defined(NETIF_F_RXHASH) && !defined(NEW_ETHTOOL) .set_flags = bnx2_set_flags, .get_flags = ethtool_op_get_flags, #endif #if defined(ETHTOOL_GCHANNELS) && !defined(GET_ETHTOOL_OP_EXT) .get_channels = bnx2_get_channels, .set_channels = bnx2_set_channels, #endif }; #if defined(BNX2_VMWARE_BMAPILNX) static int bnx2_ioctl_cim(struct net_device *dev, struct ifreq *ifr) { struct bnx2 *bp = netdev_priv(dev); void __user *useraddr = ifr->ifr_data; struct bnx2_ioctl_req req; int rc = 0; u32 val; if (copy_from_user(&req, useraddr, sizeof(req))) { netdev_err(bp->dev, "bnx2_ioctl() could not copy from user"); return -EFAULT; } switch(req.cmd) { case BNX2_VMWARE_CIM_CMD_ENABLE_NIC: BNX2_DP(BNX2_MSG_ESX_IOCTL, "enable NIC\n"); rc = bnx2_open(bp->dev); break; case BNX2_VMWARE_CIM_CMD_DISABLE_NIC: BNX2_DP(BNX2_MSG_ESX_IOCTL, "disable NIC\n"); rc = bnx2_close(bp->dev); break; case BNX2_VMWARE_CIM_CMD_REG_READ: { struct bnx2_ioctl_reg_read_req *rd_req; u32 mem_len; #if defined(__VMKLNX__) && defined(__VMKNETDDI_QUEUEOPS__) mem_len = MB_GET_CID_ADDR(NETQUEUE_KCQ_CID + 2); #else mem_len = MB_GET_CID_ADDR(TX_TSS_CID + TX_MAX_TSS_RINGS + 1); #endif rd_req = &req.cmd_req.reg_read; switch (rd_req->reg_access_type) { case BRCM_VMWARE_REG_ACCESS_DIRECT: if (mem_len < rd_req->reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() reg read: " "out of range: " "max reg: 0x%x req reg: 0x%x\n", mem_len, rd_req->reg_offset); rc = -EINVAL; break; } val = BNX2_RD(bp, req.cmd_req.reg_read.reg_offset); BNX2_DP(BNX2_MSG_ESX_IOCTL, "reg read: reg: 0x%x value:0x%x\n", rd_req->reg_offset, rd_req->reg_value); rd_req->reg_value = val; break; case BRCM_VMWARE_REG_ACCESS_PCI_CFG: BNX2_DP(BNX2_MSG_ESX_IOCTL, "PCI config reg read: reg: 0x%x value:0x%x\n", rd_req->reg_offset, rd_req->reg_value); pci_read_config_dword(bp->pdev, rd_req->reg_offset, &val); rd_req->reg_value = val; break; case BRCM_VMWARE_REG_ACCESS_INDIRECT: mem_len = 0x240800; if (mem_len < rd_req->reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() indirect reg read: " "out of range: " "max reg: 0x%x req reg: 0x%x\n", mem_len, rd_req->reg_offset); rc = -EINVAL; break; } val = bnx2_reg_rd_ind(bp, rd_req->reg_offset); BNX2_DP(BNX2_MSG_ESX_IOCTL, "indirect reg read: reg: 0x%x value:0x%x", rd_req->reg_offset, rd_req->reg_value); rd_req->reg_value = val; break; default: netdev_err(bp->dev, "invalid reg read access method: " "access type: 0x%x req reg: 0x%x\n", rd_req->reg_access_type, rd_req->reg_offset); rc = -EINVAL; break; } } case BNX2_VMWARE_CIM_CMD_REG_WRITE: { struct bnx2_ioctl_reg_write_req *wr_req; u32 mem_len; #if defined(__VMKLNX__) && defined(__VMKNETDDI_QUEUEOPS__) mem_len = MB_GET_CID_ADDR(NETQUEUE_KCQ_CID + 2); #else mem_len = MB_GET_CID_ADDR(TX_TSS_CID + TX_MAX_TSS_RINGS + 1); #endif wr_req = &req.cmd_req.reg_write; switch (wr_req->reg_access_type) { case BRCM_VMWARE_REG_ACCESS_DIRECT: if (mem_len < req.cmd_req.reg_write.reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() reg write: " "out of range: max reg: 0x%x " "req reg: 0x%x\n", mem_len, req.cmd_req.reg_write.reg_offset); rc = -EINVAL; break; } BNX2_DP(BNX2_MSG_ESX_IOCTL, "reg write: reg: 0x%x value:0x%x\n", wr_req->reg_offset, wr_req->reg_value); BNX2_WR(bp, wr_req->reg_offset, wr_req->reg_value); break; case BRCM_VMWARE_REG_ACCESS_PCI_CFG: netdev_info(bp->dev, "bnx2_ioctl() PCI config reg write: " "reg: 0x%x value:0x%x\n", wr_req->reg_offset, wr_req->reg_value); pci_write_config_dword(bp->pdev, wr_req->reg_offset, wr_req->reg_value); break; case BRCM_VMWARE_REG_ACCESS_INDIRECT: mem_len = 0x240800; if (mem_len < wr_req->reg_offset) { netdev_err(bp->dev, "bnx2_ioctl() indirect reg write: " "out of range: " "max reg: 0x%x req reg: 0x%x\n", mem_len, wr_req->reg_offset); rc = -EINVAL; break; } bnx2_reg_wr_ind(bp, wr_req->reg_offset, wr_req->reg_value); BNX2_DP(BNX2_MSG_ESX_IOCTL, "indirect reg write: reg: 0x%x value:0x%x\n", wr_req->reg_offset, wr_req->reg_value); wr_req->reg_value = val; break; default: netdev_err(bp->dev, "invalid reg write access method: " "access type: 0x%x reg: 0x%x\n", wr_req->reg_access_type, wr_req->reg_offset); rc = -EINVAL; break; } } case BNX2_VMWARE_CIM_CMD_GET_NIC_PARAM: BNX2_DP(BNX2_MSG_ESX_IOCTL, "get NIC param\n"); req.cmd_req.get_nic_param.mtu = dev->mtu; memcpy(req.cmd_req.get_nic_param.current_mac_addr, dev->dev_addr, sizeof(req.cmd_req.get_nic_param.current_mac_addr)); break; case BNX2_VMWARE_CIM_CMD_GET_NIC_STATUS: BNX2_DP(BNX2_MSG_ESX_IOCTL, "get NIC status\n"); req.cmd_req.get_nic_status.nic_status = netif_running(dev); break; default: netdev_warn(bp->dev, "bnx2_ioctl() unknown req.cmd: 0x%x\n", req.cmd); rc = -EINVAL; } if (rc == 0 && copy_to_user(useraddr, &req, sizeof(req))) { netdev_err(bp->dev, "bnx2_ioctl() couldn't copy to user " "bnx2_ioctl_req\n"); return -EFAULT; } return rc; } #endif /* BNX2_VMWARE_BMAPILNX */ /* Called with rtnl_lock */ static int bnx2_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { #if (LINUX_VERSION_CODE >= 0x020607) struct mii_ioctl_data *data = if_mii(ifr); #else struct mii_ioctl_data *data = (struct mii_ioctl_data *) &ifr->ifr_ifru; #endif struct bnx2 *bp = netdev_priv(dev); int err; switch(cmd) { case SIOCGMIIPHY: data->phy_id = bp->phy_addr; /* fallthru */ case SIOCGMIIREG: { u32 mii_regval; if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return -EOPNOTSUPP; if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&bp->phy_lock); err = bnx2_read_phy(bp, data->reg_num & 0x1f, &mii_regval); spin_unlock_bh(&bp->phy_lock); data->val_out = mii_regval; return err; } case SIOCSMIIREG: #if defined(__VMKLNX__) if (!capable(CAP_NET_ADMIN)) return -EPERM; #endif if (bp->phy_flags & BNX2_PHY_FLAG_REMOTE_PHY_CAP) return -EOPNOTSUPP; if (!netif_running(dev)) return -EAGAIN; spin_lock_bh(&bp->phy_lock); err = bnx2_write_phy(bp, data->reg_num & 0x1f, data->val_in); spin_unlock_bh(&bp->phy_lock); return err; #if defined(BNX2_VMWARE_BMAPILNX) #define SIOBNX2CIM 0x89F0 case SIOBNX2CIM: return bnx2_ioctl_cim(dev, ifr); #endif /* BNX2_VMWARE_BMAPILNX */ default: /* do nothing */ break; } return -EOPNOTSUPP; } #if defined(__VMKLNX__) static int bnx2_vmk_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { int rc; #if (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif rc = bnx2_ioctl(dev, ifr, cmd); #if (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif return rc; } #endif /* Called with rtnl_lock */ static int bnx2_change_mac_addr(struct net_device *dev, void *p) { struct sockaddr *addr = p; struct bnx2 *bp = netdev_priv(dev); if (!is_valid_ether_addr(addr->sa_data)) return -EADDRNOTAVAIL; memcpy(dev->dev_addr, addr->sa_data, dev->addr_len); if (netif_running(dev)) bnx2_set_mac_addr(bp, bp->dev->dev_addr, 0); return 0; } /* Called with rtnl_lock */ static int bnx2_change_mtu(struct net_device *dev, int new_mtu) { struct bnx2 *bp = netdev_priv(dev); if (((new_mtu + ETH_HLEN) > MAX_ETHERNET_JUMBO_PACKET_SIZE) || ((new_mtu + ETH_HLEN) < MIN_ETHERNET_PACKET_SIZE)) return -EINVAL; dev->mtu = new_mtu; return (bnx2_change_ring_size(bp, bp->rx_ring_size, bp->tx_ring_size, false)); } #if defined(__VMKLNX__) static int bnx2_vmk_change_mtu(struct net_device *dev, int new_mtu) { int rc; #if (VMWARE_ESX_DDK_VERSION < 50000) /* rtnl_lock() needed for ESX 4.0 and 4.1 only */ rtnl_lock(); #endif rc = bnx2_change_mtu(dev, new_mtu); #if (VMWARE_ESX_DDK_VERSION < 50000) rtnl_unlock(); #endif return rc; } #endif #if defined(HAVE_POLL_CONTROLLER) || defined(CONFIG_NET_POLL_CONTROLLER) static void poll_bnx2(struct net_device *dev) { struct bnx2 *bp = netdev_priv(dev); #if defined(RED_HAT_LINUX_KERNEL) && (LINUX_VERSION_CODE < 0x020600) if (netdump_mode) { struct bnx2_irq *irq = &bp->irq_tbl[0]; irq_handler(irq->vector, &bp->bnx2_napi[0], NULL); if (dev->poll_list.prev) { int budget = 64; bnx2_poll(dev, &budget); } } else #endif { int i; for (i = 0; i < bp->irq_nvecs; i++) { struct bnx2_irq *irq = &bp->irq_tbl[i]; disable_irq(irq->vector); #if (LINUX_VERSION_CODE >= 0x20613) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) irq->handler(irq->vector, &bp->bnx2_napi[i]); #else irq->handler(irq->vector, &bp->bnx2_napi[i], NULL); #endif enable_irq(irq->vector); } } } #endif static void __devinit bnx2_get_5709_media(struct bnx2 *bp) { u32 val = BNX2_RD(bp, BNX2_MISC_DUAL_MEDIA_CTRL); u32 bond_id = val & BNX2_MISC_DUAL_MEDIA_CTRL_BOND_ID; u32 strap; if (bond_id == BNX2_MISC_DUAL_MEDIA_CTRL_BOND_ID_C) return; else if (bond_id == BNX2_MISC_DUAL_MEDIA_CTRL_BOND_ID_S) { bp->phy_flags |= BNX2_PHY_FLAG_SERDES; return; } if (val & BNX2_MISC_DUAL_MEDIA_CTRL_STRAP_OVERRIDE) strap = (val & BNX2_MISC_DUAL_MEDIA_CTRL_PHY_CTRL) >> 21; else strap = (val & BNX2_MISC_DUAL_MEDIA_CTRL_PHY_CTRL_STRAP) >> 8; if (bp->func == 0) { switch (strap) { case 0x4: case 0x5: case 0x6: bp->phy_flags |= BNX2_PHY_FLAG_SERDES; return; } } else { switch (strap) { case 0x1: case 0x2: case 0x4: bp->phy_flags |= BNX2_PHY_FLAG_SERDES; return; } } } static void __devinit bnx2_get_pci_speed(struct bnx2 *bp) { u32 reg; reg = BNX2_RD(bp, BNX2_PCICFG_MISC_STATUS); if (reg & BNX2_PCICFG_MISC_STATUS_PCIX_DET) { u32 clkreg; bp->flags |= BNX2_FLAG_PCIX; clkreg = BNX2_RD(bp, BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS); clkreg &= BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET; switch (clkreg) { case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_133MHZ: bp->bus_speed_mhz = 133; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_95MHZ: bp->bus_speed_mhz = 100; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_66MHZ: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_80MHZ: bp->bus_speed_mhz = 66; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_48MHZ: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_55MHZ: bp->bus_speed_mhz = 50; break; case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_LOW: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_32MHZ: case BNX2_PCICFG_PCI_CLOCK_CONTROL_BITS_PCI_CLK_SPD_DET_38MHZ: bp->bus_speed_mhz = 33; break; } } else { if (reg & BNX2_PCICFG_MISC_STATUS_M66EN) bp->bus_speed_mhz = 66; else bp->bus_speed_mhz = 33; } if (reg & BNX2_PCICFG_MISC_STATUS_32BIT_DET) bp->flags |= BNX2_FLAG_PCI_32BIT; } static void __devinit bnx2_read_vpd_fw_ver(struct bnx2 *bp) { int rc, i, v0_len = 0; u8 *data; u8 *v0_str = NULL; bool mn_match = false; #define BNX2_VPD_NVRAM_OFFSET 0x300 #define BNX2_VPD_LEN 128 #define BNX2_MAX_VER_SLEN 30 data = kmalloc(256, GFP_KERNEL); if (!data) return; rc = bnx2_nvram_read(bp, BNX2_VPD_NVRAM_OFFSET, data + BNX2_VPD_LEN, BNX2_VPD_LEN); if (rc) goto vpd_done; for (i = 0; i < BNX2_VPD_LEN; i += 4) { data[i] = data[i + BNX2_VPD_LEN + 3]; data[i + 1] = data[i + BNX2_VPD_LEN + 2]; data[i + 2] = data[i + BNX2_VPD_LEN + 1]; data[i + 3] = data[i + BNX2_VPD_LEN]; } for (i = 0; i <= BNX2_VPD_LEN - 3; ) { unsigned char val = data[i]; unsigned int block_end; if (val == 0x82 || val == 0x91) { i = (i + 3 + (data[i + 1] + (data[i + 2] << 8))); continue; } if (val != 0x90) goto vpd_done; block_end = (i + 3 + (data[i + 1] + (data[i + 2] << 8))); i += 3; if (block_end > BNX2_VPD_LEN) goto vpd_done; while (i < (block_end - 2)) { int len = data[i + 2]; if (i + 3 + len > block_end) goto vpd_done; if (data[i] == 'M' && data[i + 1] == 'N') { if (len != 4 || memcmp(&data[i + 3], "1028", 4)) goto vpd_done; mn_match = true; } else if (data[i] == 'V' && data[i + 1] == '0') { if (len > BNX2_MAX_VER_SLEN) goto vpd_done; v0_len = len; v0_str = &data[i + 3]; } i += 3 + len; if (mn_match && v0_str) { memcpy(bp->fw_version, v0_str, v0_len); bp->fw_version[v0_len] = ' '; goto vpd_done; } } goto vpd_done; } vpd_done: kfree(data); } static int __devinit bnx2_init_board(struct pci_dev *pdev, struct net_device *dev) { struct bnx2 *bp; int rc, i, j; u32 reg; u64 dma_mask, persist_dma_mask; int __maybe_unused err; #if (LINUX_VERSION_CODE < 0x20610) SET_MODULE_OWNER(dev); #endif #if (LINUX_VERSION_CODE >= 0x20419) SET_NETDEV_DEV(dev, &pdev->dev); #endif bp = netdev_priv(dev); bp->flags = 0; bp->phy_flags = 0; bp->temp_stats_blk = kmalloc(sizeof(struct statistics_block), GFP_KERNEL); if (bp->temp_stats_blk == NULL) { rc = -ENOMEM; goto err_out; } memset(bp->temp_stats_blk, 0, sizeof(struct statistics_block)); /* enable device (incl. PCI PM wakeup), and bus-mastering */ rc = pci_enable_device(pdev); if (rc) { dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n"); goto err_out; } if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { dev_err(&pdev->dev, "Cannot find PCI device base address, aborting\n"); rc = -ENODEV; goto err_out_disable; } rc = pci_request_regions(pdev, DRV_MODULE_NAME); if (rc) { dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n"); goto err_out_disable; } pci_set_master(pdev); bp->pm_cap = pci_find_capability(pdev, PCI_CAP_ID_PM); if (bp->pm_cap == 0) { dev_err(&pdev->dev, "Cannot find power management capability, aborting\n"); rc = -EIO; goto err_out_release; } bp->dev = dev; bp->pdev = pdev; spin_lock_init(&bp->phy_lock); spin_lock_init(&bp->indirect_lock); #if defined(BNX2_ENABLE_NETQUEUE) mutex_init(&bp->netq_lock); #endif #ifdef BCM_CNIC mutex_init(&bp->cnic_lock); #endif #if (LINUX_VERSION_CODE >= 0x20600) #if defined(INIT_DELAYED_WORK_DEFERRABLE) || defined(INIT_WORK_NAR) || defined(INIT_DEFERRABLE_WORK) || (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 40000)) INIT_WORK(&bp->reset_task, bnx2_reset_task); #else INIT_WORK(&bp->reset_task, bnx2_reset_task, bp); #endif #else INIT_TQUEUE(&bp->reset_task, bnx2_reset_task, bp); #endif #if defined(BNX2_ENABLE_NETQUEUE) bp->regview = pci_iomap(pdev, 0, MB_GET_CID_ADDR(NETQUEUE_KCQ_CID + 2)); #else bp->regview = pci_iomap(pdev, 0, MB_GET_CID_ADDR(TX_TSS_CID + TX_MAX_TSS_RINGS + 1)); #endif if (!bp->regview) { dev_err(&pdev->dev, "Cannot map register space, aborting\n"); rc = -ENOMEM; goto err_out_release; } /* Configure byte swap and enable write to the reg_window registers. * Rely on CPU to do target byte swapping on big endian systems * The chip's target access swapping will not swap all accesses */ BNX2_WR(bp, BNX2_PCICFG_MISC_CONFIG, BNX2_PCICFG_MISC_CONFIG_REG_WINDOW_ENA | BNX2_PCICFG_MISC_CONFIG_TARGET_MB_WORD_SWAP); bp->chip_id = BNX2_RD(bp, BNX2_MISC_ID); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (!pci_is_pcie(pdev)) { dev_err(&pdev->dev, "Not PCIE, aborting\n"); rc = -EIO; goto err_out_unmap; } bp->flags |= BNX2_FLAG_PCIE; if (BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Ax) bp->flags |= BNX2_FLAG_JUMBO_BROKEN; #if !defined(CONFIG_PPC64) && !defined(CONFIG_PPC32) /* AER (Advanced Error Reporting) hooks */ err = pci_enable_pcie_error_reporting(pdev); if (!err) bp->flags |= BNX2_FLAG_AER_ENABLED; #endif } else { bp->pcix_cap = pci_find_capability(pdev, PCI_CAP_ID_PCIX); if (bp->pcix_cap == 0) { dev_err(&pdev->dev, "Cannot find PCIX capability, aborting\n"); rc = -EIO; goto err_out_unmap; } bp->flags |= BNX2_FLAG_BROKEN_STATS; } #ifdef CONFIG_PCI_MSI if (BNX2_CHIP(bp) == BNX2_CHIP_5709 && BNX2_CHIP_REV(bp) != BNX2_CHIP_REV_Ax) { if (pci_find_capability(pdev, PCI_CAP_ID_MSIX)) bp->flags |= BNX2_FLAG_MSIX_CAP; } #endif if (BNX2_CHIP_ID(bp) != BNX2_CHIP_ID_5706_A0 && BNX2_CHIP_ID(bp) != BNX2_CHIP_ID_5706_A1) { if (pci_find_capability(pdev, PCI_CAP_ID_MSI)) bp->flags |= BNX2_FLAG_MSI_CAP; } /* 5708 cannot support DMA addresses > 40-bit. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5708) persist_dma_mask = dma_mask = DMA_BIT_MASK(40); else persist_dma_mask = dma_mask = DMA_BIT_MASK(64); /* Configure DMA attributes. */ if (pci_set_dma_mask(pdev, dma_mask) == 0) { #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) if (BNX2_CHIP(bp) == BNX2_CHIP_5708) dev->features |= NETIF_F_DMA40; else dev->features |= NETIF_F_HIGHDMA; #else dev->features |= NETIF_F_HIGHDMA; #endif rc = pci_set_consistent_dma_mask(pdev, persist_dma_mask); if (rc) { dev_err(&pdev->dev, "pci_set_consistent_dma_mask failed, aborting\n"); goto err_out_unmap; } } else if ((rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) { dev_err(&pdev->dev, "System does not support DMA, aborting\n"); goto err_out_unmap; } if (!(bp->flags & BNX2_FLAG_PCIE)) bnx2_get_pci_speed(bp); /* 5706A0 may falsely detect SERR and PERR. */ if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { reg = BNX2_RD(bp, PCI_COMMAND); reg &= ~(PCI_COMMAND_SERR | PCI_COMMAND_PARITY); BNX2_WR(bp, PCI_COMMAND, reg); } else if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A1) && !(bp->flags & BNX2_FLAG_PCIX)) { dev_err(&pdev->dev, "5706 A1 can only be used in a PCIX bus, aborting\n"); goto err_out_unmap; } bnx2_init_nvram(bp); reg = bnx2_reg_rd_ind(bp, BNX2_SHM_HDR_SIGNATURE); if (bnx2_reg_rd_ind(bp, BNX2_MCP_TOE_ID) & BNX2_MCP_TOE_ID_FUNCTION_ID) bp->func = 1; if ((reg & BNX2_SHM_HDR_SIGNATURE_SIG_MASK) == BNX2_SHM_HDR_SIGNATURE_SIG) { u32 off = bp->func << 2; bp->shmem_base = bnx2_reg_rd_ind(bp, BNX2_SHM_HDR_ADDR_0 + off); } else bp->shmem_base = HOST_VIEW_SHMEM_BASE; /* Get the permanent MAC address. First we need to make sure the * firmware is actually running. */ reg = bnx2_shmem_rd(bp, BNX2_DEV_INFO_SIGNATURE); if ((reg & BNX2_DEV_INFO_SIGNATURE_MAGIC_MASK) != BNX2_DEV_INFO_SIGNATURE_MAGIC) { dev_err(&pdev->dev, "Firmware not running, aborting\n"); rc = -ENODEV; goto err_out_unmap; } bnx2_read_vpd_fw_ver(bp); j = strlen(bp->fw_version); reg = bnx2_shmem_rd(bp, BNX2_DEV_INFO_BC_REV); for (i = 0; i < 3 && j < 24; i++) { u8 num, k, skip0; if (i == 0) { bp->fw_version[j++] = 'b'; bp->fw_version[j++] = 'c'; bp->fw_version[j++] = ' '; } num = (u8) (reg >> (24 - (i * 8))); for (k = 100, skip0 = 1; k >= 1; num %= k, k /= 10) { if (num >= k || !skip0 || k == 1) { bp->fw_version[j++] = (num / k) + '0'; skip0 = 0; } } if (i != 2) bp->fw_version[j++] = '.'; } reg = bnx2_shmem_rd(bp, BNX2_PORT_FEATURE); if (reg & BNX2_PORT_FEATURE_WOL_ENABLED) bp->wol = 1; if (reg & BNX2_PORT_FEATURE_ASF_ENABLED) { bp->flags |= BNX2_FLAG_ASF_ENABLE; for (i = 0; i < 30; i++) { reg = bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION); if (reg & BNX2_CONDITION_MFW_RUN_MASK) break; bnx2_msleep(10); } } reg = bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION); reg &= BNX2_CONDITION_MFW_RUN_MASK; if (reg != BNX2_CONDITION_MFW_RUN_UNKNOWN && reg != BNX2_CONDITION_MFW_RUN_NONE) { u32 addr = bnx2_shmem_rd(bp, BNX2_MFW_VER_PTR); if (j < 32) bp->fw_version[j++] = ' '; for (i = 0; i < 3 && j < 28; i++) { reg = bnx2_reg_rd_ind(bp, addr + i * 4); reg = be32_to_cpu(reg); memcpy(&bp->fw_version[j], &reg, 4); j += 4; } } reg = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_MAC_UPPER); bp->mac_addr[0] = (u8) (reg >> 8); bp->mac_addr[1] = (u8) reg; reg = bnx2_shmem_rd(bp, BNX2_PORT_HW_CFG_MAC_LOWER); bp->mac_addr[2] = (u8) (reg >> 24); bp->mac_addr[3] = (u8) (reg >> 16); bp->mac_addr[4] = (u8) (reg >> 8); bp->mac_addr[5] = (u8) reg; bp->tx_ring_size = BNX2_MAX_TX_DESC_CNT; bnx2_set_rx_ring_size(bp, 255); bp->rx_csum = 1; bp->tx_quick_cons_trip_int = 2; bp->tx_quick_cons_trip = 20; bp->tx_ticks_int = 18; bp->tx_ticks = 80; bp->rx_quick_cons_trip_int = 2; bp->rx_quick_cons_trip = 12; bp->rx_ticks_int = 18; bp->rx_ticks = 18; bp->stats_ticks = USEC_PER_SEC & BNX2_HC_STATS_TICKS_HC_STAT_TICKS; bp->current_interval = BNX2_TIMER_INTERVAL; bp->phy_addr = 1; /* Disable WOL support if we are running on a SERDES chip. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) bnx2_get_5709_media(bp); else if (BNX2_CHIP_BOND(bp) & BNX2_CHIP_BOND_SERDES_BIT) bp->phy_flags |= BNX2_PHY_FLAG_SERDES; bp->phy_port = PORT_TP; if (bp->phy_flags & BNX2_PHY_FLAG_SERDES) { bp->phy_port = PORT_FIBRE; reg = bnx2_shmem_rd(bp, BNX2_SHARED_HW_CFG_CONFIG); if (!(reg & BNX2_SHARED_HW_CFG_GIG_LINK_ON_VAUX)) { bp->flags |= BNX2_FLAG_NO_WOL; bp->wol = 0; } if (BNX2_CHIP(bp) == BNX2_CHIP_5706) { /* Don't do parallel detect on this board because of * some board problems. The link will not go down * if we do parallel detect. */ if (pdev->subsystem_vendor == PCI_VENDOR_ID_HP && pdev->subsystem_device == 0x310c) bp->phy_flags |= BNX2_PHY_FLAG_NO_PARALLEL; } else { bp->phy_addr = 2; if (reg & BNX2_SHARED_HW_CFG_PHY_2_5G) bp->phy_flags |= BNX2_PHY_FLAG_2_5G_CAPABLE; } } else if (BNX2_CHIP(bp) == BNX2_CHIP_5706 || BNX2_CHIP(bp) == BNX2_CHIP_5708) bp->phy_flags |= BNX2_PHY_FLAG_CRC_FIX; else if (BNX2_CHIP(bp) == BNX2_CHIP_5709 && (BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Ax || BNX2_CHIP_REV(bp) == BNX2_CHIP_REV_Bx)) bp->phy_flags |= BNX2_PHY_FLAG_DIS_EARLY_DAC; bp->fw_wr_seq = bnx2_shmem_rd(bp, BNX2_FW_MB) & BNX2_FW_MSG_ACK; bnx2_init_fw_cap(bp); if ((BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_A0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B0) || (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5708_B1) || !(BNX2_RD(bp, BNX2_PCI_CONFIG_3) & BNX2_PCI_CONFIG_3_VAUX_PRESET)) { bp->flags |= BNX2_FLAG_NO_WOL; bp->wol = 0; } if (bp->flags & BNX2_FLAG_NO_WOL) device_set_wakeup_capable(&bp->pdev->dev, false); else device_set_wakeup_enable(&bp->pdev->dev, bp->wol); if (BNX2_CHIP_ID(bp) == BNX2_CHIP_ID_5706_A0) { bp->tx_quick_cons_trip_int = bp->tx_quick_cons_trip; bp->tx_ticks_int = bp->tx_ticks; bp->rx_quick_cons_trip_int = bp->rx_quick_cons_trip; bp->rx_ticks_int = bp->rx_ticks; bp->comp_prod_trip_int = bp->comp_prod_trip; bp->com_ticks_int = bp->com_ticks; bp->cmd_ticks_int = bp->cmd_ticks; } #ifdef CONFIG_PCI_MSI #if defined(__VMKLNX__) /* PR496996: There is some additional setup needed for the P2P * ServerWorks bridge with VID/DID of 0x1666/0x0036 when * 5706 is plugged into an IBM system x3655 server and MSI * is used. Since that workaround cannot be done using * vmklinux api, we are disabling MSI on 5706 to avoid PSOD. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5706) disable_msi = 1; #else /* !defined(__VMKLNX__) */ /* Disable MSI on 5706 if AMD 8132 bridge is found. * * MSI is defined to be 32-bit write. The 5706 does 64-bit MSI writes * with byte enables disabled on the unused 32-bit word. This is legal * but causes problems on the AMD 8132 which will eventually stop * responding after a while. * * AMD believes this incompatibility is unique to the 5706, and * prefers to locally disable MSI rather than globally disabling it. */ if (BNX2_CHIP(bp) == BNX2_CHIP_5706 && disable_msi == 0) { struct pci_dev *amd_8132 = NULL; while ((amd_8132 = pci_get_device(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, amd_8132))) { u8 rev; pci_read_config_byte(amd_8132, PCI_REVISION_ID, &rev); if (rev >= 0x10 && rev <= 0x13) { disable_msi = 1; pci_dev_put(amd_8132); break; } } } #endif /* defined(__VMKLNX__) */ #endif bnx2_set_default_link(bp); bp->req_flow_ctrl = FLOW_CTRL_RX | FLOW_CTRL_TX; init_timer(&bp->timer); bp->timer.expires = RUN_AT(BNX2_TIMER_INTERVAL); bp->timer.data = (unsigned long) bp; bp->timer.function = bnx2_timer; #ifdef BCM_CNIC if (bnx2_shmem_rd(bp, BNX2_ISCSI_INITIATOR) & BNX2_ISCSI_INITIATOR_EN) bp->cnic_eth_dev.max_iscsi_conn = (bnx2_shmem_rd(bp, BNX2_ISCSI_MAX_CONN) & BNX2_ISCSI_MAX_CONN_MASK) >> BNX2_ISCSI_MAX_CONN_SHIFT; bp->version = BNX2_DEV_VER; #if defined(BNX2_INBOX) bp->cnic_probe = bnx2_cnic_probe; #else bp->cnic_probe = bnx2_cnic_probe2; #endif #endif #if (LINUX_VERSION_CODE >= 0x020611) pci_save_state(pdev); #endif return 0; err_out_unmap: if (bp->flags & BNX2_FLAG_AER_ENABLED) { pci_disable_pcie_error_reporting(pdev); bp->flags &= ~BNX2_FLAG_AER_ENABLED; } pci_iounmap(pdev, bp->regview); bp->regview = NULL; err_out_release: pci_release_regions(pdev); err_out_disable: pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); err_out: return rc; } static char * __devinit bnx2_bus_string(struct bnx2 *bp, char *str) { char *s = str; if (bp->flags & BNX2_FLAG_PCIE) { s += sprintf(s, "PCI Express"); } else { s += sprintf(s, "PCI"); if (bp->flags & BNX2_FLAG_PCIX) s += sprintf(s, "-X"); if (bp->flags & BNX2_FLAG_PCI_32BIT) s += sprintf(s, " 32-bit"); else s += sprintf(s, " 64-bit"); s += sprintf(s, " %dMHz", bp->bus_speed_mhz); } return str; } #if !defined(__VMKLNX__) static void bnx2_del_napi(struct bnx2 *bp) #else static void __devinit bnx2_del_napi(struct bnx2 *bp) #endif { #ifdef BNX2_NEW_NAPI int i; for (i = 0; i < bp->irq_nvecs; i++) netif_napi_del(&bp->bnx2_napi[i].napi); #endif } #if !defined(__VMKLNX__) static void bnx2_init_napi(struct bnx2 *bp) #else static void __devinit bnx2_init_napi(struct bnx2 *bp) #endif { int i; for (i = 0; i < bp->irq_nvecs; i++) { struct bnx2_napi *bnapi = &bp->bnx2_napi[i]; #ifdef BNX2_NEW_NAPI int (*poll)(struct napi_struct *, int); if (i == 0) poll = bnx2_poll; else poll = bnx2_poll_msix; netif_napi_add(bp->dev, &bp->bnx2_napi[i].napi, poll, 64); #endif bnapi->bp = bp; } #ifndef BNX2_NEW_NAPI bp->dev->poll = bnx2_poll; bp->dev->weight = 64; #endif } #if defined(HAVE_NET_DEVICE_OPS) || (LINUX_VERSION_CODE >= 0x30000) static const struct net_device_ops bnx2_netdev_ops = { .ndo_open = bnx2_open, .ndo_start_xmit = bnx2_start_xmit, .ndo_stop = bnx2_close, .ndo_get_stats = bnx2_get_stats, .ndo_set_rx_mode = bnx2_set_rx_mode, #if defined(__VMKLNX__) .ndo_do_ioctl = bnx2_vmk_ioctl, #else .ndo_do_ioctl = bnx2_ioctl, #endif .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = bnx2_change_mac_addr, #if defined(__VMKLNX__) .ndo_change_mtu = bnx2_vmk_change_mtu, #else .ndo_change_mtu = bnx2_change_mtu, #endif #ifdef HAVE_FIX_FEATURES .ndo_fix_features = bnx2_fix_features, .ndo_set_features = bnx2_set_features, #endif .ndo_tx_timeout = bnx2_tx_timeout, #if defined(BCM_VLAN) && !defined(NEW_VLAN) .ndo_vlan_rx_register = bnx2_vlan_rx_register, #endif #if defined(HAVE_POLL_CONTROLLER) || defined(CONFIG_NET_POLL_CONTROLLER) .ndo_poll_controller = poll_bnx2, #endif }; #endif static inline void vlan_features_add(struct net_device *dev, unsigned long flags) { #if (LINUX_VERSION_CODE >= 0x2061a) #ifdef BCM_VLAN dev->vlan_features |= flags; #endif #endif } static int __devinit bnx2_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { static int version_printed = 0; struct net_device *dev; struct bnx2 *bp; int rc; char str[40]; DECLARE_MAC_BUF(mac); #if (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000)) || \ (defined(BNX2_ENABLE_NETQUEUE)) static int index = 0; #endif if (version_printed++ == 0) pr_info("%s", version); /* dev zeroed in init_etherdev */ #if (LINUX_VERSION_CODE >= 0x20418) #ifndef BCM_HAVE_MULTI_QUEUE dev = alloc_etherdev(sizeof(*bp)); #else dev = alloc_etherdev_mq(sizeof(*bp), TX_MAX_RINGS); #endif #else dev = init_etherdev(NULL, sizeof(*bp)); #endif if (!dev) return -ENOMEM; rc = bnx2_init_board(pdev, dev); if (rc < 0) goto err_free; #if !defined(HAVE_NET_DEVICE_OPS) && (LINUX_VERSION_CODE < 0x30000) dev->open = bnx2_open; dev->hard_start_xmit = bnx2_start_xmit; dev->stop = bnx2_close; dev->get_stats = bnx2_get_stats; #ifdef BCM_HAVE_SET_RX_MODE dev->set_rx_mode = bnx2_set_rx_mode; #else dev->set_multicast_list = bnx2_set_rx_mode; #endif #if defined(__VMKLNX__) dev->do_ioctl = bnx2_vmk_ioctl; #else dev->do_ioctl = bnx2_ioctl; #endif dev->set_mac_address = bnx2_change_mac_addr; #if defined(__VMKLNX__) dev->change_mtu = bnx2_vmk_change_mtu; #else dev->change_mtu = bnx2_change_mtu; #endif dev->tx_timeout = bnx2_tx_timeout; #ifdef BCM_VLAN dev->vlan_rx_register = bnx2_vlan_rx_register; #if (LINUX_VERSION_CODE < 0x20616) dev->vlan_rx_kill_vid = bnx2_vlan_rx_kill_vid; #endif #endif #if defined(HAVE_POLL_CONTROLLER) || defined(CONFIG_NET_POLL_CONTROLLER) dev->poll_controller = poll_bnx2; #endif #else dev->netdev_ops = &bnx2_netdev_ops; #endif dev->watchdog_timeo = TX_TIMEOUT; dev->ethtool_ops = &bnx2_ethtool_ops; bp = netdev_priv(dev); /* NAPI add must be called in bnx2_init_one() on ESX so that the * proper affinity will be assigned */ bp->msg_enable = debug; #if defined(__VMKLNX__) bnx2_setup_int_mode(bp, disable_msi); bnx2_init_napi(bp); #endif /* (__VMKLNX__)*/ pci_set_drvdata(pdev, dev); memcpy(dev->dev_addr, bp->mac_addr, 6); #ifdef ETHTOOL_GPERMADDR memcpy(dev->perm_addr, bp->mac_addr, 6); #endif #ifdef NETIF_F_IPV6_CSUM dev->features |= NETIF_F_IP_CSUM | NETIF_F_SG; #if defined(NETIF_F_GRO) && defined(BNX2_NEW_NAPI) dev->features |= NETIF_F_GRO; #endif #ifdef NETIF_F_RXHASH dev->features |= NETIF_F_RXHASH; #endif vlan_features_add(dev, NETIF_F_IP_CSUM | NETIF_F_SG); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { dev->features |= NETIF_F_IPV6_CSUM; vlan_features_add(dev, NETIF_F_IPV6_CSUM); } #else dev->features |= NETIF_F_SG; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) dev->features |= NETIF_F_HW_CSUM; else dev->features |= NETIF_F_IP_CSUM; #endif #ifdef BCM_VLAN dev->features |= NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX; #endif #ifdef BCM_TSO dev->features |= NETIF_F_TSO | NETIF_F_TSO_ECN; vlan_features_add(dev, NETIF_F_TSO | NETIF_F_TSO_ECN); if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { dev->features |= NETIF_F_TSO6; vlan_features_add(dev, NETIF_F_TSO6); } #endif #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) if (BNX2_CHIP(bp) == BNX2_CHIP_5706 || BNX2_CHIP(bp) == BNX2_CHIP_5708) { dev->features |= NETIF_F_NO_SCHED; } #endif #if (defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000)) || \ (defined(BNX2_ENABLE_NETQUEUE)) bp->index = index; index++; #endif #if defined(BNX2_ENABLE_NETQUEUE) /* If enabled register the NetQueue callbacks */ if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (BNX2_NETQUEUE_ENABLED(bp)) VMKNETDDI_REGISTER_QUEUEOPS(dev, bnx2_netqueue_ops); } #endif #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) fwdmp_bp_ptr[bp->index] = bp; #endif #if (LINUX_VERSION_CODE >= 0x20418) if ((rc = register_netdev(dev))) { dev_err(&pdev->dev, "Cannot register net device\n"); goto error; } #endif netdev_info(dev, "%s (%c%d) %s found at mem %lx, IRQ %d, " "node addr %s\n", board_info[ent->driver_data].name, ((BNX2_CHIP_ID(bp) & 0xf000) >> 12) + 'A', ((BNX2_CHIP_ID(bp) & 0x0ff0) >> 4), bnx2_bus_string(bp, str), (long)pci_resource_start(pdev, 0), bp->pdev->irq, print_mac(mac, dev->dev_addr)); #if defined(BNX2_ENABLE_NETQUEUE) if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { if (BNX2_NETQUEUE_ENABLED(bp)) { netdev_info(bp->dev, "NetQueue Ops registered [%d]\n", bp->index); } else netdev_info(bp->dev, "NetQueue Ops not registered " "[%d]\n", bp->index); } #endif return 0; error: pci_iounmap(pdev, bp->regview); pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); err_free: #if (LINUX_VERSION_CODE >= 0x20418) free_netdev(dev); #else unregister_netdev(dev); kfree(dev); #endif return rc; } static void __devexit bnx2_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); #if defined(__VMKLNX__) bnx2_del_napi(bp); bnx2_disable_msi(bp); #endif /* !(defined __VMKLNX__) */ unregister_netdev(dev); del_timer_sync(&bp->timer); #if (LINUX_VERSION_CODE >= 0x20616) || defined(__VMKLNX__) cancel_work_sync(&bp->reset_task); #elif (LINUX_VERSION_CODE >= 0x20600) flush_scheduled_work(); #endif pci_iounmap(bp->pdev, bp->regview); kfree(bp->temp_stats_blk); if (bp->flags & BNX2_FLAG_AER_ENABLED) { pci_disable_pcie_error_reporting(pdev); bp->flags &= ~BNX2_FLAG_AER_ENABLED; } #if (LINUX_VERSION_CODE >= 0x20418) free_netdev(dev); #else kfree(dev); #endif pci_disable_pcie_error_reporting(pdev); pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } static int #ifdef SIMPLE_DEV_PM_OPS bnx2_suspend(struct device *device) #else bnx2_suspend(struct pci_dev *pdev, pm_message_t state) #endif { #ifdef SIMPLE_DEV_PM_OPS struct pci_dev *pdev = to_pci_dev(device); #endif struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); #if (LINUX_VERSION_CODE >= 0x2060b) && !defined(SIMPLE_DEV_PM_OPS) /* PCI register 4 needs to be saved whether netif_running() or not. * MSI address and data need to be saved if using MSI and * netif_running(). */ pci_save_state(pdev); #endif if (netif_running(dev)) { #if (LINUX_VERSION_CODE >= 0x20616) || defined(__VMKLNX__) cancel_work_sync(&bp->reset_task); #endif bnx2_netif_stop(bp, true); netif_device_detach(dev); del_timer_sync(&bp->timer); bnx2_shutdown_chip(bp); __bnx2_free_irq(bp); bnx2_free_skbs(bp); } #ifdef SIMPLE_DEV_PM_OPS bnx2_setup_wol(bp); #else #if (LINUX_VERSION_CODE < 0x2060b) bnx2_set_power_state(bp, state); #else bnx2_set_power_state(bp, pci_choose_state(pdev, state)); #endif #endif return 0; } static int #ifdef SIMPLE_DEV_PM_OPS bnx2_resume(struct device *device) #else bnx2_resume(struct pci_dev *pdev) #endif { #ifdef SIMPLE_DEV_PM_OPS struct pci_dev *pdev = to_pci_dev(device); #endif struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); #if (LINUX_VERSION_CODE >= 0x2060b) && !defined(SIMPLE_DEV_PM_OPS) pci_restore_state(pdev); #endif if (!netif_running(dev)) return 0; bnx2_set_power_state(bp, PCI_D0); netif_device_attach(dev); bnx2_request_irq(bp); bnx2_init_nic(bp, 1); bnx2_netif_start(bp, true); return 0; } #ifdef SIMPLE_DEV_PM_OPS #ifdef CONFIG_PM_SLEEP static SIMPLE_DEV_PM_OPS(bnx2_pm_ops, bnx2_suspend, bnx2_resume); #define BNX2_PM_OPS (&bnx2_pm_ops) #else #define BNX2_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ #endif #if !defined(__VMKLNX__) #if (LINUX_VERSION_CODE >= 0x020611) /** * bnx2_io_error_detected - called when PCI error is detected * @pdev: Pointer to PCI device * @state: The current pci connection state * * This function is called after a PCI bus error affecting * this device has been detected. */ static pci_ers_result_t bnx2_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); rtnl_lock(); netif_device_detach(dev); if (state == pci_channel_io_perm_failure) { rtnl_unlock(); return PCI_ERS_RESULT_DISCONNECT; } if (netif_running(dev)) { bnx2_netif_stop(bp, true); del_timer_sync(&bp->timer); bnx2_reset_nic(bp, BNX2_DRV_MSG_CODE_RESET); } pci_disable_device(pdev); rtnl_unlock(); /* Request a slot slot reset. */ return PCI_ERS_RESULT_NEED_RESET; } /** * bnx2_io_slot_reset - called after the pci bus has been reset. * @pdev: Pointer to PCI device * * Restart the card from scratch, as if from a cold-boot. */ static pci_ers_result_t bnx2_io_slot_reset(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); pci_ers_result_t result = PCI_ERS_RESULT_DISCONNECT; int err = 0; rtnl_lock(); if (pci_enable_device(pdev)) { dev_err(&pdev->dev, "Cannot re-enable PCI device after reset\n"); } else { pci_set_master(pdev); pci_restore_state(pdev); pci_save_state(pdev); if (netif_running(dev)) err = bnx2_init_nic(bp, 1); if (!err) result = PCI_ERS_RESULT_RECOVERED; } if (result != PCI_ERS_RESULT_RECOVERED && netif_running(dev)) { bnx2_napi_enable(bp); dev_close(bp->dev); } rtnl_unlock(); if (!(bp->flags & BNX2_FLAG_AER_ENABLED)) return result; err = pci_cleanup_aer_uncorrect_error_status(pdev); if (err) { dev_err(&pdev->dev, "pci_cleanup_aer_uncorrect_error_status failed 0x%0x\n", err); /* non-fatal, continue */ } return result; } /** * bnx2_io_resume - called when traffic can start flowing again. * @pdev: Pointer to PCI device * * This callback is called when the error recovery driver tells us that * its OK to resume normal operation. */ static void bnx2_io_resume(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp = netdev_priv(dev); rtnl_lock(); if (netif_running(dev)) bnx2_netif_start(bp, true); netif_device_attach(dev); rtnl_unlock(); } static struct pci_error_handlers bnx2_err_handler = { .error_detected = bnx2_io_error_detected, .slot_reset = bnx2_io_slot_reset, .resume = bnx2_io_resume, }; #endif #endif #if (LINUX_VERSION_CODE >= 0x02060c) static void bnx2_shutdown(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct bnx2 *bp; if (!dev) return; bp = netdev_priv(dev); if (!bp) return; rtnl_lock(); if (netif_running(dev)) dev_close(bp->dev); if (system_state == SYSTEM_POWER_OFF) bnx2_set_power_state(bp, PCI_D3hot); rtnl_unlock(); } #endif static struct pci_driver bnx2_pci_driver = { .name = DRV_MODULE_NAME, .id_table = bnx2_pci_tbl, .probe = bnx2_init_one, .remove = __devexit_p(bnx2_remove_one), #ifdef SIMPLE_DEV_PM_OPS .driver.pm = BNX2_PM_OPS, #else .suspend = bnx2_suspend, .resume = bnx2_resume, #endif #if !defined(__VMKLNX__) #if (LINUX_VERSION_CODE >= 0x020611) .err_handler = &bnx2_err_handler, #endif #endif #if (LINUX_VERSION_CODE >= 0x02060c) .shutdown = bnx2_shutdown, #endif }; static int __init bnx2_init(void) { int rc = 0; #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) VMK_ReturnStatus status; #endif #if defined(BNX2_ENABLE_NETQUEUE) int i; /* sanity check the force_netq parameter */ for (i = 0; i < BNX2_MAX_NIC; i++) { if((force_netq_param[i] < BNX2_OPTION_UNSET) || (force_netq_param[i] > 7)) { pr_err("bnx2: please use a 'force_netq' " "value between (-1 to 7), " "0 to disable NetQueue, " "-1 to use the default value " "failure at index %d val: %d\n", i, force_netq_param[i]); rc = -EINVAL; } } if(rc != 0) return rc; #endif #if (LINUX_VERSION_CODE < 0x020613) rc = pci_module_init(&bnx2_pci_driver); #else rc = pci_register_driver(&bnx2_pci_driver); #endif #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) #if defined(BNX2_INBOX) if (cnic_register_adapter("bnx2", bnx2_cnic_probe) < 0) { #else /* !defined(BNX2_INBOX) */ if (cnic_register_adapter("bnx2", bnx2_cnic_probe2) < 0) { #endif /* defined(BNX2_INBOX) */ pr_warn("bnx2: Unable to register with CNIC adapter\n"); /* * We won't call pci_unregister_driver(&bnx2_pci_driver) here, * because we still want to retain L2 funtion * even if cnic_register_adapter failed */ } else { bnx2_registered_cnic_adapter = 1; } #endif /* defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 50000) */ #if defined(__VMKLNX__) && (VMWARE_ESX_DDK_VERSION >= 55000) if (!disable_fw_dmp) { fwdmp_va_ptr = kzalloc(BNX2_FWDMP_SIZE, GFP_KERNEL); if (!fwdmp_va_ptr) pr_warn("bnx2: Unable to allocate memory " "for firmware dump handler!\n"); else { status = vmklnx_dump_add_callback(BNX2_DUMPNAME, bnx2_fwdmp_callback, NULL, BNX2_DUMPNAME, &bnx2_fwdmp_dh); if (status != VMK_OK) pr_warn("bnx2: Unable to register firmware " "dump handler (rc = 0x%x!)\n", status); } } #endif return rc; } static void __exit bnx2_cleanup(void) { #if defined(__VMKLNX__) #if (VMWARE_ESX_DDK_VERSION >= 55000) if (bnx2_fwdmp_dh) { VMK_ReturnStatus status; status = vmklnx_dump_delete_callback(bnx2_fwdmp_dh); if (status != VMK_OK) { VMK_ASSERT(0); } else { pr_info("bnx2: firmware dump handler (%p)" " unregistered!\n", bnx2_fwdmp_dh); } } kfree(fwdmp_va_ptr); fwdmp_va_ptr = NULL; #endif #if (VMWARE_ESX_DDK_VERSION >= 50000) if (bnx2_registered_cnic_adapter) { cnic_register_cancel("bnx2"); bnx2_registered_cnic_adapter = 0; } #endif #endif /* defined(__VMKLNX__) */ pci_unregister_driver(&bnx2_pci_driver); } module_init(bnx2_init); module_exit(bnx2_cleanup); #if defined(BNX2_ENABLE_NETQUEUE) #ifdef BNX2_DEBUG static u32 bnx2_read_ctx(struct bnx2 *bp, u32 offset) { int i; if (BNX2_CHIP(bp) != BNX2_CHIP_5709) { BNX2_WR(bp, BNX2_CTX_DATA_ADR, offset); return BNX2_RD(bp, BNX2_CTX_DATA); } BNX2_WR(bp, BNX2_CTX_CTX_CTRL, offset | BNX2_CTX_CTX_CTRL_READ_REQ); for (i = 0; i < 5; i++) { udelay(5); if (BNX2_RD(bp, BNX2_CTX_CTX_CTRL) & BNX2_CTX_CTX_CTRL_READ_REQ) continue; break; } return BNX2_RD(bp, BNX2_CTX_CTX_DATA); } static void dump_ctx(struct bnx2 *bp, u32 cid) { u32 addr = cid * 128; int i; for (i = 0; i < 8; i++) { u32 val, val1, val2, val3; val = bnx2_read_ctx(bp, addr); val1 = bnx2_read_ctx(bp, addr+4); val2 = bnx2_read_ctx(bp, addr+8); val3 = bnx2_read_ctx(bp, addr+0xc); netdev_err(bp->dev, "ctx %08x: %08x %08x %08x %08x\n", addr, val, val1, val2, val3); addr += 0x10; } } #endif #define BNX2_NETQ_WAIT_EVENT_TIMEOUT msecs_to_jiffies(1000) #define L2_KWQ_PAGE_CNT 1 #define L2_KCQ_PAGE_CNT 1 #define L2_KWQE_CNT (BNX2_PAGE_SIZE / sizeof(struct l2_kwqe)) #define L2_KCQE_CNT (BNX2_PAGE_SIZE / sizeof(struct l2_kcqe)) #define MAX_L2_KWQE_CNT (L2_KWQE_CNT - 1) #define MAX_L2_KCQE_CNT (L2_KCQE_CNT - 1) #define MAX_L2_KWQ_IDX ((L2_KWQ_PAGE_CNT * L2_KWQE_CNT) - 1) #define MAX_L2_KCQ_IDX ((L2_KCQ_PAGE_CNT * L2_KCQE_CNT) - 1) #define L2_KWQ_PG(x) (((x) & ~MAX_L2_KWQE_CNT) >> (BNX2_PAGE_BITS - 5)) #define L2_KWQ_IDX(x) ((x) & MAX_L2_KWQE_CNT) #define L2_KCQ_PG(x) (((x) & ~MAX_L2_KCQE_CNT) >> (BNX2_PAGE_BITS - 5)) #define L2_KCQ_IDX(x) ((x) & MAX_L2_KCQE_CNT) /* * krnlq_context definition */ #define L2_KRNLQ_FLAGS 0x00000000 #define L2_KRNLQ_SIZE 0x00000000 #define L2_KRNLQ_TYPE 0x00000000 #define KRNLQ_FLAGS_PG_SZ (0xf<<0) #define KRNLQ_FLAGS_PG_SZ_256 (0<<0) #define KRNLQ_FLAGS_PG_SZ_512 (1<<0) #define KRNLQ_FLAGS_PG_SZ_1K (2<<0) #define KRNLQ_FLAGS_PG_SZ_2K (3<<0) #define KRNLQ_FLAGS_PG_SZ_4K (4<<0) #define KRNLQ_FLAGS_PG_SZ_8K (5<<0) #define KRNLQ_FLAGS_PG_SZ_16K (6<<0) #define KRNLQ_FLAGS_PG_SZ_32K (7<<0) #define KRNLQ_FLAGS_PG_SZ_64K (8<<0) #define KRNLQ_FLAGS_PG_SZ_128K (9<<0) #define KRNLQ_FLAGS_PG_SZ_256K (10<<0) #define KRNLQ_FLAGS_PG_SZ_512K (11<<0) #define KRNLQ_FLAGS_PG_SZ_1M (12<<0) #define KRNLQ_FLAGS_PG_SZ_2M (13<<0) #define KRNLQ_FLAGS_QE_SELF_SEQ (1<<15) #define KRNLQ_SIZE_TYPE_SIZE ((((0x28 + 0x1f) & ~0x1f) / 0x20) << 16) #define KRNLQ_TYPE_TYPE (0xf<<28) #define KRNLQ_TYPE_TYPE_EMPTY (0<<28) #define KRNLQ_TYPE_TYPE_KRNLQ (6<<28) #define L2_KRNLQ_HOST_QIDX 0x00000004 #define L2_KRNLQ_HOST_FW_QIDX 0x00000008 #define L2_KRNLQ_NX_QE_SELF_SEQ 0x0000000c #define L2_KRNLQ_QE_SELF_SEQ_MAX 0x0000000c #define L2_KRNLQ_NX_QE_HADDR_HI 0x00000010 #define L2_KRNLQ_NX_QE_HADDR_LO 0x00000014 #define L2_KRNLQ_PGTBL_PGIDX 0x00000018 #define L2_KRNLQ_NX_PG_QIDX 0x00000018 #define L2_KRNLQ_PGTBL_NPAGES 0x0000001c #define L2_KRNLQ_QIDX_INCR 0x0000001c #define L2_KRNLQ_PGTBL_HADDR_HI 0x00000020 #define L2_KRNLQ_PGTBL_HADDR_LO 0x00000024 #define BNX2_PG_CTX_MAP 0x1a0034 static int bnx2_netq_free_rx_queue(struct net_device *netdev, int index); static int bnx2_netqueue_is_avail(struct bnx2 *bp) { rmb(); return ((BNX2_NETQUEUE_ENABLED(bp)) && (bp->flags & BNX2_FLAG_USING_MSIX) && (BNX2_CHIP(bp) == BNX2_CHIP_5709)); } static inline u32 bnx2_netqueue_kwq_avail(struct bnx2 *bp) { return MAX_L2_KWQ_IDX - ((bp->netq_kwq_prod_idx - bp->netq_kwq_con_idx) & MAX_L2_KWQ_IDX); } static int bnx2_netqueue_submit_kwqes(struct bnx2 *bp, struct l2_kwqe *wqes) { struct l2_kwqe *prod_qe; u16 prod, sw_prod; if (1 > bnx2_netqueue_kwq_avail(bp)) { netdev_warn(bp->dev, "No kwq's available\n"); return -EAGAIN; } prod = bp->netq_kwq_prod_idx; sw_prod = prod & MAX_L2_KWQ_IDX; prod_qe = &bp->netq_kwq[L2_KWQ_PG(sw_prod)][L2_KWQ_IDX(sw_prod)]; memcpy(prod_qe, wqes, sizeof(struct l2_kwqe)); prod++; sw_prod = prod & MAX_L2_KWQ_IDX; bp->netq_kwq_prod_idx = prod; barrier(); BNX2_WR16(bp, bp->netq_kwq_io_addr, bp->netq_kwq_prod_idx); wmb(); mmiowb(); return 0; } static void bnx2_netqueue_free_dma(struct bnx2 *bp, struct netq_dma *dma) { int i; if (dma->pg_arr) { for (i = 0; i < dma->num_pages; i++) { if (dma->pg_arr[i]) { pci_free_consistent(bp->pdev, BNX2_PAGE_SIZE, dma->pg_arr[i], dma->pg_map_arr[i]); dma->pg_arr[i] = NULL; } } } if (dma->pgtbl) { pci_free_consistent(bp->pdev, dma->pgtbl_size, dma->pgtbl, dma->pgtbl_map); dma->pgtbl = NULL; } kfree(dma->pg_arr); dma->pg_arr = NULL; dma->num_pages = 0; } static void bnx2_netqueue_free_resc(struct bnx2 *bp) { bnx2_netqueue_free_dma(bp, &bp->netq_kwq_info); bnx2_netqueue_free_dma(bp, &bp->netq_kcq_info); } static void bnx2_netqueue_setup_page_tbl(struct bnx2 *bp, struct netq_dma *dma) { int i; u32 *page_table = dma->pgtbl; for (i = 0; i < dma->num_pages; i++) { /* Each entry needs to be in big endian format. */ *page_table = (u32) ((u64) dma->pg_map_arr[i] >> 32); page_table++; *page_table = (u32) dma->pg_map_arr[i]; page_table++; } } static int bnx2_netqueue_alloc_dma(struct bnx2 *bp, struct netq_dma *dma, int pages) { int i, size; size = pages * (sizeof(void *) + sizeof(dma_addr_t)); dma->pg_arr = kzalloc(size, GFP_ATOMIC); if (dma->pg_arr == NULL) { netdev_err(bp->dev, "Couldn't alloc dma page array\n"); return -ENOMEM; } dma->pg_map_arr = (dma_addr_t *) (dma->pg_arr + pages); dma->num_pages = pages; for (i = 0; i < pages; i++) { dma->pg_arr[i] = pci_alloc_consistent(bp->pdev, BNX2_PAGE_SIZE, &dma->pg_map_arr[i]); if (dma->pg_arr[i] == NULL) { netdev_err(bp->dev, "Couldn't alloc dma page\n"); goto error; } } dma->pgtbl_size = ((pages * 8) + BNX2_PAGE_SIZE - 1) & ~(BNX2_PAGE_SIZE - 1); dma->pgtbl = pci_alloc_consistent(bp->pdev, dma->pgtbl_size, &dma->pgtbl_map); if (dma->pgtbl == NULL) goto error; bnx2_netqueue_setup_page_tbl(bp, dma); return 0; error: bnx2_netqueue_free_dma(bp, dma); return -ENOMEM; } static int bnx2_netqueue_alloc_resc(struct bnx2 *bp) { int ret; ret = bnx2_netqueue_alloc_dma(bp, &bp->netq_kwq_info, L2_KWQ_PAGE_CNT); if (ret) { netdev_err(bp->dev, "Couldn't alloc space for kwq\n"); goto error; } bp->netq_kwq = (struct l2_kwqe **) bp->netq_kwq_info.pg_arr; ret = bnx2_netqueue_alloc_dma(bp, &bp->netq_kcq_info, L2_KCQ_PAGE_CNT); if (ret) { netdev_err(bp->dev, "Couldn't alloc space for kwq\n"); goto error; } bp->netq_kcq = (struct l2_kcqe **) bp->netq_kcq_info.pg_arr; return 0; error: bnx2_netqueue_free_resc(bp); bp->netq_kwq = NULL; bp->netq_kcq = NULL; return ret; } static void bnx2_init_netqueue_context(struct bnx2 *bp, u32 cid) { u32 cid_addr; int i; cid_addr = GET_CID_ADDR(cid); for (i = 0; i < CTX_SIZE; i += 4) bnx2_ctx_wr(bp, cid_addr, i, 0); } static int bnx2_netqueue_get_kcqes(struct bnx2 *bp, u16 hw_prod, u16 *sw_prod) { u16 i, ri, last; struct l2_kcqe *kcqe; int kcqe_cnt = 0, last_cnt = 0; i = ri = last = *sw_prod; ri &= MAX_L2_KCQ_IDX; while ((i != hw_prod) && (kcqe_cnt < BNX2_NETQ_MAX_COMPLETED_KCQE)) { kcqe = &bp->netq_kcq[L2_KCQ_PG(ri)][L2_KCQ_IDX(ri)]; bp->netq_completed_kcq[kcqe_cnt++] = kcqe; i = (i + 1); ri = i & MAX_L2_KCQ_IDX; if (likely(!(kcqe->flags & L2_KCQE_FLAGS_NEXT))) { last_cnt = kcqe_cnt; last = i; } } *sw_prod = last; return last_cnt; } static void bnx2_service_netq_kcqes(struct bnx2_napi *bnapi, int num_cqes) { struct bnx2 *bp = bnapi->bp; int i, j; i = 0; j = 1; while (num_cqes) { u32 kcqe_op_flag = bp->netq_completed_kcq[i]->opcode; u32 kcqe_layer = bp->netq_completed_kcq[i]->flags & L2_KCQE_FLAGS_LAYER_MASK; while (j < num_cqes) { u32 next_op = bp->netq_completed_kcq[i + j]->opcode; if ((next_op & L2_KCQE_FLAGS_LAYER_MASK) != kcqe_layer) break; j++; } if (kcqe_layer != L2_KCQE_FLAGS_LAYER_MASK_L2) { netdev_err(bp->dev, "Unknown type of KCQE(0x%x)\n", kcqe_op_flag); goto end; } bp->netq_flags = kcqe_op_flag; wake_up(&bp->netq_wait); wmb(); end: num_cqes -= j; i += j; j = 1; } return; } static void bnx2_netqueue_service_bnx2_msix(struct bnx2_napi *bnapi) { struct bnx2 *bp = bnapi->bp; struct status_block *status_blk = bp->bnx2_napi[0].status_blk.msi; u32 status_idx = status_blk->status_idx; u16 hw_prod, sw_prod; int kcqe_cnt; bp->netq_kwq_con_idx = status_blk->status_cmd_consumer_index; hw_prod = status_blk->status_completion_producer_index; sw_prod = bp->netq_kcq_prod_idx; /* Ensure that there is a NetQ kcq avaliable */ if (sw_prod == hw_prod) return; while (sw_prod != hw_prod) { kcqe_cnt = bnx2_netqueue_get_kcqes(bp, hw_prod, &sw_prod); if (kcqe_cnt == 0) goto done; bnx2_service_netq_kcqes(bnapi, kcqe_cnt); /* Tell compiler that status_blk fields can change. */ barrier(); if (status_idx != status_blk->status_idx) { status_idx = status_blk->status_idx; bp->netq_kwq_con_idx = status_blk->status_cmd_consumer_index; hw_prod = status_blk->status_completion_producer_index; } else break; } barrier(); done: BNX2_WR16(bp, bp->netq_kcq_io_addr, sw_prod); bp->netq_kcq_prod_idx = sw_prod; bp->netq_last_status_idx = status_idx; } static void bnx2_close_netqueue(struct bnx2 *bp) { if (bnx2_netqueue_is_avail(bp) && (bp->netq_state == BNX2_NETQ_HW_STARTED)) bnx2_netqueue_flush_all(bp); if (bnx2_netqueue_open_started(bp)) bnx2_netqueue_tx_flush(bp); if (bnx2_netqueue_is_avail(bp)) bnx2_close_netqueue_hw(bp); vmknetddi_queueops_invalidate_state(bp->dev); } static int bnx2_netqueue_open_started(struct bnx2 *bp) { return (((bp->netq_state & BNX2_NETQ_HW_STARTED) == BNX2_NETQ_HW_STARTED) && ((bp->netq_state & BNX2_NETQ_HW_OPENED) == BNX2_NETQ_HW_OPENED)); } static void bnx2_stop_netqueue_hw(struct bnx2 *bp) { u32 val; /* Disable the CP and COM doorbells. These two processors polls the * doorbell for a non zero value before running. This must be done * after setting up the kernel queue contexts. This is for * KQW/KCQ #1. */ val = bnx2_reg_rd_ind(bp, BNX2_CP_SCRATCH + 0x20); val &= ~KWQ1_READY; bnx2_reg_wr_ind(bp, BNX2_CP_SCRATCH + 0x20, val); val = bnx2_reg_rd_ind(bp, BNX2_COM_SCRATCH + 0x20); val &= ~KCQ1_READY; bnx2_reg_wr_ind(bp, BNX2_COM_SCRATCH + 0x20, val); barrier(); bp->netq_state &= ~BNX2_NETQ_HW_STARTED; wmb(); } static void bnx2_force_stop_netqueue(struct bnx2 * bp) { int index; for_each_nondefault_rx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->netq_state & BNX2_NETQ_RX_FILTER_APPLIED) { bnapi->rx_queue_active = FALSE; bnapi->netq_state &= ~BNX2_NETQ_RX_FILTER_APPLIED; netdev_info(bp->dev, "NetQ force removed RX filter: %d\n", index); } if (bnapi->rx_queue_allocated == TRUE) { bnapi->rx_queue_allocated = FALSE; bp->n_rx_queues_allocated--; netdev_info(bp->dev, "Force free NetQ RX Queue %d\n", index); } } for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->tx_queue_allocated == TRUE) { bnapi->tx_queue_allocated = FALSE; bp->n_tx_queues_allocated--; netdev_info(bp->dev, "Force free NetQ TX Queue: 0x%x\n", index); } } } static void bnx2_stop_netqueue(struct bnx2 *bp) { netif_tx_disable(bp->dev); bp->dev->trans_start = jiffies; /* prevent tx timeout */ if (bnx2_netqueue_is_avail(bp) && (bp->netq_state & BNX2_NETQ_HW_STARTED)) { bnx2_netqueue_flush_all(bp); } bnx2_stop_netqueue_hw(bp); } static void bnx2_close_netqueue_hw(struct bnx2 *bp) { bnx2_stop_netqueue_hw(bp); bnx2_netqueue_free_resc(bp); bp->netq_state &= ~BNX2_NETQ_HW_OPENED; wmb(); } static void bnx2_start_netqueue_hw(struct bnx2 *bp) { /* Set the CP and COM doorbells. These two processors polls the * doorbell for a non zero value before running. This must be done * after setting up the kernel queue contexts. This is for * KQW/KCQ 1. */ bnx2_reg_wr_ind(bp, BNX2_CP_SCRATCH + 0x20, KWQ1_READY); bnx2_reg_wr_ind(bp, BNX2_COM_SCRATCH + 0x20, KCQ1_READY); bp->netq_state |= BNX2_NETQ_HW_STARTED; wmb(); } static void bnx2_init_netqueue_hw(struct bnx2 *bp) { u32 val; /* Initialize the bnx2 netqueue structures */ init_waitqueue_head(&bp->netq_wait); val = BNX2_RD(bp, BNX2_MQ_CONFIG); val &= ~BNX2_MQ_CONFIG_KNL_BYP_BLK_SIZE; if (BNX2_PAGE_BITS > 12) val |= (12 - 8) << 4; else val |= (BNX2_PAGE_BITS - 8) << 4; BNX2_WR(bp, BNX2_MQ_CONFIG, val); BNX2_WR(bp, BNX2_HC_COMP_PROD_TRIP, (2 << 16) | 8); BNX2_WR(bp, BNX2_HC_COM_TICKS, (64 << 16) | 220); BNX2_WR(bp, BNX2_HC_CMD_TICKS, (64 << 16) | 220); bnx2_init_netqueue_context(bp, NETQUEUE_KWQ_CID); bnx2_init_netqueue_context(bp, NETQUEUE_KCQ_CID); bp->netq_kwq_cid_addr = GET_CID_ADDR(NETQUEUE_KWQ_CID); bp->netq_kwq_io_addr = MB_GET_CID_ADDR(NETQUEUE_KWQ_CID) + L2_KRNLQ_HOST_QIDX; bp->netq_kwq_prod_idx = 0; bp->netq_kwq_con_idx = 0; /* Initialize the kernel work queue context. */ val = KRNLQ_TYPE_TYPE_KRNLQ | KRNLQ_SIZE_TYPE_SIZE | (BNX2_PAGE_BITS - 8) | KRNLQ_FLAGS_QE_SELF_SEQ; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_TYPE, val); val = (BNX2_PAGE_SIZE / sizeof(struct l2_kwqe) - 1) << 16; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_QE_SELF_SEQ_MAX, val); val = ((BNX2_PAGE_SIZE / sizeof(struct l2_kwqe)) << 16) | L2_KWQ_PAGE_CNT; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_PGTBL_NPAGES, val); val = (u32) ((u64) bp->netq_kwq_info.pgtbl_map >> 32); bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_PGTBL_HADDR_HI, val); val = (u32) bp->netq_kwq_info.pgtbl_map; bnx2_ctx_wr(bp, bp->netq_kwq_cid_addr, L2_KRNLQ_PGTBL_HADDR_LO, val); bp->netq_kcq_cid_addr = GET_CID_ADDR(NETQUEUE_KCQ_CID); bp->netq_kcq_io_addr = MB_GET_CID_ADDR(NETQUEUE_KCQ_CID) + L2_KRNLQ_HOST_QIDX; bp->netq_kcq_prod_idx = 0; /* Initialize the kernel complete queue context. */ val = KRNLQ_TYPE_TYPE_KRNLQ | KRNLQ_SIZE_TYPE_SIZE | (BNX2_PAGE_BITS - 8) | KRNLQ_FLAGS_QE_SELF_SEQ; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_TYPE, val); val = (BNX2_PAGE_SIZE / sizeof(struct l2_kcqe) - 1) << 16; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_QE_SELF_SEQ_MAX, val); val = ((BNX2_PAGE_SIZE / sizeof(struct l2_kcqe)) << 16)|L2_KCQ_PAGE_CNT; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_PGTBL_NPAGES, val); val = (u32) ((u64) bp->netq_kcq_info.pgtbl_map >> 32); bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_PGTBL_HADDR_HI, val); val = (u32) bp->netq_kcq_info.pgtbl_map; bnx2_ctx_wr(bp, bp->netq_kcq_cid_addr, L2_KRNLQ_PGTBL_HADDR_LO, val); /* Enable Commnad Scheduler notification when we write to the * host producer index of the kernel contexts. */ BNX2_WR(bp, BNX2_MQ_KNL_CMD_MASK1, 2); /* Enable Command Scheduler notification when we write to either * the Send Queue or Receive Queue producer indexes of the kernel * bypass contexts. */ BNX2_WR(bp, BNX2_MQ_KNL_BYP_CMD_MASK1, 7); BNX2_WR(bp, BNX2_MQ_KNL_BYP_WRITE_MASK1, 7); /* Notify COM when the driver post an application buffer. */ BNX2_WR(bp, BNX2_MQ_KNL_RX_V2P_MASK2, 0x2000); barrier(); } static void bnx2_start_netqueue(struct bnx2 *bp) { bnx2_init_netqueue_hw(bp); bnx2_start_netqueue_hw(bp); } static int bnx2_open_netqueue_hw(struct bnx2 *bp) { int err; err = bnx2_netqueue_alloc_resc(bp); if (err != 0) { netdev_err(bp->dev, "Couldn't allocate netq resources\n"); return err; } bnx2_start_netqueue(bp); bp->netq_state |= BNX2_NETQ_HW_OPENED; wmb(); netdev_info(bp->dev, "NetQueue hardware support is enabled\n"); return 0; } static int bnx2_netq_get_netqueue_features(vmknetddi_queueop_get_features_args_t *args) { args->features = VMKNETDDI_QUEUEOPS_FEATURE_NONE; args->features |= VMKNETDDI_QUEUEOPS_FEATURE_RXQUEUES; args->features |= VMKNETDDI_QUEUEOPS_FEATURE_TXQUEUES; return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_get_queue_count(vmknetddi_queueop_get_queue_count_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); /* workaround for packets duplicated */ if (bp->num_tx_rings + bp->num_rx_rings > 1) bp->netq_enabled = 1; if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_RX) { args->count = max_t(u16, bp->num_rx_rings - 1, 0); netdev_info(args->netdev, "Using %d RX NetQ rings\n", args->count); return VMKNETDDI_QUEUEOPS_OK; } else if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_TX) { args->count = max_t(u16, bp->num_tx_rings - 1, 0); netdev_info(args->netdev, "Using %d TX NetQ rings\n", args->count); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_err(args->netdev, "queue count: invalid queue type " "0x%x\n", args->type); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_get_filter_count(vmknetddi_queueop_get_filter_count_args_t *args) { /* Only support 1 Mac filter per queue */ args->count = 1; return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_alloc_rx_queue(struct bnx2 *bp, struct bnx2_napi *bnapi, int index) { /* We need to count the default ring as part of the number of RX rings avaliable */ if (bp->n_rx_queues_allocated >= (bp->num_rx_rings - 1)) { netdev_warn(bp->dev, "Unable to allocate RX NetQueue n_rx_queues_allocated(%d) >= Num NetQ's(%d)\n", bp->n_rx_queues_allocated, (bp->num_rx_rings - 1)); return VMKNETDDI_QUEUEOPS_ERR; } if((bp->netq_state & BNX2_NETQ_HW_STARTED) != BNX2_NETQ_HW_STARTED) { netdev_warn(bp->dev, "NetQueue hardware not running\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnapi->rx_queue_allocated) { int rc; struct l2_kwqe_vm_alloc_rx_queue kwqe_alloc_rx; /* Prepare the kwqe to be passed to the firmware */ memset(&kwqe_alloc_rx, 0, sizeof(kwqe_alloc_rx)); kwqe_alloc_rx.kwqe_flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_alloc_rx.kwqe_opcode = L2_KWQE_OPCODE_VALUE_VM_ALLOC_RX_QUEUE; kwqe_alloc_rx.queue_type = L2_NET_QUEUE; kwqe_alloc_rx.qid = BNX2_DRV_TO_FW_QUEUE_ID(index); rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *)&kwqe_alloc_rx); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit alloc rx kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_ALLOC_RX_QUEUE), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_allocated = TRUE; netdev_info(bp->dev, "RX NetQ allocated on %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_info(bp->dev, "Timeout RX NetQ allocate on %d\n", index); return VMKNETDDI_QUEUEOPS_ERR; } } netdev_info(bp->dev, "No RX NetQueues avaliable!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_rx_queue_vmk(struct net_device *netdev, vmknetddi_queueops_queueid_t *p_qid, struct napi_struct **napi_p) { int index; struct bnx2 *bp = netdev_priv(netdev); /* We need to count the default ring as part of the number of RX rings avaliable */ if (bp->n_rx_queues_allocated >= (bp->num_rx_rings - 1)) { netdev_warn(bp->dev, "Unable to allocate RX NetQueue n_rx_queues_allocated(%d) >= Num NetQ's(%d)\n", bp->n_rx_queues_allocated, (bp->num_rx_rings - 1)); return VMKNETDDI_QUEUEOPS_ERR; } for_each_nondefault_rx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if (!bnapi->rx_queue_allocated) { int rc; rc = bnx2_netq_alloc_rx_queue(bp, bnapi, index); if (rc == VMKNETDDI_QUEUEOPS_OK) { bp->n_rx_queues_allocated++; *p_qid = VMKNETDDI_QUEUEOPS_MK_RX_QUEUEID(index); *napi_p = &bnapi->napi; return VMKNETDDI_QUEUEOPS_OK; } else return VMKNETDDI_QUEUEOPS_ERR; } } netdev_err(bp->dev, "No free RX NetQueues found!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_tx_queue(struct bnx2 *bp, struct bnx2_napi *bnapi, int index) { if (bp->n_tx_queues_allocated >= (bp->num_tx_rings - 1)) return VMKNETDDI_QUEUEOPS_ERR; if (!bnapi->tx_queue_allocated) { bnapi->tx_queue_allocated = TRUE; bp->n_tx_queues_allocated++; netdev_info(bp->dev, "TX NetQ allocated on %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } netdev_err(bp->dev, "tx queue already allocated!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_tx_queue_vmk(struct net_device *netdev, vmknetddi_queueops_queueid_t *p_qid, u16 *queue_mapping) { int index; struct bnx2 *bp = netdev_priv(netdev); if (bp->n_tx_queues_allocated >= (bp->num_tx_rings - 1)) return VMKNETDDI_QUEUEOPS_ERR; for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if (!bnapi->tx_queue_allocated) { int rc = bnx2_netq_alloc_tx_queue(bp, bnapi, index); *p_qid = VMKNETDDI_QUEUEOPS_MK_TX_QUEUEID(index); *queue_mapping = index; return rc; } } netdev_err(bp->dev, "no free tx queues found!\n"); return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_alloc_queue(vmknetddi_queueop_alloc_queue_args_t *args) { struct net_device *netdev = args->netdev; struct bnx2 *bp = netdev_priv(netdev); if(bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to alloc NetQueue on failed reset " "device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_TX) { return bnx2_netq_alloc_tx_queue_vmk(args->netdev, &args->queueid, &args->queue_mapping); } else if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_RX) { return bnx2_netq_alloc_rx_queue_vmk(args->netdev, &args->queueid, &args->napi); } else { netdev_err(bp->dev, "Trying to alloc invalid queue type: %x\n", args->type); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_free_tx_queue(struct net_device *netdev, vmknetddi_queueops_queueid_t qid) { struct bnx2 *bp = netdev_priv(netdev); struct bnx2_napi *bnapi; u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(qid); if (index > bp->num_tx_rings) return VMKNETDDI_QUEUEOPS_ERR; bnapi = &bp->bnx2_napi[index]; if (bnapi->tx_queue_allocated != TRUE) return VMKNETDDI_QUEUEOPS_ERR; bnapi->tx_queue_allocated = FALSE; bp->n_tx_queues_allocated--; netdev_info(bp->dev, "Free NetQ TX Queue: 0x%x\n", index); return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_free_rx_queue(struct net_device *netdev, int index) { int rc; struct bnx2 *bp = netdev_priv(netdev); struct bnx2_napi *bnapi; struct l2_kwqe_vm_free_rx_queue kwqe_free_rx; if (index > bp->num_rx_rings) { netdev_err(bp->dev, "Error Free NetQ RX Queue: " "index(%d) > bp->num_rx_rings(%d)\n", index, bp->num_rx_rings); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (bnapi->rx_queue_allocated != TRUE) { netdev_warn(bp->dev, "NetQ RX Queue %d already freed\n", index); return VMKNETDDI_QUEUEOPS_OK; } memset(&kwqe_free_rx, 0, sizeof(kwqe_free_rx)); kwqe_free_rx.flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_free_rx.opcode = L2_KWQE_OPCODE_VALUE_VM_FREE_RX_QUEUE; kwqe_free_rx.qid = BNX2_DRV_TO_FW_QUEUE_ID(index); kwqe_free_rx.queue_type = L2_NET_QUEUE; rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *) &kwqe_free_rx); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit free rx kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_FREE_RX_QUEUE), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_allocated = FALSE; bp->n_rx_queues_allocated--; netdev_info(bp->dev, "Free NetQ RX Queue %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_err(bp->dev, "Timeout free NetQ RX Queue %d\n", index); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_free_queue(vmknetddi_queueop_free_queue_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); if(bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to free NetQueue on failed reset " "device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (VMKNETDDI_QUEUEOPS_IS_TX_QUEUEID(args->queueid)) { return bnx2_netq_free_tx_queue(args->netdev, args->queueid); } else if (VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID(args->queueid)) { return bnx2_netq_free_rx_queue(args->netdev, VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid)); } else { netdev_err(bp->dev, "free netq: invalid queue type: 0x%x\n", args->queueid); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_get_queue_vector(vmknetddi_queueop_get_queue_vector_args_t *args) { int qid; struct bnx2 *bp = netdev_priv(args->netdev); qid = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); if (qid > bp->num_rx_rings) return VMKNETDDI_QUEUEOPS_ERR; #ifdef CONFIG_PCI_MSI args->vector = bp->bnx2_napi[qid].int_num; #endif return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_get_default_queue(vmknetddi_queueop_get_default_queue_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_RX) { args->queueid = VMKNETDDI_QUEUEOPS_MK_RX_QUEUEID(0); args->napi = &bp->bnx2_napi[0].napi; return VMKNETDDI_QUEUEOPS_OK; } else if (args->type == VMKNETDDI_QUEUEOPS_QUEUE_TYPE_TX) { args->queueid = VMKNETDDI_QUEUEOPS_MK_TX_QUEUEID(0); args->queue_mapping = 0; return VMKNETDDI_QUEUEOPS_OK; } else return VMKNETDDI_QUEUEOPS_ERR; } static int bnx2_netq_remove_rx_filter(struct bnx2 *bp, int index) { u16 fw_qid = BNX2_DRV_TO_FW_QUEUE_ID(index); struct bnx2_napi *bnapi; struct l2_kwqe_vm_remove_rx_filter kwqe_remove_rx_filter; int rc; if(bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to remove RX filter NetQueue on " "failed reset device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_err(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (fw_qid > bp->num_rx_rings) { netdev_info(bp->dev, "Free RX Filter NetQ: failed " "qid(%d) > bp->num_rx_rings(%d)\n", index, bp->num_rx_rings); return VMKNETDDI_QUEUEOPS_ERR; } memset(&kwqe_remove_rx_filter, 0, sizeof(kwqe_remove_rx_filter)); kwqe_remove_rx_filter.flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_remove_rx_filter.opcode = L2_KWQE_OPCODE_VALUE_VM_REMOVE_RX_FILTER; kwqe_remove_rx_filter.filter_type = L2_VM_FILTER_MAC; kwqe_remove_rx_filter.qid = fw_qid; kwqe_remove_rx_filter.filter_id = fw_qid + BNX2_START_FILTER_ID; rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *) &kwqe_remove_rx_filter); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit rx filter kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_REMOVE_RX_FILTER), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_active = FALSE; bnapi->netq_state &= ~BNX2_NETQ_RX_FILTER_APPLIED; netdev_info(bp->dev, "NetQ remove RX filter: %d\n", index); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_warn(bp->dev, "Timeout NetQ remove RX filter: %d\n", index); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_remove_rx_filter_vmk(vmknetddi_queueop_remove_rx_filter_args_t *args) { struct bnx2 *bp = netdev_priv(args->netdev); u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); struct bnx2_napi *bnapi; if (bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to remove RX filter NetQueue on " "failed reset device\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (!VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID(args->queueid)) { netdev_err(bp->dev, "!VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID: " "qid: %d)\n", index); return VMKNETDDI_QUEUEOPS_ERR; } if (index > bp->num_rx_rings) { netdev_err(bp->dev, "qid(%d) > bp->num_rx_rings(%d)\n", index, bp->num_rx_rings); return VMKNETDDI_QUEUEOPS_ERR; } /* Only support one Mac filter per queue */ if (bnapi->rx_queue_active == 0) { netdev_info(bp->dev, "bnapi->rx_queue_active(%d) == 0\n", bnapi->rx_queue_active); return VMKNETDDI_QUEUEOPS_ERR; } return bnx2_netq_remove_rx_filter(bp, index); } static int bnx2_netq_apply_rx_filter(struct bnx2 *bp, struct bnx2_napi *bnapi, int index) { u16 fw_queueid = BNX2_DRV_TO_FW_QUEUE_ID(index); struct l2_kwqe_vm_set_rx_filter kwqe_set_rx_filter; int rc; DECLARE_MAC_BUF(mac); if (bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to apply RX filter NetQueue on %d" "failed reset device\n", index); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (bnapi->rx_queue_active == TRUE || !bnapi->rx_queue_allocated) { netdev_err(bp->dev, "apply filter: RX NetQ %d already active" "bnapi->rx_queue_active(%d) || " "!bnapi->rx_queue_allocated(%d)\n", index, bnapi->rx_queue_active, bnapi->rx_queue_allocated); return VMKNETDDI_QUEUEOPS_ERR; } bnx2_set_mac_addr(bp, bnapi->mac_filter_addr, fw_queueid + QID_TO_PM_OFFSET); memset(&kwqe_set_rx_filter, 0, sizeof(kwqe_set_rx_filter)); kwqe_set_rx_filter.flags = L2_KWQE_FLAGS_LAYER_MASK_L2; kwqe_set_rx_filter.opcode = L2_KWQE_OPCODE_VALUE_VM_SET_RX_FILTER; kwqe_set_rx_filter.filter_id = fw_queueid + BNX2_START_FILTER_ID; #if defined(__LITTLE_ENDIAN) memcpy(&kwqe_set_rx_filter.mac_addr_hi, bnapi->mac_filter_addr, 2); memcpy(&kwqe_set_rx_filter.mac_addr_lo, bnapi->mac_filter_addr + 2, 4); #else memcpy(&kwqe_set_rx_filter.mac_addr, bnapi->mac_filter_addr, 6); #endif if (bnapi->class == VMKNETDDI_QUEUEOPS_FILTER_MACADDR) { kwqe_set_rx_filter.filter_type = L2_VM_FILTER_MAC; } else { kwqe_set_rx_filter.filter_type = L2_VM_FILTER_MAC_VLAN; kwqe_set_rx_filter.vlan = bnapi->vlan_id; } kwqe_set_rx_filter.qid = fw_queueid; rc = bnx2_netqueue_submit_kwqes(bp, (struct l2_kwqe *) &kwqe_set_rx_filter); if (rc != 0) { netdev_err(bp->dev, "Couldn't submit rx filter kwqe\n"); return VMKNETDDI_QUEUEOPS_ERR; } bp->netq_flags = 0; wmb(); rc = wait_event_timeout(bp->netq_wait, (bp->netq_flags & L2_KCQE_OPCODE_VALUE_VM_SET_RX_FILTER), BNX2_NETQ_WAIT_EVENT_TIMEOUT); if (rc != 0) { bnapi->rx_queue_active = TRUE; bnapi->netq_state |= BNX2_NETQ_RX_FILTER_APPLIED; netdev_info(bp->dev, "NetQ set RX Filter: %d [%s %d]\n", index, print_mac(mac, bnapi->mac_filter_addr), bnapi->vlan_id); return VMKNETDDI_QUEUEOPS_OK; } else { netdev_info(bp->dev, "Timeout submitting NetQ set RX Filter: " "%d [%s]\n", index, print_mac(mac, bnapi->mac_filter_addr)); return VMKNETDDI_QUEUEOPS_ERR; } } static int bnx2_netq_apply_rx_filter_vmk(vmknetddi_queueop_apply_rx_filter_args_t *args) { u8 *macaddr; struct bnx2_napi *bnapi; struct bnx2 *bp = netdev_priv(args->netdev); u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); vmknetddi_queueops_filter_class_t class; DECLARE_MAC_BUF(mac); if (bp->reset_failed == 1) { netdev_err(bp->dev, "Trying to apply RX filter NetQueue on %d" "failed reset device\n", index); return VMKNETDDI_QUEUEOPS_ERR; } if (!bnx2_netqueue_open_started(bp)) { netdev_warn(bp->dev, "NetQueue hardware not running yet\n"); return VMKNETDDI_QUEUEOPS_ERR; } if (!VMKNETDDI_QUEUEOPS_IS_RX_QUEUEID(args->queueid)) { netdev_err(bp->dev, "invalid NetQ RX ID: %x\n", args->queueid); return VMKNETDDI_QUEUEOPS_ERR; } class = vmknetddi_queueops_get_filter_class(&args->filter); if ((class != VMKNETDDI_QUEUEOPS_FILTER_MACADDR) && (class != VMKNETDDI_QUEUEOPS_FILTER_VLANMACADDR)) { netdev_err(bp->dev, "recieved invalid RX NetQ filter: %x\n", class); return VMKNETDDI_QUEUEOPS_ERR; } if (index > bp->num_rx_rings) { netdev_err(bp->dev, "applying filter with invalid " "RX NetQ %d ID\n", index); return VMKNETDDI_QUEUEOPS_ERR; } bnapi = &bp->bnx2_napi[index]; if (bnapi->rx_queue_active || !bnapi->rx_queue_allocated) { netdev_err(bp->dev, "RX NetQ %d already active\n", index); return VMKNETDDI_QUEUEOPS_ERR; } macaddr = (void *)vmknetddi_queueops_get_filter_macaddr(&args->filter); memcpy(bnapi->mac_filter_addr, macaddr, ETH_ALEN); bnapi->vlan_id = vmknetddi_queueops_get_filter_vlanid(&args->filter); bnapi->class = class; /* Apply RX filter code here */ args->filterid = VMKNETDDI_QUEUEOPS_MK_FILTERID(index); return bnx2_netq_apply_rx_filter(bp, bnapi, index); } static int bnx2_netq_get_queue_stats(vmknetddi_queueop_get_stats_args_t *args) { u16 index = VMKNETDDI_QUEUEOPS_QUEUEID_VAL(args->queueid); struct bnx2_napi *bnapi; struct bnx2 *bp = netdev_priv(args->netdev); bnapi = &bp->bnx2_napi[index]; args->stats = &bnapi->stats; return VMKNETDDI_QUEUEOPS_OK; } static int bnx2_netq_get_netqueue_version(vmknetddi_queueop_get_version_args_t *args) { return vmknetddi_queueops_version(args); } static void bnx2_netqueue_flush_all(struct bnx2 *bp) { int index; u16 num_tx = 0, num_rx = 0; netdev_info(bp->dev, "Flushing NetQueues\n"); mutex_lock(&bp->netq_lock); for_each_nondefault_rx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->netq_state & BNX2_NETQ_RX_FILTER_APPLIED) { int rc = bnx2_netq_remove_rx_filter(bp, index); if (rc == VMKNETDDI_QUEUEOPS_ERR) { netdev_err(bp->dev, "could not remove RX " "filter during flush\n"); } if(bnapi->rx_queue_allocated == TRUE) { rc = bnx2_netq_free_rx_queue(bp->dev, index); if (rc == VMKNETDDI_QUEUEOPS_OK) { num_rx++; } else { netdev_err(bp->dev, "couldn't free RX " "queue %d during " "flush\n", index); } } } } for_each_nondefault_tx_queue(bp, index) { struct bnx2_napi *bnapi = &bp->bnx2_napi[index]; if(bnapi->tx_queue_allocated == TRUE) { bnx2_netq_free_tx_queue(bp->dev, index); } num_tx++; } mutex_unlock(&bp->netq_lock); netdev_info(bp->dev, "Flushed NetQueues: rx: %d tx: %d\n", num_rx, num_tx); } static int bnx2_netqueue_ops(vmknetddi_queueops_op_t op, void *args) { int rc; struct bnx2 *bp; if (op == VMKNETDDI_QUEUEOPS_OP_GET_VERSION) return bnx2_netq_get_netqueue_version( (vmknetddi_queueop_get_version_args_t *)args); bp = netdev_priv(((vmknetddi_queueop_get_features_args_t *)args)->netdev); if (!bnx2_netqueue_is_avail(bp) || !bnx2_netqueue_open_started(bp)) return VMKNETDDI_QUEUEOPS_ERR; mutex_lock(&bp->netq_lock); switch (op) { case VMKNETDDI_QUEUEOPS_OP_GET_FEATURES: rc = bnx2_netq_get_netqueue_features( (vmknetddi_queueop_get_features_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_QUEUE_COUNT: rc = bnx2_netq_get_queue_count( (vmknetddi_queueop_get_queue_count_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_FILTER_COUNT: rc = bnx2_netq_get_filter_count( (vmknetddi_queueop_get_filter_count_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_ALLOC_QUEUE: rc = bnx2_netq_alloc_queue( (vmknetddi_queueop_alloc_queue_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_FREE_QUEUE: rc = bnx2_netq_free_queue( (vmknetddi_queueop_free_queue_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_QUEUE_VECTOR: rc = bnx2_netq_get_queue_vector( (vmknetddi_queueop_get_queue_vector_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_DEFAULT_QUEUE: rc = bnx2_netq_get_default_queue( (vmknetddi_queueop_get_default_queue_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_APPLY_RX_FILTER: rc = bnx2_netq_apply_rx_filter_vmk( (vmknetddi_queueop_apply_rx_filter_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_REMOVE_RX_FILTER: rc = bnx2_netq_remove_rx_filter_vmk( (vmknetddi_queueop_remove_rx_filter_args_t *)args); break; case VMKNETDDI_QUEUEOPS_OP_GET_STATS: rc = bnx2_netq_get_queue_stats( (vmknetddi_queueop_get_stats_args_t *)args); break; /* Unsupported for now */ case VMKNETDDI_QUEUEOPS_OP_SET_TX_PRIORITY: rc = VMKNETDDI_QUEUEOPS_ERR; break; #if (VMWARE_ESX_DDK_VERSION >= 41000) case VMKNETDDI_QUEUEOPS_OP_ALLOC_QUEUE_WITH_ATTR: rc = VMKNETDDI_QUEUEOPS_ERR; break; case VMKNETDDI_QUEUEOPS_OP_GET_SUPPORTED_FEAT: rc = VMKNETDDI_QUEUEOPS_ERR; break; #if (VMWARE_ESX_DDK_VERSION >= 50000) case VMKNETDDI_QUEUEOPS_OP_GET_SUPPORTED_FILTER_CLASS: rc = VMKNETDDI_QUEUEOPS_ERR; break; #endif #endif default: netdev_warn(bp->dev, "Unhandled NETQUEUE OP %d\n", op); rc = VMKNETDDI_QUEUEOPS_ERR; } mutex_unlock(&bp->netq_lock); return rc; } #endif /* defined(BNX2_ENABLE_NETQUEUE) */ #if defined(__VMKLNX__) #if (VMWARE_ESX_DDK_VERSION >= 55000) static void bnx2_dump(struct bnx2 *bp, u32 reg_offset, u32 *dest_addr, u32 word_cnt) { u32 *dst = dest_addr; u32 i; for (i = 0; i < word_cnt; i++) { *dst++ = BNX2_RD(bp, reg_offset); reg_offset += 4; } } static void bnx2_dump_ind(struct bnx2 *bp, u32 reg_offset, u32 *dest_addr, u32 word_cnt) { u32 *dst = dest_addr; u32 i; for (i = 0; i < word_cnt; i++) { *dst++ = bnx2_reg_rd_ind(bp, reg_offset); reg_offset += 4; } } #define BNX2_CPU_ENTRY(offset, size) { offset, size } static const struct cpu_data_reg { u32 off; u32 size; } cpu_arr[] = { BNX2_CPU_ENTRY(0, 3), BNX2_CPU_ENTRY(0x1c, 8), BNX2_CPU_ENTRY(0x48, 1), BNX2_CPU_ENTRY(0x200, 32), }; static u32 * dump_cpu_state(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 reg, i; u32 cpu_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (reg = BNX2_TXP_CPU_MODE; reg <= BNX2_CP_CPU_MODE; reg += 0x40000) { /* make sure these are 64-bit align */ for (i = 0; i < ARRAY_SIZE(cpu_arr); i++) cpu_size += cpu_arr[i].size * 4; } if ((dmp->fw_hdr.dmp_size + cpu_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_CPU_DUMP; *dst++ = cpu_size; for (reg = BNX2_TXP_CPU_MODE; reg <= BNX2_CP_CPU_MODE; reg += 0x40000) { /* make sure these are 64-bit align */ for (i = 0; i < ARRAY_SIZE(cpu_arr); i++) { bnx2_dump_ind(bp, reg + cpu_arr[i].off, dst, cpu_arr[i].size); dst += cpu_arr[i].size; } } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += cpu_size + BNX2_FWDMP_MARKER_SZ; return dst; } #define BNX2_FTQ_DATA_ENTRY(offset, cmdoff, size, dataoff) { BNX2_##offset, \ BNX2_##cmdoff, \ size, \ BNX2_##dataoff } static const struct ftq_data_reg { u32 off; u32 cmdoff; u32 size; u32 dataoff; } ftq_data_arr[] = { BNX2_FTQ_DATA_ENTRY(TSCH_FTQ_CMD, TSCH_FTQ_CMD_RD_DATA, 2, TSCH_TSCHQ), BNX2_FTQ_DATA_ENTRY(TBDR_FTQ_CMD, TBDR_FTQ_CMD_RD_DATA, 5, TBDR_TBDRQ), BNX2_FTQ_DATA_ENTRY(TXP_FTQ_CMD, TXP_FTQ_CMD_RD_DATA, 5, TXP_TXPQ), BNX2_FTQ_DATA_ENTRY(TDMA_FTQ_CMD, TDMA_FTQ_CMD_RD_DATA, 12, TDMA_TDMAQ), BNX2_FTQ_DATA_ENTRY(TPAT_FTQ_CMD, TPAT_FTQ_CMD_RD_DATA, 5, TPAT_TPATQ), BNX2_FTQ_DATA_ENTRY(TAS_FTQ_CMD, TAS_FTQ_CMD_RD_DATA, 4, TPAT_TPATQ), BNX2_FTQ_DATA_ENTRY(RLUP_FTQ_COMMAND, RLUP_FTQ_CMD_RD_DATA, 30, RLUP_RLUPQ), BNX2_FTQ_DATA_ENTRY(RXP_FTQ_CMD, RXP_FTQ_CMD_RD_DATA, 13, RXP_RXPQ), BNX2_FTQ_DATA_ENTRY(RXP_CFTQ_CMD, RXP_CFTQ_CMD_RD_DATA, 4, RXP_RXPCQ), BNX2_FTQ_DATA_ENTRY(RV2P_MFTQ_CMD, RV2P_MFTQ_CMD_RD_DATA, 1, RV2P_RV2PMQ), BNX2_FTQ_DATA_ENTRY(RV2P_TFTQ_CMD, RV2P_TFTQ_CMD_RD_DATA, 1, RV2P_RV2PTQ), BNX2_FTQ_DATA_ENTRY(RV2P_PFTQ_CMD, RV2P_PFTQ_CMD_RD_DATA, 13, RV2P_RV2PPQ), BNX2_FTQ_DATA_ENTRY(RDMA_FTQ_COMMAND, RDMA_FTQ_CMD_RD_DATA, 13, RDMA_RDMAQ), BNX2_FTQ_DATA_ENTRY(COM_COMQ_FTQ_CMD, COM_COMQ_FTQ_CMD_RD_DATA, 10, COM_COMQ), BNX2_FTQ_DATA_ENTRY(COM_COMTQ_FTQ_CMD, COM_COMTQ_FTQ_CMD_RD_DATA, 3, COM_COMTQ), BNX2_FTQ_DATA_ENTRY(COM_COMXQ_FTQ_CMD, COM_COMXQ_FTQ_CMD_RD_DATA, 4, COM_COMXQ), BNX2_FTQ_DATA_ENTRY(CP_CPQ_FTQ_CMD, CP_CPQ_FTQ_CMD_RD_DATA, 1, CP_CPQ), BNX2_FTQ_DATA_ENTRY(CSCH_CH_FTQ_COMMAND, CSCH_CH_FTQ_CMD_RD_DATA, 2, CSCH_CSQ), BNX2_FTQ_DATA_ENTRY(MCP_MCPQ_FTQ_CMD, MCP_MCPQ_FTQ_CMD_RD_DATA, 5, MCP_MCPQ), }; static u32 * dump_ftq_ctrl_info(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { int i; u32 ftq_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (i = 0; i < ARRAY_SIZE(ftq_arr); i++) ftq_size += 4; for (i = 0; i < ARRAY_SIZE(ftq_data_arr); i++) ftq_size += ftq_data_arr[i].size * 4; if ((dmp->fw_hdr.dmp_size + ftq_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_FTQ_DUMP; *dst++ = ftq_size; for (i = 0; i < ARRAY_SIZE(ftq_arr); i++) *dst++ = bnx2_reg_rd_ind(bp, ftq_arr[i].off); for (i = 0; i < ARRAY_SIZE(ftq_data_arr); i++) { bnx2_reg_wr_ind(bp, ftq_data_arr[i].off, ftq_data_arr[i].cmdoff); bnx2_dump_ind(bp, ftq_data_arr[i].dataoff, dst, ftq_data_arr[i].size); dst += ftq_data_arr[i].size; } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += ftq_size + BNX2_FWDMP_MARKER_SZ; return dst; } #define BNX2_GRCBLK_SIZE 0x400 #define BNX2_GRC_ENTRY(offset) { BNX2_##offset } static const struct grc_reg { u32 off; } grc_arr[] = { BNX2_GRC_ENTRY(PCICFG_START), BNX2_GRC_ENTRY(PCI_GRC_WINDOW_ADDR), BNX2_GRC_ENTRY(MISC_COMMAND), BNX2_GRC_ENTRY(DMA_COMMAND), BNX2_GRC_ENTRY(CTX_COMMAND), BNX2_GRC_ENTRY(EMAC_MODE), BNX2_GRC_ENTRY(RPM_COMMAND), BNX2_GRC_ENTRY(RCP_START), BNX2_GRC_ENTRY(RLUP_COMMAND), BNX2_GRC_ENTRY(CH_COMMAND), BNX2_GRC_ENTRY(RV2P_COMMAND), BNX2_GRC_ENTRY(RDMA_COMMAND), BNX2_GRC_ENTRY(RBDC_COMMAND), BNX2_GRC_ENTRY(MQ_COMMAND), BNX2_GRC_ENTRY(TIMER_COMMAND), BNX2_GRC_ENTRY(TSCH_COMMAND), BNX2_GRC_ENTRY(TBDR_COMMAND), BNX2_GRC_ENTRY(TBDC_COMMAND), BNX2_GRC_ENTRY(TDMA_COMMAND), BNX2_GRC_ENTRY(DBU_CMD), BNX2_GRC_ENTRY(NVM_COMMAND), BNX2_GRC_ENTRY(HC_COMMAND), BNX2_GRC_ENTRY(DEBUG_COMMAND), }; static u32 *dump_grc(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; u32 grc_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (i = 0; i < ARRAY_SIZE(grc_arr); i++) grc_size += BNX2_GRCBLK_SIZE; if ((dmp->fw_hdr.dmp_size + grc_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_GRC_DUMP; *dst++ = grc_size; for (i = 0; i < ARRAY_SIZE(grc_arr); i++) { bnx2_dump(bp, grc_arr[i].off, dst, BNX2_GRCBLK_SIZE/4); dst += BNX2_GRCBLK_SIZE/4; } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += grc_size + BNX2_FWDMP_MARKER_SZ; return dst; } #define BNX2_HSI_ENTRY(offset, size) { BNX2_##offset, BNX2_##size } static const struct hsi_reg { u32 off; u32 size; } hsi_arr[] = { BNX2_HSI_ENTRY(CP_HSI_START, CP_HSI_SIZE), BNX2_HSI_ENTRY(COM_HSI_START, COM_HSI_SIZE), BNX2_HSI_ENTRY(RXP_HSI_START, RXP_HSI_SIZE), BNX2_HSI_ENTRY(TXP_HSI_START, TXP_HSI_SIZE), BNX2_HSI_ENTRY(TPAT_HSI_START, TPAT_HSI_SIZE), }; static u32 *dump_hsi(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; u32 hsi_size = 0; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; for (i = 0; i < ARRAY_SIZE(hsi_arr); i++) hsi_size += hsi_arr[i].size; if ((dmp->fw_hdr.dmp_size + hsi_size + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_HSI_DUMP; *dst++ = hsi_size; for (i = 0; i < ARRAY_SIZE(hsi_arr); i++) { bnx2_dump_ind(bp, hsi_arr[i].off, dst, hsi_arr[i].size/4); dst += hsi_arr[i].size/4; } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += hsi_size + BNX2_FWDMP_MARKER_SZ; return dst; } static u32 * dump_mcp_info(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_MCP_DUMP; *dst++ = BNX2_MCP_DUMP_SIZE; if (BNX2_CHIP(bp) == BNX2_CHIP_5709) { *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P0); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P1); } else { *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P0_5708); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_STATE_P1_5708); } *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_MODE); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_STATE); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_EVENT_MASK); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_PROGRAM_COUNTER); *dst++ = bnx2_reg_rd_ind(bp, BNX2_MCP_CPU_INSTRUCTION); *dst++ = bnx2_shmem_rd(bp, BNX2_DRV_MB); *dst++ = bnx2_shmem_rd(bp, BNX2_FW_MB); *dst++ = bnx2_shmem_rd(bp, BNX2_LINK_STATUS); *dst++ = bnx2_shmem_rd(bp, BNX2_DRV_PULSE_MB); *dst++ = bnx2_shmem_rd(bp, BNX2_DEV_INFO_SIGNATURE); *dst++ = bnx2_shmem_rd(bp, BNX2_BC_STATE_RESET_TYPE); *dst++ = bnx2_shmem_rd(bp, BNX2_BC_STATE_CONDITION); for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, BNX2_BC_STATE_RESET_TYPE); i += 4; } for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, 0x3cc); i += 4; } for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, 0x3dc); i += 4; } for (i = 0; i < 16;) { *dst++ = bnx2_shmem_rd(bp, 0x3ec); i += 4; } *dst++ = bnx2_shmem_rd(bp, 0x3fc); *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += BNX2_MCP_DUMP_SIZE + BNX2_FWDMP_MARKER_SZ; return dst; } static u32 *dump_tbdc(struct bnx2 *bp, u32 *dst, struct bnx2_chip_core_dmp *dmp) { u32 i; if (dmp->fw_hdr.dmp_size >= BNX2_FWDMP_SIZE) return dst; if ((dmp->fw_hdr.dmp_size + BNX2_TBDC_DUMP_SIZE + BNX2_FWDMP_MARKER_SZ) > BNX2_FWDMP_SIZE) return dst; *dst++ = BNX2_FWDMP_MARKER; *dst++ = 0; *dst++ = BNX2_FWDMP_TBDC_DUMP; *dst++ = BNX2_TBDC_DUMP_SIZE; for (i = 0; i < 0x20; i++) { int j = 0; BNX2_WR(bp, BNX2_TBDC_BD_ADDR, i); BNX2_WR(bp, BNX2_TBDC_CAM_OPCODE, BNX2_TBDC_CAM_OPCODE_OPCODE_CAM_READ); BNX2_WR(bp, BNX2_TBDC_COMMAND, BNX2_TBDC_COMMAND_CMD_REG_ARB); while ((BNX2_RD(bp, BNX2_TBDC_COMMAND) & BNX2_TBDC_COMMAND_CMD_REG_ARB) && j < 100) j++; *dst++ = BNX2_RD(bp, BNX2_TBDC_CID); *dst++ = BNX2_RD(bp, BNX2_TBDC_BIDX); *dst++ = BNX2_RD(bp, BNX2_TBDC_CAM_OPCODE); } *dst++ = BNX2_FWDMP_MARKER_END; dmp->fw_hdr.dmp_size += BNX2_TBDC_DUMP_SIZE + BNX2_FWDMP_MARKER_SZ; return dst; } static VMK_ReturnStatus bnx2_fwdmp_callback(void *cookie, vmk_Bool liveDump) { VMK_ReturnStatus status = VMK_OK; u32 idx; u32 *dst; struct bnx2_chip_core_dmp *dmp; struct bnx2 *bp; printk(KERN_INFO "FW dump for QLogic Nx2 Gigabit Ethernet Driver " DRV_MODULE_NAME " v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n"); for (idx = 0; idx < BNX2_MAX_NIC; idx++) { if (fwdmp_va_ptr && fwdmp_bp_ptr[idx]) { /* dump chip information to buffer */ bp = fwdmp_bp_ptr[idx]; dmp = (struct bnx2_chip_core_dmp *)fwdmp_va_ptr; snprintf(dmp->fw_hdr.name, sizeof(dmp->fw_hdr.name), "%s", bp->dev->name); dmp->fw_hdr.bp = (void *)bp; dmp->fw_hdr.chip_id = bp->chip_id; dmp->fw_hdr.len = sizeof(struct bnx2_fw_dmp_hdr); dmp->fw_hdr.ver = 0x000700006; dmp->fw_hdr.dmp_size = dmp->fw_hdr.len; /* 1. dump all CPUs states */ dst = dmp->fw_dmp_buf; dst = dump_cpu_state(bp, dst, dmp); /* 2. dump all ftqs control information */ dst = dump_ftq_ctrl_info(bp, dst, dmp); /* 3. dump mcp info */ dst = dump_mcp_info(bp, dst, dmp); /* 4. dump tbdc contents */ dst = dump_tbdc(bp, dst, dmp); /* 5. dump hsi section for all processors */ dst = dump_hsi(bp, dst, dmp); /* 6. dump 32k grc registers */ dst = dump_grc(bp, dst, dmp); status = vmklnx_dump_range(bnx2_fwdmp_dh, fwdmp_va_ptr, dmp->fw_hdr.dmp_size); if (status != VMK_OK) { printk(KERN_ERR "####failed to dump firmware/chip data %x %d!\n", status, idx); break; } } } return status; } #endif /* The following debug buffers and exported routines are used by GDB to access teton/xinan hardware registers when doing live debug over serial port. */ #define DBG_BUF_SZ 128 static u32 bnx2_dbg_buf[DBG_BUF_SZ]; static u32 bnx2_dbg_read32_ind_single(void __iomem *reg_view, u32 off) { u32 val; writel(off, reg_view + BNX2_PCICFG_REG_WINDOW_ADDRESS); val = readl(reg_view + BNX2_PCICFG_REG_WINDOW); return val; } void bnx2_dbg_read32_ind(void __iomem *reg_view, u32 off, u32 len) { u32 *buf = bnx2_dbg_buf; if (len & 0x3) len = (len + 3) & ~3; if (len > DBG_BUF_SZ) len = DBG_BUF_SZ; while (len > 0) { *buf = bnx2_dbg_read32_ind_single(reg_view, off); buf++; off += 4; len -= 4; } } EXPORT_SYMBOL(bnx2_dbg_read32_ind); static u32 bnx2_dbg_read32_single(void __iomem *reg_view, u32 off) { return readl(reg_view + off); } void bnx2_dbg_read32(void __iomem *reg_view, u32 off, u32 len) { u32 *buf = bnx2_dbg_buf; if (len & 0x3) len = (len + 3) & ~3; if (len > DBG_BUF_SZ) len = DBG_BUF_SZ; while (len > 0) { *buf = bnx2_dbg_read32_single(reg_view, off); buf++; off += 4; len -= 4; } } EXPORT_SYMBOL(bnx2_dbg_read32); void bnx2_dbg_write32(void __iomem *reg_view, u32 off, u32 val) { writel(val, reg_view + off); } EXPORT_SYMBOL(bnx2_dbg_write32); void bnx2_dbg_write32_ind(void __iomem *reg_view, u32 off, u32 val) { writel(off, reg_view + BNX2_PCICFG_REG_WINDOW_ADDRESS); writel(val, reg_view + BNX2_PCICFG_REG_WINDOW); } EXPORT_SYMBOL(bnx2_dbg_write32_ind); #endif /*__VMKLNX__ */
pombredanne/https-git.sfconservancy.org-vmkdrivers
vmkdrivers/src_9/drivers/net/bnx2/bnx2.c
C
gpl-2.0
326,854
/* * libpal - Automated Placement of Labels Library * * Copyright (C) 2008 Maxence Laurent, MIS-TIC, HEIG-VD * University of Applied Sciences, Western Switzerland * http://www.hes-so.ch * * Contact: * maxence.laurent <at> heig-vd <dot> ch * or * eric.taillard <at> heig-vd <dot> ch * * This file is part of libpal. * * libpal 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. * * libpal 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 libpal. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef FEATURE_H #define FEATURE_H #define SIP_NO_FILE #include "qgis_core.h" #include "pointset.h" #include "labelposition.h" // for LabelPosition enum #include "qgslabelfeature.h" #include <iostream> #include <fstream> #include <cmath> #include <QString> /** * \ingroup core * \class pal::LabelInfo * \note not available in Python bindings */ namespace pal { //! Optional additional info about label (for curved labels) class CORE_EXPORT LabelInfo { public: struct CharacterInfo { double width; }; LabelInfo( int num, double height, double maxinangle = 20.0, double maxoutangle = -20.0 ) { max_char_angle_inside = maxinangle; // outside angle should be negative max_char_angle_outside = maxoutangle > 0 ? -maxoutangle : maxoutangle; label_height = height; char_num = num; char_info = new CharacterInfo[num]; } ~LabelInfo() { delete [] char_info; } //! LabelInfo cannot be copied LabelInfo( const LabelInfo &rh ) = delete; //! LabelInfo cannot be copied LabelInfo &operator=( const LabelInfo &rh ) = delete; double max_char_angle_inside; double max_char_angle_outside; double label_height; int char_num; CharacterInfo *char_info = nullptr; }; class LabelPosition; class FeaturePart; /** * \ingroup core * \brief Main class to handle feature * \class pal::FeaturePart * \note not available in Python bindings */ class CORE_EXPORT FeaturePart : public PointSet { public: /** * Creates a new generic feature. * \param lf a pointer for a feature which contains the spatial entites * \param geom a pointer to a GEOS geometry */ FeaturePart( QgsLabelFeature *lf, const GEOSGeometry *geom ); FeaturePart( const FeaturePart &other ); /** * Delete the feature */ ~FeaturePart() override; /** * Returns the parent feature. */ QgsLabelFeature *feature() { return mLF; } /** * Returns the layer that feature belongs to. */ Layer *layer(); /** * Returns the unique ID of the feature. */ QgsFeatureId featureId() const; /** * Returns the maximum number of point candidates to generate for this feature. */ std::size_t maximumPointCandidates() const; /** * Returns the maximum number of line candidates to generate for this feature. */ std::size_t maximumLineCandidates() const; /** * Returns the maximum number of polygon candidates to generate for this feature. */ std::size_t maximumPolygonCandidates() const; /** * Generates a list of candidate positions for labels for this feature. */ std::vector<std::unique_ptr<LabelPosition> > createCandidates( Pal *pal ); /** * Generate candidates for point feature, located around a specified point. * \param x x coordinate of the point * \param y y coordinate of the point * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param angle orientation of the label * \returns the number of generated candidates */ std::size_t createCandidatesAroundPoint( double x, double y, std::vector<std::unique_ptr<LabelPosition> > &lPos, double angle ); /** * Generate one candidate over or offset the specified point. * \param x x coordinate of the point * \param y y coordinate of the point * \param lPos pointer to an array of candidates, will be filled by generated candidate * \param angle orientation of the label * \returns the number of generated candidates (always 1) */ std::size_t createCandidatesOverPoint( double x, double y, std::vector<std::unique_ptr<LabelPosition> > &lPos, double angle ); /** * Creates a single candidate using the "point on sruface" algorithm. * * \note Unlike the other create candidates methods, this method * bypasses the usual candidate filtering steps and ALWAYS returns a single candidate. */ std::unique_ptr< LabelPosition > createCandidatePointOnSurface( PointSet *mapShape ); /** * Generates candidates following a prioritized list of predefined positions around a point. * \param x x coordinate of the point * \param y y coordinate of the point * \param lPos pointer to an array of candidates, will be filled by generated candidate * \param angle orientation of the label * \returns the number of generated candidates */ std::size_t createCandidatesAtOrderedPositionsOverPoint( double x, double y, std::vector<std::unique_ptr<LabelPosition> > &lPos, double angle ); /** * Generate candidates for line feature. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param allowOverrun set to TRUE to allow labels to overrun features * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesAlongLine( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, bool allowOverrun, Pal *pal ); /** * Generate candidates for line feature, by trying to place candidates towards the middle of the longest * straightish segments of the line. Segments closer to horizontal are preferred over vertical segments. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesAlongLineNearStraightSegments( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, Pal *pal ); /** * Generate candidates for line feature, by trying to place candidates as close as possible to the line's midpoint. * Candidates can "cut corners" if it helps them place near this mid point. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param initialCost initial cost for candidates generated using this method. If set, cost can be increased * by a preset amount. * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesAlongLineNearMidpoint( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, double initialCost = 0.0, Pal *pal = nullptr ); /** * Returns the label position for a curved label at a specific offset along a path. * \param path_positions line path to place label on * \param path_distances array of distances to each segment on path * \param orientation can be 0 for automatic calculation of orientation, or -1/+1 for a specific label orientation * \param distance distance to offset label along curve by * \param reversed if TRUE label is reversed from lefttoright to righttoleft * \param flip if TRUE label is placed on the other side of the line * \returns calculated label position */ std::unique_ptr< LabelPosition > curvedPlacementAtOffset( PointSet *path_positions, double *path_distances, int &orientation, double distance, bool &reversed, bool &flip ); /** * Generate curved candidates for line features. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the line * \param allowOverrun set to TRUE to allow labels to overrun features * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCurvedCandidatesAlongLine( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, bool allowOverrun, Pal *pal ); /** * Generate candidates for polygon features. * \param lPos pointer to an array of candidates, will be filled by generated candidates * \param mapShape a pointer to the polygon * \param pal point to pal settings object, for cancellation support * \returns the number of generated candidates */ std::size_t createCandidatesForPolygon( std::vector<std::unique_ptr<LabelPosition> > &lPos, PointSet *mapShape, Pal *pal ); /** * Tests whether this feature part belongs to the same QgsLabelFeature as another * feature part. * \param part part to compare to * \returns TRUE if both parts belong to same QgsLabelFeature */ bool hasSameLabelFeatureAs( FeaturePart *part ) const; #if 0 /** * \brief Print feature information * Print feature unique id, geometry type, points, and holes on screen */ void print(); #endif /** * Returns the width of the label, optionally taking an \a angle into account. * \returns the width of the label */ double getLabelWidth( double angle = 0.0 ) const { return mLF->size( angle ).width(); } /** * Returns the height of the label, optionally taking an \a angle into account. * \returns the hieght of the label */ double getLabelHeight( double angle = 0.0 ) const { return mLF->size( angle ).height(); } /** * Returns the distance from the anchor point to the label * \returns the distance to the label */ double getLabelDistance() const { return mLF->distLabel(); } //! Returns TRUE if the feature's label has a fixed rotation bool hasFixedRotation() const { return mLF->hasFixedAngle(); } //! Returns the fixed angle for the feature's label double fixedAngle() const { return mLF->fixedAngle(); } //! Returns TRUE if the feature's label has a fixed position bool hasFixedPosition() const { return mLF->hasFixedPosition(); } /** * Returns TRUE if the feature's label should always been shown, * even when it collides with other labels */ bool alwaysShow() const { return mLF->alwaysShow(); } /** * Returns the feature's obstacle settings. */ const QgsLabelObstacleSettings &obstacleSettings() const { return mLF->obstacleSettings(); } //! Returns the distance between repeating labels for this feature double repeatDistance() const { return mLF->repeatDistance(); } //! Gets number of holes (inner rings) - they are considered as obstacles int getNumSelfObstacles() const { return mHoles.count(); } //! Gets hole (inner ring) - considered as obstacle FeaturePart *getSelfObstacle( int i ) { return mHoles.at( i ); } //! Check whether this part is connected with some other part bool isConnected( FeaturePart *p2 ); /** * Merge other (connected) part with this one and save the result in this part (other is unchanged). * Returns TRUE on success, FALSE if the feature wasn't modified */ bool mergeWithFeaturePart( FeaturePart *other ); /** * Increases the cost of the label candidates for this feature, based on the size of the feature. * * E.g. small lines or polygons get higher cost so that larger features are more likely to be labeled. */ void addSizePenalty( std::vector<std::unique_ptr<LabelPosition> > &lPos, double bbx[4], double bby[4] ); /** * Calculates the priority for the feature. This will be the feature's priority if set, * otherwise the layer's default priority. */ double calculatePriority() const; //! Returns TRUE if feature's label must be displayed upright bool showUprightLabels() const; //! Returns TRUE if the next char position is found. The referenced parameters are updated. bool nextCharPosition( double charWidth, double segmentLength, PointSet *path_positions, int &index, double &currentDistanceAlongSegment, double &characterStartX, double &characterStartY, double &characterEndX, double &characterEndY ) const; /** * Returns the total number of repeating labels associated with this label. * \see setTotalRepeats() */ int totalRepeats() const; /** * Returns the total number of repeating labels associated with this label. * \see totalRepeats() */ void setTotalRepeats( int repeats ); protected: QgsLabelFeature *mLF = nullptr; QList<FeaturePart *> mHoles; //! \brief read coordinates from a GEOS geom void extractCoords( const GEOSGeometry *geom ); private: LabelPosition::Quadrant quadrantFromOffset() const; int mTotalRepeats = 0; mutable std::size_t mCachedMaxLineCandidates = 0; mutable std::size_t mCachedMaxPolygonCandidates = 0; }; } // end namespace pal #endif
physycom/QGIS
src/core/pal/feature.h
C
gpl-2.0
14,361
<?php // @codingStandardsIgnoreFile namespace Drupal\Tests\Component\Annotation\Doctrine; use Drupal\Component\Annotation\Doctrine\DocParser; use Doctrine\Common\Annotations\AnnotationRegistry; use Doctrine\Common\Annotations\Annotation\Target; use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants; use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants; use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \Drupal\Component\Annotation\Doctrine\DocParser * * This class is a near-copy of * Doctrine\Tests\Common\Annotations\DocParserTest, which is part of the * Doctrine project: <http://www.doctrine-project.org>. It was copied from * version 1.2.7. * * The supporting test fixture classes in * core/tests/Drupal/Tests/Component/Annotation/Doctrine/Fixtures were also * copied from version 1.2.7. * * @group Annotation */ class DocParserTest extends TestCase { public function testNestedArraysWithNestedAnnotation() { $parser = $this->createTestParser(); // Nested arrays with nested annotations $result = $parser->parse('@Name(foo={1,2, {"key"=@Name}})'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertNull($annot->value); $this->assertEquals(3, count($annot->foo)); $this->assertEquals(1, $annot->foo[0]); $this->assertEquals(2, $annot->foo[1]); $this->assertTrue(is_array($annot->foo[2])); $nestedArray = $annot->foo[2]; $this->assertTrue(isset($nestedArray['key'])); $this->assertTrue($nestedArray['key'] instanceof Name); } public function testBasicAnnotations() { $parser = $this->createTestParser(); // Marker annotation $result = $parser->parse("@Name"); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertNull($annot->value); $this->assertNull($annot->foo); // Associative arrays $result = $parser->parse('@Name(foo={"key1" = "value1"})'); $annot = $result[0]; $this->assertNull($annot->value); $this->assertTrue(is_array($annot->foo)); $this->assertTrue(isset($annot->foo['key1'])); // Numerical arrays $result = $parser->parse('@Name({2="foo", 4="bar"})'); $annot = $result[0]; $this->assertTrue(is_array($annot->value)); $this->assertEquals('foo', $annot->value[2]); $this->assertEquals('bar', $annot->value[4]); $this->assertFalse(isset($annot->value[0])); $this->assertFalse(isset($annot->value[1])); $this->assertFalse(isset($annot->value[3])); // Multiple values $result = $parser->parse('@Name(@Name, @Name)'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertTrue($annot->value[0] instanceof Name); $this->assertTrue($annot->value[1] instanceof Name); // Multiple types as values $result = $parser->parse('@Name(foo="Bar", @Name, {"key1"="value1", "key2"="value2"})'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertTrue($annot->value[0] instanceof Name); $this->assertTrue(is_array($annot->value[1])); $this->assertEquals('value1', $annot->value[1]['key1']); $this->assertEquals('value2', $annot->value[1]['key2']); // Complete docblock $docblock = <<<DOCBLOCK /** * Some nifty class. * * @author Mr.X * @Name(foo="bar") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(1, count($result)); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertEquals("bar", $annot->foo); $this->assertNull($annot->value); } public function testDefaultValueAnnotations() { $parser = $this->createTestParser(); // Array as first value $result = $parser->parse('@Name({"key1"="value1"})'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertEquals('value1', $annot->value['key1']); // Array as first value and additional values $result = $parser->parse('@Name({"key1"="value1"}, foo="bar")'); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertTrue(is_array($annot->value)); $this->assertEquals('value1', $annot->value['key1']); $this->assertEquals('bar', $annot->foo); } public function testNamespacedAnnotations() { $parser = new DocParser; $parser->setIgnoreNotImportedAnnotations(true); $docblock = <<<DOCBLOCK /** * Some nifty class. * * @package foo * @subpackage bar * @author Mr.X <mr@x.com> * @Drupal\Tests\Component\Annotation\Doctrine\Name(foo="bar") * @ignore */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(1, count($result)); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertEquals("bar", $annot->foo); } /** * @group debug */ public function testTypicalMethodDocBlock() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * Some nifty method. * * @since 2.0 * @Drupal\Tests\Component\Annotation\Doctrine\Name(foo="bar") * @param string \$foo This is foo. * @param mixed \$bar This is bar. * @return string Foo and bar. * @This is irrelevant * @Marker */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(2, count($result)); $this->assertTrue(isset($result[0])); $this->assertTrue(isset($result[1])); $annot = $result[0]; $this->assertTrue($annot instanceof Name); $this->assertEquals("bar", $annot->foo); $marker = $result[1]; $this->assertTrue($marker instanceof Marker); } public function testAnnotationWithoutConstructor() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor("Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertNotNull($annot); $this->assertTrue($annot instanceof SomeAnnotationClassNameWithoutConstructor); $this->assertNull($annot->name); $this->assertNotNull($annot->data); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(name="Some Name", data = "Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertNotNull($annot); $this->assertTrue($annot instanceof SomeAnnotationClassNameWithoutConstructor); $this->assertEquals($annot->name, "Some Name"); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(data = "Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->data, "Some data"); $this->assertNull($annot->name); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(name = "Some name") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->name, "Some name"); $this->assertNull($annot->data); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor("Some data") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->data, "Some data"); $this->assertNull($annot->name); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor("Some data",name = "Some name") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->name, "Some name"); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationWithConstructorWithoutParams(name = "Some name") */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $annot = $result[0]; $this->assertEquals($annot->name, "Some name"); $this->assertEquals($annot->data, "Some data"); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructorAndProperties() */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertEquals(count($result), 1); $this->assertTrue($result[0] instanceof SomeAnnotationClassNameWithoutConstructorAndProperties); } public function testAnnotationTarget() { $parser = new DocParser; $parser->setImports(array( '__NAMESPACE__' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures', )); $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithValidAnnotationTarget'); $context = 'class ' . $class->getName(); $docComment = $class->getDocComment(); $parser->setTarget(Target::TARGET_CLASS); $this->assertNotNull($parser->parse($docComment,$context)); $property = $class->getProperty('foo'); $docComment = $property->getDocComment(); $context = 'property ' . $class->getName() . "::\$" . $property->getName(); $parser->setTarget(Target::TARGET_PROPERTY); $this->assertNotNull($parser->parse($docComment,$context)); $method = $class->getMethod('someFunction'); $docComment = $property->getDocComment(); $context = 'method ' . $class->getName() . '::' . $method->getName() . '()'; $parser->setTarget(Target::TARGET_METHOD); $this->assertNotNull($parser->parse($docComment,$context)); try { $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtClass'); $context = 'class ' . $class->getName(); $docComment = $class->getDocComment(); $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docComment, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertNotNull($exc->getMessage()); } try { $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtMethod'); $method = $class->getMethod('functionName'); $docComment = $method->getDocComment(); $context = 'method ' . $class->getName() . '::' . $method->getName() . '()'; $parser->setTarget(Target::TARGET_METHOD); $parser->parse($docComment, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertNotNull($exc->getMessage()); } try { $class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtProperty'); $property = $class->getProperty('foo'); $docComment = $property->getDocComment(); $context = 'property ' . $class->getName() . "::\$" . $property->getName(); $parser->setTarget(Target::TARGET_PROPERTY); $parser->parse($docComment, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertNotNull($exc->getMessage()); } } public function getAnnotationVarTypeProviderValid() { //({attribute name}, {attribute value}) return array( // mixed type array('mixed', '"String Value"'), array('mixed', 'true'), array('mixed', 'false'), array('mixed', '1'), array('mixed', '1.2'), array('mixed', '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll'), // boolean type array('boolean', 'true'), array('boolean', 'false'), // alias for internal type boolean array('bool', 'true'), array('bool', 'false'), // integer type array('integer', '0'), array('integer', '1'), array('integer', '123456789'), array('integer', '9223372036854775807'), // alias for internal type double array('float', '0.1'), array('float', '1.2'), array('float', '123.456'), // string type array('string', '"String Value"'), array('string', '"true"'), array('string', '"123"'), // array type array('array', '{@AnnotationExtendsAnnotationTargetAll}'), array('array', '{@AnnotationExtendsAnnotationTargetAll,@AnnotationExtendsAnnotationTargetAll}'), array('arrayOfIntegers', '1'), array('arrayOfIntegers', '{1}'), array('arrayOfIntegers', '{1,2,3,4}'), array('arrayOfAnnotations', '@AnnotationExtendsAnnotationTargetAll'), array('arrayOfAnnotations', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll}'), array('arrayOfAnnotations', '{@AnnotationExtendsAnnotationTargetAll, @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll}'), // annotation instance array('annotation', '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll'), array('annotation', '@AnnotationExtendsAnnotationTargetAll'), ); } public function getAnnotationVarTypeProviderInvalid() { //({attribute name}, {type declared type}, {attribute value} , {given type or class}) return array( // boolean type array('boolean','boolean','1','integer'), array('boolean','boolean','1.2','double'), array('boolean','boolean','"str"','string'), array('boolean','boolean','{1,2,3}','array'), array('boolean','boolean','@Name', 'an instance of Drupal\Tests\Component\Annotation\Doctrine\Name'), // alias for internal type boolean array('bool','bool', '1','integer'), array('bool','bool', '1.2','double'), array('bool','bool', '"str"','string'), array('bool','bool', '{"str"}','array'), // integer type array('integer','integer', 'true','boolean'), array('integer','integer', 'false','boolean'), array('integer','integer', '1.2','double'), array('integer','integer', '"str"','string'), array('integer','integer', '{"str"}','array'), array('integer','integer', '{1,2,3,4}','array'), // alias for internal type double array('float','float', 'true','boolean'), array('float','float', 'false','boolean'), array('float','float', '123','integer'), array('float','float', '"str"','string'), array('float','float', '{"str"}','array'), array('float','float', '{12.34}','array'), array('float','float', '{1,2,3}','array'), // string type array('string','string', 'true','boolean'), array('string','string', 'false','boolean'), array('string','string', '12','integer'), array('string','string', '1.2','double'), array('string','string', '{"str"}','array'), array('string','string', '{1,2,3,4}','array'), // annotation instance array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'true','boolean'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'false','boolean'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '12','integer'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '1.2','double'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{"str"}','array'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{1,2,3,4}','array'), array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '@Name','an instance of Drupal\Tests\Component\Annotation\Doctrine\Name'), ); } public function getAnnotationVarTypeArrayProviderInvalid() { //({attribute name}, {type declared type}, {attribute value} , {given type or class}) return array( array('arrayOfIntegers', 'integer', 'true', 'boolean'), array('arrayOfIntegers', 'integer', 'false', 'boolean'), array('arrayOfIntegers', 'integer', '{true,true}', 'boolean'), array('arrayOfIntegers', 'integer', '{1,true}', 'boolean'), array('arrayOfIntegers', 'integer', '{1,2,1.2}', 'double'), array('arrayOfIntegers', 'integer', '{1,2,"str"}', 'string'), array('arrayOfStrings', 'string', 'true', 'boolean'), array('arrayOfStrings', 'string', 'false', 'boolean'), array('arrayOfStrings', 'string', '{true,true}', 'boolean'), array('arrayOfStrings', 'string', '{"foo",true}', 'boolean'), array('arrayOfStrings', 'string', '{"foo","bar",1.2}', 'double'), array('arrayOfStrings', 'string', '1', 'integer'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'true', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'false', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,true}', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,true}', 'boolean'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,1.2}', 'double'), array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,@AnnotationExtendsAnnotationTargetAll,"str"}', 'string'), ); } /** * @dataProvider getAnnotationVarTypeProviderValid */ public function testAnnotationWithVarType($attribute, $value) { $parser = $this->createTestParser(); $context = 'property SomeClassName::$invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); $result = $parser->parse($docblock, $context); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType', $result[0]); $this->assertNotNull($result[0]->$attribute); } /** * @dataProvider getAnnotationVarTypeProviderInvalid */ public function testAnnotationWithVarTypeError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType declared on property SomeClassName::invalidProperty. expects a(n) $type, but got $given.", $exc->getMessage()); } } /** * @dataProvider getAnnotationVarTypeArrayProviderInvalid */ public function testAnnotationWithVarTypeArrayError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType declared on property SomeClassName::invalidProperty. expects either a(n) $type, or an array of {$type}s, but got $given.", $exc->getMessage()); } } /** * @dataProvider getAnnotationVarTypeProviderValid */ public function testAnnotationWithAttributes($attribute, $value) { $parser = $this->createTestParser(); $context = 'property SomeClassName::$invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); $result = $parser->parse($docblock, $context); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes', $result[0]); $getter = "get".ucfirst($attribute); $this->assertNotNull($result[0]->$getter()); } /** * @dataProvider getAnnotationVarTypeProviderInvalid */ public function testAnnotationWithAttributesError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes declared on property SomeClassName::invalidProperty. expects a(n) $type, but got $given.", $exc->getMessage()); } } /** * @dataProvider getAnnotationVarTypeArrayProviderInvalid */ public function testAnnotationWithAttributesWithVarTypeArrayError($attribute,$type,$value,$given) { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value); $parser->setTarget(Target::TARGET_PROPERTY); try { $parser->parse($docblock, $context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes declared on property SomeClassName::invalidProperty. expects either a(n) $type, or an array of {$type}s, but got $given.", $exc->getMessage()); } } public function testAnnotationWithRequiredAttributes() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $parser->setTarget(Target::TARGET_PROPERTY); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes("Some Value", annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; $result = $parser->parse($docblock); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes', $result[0]); $this->assertEquals("Some Value",$result[0]->getValue()); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation', $result[0]->getAnnot()); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes("Some Value")'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "annot" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes declared on property SomeClassName::invalidProperty. expects a(n) Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation. This value should not be null.', $exc->getMessage()); } $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes(annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes declared on property SomeClassName::invalidProperty. expects a(n) string. This value should not be null.', $exc->getMessage()); } } public function testAnnotationWithRequiredAttributesWithoutContructor() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $parser->setTarget(Target::TARGET_PROPERTY); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor("Some Value", annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; $result = $parser->parse($docblock); $this->assertTrue(sizeof($result) === 1); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor', $result[0]); $this->assertEquals("Some Value", $result[0]->value); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation', $result[0]->annot); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor("Some Value")'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "annot" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor declared on property SomeClassName::invalidProperty. expects a(n) Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation. This value should not be null.', $exc->getMessage()); } $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor(annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)'; try { $result = $parser->parse($docblock,$context); $this->fail(); } catch (\Doctrine\Common\Annotations\AnnotationException $exc) { $this->assertContains('Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor declared on property SomeClassName::invalidProperty. expects a(n) string. This value should not be null.', $exc->getMessage()); } } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnum declared on property SomeClassName::invalidProperty. accept only [ONE, TWO, THREE], but got FOUR. */ public function testAnnotationEnumeratorException() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnum("FOUR")'; $parser->setIgnoreNotImportedAnnotations(false); $parser->setTarget(Target::TARGET_PROPERTY); $parser->parse($docblock, $context); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteral declared on property SomeClassName::invalidProperty. accept only [AnnotationEnumLiteral::ONE, AnnotationEnumLiteral::TWO, AnnotationEnumLiteral::THREE], but got 4. */ public function testAnnotationEnumeratorLiteralException() { $parser = $this->createTestParser(); $context = 'property SomeClassName::invalidProperty.'; $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteral(4)'; $parser->setIgnoreNotImportedAnnotations(false); $parser->setTarget(Target::TARGET_PROPERTY); $parser->parse($docblock, $context); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage @Enum supports only scalar values "array" given. */ public function testAnnotationEnumInvalidTypeDeclarationException() { $parser = $this->createTestParser(); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumInvalid("foo")'; $parser->setIgnoreNotImportedAnnotations(false); $parser->parse($docblock); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Undefined enumerator value "3" for literal "AnnotationEnumLiteral::THREE". */ public function testAnnotationEnumInvalidLiteralDeclarationException() { $parser = $this->createTestParser(); $docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteralInvalid("foo")'; $parser->setIgnoreNotImportedAnnotations(false); $parser->parse($docblock); } public function getConstantsProvider() { $provider[] = array( '@AnnotationWithConstants(PHP_EOL)', PHP_EOL ); $provider[] = array( '@AnnotationWithConstants(AnnotationWithConstants::INTEGER)', AnnotationWithConstants::INTEGER ); $provider[] = array( '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants(AnnotationWithConstants::STRING)', AnnotationWithConstants::STRING ); $provider[] = array( '@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::FLOAT)', AnnotationWithConstants::FLOAT ); $provider[] = array( '@AnnotationWithConstants(ClassWithConstants::SOME_VALUE)', ClassWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants(ClassWithConstants::OTHER_KEY_)', ClassWithConstants::OTHER_KEY_ ); $provider[] = array( '@AnnotationWithConstants(ClassWithConstants::OTHER_KEY_2)', ClassWithConstants::OTHER_KEY_2 ); $provider[] = array( '@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants::SOME_VALUE)', ClassWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants(IntefaceWithConstants::SOME_VALUE)', IntefaceWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants(\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_VALUE)', IntefaceWithConstants::SOME_VALUE ); $provider[] = array( '@AnnotationWithConstants({AnnotationWithConstants::STRING, AnnotationWithConstants::INTEGER, AnnotationWithConstants::FLOAT})', array(AnnotationWithConstants::STRING, AnnotationWithConstants::INTEGER, AnnotationWithConstants::FLOAT) ); $provider[] = array( '@AnnotationWithConstants({ AnnotationWithConstants::STRING = AnnotationWithConstants::INTEGER })', array(AnnotationWithConstants::STRING => AnnotationWithConstants::INTEGER) ); $provider[] = array( '@AnnotationWithConstants({ Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_KEY = AnnotationWithConstants::INTEGER })', array(IntefaceWithConstants::SOME_KEY => AnnotationWithConstants::INTEGER) ); $provider[] = array( '@AnnotationWithConstants({ \Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_KEY = AnnotationWithConstants::INTEGER })', array(IntefaceWithConstants::SOME_KEY => AnnotationWithConstants::INTEGER) ); $provider[] = array( '@AnnotationWithConstants({ AnnotationWithConstants::STRING = AnnotationWithConstants::INTEGER, ClassWithConstants::SOME_KEY = ClassWithConstants::SOME_VALUE, Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants::SOME_KEY = IntefaceWithConstants::SOME_VALUE })', array( AnnotationWithConstants::STRING => AnnotationWithConstants::INTEGER, ClassWithConstants::SOME_KEY => ClassWithConstants::SOME_VALUE, ClassWithConstants::SOME_KEY => IntefaceWithConstants::SOME_VALUE ) ); $provider[] = array( '@AnnotationWithConstants(AnnotationWithConstants::class)', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' ); $provider[] = array( '@AnnotationWithConstants({AnnotationWithConstants::class = AnnotationWithConstants::class})', array('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants') ); $provider[] = array( '@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::class)', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' ); $provider[] = array( '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::class)', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' ); return $provider; } /** * @dataProvider getConstantsProvider */ public function testSupportClassConstants($docblock, $expected) { $parser = $this->createTestParser(); $parser->setImports(array( 'classwithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants', 'intefacewithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants', 'annotationwithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' )); $result = $parser->parse($docblock); $this->assertInstanceOf('\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants', $annotation = $result[0]); $this->assertEquals($expected, $annotation->value); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage The annotation @SomeAnnotationClassNameWithoutConstructorAndProperties declared on does not accept any values, but got {"value":"Foo"}. */ public function testWithoutConstructorWhenIsNotDefaultValue() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructorAndProperties("Foo") */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage The annotation @SomeAnnotationClassNameWithoutConstructorAndProperties declared on does not accept any values, but got {"value":"Foo"}. */ public function testWithoutConstructorWhenHasNoProperties() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructorAndProperties(value = "Foo") */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Expected namespace separator or identifier, got ')' at position 24 in class @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithTargetSyntaxError. */ public function testAnnotationTargetSyntaxError() { $parser = $this->createTestParser(); $context = 'class ' . 'SomeClassName'; $docblock = <<<DOCBLOCK /** * @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithTargetSyntaxError() */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock,$context); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Invalid Target "Foo". Available targets: [ALL, CLASS, METHOD, PROPERTY, ANNOTATION] */ public function testAnnotationWithInvalidTargetDeclarationError() { $parser = $this->createTestParser(); $context = 'class ' . 'SomeClassName'; $docblock = <<<DOCBLOCK /** * @AnnotationWithInvalidTargetDeclaration() */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock,$context); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage @Target expects either a string value, or an array of strings, "NULL" given. */ public function testAnnotationWithTargetEmptyError() { $parser = $this->createTestParser(); $context = 'class ' . 'SomeClassName'; $docblock = <<<DOCBLOCK /** * @AnnotationWithTargetEmpty() */ DOCBLOCK; $parser->setTarget(Target::TARGET_CLASS); $parser->parse($docblock,$context); } /** * @group DDC-575 */ public function testRegressionDDC575() { $parser = $this->createTestParser(); $docblock = <<<DOCBLOCK /** * @Name * * Will trigger error. */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertInstanceOf("Drupal\Tests\Component\Annotation\Doctrine\Name", $result[0]); $docblock = <<<DOCBLOCK /** * @Name * @Marker * * Will trigger error. */ DOCBLOCK; $result = $parser->parse($docblock); $this->assertInstanceOf("Drupal\Tests\Component\Annotation\Doctrine\Name", $result[0]); } /** * @group DDC-77 */ public function testAnnotationWithoutClassIsIgnoredWithoutWarning() { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $result = $parser->parse("@param"); $this->assertEquals(0, count($result)); } /** * @group DCOM-168 */ public function testNotAnAnnotationClassIsIgnoredWithoutWarning() { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $parser->setIgnoredAnnotationNames(array('PHPUnit_Framework_TestCase' => true)); $result = $parser->parse('@PHPUnit_Framework_TestCase'); $this->assertEquals(0, count($result)); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Expected PlainValue, got ''' at position 10. */ public function testAnnotationDontAcceptSingleQuotes() { $parser = $this->createTestParser(); $parser->parse("@Name(foo='bar')"); } /** * @group DCOM-41 */ public function testAnnotationDoesntThrowExceptionWhenAtSignIsNotFollowedByIdentifier() { $parser = new DocParser(); $result = $parser->parse("'@'"); $this->assertEquals(0, count($result)); } /** * @group DCOM-41 * @expectedException \Doctrine\Common\Annotations\AnnotationException */ public function testAnnotationThrowsExceptionWhenAtSignIsNotFollowedByIdentifierInNestedAnnotation() { $parser = new DocParser(); $parser->parse("@Drupal\Tests\Component\Annotation\Doctrine\Name(@')"); } /** * @group DCOM-56 */ public function testAutoloadAnnotation() { $this->assertFalse(class_exists('Drupal\Tests\Component\Annotation\Doctrine\Fixture\Annotation\Autoload', false), 'Pre-condition: Drupal\Tests\Component\Annotation\Doctrine\Fixture\Annotation\Autoload not allowed to be loaded.'); $parser = new DocParser(); AnnotationRegistry::registerAutoloadNamespace('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation', __DIR__ . '/../../../../'); $parser->setImports(array( 'autoload' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\Autoload', )); $annotations = $parser->parse('@Autoload'); $this->assertEquals(1, count($annotations)); $this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\Autoload', $annotations[0]); } public function createTestParser() { $parser = new DocParser(); $parser->setIgnoreNotImportedAnnotations(true); $parser->setImports(array( 'name' => 'Drupal\Tests\Component\Annotation\Doctrine\Name', '__NAMESPACE__' => 'Drupal\Tests\Component\Annotation\Doctrine', )); return $parser; } /** * @group DDC-78 * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage Expected PlainValue, got ''' at position 10 in class \Drupal\Tests\Component\Annotation\Doctrine\Name */ public function testSyntaxErrorWithContextDescription() { $parser = $this->createTestParser(); $parser->parse("@Name(foo='bar')", "class \Drupal\Tests\Component\Annotation\Doctrine\Name"); } /** * @group DDC-183 */ public function testSyntaxErrorWithUnknownCharacters() { $docblock = <<<DOCBLOCK /** * @test at. */ class A { } DOCBLOCK; //$lexer = new \Doctrine\Common\Annotations\Lexer(); //$lexer->setInput(trim($docblock, '/ *')); //var_dump($lexer); try { $parser = $this->createTestParser(); $result = $parser->parse($docblock); $this->assertTrue(is_array($result) && empty($result)); } catch (\Exception $e) { $this->fail($e->getMessage()); } } /** * @group DCOM-14 */ public function testIgnorePHPDocThrowTag() { $docblock = <<<DOCBLOCK /** * @throws \RuntimeException */ class A { } DOCBLOCK; try { $parser = $this->createTestParser(); $result = $parser->parse($docblock); $this->assertTrue(is_array($result) && empty($result)); } catch (\Exception $e) { $this->fail($e->getMessage()); } } /** * @group DCOM-38 */ public function testCastInt() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=1234)"); $annot = $result[0]; $this->assertInternalType('int', $annot->foo); } /** * @group DCOM-38 */ public function testCastNegativeInt() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=-1234)"); $annot = $result[0]; $this->assertInternalType('int', $annot->foo); } /** * @group DCOM-38 */ public function testCastFloat() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=1234.345)"); $annot = $result[0]; $this->assertInternalType('float', $annot->foo); } /** * @group DCOM-38 */ public function testCastNegativeFloat() { $parser = $this->createTestParser(); $result = $parser->parse("@Name(foo=-1234.345)"); $annot = $result[0]; $this->assertInternalType('float', $annot->foo); $result = $parser->parse("@Marker(-1234.345)"); $annot = $result[0]; $this->assertInternalType('float', $annot->value); } public function testReservedKeywordsInAnnotations() { if (PHP_VERSION_ID >= 70000) { $this->markTestSkipped('This test requires PHP 5.6 or lower.'); } require 'ReservedKeywordsClasses.php'; $parser = $this->createTestParser(); $result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\True'); $this->assertTrue($result[0] instanceof True); $result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\False'); $this->assertTrue($result[0] instanceof False); $result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\Null'); $this->assertTrue($result[0] instanceof Null); $result = $parser->parse('@True'); $this->assertTrue($result[0] instanceof True); $result = $parser->parse('@False'); $this->assertTrue($result[0] instanceof False); $result = $parser->parse('@Null'); $this->assertTrue($result[0] instanceof Null); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage [Creation Error] The annotation @SomeAnnotationClassNameWithoutConstructor declared on some class does not have a property named "invalidaProperty". Available properties: data, name */ public function testSetValuesExeption() { $docblock = <<<DOCBLOCK /** * @SomeAnnotationClassNameWithoutConstructor(invalidaProperty = "Some val") */ DOCBLOCK; $this->createTestParser()->parse($docblock, 'some class'); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage [Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_IDENTIFIER or Doctrine\Common\Annotations\DocLexer::T_TRUE or Doctrine\Common\Annotations\DocLexer::T_FALSE or Doctrine\Common\Annotations\DocLexer::T_NULL, got '3.42' at position 5. */ public function testInvalidIdentifierInAnnotation() { $parser = $this->createTestParser(); $parser->parse('@Foo\3.42'); } public function testTrailingCommaIsAllowed() { $parser = $this->createTestParser(); $annots = $parser->parse('@Name({ "Foo", "Bar", })'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('Foo', 'Bar'), $annots[0]->value); } public function testDefaultAnnotationValueIsNotOverwritten() { $parser = $this->createTestParser(); $annots = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\AnnotWithDefaultValue'); $this->assertEquals(1, count($annots)); $this->assertEquals('bar', $annots[0]->foo); } public function testArrayWithColon() { $parser = $this->createTestParser(); $annots = $parser->parse('@Name({"foo": "bar"})'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('foo' => 'bar'), $annots[0]->value); } /** * @expectedException \Doctrine\Common\Annotations\AnnotationException * @expectedExceptionMessage [Semantical Error] Couldn't find constant foo. */ public function testInvalidContantName() { $parser = $this->createTestParser(); $parser->parse('@Name(foo: "bar")'); } /** * Tests parsing empty arrays. */ public function testEmptyArray() { $parser = $this->createTestParser(); $annots = $parser->parse('@Name({"foo": {}})'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('foo' => array()), $annots[0]->value); } public function testKeyHasNumber() { $parser = $this->createTestParser(); $annots = $parser->parse('@SettingsAnnotation(foo="test", bar2="test")'); $this->assertEquals(1, count($annots)); $this->assertEquals(array('foo' => 'test', 'bar2' => 'test'), $annots[0]->settings); } /** * @group 44 */ public function testSupportsEscapedQuotedValues() { $result = $this->createTestParser()->parse('@Drupal\Tests\Component\Annotation\Doctrine\Name(foo="""bar""")'); $this->assertCount(1, $result); $this->assertTrue($result[0] instanceof Name); $this->assertEquals('"bar"', $result[0]->foo); } } /** @Annotation */ class SettingsAnnotation { public $settings; public function __construct($settings) { $this->settings = $settings; } } /** @Annotation */ class SomeAnnotationClassNameWithoutConstructor { public $data; public $name; } /** @Annotation */ class SomeAnnotationWithConstructorWithoutParams { function __construct() { $this->data = "Some data"; } public $data; public $name; } /** @Annotation */ class SomeAnnotationClassNameWithoutConstructorAndProperties{} /** * @Annotation * @Target("Foo") */ class AnnotationWithInvalidTargetDeclaration{} /** * @Annotation * @Target */ class AnnotationWithTargetEmpty{} /** @Annotation */ class AnnotationExtendsAnnotationTargetAll extends \Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll { } /** @Annotation */ class Name extends \Doctrine\Common\Annotations\Annotation { public $foo; } /** @Annotation */ class Marker { public $value; } namespace Drupal\Tests\Component\Annotation\Doctrine\FooBar; /** @Annotation */ class Name extends \Doctrine\Common\Annotations\Annotation { }
savaslabs/durham-civil-rights-map
core/tests/Drupal/Tests/Component/Annotation/Doctrine/DocParserTest.php
PHP
gpl-2.0
52,547
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "MovementPacketBuilder.h" #include "MoveSpline.h" #include "ByteBuffer.h" namespace Movement { inline void operator << (ByteBuffer& b, const Vector3& v) { b << v.x << v.y << v.z; } inline void operator >> (ByteBuffer& b, Vector3& v) { b >> v.x >> v.y >> v.z; } enum MonsterMoveType { MonsterMoveNormal = 0, MonsterMoveStop = 1, MonsterMoveFacingSpot = 2, MonsterMoveFacingTarget = 3, MonsterMoveFacingAngle = 4 }; void PacketBuilder::WriteCommonMonsterMovePart(const MoveSpline& move_spline, ByteBuffer& data) { MoveSplineFlag splineflags = move_spline.splineflags; data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40) data << move_spline.spline.getPoint(move_spline.spline.first()); data << move_spline.GetId(); switch (splineflags & MoveSplineFlag::Mask_Final_Facing) { case MoveSplineFlag::Final_Target: data << uint8(MonsterMoveFacingTarget); data << move_spline.facing.target; break; case MoveSplineFlag::Final_Angle: data << uint8(MonsterMoveFacingAngle); data << move_spline.facing.angle; break; case MoveSplineFlag::Final_Point: data << uint8(MonsterMoveFacingSpot); data << move_spline.facing.f.x << move_spline.facing.f.y << move_spline.facing.f.z; break; default: data << uint8(MonsterMoveNormal); break; } // add fake Enter_Cycle flag - needed for client-side cyclic movement (client will erase first spline vertex after first cycle done) splineflags.enter_cycle = move_spline.isCyclic(); data << uint32(splineflags & uint32(~MoveSplineFlag::Mask_No_Monster_Move)); if (splineflags.animation) { data << splineflags.getAnimationId(); data << move_spline.effect_start_time; } data << move_spline.Duration(); if (splineflags.parabolic) { data << move_spline.vertical_acceleration; data << move_spline.effect_start_time; } } void PacketBuilder::WriteStopMovement(Vector3 const& pos, uint32 splineId, ByteBuffer& data) { data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40) data << pos; data << splineId; data << uint8(MonsterMoveStop); } void WriteLinearPath(const Spline<int32>& spline, ByteBuffer& data) { uint32 last_idx = spline.getPointCount() - 3; const Vector3 * real_path = &spline.getPoint(1); data << last_idx; data << real_path[last_idx]; // destination if (last_idx > 1) { Vector3 middle = (real_path[0] + real_path[last_idx]) / 2.f; Vector3 offset; // first and last points already appended for (uint32 i = 1; i < last_idx; ++i) { offset = middle - real_path[i]; data.appendPackXYZ(offset.x, offset.y, offset.z); } } } void WriteCatmullRomPath(const Spline<int32>& spline, ByteBuffer& data) { uint32 count = spline.getPointCount() - 3; data << count; data.append<Vector3>(&spline.getPoint(2), count); } void WriteCatmullRomCyclicPath(const Spline<int32>& spline, ByteBuffer& data) { uint32 count = spline.getPointCount() - 3; data << uint32(count + 1); data << spline.getPoint(1); // fake point, client will erase it from the spline after first cycle done data.append<Vector3>(&spline.getPoint(1), count); } void PacketBuilder::WriteMonsterMove(const MoveSpline& move_spline, ByteBuffer& data) { WriteCommonMonsterMovePart(move_spline, data); const Spline<int32>& spline = move_spline.spline; MoveSplineFlag splineflags = move_spline.splineflags; if (splineflags & MoveSplineFlag::Mask_CatmullRom) { if (splineflags.cyclic) WriteCatmullRomCyclicPath(spline, data); else WriteCatmullRomPath(spline, data); } else WriteLinearPath(spline, data); } void PacketBuilder::WriteCreate(const MoveSpline& move_spline, ByteBuffer& data) { //WriteClientStatus(mov, data); //data.append<float>(&mov.m_float_values[SpeedWalk], SpeedMaxCount); //if (mov.SplineEnabled()) { MoveSplineFlag const& splineFlags = move_spline.splineflags; data << splineFlags.raw(); if (splineFlags.final_angle) { data << move_spline.facing.angle; } else if (splineFlags.final_target) { data << move_spline.facing.target; } else if (splineFlags.final_point) { data << move_spline.facing.f.x << move_spline.facing.f.y << move_spline.facing.f.z; } data << move_spline.timePassed(); data << move_spline.Duration(); data << move_spline.GetId(); data << float(1.f); // splineInfo.duration_mod; added in 3.1 data << float(1.f); // splineInfo.duration_mod_next; added in 3.1 data << move_spline.vertical_acceleration; // added in 3.1 data << move_spline.effect_start_time; // added in 3.1 uint32 nodes = move_spline.getPath().size(); data << nodes; data.append<Vector3>(&move_spline.getPath()[0], nodes); data << uint8(move_spline.spline.mode()); // added in 3.1 data << (move_spline.isCyclic() ? Vector3::zero() : move_spline.FinalDestination()); } } }
ironhead123/DeathCore_3.3.5
src/server/game/Movement/Spline/MovementPacketBuilder.cpp
C++
gpl-2.0
6,925
/* * Copyright (C) 2012 Spreadtrum Communications Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <asm/io.h> #include <asm/setup.h> #include <asm/mach/time.h> #include <asm/mach/arch.h> #include <asm/mach-types.h> #include <asm/hardware/gic.h> #include <asm/hardware/cache-l2x0.h> #include <asm/localtimer.h> #include <mach/hardware.h> #include <linux/i2c.h> #include <linux/i2c/ft5306_ts.h> #include <linux/i2c/lis3dh.h> #include <linux/i2c/ltr_558als.h> #include <linux/akm8975.h> #include <linux/spi/spi.h> #include <mach/board.h> #include <mach/serial_sprd.h> #include <mach/adi.h> #include <mach/adc.h> #include "../devices.h" #include <linux/gpio.h> #include <linux/mpu.h> #include <linux/akm8975.h> #include <linux/irq.h> #include <mach/sci.h> #include <mach/hardware.h> #include <mach/regs_glb.h> #include <mach/regs_ahb.h> #include <mach/pinmap.h> /* IRQ's for the multi sensor board */ #define MPUIRQ_GPIO 212 extern void __init sc8825_reserve(void); extern void __init sci_map_io(void); extern void __init sc8825_init_irq(void); extern void __init sc8825_timer_init(void); extern int __init sc8825_regulator_init(void); extern int __init sci_clock_init(void); #ifdef CONFIG_ANDROID_RAM_CONSOLE extern int __init sprd_ramconsole_init(void); #endif static struct platform_device rfkill_device; static struct platform_device kb_backlight_device; static struct platform_device *devices[] __initdata = { &sprd_serial_device0, &sprd_serial_device1, &sprd_serial_device2, &sprd_device_rtc, &sprd_nand_device, &sprd_lcd_device0, &sprd_backlight_device, &sprd_i2c_device0, &sprd_i2c_device1, &sprd_i2c_device2, &sprd_i2c_device3, &sprd_spi0_device, &sprd_spi1_device, &sprd_spi2_device, &sprd_keypad_device, &sprd_audio_platform_pcm_device, &sprd_audio_cpu_dai_vaudio_device, &sprd_audio_cpu_dai_vbc_device, &sprd_audio_codec_sprd_codec_device, &sprd_audio_cpu_dai_i2s_device, &sprd_audio_cpu_dai_i2s_device1, &sprd_audio_codec_null_codec_device, &sprd_battery_device, #ifdef CONFIG_ANDROID_PMEM &sprd_pmem_device, &sprd_pmem_adsp_device, #endif #ifdef CONFIG_ION &sprd_ion_dev, #endif &sprd_emmc_device, &sprd_sdio0_device, &sprd_sdio1_device, &sprd_sdio2_device, &sprd_vsp_device, &sprd_dcam_device, &sprd_scale_device, &sprd_rotation_device, &sprd_sensor_device, &sprd_isp_device, &sprd_ahb_bm0_device, &sprd_ahb_bm1_device, &sprd_ahb_bm2_device, &sprd_ahb_bm3_device, &sprd_ahb_bm4_device, &sprd_axi_bm0_device, &sprd_axi_bm1_device, &sprd_axi_bm2_device, #ifdef CONFIG_SIPC &sprd_cproc_td_device, &sprd_spipe_td_device, &sprd_slog_td_device, &sprd_stty_td_device, #endif &kb_backlight_device, &rfkill_device, }; /* RFKILL */ static struct resource rfkill_resources[] = { { .name = "bt_reset", .start = GPIO_BT_RESET, .end = GPIO_BT_RESET, .flags = IORESOURCE_IO, }, }; static struct platform_device rfkill_device = { .name = "rfkill", .id = -1, .num_resources = ARRAY_SIZE(rfkill_resources), .resource = rfkill_resources, }; /* keypad backlight */ static struct platform_device kb_backlight_device = { .name = "keyboard-backlight", .id = -1, }; static struct sys_timer sc8825_timer = { .init = sc8825_timer_init, }; static int calibration_mode = false; static int __init calibration_start(char *str) { if(str) pr_info("modem calibartion:%s\n", str); calibration_mode = true; return 1; } __setup("calibration=", calibration_start); int in_calibration(void) { return (calibration_mode == true); } EXPORT_SYMBOL(in_calibration); static void __init sprd_add_otg_device(void) { /* * if in calibrtaion mode, we do nothing, modem will handle everything */ if (calibration_mode) return; platform_device_register(&sprd_otg_device); } static struct serial_data plat_data0 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 48000000, }; static struct serial_data plat_data1 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 26000000, }; static struct serial_data plat_data2 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 26000000, }; static struct ft5x0x_ts_platform_data ft5x0x_ts_info = { .irq_gpio_number = GPIO_TOUCH_IRQ, .reset_gpio_number = GPIO_TOUCH_RESET, .vdd_name = "vdd28", }; static struct ltr558_pls_platform_data ltr558_pls_info = { .irq_gpio_number = GPIO_PLSENSOR_IRQ, }; static struct lis3dh_acc_platform_data lis3dh_plat_data = { .poll_interval = 10, .min_interval = 10, .g_range = LIS3DH_ACC_G_2G, .axis_map_x = 1, .axis_map_y = 0, .axis_map_z = 2, .negate_x = 0, .negate_y = 0, .negate_z = 1 }; struct akm8975_platform_data akm8975_platform_d = { .mag_low_x = -20480, .mag_high_x = 20479, .mag_low_y = -20480, .mag_high_y = 20479, .mag_low_z = -20480, .mag_high_z = 20479, }; static struct mpu_platform_data mpu9150_platform_data = { .int_config = 0x00, .level_shifter = 0, .orientation = { -1, 0, 0, 0, -1, 0, 0, 0, +1 }, .sec_slave_type = SECONDARY_SLAVE_TYPE_COMPASS, .sec_slave_id = COMPASS_ID_AK8963, .secondary_i2c_addr = 0x0C, .secondary_orientation = { 0, -1, 0, 1, 0, 0, 0, 0, 1 }, .key = {0xec, 0x06, 0x17, 0xdf, 0x77, 0xfc, 0xe6, 0xac, 0x7b, 0x6f, 0x12, 0x8a, 0x1d, 0x63, 0x67, 0x37}, }; static struct i2c_board_info i2c2_boardinfo[] = { { I2C_BOARD_INFO(LIS3DH_ACC_I2C_NAME, LIS3DH_ACC_I2C_ADDR), .platform_data = &lis3dh_plat_data, }, { I2C_BOARD_INFO("mpu9150", 0x68), .irq = MPUIRQ_GPIO, .platform_data = &mpu9150_platform_data, }, { I2C_BOARD_INFO(LTR558_I2C_NAME, LTR558_I2C_ADDR), .platform_data = &ltr558_pls_info, }, { I2C_BOARD_INFO("BEKEN_FM", 0x70), }, /* { I2C_BOARD_INFO(AKM8975_I2C_NAME, AKM8975_I2C_ADDR), .platform_data = &akm8975_platform_d, },*/ }; static struct i2c_board_info i2c1_boardinfo[] = { {I2C_BOARD_INFO("sensor_main",0x3C),}, {I2C_BOARD_INFO("sensor_sub",0x21),}, }; static struct i2c_board_info i2c0_boardinfo[] = { { I2C_BOARD_INFO(FT5206_TS_DEVICE, FT5206_TS_ADDR), .platform_data = &ft5x0x_ts_info, }, }; static int sc8810_add_i2c_devices(void) { i2c_register_board_info(2, i2c2_boardinfo, ARRAY_SIZE(i2c2_boardinfo)); i2c_register_board_info(1, i2c1_boardinfo, ARRAY_SIZE(i2c1_boardinfo)); i2c_register_board_info(0, i2c0_boardinfo, ARRAY_SIZE(i2c0_boardinfo)); return 0; } struct platform_device audio_pa_amplifier_device = { .name = "speaker-pa", .id = -1, }; static int audio_pa_amplifier_l(u32 cmd, void *data) { int ret = 0; if (cmd < 0) { /* get speaker amplifier status : enabled or disabled */ ret = 0; } else { /* set speaker amplifier */ } return ret; } const char * sc8825_regulator_map[] = { /*supply source, consumer0, consumer1, ..., NULL */ "vdd28", "iic_vdd", "ctp_vdd", NULL, "vddsd0", "tflash_vcc", NULL, "vddsim0", "nfc_vcc", NULL, "vddsim1", "sim_vcc", NULL, NULL, }; int __init sc8825_regulator_init(void) { static struct platform_device sc8825_regulator_device = { .name = "sprd-regulator", .id = -1, .dev = {.platform_data = sc8825_regulator_map}, }; return platform_device_register(&sc8825_regulator_device); } int __init sc8825_clock_init_early(void) { /* FIXME: Force disable all unused clocks */ sci_glb_clr(REG_AHB_AHB_CTL0, BIT_AXIBUSMON2_EB | BIT_AXIBUSMON1_EB | BIT_AXIBUSMON0_EB | // BIT_EMC_EB | // BIT_AHB_ARCH_EB | // BIT_SPINLOCK_EB | BIT_SDIO2_EB | BIT_EMMC_EB | // BIT_DISPC_EB | BIT_G3D_EB | BIT_SDIO1_EB | BIT_DRM_EB | BIT_BUSMON4_EB | BIT_BUSMON3_EB | BIT_BUSMON2_EB | BIT_ROT_EB | BIT_VSP_EB | BIT_ISP_EB | BIT_BUSMON1_EB | BIT_DCAM_MIPI_EB | BIT_CCIR_EB | BIT_NFC_EB | BIT_BUSMON0_EB | // BIT_DMA_EB | // BIT_USBD_EB | BIT_SDIO0_EB | // BIT_LCDC_EB | BIT_CCIR_IN_EB | BIT_DCAM_EB | 0); sci_glb_clr(REG_AHB_AHB_CTL2, // BIT_DISPMTX_CLK_EN | BIT_MMMTX_CLK_EN | // BIT_DISPC_CORE_CLK_EN| // BIT_LCDC_CORE_CLK_EN| BIT_ISP_CORE_CLK_EN | BIT_VSP_CORE_CLK_EN | BIT_DCAM_CORE_CLK_EN| 0); sci_glb_clr(REG_AHB_AHB_CTL3, // BIT_CLK_ULPI_EN | // BIT_CLK_USB_REF_EN | 0); sci_glb_clr(REG_GLB_GEN0, BIT_IC3_EB | BIT_IC2_EB | BIT_IC1_EB | // BIT_RTC_TMR_EB | // BIT_RTC_SYST0_EB | BIT_RTC_KPD_EB | BIT_IIS1_EB | // BIT_RTC_EIC_EB | BIT_UART2_EB | // BIT_UART1_EB | BIT_UART0_EB | // BIT_SYST0_EB | BIT_SPI1_EB | BIT_SPI0_EB | // BIT_SIM1_EB | // BIT_EPT_EB | BIT_CCIR_MCLK_EN | // BIT_PINREG_EB | BIT_IIS0_EB | // BIT_MCU_DSP_RST | // BIT_EIC_EB | BIT_KPD_EB | BIT_EFUSE_EB | // BIT_ADI_EB | // BIT_GPIO_EB | BIT_I2C0_EB | // BIT_SIM0_EB | // BIT_TMR_EB | BIT_SPI2_EB | BIT_UART3_EB | 0); sci_glb_clr(REG_AHB_CA5_CFG, // BIT_CA5_CLK_DBG_EN | 0); sci_glb_clr(REG_GLB_GEN1, BIT_AUDIF_AUTO_EN | BIT_VBC_EN | BIT_AUD_TOP_EB | BIT_AUD_IF_EB | BIT_CLK_AUX1_EN | BIT_CLK_AUX0_EN | 0); sci_glb_clr(REG_GLB_CLK_EN, BIT_PWM3_EB | //BIT_PWM2_EB | BIT_PWM1_EB | // BIT_PWM0_EB | 0); sci_glb_clr(REG_GLB_PCTRL, // BIT_MCU_MPLL_EN | // BIT_MCU_TDPLL_EN | // BIT_MCU_DPLL_EN | BIT_MCU_GPLL_EN); /* clk_gpu */ sci_glb_set(REG_GLB_TD_PLL_CTL, // BIT_TDPLL_DIV2OUT_FORCE_PD | /* clk_384m */ // BIT_TDPLL_DIV3OUT_FORCE_PD | /* clk_256m */ // BIT_TDPLL_DIV4OUT_FORCE_PD | /* clk_192m */ // BIT_TDPLL_DIV5OUT_FORCE_PD | /* clk_153p6m */ 0); printk("sc8825 clock module early init ok\n"); return 0; } static void __init sc8825_init_machine(void) { #ifdef CONFIG_ANDROID_RAM_CONSOLE sprd_ramconsole_init(); #endif sci_adc_init((void __iomem *)ADC_BASE); sc8825_regulator_init(); sprd_add_otg_device(); platform_device_add_data(&sprd_serial_device0,(const void*)&plat_data0,sizeof(plat_data0)); platform_device_add_data(&sprd_serial_device1,(const void*)&plat_data1,sizeof(plat_data1)); platform_device_add_data(&sprd_serial_device2,(const void*)&plat_data2,sizeof(plat_data2)); platform_add_devices(devices, ARRAY_SIZE(devices)); sc8810_add_i2c_devices(); } extern void sc8825_enable_timer_early(void); static void __init sc8825_init_early(void) { /* earlier init request than irq and timer */ sc8825_clock_init_early(); sc8825_enable_timer_early(); sci_adi_init(); } /* * Setup the memory banks. */ static void __init sc8825_fixup(struct machine_desc *desc, struct tag *tags, char **cmdline, struct meminfo *mi) { } MACHINE_START(SC8825OPENPHONE, "sc8825") .reserve = sc8825_reserve, .map_io = sci_map_io, .fixup = sc8825_fixup, .init_early = sc8825_init_early, .init_irq = sc8825_init_irq, .timer = &sc8825_timer, .init_machine = sc8825_init_machine, MACHINE_END
voltagex/kernel-sprdb2g_gonk4.0_6821
arch/arm/mach-sc8825/board_sp6825gb/board.c
C
gpl-2.0
11,412
/* * Secure Digital Host Controller Interface ACPI driver. * * Copyright (c) 2012, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/init.h> #include <linux/export.h> #include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/ioport.h> #include <linux/io.h> #include <linux/dma-mapping.h> #include <linux/compiler.h> #include <linux/stddef.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/acpi.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include <linux/delay.h> #include <linux/mmc/host.h> #include <linux/mmc/pm.h> #include <linux/mmc/sdhci.h> #include "sdhci.h" enum { SDHCI_ACPI_SD_CD = BIT(0), SDHCI_ACPI_RUNTIME_PM = BIT(1), }; struct sdhci_acpi_chip { const struct sdhci_ops *ops; unsigned int quirks; unsigned int quirks2; unsigned long caps; unsigned int caps2; mmc_pm_flag_t pm_caps; }; struct sdhci_acpi_slot { const struct sdhci_acpi_chip *chip; unsigned int quirks; unsigned int quirks2; unsigned long caps; unsigned int caps2; mmc_pm_flag_t pm_caps; unsigned int flags; }; struct sdhci_acpi_host { struct sdhci_host *host; const struct sdhci_acpi_slot *slot; struct platform_device *pdev; bool use_runtime_pm; }; static inline bool sdhci_acpi_flag(struct sdhci_acpi_host *c, unsigned int flag) { return c->slot && (c->slot->flags & flag); } static int sdhci_acpi_enable_dma(struct sdhci_host *host) { return 0; } static void sdhci_acpi_int_hw_reset(struct sdhci_host *host) { u8 reg; reg = sdhci_readb(host, SDHCI_POWER_CONTROL); reg |= 0x10; sdhci_writeb(host, reg, SDHCI_POWER_CONTROL); /* For eMMC, minimum is 1us but give it 9us for good measure */ udelay(9); reg &= ~0x10; sdhci_writeb(host, reg, SDHCI_POWER_CONTROL); /* For eMMC, minimum is 200us but give it 300us for good measure */ usleep_range(300, 1000); } static const struct sdhci_ops sdhci_acpi_ops_dflt = { .enable_dma = sdhci_acpi_enable_dma, }; static const struct sdhci_ops sdhci_acpi_ops_int = { .enable_dma = sdhci_acpi_enable_dma, .hw_reset = sdhci_acpi_int_hw_reset, }; static const struct sdhci_acpi_chip sdhci_acpi_chip_int = { .ops = &sdhci_acpi_ops_int, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_emmc = { .chip = &sdhci_acpi_chip_int, .caps = MMC_CAP_8_BIT_DATA | MMC_CAP_NONREMOVABLE | MMC_CAP_HW_RESET, .caps2 = MMC_CAP2_HC_ERASE_SZ, .flags = SDHCI_ACPI_RUNTIME_PM, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sdio = { .quirks2 = SDHCI_QUIRK2_HOST_OFF_CARD_ON, .caps = MMC_CAP_NONREMOVABLE | MMC_CAP_POWER_OFF_CARD, .flags = SDHCI_ACPI_RUNTIME_PM, .pm_caps = MMC_PM_KEEP_POWER, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sd = { .flags = SDHCI_ACPI_SD_CD | SDHCI_ACPI_RUNTIME_PM, .quirks2 = SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON, }; struct sdhci_acpi_uid_slot { const char *hid; const char *uid; const struct sdhci_acpi_slot *slot; }; static const struct sdhci_acpi_uid_slot sdhci_acpi_uids[] = { { "80860F14" , "1" , &sdhci_acpi_slot_int_emmc }, { "80860F14" , "3" , &sdhci_acpi_slot_int_sd }, { "INT33BB" , "2" , &sdhci_acpi_slot_int_sdio }, { "INT33C6" , NULL, &sdhci_acpi_slot_int_sdio }, { "PNP0D40" }, { }, }; static const struct acpi_device_id sdhci_acpi_ids[] = { { "80860F14" }, { "INT33BB" }, { "INT33C6" }, { "PNP0D40" }, { }, }; MODULE_DEVICE_TABLE(acpi, sdhci_acpi_ids); static const struct sdhci_acpi_slot *sdhci_acpi_get_slot_by_ids(const char *hid, const char *uid) { const struct sdhci_acpi_uid_slot *u; for (u = sdhci_acpi_uids; u->hid; u++) { if (strcmp(u->hid, hid)) continue; if (!u->uid) return u->slot; if (uid && !strcmp(u->uid, uid)) return u->slot; } return NULL; } static const struct sdhci_acpi_slot *sdhci_acpi_get_slot(acpi_handle handle, const char *hid) { const struct sdhci_acpi_slot *slot; struct acpi_device_info *info; const char *uid = NULL; acpi_status status; status = acpi_get_object_info(handle, &info); if (!ACPI_FAILURE(status) && (info->valid & ACPI_VALID_UID)) uid = info->unique_id.string; slot = sdhci_acpi_get_slot_by_ids(hid, uid); kfree(info); return slot; } #ifdef CONFIG_PM_RUNTIME static irqreturn_t sdhci_acpi_sd_cd(int irq, void *dev_id) { mmc_detect_change(dev_id, msecs_to_jiffies(200)); return IRQ_HANDLED; } static int sdhci_acpi_add_own_cd(struct device *dev, struct mmc_host *mmc) { struct gpio_desc *desc; unsigned long flags; int err, irq; desc = devm_gpiod_get_index(dev, "sd_cd", 0); if (IS_ERR(desc)) { err = PTR_ERR(desc); goto out; } err = gpiod_direction_input(desc); if (err) goto out_free; irq = gpiod_to_irq(desc); if (irq < 0) { err = irq; goto out_free; } flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING; err = devm_request_irq(dev, irq, sdhci_acpi_sd_cd, flags, "sd_cd", mmc); if (err) goto out_free; return 0; out_free: devm_gpiod_put(dev, desc); out: dev_warn(dev, "failed to setup card detect wake up\n"); return err; } #else static int sdhci_acpi_add_own_cd(struct device *dev, struct mmc_host *mmc) { return 0; } #endif static int sdhci_acpi_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; acpi_handle handle = ACPI_HANDLE(dev); struct acpi_device *device; struct sdhci_acpi_host *c; struct sdhci_host *host; struct resource *iomem; resource_size_t len; const char *hid; int err; if (acpi_bus_get_device(handle, &device)) return -ENODEV; if (acpi_bus_get_status(device) || !device->status.present) return -ENODEV; hid = acpi_device_hid(device); iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!iomem) return -ENOMEM; len = resource_size(iomem); if (len < 0x100) dev_err(dev, "Invalid iomem size!\n"); if (!devm_request_mem_region(dev, iomem->start, len, dev_name(dev))) return -ENOMEM; host = sdhci_alloc_host(dev, sizeof(struct sdhci_acpi_host)); if (IS_ERR(host)) return PTR_ERR(host); c = sdhci_priv(host); c->host = host; c->slot = sdhci_acpi_get_slot(handle, hid); c->pdev = pdev; c->use_runtime_pm = sdhci_acpi_flag(c, SDHCI_ACPI_RUNTIME_PM); platform_set_drvdata(pdev, c); host->hw_name = "ACPI"; host->ops = &sdhci_acpi_ops_dflt; host->irq = platform_get_irq(pdev, 0); host->ioaddr = devm_ioremap_nocache(dev, iomem->start, resource_size(iomem)); if (host->ioaddr == NULL) { err = -ENOMEM; goto err_free; } if (!dev->dma_mask) { u64 dma_mask; if (sdhci_readl(host, SDHCI_CAPABILITIES) & SDHCI_CAN_64BIT) { /* 64-bit DMA is not supported at present */ dma_mask = DMA_BIT_MASK(32); } else { dma_mask = DMA_BIT_MASK(32); } err = dma_coerce_mask_and_coherent(dev, dma_mask); if (err) goto err_free; } if (c->slot) { if (c->slot->chip) { host->ops = c->slot->chip->ops; host->quirks |= c->slot->chip->quirks; host->quirks2 |= c->slot->chip->quirks2; host->mmc->caps |= c->slot->chip->caps; host->mmc->caps2 |= c->slot->chip->caps2; host->mmc->pm_caps |= c->slot->chip->pm_caps; } host->quirks |= c->slot->quirks; host->quirks2 |= c->slot->quirks2; host->mmc->caps |= c->slot->caps; host->mmc->caps2 |= c->slot->caps2; host->mmc->pm_caps |= c->slot->pm_caps; } host->mmc->caps2 |= MMC_CAP2_NO_PRESCAN_POWERUP; err = sdhci_add_host(host); if (err) goto err_free; if (sdhci_acpi_flag(c, SDHCI_ACPI_SD_CD)) { if (sdhci_acpi_add_own_cd(dev, host->mmc)) c->use_runtime_pm = false; } if (c->use_runtime_pm) { pm_runtime_set_active(dev); pm_suspend_ignore_children(dev, 1); pm_runtime_set_autosuspend_delay(dev, 50); pm_runtime_use_autosuspend(dev); pm_runtime_enable(dev); } return 0; err_free: sdhci_free_host(c->host); return err; } static int sdhci_acpi_remove(struct platform_device *pdev) { struct sdhci_acpi_host *c = platform_get_drvdata(pdev); struct device *dev = &pdev->dev; int dead; if (c->use_runtime_pm) { pm_runtime_get_sync(dev); pm_runtime_disable(dev); pm_runtime_put_noidle(dev); } dead = (sdhci_readl(c->host, SDHCI_INT_STATUS) == ~0); sdhci_remove_host(c->host, dead); sdhci_free_host(c->host); return 0; } #ifdef CONFIG_PM_SLEEP static int sdhci_acpi_suspend(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_suspend_host(c->host); } static int sdhci_acpi_resume(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_resume_host(c->host); } #else #define sdhci_acpi_suspend NULL #define sdhci_acpi_resume NULL #endif #ifdef CONFIG_PM_RUNTIME static int sdhci_acpi_runtime_suspend(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_runtime_suspend_host(c->host); } static int sdhci_acpi_runtime_resume(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_runtime_resume_host(c->host); } static int sdhci_acpi_runtime_idle(struct device *dev) { return 0; } #else #define sdhci_acpi_runtime_suspend NULL #define sdhci_acpi_runtime_resume NULL #define sdhci_acpi_runtime_idle NULL #endif static const struct dev_pm_ops sdhci_acpi_pm_ops = { .suspend = sdhci_acpi_suspend, .resume = sdhci_acpi_resume, .runtime_suspend = sdhci_acpi_runtime_suspend, .runtime_resume = sdhci_acpi_runtime_resume, .runtime_idle = sdhci_acpi_runtime_idle, }; static struct platform_driver sdhci_acpi_driver = { .driver = { .name = "sdhci-acpi", .owner = THIS_MODULE, .acpi_match_table = sdhci_acpi_ids, .pm = &sdhci_acpi_pm_ops, }, .probe = sdhci_acpi_probe, .remove = sdhci_acpi_remove, }; module_platform_driver(sdhci_acpi_driver); MODULE_DESCRIPTION("Secure Digital Host Controller Interface ACPI driver"); MODULE_AUTHOR("Adrian Hunter"); MODULE_LICENSE("GPL v2");
wgoossens/linux-nios2
drivers/mmc/host/sdhci-acpi.c
C
gpl-2.0
10,570
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "RBAC.h" #include "AccountMgr.h" #include "DatabaseEnv.h" #include "Log.h" namespace rbac { std::string GetDebugPermissionString(RBACPermissionContainer const& perms) { std::string str = ""; if (!perms.empty()) { std::ostringstream o; RBACPermissionContainer::const_iterator itr = perms.begin(); o << (*itr); for (++itr; itr != perms.end(); ++itr) o << ", " << uint32(*itr); str = o.str(); } return str; } RBACCommandResult RBACData::GrantPermission(uint32 permissionId, int32 realmId /* = 0*/) { // Check if permission Id exists RBACPermission const* perm = sAccountMgr->GetRBACPermission(permissionId); if (!perm) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission does not exists", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_ID_DOES_NOT_EXISTS; } // Check if already added in denied list if (HasDeniedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission in deny list", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_IN_DENIED_LIST; } // Already added? if (HasGrantedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission already granted", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_CANT_ADD_ALREADY_ADDED; } AddGrantedPermission(permissionId); // Do not save to db when loading data from DB (realmId = 0) if (realmId) { TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated", GetId(), GetName().c_str(), permissionId, realmId); SavePermission(permissionId, true, realmId); CalculateNewPermissions(); } else TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_OK; } RBACCommandResult RBACData::DenyPermission(uint32 permissionId, int32 realmId /* = 0*/) { // Check if permission Id exists RBACPermission const* perm = sAccountMgr->GetRBACPermission(permissionId); if (!perm) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission does not exists", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_ID_DOES_NOT_EXISTS; } // Check if already added in granted list if (HasGrantedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission in grant list", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_IN_GRANTED_LIST; } // Already added? if (HasDeniedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission already denied", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_CANT_ADD_ALREADY_ADDED; } AddDeniedPermission(permissionId); // Do not save to db when loading data from DB (realmId = 0) if (realmId) { TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated", GetId(), GetName().c_str(), permissionId, realmId); SavePermission(permissionId, false, realmId); CalculateNewPermissions(); } else TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_OK; } void RBACData::SavePermission(uint32 permission, bool granted, int32 realmId) { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_RBAC_ACCOUNT_PERMISSION); stmt->setUInt32(0, GetId()); stmt->setUInt32(1, permission); stmt->setBool(2, granted); stmt->setInt32(3, realmId); LoginDatabase.Execute(stmt); } RBACCommandResult RBACData::RevokePermission(uint32 permissionId, int32 realmId /* = 0*/) { // Check if it's present in any list if (!HasGrantedPermission(permissionId) && !HasDeniedPermission(permissionId)) { TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Not granted or revoked", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_CANT_REVOKE_NOT_IN_LIST; } RemoveGrantedPermission(permissionId); RemoveDeniedPermission(permissionId); // Do not save to db when loading data from DB (realmId = 0) if (realmId) { TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated", GetId(), GetName().c_str(), permissionId, realmId); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_RBAC_ACCOUNT_PERMISSION); stmt->setUInt32(0, GetId()); stmt->setUInt32(1, permissionId); stmt->setInt32(2, realmId); LoginDatabase.Execute(stmt); CalculateNewPermissions(); } else TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok", GetId(), GetName().c_str(), permissionId, realmId); return RBAC_OK; } void RBACData::LoadFromDB() { ClearData(); TC_LOG_DEBUG("rbac", "RBACData::LoadFromDB [Id: %u Name: %s]: Loading permissions", GetId(), GetName().c_str()); // Load account permissions (granted and denied) that affect current realm PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_RBAC_ACCOUNT_PERMISSIONS); stmt->setUInt32(0, GetId()); stmt->setInt32(1, GetRealmId()); PreparedQueryResult result = LoginDatabase.Query(stmt); if (result) { do { Field* fields = result->Fetch(); if (fields[1].GetBool()) GrantPermission(fields[0].GetUInt32()); else DenyPermission(fields[0].GetUInt32()); } while (result->NextRow()); } // Add default permissions RBACPermissionContainer const& permissions = sAccountMgr->GetRBACDefaultPermissions(_secLevel); for (RBACPermissionContainer::const_iterator itr = permissions.begin(); itr != permissions.end(); ++itr) GrantPermission(*itr); // Force calculation of permissions CalculateNewPermissions(); } void RBACData::CalculateNewPermissions() { TC_LOG_TRACE("rbac", "RBACData::CalculateNewPermissions [Id: %u Name: %s]", GetId(), GetName().c_str()); // Get the list of granted permissions _globalPerms = GetGrantedPermissions(); ExpandPermissions(_globalPerms); RBACPermissionContainer revoked = GetDeniedPermissions(); ExpandPermissions(revoked); RemovePermissions(_globalPerms, revoked); } void RBACData::AddPermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo) { for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr) permsTo.insert(*itr); } void RBACData::RemovePermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo) { for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr) permsTo.erase(*itr); } void RBACData::ExpandPermissions(RBACPermissionContainer& permissions) { RBACPermissionContainer toCheck = permissions; permissions.clear(); while (!toCheck.empty()) { // remove the permission from original list uint32 permissionId = *toCheck.begin(); toCheck.erase(toCheck.begin()); RBACPermission const* permission = sAccountMgr->GetRBACPermission(permissionId); if (!permission) continue; // insert into the final list (expanded list) permissions.insert(permissionId); // add all linked permissions (that are not already expanded) to the list of permissions to be checked RBACPermissionContainer const& linkedPerms = permission->GetLinkedPermissions(); for (RBACPermissionContainer::const_iterator itr = linkedPerms.begin(); itr != linkedPerms.end(); ++itr) if (permissions.find(*itr) == permissions.end()) toCheck.insert(*itr); } TC_LOG_DEBUG("rbac", "RBACData::ExpandPermissions: Expanded: %s", GetDebugPermissionString(permissions).c_str()); } void RBACData::ClearData() { _grantedPerms.clear(); _deniedPerms.clear(); _globalPerms.clear(); } }
fuhongxue/TrinityCore
src/server/game/Accounts/RBAC.cpp
C++
gpl-2.0
10,027
<?php /** * @file * Contains \Drupal\commerce\AvailabilityCheckerInterface. */ namespace Drupal\commerce; /** * Defines the interface for availability checkers. */ interface AvailabilityCheckerInterface { /** * Determines whether the checker applies to the given purchasable entity. * * @param \Drupal\commerce\PurchasableEntityInterface $entity * The purchasable entity. * * @return bool * TRUE if the checker applies to the given purchasable entity, FALSE * otherwise. */ public function applies(PurchasableEntityInterface $entity); /** * Checks the availability of the given purchasable entity. * * @param \Drupal\commerce\PurchasableEntityInterface $entity * The purchasable entity. * @param int $quantity * The quantity. * * @return bool|null * TRUE if the entity is available, FALSE if it's unavailable, * or NULL if it has no opinion. */ public function check(PurchasableEntityInterface $entity, $quantity = 1); }
tom-fallon/free-commerce
modules/contrib/commerce/src/AvailabilityCheckerInterface.php
PHP
gpl-2.0
1,014
<?php /* ** Zabbix ** Copyright (C) 2001-2014 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ /** * Class that holds processed (created and updated) host and template IDs during the current import. */ class CImportedObjectContainer { /** * @var array with created and updated hosts. */ protected $hostIds = array(); /** * @var array with created and updated templates. */ protected $templateIds = array(); /** * Add host IDs that have been created and updated. * * @param array $hostIds */ public function addHostIds(array $hostIds) { foreach ($hostIds as $hostId) { $this->hostIds[$hostId] = $hostId; } } /** * Add template IDs that have been created and updated. * * @param array $templateIds */ public function addTemplateIds(array $templateIds) { foreach ($templateIds as $templateId) { $this->templateIds[$templateId] = $templateId; } } /** * Checks if host has been created and updated during the current import. * * @param string $hostId * * @return bool */ public function isHostProcessed($hostId) { return isset($this->hostIds[$hostId]); } /** * Checks if template has been created and updated during the current import. * * @param string $templateId * * @return bool */ public function isTemplateProcessed($templateId) { return isset($this->templateIds[$templateId]); } /** * Get array of created and updated hosts IDs. * * @return array */ public function getHostIds() { return array_values($this->hostIds); } /** * Get array of created and updated template IDs. * * @return array */ public function getTemplateIds() { return array_values($this->templateIds); } }
qinglan2014/Zabbix
frontends/php/include/classes/import/CImportedObjectContainer.php
PHP
gpl-2.0
2,382
// SPDX-License-Identifier: GPL-2.0-or-later /* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <stdbool.h> #include <glib.h> #include "lib/bluetooth.h" #include "lib/sco.h" #include "lib/mgmt.h" #include "monitor/bt.h" #include "emulator/bthost.h" #include "emulator/hciemu.h" #include "src/shared/tester.h" #include "src/shared/mgmt.h" struct test_data { const void *test_data; struct mgmt *mgmt; uint16_t mgmt_index; struct hciemu *hciemu; enum hciemu_type hciemu_type; unsigned int io_id; bool disable_esco; bool enable_codecs; }; struct sco_client_data { int expect_err; const uint8_t *send_data; uint16_t data_len; }; static void print_debug(const char *str, void *user_data) { const char *prefix = user_data; tester_print("%s%s", prefix, str); } static void read_info_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); const struct mgmt_rp_read_info *rp = param; char addr[18]; uint16_t manufacturer; uint32_t supported_settings, current_settings; tester_print("Read Info callback"); tester_print(" Status: 0x%02x", status); if (status || !param) { tester_pre_setup_failed(); return; } ba2str(&rp->bdaddr, addr); manufacturer = btohs(rp->manufacturer); supported_settings = btohl(rp->supported_settings); current_settings = btohl(rp->current_settings); tester_print(" Address: %s", addr); tester_print(" Version: 0x%02x", rp->version); tester_print(" Manufacturer: 0x%04x", manufacturer); tester_print(" Supported settings: 0x%08x", supported_settings); tester_print(" Current settings: 0x%08x", current_settings); tester_print(" Class: 0x%02x%02x%02x", rp->dev_class[2], rp->dev_class[1], rp->dev_class[0]); tester_print(" Name: %s", rp->name); tester_print(" Short name: %s", rp->short_name); if (strcmp(hciemu_get_address(data->hciemu), addr)) { tester_pre_setup_failed(); return; } tester_pre_setup_complete(); } static void index_added_callback(uint16_t index, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Index Added callback"); tester_print(" Index: 0x%04x", index); data->mgmt_index = index; mgmt_send(data->mgmt, MGMT_OP_READ_INFO, data->mgmt_index, 0, NULL, read_info_callback, NULL, NULL); } static void index_removed_callback(uint16_t index, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Index Removed callback"); tester_print(" Index: 0x%04x", index); if (index != data->mgmt_index) return; mgmt_unregister_index(data->mgmt, data->mgmt_index); mgmt_unref(data->mgmt); data->mgmt = NULL; tester_post_teardown_complete(); } static void enable_codec_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { if (status != MGMT_STATUS_SUCCESS) { tester_warn("Failed to enable codecs"); tester_setup_failed(); return; } tester_print("Enabled codecs"); } static void read_index_list_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Read Index List callback"); tester_print(" Status: 0x%02x", status); if (status || !param) { tester_pre_setup_failed(); return; } mgmt_register(data->mgmt, MGMT_EV_INDEX_ADDED, MGMT_INDEX_NONE, index_added_callback, NULL, NULL); mgmt_register(data->mgmt, MGMT_EV_INDEX_REMOVED, MGMT_INDEX_NONE, index_removed_callback, NULL, NULL); data->hciemu = hciemu_new(HCIEMU_TYPE_BREDRLE); if (!data->hciemu) { tester_warn("Failed to setup HCI emulation"); tester_pre_setup_failed(); return; } if (tester_use_debug()) hciemu_set_debug(data->hciemu, print_debug, "hciemu: ", NULL); tester_print("New hciemu instance created"); if (data->disable_esco) { uint8_t *features; tester_print("Disabling eSCO packet type support"); features = hciemu_get_features(data->hciemu); if (features) features[3] &= ~0x80; } } static void test_pre_setup(const void *test_data) { struct test_data *data = tester_get_data(); data->mgmt = mgmt_new_default(); if (!data->mgmt) { tester_warn("Failed to setup management interface"); tester_pre_setup_failed(); return; } if (tester_use_debug()) mgmt_set_debug(data->mgmt, print_debug, "mgmt: ", NULL); mgmt_send(data->mgmt, MGMT_OP_READ_INDEX_LIST, MGMT_INDEX_NONE, 0, NULL, read_index_list_callback, NULL, NULL); } static void test_post_teardown(const void *test_data) { struct test_data *data = tester_get_data(); hciemu_unref(data->hciemu); data->hciemu = NULL; } static void test_data_free(void *test_data) { struct test_data *data = test_data; if (data->io_id > 0) g_source_remove(data->io_id); free(data); } #define test_sco_full(name, data, setup, func, _disable_esco, _enable_codecs) \ do { \ struct test_data *user; \ user = malloc(sizeof(struct test_data)); \ if (!user) \ break; \ user->hciemu_type = HCIEMU_TYPE_BREDRLE; \ user->io_id = 0; \ user->test_data = data; \ user->disable_esco = _disable_esco; \ user->enable_codecs = _enable_codecs; \ tester_add_full(name, data, \ test_pre_setup, setup, func, NULL, \ test_post_teardown, 2, user, test_data_free); \ } while (0) #define test_sco(name, data, setup, func) \ test_sco_full(name, data, setup, func, false, false) #define test_sco_11(name, data, setup, func) \ test_sco_full(name, data, setup, func, true, false) #define test_offload_sco(name, data, setup, func) \ test_sco_full(name, data, setup, func, false, true) static const struct sco_client_data connect_success = { .expect_err = 0 }; static const struct sco_client_data connect_failure = { .expect_err = EOPNOTSUPP }; const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; static const struct sco_client_data connect_send_success = { .expect_err = 0, .data_len = sizeof(data), .send_data = data }; static void client_connectable_complete(uint16_t opcode, uint8_t status, const void *param, uint8_t len, void *user_data) { if (opcode != BT_HCI_CMD_WRITE_SCAN_ENABLE) return; tester_print("Client set connectable status 0x%02x", status); if (status) tester_setup_failed(); else tester_setup_complete(); } static void setup_powered_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); struct bthost *bthost; if (status != MGMT_STATUS_SUCCESS) { tester_setup_failed(); return; } tester_print("Controller powered on"); bthost = hciemu_client_get_host(data->hciemu); bthost_set_cmd_complete_cb(bthost, client_connectable_complete, data); bthost_write_scan_enable(bthost, 0x03); } static void setup_powered(const void *test_data) { struct test_data *data = tester_get_data(); unsigned char param[] = { 0x01 }; tester_print("Powering on controller"); mgmt_send(data->mgmt, MGMT_OP_SET_CONNECTABLE, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); mgmt_send(data->mgmt, MGMT_OP_SET_SSP, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); mgmt_send(data->mgmt, MGMT_OP_SET_LE, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); if (data->enable_codecs) { /* a6695ace-ee7f-4fb9-881a-5fac66c629af */ static const uint8_t uuid[16] = { 0xaf, 0x29, 0xc6, 0x66, 0xac, 0x5f, 0x1a, 0x88, 0xb9, 0x4f, 0x7f, 0xee, 0xce, 0x5a, 0x69, 0xa6, }; struct mgmt_cp_set_exp_feature cp; memset(&cp, 0, sizeof(cp)); memcpy(cp.uuid, uuid, 16); cp.action = 1; tester_print("Enabling codecs"); mgmt_send(data->mgmt, MGMT_OP_SET_EXP_FEATURE, data->mgmt_index, sizeof(cp), &cp, enable_codec_callback, NULL, NULL); } mgmt_send(data->mgmt, MGMT_OP_SET_POWERED, data->mgmt_index, sizeof(param), param, setup_powered_callback, NULL, NULL); } static void test_framework(const void *test_data) { tester_test_passed(); } static void test_socket(const void *test_data) { int sk; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } close(sk); tester_test_passed(); } static void test_codecs_getsockopt(const void *test_data) { int sk, err; socklen_t len; char buffer[255]; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } len = sizeof(buffer); memset(buffer, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_CODEC, buffer, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_codecs_setsockopt(const void *test_data) { int sk, err; char buffer[255]; struct bt_codecs *codecs; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } memset(buffer, 0, sizeof(buffer)); codecs = (void *)buffer; codecs->codecs[0].id = 0x05; codecs->num_codecs = 1; codecs->codecs[0].data_path_id = 1; codecs->codecs[0].num_caps = 0x00; err = setsockopt(sk, SOL_BLUETOOTH, BT_CODEC, codecs, sizeof(buffer)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_getsockopt(const void *test_data) { int sk, err; socklen_t len; struct bt_voice voice; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_CVSD_16BIT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_setsockopt(const void *test_data) { int sk, err; socklen_t len; struct bt_voice voice; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_CVSD_16BIT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } memset(&voice, 0, sizeof(voice)); voice.setting = BT_VOICE_TRANSPARENT; err = setsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_TRANSPARENT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static int create_sco_sock(struct test_data *data) { const uint8_t *central_bdaddr; struct sockaddr_sco addr; int sk, err; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET | SOCK_NONBLOCK, BTPROTO_SCO); if (sk < 0) { err = -errno; tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); return err; } central_bdaddr = hciemu_get_central_bdaddr(data->hciemu); if (!central_bdaddr) { tester_warn("No central bdaddr"); return -ENODEV; } memset(&addr, 0, sizeof(addr)); addr.sco_family = AF_BLUETOOTH; bacpy(&addr.sco_bdaddr, (void *) central_bdaddr); if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { err = -errno; tester_warn("Can't bind socket: %s (%d)", strerror(errno), errno); close(sk); return err; } return sk; } static int connect_sco_sock(struct test_data *data, int sk) { const uint8_t *client_bdaddr; struct sockaddr_sco addr; int err; client_bdaddr = hciemu_get_client_bdaddr(data->hciemu); if (!client_bdaddr) { tester_warn("No client bdaddr"); return -ENODEV; } memset(&addr, 0, sizeof(addr)); addr.sco_family = AF_BLUETOOTH; bacpy(&addr.sco_bdaddr, (void *) client_bdaddr); err = connect(sk, (struct sockaddr *) &addr, sizeof(addr)); if (err < 0 && !(errno == EAGAIN || errno == EINPROGRESS)) { err = -errno; tester_warn("Can't connect socket: %s (%d)", strerror(errno), errno); return err; } return 0; } static gboolean sco_connect_cb(GIOChannel *io, GIOCondition cond, gpointer user_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int err, sk_err, sk; socklen_t len = sizeof(sk_err); data->io_id = 0; sk = g_io_channel_unix_get_fd(io); if (getsockopt(sk, SOL_SOCKET, SO_ERROR, &sk_err, &len) < 0) err = -errno; else err = -sk_err; if (err < 0) tester_warn("Connect failed: %s (%d)", strerror(-err), -err); else tester_print("Successfully connected"); if (scodata->send_data) { ssize_t ret; tester_print("Writing %u bytes of data", scodata->data_len); ret = write(sk, scodata->send_data, scodata->data_len); if (scodata->data_len != ret) { tester_warn("Failed to write %u bytes: %zu %s (%d)", scodata->data_len, ret, strerror(errno), errno); err = -errno; } } if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); return FALSE; } static void test_connect(const void *test_data) { struct test_data *data = tester_get_data(); GIOChannel *io; int sk; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } if (connect_sco_sock(data, sk) < 0) { close(sk); tester_test_failed(); return; } io = g_io_channel_unix_new(sk); g_io_channel_set_close_on_unref(io, TRUE); data->io_id = g_io_add_watch(io, G_IO_OUT, sco_connect_cb, NULL); g_io_channel_unref(io); tester_print("Connect in progress"); } static void test_connect_transp(const void *test_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int sk, err; struct bt_voice voice; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } memset(&voice, 0, sizeof(voice)); voice.setting = BT_VOICE_TRANSPARENT; err = setsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } err = connect_sco_sock(data, sk); tester_warn("Connect returned %s (%d), expected %s (%d)", strerror(-err), -err, strerror(scodata->expect_err), scodata->expect_err); if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); end: close(sk); } static void test_connect_offload_msbc(const void *test_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int sk, err; int len; char buffer[255]; struct bt_codecs *codecs; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } len = sizeof(buffer); memset(buffer, 0, len); codecs = (void *)buffer; codecs->codecs[0].id = 0x05; codecs->num_codecs = 1; codecs->codecs[0].data_path_id = 1; codecs->codecs[0].num_caps = 0x00; err = setsockopt(sk, SOL_BLUETOOTH, BT_CODEC, codecs, sizeof(buffer)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } err = connect_sco_sock(data, sk); tester_warn("Connect returned %s (%d), expected %s (%d)", strerror(-err), -err, strerror(scodata->expect_err), scodata->expect_err); if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); end: close(sk); } int main(int argc, char *argv[]) { tester_init(&argc, &argv); test_sco("Basic Framework - Success", NULL, setup_powered, test_framework); test_sco("Basic SCO Socket - Success", NULL, setup_powered, test_socket); test_sco("Basic SCO Get Socket Option - Success", NULL, setup_powered, test_getsockopt); test_sco("Basic SCO Set Socket Option - Success", NULL, setup_powered, test_setsockopt); test_sco("eSCO CVSD - Success", &connect_success, setup_powered, test_connect); test_sco("eSCO mSBC - Success", &connect_success, setup_powered, test_connect_transp); test_sco_11("SCO CVSD 1.1 - Success", &connect_success, setup_powered, test_connect); test_sco_11("SCO mSBC 1.1 - Failure", &connect_failure, setup_powered, test_connect_transp); test_sco("SCO CVSD Send - Success", &connect_send_success, setup_powered, test_connect); test_offload_sco("Basic SCO Get Socket Option - Offload - Success", NULL, setup_powered, test_codecs_getsockopt); test_offload_sco("Basic SCO Set Socket Option - Offload - Success", NULL, setup_powered, test_codecs_setsockopt); test_offload_sco("eSCO mSBC - Offload - Success", &connect_success, setup_powered, test_connect_offload_msbc); return tester_run(); }
cktakahasi/bluez
tools/sco-tester.c
C
gpl-2.0
18,002
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>DB_ENV-&gt;rep_get_clockskew()</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C API Reference" /> <link rel="up" href="rep.html" title="Chapter 10.  Replication Methods" /> <link rel="prev" href="repelect.html" title="DB_ENV-&gt;rep_elect()" /> <link rel="next" href="repget_config.html" title="DB_ENV-&gt;rep_get_config()" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">DB_ENV-&gt;rep_get_clockskew()</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="repelect.html">Prev</a> </td> <th width="60%" align="center">Chapter 10.  Replication Methods </th> <td width="20%" align="right"> <a accesskey="n" href="repget_config.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="repget_clockskew"></a>DB_ENV-&gt;rep_get_clockskew()</h2> </div> </div> </div> <pre class="programlisting">#include &lt;db.h&gt; int DB_ENV-&gt;rep_get_clockskew(DB_ENV *env, u_int32_t *fast_clockp, u_int32_t *slow_clockp); </pre> <p> The <code class="methodname">DB_ENV-&gt;rep_get_clockskew()</code> method returns the current clock skew ratio values, as set by the <a class="xref" href="repclockskew.html" title="DB_ENV-&gt;rep_set_clockskew()">DB_ENV-&gt;rep_set_clockskew()</a> method. </p> <p> The <code class="methodname">DB_ENV-&gt;rep_get_clockskew()</code> method may be called at any time during the life of the application. </p> <p> The <code class="methodname">DB_ENV-&gt;rep_get_clockskew()</code> <span> <span> method returns a non-zero error value on failure and 0 on success. </span> </span> </p> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id3891622"></a>Parameters</h3> </div> </div> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="id3891611"></a>fast_clockp</h4> </div> </div> </div> <p> The <span class="bold"><strong>fast_clockp</strong></span> parameter references memory into which the value for the fastest clock in the group of sites is copied. </p> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="id3891226"></a>slow_clockp</h4> </div> </div> </div> <p> The <span class="bold"><strong>slow_clockp</strong></span> parameter references memory into which the value for the slowest clock in the group of sites is copied. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id3891280"></a>Class</h3> </div> </div> </div> <p> <a class="link" href="env.html" title="Chapter 5.  The DB_ENV Handle">DB_ENV</a> </p> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id3891071"></a>See Also</h3> </div> </div> </div> <p> <a class="xref" href="rep.html#replist" title="Replication and Related Methods">Replication and Related Methods</a>, <a class="xref" href="repclockskew.html" title="DB_ENV-&gt;rep_set_clockskew()">DB_ENV-&gt;rep_set_clockskew()</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="repelect.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="rep.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="repget_config.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">DB_ENV-&gt;rep_elect() </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> DB_ENV-&gt;rep_get_config()</td> </tr> </table> </div> </body> </html>
joglomedia/masedi.net
work/berkeley-db/docs/api_reference/C/repget_clockskew.html
HTML
gpl-2.0
5,622
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: NETLINK kernel command channel. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * 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. * * 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. * * Copyright (C) 2001-2012 Alexandre Cassen, <acassen@gmail.com> */ /* global include */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <syslog.h> #include <fcntl.h> #include <net/if_arp.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <errno.h> #include <time.h> #include <sys/uio.h> /* local include */ #include "check_api.h" #include "vrrp_netlink.h" #include "vrrp_if.h" #include "logger.h" #include "memory.h" #include "scheduler.h" #include "utils.h" /* Global vars */ nl_handle_t nl_kernel; /* Kernel reflection channel */ nl_handle_t nl_cmd; /* Command channel */ /* Create a socket to netlink interface_t */ int netlink_socket(nl_handle_t *nl, unsigned long groups) { socklen_t addr_len; int ret; memset(nl, 0, sizeof (*nl)); nl->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (nl->fd < 0) { log_message(LOG_INFO, "Netlink: Cannot open netlink socket : (%s)", strerror(errno)); return -1; } ret = fcntl(nl->fd, F_SETFL, O_NONBLOCK); if (ret < 0) { log_message(LOG_INFO, "Netlink: Cannot set netlink socket flags : (%s)", strerror(errno)); close(nl->fd); return -1; } memset(&nl->snl, 0, sizeof (nl->snl)); nl->snl.nl_family = AF_NETLINK; nl->snl.nl_groups = groups; ret = bind(nl->fd, (struct sockaddr *) &nl->snl, sizeof (nl->snl)); if (ret < 0) { log_message(LOG_INFO, "Netlink: Cannot bind netlink socket : (%s)", strerror(errno)); close(nl->fd); return -1; } addr_len = sizeof (nl->snl); ret = getsockname(nl->fd, (struct sockaddr *) &nl->snl, &addr_len); if (ret < 0 || addr_len != sizeof (nl->snl)) { log_message(LOG_INFO, "Netlink: Cannot getsockname : (%s)", strerror(errno)); close(nl->fd); return -1; } if (nl->snl.nl_family != AF_NETLINK) { log_message(LOG_INFO, "Netlink: Wrong address family %d", nl->snl.nl_family); close(nl->fd); return -1; } nl->seq = time(NULL); /* Set default rcvbuf size */ if_setsockopt_rcvbuf(&nl->fd, IF_DEFAULT_BUFSIZE); if (nl->fd < 0) return -1; return ret; } /* Close a netlink socket */ int netlink_close(nl_handle_t *nl) { /* First of all release pending thread */ thread_cancel(nl->thread); close(nl->fd); return 0; } /* Set netlink socket channel as blocking */ int netlink_set_block(nl_handle_t *nl, int *flags) { if ((*flags = fcntl(nl->fd, F_GETFL, 0)) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_GETFL socket : (%s)", strerror(errno)); return -1; } *flags &= ~O_NONBLOCK; if (fcntl(nl->fd, F_SETFL, *flags) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_SETFL socket : (%s)", strerror(errno)); return -1; } return 0; } /* Set netlink socket channel as non-blocking */ int netlink_set_nonblock(nl_handle_t *nl, int *flags) { *flags |= O_NONBLOCK; if (fcntl(nl->fd, F_SETFL, *flags) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_SETFL socket : (%s)", strerror(errno)); return -1; } return 0; } /* iproute2 utility function */ int addattr32(struct nlmsghdr *n, int maxlen, int type, uint32_t data) { int len = RTA_LENGTH(4); struct rtattr *rta; if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) return -1; rta = (struct rtattr*)(((char*)n) + NLMSG_ALIGN(n->nlmsg_len)); rta->rta_type = type; rta->rta_len = len; memcpy(RTA_DATA(rta), &data, 4); n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; return 0; } int addattr_l(struct nlmsghdr *n, int maxlen, int type, void *data, int alen) { int len = RTA_LENGTH(alen); struct rtattr *rta; if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) return -1; rta = (struct rtattr *) (((char *) n) + NLMSG_ALIGN(n->nlmsg_len)); rta->rta_type = type; rta->rta_len = len; memcpy(RTA_DATA(rta), data, alen); n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; return 0; } int rta_addattr_l(struct rtattr *rta, int maxlen, int type, const void *data, int alen) { struct rtattr *subrta; int len = RTA_LENGTH(alen); if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen) { return -1; } subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len)); subrta->rta_type = type; subrta->rta_len = len; memcpy(RTA_DATA(subrta), data, alen); rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len); return 0; } static void parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta, int len) { while (RTA_OK(rta, len)) { if (rta->rta_type <= max) tb[rta->rta_type] = rta; rta = RTA_NEXT(rta, len); } } char * netlink_scope_n2a(int scope) { if (scope == 0) return "global"; if (scope == 255) return "nowhere"; if (scope == 254) return "host"; if (scope == 253) return "link"; if (scope == 200) return "site"; return "unknown"; } int netlink_scope_a2n(char *scope) { if (!strcmp(scope, "global")) return 0; if (!strcmp(scope, "nowhere")) return 255; if (!strcmp(scope, "host")) return 254; if (!strcmp(scope, "link")) return 253; if (!strcmp(scope, "site")) return 200; return -1; } /* * Reflect base interface flags on VMAC interface. * VMAC interfaces should never update it own flags, only be reflected * by the base interface flags. */ static void vmac_reflect_flags(struct ifinfomsg *ifi) { interface_t *ifp; /* find the VMAC interface (if any) */ ifp = if_get_by_vmac_base_ifindex(ifi->ifi_index); /* if found, reflect base interface flags on VMAC interface */ if (ifp) { ifp->flags = ifi->ifi_flags; } } /* Our netlink parser */ static int netlink_parse_info(int (*filter) (struct sockaddr_nl *, struct nlmsghdr *), nl_handle_t *nl, struct nlmsghdr *n) { int status; int ret = 0; int error; while (1) { char buf[4096]; struct iovec iov = { buf, sizeof buf }; struct sockaddr_nl snl; struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; struct nlmsghdr *h; status = recvmsg(nl->fd, &msg, 0); if (status < 0) { if (errno == EINTR) continue; if (errno == EWOULDBLOCK || errno == EAGAIN) break; log_message(LOG_INFO, "Netlink: Received message overrun (%m)"); continue; } if (status == 0) { log_message(LOG_INFO, "Netlink: EOF"); return -1; } if (msg.msg_namelen != sizeof snl) { log_message(LOG_INFO, "Netlink: Sender address length error: length %d", msg.msg_namelen); return -1; } for (h = (struct nlmsghdr *) buf; NLMSG_OK(h, status); h = NLMSG_NEXT(h, status)) { /* Finish of reading. */ if (h->nlmsg_type == NLMSG_DONE) return ret; /* Error handling. */ if (h->nlmsg_type == NLMSG_ERROR) { struct nlmsgerr *err = (struct nlmsgerr *) NLMSG_DATA(h); /* * If error == 0 then this is a netlink ACK. * return if not related to multipart message. */ if (err->error == 0) { if (!(h->nlmsg_flags & NLM_F_MULTI)) return 0; continue; } if (h->nlmsg_len < NLMSG_LENGTH(sizeof (struct nlmsgerr))) { log_message(LOG_INFO, "Netlink: error: message truncated"); return -1; } if (n && (err->error == -EEXIST) && ((n->nlmsg_type == RTM_NEWROUTE) || (n->nlmsg_type == RTM_NEWADDR))) return 0; log_message(LOG_INFO, "Netlink: error: %s, type=(%u), seq=%u, pid=%d", strerror(-err->error), err->msg.nlmsg_type, err->msg.nlmsg_seq, err->msg.nlmsg_pid); return -1; } /* Skip unsolicited messages from cmd channel */ if (nl != &nl_cmd && h->nlmsg_pid == nl_cmd.snl.nl_pid) continue; error = (*filter) (&snl, h); if (error < 0) { log_message(LOG_INFO, "Netlink: filter function error"); ret = error; } } /* After error care. */ if (msg.msg_flags & MSG_TRUNC) { log_message(LOG_INFO, "Netlink: error: message truncated"); continue; } if (status) { log_message(LOG_INFO, "Netlink: error: data remnant size %d", status); return -1; } } return ret; } /* Out talk filter */ static int netlink_talk_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { log_message(LOG_INFO, "Netlink: ignoring message type 0x%04x", h->nlmsg_type); return 0; } /* send message to netlink kernel socket, then receive response */ int netlink_talk(nl_handle_t *nl, struct nlmsghdr *n) { int status; int ret, flags; struct sockaddr_nl snl; struct iovec iov = { (void *) n, n->nlmsg_len }; struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; memset(&snl, 0, sizeof snl); snl.nl_family = AF_NETLINK; n->nlmsg_seq = ++nl->seq; /* Request Netlink acknowledgement */ n->nlmsg_flags |= NLM_F_ACK; /* Send message to netlink interface. */ status = sendmsg(nl->fd, &msg, 0); if (status < 0) { log_message(LOG_INFO, "Netlink: sendmsg() error: %s", strerror(errno)); return -1; } /* Set blocking flag */ ret = netlink_set_block(nl, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); status = netlink_parse_info(netlink_talk_filter, nl, n); /* Restore previous flags */ if (ret == 0) netlink_set_nonblock(nl, &flags); return status; } /* Fetch a specific type information from netlink kernel */ static int netlink_request(nl_handle_t *nl, int family, int type) { int status; struct sockaddr_nl snl; struct { struct nlmsghdr nlh; struct rtgenmsg g; } req; /* Cleanup the room */ memset(&snl, 0, sizeof (snl)); snl.nl_family = AF_NETLINK; req.nlh.nlmsg_len = sizeof (req); req.nlh.nlmsg_type = type; req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; req.nlh.nlmsg_pid = 0; req.nlh.nlmsg_seq = ++nl->seq; req.g.rtgen_family = family; status = sendto(nl->fd, (void *) &req, sizeof (req) , 0, (struct sockaddr *) &snl, sizeof (snl)); if (status < 0) { log_message(LOG_INFO, "Netlink: sendto() failed: %s", strerror(errno)); return -1; } return 0; } /* Netlink interface link lookup filter */ static int netlink_if_link_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifinfomsg *ifi; struct rtattr *tb[IFLA_MAX + 1]; interface_t *ifp; int i, len; char *name; ifi = NLMSG_DATA(h); if (h->nlmsg_type != RTM_NEWLINK) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg)); if (len < 0) return -1; /* Interface name lookup */ memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); if (tb[IFLA_IFNAME] == NULL) return -1; name = (char *) RTA_DATA(tb[IFLA_IFNAME]); /* Return if loopback */ if (ifi->ifi_type == ARPHRD_LOOPBACK) return 0; /* Skip it if already exist */ ifp = if_get_by_ifname(name); if (ifp) { if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; } return 0; } /* Fill the interface structure */ ifp = (interface_t *) MALLOC(sizeof(interface_t)); memcpy(ifp->ifname, name, strlen(name)); ifp->ifindex = ifi->ifi_index; ifp->mtu = *(int *) RTA_DATA(tb[IFLA_MTU]); ifp->hw_type = ifi->ifi_type; if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; ifp->base_ifindex = ifi->ifi_index; } if (tb[IFLA_ADDRESS]) { int hw_addr_len = RTA_PAYLOAD(tb[IFLA_ADDRESS]); if (hw_addr_len > IF_HWADDR_MAX) log_message(LOG_ERR, "MAC address for %s is too large: %d", name, hw_addr_len); else { ifp->hw_addr_len = hw_addr_len; memcpy(ifp->hw_addr, RTA_DATA(tb[IFLA_ADDRESS]), hw_addr_len); for (i = 0; i < hw_addr_len; i++) if (ifp->hw_addr[i] != 0) break; if (i == hw_addr_len) ifp->hw_addr_len = 0; else ifp->hw_addr_len = hw_addr_len; } } /* Queue this new interface_t */ if_add_queue(ifp); return 0; } /* * Netlink interface address lookup filter * We need to handle multiple primary address and * multiple secondary address to the same interface. */ static int netlink_if_address_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifaddrmsg *ifa; struct rtattr *tb[IFA_MAX + 1]; interface_t *ifp; int len; void *addr; ifa = NLMSG_DATA(h); /* Only IPV4 are valid us */ if (ifa->ifa_family != AF_INET && ifa->ifa_family != AF_INET6) return 0; if (h->nlmsg_type != RTM_NEWADDR && h->nlmsg_type != RTM_DELADDR) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifaddrmsg)); if (len < 0) return -1; memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFA_MAX, IFA_RTA(ifa), len); /* Fetch interface_t */ ifp = if_get_by_ifindex(ifa->ifa_index); if (!ifp) return 0; if (tb[IFA_LOCAL] == NULL) tb[IFA_LOCAL] = tb[IFA_ADDRESS]; if (tb[IFA_ADDRESS] == NULL) tb[IFA_ADDRESS] = tb[IFA_LOCAL]; /* local interface address */ addr = (tb[IFA_LOCAL] ? RTA_DATA(tb[IFA_LOCAL]) : NULL); if (addr == NULL) return -1; /* If no address is set on interface then set the first time */ if (ifa->ifa_family == AF_INET) { if (!ifp->sin_addr.s_addr) ifp->sin_addr = *(struct in_addr *) addr; } else { if (!ifp->sin6_addr.s6_addr16[0] && ifa->ifa_scope == RT_SCOPE_LINK) ifp->sin6_addr = *(struct in6_addr *) addr; } #ifdef _WITH_LVS_ /* Refresh checkers state */ update_checker_activity(ifa->ifa_family, addr, (h->nlmsg_type == RTM_NEWADDR) ? 1 : 0); #endif return 0; } /* Interfaces lookup bootstrap function */ int netlink_interface_lookup(void) { nl_handle_t nlh; int status = 0; int ret, flags; if (netlink_socket(&nlh, 0) < 0) return -1; /* Set blocking flag */ ret = netlink_set_block(&nlh, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); /* Interface lookup */ if (netlink_request(&nlh, AF_PACKET, RTM_GETLINK) < 0) { status = -1; goto end_int; } status = netlink_parse_info(netlink_if_link_filter, &nlh, NULL); end_int: netlink_close(&nlh); return status; } /* Adresses lookup bootstrap function */ static int netlink_address_lookup(void) { nl_handle_t nlh; int status = 0; int ret, flags; if (netlink_socket(&nlh, 0) < 0) return -1; /* Set blocking flag */ ret = netlink_set_block(&nlh, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); /* IPv4 Address lookup */ if (netlink_request(&nlh, AF_INET, RTM_GETADDR) < 0) { status = -1; goto end_addr; } status = netlink_parse_info(netlink_if_address_filter, &nlh, NULL); /* IPv6 Address lookup */ if (netlink_request(&nlh, AF_INET6, RTM_GETADDR) < 0) { status = -1; goto end_addr; } status = netlink_parse_info(netlink_if_address_filter, &nlh, NULL); end_addr: netlink_close(&nlh); return status; } /* Netlink flag Link update */ static int netlink_reflect_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifinfomsg *ifi; struct rtattr *tb[IFLA_MAX + 1]; interface_t *ifp; int len; ifi = NLMSG_DATA(h); if (!(h->nlmsg_type == RTM_NEWLINK || h->nlmsg_type == RTM_DELLINK)) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg)); if (len < 0) return -1; /* Interface name lookup */ memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); if (tb[IFLA_IFNAME] == NULL) return -1; /* ignore loopback device */ if (ifi->ifi_type == ARPHRD_LOOPBACK) return 0; /* find the interface_t */ ifp = if_get_by_ifindex(ifi->ifi_index); if (!ifp) return -1; /* * Update flags. * VMAC interfaces should never update it own flags, only be reflected * by the base interface flags. */ if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; } return 0; } /* Netlink kernel message reflection */ static int netlink_broadcast_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { switch (h->nlmsg_type) { case RTM_NEWLINK: case RTM_DELLINK: return netlink_reflect_filter(snl, h); break; case RTM_NEWADDR: case RTM_DELADDR: return netlink_if_address_filter(snl, h); break; default: log_message(LOG_INFO, "Kernel is reflecting an unknown netlink nlmsg_type: %d", h->nlmsg_type); break; } return 0; } int kernel_netlink(thread_t * thread) { nl_handle_t *nl = THREAD_ARG(thread); if (thread->type != THREAD_READ_TIMEOUT) netlink_parse_info(netlink_broadcast_filter, nl, NULL); nl->thread = thread_add_read(master, kernel_netlink, nl, nl->fd, NETLINK_TIMER); return 0; } void kernel_netlink_init(void) { unsigned long groups; /* Start with a netlink address lookup */ netlink_address_lookup(); /* * Prepare netlink kernel broadcast channel * subscribtion. We subscribe to LINK and ADDR * netlink broadcast messages. */ groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; netlink_socket(&nl_kernel, groups); if (nl_kernel.fd > 0) { log_message(LOG_INFO, "Registering Kernel netlink reflector"); nl_kernel.thread = thread_add_read(master, kernel_netlink, &nl_kernel, nl_kernel.fd, NETLINK_TIMER); } else log_message(LOG_INFO, "Error while registering Kernel netlink reflector channel"); /* Prepare netlink command channel. */ netlink_socket(&nl_cmd, 0); if (nl_cmd.fd > 0) log_message(LOG_INFO, "Registering Kernel netlink command channel"); else log_message(LOG_INFO, "Error while registering Kernel netlink cmd channel"); } void kernel_netlink_close(void) { netlink_close(&nl_kernel); netlink_close(&nl_cmd); }
xmllovemm/keepalived_modify
keepalived/vrrp/vrrp_netlink.c
C
gpl-2.0
18,234
using System; using System.Collections.Generic; using System.Text; namespace BarcodeLib.Symbologies { class ISBN : BarcodeCommon, IBarcode { public ISBN(string input) { Raw_Data = input; } /// <summary> /// Encode the raw data using the Bookland/ISBN algorithm. /// </summary> private string Encode_ISBN_Bookland() { if (!BarcodeLib.Barcode.CheckNumericOnly(Raw_Data)) Error("EBOOKLANDISBN-1: Numeric Data Only"); string type = "UNKNOWN"; if (Raw_Data.Length == 10 || Raw_Data.Length == 9) { if (Raw_Data.Length == 10) Raw_Data = Raw_Data.Remove(9, 1); Raw_Data = "978" + Raw_Data; type = "ISBN"; }//if else if (Raw_Data.Length == 12 && Raw_Data.StartsWith("978")) { type = "BOOKLAND-NOCHECKDIGIT"; }//else if else if (Raw_Data.Length == 13 && Raw_Data.StartsWith("978")) { type = "BOOKLAND-CHECKDIGIT"; Raw_Data = Raw_Data.Remove(12, 1); }//else if //check to see if its an unknown type if (type == "UNKNOWN") Error("EBOOKLANDISBN-2: Invalid input. Must start with 978 and be length must be 9, 10, 12, 13 characters."); EAN13 ean13 = new EAN13(Raw_Data); return ean13.Encoded_Value; }//Encode_ISBN_Bookland #region IBarcode Members public string Encoded_Value { get { return Encode_ISBN_Bookland(); } } #endregion } }
marhazk/HazTechClass
QRbit4/Sources/BarCodes/Symbologies/ISBN.cs
C#
gpl-2.0
1,721
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'basicstyles', 'en-gb', { bold: 'Bold', italic: 'Italic', strike: 'Strike Through', subscript: 'Subscript', superscript: 'Superscript', underline: 'Underline' } );
SeeyaSia/www
web/libraries/ckeditor/plugins/basicstyles/lang/en-gb.js
JavaScript
gpl-2.0
339
/* * Note: this file originally auto-generated by mib2c using * : mib2c.int_watch.conf 13957 2005-12-20 15:33:08Z tanders $ */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> #include <net-snmp/agent/net-snmp-agent-includes.h> #include "statPPTP.h" #include "triton.h" /* * The variables we want to tie the relevant OIDs to. * The agent will handle all GET and (if applicable) SET requests * to these variables automatically, changing the values as needed. */ void pptp_get_stat(unsigned int **, unsigned int **); static unsigned int *stat_starting; static unsigned int *stat_active; /* * Our initialization routine, called automatically by the agent * (Note that the function name must match init_FILENAME()) */ void init_statPPTP(void) { netsnmp_handler_registration *reg; netsnmp_watcher_info *winfo; static oid statPPTPStarting_oid[] = { 1,3,6,1,4,1,8072,100,1,3,1 }; static oid statPPTPActive_oid[] = { 1,3,6,1,4,1,8072,100,1,3,2 }; /* * a debugging statement. Run the agent with -DstatPPTP to see * the output of this debugging statement. */ DEBUGMSGTL(("statPPTP", "Initializing the statPPTP module\n")); if (!triton_module_loaded("pptp")) return; pptp_get_stat(&stat_starting, &stat_active); /* * Register scalar watchers for each of the MIB objects. * The ASN type and RO/RW status are taken from the MIB definition, * but can be adjusted if needed. * * In most circumstances, the scalar watcher will handle all * of the necessary processing. But the NULL parameter in the * netsnmp_create_handler_registration() call can be used to * supply a user-provided handler if necessary. * * This approach can also be used to handle Counter64, string- * and OID-based watched scalars (although variable-sized writeable * objects will need some more specialised initialisation). */ DEBUGMSGTL(("statPPTP", "Initializing statPPTPStarting scalar integer. Default value = %d\n", 0)); reg = netsnmp_create_handler_registration( "statPPTPStarting", NULL, statPPTPStarting_oid, OID_LENGTH(statPPTPStarting_oid), HANDLER_CAN_RONLY); winfo = netsnmp_create_watcher_info( stat_starting, sizeof(*stat_starting), ASN_INTEGER, WATCHER_FIXED_SIZE); if (netsnmp_register_watched_scalar( reg, winfo ) < 0 ) { snmp_log( LOG_ERR, "Failed to register watched statPPTPStarting" ); } DEBUGMSGTL(("statPPTP", "Initializing statPPTPActive scalar integer. Default value = %d\n", 0)); reg = netsnmp_create_handler_registration( "statPPTPActive", NULL, statPPTPActive_oid, OID_LENGTH(statPPTPActive_oid), HANDLER_CAN_RONLY); winfo = netsnmp_create_watcher_info( stat_active, sizeof(*stat_active), ASN_INTEGER, WATCHER_FIXED_SIZE); if (netsnmp_register_watched_scalar( reg, winfo ) < 0 ) { snmp_log( LOG_ERR, "Failed to register watched statPPTPActive" ); } DEBUGMSGTL(("statPPTP", "Done initalizing statPPTP module\n")); }
musman2012/commented-accel
accel-pppd/extra/net-snmp/statPPTP.c
C
gpl-2.0
3,252
.ultb3-box { width: 100%; display: block; position: relative; background: #f2f2f2; overflow: hidden } img.ultb3-img { border: 0; -webkit-box-shadow: none; box-shadow: none; max-width: none; width: auto !important; float: none; margin: 0 auto; display: block; position: absolute; z-index: 1; -webkit-transition: all 300ms linear; transition: all 300ms linear } .ultb3-box-overlay { background: rgba(0, 0, 0, 0.5); position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2 } .ultb3-info { padding: 25px; position: relative; z-index: 5 } .ultb3-info.ib3-info-center { text-align: center } .ultb3-info.ib3-info-right { text-align: right } img.ultb3-img.ultb3-img-top-center { left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } img.ultb3-img.ultb3-img-top-right { left: auto; right: 0 } img.ultb3-img.ultb3-img-center-left { top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } img.ultb3-img.ultb3-img-center { top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } img.ultb3-img.ultb3-img-center-right { top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); left: auto; right: 0 } img.ultb3-img.ultb3-img-bottom-left, img.ultb3-img.ultb3-img-bottom-center, img.ultb3-img.ultb3-img-bottom-right { top: auto; bottom: 0 } img.ultb3-img.ultb3-img-bottom-center { left: 50%; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } img.ultb3-img.ultb3-img-bottom-right { right: 0; left: auto } .ultb3-title { font-size: 40px; color: #252525; line-height: 1.35em; margin-bottom: 5px } .ultb3-desc { font-size: 20px; line-height: 1.5em; margin-bottom: 10px } a.ultb3-btn { display: inline-block; color: #0483d9; text-align: center; font-size: 20px; padding: 15px 25px; -webkit-border-radius: 30px; border-radius: 30px; border: 2px solid #0483d9; position: relative; text-decoration: none; -webkit-transition: all .2s; transition: all .2s } a.ultb3-btn i { position: absolute; left: auto; right: 25px; top: 50%; opacity: 0; width: auto; height: auto; font-size: inherit !important; -webkit-transition: all .25s; transition: all .25s; -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%) } a.ultb3-btn:hover i { right: 20px; opacity: 1 } a.ultb3-btn:hover { padding-right: 45px } a.ultb3-btn:hover; a.ultb3-btn:focus; a.ultb3-btn:active; a.ultb3-btn:visited { text-decoration: none; color: inherit; outline: 0 } .ultb3-hover-1 .ultb3-img.ultb3-img-top-left, .ultb3-hover-1 .ultb3-img.ultb3-img-top-center, .ultb3-hover-1 .ultb3-img.ultb3-img-top-right { top: -50px } .ultb3-hover-1:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-1:hover .ultb3-img.ultb3-img-top-center, .ultb3-hover-1:hover .ultb3-img.ultb3-img-top-right { top: 0 } .ultb3-hover-1 .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-1:hover .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-25%); -ms-transform: translateY(-25%); transform: translateY(-25%) } .ultb3-hover-1 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-1:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -25%); -ms-transform: translate(-50%, -25%); transform: translate(-50%, -25%) } .ultb3-hover-1 .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-1:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-25%); -ms-transform: translateY(-25%); transform: translateY(-25%) } .ultb3-hover-1 .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-1 .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-1 .ultb3-img.ultb3-img-bottom-right { bottom: 0 } .ultb3-hover-1:hover .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-1:hover .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-1:hover .ultb3-img.ultb3-img-bottom-right { bottom: -50px } .ultb3-hover-2 .ultb3-img.ultb3-img-top-left, .ultb3-hover-2 .ultb3-img.ultb3-img-top-center, .ultb3-hover-2 .ultb3-img.ultb3-img-top-right { top: 0 } .ultb3-hover-2:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-2:hover .ultb3-img.ultb3-img-top-center, .ultb3-hover-2:hover .ultb3-img.ultb3-img-top-right { top: -50px } .ultb3-hover-2 .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-2:hover .ultb3-img.ultb3-img-center-left { -webkit-transform: translateY(-75%); -ms-transform: translateY(-75%); transform: translateY(-75%) } .ultb3-hover-2 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-2:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -75%); -ms-transform: translate(-50%, -75%); transform: translate(-50%, -75%) } .ultb3-hover-2 .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%) } .ultb3-hover-2:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translateY(-75%); -ms-transform: translateY(-75%); transform: translateY(-75%) } .ultb3-hover-2 .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-2 .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-2 .ultb3-img.ultb3-img-bottom-right { bottom: -50px } .ultb3-hover-2:hover .ultb3-img.ultb3-img-bottom-left, .ultb3-hover-2:hover .ultb3-img.ultb3-img-bottom-center, .ultb3-hover-2:hover .ultb3-img.ultb3-img-bottom-right { bottom: 0 } .ultb3-hover-3 .ultb3-img.ultb3-img-top-left, .ultb3-hover-3 .ultb3-img.ultb3-img-center-left { left: 0 } .ultb3-hover-3:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-3:hover .ultb3-img.ultb3-img-center-left { left: -50px } .ultb3-hover-3 .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-25%); -ms-transform: translateX(-25%); transform: translateX(-25%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } .ultb3-hover-3 .ultb3-img.ultb3-img-top-right, .ultb3-hover-3 .ultb3-img.ultb3-img-bottom-right { right: -50px } .ultb3-hover-3:hover .ultb3-img.ultb3-img-top-right, .ultb3-hover-3:hover .ultb3-img.ultb3-img-bottom-right { right: 0 } .ultb3-hover-3 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-75%, -50%); -ms-transform: translate(-75%, -50%); transform: translate(-75%, -50%) } .ultb3-hover-3 .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(25%, -50%); -ms-transform: translate(25%, -50%); transform: translate(25%, -50%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%) } .ultb3-hover-3 .ultb3-img.ultb3-img-bottom-left { left: 0 } .ultb3-hover-3:hover .ultb3-img.ultb3-img-bottom-left { left: -50px } .ultb3-hover-3 .ultb3-img.ultb3-img-bottom-center { -webkit-transform: translate(-50%); -ms-transform: translate(-50%); transform: translate(-50%) } .ultb3-hover-3:hover .ultb3-img.ultb3-img-bottom-center { -webkit-transform: translate(-75%); -ms-transform: translate(-75%); transform: translate(-75%) } .ultb3-hover-4 .ultb3-img.ultb3-img-top-left, .ultb3-hover-4 .ultb3-img.ultb3-img-center-left { left: -50px } .ultb3-hover-4:hover .ultb3-img.ultb3-img-top-left, .ultb3-hover-4:hover .ultb3-img.ultb3-img-center-left { left: 0 } .ultb3-hover-4 .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-75%); -ms-transform: translateX(-75%); transform: translateX(-75%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-top-center { -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%) } .ultb3-hover-4 .ultb3-img.ultb3-img-top-right, .ultb3-hover-4 .ultb3-img.ultb3-img-bottom-right { right: 0 } .ultb3-hover-4:hover .ultb3-img.ultb3-img-top-right, .ultb3-hover-4:hover .ultb3-img.ultb3-img-bottom-right { right: -50px } .ultb3-hover-4 .ultb3-img.ultb3-img-center { -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-center { -webkit-transform: translate(-25%, -50%); -ms-transform: translate(-25%, -50%); transform: translate(-25%, -50%) } .ultb3-hover-4 .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-center-right { -webkit-transform: translate(25%, -50%); -ms-transform: translate(25%, -50%); transform: translate(25%, -50%) } .ultb3-hover-4 .ultb3-img.ultb3-img-bottom-left { left: -50px } .ultb3-hover-4:hover .ultb3-img.ultb3-img-bottom-left { left: 0 } .ultb3-hover-4 .ultb3-img.ultb3-img-bottom-center { -webkit-transform: translate(-50%); -ms-transform: translate(-50%); transform: translate(-50%) } .ultb3-hover-4:hover .ultb3-img.ultb3-img-bottom-center { transform: translate(-25%); -webkit-transform: translate(-25%); -moz-transform: translate(-25%); -ms-transform: translate(-25%); -o-transform: translate(-25%) } .ultb3-hover-5 .ultb3-img { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1) } .ultb3-hover-5:hover .ultb3-img { -webkit-transform: scale(1.1); -ms-transform: scale(1.1); transform: scale(1.1) } .ultb3-hover-6 .ultb3-img { -webkit-transform: scale(1); -ms-transform: scale(1); transform: scale(1); opacity: 1 } .ultb3-hover-6:hover .ultb3-img { -webkit-transform: scale(2.5); -ms-transform: scale(2.5); transform: scale(2.5); opacity: 0 }
dans-lweb/immunoconcept
wp-content/plugins/Ultimate_VC_Addons/assets/css/info-banner.css
CSS
gpl-2.0
10,982
/* * #%L * Fork of MDB Tools (Java port). * %% * Copyright (C) 2008 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /* * Created on Jan 14, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package mdbtools.libmdb06util; /** * @author calvin * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class mdbver { public static void main(String[] args) { } }
ctrueden/bioformats
components/forks/mdbtools/src/mdbtools/libmdb06util/mdbver.java
Java
gpl-2.0
1,360
/* * Copyright 1999-2001 Sun Microsystems, Inc. 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. * * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * */ class Optimizer VALUE_OBJ_CLASS_SPEC { private: IR* _ir; public: Optimizer(IR* ir); IR* ir() const { return _ir; } // optimizations void eliminate_conditional_expressions(); void eliminate_blocks(); void eliminate_null_checks(); };
guanxiaohua/TransGC
src/share/vm/c1/c1_Optimizer.hpp
C++
gpl-2.0
1,342
namespace Server.Items { public class DestroyingAngel : BaseReagent, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public DestroyingAngel() : this( 1 ) { } [Constructable] public DestroyingAngel( int amount ) : base( 0xE1F ) { Stackable = true; Weight = 0.0; Amount = amount; Name = "Destroying Angel"; Hue = 0x290; } public DestroyingAngel( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class PetrafiedWood : BaseReagent, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public PetrafiedWood() : this( 1 ) { } [Constructable] public PetrafiedWood( int amount ) : base( 0x97A ) { Stackable = true; Weight = 0.0; Amount = amount; Name = "Petrafied Wood"; Hue = 0x46C; } public PetrafiedWood( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class SpringWater : BaseReagent, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public SpringWater() : this( 1 ) { } [Constructable] public SpringWater( int amount ) : base( 0xE24 ) { Stackable = true; Weight = 0.0; Amount = amount; Name = "Spring Water"; Hue = 0x47F; } public SpringWater( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
cmileto/neverybody
Scripts/Custom/New Systems/OWLTR/New/Druid Reagents.cs
C#
gpl-2.0
2,326
/** * Drupal-specific JS helper functions and utils. Not to be confused with the * Recline library, which should live in your libraries directory. */ ;(function ($) { // Constants. var MAX_LABEL_WIDTH = 77; var LABEL_MARGIN = 5; // Undefined variables. var dataset, views, datasetOptions, fileSize, fileType, router; var dataExplorerSettings, state, $explorer, dataExplorer, maxSizePreview; var datastoreStatus; // Create drupal behavior Drupal.behaviors.Recline = { attach: function (context) { $explorer = $('.data-explorer'); // Local scoped variables. Drupal.settings.recline = Drupal.settings.recline || {}; fileSize = Drupal.settings.recline.fileSize; fileType = Drupal.settings.recline.fileType; maxSizePreview = Drupal.settings.recline.maxSizePreview; datastoreStatus = Drupal.settings.recline.datastoreStatus; dataExplorerSettings = { grid: Drupal.settings.recline.grid, graph: Drupal.settings.recline.graph, map: Drupal.settings.recline.map }; // This is the very basic state collection. state = recline.View.parseQueryString(decodeURIComponent(window.location.hash)); if ('#map' in state) { state.currentView = 'map'; } else if ('#graph' in state) { state.currentView = 'graph'; } // Init the explorer. init(); // Attach toogle event. $('.recline-embed a.embed-link').on('click', function(){ $(this).parents('.recline-embed').find('.embed-code-wrapper').toggle(); return false; }); } } // make Explorer creation / initialization in a function so we can call it // again and again function createExplorer (dataset, state, settings) { // Remove existing data explorer view. dataExplorer && dataExplorer.remove(); var $el = $('<div />'); $el.appendTo($explorer); var views = []; if (settings.grid) { views.push({ id: 'grid', label: 'Grid', view: new recline.View.SlickGrid({ model: dataset }) }); } if (settings.graph) { state.graphOptions = { xaxis: { tickFormatter: tickFormatter(dataset), }, hooks:{ processOffset: [processOffset(dataset)], bindEvents: [bindEvents], } }; views.push({ id: 'graph', label: 'Graph', view: new recline.View.Graph({ model: dataset, state: state }) }); } if (settings.map) { views.push({ id: 'map', label: 'Map', view: new recline.View.Map({ model: dataset, options: { mapTilesURL: '//stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png', } }) }); } // Multiview settings var multiviewOptions = { model: dataset, el: $el, state: state, views: views }; // Getting base embed url. var urlBaseEmbed = $('.embed-code').text(); var iframeOptions = {src: urlBaseEmbed, width:850, height:400}; // Attaching router to dataexplorer state. dataExplorer = new recline.View.MultiView(multiviewOptions); router = new recline.DeepLink.Router(dataExplorer); // Adding router listeners. var changeEmbedCode = getEmbedCode(iframeOptions); router.on('init', changeEmbedCode); router.on('stateChange', changeEmbedCode); // Add map dependency just for map views. _.each(dataExplorer.pageViews, function(item, index){ if(item.id && item.id === 'map'){ var map = dataExplorer.pageViews[index].view.map; router.addDependency(new recline.DeepLink.Deps.Map(map, router)); } }); // Start to track state chages. router.start(); $.event.trigger('createDataExplorer'); return views; } // Returns the dataset configuration. function getDatasetOptions () { var datasetOptions = {}; var delimiter = Drupal.settings.recline.delimiter; var file = Drupal.settings.recline.file; var uuid = Drupal.settings.recline.uuid; // Get correct file location, make sure not local file = (getOrigin(window.location) !== getOrigin(file)) ? '/node/' + Drupal.settings.recline.uuid + '/data' : file; // Select the backend to use switch(getBackend(datastoreStatus, fileType)) { case 'csv': datasetOptions = { backend: 'csv', url: file, delimiter: delimiter }; break; case 'tsv': datasetOptions = { backend: 'csv', url: file, delimiter: delimiter }; break; case 'txt': datasetOptions = { backend: 'csv', url: file, delimiter: delimiter }; break; case 'ckan': datasetOptions = { endpoint: 'api', id: uuid, backend: 'ckan' }; break; case 'xls': datasetOptions = { backend: 'xls', url: file }; break; case 'dataproxy': datasetOptions = { url: file, backend: 'dataproxy' }; break; default: showError('File type ' + fileType + ' not supported for preview.'); break; } return datasetOptions; } // Correct for fact that IE does not provide .origin function getOrigin(u) { var url = parseURL(u); return url.protocol + '//' + url.hostname + (url.port ? (':' + url.port) : ''); } // Parse a simple URL string to get its properties function parseURL(url) { var parser = document.createElement('a'); parser.href = url; return { protocol: parser.protocol, hostname: parser.hostname, port: parser.port, pathname: parser.pathname, search: parser.search, hash: parser.hash, host: parser.host } } // Retrieve a backend given a file type and and a datastore status. function getBackend (datastoreStatus, fileType) { // If it's inside the datastore then we use the dkan API if (datastoreStatus) return 'ckan'; var formats = { 'csv': ['text/csv', 'csv'], 'xls': ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], 'tsv': ['text/tab-separated-values', 'text/tsv', 'tsv', 'tab'], 'txt': ['text/plain', 'txt'], }; var backend = _.findKey(formats, function(format) { return _.include(format, fileType) }); // If the backend is a txt but the delimiter is not a tab, we don't need // to show it using the backend. if (Drupal.settings.recline.delimiter !== "\t" && backend === 'txt') {return '';} // If the backend is an xls but the browser version is prior 9 then // we need to fallback to dataproxy if (backend === 'xls' && document.documentMode < 9) return 'dataproxy'; return backend; } // Displays an error retrieved from the response object. function showRequestError (response) { // Actually dkan doesn't provide standarization over // error handling responses. For example: if you request // unexistent resources it will retrive an array with a // message inside. // Recline backends will return an object with an error. try { var ro = (typeof response === 'string') ? JSON.parse(response) : response; if(ro.error) { showError(ro.error.message) } else if(ro instanceof Array) { showError(ro[0]); } } catch (error) { showError(response); } } // Displays an error. function showError (message) { $explorer.html('<div class="messages error">' + message + '</div>'); } // Creates the embed code. function getEmbedCode (options){ return function(state){ var iframeOptions = _.clone(options); var iframeTmpl = _.template('<iframe width="<%= width %>" height="<%= height %>" src="<%= src %>" frameborder="0"></iframe>'); var previewTmpl = _.template('<%= src %>'); _.extend(iframeOptions, {src: iframeOptions.src + '#' + (state.serializedState || '')}); var html = iframeTmpl(iframeOptions); $('.embed-code').text(html); var preview = previewTmpl(iframeOptions); $('.preview-code').text(preview); }; } // Creates the preview url code. function getPreviewCode (options){ return function(state){ var previewOptions = _.clone(options); var previewTmpl = _.template('<%= src %>'); _.extend(previewOptions, {src: previewOptions.src + '#' + (state.serializedState || '')}); var html = previewTmpl(previewOptions); $('.preview-url').text(html); }; } // Check if a chart has their axis inverted. function isInverted (){ return dataExplorer.pageViews[1].view.state.attributes.graphType === 'bars'; } // Computes the width of a chart. function computeWidth (plot, labels) { var biggerLabel = ''; for( var i = 0; i < labels.length; i++){ if(labels[i].length > biggerLabel.length && !_.isUndefined(labels[i])){ biggerLabel = labels[i]; } } var canvas = plot.getCanvas(); var ctx = canvas.getContext('2d'); ctx.font = 'sans-serif smaller'; return ctx.measureText(biggerLabel).width; } // Resize a chart. function resize (plot) { var itemWidth = computeWidth(plot, _.pluck(plot.getXAxes()[0].ticks, 'label')); var graph = dataExplorer.pageViews[1]; if(!isInverted() && $('#prevent-label-overlapping').is(':checked')){ var canvasWidth = Math.min(itemWidth + LABEL_MARGIN, MAX_LABEL_WIDTH) * plot.getXAxes()[0].ticks.length; var canvasContainerWith = $('.panel.graph').parent().width(); if(canvasWidth < canvasContainerWith){ canvasWidth = canvasContainerWith; } $('.panel.graph').width(canvasWidth); $('.recline-flot').css({overflow:'auto'}); }else{ $('.recline-flot').css({overflow:'hidden'}); $('.panel.graph').css({width: '100%'}); } plot.resize(); plot.setupGrid(); plot.draw(); } // Bind events after chart resizes. function bindEvents (plot, eventHolder) { var p = plot || dataExplorer.pageViews[1].view.plot; resize(p); setTimeout(addCheckbox, 0); } // Compute the chart offset to display ticks properly. function processOffset (dataset) { return function(plot, offset) { if(dataExplorer.pageViews[1].view.xvaluesAreIndex){ var series = plot.getData(); for (var i = 0; i < series.length; i++) { var numTicks = Math.min(dataset.records.length, 200); var ticks = []; for (var j = 0; j < dataset.records.length; j++) { ticks.push(parseInt(j, 10)); } if(isInverted()){ series[i].yaxis.options.ticks = ticks; }else{ series[i].xaxis.options.ticks = ticks; } } } }; } // Format ticks base on previews computations. function tickFormatter (dataset){ return function (x) { x = parseInt(x, 10); try { if(isInverted()) return x; var field = dataExplorer.pageViews[1].view.state.get('group'); var label = dataset.records.models[x].get(field) || ''; if(!moment(String(label)).isValid() && !isNaN(parseInt(label, 10))){ label = parseInt(label, 10) - 1; } return label; } catch(e) { return x; } }; } // Add checkbox to control resize behavior. function addCheckbox () { $control = $('.form-stacked:visible').find('#prevent-label-overlapping'); if(!$control.length){ $form = $('.form-stacked'); $checkboxDiv = $('<div class="checkbox"></div>').appendTo($form); $label = $('<label />', { 'for': 'prevent-label-overlapping', text: 'Resize graph to prevent label overlapping' }).appendTo($checkboxDiv); $label.prepend($('<input />', { type: 'checkbox', id: 'prevent-label-overlapping', value: '' })); $control = $('#prevent-label-overlapping'); $control.on('change', function(){ resize(dataExplorer.pageViews[1].view.plot); }); } } // Init the multiview. function init () { if(fileSize < maxSizePreview || datastoreStatus) { dataset = new recline.Model.Dataset(getDatasetOptions()); dataset.fetch().fail(showRequestError); views = createExplorer(dataset, state, dataExplorerSettings); views.forEach(function(view) { view.id === 'map' && view.view.redraw('refresh') }); } else { showError('File was too large or unavailable for preview.'); } } })(jQuery);
NuCivic/recline
recline.js
JavaScript
gpl-2.0
13,387
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="refresh" content="0;url=help.php?module=questionnaire&amp;file=fieldlength.html" /> <title>redirect</title> </head> <body> <p> しばらくお待ち下さい。 </p> </body> </html>
orvsd/moodle19
mod/questionnaire/lang/ja_utf8/help/questionnaire/maxtextlength.html
HTML
gpl-2.0
442
/* * Copyright (C) 2011-2012 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * Modifyed by: Edison Fernández <edison.fernandez@ridgerun.com> * Added support to use it with Nitrogen6x * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/ctype.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/clk.h> #include <linux/i2c.h> #include <linux/mfd/syscon.h> #include <linux/mfd/syscon/imx6q-iomuxc-gpr.h> #include <linux/of_gpio.h> #include <linux/regulator/consumer.h> #include <linux/fsl_devices.h> #include <linux/mutex.h> #include <linux/mipi_csi2.h> #include <linux/pwm.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-int-device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/jack.h> #include <sound/soc-dapm.h> #include <asm/mach-types.h> //#include <mach/audmux.h> #include <linux/slab.h> #include "mxc_v4l2_capture.h" #define CODEC_CLOCK 16500000 /* SSI clock sources */ #define IMX_SSP_SYS_CLK 0 #define TC358743_VOLTAGE_ANALOG 2800000 #define TC358743_VOLTAGE_DIGITAL_CORE 1500000 #define TC358743_VOLTAGE_DIGITAL_IO 1800000 #define MIN_FPS 30 #define MAX_FPS 60 #define DEFAULT_FPS 60 #define TC358743_XCLK_MIN 27000000 #define TC358743_XCLK_MAX 42000000 #define TC358743_CHIP_ID_HIGH_BYTE 0x0 #define TC358743_CHIP_ID_LOW_BYTE 0x0 #define TC3587430_HDMI_DETECT 0x0f //0x10 #define TC_VOLTAGE_ANALOG 2800000 #define TC_VOLTAGE_DIGITAL_CORE 1500000 #define TC_VOLTAGE_DIGITAL_IO 1800000 enum tc358743_mode { tc358743_mode_INIT, /*only for sensor init*/ tc358743_mode_INIT1, /*only for sensor init*/ tc358743_mode_480P_720_480, tc358743_mode_720P_60_1280_720, tc358743_mode_480P_640_480, tc358743_mode_1080P_1920_1080, tc358743_mode_INIT2, /*only for sensor init*/ tc358743_mode_INIT3, /*only for sensor init*/ tc358743_mode_INIT4, /*only for sensor init*/ tc358743_mode_INIT5, /*only for sensor init*/ tc358743_mode_INIT6, /*only for sensor init*/ tc358743_mode_720P_1280_720, tc358743_mode_MAX , }; enum tc358743_frame_rate { tc358743_60_fps, tc358743_30_fps, tc358743_max_fps }; struct reg_value { u16 u16RegAddr; u32 u32Val; u32 u32Mask; u8 u8Length; u32 u32Delay_ms; }; struct tc358743_mode_info { enum tc358743_mode mode; u32 width; u32 height; u32 vformat; u32 fps; u32 lanes; u32 freq; struct reg_value *init_data_ptr; u32 init_data_size; __u32 flags; }; static struct delayed_work det_work; static struct sensor_data tc358743_data; static int pwn_gpio, rst_gpio; static struct regulator *io_regulator; static struct regulator *core_regulator; static struct regulator *analog_regulator; static struct regulator *gpo_regulator; static u16 hpd_active = 1; #define DET_WORK_TIMEOUT_DEFAULT 100 #define DET_WORK_TIMEOUT_DEFERRED 2000 #define MAX_BOUNCE 5 static DEFINE_MUTEX(access_lock); static int det_work_disable = 0; static int det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; static u32 hdmi_mode = 0, lock = 0, bounce = 0, fps = 0, audio = 2; static int tc358743_init_mode(enum tc358743_frame_rate frame_rate, enum tc358743_mode mode); static int tc358743_toggle_hpd(int active); static void tc_standby(s32 enable) { if (gpio_is_valid(pwn_gpio)) gpio_set_value(pwn_gpio, enable ? 1 : 0); pr_debug("tc_standby: powerdown=%x, power_gp=0x%x\n", enable, pwn_gpio); msleep(2); } static void tc_reset(void) { /* camera reset */ gpio_set_value(rst_gpio, 1); /* camera power dowmn */ if (gpio_is_valid(pwn_gpio)) { gpio_set_value(pwn_gpio, 1); msleep(5); gpio_set_value(pwn_gpio, 0); } msleep(5); gpio_set_value(rst_gpio, 0); msleep(1); gpio_set_value(rst_gpio, 1); msleep(20); if (gpio_is_valid(pwn_gpio)) gpio_set_value(pwn_gpio, 1); } static int tc_power_on(struct device *dev) { int ret = 0; io_regulator = devm_regulator_get(dev, "DOVDD"); if (!IS_ERR(io_regulator)) { regulator_set_voltage(io_regulator, TC_VOLTAGE_DIGITAL_IO, TC_VOLTAGE_DIGITAL_IO); ret = regulator_enable(io_regulator); if (ret) { pr_err("%s:io set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:io set voltage ok\n", __func__); } } else { pr_err("%s: cannot get io voltage error\n", __func__); io_regulator = NULL; } core_regulator = devm_regulator_get(dev, "DVDD"); if (!IS_ERR(core_regulator)) { regulator_set_voltage(core_regulator, TC_VOLTAGE_DIGITAL_CORE, TC_VOLTAGE_DIGITAL_CORE); ret = regulator_enable(core_regulator); if (ret) { pr_err("%s:core set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:core set voltage ok\n", __func__); } } else { core_regulator = NULL; pr_err("%s: cannot get core voltage error\n", __func__); } analog_regulator = devm_regulator_get(dev, "AVDD"); if (!IS_ERR(analog_regulator)) { regulator_set_voltage(analog_regulator, TC_VOLTAGE_ANALOG, TC_VOLTAGE_ANALOG); ret = regulator_enable(analog_regulator); if (ret) { pr_err("%s:analog set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:analog set voltage ok\n", __func__); } } else { analog_regulator = NULL; pr_err("%s: cannot get analog voltage error\n", __func__); } return ret; } static void det_work_enable(int i) { mutex_lock(&access_lock); if (i) { det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); det_work_disable = 0; } else { det_work_disable = 1; det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; } mutex_unlock(&access_lock); pr_debug("%s: %d %d\n", __func__, det_work_disable, det_work_timeout); } static u8 cHDMIEDID[256] = { /* FIXME! This is the edid that my ASUS HDMI monitor returns */ 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x04, 0x69, 0xf3, 0x24, 0xd6, 0x12, 0x00, 0x00, 0x16, 0x16, 0x01, 0x03, 0x80, 0x34, 0x1d, 0x78, 0x2a, 0xc7, 0x20, 0xa4, 0x55, 0x49, 0x99, 0x27, 0x13, 0x50, 0x54, 0xbf, 0xef, 0x00, 0x71, 0x4f, 0x81, 0x40, 0x81, 0x80, 0x95, 0x00, 0xb3, 0x00, 0xd1, 0xc0, 0x01, 0x01, 0x01, 0x01, 0x02, 0x3a, 0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c, 0x45, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x43, 0x36, 0x4c, 0x4d, 0x54, 0x46, 0x30, 0x30, 0x34, 0x38, 0x32, 0x32, 0x0a, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x37, 0x4b, 0x1e, 0x55, 0x10, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x41, 0x53, 0x55, 0x53, 0x20, 0x56, 0x48, 0x32, 0x34, 0x32, 0x48, 0x0a, 0x20, 0x01, 0x78, 0x02, 0x03, 0x22, 0x71, 0x4f, 0x01, 0x02, 0x03, 0x11, 0x12, 0x13, 0x04, 0x14, 0x05, 0x0e, 0x0f, 0x1d, 0x1e, 0x1f, 0x10, 0x23, 0x09, 0x07, 0x01, 0x83, 0x01, 0x00, 0x00, 0x65, 0x03, 0x0c, 0x00, 0x10, 0x00, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x01, 0x1d, 0x00, 0xbc, 0x52, 0xd0, 0x1e, 0x20, 0xb8, 0x28, 0x55, 0x40, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40, 0x55, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, }; /*! * Maintains the information on the current state of the sesor. */ static struct reg_value tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000402d, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000001, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004800, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa300be82, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x0000008c, 0x00000000, 1, 0}, {0x8541, 0x0000000a, 0x00000000, 1, 0}, {0x8630, 0x000000b0, 0x00000000, 1, 0}, {0x8631, 0x0000001e, 0x00000000, 1, 0}, {0x8632, 0x00000004, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, // {0x8544, 0x00000000, 0x00000000, 1, 1000}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // Video settings {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, // {0x8651, 0x00000003, 0x00000000, 1, 0}, // Inverted LRCK polarity - (Sony) format {0x8652, 0x00000002, 0x00000000, 1, 0}, // Left-justified I2S (Phillips) format // {0x8652, 0x00000000, 0x00000000, 1, 0}, // Right-justified (Sony) format {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0014, 0x0000ffff, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00004062, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa300be86, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 0}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion // {0x8574, 0x00000000, 0x00000000, 1, 0}, {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000006, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x00000007, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a2, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000580, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000006, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001F, 0x00000000, 4, 0}, //{0x0234, 0x00000007, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, //{0x0500, 0xa30080a2, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000300, 0x00000000, 2, 0}, //{0x7092, 0x00000580, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00004050, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001800, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00001102, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000007, 0x00000000, 4, 0}, {0x022c, 0x00000001, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000800, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x0020, 0x0000406f, 0x00000000, 2, 100}, {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000540, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x000006b8, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1920x1023 colorbar {0x000a, 0x00000f00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 1023 lines {0x7090, 0x000003fe, 0x00000000, 2, 0}, {0x7092, 0x000004d8, 0x00000000, 2, 0}, {0x7094, 0x0000002d, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00008073, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, // {0x014c, 0x00000000, 0x00000000, 4, 0}, // {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001200, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00000b02, 0x00000000, 4, 0}, {0x021c, 0x00000001, 0x00000000, 4, 0}, {0x0220, 0x00000103, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000000, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA3008082, 0x00000000, 4, 0}, // 640x480 colorbar {0x000a, 0x00000500, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 80 pixel black - repeate 80 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(80<<16)}, // 80 pixel blue - repeate 40 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel red - repeate 40 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel pink - repeate 40 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel green - repeate 40 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel light blue - repeate 40 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel yellow - repeate 40 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel white - repeate 40 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(40<<16)}, // 480 lines {0x7090, 0x000001df, 0x00000000, 2, 0}, {0x7092, 0x00000898, 0x00000000, 2, 0}, {0x7094, 0x00000285, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000404F, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001800, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00001102, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000007, 0x00000000, 4, 0}, {0x022c, 0x00000001, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // 640x480 colorbar {0x000a, 0x00000500, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 80 pixel black - repeate 80 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(80<<16)}, // 80 pixel blue - repeate 40 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel red - repeate 40 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel pink - repeate 40 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel green - repeate 40 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel light blue - repeate 40 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel yellow - repeate 40 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel white - repeate 40 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(40<<16)}, // 480 lines {0x7090, 0x000001df, 0x00000000, 2, 0}, {0x7092, 0x00000700, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; //480p RGB2YUV442 static struct reg_value tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, // {0x000a, 0x000005a0, 0x00000000, 2, 0}, // {0x0010, 0x0000001e, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 100}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; //480p RGB2YUV442 static struct reg_value tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, {0x000a, 0x000005a0, 0x00000000, 2, 0}, // {0x0010, 0x0000001e, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405b, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 100}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100},//0}, {0x0002, 0x00000000, 0x00000000, 2, 1000},//0}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000010, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8571, 0x00000002, 0x00000000, 1, 0}, {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8576, 0x00000060, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, // IR control resister {0x0004, 0x00000084, 0x00000000, 2, 0}, // Internal Generated output pattern,Do not send InfoFrame data out to CSI2,Audio output to CSI2-TX i/f,I2C address index increments on every data byte transfer, disable audio and video TX buffers {0x0002, 0x00000f00, 0x00000000, 2, 100},//0}, // Reset devices and set normal operatio (not sleep) {0x0002, 0x00000000, 0x00000000, 2, 1000},//0}, // Clear reset bits {0x0006, 0x000001f8, 0x00000000, 2, 0}, // FIFO level = 1f8 = 504 {0x0014, 0x00000000, 0x00000000, 2, 0}, // Clear interrupt status bits {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Mask audio mute, CSI-TX, and the other interrups // Program CSI Tx PLL //{0x0020, 0x000080c7, 0x00000000, 2, 0}, // Input divider setting = 0x8 -> Division ratio = (PRD3..0) + 1 = 9, Feedback divider setting = 0xc7 -> Division ratio = (FBD8...0) + 1 = 200 {0x0020, 0x000080c7, 0x00000000, 2, 0}, // Input divider setting = 0x8 -> Division ratio = (PRD3..0) + 1 = 9, Feedback divider setting = 0xc7 -> Division ratio = (FBD8...0) + 1 = 200 {0x0022, 0x00000213, 0x00000000, 2, 0}, // HSCK frequency = 500MHz – 1GHz HSCK frequency, Loop bandwidth setting = 50% of maximum loop bandwidth (default), REFCLK toggling –> normal operation, REFCLK stops -> no oscillation, Bypass clock = normal operation, clocks switched off (output LOW), PLL Reset normal operation, PLL Enable = PLL on // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, // Clock Lane DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0144, 0x00000000, 0x00000000, 4, 0}, // Data Lane 0 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0148, 0x00000000, 0x00000000, 4, 0}, // Data Lane 1 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x014c, 0x00000000, 0x00000000, 4, 0}, // Data Lane 2 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0150, 0x00000000, 0x00000000, 4, 0}, // Data Lane 3 DPHY Control: Bypass Lane Enable from PPI Layer enable. // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, // LINEINITCNT: Line Initialization Wait Counter = 0x1e00 = 7680 {0x0214, 0x00000003, 0x00000000, 4, 0}, // LPTXTIMECNT: SYSLPTX Timing Generation Counter = 3 {0x0218, 0x00001402, 0x00000000, 4, 0}, // TCLK_HEADERCNT: TCLK_ZERO Counter = 0x14 = 20, TCLK_PREPARE Counter = 0x02 = 2 {0x021c, 0x00000000, 0x00000000, 4, 0}, // TCLK_TRAILCNT: TCLK_TRAIL Counter = 0 {0x0220, 0x00000003, 0x00000000, 4, 0}, // THS_HEADERCNT: THS_ZERO Counter = 0, THS_PREPARE Counter = 3 {0x0224, 0x00004a00, 0x00000000, 4, 0}, // TWAKEUP: TWAKEUP Counter = 0x4a00 = 18944 {0x0228, 0x00000008, 0x00000000, 4, 0}, // TCLK_POSTCNT: TCLK_POST Counter = 8 {0x022c, 0x00000002, 0x00000000, 4, 0}, // THS_TRAILCNT: THS_TRAIL Counter = 2 {0x0234, 0x0000001f, 0x00000000, 4, 0}, // HSTXVREGEN: Enable voltage regulators for lanes and clk {0x0238, 0x00000001, 0x00000000, 4, 0}, // TXOPTIONCNTRL: Set Continuous Clock Mode {0x0204, 0x00000001, 0x00000000, 4, 0}, // PPI STARTCNTRL: start PPI function {0x0518, 0x00000001, 0x00000000, 4, 0}, // CSI_START: start {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // CSI Configuration Register: set register 0x040C with data 0x80a6 (CSI MOde, Disables the HTX_TO timer, High-Speed data transfer is performed to Tx, DSCClk Stays in HS mode when Data Lane goes to LP, 4 Data Lanes,The EOT packet is automatically granted at the end of HS transfer then is transmitted) // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, // SYSTEM INTERRUPT: clear DDC power change detection interrupt {0x8512, 0x000000fe, 0x00000000, 1, 0}, // SYS INTERRUPT MASK: DDC power change detection interrupt not masked {0x8514, 0x00000000, 0x00000000, 1, 0}, // PACKET INTERRUPT MASK: unmask all {0x8515, 0x00000000, 0x00000000, 1, 0}, // CBIT INTERRUPT MASK: unmask all {0x8516, 0x00000000, 0x00000000, 1, 0}, // AUDIO INTERRUPT MASK: unmask all // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, // PHY CONTROL0: 27MHz, DDC5V detection operation. {0x8540, 0x00000a8c, 0x00000000, 1, 0}, // SYS FREQ0 Register: 27MHz {0x8630, 0x00041eb0, 0x00000000, 1, 0}, // Audio FS Lock Detect Control: for 27MHz {0x8670, 0x00000001, 0x00000000, 1, 0}, // AUDIO PLL Setting: For REFCLK = 27MHz // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, // {0x8536, 0x00000040, 0x00000000, 1, 0}, // {0x853f, 0x0000000a, 0x00000000, 1, 0}, // // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, // DDC CONTROL: DDC_ACK output terminal H active, DDC5V_active detect delay 200ms {0x8544, 0x00000010, 0x00000000, 1, 100}, // HPD Control Register: HOTPLUG output ON/OFF control mode = DDC5V detection interlock {0x8545, 0x00000031, 0x00000000, 1, 0}, // ANA CONTROL: PLL charge pump setting for Audio = normal, DAC/PLL power ON/OFF setting for Audio = ON {0x8546, 0x0000002d, 0x00000000, 1, 0}, // AVMUTE CONTROL: AVM_CTL = 0x2d // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, // EDID MODE REGISTER: nternal EDID-RAM & DDC2B mode {0x85cb, 0x00000001, 0x00000000, 1, 0}, // EDID Length REGISTER 2: EDID data size stored in RAM (upper address bits) = 0x1 (Size = 0x100 = 256) // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, // {0x8560, 0x00000024, 0x00000000, 1, 0}, // HDCP MODE: HDCP automatic reset when DVI⇔HDMI switched = on, HDCP Line Rekey timing switch = 7clk mode (Data island delay ON), Bcaps[5] KSVINFO_READY(0x8840[5]) auto clear mode = Auto clear using AKSV write {0x8563, 0x00000011, 0x00000000, 1, 0}, // {0x8564, 0x0000000f, 0x00000000, 1, 0}, // // RGB --> YUV Conversion {0x8571, 0x00000002, 0x00000000, 1, 0}, // {0x8573, 0x000000c1, 0x00000000, 1, 0}, // VOUT SET2 REGISTER: 422 fixed output, Video Output 422 conversion mode selection 000: During 444 input, 3tap filter; during 422 input, simple decimation, Enable RGB888 to YUV422 Conversion (Fixed Color output) {0x8574, 0x00000008, 0x00000000, 1, 0}, // VOUT SET3 REGISTER (VOUT_SET3): Follow register bit 0x8573[7] setting {0x8576, 0x00000060, 0x00000000, 1, 0}, // VOUT_COLOR: Output Color = 601 YCbCr Limited, Input Pixel Repetition judgment = automatic, Input Pixel Repetition HOST setting = no repetition // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, // PACKET INTERRUPT MODE: all enable {0x870b, 0x0000002c, 0x00000000, 1, 0}, // NO PACKET LIMIT: NO_ACP_LIMIT = 0x2, NO_AVI_LIMIT = 0xC {0x870c, 0x00000053, 0x00000000, 1, 0}, // When VS receive interrupt is detected, VS storage register automatic clear, When ACP receive interrupt is detected, ACP storage register automatic clear, When AVI receive interrupt occurs, judge input video signal with RGB and no Repetition, When AVI receive interrupt is detected, AVI storage register automatic clear. {0x870d, 0x00000001, 0x00000000, 1, 0}, // ERROR PACKET LIMIT: Packet continuing receive error occurrence detection threshold = 1 {0x870e, 0x00000030, 0x00000000, 1, 0}, // NO PACKET LIMIT: {0x9007, 0x00000010, 0x00000000, 1, 0}, // {0x854a, 0x00000001, 0x00000000, 1, 0}, // Initialization completed flag // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, // Configuration Control Register: Power Island Normal, I2S/TDM clock are free running, Enable 2 Audio channels, Audio channel number Auto detect by HW, I2S/TDM Data no delay, Select YCbCr422 8-bit (HDMI YCbCr422 12-bit data format), Send InfoFrame data out to CSI2, Audio output to I2S i/f (valid for 2 channel only), I2C address index increments on every data byte transfer, Audio and Video tx buffres enable. }; /* list of image formats supported by TCM825X sensor */ static const struct v4l2_fmtdesc tc358743_formats[] = { { .description = "RGB888 (RGB24)", .pixelformat = V4L2_PIX_FMT_RGB24, /* 24 RGB-8-8-8 */ .flags = MIPI_DT_RGB888 // 0x24 }, { .description = "RAW12 (Y/CbCr 4:2:0)", .pixelformat = V4L2_PIX_FMT_UYVY, /* 12 Y/CbCr 4:2:0 */ .flags = MIPI_DT_RAW12 // 0x2c }, { .description = "YUV 4:2:2 8-bit", .pixelformat = V4L2_PIX_FMT_YUYV, /* 8 8-bit color */ .flags = MIPI_DT_YUV422 // 0x1e /* UYVY... */ }, }; static struct tc358743_mode_info tc358743_mode_info_data[2][tc358743_mode_MAX] = { [0][tc358743_mode_720P_60_1280_720] = {tc358743_mode_720P_60_1280_720, 1280, 720, 12, 0, 4, 133, tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz), MIPI_DT_YUV422 }, [0][tc358743_mode_1080P_1920_1080] = {tc358743_mode_1080P_1920_1080, 1920, 1080, 15, 0x0b, 4, 300, tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT1] = {tc358743_mode_INIT1, 1280, 720, 12, 0, 2, 125, tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT2] = {tc358743_mode_INIT2, 1280, 720, 12, 0, 4, 125, tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT] = {tc358743_mode_INIT, 640, 480, 6, 1, 2, 108, tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT4] = {tc358743_mode_INIT4, 640, 480, 6, 1, 2, 174, tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT3] = {tc358743_mode_INIT3, 1024, 720, 6, 1, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_720P_1280_720] = {tc358743_mode_720P_1280_720, 1280, 720, 12, (0x3e)<<8|(0x3c), 2, 125, tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_720_480] = {tc358743_mode_480P_720_480, 720, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_640_480] = {tc358743_mode_480P_640_480, 640, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_INIT5] = {tc358743_mode_INIT5, 1280, 720, 12, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT6] = {tc358743_mode_INIT6, 1920, 1023, 15, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_720P_60_1280_720] = {tc358743_mode_720P_60_1280_720, 1280, 720, 12, 0, 4, 133, tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz), MIPI_DT_YUV422 }, [1][tc358743_mode_1080P_1920_1080] = {tc358743_mode_1080P_1920_1080, 1920, 1080, 15, 0xa, 4, 300, tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT1] = {tc358743_mode_INIT1, 1280, 720, 12, 0, 2, 125, tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT2] = {tc358743_mode_INIT2, 1280, 720, 12, 0, 4, 125, tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT] = {tc358743_mode_INIT, 640, 480, 6, 1, 2, 108, tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT4] = {tc358743_mode_INIT4, 640, 480, 6, 1, 2, 174, tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT3] = {tc358743_mode_INIT3, 1024, 720, 6, 1, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_720P_1280_720] = {tc358743_mode_720P_1280_720, 1280, 720, 12, (0x3e)<<8|(0x3c), 2, 125, tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz), MIPI_DT_YUV422, }, [1][tc358743_mode_480P_720_480] = {tc358743_mode_480P_720_480, 720, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_640_480] = {tc358743_mode_480P_640_480, 640, 480, 1, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz), MIPI_DT_YUV422, }, [1][tc358743_mode_INIT5] = {tc358743_mode_INIT5, 1280, 720, 12, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT6] = {tc358743_mode_INIT6, 1920, 1023, 15, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz), MIPI_DT_YUV422 }, }; static int tc358743_probe(struct i2c_client *adapter, const struct i2c_device_id *device_id); static int tc358743_remove(struct i2c_client *client); static s32 tc358743_read_reg(u16 reg, u32 *val); static s32 tc358743_write_reg(u16 reg, u32 val, int len); static const struct i2c_device_id tc358743_id[] = { {"tc358743_mipi", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, tc358743_id); static struct i2c_driver tc358743_i2c_driver = { .driver = { .owner = THIS_MODULE, .name = "tc358743_mipi", }, .probe = tc358743_probe, .remove = tc358743_remove, .id_table = tc358743_id, }; struct _reg_size { u16 startaddr, endaddr; int size; } tc358743_read_reg_size [] = { {0x0000, 0x005a, 2}, {0x0140, 0x0150, 4}, {0x0204, 0x0238, 4}, {0x040c, 0x0418, 4}, {0x044c, 0x0454, 4}, {0x0500, 0x0518, 4}, {0x0600, 0x06cc, 4}, {0x7000, 0x7100, 2}, {0x8500, 0x8bff, 1}, {0x8c00, 0x8fff, 4}, {0x9000, 0x90ff, 1}, {0x9100, 0x92ff, 1}, {0, 0, 0}, }; static s32 tc358743_write_reg(u16 reg, u32 val, int len) { int i = 0; u32 data = val; u8 au8Buf[6] = {0}; int size = 0; while (0 != tc358743_read_reg_size[i].startaddr || 0 != tc358743_read_reg_size[i].endaddr || 0 != tc358743_read_reg_size[i].size) { if (tc358743_read_reg_size[i].startaddr <= reg && tc358743_read_reg_size[i].endaddr >= reg) { size = tc358743_read_reg_size[i].size; break; } i++; } if (!size) { pr_err("%s:write reg error:reg=%x is not found\n",__func__, reg); return -1; } if (size == 3) { size = 2; } else if (size != len) { pr_err("%s:write reg len error:reg=%x %d instead of %d\n", __func__, reg, len, size); return 0; } while (len > 0) { i = 0; au8Buf[i++] = (reg >> 8) & 0xff; au8Buf[i++] = reg & 0xff; while (size-- > 0) { au8Buf[i++] = (u8)data; data >>= 8; } if (i2c_master_send(tc358743_data.i2c_client, au8Buf, i) < 0) { pr_err("%s:write reg error:reg=%x,val=%x\n", __func__, reg, val); return -1; } len -= (u8)size; reg += (u16)size; } return 0; } static s32 tc358743_read_reg(u16 reg, u32 *val) { u8 au8RegBuf[2] = {0}; u32 u32RdVal = 0; int i=0; int size = 0; while (0 != tc358743_read_reg_size[i].startaddr || 0 != tc358743_read_reg_size[i].endaddr || 0 != tc358743_read_reg_size[i].size) { if (tc358743_read_reg_size[i].startaddr <= reg && tc358743_read_reg_size[i].endaddr >= reg) { size = tc358743_read_reg_size[i].size; break; } i++; } if (!size) return -1; au8RegBuf[0] = reg >> 8; au8RegBuf[1] = reg & 0xff; if (2 != i2c_master_send(tc358743_data.i2c_client, au8RegBuf, 2)) { pr_err("%s:read reg error:reg=%x\n", __func__, reg); return -1; } if (size /*of(u32RdVal)*/ != i2c_master_recv(tc358743_data.i2c_client, (char *)&u32RdVal, size /*of(u32RdVal)*/)) { pr_err("%s:read reg error:reg=%x,val=%x\n", __func__, reg, u32RdVal); return -1; } *val = u32RdVal; return size; } static int tc358743_write_edid(u8 *edid, int len) { int i = 0, off = 0; u8 au8Buf[8+2] = {0}; int size = 0; u16 reg; reg = 0x8C00; off = 0; size = ARRAY_SIZE(au8Buf)-2; pr_debug("Write EDID: %d (%d)\n", len, size); while (len > 0) { i = 0; au8Buf[i++] = (reg >> 8) & 0xff; au8Buf[i++] = reg & 0xff; while (i < ARRAY_SIZE(au8Buf)) { au8Buf[i++] = edid[off++]; } if (i2c_master_send(tc358743_data.i2c_client, au8Buf, i) < 0) { pr_err("%s:write reg error:reg=%x,val=%x\n", __func__, reg, off); return -1; } len -= (u8)size; reg += (u16)size; } pr_debug("Activate EDID\n"); tc358743_write_reg(0x85c7, 0x01, 1); tc358743_write_reg(0x85ca, 0x00, 1); tc358743_write_reg(0x85cb, 0x01, 1); return 0; } static int tc358743_reset(struct sensor_data *sensor) { u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate = tc358743_60_fps; int ret = -1; det_work_enable(0); while (ret) { tc_standby(1); mdelay(100); tc_standby(0); mdelay(1000); tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; pr_debug("%s: capture mode: %d extended mode: %d fps: %d\n", __func__,sensor->streamcap.capturemode, sensor->streamcap.extendedmode, tgt_fps); ret = tc358743_init_mode(frame_rate, sensor->streamcap.capturemode); if (ret) pr_err("%s: Fail to init tc35874! - retry\n", __func__); } det_work_enable(1); return ret; } void mipi_csi2_swreset(struct mipi_csi2_info *info); #include "../../../../mxc/mipi/mxc_mipi_csi2.h" static int tc358743_init_mode(enum tc358743_frame_rate frame_rate, enum tc358743_mode mode) { struct reg_value *pModeSetting = NULL; s32 i = 0; s32 iModeSettingArySize = 0; register u32 RepeateLines = 0; register int RepeateTimes = 0; register u32 Delay_ms = 0; register u16 RegAddr = 0; register u32 Mask = 0; register u32 Val = 0; u8 Length; u32 RegVal = 0; int retval = 0; void *mipi_csi2_info; u32 mipi_reg; u32 mipi_reg_test[10]; pr_debug("%s rate: %d mode: %d\n", __func__, frame_rate, mode); if ((mode > tc358743_mode_MAX || mode < 0) && (mode != tc358743_mode_INIT)) { pr_debug("%s Wrong tc358743 mode detected! %d. Set mode 0\n", __func__, mode); mode = 0; } mipi_csi2_info = mipi_csi2_get_info(); pr_debug("%s rate: %d mode: %d, info %p\n", __func__, frame_rate, mode, mipi_csi2_info); /* initial mipi dphy */ tc358743_toggle_hpd(!hpd_active); if (mipi_csi2_info) { pr_debug("%s: mipi_csi2_info:\n" "mipi_en: %d\n" "ipu_id: %d\n" "csi_id: %d\n" "v_channel: %d\n" "lanes: %d\n" "datatype: %d\n" "dphy_clk: %p\n" "pixel_clk: %p\n" "mipi_csi2_base:%p\n" "pdev: %p\n" , __func__, ((struct mipi_csi2_info *)mipi_csi2_info)->mipi_en, ((struct mipi_csi2_info *)mipi_csi2_info)->ipu_id, ((struct mipi_csi2_info *)mipi_csi2_info)->csi_id, ((struct mipi_csi2_info *)mipi_csi2_info)->v_channel, ((struct mipi_csi2_info *)mipi_csi2_info)->lanes, ((struct mipi_csi2_info *)mipi_csi2_info)->datatype, ((struct mipi_csi2_info *)mipi_csi2_info)->dphy_clk, ((struct mipi_csi2_info *)mipi_csi2_info)->pixel_clk, ((struct mipi_csi2_info *)mipi_csi2_info)->mipi_csi2_base, ((struct mipi_csi2_info *)mipi_csi2_info)->pdev ); if (!mipi_csi2_get_status(mipi_csi2_info)) mipi_csi2_enable(mipi_csi2_info); if (mipi_csi2_get_status(mipi_csi2_info)) { int ifmt; if (tc358743_mode_info_data[frame_rate][mode].lanes != 0) { pr_debug("%s Change lanes: from %d to %d\n", __func__, ((struct mipi_csi2_info *)mipi_csi2_info)->lanes, tc358743_mode_info_data[frame_rate][mode].lanes); ((struct mipi_csi2_info *)mipi_csi2_info)->lanes = tc358743_mode_info_data[frame_rate][mode].lanes; ((struct mipi_csi2_info *)mipi_csi2_info)->lanes = tc358743_mode_info_data[frame_rate][mode].lanes; } pr_debug("Now Using %d lanes\n",mipi_csi2_set_lanes(mipi_csi2_info)); /*Only reset MIPI CSI2 HW at sensor initialize*/ if (!hdmi_mode) // is this during reset mipi_csi2_reset(mipi_csi2_info); pr_debug("%s format: %x\n", __func__, tc358743_data.pix.pixelformat); for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[frame_rate][mode].flags == tc358743_formats[ifmt].flags) { tc358743_data.pix.pixelformat = tc358743_formats[ifmt].pixelformat; pr_debug("%s: %s (%x, %x)\n", __func__, tc358743_formats[ifmt].description, tc358743_data.pix.pixelformat, tc358743_formats[ifmt].flags); mipi_csi2_set_datatype(mipi_csi2_info, tc358743_formats[ifmt].flags); break; } if (ifmt >= ARRAY_SIZE(tc358743_formats)) { pr_err("currently this sensor format (0x%x) can not be supported!\n", tc358743_data.pix.pixelformat); return -1; } } else { pr_err("Can not enable mipi csi2 driver!\n"); return -1; } } else { pr_err("Fail to get mipi_csi2_info!\n"); return -1; } { pModeSetting = tc358743_mode_info_data[frame_rate][mode].init_data_ptr; iModeSettingArySize = tc358743_mode_info_data[frame_rate][mode].init_data_size; tc358743_data.pix.width = tc358743_mode_info_data[frame_rate][mode].width; tc358743_data.pix.height = tc358743_mode_info_data[frame_rate][mode].height; pr_debug("%s: Set %d regs from %p for frs %d mode %d with width %d height %d\n", __func__, iModeSettingArySize, pModeSetting, frame_rate, mode, tc358743_data.pix.width, tc358743_data.pix.height); for (i = 0; i < iModeSettingArySize; ++i) { pModeSetting = tc358743_mode_info_data[frame_rate][mode].init_data_ptr + i; Delay_ms = pModeSetting->u32Delay_ms & (0xffff); RegAddr = pModeSetting->u16RegAddr; Val = pModeSetting->u32Val; Mask = pModeSetting->u32Mask; Length = pModeSetting->u8Length; if (Mask) { retval = tc358743_read_reg(RegAddr, &RegVal); if (retval < 0) break; RegVal &= ~(u8)Mask; Val &= Mask; Val |= RegVal; } retval = tc358743_write_reg(RegAddr, Val, Length); if (retval < 0) break; if (Delay_ms) msleep(Delay_ms); if (0 != ((pModeSetting->u32Delay_ms>>16) & (0xff))) { if (!RepeateTimes) { RepeateTimes = (pModeSetting->u32Delay_ms>>16) & (0xff); RepeateLines = (pModeSetting->u32Delay_ms>>24) & (0xff); } if (--RepeateTimes > 0) { i -= RepeateLines; } } } if (retval < 0) { pr_err("%s: Fail to write REGS to tc35874!\n", __func__); goto err; } } if (!hdmi_mode) // is this during reset if ((retval = tc358743_write_edid(cHDMIEDID, ARRAY_SIZE(cHDMIEDID)))) pr_err("%s: Fail to write EDID to tc35874!\n", __func__); tc358743_toggle_hpd(hpd_active); if (mipi_csi2_info) { unsigned int i = 0; /* wait for mipi sensor ready */ mipi_reg = mipi_csi2_dphy_status(mipi_csi2_info); while ((mipi_reg == 0x200) && (i < 10)) { mipi_reg_test[i] = mipi_reg; mipi_reg = mipi_csi2_dphy_status(mipi_csi2_info); i++; msleep(10); } if (i >= 10) { pr_err("mipi csi2 can not receive sensor clk!\n"); return -1; } { int j; for (j = 0; j < i; j++) { pr_debug("%d mipi csi2 dphy status %x\n", j, mipi_reg_test[j]); } } i = 0; /* wait for mipi stable */ mipi_reg = mipi_csi2_get_error1(mipi_csi2_info); while ((mipi_reg != 0x0) && (i < 10)) { mipi_reg_test[i] = mipi_reg; mipi_reg = mipi_csi2_get_error1(mipi_csi2_info); i++; msleep(10); } if (i >= 10) { pr_err("mipi csi2 can not reveive data correctly!\n"); return -1; } { int j; for (j = 0; j < i; j++) { pr_debug("%d mipi csi2 err1 %x\n", j, mipi_reg_test[j]); } } } err: return (retval>0)?0:retval; } /* --------------- IOCTL functions from v4l2_int_ioctl_desc --------------- */ static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) { pr_debug("%s\n", __func__); if (s == NULL) { pr_err(" ERROR!! no slave device set!\n"); return -1; } memset(p, 0, sizeof(*p)); p->u.bt656.clock_curr = TC358743_XCLK_MIN; //tc358743_data.mclk; pr_debug("%s: clock_curr=mclk=%d\n", __func__, tc358743_data.mclk); p->if_type = V4L2_IF_TYPE_BT656; p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; p->u.bt656.clock_min = TC358743_XCLK_MIN; p->u.bt656.clock_max = TC358743_XCLK_MAX; p->u.bt656.bt_sync_correct = 1; /* Indicate external vsync */ return 0; } /*! * ioctl_s_power - V4L2 sensor interface handler for VIDIOC_S_POWER ioctl * @s: pointer to standard V4L2 device structure * @on: indicates power mode (on or off) * * Turns the power on or off, depending on the value of on and returns the * appropriate error code. */ static int ioctl_s_power(struct v4l2_int_device *s, int on) { struct sensor_data *sensor = s->priv; pr_debug("%s: %d\n", __func__, on); if (on && !sensor->on) { if (io_regulator) if (regulator_enable(io_regulator) != 0) return -EIO; if (core_regulator) if (regulator_enable(core_regulator) != 0) return -EIO; if (gpo_regulator) if (regulator_enable(gpo_regulator) != 0) return -EIO; if (analog_regulator) if (regulator_enable(analog_regulator) != 0) return -EIO; /* Make sure power on */ tc_standby(0); } else if (!on && sensor->on) { if (analog_regulator) regulator_disable(analog_regulator); if (core_regulator) regulator_disable(core_regulator); if (io_regulator) regulator_disable(io_regulator); if (gpo_regulator) regulator_disable(gpo_regulator); if (!hdmi_mode) tc358743_reset(sensor); } sensor->on = on; return 0; } /*! * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl * @s: pointer to standard V4L2 device structure * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure * * Returns the sensor's video CAPTURE parameters. */ static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) { struct sensor_data *sensor = s->priv; struct v4l2_captureparm *cparm = &a->parm.capture; int ret = 0; pr_debug("%s type: %x\n", __func__, a->type); switch (a->type) { /* This is the only case currently handled. */ case V4L2_BUF_TYPE_VIDEO_CAPTURE: memset(a, 0, sizeof(*a)); a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; cparm->capability = sensor->streamcap.capability; cparm->timeperframe = sensor->streamcap.timeperframe; cparm->capturemode = sensor->streamcap.capturemode; cparm->extendedmode = sensor->streamcap.extendedmode; ret = 0; break; /* These are all the possible cases. */ case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: ret = -EINVAL; break; default: pr_debug(" type is unknown - %d\n", a->type); ret = -EINVAL; break; } det_work_enable(1); pr_debug("%s done %d\n", __func__, ret); return ret; } static int tc358743_toggle_hpd(int active) { int ret = 0; if (active) { ret += tc358743_write_reg(0x8544, 0x00, 1); mdelay(500); ret += tc358743_write_reg(0x8544, 0x10, 1); } else { ret += tc358743_write_reg(0x8544, 0x10, 1); mdelay(500); ret += tc358743_write_reg(0x8544, 0x00, 1); } return ret; } /*! * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl * @s: pointer to standard V4L2 device structure * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure * * Configures the sensor to use the input parameters, if possible. If * not possible, reverts to the old parameters and returns the * appropriate error code. */ static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) { struct sensor_data *sensor = s->priv; struct v4l2_fract *timeperframe = &a->parm.capture.timeperframe; u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate = tc358743_60_fps, frame_rate_now = tc358743_60_fps; int ret = 0; pr_debug("%s\n", __func__); det_work_enable(0); /* Make sure power on */ tc_standby(0); switch (a->type) { /* This is the only case currently handled. */ case V4L2_BUF_TYPE_VIDEO_CAPTURE: /* Check that the new frame rate is allowed. */ if ((timeperframe->numerator == 0) || (timeperframe->denominator == 0)) { timeperframe->denominator = DEFAULT_FPS; timeperframe->numerator = 1; } tgt_fps = timeperframe->denominator / timeperframe->numerator; if (tgt_fps > MAX_FPS) { timeperframe->denominator = MAX_FPS; timeperframe->numerator = 1; } else if (tgt_fps < MIN_FPS) { timeperframe->denominator = MIN_FPS; timeperframe->numerator = 1; } /* Actual frame rate we use */ tgt_fps = timeperframe->denominator / timeperframe->numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; else { pr_err(" The camera frame rate is not supported!\n"); ret = -EINVAL; break; } if ((u32)a->parm.capture.capturemode > tc358743_mode_MAX) { a->parm.capture.capturemode = 0; pr_debug("%s: Forse extended mode: %d \n", __func__,(u32)a->parm.capture.capturemode); } tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate_now = tc358743_60_fps; else if (tgt_fps == 30) frame_rate_now = tc358743_30_fps; if (frame_rate_now != frame_rate || sensor->streamcap.capturemode != (u32)a->parm.capture.capturemode || sensor->streamcap.extendedmode != (u32)a->parm.capture.extendedmode) { sensor->streamcap.timeperframe = *timeperframe; sensor->streamcap.capturemode = (u32)a->parm.capture.capturemode; sensor->streamcap.extendedmode = (u32)a->parm.capture.extendedmode; pr_debug("%s: capture mode: %d extended mode: %d \n", __func__,sensor->streamcap.capturemode, sensor->streamcap.extendedmode); ret = tc358743_init_mode(frame_rate, sensor->streamcap.capturemode); } else { pr_debug("%s: Keep current settings\n", __func__); } break; /* These are all the possible cases. */ case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: pr_debug(" type is not " \ "V4L2_BUF_TYPE_VIDEO_CAPTURE but %d\n", a->type); ret = -EINVAL; break; default: pr_debug(" type is unknown - %d\n", a->type); ret = -EINVAL; break; } if (ret) det_work_enable(1); return ret; } /*! * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl * @s: pointer to standard V4L2 device structure * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure * * If the requested control is supported, returns the control's current * value from the video_control[] array. Otherwise, returns -EINVAL * if the control is not supported. */ static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) { int ret = 0; pr_debug("%s\n", __func__); switch (vc->id) { case V4L2_CID_BRIGHTNESS: vc->value = tc358743_data.brightness; break; case V4L2_CID_HUE: vc->value = tc358743_data.hue; break; case V4L2_CID_CONTRAST: vc->value = tc358743_data.contrast; break; case V4L2_CID_SATURATION: vc->value = tc358743_data.saturation; break; case V4L2_CID_RED_BALANCE: vc->value = tc358743_data.red; break; case V4L2_CID_BLUE_BALANCE: vc->value = tc358743_data.blue; break; case V4L2_CID_EXPOSURE: vc->value = tc358743_data.ae_mode; break; default: ret = -EINVAL; } return ret; } /*! * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl * @s: pointer to standard V4L2 device structure * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure * * If the requested control is supported, sets the control's current * value in HW (and updates the video_control[] array). Otherwise, * returns -EINVAL if the control is not supported. */ static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) { int retval = 0; pr_debug("In tc358743:ioctl_s_ctrl %d\n", vc->id); switch (vc->id) { case V4L2_CID_BRIGHTNESS: break; case V4L2_CID_CONTRAST: break; case V4L2_CID_SATURATION: break; case V4L2_CID_HUE: break; case V4L2_CID_AUTO_WHITE_BALANCE: break; case V4L2_CID_DO_WHITE_BALANCE: break; case V4L2_CID_RED_BALANCE: break; case V4L2_CID_BLUE_BALANCE: break; case V4L2_CID_GAMMA: break; case V4L2_CID_EXPOSURE: break; case V4L2_CID_AUTOGAIN: break; case V4L2_CID_GAIN: break; case V4L2_CID_HFLIP: break; case V4L2_CID_VFLIP: break; default: retval = -EPERM; break; } return retval; } int get_pixelformat(int index) { int ifmt; for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[0][index].flags == tc358743_formats[ifmt].flags) break; if (ifmt == ARRAY_SIZE(tc358743_formats)) ifmt = 0; /* Default = RBG888 */ return ifmt; } /*! * ioctl_enum_framesizes - V4L2 sensor interface handler for * VIDIOC_ENUM_FRAMESIZES ioctl * @s: pointer to standard V4L2 device structure * @fsize: standard V4L2 VIDIOC_ENUM_FRAMESIZES ioctl structure * * Return 0 if successful, otherwise -EINVAL. */ static int ioctl_enum_framesizes(struct v4l2_int_device *s, struct v4l2_frmsizeenum *fsize) { pr_debug("%s, INDEX: %d\n", __func__,fsize->index); if (fsize->index > tc358743_mode_MAX) return -EINVAL; fsize->pixel_format = tc358743_formats[get_pixelformat(fsize->index)].pixelformat; fsize->discrete.width = tc358743_mode_info_data[0][fsize->index].width; fsize->discrete.height = tc358743_mode_info_data[0][fsize->index].height; pr_debug("%s %d:%d format: %x\n", __func__, fsize->discrete.width, fsize->discrete.height, fsize->pixel_format); return 0; } /*! * ioctl_g_chip_ident - V4L2 sensor interface handler for * VIDIOC_DBG_G_CHIP_IDENT ioctl * @s: pointer to standard V4L2 device structure * @id: pointer to int * * Return 0. */ static int ioctl_g_chip_ident(struct v4l2_int_device *s, int *id) { ((struct v4l2_dbg_chip_ident *)id)->match.type = V4L2_CHIP_MATCH_I2C_DRIVER; strcpy(((struct v4l2_dbg_chip_ident *)id)->match.name, "tc358743_mipi"); return 0; } /*! * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT * @s: pointer to standard V4L2 device structure */ static int ioctl_init(struct v4l2_int_device *s) { pr_debug("%s\n", __func__); return 0; } /*! * ioctl_enum_fmt_cap - V4L2 sensor interface handler for VIDIOC_ENUM_FMT * @s: pointer to standard V4L2 device structure * @fmt: pointer to standard V4L2 fmt description structure * * Return 0. */ static int ioctl_enum_fmt_cap(struct v4l2_int_device *s, struct v4l2_fmtdesc *fmt) { pr_debug("%s\n", __func__); if (fmt->index > tc358743_mode_MAX) return -EINVAL; fmt->pixelformat = tc358743_formats[get_pixelformat(fmt->index)].pixelformat; pr_debug("%s: format: %x\n", __func__, fmt->pixelformat); return 0; } static int ioctl_try_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) { struct sensor_data *sensor = s->priv; u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate; // enum image_size isize; int ifmt; struct v4l2_pix_format *pix = &f->fmt.pix; pr_debug("%s\n", __func__); tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) { frame_rate = tc358743_60_fps; } else if (tgt_fps == 30) { frame_rate = tc358743_30_fps; } else { pr_debug("%s: %d fps (%d,%d) is not supported\n", __func__, tgt_fps, sensor->streamcap.timeperframe.denominator,sensor->streamcap.timeperframe.numerator); return -EINVAL; } tc358743_data.pix.width = pix->width = tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].width; tc358743_data.pix.height = pix->height = tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].height; for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].flags == tc358743_formats[ifmt].flags) break; if (ifmt == ARRAY_SIZE(tc358743_formats)) ifmt = 0; /* Default = RBG888 */ tc358743_data.pix.pixelformat = pix->pixelformat = tc358743_formats[ifmt].pixelformat; pix->field = V4L2_FIELD_NONE; pix->bytesperline = pix->width * 4; pix->sizeimage = pix->bytesperline * pix->height; pix->priv = 0; switch (pix->pixelformat) { case V4L2_PIX_FMT_UYVY: default: pix->colorspace = V4L2_COLORSPACE_SRGB; break; } { u32 u32val; int ret = tc358743_read_reg(0x8520,&u32val); pr_debug("SYS_STATUS: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8521,&u32val); pr_debug("VI_STATUS0: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8522,&u32val); pr_debug("VI_STATUS1: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8525,&u32val); pr_debug("VI_STATUS2: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8528,&u32val); pr_debug("VI_STATUS3: 0x%x, ret val: %d \n",u32val,ret); pr_debug("%s %d:%d format: %x\n", __func__, pix->width, pix->height, pix->pixelformat); } return 0; } /*! * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap * @s: pointer to standard V4L2 device structure * @f: pointer to standard V4L2 v4l2_format structure * * Returns the sensor's current pixel format in the v4l2_format * parameter. */ static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) { pr_debug("%s\n", __func__); return ioctl_try_fmt_cap(s, f); } /*! * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num * @s: pointer to standard V4L2 device structure * * Initialise the device when slave attaches to the master. */ static int ioctl_dev_init(struct v4l2_int_device *s) { struct sensor_data *sensor = s->priv; u32 tgt_xclk; /* target xclk */ u32 tgt_fps; /* target frames per secound */ int ret = 0; enum tc358743_frame_rate frame_rate; void *mipi_csi2_info; pr_debug("%s\n", __func__); tc358743_data.on = true; /* mclk */ tgt_xclk = tc358743_data.mclk; tgt_xclk = min(tgt_xclk, (u32)TC358743_XCLK_MAX); tgt_xclk = max(tgt_xclk, (u32)TC358743_XCLK_MIN); tc358743_data.mclk = tgt_xclk; pr_debug("%s: Setting mclk to %d MHz\n", __func__, tc358743_data.mclk / 1000000); // set_mclk_rate(&tc358743_data.mclk, tc358743_data.mclk_source); // pr_debug("%s: After mclk to %d MHz\n", __func__, tc358743_data.mclk / 1000000); /* Default camera frame rate is set in probe */ tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; else return -EINVAL; mipi_csi2_info = mipi_csi2_get_info(); /* enable mipi csi2 */ if (mipi_csi2_info) { mipi_csi2_enable(mipi_csi2_info); } else { pr_err("Fail to get mipi_csi2_info!\n"); return -EPERM; } pr_debug("%s done\n", __func__); return ret; } /*! * ioctl_dev_exit - V4L2 sensor interface handler for vidioc_int_dev_exit_num * @s: pointer to standard V4L2 device structure * * Delinitialise the device when slave detaches to the master. */ static int ioctl_dev_exit(struct v4l2_int_device *s) { void *mipi_csi2_info; mipi_csi2_info = mipi_csi2_get_info(); /* disable mipi csi2 */ if (mipi_csi2_info) if (mipi_csi2_get_status(mipi_csi2_info)) mipi_csi2_disable(mipi_csi2_info); return 0; } /*! * This structure defines all the ioctls for this module and links them to the * enumeration. */ static struct v4l2_int_ioctl_desc tc358743_ioctl_desc[] = { {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*) ioctl_dev_init}, {vidioc_int_dev_exit_num, ioctl_dev_exit}, {vidioc_int_s_power_num, (v4l2_int_ioctl_func*) ioctl_s_power}, {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*) ioctl_g_ifparm}, {vidioc_int_init_num, (v4l2_int_ioctl_func*) ioctl_init}, {vidioc_int_enum_fmt_cap_num, (v4l2_int_ioctl_func *) ioctl_enum_fmt_cap}, {vidioc_int_try_fmt_cap_num, (v4l2_int_ioctl_func *)ioctl_try_fmt_cap}, {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func *) ioctl_g_fmt_cap}, {vidioc_int_g_parm_num, (v4l2_int_ioctl_func *) ioctl_g_parm}, {vidioc_int_s_parm_num, (v4l2_int_ioctl_func *) ioctl_s_parm}, {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func *) ioctl_g_ctrl}, {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func *) ioctl_s_ctrl}, {vidioc_int_enum_framesizes_num, (v4l2_int_ioctl_func *) ioctl_enum_framesizes}, {vidioc_int_g_chip_ident_num, (v4l2_int_ioctl_func *) ioctl_g_chip_ident}, }; static struct v4l2_int_slave tc358743_slave = { .ioctls = tc358743_ioctl_desc, .num_ioctls = ARRAY_SIZE(tc358743_ioctl_desc), }; static struct v4l2_int_device tc358743_int_device = { .module = THIS_MODULE, .name = "tc358743", .type = v4l2_int_type_slave, .u = { .slave = &tc358743_slave, }, }; #ifdef AUDIO_ENABLE struct imx_ssi { struct platform_device *ac97_dev; struct snd_soc_dai *imx_ac97; struct clk *clk; void __iomem *base; int irq; int fiq_enable; unsigned int offset; unsigned int flags; void (*ac97_reset) (struct snd_ac97 *ac97); void (*ac97_warm_reset)(struct snd_ac97 *ac97); struct imx_pcm_dma_params dma_params_rx; struct imx_pcm_dma_params dma_params_tx; int enabled; struct platform_device *soc_platform_pdev; struct platform_device *soc_platform_pdev_fiq; }; #define SSI_SCR 0x10 #define SSI_SRCR 0x20 #define SSI_STCCR 0x24 #define SSI_SRCCR 0x28 #define SSI_SCR_I2S_MODE_NORM (0 << 5) #define SSI_SCR_I2S_MODE_MSTR (1 << 5) #define SSI_SCR_I2S_MODE_SLAVE (2 << 5) #define SSI_I2S_MODE_MASK (3 << 5) #define SSI_SCR_SYN (1 << 4) #define SSI_SRCR_RSHFD (1 << 4) #define SSI_SRCR_RSCKP (1 << 3) #define SSI_SRCR_RFSI (1 << 2) #define SSI_SRCR_REFS (1 << 0) #define SSI_STCCR_WL(x) ((((x) - 2) >> 1) << 13) #define SSI_STCCR_WL_MASK (0xf << 13) #define SSI_SRCCR_WL(x) ((((x) - 2) >> 1) << 13) #define SSI_SRCCR_WL_MASK (0xf << 13) /* Audio setup */ static int imxpac_tc358743_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret; ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_IF | SND_SOC_DAIFMT_CBM_CFM); if (ret) { pr_err("%s: failed set cpu dai format\n", __func__); return ret; } ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret) { pr_err("%s: failed set codec dai format\n", __func__); return ret; } ret = snd_soc_dai_set_sysclk(codec_dai, 0, CODEC_CLOCK, SND_SOC_CLOCK_OUT); if (ret) { pr_err("%s: failed setting codec sysclk\n", __func__); return ret; } snd_soc_dai_set_tdm_slot(cpu_dai, 0xffffffc, 0xffffffc, 2, 0); ret = snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); if (ret) { pr_err("can't set CPU system clock IMX_SSP_SYS_CLK\n"); return ret; } #if 1 // clear SSI_SRCR_RXBIT0 and SSI_SRCR_RSHFD in order to push Right-justified MSB data fro { struct imx_ssi *ssi = snd_soc_dai_get_drvdata(cpu_dai); u32 scr = 0, srcr = 0, stccr = 0, srccr = 0; pr_debug("%s: base %p\n", __func__, (void *)ssi->base); scr = readl(ssi->base + SSI_SCR); pr_debug("%s: SSI_SCR before: %p\n", __func__, (void *)scr); writel(scr, ssi->base + SSI_SCR); pr_debug("%s: SSI_SCR after: %p\n", __func__, (void *)scr); srcr = readl(ssi->base + SSI_SRCR); pr_debug("%s: SSI_SRCR before: %p\n", __func__, (void *)srcr); writel(srcr, ssi->base + SSI_SRCR); pr_debug("%s: SSI_SRCR after: %p\n", __func__, (void *)srcr); stccr = readl(ssi->base + SSI_STCCR); pr_debug("%s: SSI_STCCR before: %p\n", __func__, (void *)stccr); stccr &= ~SSI_STCCR_WL_MASK; stccr |= SSI_STCCR_WL(16); writel(stccr, ssi->base + SSI_STCCR); pr_debug("%s: SSI_STCCR after: %p\n", __func__, (void *)stccr); srccr = readl(ssi->base + SSI_SRCCR); pr_debug("%s: SSI_SRCCR before: %p\n", __func__, (void *)srccr); srccr &= ~SSI_SRCCR_WL_MASK; srccr |= SSI_SRCCR_WL(16); writel(srccr, ssi->base + SSI_SRCCR); pr_debug("%s: SSI_SRCCR after: %p\n", __func__, (void *)srccr); } #endif return 0; } /* Headphones jack detection DAPM pins */ static struct snd_soc_jack_pin hs_jack_pins_a[] = { }; /* imx_3stack card dapm widgets */ static struct snd_soc_dapm_widget imx_3stack_dapm_widgets_a[] = { }; static struct snd_kcontrol_new tc358743_machine_controls_a[] = { }; /* imx_3stack machine connections to the codec pins */ static struct snd_soc_dapm_route audio_map_a[] = { }; static int imx_3stack_tc358743_init(struct snd_soc_pcm_runtime *rtd) { struct snd_soc_codec *codec = rtd->codec; int ret; struct snd_soc_jack *hs_jack; struct snd_soc_jack_pin *hs_jack_pins; int hs_jack_pins_size; struct snd_soc_dapm_widget *imx_3stack_dapm_widgets; int imx_3stack_dapm_widgets_size; struct snd_kcontrol_new *tc358743_machine_controls; int tc358743_machine_controls_size; struct snd_soc_dapm_route *audio_map; int audio_map_size; int gpio_num = -1; char *gpio_name; pr_debug("%s started\n", __func__); hs_jack_pins = hs_jack_pins_a; hs_jack_pins_size = ARRAY_SIZE(hs_jack_pins_a); imx_3stack_dapm_widgets = imx_3stack_dapm_widgets_a; imx_3stack_dapm_widgets_size = ARRAY_SIZE(imx_3stack_dapm_widgets_a); tc358743_machine_controls = tc358743_machine_controls_a; tc358743_machine_controls_size = ARRAY_SIZE(tc358743_machine_controls_a); audio_map = audio_map_a; audio_map_size = ARRAY_SIZE(audio_map_a); gpio_num = -1; //card_a_gpio_num; gpio_name = NULL; ret = snd_soc_add_controls(codec, tc358743_machine_controls, tc358743_machine_controls_size); if (ret) { pr_err("%s: snd_soc_add_controls failed. err = %d\n", __func__, ret); return ret; } /* Add imx_3stack specific widgets */ snd_soc_dapm_new_controls(&codec->dapm, imx_3stack_dapm_widgets, imx_3stack_dapm_widgets_size); /* Set up imx_3stack specific audio path audio_map */ snd_soc_dapm_add_routes(&codec->dapm, audio_map, audio_map_size); snd_soc_dapm_enable_pin(&codec->dapm, hs_jack_pins->pin); snd_soc_dapm_sync(&codec->dapm); hs_jack = kzalloc(sizeof(struct snd_soc_jack), GFP_KERNEL); ret = snd_soc_jack_new(codec, hs_jack_pins->pin, SND_JACK_HEADPHONE, hs_jack); if (ret) { pr_err("%s: snd_soc_jack_new failed. err = %d\n", __func__, ret); return ret; } ret = snd_soc_jack_add_pins(hs_jack,hs_jack_pins_size, hs_jack_pins); if (ret) { pr_err("%s: snd_soc_jack_add_pinsfailed. err = %d\n", __func__, ret); return ret; } return 0; } static struct snd_soc_ops imxpac_tc358743_snd_ops = { .hw_params = imxpac_tc358743_hw_params, }; static struct snd_soc_dai_link imxpac_tc358743_dai = { .name = "tc358743", .stream_name = "TC358743", .codec_dai_name = "tc358743-hifi", .platform_name = "imx-pcm-audio.2", .codec_name = "tc358743_mipi.1-000f", .cpu_dai_name = "imx-ssi.2", .init = imx_3stack_tc358743_init, .ops = &imxpac_tc358743_snd_ops, }; static struct snd_soc_card imxpac_tc358743 = { .name = "cpuimx-audio_hdmi_in", .dai_link = &imxpac_tc358743_dai, .num_links = 1, }; static struct platform_device *imxpac_tc358743_snd_device; static struct platform_device *imxpac_tc358743_snd_device; static int imx_audmux_config(int slave, int master) { unsigned int ptcr, pdcr; slave = slave - 1; master = master - 1; /* SSI0 mastered by port 5 */ ptcr = MXC_AUDMUX_V2_PTCR_SYN | MXC_AUDMUX_V2_PTCR_TFSDIR | MXC_AUDMUX_V2_PTCR_TFSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_TCLKDIR | MXC_AUDMUX_V2_PTCR_RFSDIR | MXC_AUDMUX_V2_PTCR_RFSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_RCLKDIR | MXC_AUDMUX_V2_PTCR_RCSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_TCSEL(master | 0x8); pdcr = MXC_AUDMUX_V2_PDCR_RXDSEL(master); mxc_audmux_v2_configure_port(slave, ptcr, pdcr); ptcr = MXC_AUDMUX_V2_PTCR_SYN; pdcr = MXC_AUDMUX_V2_PDCR_RXDSEL(master); mxc_audmux_v2_configure_port(master, ptcr, pdcr); return 0; } static int __devinit imx_tc358743_probe(struct platform_device *pdev) { struct mxc_audio_platform_data *plat = pdev->dev.platform_data; int ret = 0; imx_audmux_config(plat->src_port, plat->ext_port); ret = -EINVAL; if (plat->init && plat->init()) return ret; printk("%s %d %s\n",__func__,__LINE__,pdev->name); return 0; } static int imx_tc358743_remove(struct platform_device *pdev) { struct mxc_audio_platform_data *plat = pdev->dev.platform_data; if (plat->finit) plat->finit(); return 0; } static struct platform_driver imx_tc358743_audio1_driver = { .probe = imx_tc358743_probe, .remove = imx_tc358743_remove, .driver = { .name = "imx-tc358743", }, }; /* Codec setup */ static int tc358743_codec_probe(struct snd_soc_codec *codec) { return 0; } static int tc358743_codec_remove(struct snd_soc_codec *codec) { return 0; } static int tc358743_codec_suspend(struct snd_soc_codec *codec, pm_message_t state) { // tc358743_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int tc358743_codec_resume(struct snd_soc_codec *codec) { // tc358743_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static int tc358743_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { return 0; } static const u8 tc358743_reg[0] = { }; static struct snd_soc_codec_driver soc_codec_dev_tc358743 = { .set_bias_level = tc358743_set_bias_level, .reg_cache_size = ARRAY_SIZE(tc358743_reg), .reg_word_size = sizeof(u8), .reg_cache_default = tc358743_reg, .probe = tc358743_codec_probe, .remove = tc358743_codec_remove, .suspend = tc358743_codec_suspend, .resume = tc358743_codec_resume, }; #define AIC3X_RATES SNDRV_PCM_RATE_8000_96000 #define AIC3X_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE) static int tc358743_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { return 0; } static int tc358743_mute(struct snd_soc_dai *dai, int mute) { return 0; } static int tc358743_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { return 0; } static int tc358743_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { return 0; } static struct snd_soc_dai_ops tc358743_dai_ops = { .hw_params = tc358743_hw_params, .digital_mute = tc358743_mute, .set_sysclk = tc358743_set_dai_sysclk, .set_fmt = tc358743_set_dai_fmt, }; static struct snd_soc_dai_driver tc358743_dai = { .name = "tc358743-hifi", .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 2, .rates = AIC3X_RATES, .formats = AIC3X_FORMATS,}, .ops = &tc358743_dai_ops, .symmetric_rates = 1, }; #endif static char tc358743_mode_list[16][12] = { "None", "VGA", "240p/480i", "288p/576i", "W240p/480i", "W288p/576i", "480p", "576p", "W480p", "W576p", "WW480p", "WW576p", "720p", "1035i", "1080i", "1080p" }; static char tc358743_fps_list[tc358743_max_fps+1] = { [tc358743_60_fps] = 60, [tc358743_30_fps] = 30, [tc358743_max_fps] = 0 }; static int tc358743_audio_list[16] = { 44100, 0, 48000, 32000, 22050, 384000, 24000, 352800, 88200, 768000, 96000, 705600, 176400, 0, 192000, 0 }; static char str_on[80]; static void report_netlink(void) { char *envp[2]; envp[0] = &str_on[0]; envp[1] = NULL; sprintf(envp[0], "HDMI RX: %d (%s) %d %d", (unsigned char)hdmi_mode & 0xf, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], tc358743_fps_list[fps], tc358743_audio_list[audio]); kobject_uevent_env(&(tc358743_data.i2c_client->dev.kobj), KOBJ_CHANGE, envp); det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; pr_debug("%s: HDMI RX (%d) mode: %s fps: %d (%d, %d) audio: %d\n", __func__, (unsigned char)hdmi_mode, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], fps, bounce, det_work_timeout, tc358743_audio_list[audio]); } static void det_worker(struct work_struct *work) { u32 u32val; u16 reg; int ret; mutex_lock(&access_lock); if (!det_work_disable) { reg = 0x8621; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { if (audio != (((unsigned char)u32val) & 0x0f)) { audio = ((unsigned char)u32val) & 0x0f; report_netlink(); } } reg = 0x852f; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { while (1) { if (u32val & TC3587430_HDMI_DETECT) { lock = u32val & TC3587430_HDMI_DETECT; reg = 0x8521; ret = tc358743_read_reg(reg, &u32val); if (ret < 0) { pr_err("%s: Error reading mode\n", __func__); } } else { if (lock) { // check if it is realy un-plug lock = 0; u32val = 0x0; hdmi_mode = 0xF0; // fake mode to detect un-plug if mode was not detected before. } } if ((unsigned char)hdmi_mode != (unsigned char)u32val) { if (u32val) det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; else det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; bounce = MAX_BOUNCE; pr_debug("%s: HDMI RX (%d != %d) mode: %s fps: %d (%d, %d)\n", __func__, (unsigned char)hdmi_mode, (unsigned char)u32val, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], fps, bounce, det_work_timeout); hdmi_mode = u32val; } else if (bounce) { bounce--; det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; } if (1 == bounce) { if (hdmi_mode >= 0xe) { reg = 0x852f; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) fps = ((((unsigned char)u32val) & 0x0f) > 0xa)? tc358743_60_fps: tc358743_30_fps; } reg = 0x8621; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { audio = ((unsigned char)u32val) & 0x0f; report_netlink(); } } break; } } else { pr_err("%s: Error reading lock\n", __func__); } } else { det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; } mutex_unlock(&access_lock); schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); } static irqreturn_t tc358743_detect_handler(int irq, void *data) { pr_debug("%s: IRQ %d\n", __func__, tc358743_data.i2c_client->irq); schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); return IRQ_HANDLED; } /*! * tc358743 I2C probe function * * @param adapter struct i2c_adapter * * @return Error code indicating success or failure */ #define DUMP_LENGTH 256 static u16 regoffs = 0; static ssize_t tc358743_show_regdump(struct device *dev, struct device_attribute *attr, char *buf) { int i, len = 0; int retval; u32 u32val; mutex_lock(&access_lock); for (i=0; i<DUMP_LENGTH; ) { retval = tc358743_read_reg(regoffs+i, &u32val); if (retval < 0) { u32val =0xff; retval = 1; } while (retval-- > 0) { if (0 == (i & 0xf)) len += sprintf(buf+len, "\n%04X:", regoffs+i); len += sprintf(buf+len, " %02X", u32val&0xff); u32val >>= 8; i++; } } mutex_unlock(&access_lock); len += sprintf(buf+len, "\n"); return len; } static DEVICE_ATTR(regdump, S_IRUGO, tc358743_show_regdump, NULL); static ssize_t tc358743_store_regoffs(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { u32 val; int retval; retval = sscanf(buf, "%x", &val); if (1 == retval) regoffs = (u16)val; return count; } static ssize_t tc358743_show_regoffs(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "0x%04X\n", regoffs); return len; } static DEVICE_ATTR(regoffs, S_IRUGO|S_IWUSR, tc358743_show_regoffs, tc358743_store_regoffs); static ssize_t tc358743_store_hpd(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { u32 val; int retval; retval = sscanf(buf, "%d", &val); if (1 == retval) hpd_active = (u16)val; return count; } static ssize_t tc358743_show_hpd(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", hpd_active); return len; } static DEVICE_ATTR(hpd, S_IRUGO|S_IWUSR, tc358743_show_hpd, tc358743_store_hpd); static ssize_t tc358743_show_hdmirx(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", hdmi_mode); return len; } static DEVICE_ATTR(hdmirx, S_IRUGO, tc358743_show_hdmirx, NULL); static ssize_t tc358743_show_fps(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", tc358743_fps_list[fps]); return len; } static DEVICE_ATTR(fps, S_IRUGO, tc358743_show_fps, NULL); #ifdef AUDIO_ENABLE static ssize_t tc358743_show_audio(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", tc358743_audio_list[audio]); return len; } static DEVICE_ATTR(audio, S_IRUGO, tc358743_show_audio, NULL); #endif static int tc358743_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct pwm_device *pwm; struct device *dev = &client->dev; int retval; struct regmap *gpr; struct sensor_data *sensor = &tc358743_data; u32 u32val; /* request power down pin */ pwn_gpio = of_get_named_gpio(dev->of_node, "pwn-gpios", 0); if (!gpio_is_valid(pwn_gpio)) { dev_warn(dev, "no sensor pwdn pin available"); } else { retval = devm_gpio_request_one(dev, pwn_gpio, GPIOF_OUT_INIT_HIGH, "tc_mipi_pwdn"); if (retval < 0) { dev_warn(dev, "request of pwn_gpio failed"); return retval; } } /* request reset pin */ rst_gpio = of_get_named_gpio(dev->of_node, "rst-gpios", 0); if (!gpio_is_valid(rst_gpio)) { dev_warn(dev, "no sensor reset pin available"); return -EINVAL; } retval = devm_gpio_request_one(dev, rst_gpio, GPIOF_OUT_INIT_HIGH, "tc_mipi_reset"); if (retval < 0) { dev_warn(dev, "request of tc_mipi_reset failed"); return retval; } /* Set initial values for the sensor struct. */ memset(sensor, 0, sizeof(*sensor)); sensor->sensor_clk = devm_clk_get(dev, "csi_mclk"); if (IS_ERR(sensor->sensor_clk)) { /* assuming clock enabled by default */ sensor->sensor_clk = NULL; dev_err(dev, "clock-frequency missing or invalid\n"); return PTR_ERR(sensor->sensor_clk); } retval = of_property_read_u32(dev->of_node, "mclk", &(sensor->mclk)); if (retval) { dev_err(dev, "mclk missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "mclk_source", (u32 *) &(sensor->mclk_source)); if (retval) { dev_err(dev, "mclk_source missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "ipu_id", &sensor->ipu_id); if (retval) { dev_err(dev, "ipu_id missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "csi_id", &(sensor->csi)); if (retval) { dev_err(dev, "csi id missing or invalid\n"); return retval; } if (((unsigned)sensor->ipu_id > 1) || ((unsigned)sensor->csi > 1)) { dev_err(dev, "invalid ipu/csi\n"); return -EINVAL; } clk_prepare_enable(sensor->sensor_clk); sensor->io_init = tc_reset; sensor->i2c_client = client; sensor->pix.pixelformat = tc358743_formats[0].pixelformat; sensor->streamcap.capability = V4L2_MODE_HIGHQUALITY | V4L2_CAP_TIMEPERFRAME; sensor->streamcap.capturemode = 0; sensor->streamcap.extendedmode = tc358743_mode_1080P_1920_1080; sensor->streamcap.timeperframe.denominator = DEFAULT_FPS; sensor->streamcap.timeperframe.numerator = 1; sensor->pix.width = tc358743_mode_info_data[0][sensor->streamcap.capturemode].width; sensor->pix.height = tc358743_mode_info_data[0][sensor->streamcap.capturemode].height; pr_debug("%s: format: %x, capture mode: %d extended mode: %d fps: %d width: %d height: %d\n",__func__, sensor->pix.pixelformat, sensor->streamcap.capturemode, sensor->streamcap.extendedmode, sensor->streamcap.timeperframe.denominator * sensor->streamcap.timeperframe.numerator, sensor->pix.width, sensor->pix.height); pwm = pwm_get(dev, NULL); if (!IS_ERR(pwm)) { dev_info(dev, "found pwm%d, period=%d\n", pwm->pwm, pwm->period); pwm_config(pwm, pwm->period >> 1, pwm->period); pwm_enable(pwm); } tc_power_on(dev); tc_reset(); tc_standby(0); retval = tc358743_read_reg(TC358743_CHIP_ID_HIGH_BYTE, &u32val); if (retval < 0) { pr_err("%s:cannot find camera\n", __func__); retval = -ENODEV; goto err4; } gpr = syscon_regmap_lookup_by_compatible("fsl,imx6q-iomuxc-gpr"); if (!IS_ERR(gpr)) { if (of_machine_is_compatible("fsl,imx6q")) { if (sensor->csi == sensor->ipu_id) { int mask = sensor->csi ? (1 << 20) : (1 << 19); regmap_update_bits(gpr, IOMUXC_GPR1, mask, 0); } } else if (of_machine_is_compatible("fsl,imx6dl")) { int mask = sensor->csi ? (7 << 3) : (7 << 0); int val = sensor->csi ? (3 << 3) : (0 << 0); if (sensor->ipu_id) { dev_err(dev, "invalid ipu\n"); return -EINVAL; } regmap_update_bits(gpr, IOMUXC_GPR13, mask, val); } } else { pr_err("%s: failed to find fsl,imx6q-iomux-gpr regmap\n", __func__); } tc358743_int_device.priv = sensor; //retval = device_create_file(&client->dev, &dev_attr_audio); retval = device_create_file(&client->dev, &dev_attr_fps); retval = device_create_file(&client->dev, &dev_attr_hdmirx); retval = device_create_file(&client->dev, &dev_attr_hpd); retval = device_create_file(&client->dev, &dev_attr_regoffs); retval = device_create_file(&client->dev, &dev_attr_regdump); if (retval) { pr_err("%s: create bin file failed, error=%d\n", __func__, retval); goto err4; } #ifdef AUDIO_ENABLE /* Audio setup */ retval = snd_soc_register_codec(&client->dev, &soc_codec_dev_tc358743, &tc358743_dai, 1); if (retval) { pr_err("%s: register failed, error=%d\n", __func__, retval); goto err4; } retval = platform_driver_register(&imx_tc358743_audio1_driver); if (retval) { pr_err("%s: Platform driver register failed, error=%d\n", __func__, retval); goto err4; } imxpac_tc358743_snd_device = platform_device_alloc("soc-audio", 5); if (!imxpac_tc358743_snd_device) { pr_err("%s: Platform device allocation failed, error=%d\n", __func__, retval); goto err4; } platform_set_drvdata(imxpac_tc358743_snd_device, &imxpac_tc358743); retval = platform_device_add(imxpac_tc358743_snd_device); if (retval) { pr_err("%s: Platform device add failed, error=%d\n", __func__, retval); platform_device_put(imxpac_tc358743_snd_device); goto err4; } #endif #if 1 INIT_DELAYED_WORK(&(det_work), det_worker); if (sensor->i2c_client->irq) { retval = request_irq(sensor->i2c_client->irq, tc358743_detect_handler, IRQF_SHARED | IRQF_TRIGGER_FALLING, "tc358743_det", sensor); if (retval < 0) dev_warn(&sensor->i2c_client->dev, "cound not request det irq %d\n", sensor->i2c_client->irq); } schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); #endif retval = tc358743_reset(sensor); tc_standby(1); retval = v4l2_int_device_register(&tc358743_int_device); if (retval) { pr_err("%s: v4l2_int_device_register failed, error=%d\n", __func__, retval); goto err4; } pr_debug("%s: finished, error=%d\n", __func__, retval); return retval; err4: pr_err("%s: failed, error=%d\n", __func__, retval); return retval; } /*! * tc358743 I2C detach function * * @param client struct i2c_client * * @return Error code indicating success or failure */ static int tc358743_remove(struct i2c_client *client) { // Stop delayed work cancel_delayed_work_sync(&(det_work)); // Remove IRQ if (tc358743_data.i2c_client->irq) { free_irq(tc358743_data.i2c_client->irq, &tc358743_data); } /*Remove sysfs entries*/ device_remove_file(&client->dev, &dev_attr_fps); device_remove_file(&client->dev, &dev_attr_hdmirx); device_remove_file(&client->dev, &dev_attr_hpd); device_remove_file(&client->dev, &dev_attr_regoffs); device_remove_file(&client->dev, &dev_attr_regdump); v4l2_int_device_unregister(&tc358743_int_device); if (gpo_regulator) { regulator_disable(gpo_regulator); regulator_put(gpo_regulator); } if (analog_regulator) { regulator_disable(analog_regulator); regulator_put(analog_regulator); } if (core_regulator) { regulator_disable(core_regulator); regulator_put(core_regulator); } if (io_regulator) { regulator_disable(io_regulator); regulator_put(io_regulator); } return 0; } /*! * tc358743 init function * Called by insmod tc358743_camera.ko. * * @return Error code indicating success or failure */ static __init int tc358743_init(void) { int err; err = i2c_add_driver(&tc358743_i2c_driver); if (err != 0) pr_err("%s:driver registration failed, error=%d\n", __func__, err); return err; } /*! * tc358743 cleanup function * Called on rmmod tc358743_camera.ko * * @return Error code indicating success or failure */ static void __exit tc358743_clean(void) { i2c_del_driver(&tc358743_i2c_driver); } module_init(tc358743_init); module_exit(tc358743_clean); MODULE_AUTHOR("Panasonic Avionics Corp."); MODULE_DESCRIPTION("Toshiba TC358743 HDMI-to-CSI2 Bridge MIPI Input Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION("1.0"); MODULE_ALIAS("CSI");
captivo/linux-captivo
drivers/media/platform/mxc/capture/tc358743_h2c.c
C
gpl-2.0
111,500
<?php /** * File containing the eZContentOperationCollection class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// * @package kernel */ /*! \class eZContentOperationCollection ezcontentoperationcollection.php \brief The class eZContentOperationCollection does */ class eZContentOperationCollection { /** * Use by {@see beginTransaction()} and {@see commitTransaction()} to handle nested publish operations */ private static $operationsStack = 0; static public function readNode( $nodeID ) { } static public function readObject( $nodeID, $userID, $languageCode ) { if ( $languageCode != '' ) { $node = eZContentObjectTreeNode::fetch( $nodeID, $languageCode ); } else { $node = eZContentObjectTreeNode::fetch( $nodeID ); } if ( $node === null ) // return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); return false; $object = $node->attribute( 'object' ); if ( $object === null ) // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); { return false; } /* if ( !$object->attribute( 'can_read' ) ) { // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); return false; } */ return array( 'status' => true, 'object' => $object, 'node' => $node ); } static public function loopNodes( $nodeID ) { return array( 'parameters' => array( array( 'parent_node_id' => 3 ), array( 'parent_node_id' => 5 ), array( 'parent_node_id' => 12 ) ) ); } static public function loopNodeAssignment( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignmentList = $version->attribute( 'node_assignments' ); $parameters = array(); foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment->attribute( 'parent_node' ) > 0 ) { if ( $nodeAssignment->attribute( 'is_main' ) == 1 ) { $mainNodeID = self::publishNode( $nodeAssignment->attribute( 'parent_node' ), $objectID, $versionNum, false ); } else { $parameters[] = array( 'parent_node_id' => $nodeAssignment->attribute( 'parent_node' ) ); } } } for ( $i = 0; $i < count( $parameters ); $i++ ) { $parameters[$i]['main_node_id'] = $mainNodeID; } return array( 'parameters' => $parameters ); } function publishObjectExtensionHandler( $contentObjectID, $contentObjectVersion ) { eZContentObjectEditHandler::executePublish( $contentObjectID, $contentObjectVersion ); } /** * Starts a database transaction. */ static public function beginTransaction() { // We only start a transaction if another content publish operation hasn't been started if ( ++self::$operationsStack === 1 ) { eZDB::instance()->begin(); } } /** * Commit a previously started database transaction. */ static public function commitTransaction() { if ( --self::$operationsStack === 0 ) { eZDB::instance()->commit(); } } static public function setVersionStatus( $objectID, $versionNum, $status ) { $object = eZContentObject::fetch( $objectID ); if ( !$versionNum ) { $versionNum = $object->attribute( 'current_version' ); } $version = $object->version( $versionNum ); if ( !$version ) return; $version->setAttribute( 'status', $status ); $version->store(); } static public function setObjectStatusPublished( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $db = eZDB::instance(); $db->begin(); $object->setAttribute( 'status', eZContentObject::STATUS_PUBLISHED ); $version->setAttribute( 'status', eZContentObjectVersion::STATUS_PUBLISHED ); $object->setAttribute( 'current_version', $versionNum ); $objectIsAlwaysAvailable = $object->isAlwaysAvailable(); $object->setAttribute( 'language_mask', eZContentLanguage::maskByLocale( $version->translationList( false, false ), $objectIsAlwaysAvailable ) ); if ( $object->attribute( 'published' ) == 0 ) { $object->setAttribute( 'published', time() ); } $object->setAttribute( 'modified', time() ); $classID = $object->attribute( 'contentclass_id' ); $class = eZContentClass::fetch( $classID ); $objectName = $class->contentObjectName( $object ); $object->setName( $objectName, $versionNum ); $existingTranslations = $version->translations( false ); foreach( $existingTranslations as $translation ) { $translatedName = $class->contentObjectName( $object, $versionNum, $translation ); $object->setName( $translatedName, $versionNum, $translation ); } if ( $objectIsAlwaysAvailable ) { $initialLanguageID = $object->attribute( 'initial_language_id' ); $object->setAlwaysAvailableLanguageID( $initialLanguageID ); } $version->store(); $object->store(); eZContentObjectTreeNode::setVersionByObjectID( $objectID, $versionNum ); $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->setName( $object->attribute( 'name' ) ); $node->updateSubTreePath(); } $db->commit(); /* Check if current class is the user class, and if so, clean up the user-policy cache */ if ( in_array( $classID, eZUser::contentClassIDs() ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } static public function attributePublishAction( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $nodes = $object->assignedNodes(); $version = $object->version( $versionNum ); $contentObjectAttributes = $object->contentObjectAttributes( true, $versionNum, $version->initialLanguageCode(), false ); foreach ( $contentObjectAttributes as $contentObjectAttribute ) { $contentObjectAttribute->onPublish( $object, $nodes ); } } /*! \static Generates the related viewcaches (PreGeneration) for the content object. It will only do this if [ContentSettings]/PreViewCache in site.ini is enabled. \param $objectID The ID of the content object to generate caches for. */ static public function generateObjectViewCache( $objectID ) { eZContentCacheManager::generateObjectViewCache( $objectID ); } /*! \static Clears the related viewcaches for the content object using the smart viewcache system. \param $objectID The ID of the content object to clear caches for \param $versionNum The version of the object to use or \c true for current version \param $additionalNodeList An array with node IDs to add to clear list, or \c false for no additional nodes. */ static public function clearObjectViewCache( $objectID, $versionNum = true, $additionalNodeList = false ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeList ); } static public function publishNode( $parentNodeID, $objectID, $versionNum, $mainNodeID ) { $object = eZContentObject::fetch( $objectID ); $nodeAssignment = eZNodeAssignment::fetch( $objectID, $versionNum, $parentNodeID ); $version = $object->version( $versionNum ); $fromNodeID = $nodeAssignment->attribute( 'from_node_id' ); $originalObjectID = $nodeAssignment->attribute( 'contentobject_id' ); $nodeID = $nodeAssignment->attribute( 'parent_node' ); $opCode = $nodeAssignment->attribute( 'op_code' ); $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); // if parent doesn't exist, return. See issue #18320 if ( !$parentNode instanceof eZContentObjectTreeNode ) { eZDebug::writeError( "Parent node doesn't exist. object id: $objectID, node_assignment id: " . $nodeAssignment->attribute( 'id' ), __METHOD__ ); return; } $parentNodeID = $parentNode->attribute( 'node_id' ); $existingNode = null; $db = eZDB::instance(); $db->begin(); if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode = eZContentObjectTreeNode::fetchByRemoteID( $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( !$existingNode ); { $existingNode = eZContentObjectTreeNode::findNode( $nodeID , $object->attribute( 'id' ), true ); } $updateSectionID = false; // now we check the op_code to see what to do if ( ( $opCode & 1 ) == eZNodeAssignment::OP_CODE_NOP ) { // There is nothing to do so just return $db->commit(); if ( $mainNodeID == false ) { return $object->attribute( 'main_node_id' ); } return; } $updateFields = false; if ( $opCode == eZNodeAssignment::OP_CODE_MOVE || $opCode == eZNodeAssignment::OP_CODE_CREATE ) { // if ( $fromNodeID == 0 || $fromNodeID == -1) if ( $opCode == eZNodeAssignment::OP_CODE_CREATE || $opCode == eZNodeAssignment::OP_CODE_SET ) { // If the node already exists it means we have a conflict (for 'CREATE'). // We resolve this by leaving node-assignment data be. if ( $existingNode == null ) { $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); $user = eZUser::currentUser(); if ( !eZSys::isShellExecution() and !$user->isAnonymous() ) { eZContentBrowseRecent::createNew( $user->id(), $parentNode->attribute( 'node_id' ), $parentNode->attribute( 'name' ) ); } $updateFields = true; $existingNode = $parentNode->addChild( $object->attribute( 'id' ), true ); if ( $fromNodeID == -1 ) { $updateSectionID = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_SET ) { $updateFields = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_MOVE ) { if ( $fromNodeID == 0 || $fromNodeID == -1 ) { eZDebug::writeError( "NodeAssignment '" . $nodeAssignment->attribute( 'id' ) . "' is marked with op_code='$opCode' but has no data in from_node_id. Cannot use it for moving node.", __METHOD__ ); } else { // clear cache for old placement. $additionalNodeIDList = array( $fromNodeID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeIDList ); $originalNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $fromNodeID ); if ( $originalNode->attribute( 'main_node_id' ) == $originalNode->attribute( 'node_id' ) ) { $updateSectionID = true; } $originalNode->move( $parentNodeID ); $existingNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $parentNodeID ); $updateFields = true; } } } elseif ( $opCode == eZNodeAssignment::OP_CODE_REMOVE ) { $db->commit(); return; } if ( $updateFields ) { if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode->setAttribute( 'remote_id', $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( $nodeAssignment->attribute( 'is_hidden' ) ) { $existingNode->setAttribute( 'is_hidden', 1 ); $existingNode->setAttribute( 'is_invisible', 1 ); } $existingNode->setAttribute( 'priority', $nodeAssignment->attribute( 'priority' ) ); $existingNode->setAttribute( 'sort_field', $nodeAssignment->attribute( 'sort_field' ) ); $existingNode->setAttribute( 'sort_order', $nodeAssignment->attribute( 'sort_order' ) ); } $existingNode->setAttribute( 'contentobject_is_published', 1 ); eZDebug::createAccumulatorGroup( 'nice_urls_total', 'Nice urls' ); if ( $mainNodeID > 0 ) { $existingNodeID = $existingNode->attribute( 'node_id' ); if ( $existingNodeID != $mainNodeID ) { eZContentBrowseRecent::updateNodeID( $existingNodeID, $mainNodeID ); } $existingNode->setAttribute( 'main_node_id', $mainNodeID ); } else { $existingNode->setAttribute( 'main_node_id', $existingNode->attribute( 'node_id' ) ); } $existingNode->store(); if ( $updateSectionID ) { eZContentOperationCollection::updateSectionID( $objectID, $versionNum ); } $db->commit(); if ( $mainNodeID == false ) { return $existingNode->attribute( 'node_id' ); } } static public function updateSectionID( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); if ( $versionNum == 1 or $object->attribute( 'current_version' ) == $versionNum ) { $newMainAssignment = null; $newMainAssignments = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); if ( isset( $newMainAssignments[0] ) ) { $newMainAssignment = $newMainAssignments[0]; } // we should not update section id for toplevel nodes if ( $newMainAssignment && $newMainAssignment->attribute( 'parent_node' ) != 1 ) { // We should check if current object already has been updated for section_id // If yes we should not update object section_id by $parentNodeSectionID $sectionID = $object->attribute( 'section_id' ); if ( $sectionID > 0 ) return; $newParentObject = $newMainAssignment->getParentObject(); if ( !$newParentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $parentNodeSectionID = $newParentObject->attribute( 'section_id' ); $object->setAttribute( 'section_id', $parentNodeSectionID ); $object->store(); } return; } $newMainAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); $newMainAssignment = ( count( $newMainAssignmentList ) ) ? array_pop( $newMainAssignmentList ) : null; $currentVersion = $object->attribute( 'current' ); // Here we need to fetch published nodes and not old node assignments. $oldMainNode = $object->mainNode(); if ( $newMainAssignment && $oldMainNode && $newMainAssignment->attribute( 'parent_node' ) != $oldMainNode->attribute( 'parent_node_id' ) ) { $oldMainParentNode = $oldMainNode->attribute( 'parent' ); if ( $oldMainParentNode ) { $oldParentObject = $oldMainParentNode->attribute( 'object' ); $oldParentObjectSectionID = $oldParentObject->attribute( 'section_id' ); if ( $oldParentObjectSectionID == $object->attribute( 'section_id' ) ) { $newParentNode = $newMainAssignment->attribute( 'parent_node_obj' ); if ( !$newParentNode ) return; $newParentObject = $newParentNode->attribute( 'object' ); if ( !$newParentObject ) return; $newSectionID = $newParentObject->attribute( 'section_id' ); if ( $newSectionID != $object->attribute( 'section_id' ) ) { $oldSectionID = $object->attribute( 'section_id' ); $object->setAttribute( 'section_id', $newSectionID ); $db = eZDB::instance(); $db->begin(); $object->store(); $mainNodeID = $object->attribute( 'main_node_id' ); if ( $mainNodeID > 0 ) { eZContentObjectTreeNode::assignSectionToSubTree( $mainNodeID, $newSectionID, $oldSectionID ); } $db->commit(); } } } } } static public function removeOldNodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); if ( !$object instanceof eZContentObject ) { eZDebug::writeError( 'Unable to find object #' . $objectID, __METHOD__ ); return; } $version = $object->version( $versionNum ); if ( !$version instanceof eZContentObjectVersion ) { eZDebug::writeError( 'Unable to find version #' . $versionNum . ' for object #' . $objectID, __METHOD__ ); return; } $moveToTrash = true; $assignedExistingNodes = $object->attribute( 'assigned_nodes' ); $curentVersionNodeAssignments = $version->attribute( 'node_assignments' ); $removeParentNodeList = array(); $removeAssignmentsList = array(); foreach ( $curentVersionNodeAssignments as $nodeAssignment ) { $nodeAssignmentOpcode = $nodeAssignment->attribute( 'op_code' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE || $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE_NOP ) { $removeAssignmentsList[] = $nodeAssignment->attribute( 'id' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE ) { $removeParentNodeList[] = $nodeAssignment->attribute( 'parent_node' ); } } } $db = eZDB::instance(); $db->begin(); foreach ( $assignedExistingNodes as $node ) { if ( in_array( $node->attribute( 'parent_node_id' ), $removeParentNodeList ) ) { eZContentObjectTreeNode::removeSubtrees( array( $node->attribute( 'node_id' ) ), $moveToTrash ); } } if ( count( $removeAssignmentsList ) > 0 ) { eZNodeAssignment::purgeByID( $removeAssignmentsList ); } $db->commit(); } // New function which resets the op_code field when the object is published. static public function resetNodeassignmentOpcodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignments = $version->attribute( 'node_assignments' ); foreach ( $nodeAssignments as $nodeAssignment ) { if ( ( $nodeAssignment->attribute( 'op_code' ) & 1 ) == eZNodeAssignment::OP_CODE_EXECUTE ) { $nodeAssignment->setAttribute( 'op_code', ( $nodeAssignment->attribute( 'op_code' ) & ~1 ) ); $nodeAssignment->store(); } } } /** * Registers the object in search engine. * * @note Transaction unsafe. If you call several transaction unsafe methods you must enclose * the calls within a db transaction; thus within db->begin and db->commit. * * @param int $objectID Id of the object. * @param int $version Operation collection passes this default param. Not used in the method * @param bool $isMoved true if node is being moved */ static public function registerSearchObject( $objectID, $version = null, $isMoved = false ) { $objectID = (int)$objectID; eZDebug::createAccumulatorGroup( 'search_total', 'Search Total' ); $ini = eZINI::instance( 'site.ini' ); $insertPendingAction = false; $object = null; switch ( $ini->variable( 'SearchSettings', 'DelayedIndexing' ) ) { case 'enabled': $insertPendingAction = true; break; case 'classbased': $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); $object = eZContentObject::fetch( $objectID ); if ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) { $insertPendingAction = true; } } if ( $insertPendingAction ) { $action = $isMoved ? 'index_moved_node' : 'index_object'; eZDB::instance()->query( "INSERT INTO ezpending_actions( action, param ) VALUES ( '$action', '$objectID' )" ); return; } if ( $object === null ) $object = eZContentObject::fetch( $objectID ); // Register the object in the search engine. $needCommit = eZSearch::needCommit(); if ( eZSearch::needRemoveWithUpdate() ) { eZDebug::accumulatorStart( 'remove_object', 'search_total', 'remove object' ); eZSearch::removeObjectById( $objectID ); eZDebug::accumulatorStop( 'remove_object' ); } eZDebug::accumulatorStart( 'add_object', 'search_total', 'add object' ); if ( !eZSearch::addObject( $object, $needCommit ) ) { eZDebug::writeError( "Failed adding object ID {$object->attribute( 'id' )} in the search engine", __METHOD__ ); } eZDebug::accumulatorStop( 'add_object' ); } /*! \note Transaction unsafe. If you call several transaction unsafe methods you must enclose the calls within a db transaction; thus within db->begin and db->commit. */ static public function createNotificationEvent( $objectID, $versionNum ) { $event = eZNotificationEvent::create( 'ezpublish', array( 'object' => $objectID, 'version' => $versionNum ) ); $event->store(); } /*! Copies missing translations from published version to the draft. */ static public function copyTranslations( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); if ( !$object instanceof eZContentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $publishedVersionNum = $object->attribute( 'current_version' ); if ( !$publishedVersionNum ) { return; } $publishedVersion = $object->version( $publishedVersionNum ); $publishedVersionTranslations = $publishedVersion->translations(); $publishedLanguages = eZContentLanguage::languagesByMask( $object->attribute( 'language_mask' ) ); $publishedLanguageCodes = array_keys( $publishedLanguages ); $version = $object->version( $versionNum ); $versionTranslationList = array_keys( eZContentLanguage::languagesByMask( $version->attribute( 'language_mask' ) ) ); foreach ( $publishedVersionTranslations as $translation ) { $translationLanguageCode = $translation->attribute( 'language_code' ); if ( in_array( $translationLanguageCode, $versionTranslationList ) || !in_array( $translationLanguageCode, $publishedLanguageCodes ) ) { continue; } foreach ( $translation->objectAttributes() as $attribute ) { $clonedAttribute = $attribute->cloneContentObjectAttribute( $versionNum, $publishedVersionNum, $objectID ); $clonedAttribute->sync(); } } $version->updateLanguageMask(); } /*! Updates non-translatable attributes. */ static public function updateNontranslatableAttributes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nonTranslatableAttributes = $version->nonTranslatableAttributesToUpdate(); if ( $nonTranslatableAttributes ) { $attributes = $version->contentObjectAttributes( $version->initialLanguageCode() ); $attributeByClassAttrID = array(); foreach ( $attributes as $attribute ) { $attributeByClassAttrID[$attribute->attribute( 'contentclassattribute_id' )] = $attribute; } foreach ( $nonTranslatableAttributes as $attributeToUpdate ) { $originalAttribute =& $attributeByClassAttrID[$attributeToUpdate->attribute( 'contentclassattribute_id' )]; if ( $originalAttribute ) { unset( $tmp ); $tmp = $attributeToUpdate; $tmp->initialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); $tmp->setAttribute( 'id', $attributeToUpdate->attribute( 'id' ) ); $tmp->setAttribute( 'language_code', $attributeToUpdate->attribute( 'language_code' ) ); $tmp->setAttribute( 'language_id', $attributeToUpdate->attribute( 'language_id' ) ); $tmp->setAttribute( 'attribute_original_id', $originalAttribute->attribute( 'id' ) ); $tmp->store(); $tmp->postInitialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); } } } } static public function removeTemporaryDrafts( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $object->cleanupInternalDrafts( eZUser::currentUserID() ); } /** * Moves a node * * @param int $nodeID * @param int $objectID * @param int $newParentNodeID * * @return array An array with operation status, always true */ static public function moveNode( $nodeID, $objectID, $newParentNodeID ) { if( !eZContentObjectTreeNodeOperations::move( $nodeID, $newParentNodeID ) ) { eZDebug::writeError( "Failed to move node $nodeID as child of parent node $newParentNodeID", __METHOD__ ); return array( 'status' => false ); } eZContentObject::fixReverseRelations( $objectID, 'move' ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Adds a new nodeAssignment * * @param int $nodeID * @param int $objectId * @param array $selectedNodeIDArray * * @return array An array with operation status, always true */ static public function addAssignment( $nodeID, $objectID, $selectedNodeIDArray ) { $userClassIDArray = eZUser::contentClassIDs(); $object = eZContentObject::fetch( $objectID ); $class = $object->contentClass(); $nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false ); $assignedNodes = $object->assignedNodes(); $parentNodeIDArray = array(); foreach ( $assignedNodes as $assignedNode ) { $append = false; foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) ) { $append = true; break; } } if ( $append ) { $parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' ); } } $db = eZDB::instance(); $db->begin(); $locationAdded = false; $node = eZContentObjectTreeNode::fetch( $nodeID ); foreach ( $selectedNodeIDArray as $selectedNodeID ) { if ( !in_array( $selectedNodeID, $parentNodeIDArray ) ) { $parentNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $parentNodeObject = $parentNode->attribute( 'object' ); $canCreate = ( ( $parentNode->checkAccess( 'create', $class->attribute( 'id' ), $parentNodeObject->attribute( 'contentclass_id' ) ) == 1 ) || ( $parentNode->canAddLocation() && $node->canRead() ) ); if ( $canCreate ) { $insertedNode = $object->addLocation( $selectedNodeID, true ); // Now set is as published and fix main_node_id $insertedNode->setAttribute( 'contentobject_is_published', 1 ); $insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) ); // Make sure the url alias is set updated. $insertedNode->updateSubTreePath(); $insertedNode->sync(); $locationAdded = true; } } } if ( $locationAdded ) { //call appropriate method from search engine eZSearch::addNodeAssignment( $nodeID, $objectID, $selectedNodeIDArray ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Removes nodes * * This function does not check about permissions, this is the responsibility of the caller! * * @param array $removeNodeIdList Array of Node ID to remove * * @return array An array with operation status, always true */ static public function removeNodes( array $removeNodeIdList ) { $mainNodeChanged = array(); $nodeAssignmentIdList = array(); $objectIdList = array(); $db = eZDB::instance(); $db->begin(); foreach ( $removeNodeIdList as $nodeId ) { $node = eZContentObjectTreeNode::fetch($nodeId); $objectId = $node->attribute( 'contentobject_id' ); foreach ( eZNodeAssignment::fetchForObject( $objectId, eZContentObject::fetch( $objectId )->attribute( 'current_version' ), 0, false ) as $nodeAssignmentKey => $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $node->attribute( 'parent_node_id' ) ) { $nodeAssignmentIdList[$nodeAssignment['id']] = 1; } } if ( $nodeId == $node->attribute( 'main_node_id' ) ) $mainNodeChanged[$objectId] = 1; $node->removeThis(); if ( !isset( $objectIdList[$objectId] ) ) $objectIdList[$objectId] = eZContentObject::fetch( $objectId ); } eZNodeAssignment::purgeByID( array_keys( $nodeAssignmentIdList ) ); foreach ( array_keys( $mainNodeChanged ) as $objectId ) { $allNodes = $objectIdList[$objectId]->assignedNodes(); // Registering node that will be promoted as 'main' if ( isset( $allNodes[0] ) ) { $mainNodeChanged[$objectId] = $allNodes[0]; eZContentObjectTreeNode::updateMainNodeID( $allNodes[0]->attribute( 'node_id' ), $objectId, false, $allNodes[0]->attribute( 'parent_node_id' ) ); } } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { foreach ( array_keys( $objectIdList ) as $objectId ) eZContentOperationCollection::registerSearchObject( $objectId ); } $db->commit(); //call appropriate method from search engine eZSearch::removeNodes( $removeNodeIdList ); $userClassIdList = eZUser::contentClassIDs(); foreach ( $objectIdList as $objectId => $object ) { eZContentCacheManager::clearObjectViewCacheIfNeeded( $objectId ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIdList ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectId ); } } // Triggering content/cache filter for Http cache purge ezpEvent::getInstance()->filter( 'content/cache', $removeNodeIdList, array_keys( $objectIdList ) ); // we don't clear template block cache here since it's cleared in eZContentObjectTreeNode::removeNode() return array( 'status' => true ); } /** * Deletes a content object, or a list of content objects * * @param array $deleteIDArray * @param bool $moveToTrash * * @return array An array with operation status, always true */ static public function deleteObject( $deleteIDArray, $moveToTrash = false ) { $ini = eZINI::instance(); $aNodes = eZContentObjectTreeNode::fetch( $deleteIDArray ); if( !is_array( $aNodes ) ) { $aNodes = array( $aNodes ); } $delayedIndexingValue = $ini->variable( 'SearchSettings', 'DelayedIndexing' ); if ( $delayedIndexingValue === 'enabled' || $delayedIndexingValue === 'classbased' ) { $pendingActionsToDelete = array(); $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); // Will be used below if DelayedIndexing is classbased $assignedNodesByObject = array(); $nodesToDeleteByObject = array(); foreach ( $aNodes as $node ) { $object = $node->object(); $objectID = $object->attribute( 'id' ); $assignedNodes = $object->attribute( 'assigned_nodes' ); // Only delete pending action if this is the last object's node that is requested for deletion // But $deleteIDArray can also contain all the object's node (mainly if this method is called programmatically) // So if this is not the last node, then store its id in a temp array // This temp array will then be compared to the whole object's assigned nodes array if ( count( $assignedNodes ) > 1 ) { // $assignedNodesByObject will be used as a referent to check if we want to delete all lasting nodes if ( !isset( $assignedNodesByObject[$objectID] ) ) { $assignedNodesByObject[$objectID] = array(); foreach ( $assignedNodes as $assignedNode ) { $assignedNodesByObject[$objectID][] = $assignedNode->attribute( 'node_id' ); } } // Store the node assignment we want to delete // Then compare the array to the referent node assignment array $nodesToDeleteByObject[$objectID][] = $node->attribute( 'node_id' ); $diff = array_diff( $assignedNodesByObject[$objectID], $nodesToDeleteByObject[$objectID] ); if ( !empty( $diff ) ) // We still have more node assignments for object, pending action is not to be deleted considering this iteration { continue; } } if ( $delayedIndexingValue !== 'classbased' || ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) ) { $pendingActionsToDelete[] = $objectID; } } if ( !empty( $pendingActionsToDelete ) ) { $filterConds = array( 'param' => array ( $pendingActionsToDelete ) ); eZPendingActions::removeByAction( 'index_object', $filterConds ); } } // Add assigned nodes to the clear cache list // This allows to clear assigned nodes separately (e.g. in reverse proxies) // as once content is removed, there is no more assigned nodes, and http cache clear is not possible any more. // See https://jira.ez.no/browse/EZP-22447 foreach ( $aNodes as $node ) { eZContentCacheManager::addAdditionalNodeIDPerObject( $node->attribute( 'contentobject_id' ), $node->attribute( 'node_id' ) ); } eZContentObjectTreeNode::removeSubtrees( $deleteIDArray, $moveToTrash ); return array( 'status' => true ); } /** * Changes an contentobject's status * * @param int $nodeID * * @return array An array with operation status, always true */ static public function changeHideStatus( $nodeID ) { $action = 'hide'; $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { if ( $curNode->attribute( 'is_hidden' ) ) { eZContentObjectTreeNode::unhideSubTree( $curNode ); $action = 'show'; } else eZContentObjectTreeNode::hideSubTree( $curNode ); } //call appropriate method from search engine eZSearch::updateNodeVisibility( $nodeID, $action ); return array( 'status' => true ); } /** * Swap a node with another one * * @param int $nodeID * @param int $selectedNodeID * @param array $nodeIdList * * @return array An array with operation status, always true */ static public function swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ) { $userClassIDArray = eZUser::contentClassIDs(); $node = eZContentObjectTreeNode::fetch( $nodeID ); $selectedNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $object = $node->object(); $nodeParentNodeID = $node->attribute( 'parent_node_id' ); $nodeParent = $node->attribute( 'parent' ); $objectID = $object->attribute( 'id' ); $objectVersion = $object->attribute( 'current_version' ); $selectedObject = $selectedNode->object(); $selectedObjectID = $selectedObject->attribute( 'id' ); $selectedObjectVersion = $selectedObject->attribute( 'current_version' ); $selectedNodeParentNodeID = $selectedNode->attribute( 'parent_node_id' ); $selectedNodeParent = $selectedNode->attribute( 'parent' ); $db = eZDB::instance(); $db->begin(); $node->setAttribute( 'contentobject_id', $selectedObjectID ); $node->setAttribute( 'contentobject_version', $selectedObjectVersion ); $selectedNode->setAttribute( 'contentobject_id', $objectID ); $selectedNode->setAttribute( 'contentobject_version', $objectVersion ); // fix main node id if ( $node->isMain() && !$selectedNode->isMain() ) { $node->setAttribute( 'main_node_id', $selectedNode->attribute( 'main_node_id' ) ); $selectedNode->setAttribute( 'main_node_id', $selectedNode->attribute( 'node_id' ) ); } else if ( $selectedNode->isMain() && !$node->isMain() ) { $selectedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $node->setAttribute( 'main_node_id', $node->attribute( 'node_id' ) ); } $node->store(); $selectedNode->store(); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } if ( in_array( $selectedObject->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $selectedObject->attribute( 'id' ) ); } // modify path string $changedOriginalNode = eZContentObjectTreeNode::fetch( $nodeID ); $changedOriginalNode->updateSubTreePath(); $changedTargetNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $changedTargetNode->updateSubTreePath(); // modify section if ( $changedOriginalNode->isMain() ) { $changedOriginalObject = $changedOriginalNode->object(); $parentObject = $nodeParent->object(); if ( $changedOriginalObject->attribute( 'section_id' ) != $parentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedOriginalNode->attribute( 'main_node_id' ), $parentObject->attribute( 'section_id' ), $changedOriginalObject->attribute( 'section_id' ) ); } } if ( $changedTargetNode->isMain() ) { $changedTargetObject = $changedTargetNode->object(); $selectedParentObject = $selectedNodeParent->object(); if ( $changedTargetObject->attribute( 'section_id' ) != $selectedParentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedTargetNode->attribute( 'main_node_id' ), $selectedParentObject->attribute( 'section_id' ), $changedTargetObject->attribute( 'section_id' ) ); } } eZContentObject::fixReverseRelations( $objectID, 'swap' ); eZContentObject::fixReverseRelations( $selectedObjectID, 'swap' ); $db->commit(); // clear cache for new placement. eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } eZSearch::swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ); return array( 'status' => true ); } /** * Assigns a node to a section * * @param int $nodeID * @param int $selectedSectionID * @param bool $updateSearchIndexes * * @return void */ static public function updateSection( $nodeID, $selectedSectionID, $updateSearchIndexes = true ) { eZContentObjectTreeNode::assignSectionToSubTree( $nodeID, $selectedSectionID, false, $updateSearchIndexes ); } /** * Changes the status of a translation * * @param int $objectID * @param int $status * * @return array An array with operation status, always true */ static public function changeTranslationAvailableStatus( $objectID, $status = false ) { $object = eZContentObject::fetch( $objectID ); if ( !$object->canEdit() ) { return array( 'status' => false ); } if ( $object->isAlwaysAvailable() & $status == false ) { $object->setAlwaysAvailableLanguageID( false ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } else if ( !$object->isAlwaysAvailable() & $status == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } return array( 'status' => true ); } /** * Changes the sort order for a node * * @param int $nodeID * @param string $sortingField * @param bool $sortingOrder * * @return array An array with operation status, always true */ static public function changeSortOrder( $nodeID, $sortingField, $sortingOrder = false ) { $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { $db = eZDB::instance(); $db->begin(); $curNode->setAttribute( 'sort_field', $sortingField ); $curNode->setAttribute( 'sort_order', $sortingOrder ); $curNode->store(); $db->commit(); $object = $curNode->object(); eZContentCacheManager::clearContentCacheIfNeeded( $object->attribute( 'id' ) ); } return array( 'status' => true ); } /** * Updates the priority of a node * * @param int $parentNodeID * @param array $priorityArray * @param array $priorityIDArray * * @return array An array with operation status, always true */ static public function updatePriority( $parentNodeID, $priorityArray = array(), $priorityIDArray = array() ) { $curNode = eZContentObjectTreeNode::fetch( $parentNodeID ); if ( $curNode instanceof eZContentObjectTreeNode ) { $objectIDs = array(); $db = eZDB::instance(); $db->begin(); for ( $i = 0, $l = count( $priorityArray ); $i < $l; $i++ ) { $priority = (int) $priorityArray[$i]; $nodeID = (int) $priorityIDArray[$i]; $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { continue; } $objectIDs[] = $node->attribute( 'contentobject_id' ); $db->query( "UPDATE ezcontentobject_tree SET priority={$priority} WHERE node_id={$nodeID} AND parent_node_id={$parentNodeID}" ); } $curNode->updateAndStoreModified(); $db->commit(); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectIDs ); foreach ( $objectIDs as $objectID ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } } return array( 'status' => true ); } /** * Update a node's main assignment * * @param int $mainAssignmentID * @param int $objectID * @param int $mainAssignmentParentID * * @return array An array with operation status, always true */ static public function updateMainAssignment( $mainAssignmentID, $objectID, $mainAssignmentParentID ) { eZContentObjectTreeNode::updateMainNodeID( $mainAssignmentID, $objectID, false, $mainAssignmentParentID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Updates an contentobject's initial language * * @param int $objectID * @param int $newInitialLanguageID * * @return array An array with operation status, always true */ static public function updateInitialLanguage( $objectID, $newInitialLanguageID ) { $object = eZContentObject::fetch( $objectID ); $language = eZContentLanguage::fetch( $newInitialLanguageID ); if ( $language and !$language->attribute( 'disabled' ) ) { $object->setAttribute( 'initial_language_id', $newInitialLanguageID ); $objectName = $object->name( false, $language->attribute( 'locale' ) ); $object->setAttribute( 'name', $objectName ); $object->store(); if ( $object->isAlwaysAvailable() ) { $object->setAlwaysAvailableLanguageID( $newInitialLanguageID ); } $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->updateSubTreePath(); } } eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Set the always available flag for a content object * * @param int $objectID * @param int $newAlwaysAvailable * @return array An array with operation status, always true */ static public function updateAlwaysAvailable( $objectID, $newAlwaysAvailable ) { $object = eZContentObject::fetch( $objectID ); $change = false; if ( $object->isAlwaysAvailable() & $newAlwaysAvailable == false ) { $object->setAlwaysAvailableLanguageID( false ); $change = true; } else if ( !$object->isAlwaysAvailable() & $newAlwaysAvailable == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); $change = true; } if ( $change ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } return array( 'status' => true ); } /** * Removes a translation for a contentobject * * @param int $objectID * @param array * @return array An array with operation status, always true */ static public function removeTranslation( $objectID, $languageIDArray ) { $object = eZContentObject::fetch( $objectID ); foreach( $languageIDArray as $languageID ) { if ( !$object->removeTranslation( $languageID ) ) { eZDebug::writeError( "Object with id $objectID: cannot remove the translation with language id $languageID!", __METHOD__ ); } } eZContentOperationCollection::registerSearchObject( $objectID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Update a contentobject's state * * @param int $objectID * @param int $selectedStateIDList * * @return array An array with operation status, always true */ static public function updateObjectState( $objectID, $selectedStateIDList ) { $object = eZContentObject::fetch( $objectID ); // we don't need to re-assign states the object currently already has assigned $currentStateIDArray = $object->attribute( 'state_id_array' ); $selectedStateIDList = array_diff( $selectedStateIDList, $currentStateIDArray ); // filter out any states the current user is not allowed to assign $canAssignStateIDList = $object->attribute( 'allowed_assign_state_id_list' ); $selectedStateIDList = array_intersect( $selectedStateIDList, $canAssignStateIDList ); foreach ( $selectedStateIDList as $selectedStateID ) { $state = eZContentObjectState::fetchById( $selectedStateID ); $object->assignState( $state ); } eZAudit::writeAudit( 'state-assign', array( 'Content object ID' => $object->attribute( 'id' ), 'Content object name' => $object->attribute( 'name' ), 'Selected State ID Array' => implode( ', ' , $selectedStateIDList ), 'Comment' => 'Updated states of the current object: eZContentOperationCollection::updateObjectState()' ) ); //call appropriate method from search engine eZSearch::updateObjectState($objectID, $selectedStateIDList); // Triggering content/state/assign event for persistence cache purge ezpEvent::getInstance()->notify( 'content/state/assign', array( $objectID, $selectedStateIDList ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Executes the pre-publish trigger for this object, and handles * specific return statuses from the workflow * * @param int $objectID Object ID * @param int $version Version number * * @since 4.2 */ static public function executePrePublishTrigger( $objectID, $version ) { } /** * Creates a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function createFeedForNode( $nodeID ) { $hasExport = eZRSSFunctionCollection::hasExportByNode( $nodeID ); if ( isset( $hasExport['result'] ) && $hasExport['result'] ) { eZDebug::writeError( 'There is already a rss/atom export feed for this node: ' . $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); $currentClassIdentifier = $node->attribute( 'class_identifier' ); $config = eZINI::instance( 'site.ini' ); $feedItemClasses = $config->variable( 'RSSSettings', 'DefaultFeedItemClasses' ); if ( !$feedItemClasses || !isset( $feedItemClasses[ $currentClassIdentifier ] ) ) { eZDebug::writeError( "EnableRSS: content class $currentClassIdentifier is not defined in site.ini[RSSSettings]DefaultFeedItemClasses[<class_id>].", __METHOD__ ); return array( 'status' => false ); } $object = $node->object(); $objectID = $object->attribute('id'); $currentUserID = eZUser::currentUserID(); $rssExportItems = array(); $db = eZDB::instance(); $db->begin(); $rssExport = eZRSSExport::create( $currentUserID ); $rssExport->setAttribute( 'access_url', 'rss_feed_' . $nodeID ); $rssExport->setAttribute( 'node_id', $nodeID ); $rssExport->setAttribute( 'main_node_only', '1' ); $rssExport->setAttribute( 'number_of_objects', $config->variable( 'RSSSettings', 'NumberOfObjectsDefault' ) ); $rssExport->setAttribute( 'rss_version', $config->variable( 'RSSSettings', 'DefaultVersion' ) ); $rssExport->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExport->setAttribute( 'title', $object->name() ); $rssExport->store(); $rssExportID = $rssExport->attribute( 'id' ); foreach( explode( ';', $feedItemClasses[$currentClassIdentifier] ) as $classIdentifier ) { $iniSection = 'RSSSettings_' . $classIdentifier; if ( $config->hasVariable( $iniSection, 'FeedObjectAttributeMap' ) ) { $feedObjectAttributeMap = $config->variable( $iniSection, 'FeedObjectAttributeMap' ); $subNodesMap = $config->hasVariable( $iniSection, 'Subnodes' ) ? $config->variable( $iniSection, 'Subnodes' ) : array(); $rssExportItem = eZRSSExportItem::create( $rssExportID ); $rssExportItem->setAttribute( 'class_id', eZContentObjectTreeNode::classIDByIdentifier( $classIdentifier ) ); $rssExportItem->setAttribute( 'title', $feedObjectAttributeMap['title'] ); if ( isset( $feedObjectAttributeMap['description'] ) ) $rssExportItem->setAttribute( 'description', $feedObjectAttributeMap['description'] ); if ( isset( $feedObjectAttributeMap['category'] ) ) $rssExportItem->setAttribute( 'category', $feedObjectAttributeMap['category'] ); if ( isset( $feedObjectAttributeMap['enclosure'] ) ) $rssExportItem->setAttribute( 'enclosure', $feedObjectAttributeMap['enclosure'] ); $rssExportItem->setAttribute( 'source_node_id', $nodeID ); $rssExportItem->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExportItem->setAttribute( 'subnodes', isset( $subNodesMap[$currentClassIdentifier] ) && $subNodesMap[$currentClassIdentifier] === 'true' ); $rssExportItem->store(); } else { eZDebug::writeError( "site.ini[$iniSection]Source[] setting is not defined.", __METHOD__ ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Removes a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function removeFeedForNode( $nodeID ) { $rssExport = eZPersistentObject::fetchObject( eZRSSExport::definition(), null, array( 'node_id' => $nodeID, 'status' => eZRSSExport::STATUS_VALID ), true ); if ( !$rssExport instanceof eZRSSExport ) { eZDebug::writeError( 'DisableRSS: There is no rss/atom feeds left to delete for this node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { eZDebug::writeError( 'DisableRSS: Could not fetch node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $objectID = $node->attribute('contentobject_id'); $rssExport->removeThis(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Sends the published object/version for publishing to the queue * Used by the content/publish operation * @param int $objectId * @param int $version * * @return array( status => int ) * @since 4.5 */ public static function sendToPublishingQueue( $objectId, $version ) { $behaviour = ezpContentPublishingBehaviour::getBehaviour(); if ( $behaviour->disableAsynchronousPublishing ) $asyncEnabled = false; else $asyncEnabled = ( eZINI::instance( 'content.ini' )->variable( 'PublishingSettings', 'AsynchronousPublishing' ) == 'enabled' ); $accepted = true; if ( $asyncEnabled === true ) { // Filter handlers $ini = eZINI::instance( 'content.ini' ); $filterHandlerClasses = $ini->variable( 'PublishingSettings', 'AsynchronousPublishingFilters' ); if ( count( $filterHandlerClasses ) ) { $versionObject = eZContentObjectVersion::fetchVersion( $version, $objectId ); foreach( $filterHandlerClasses as $filterHandlerClass ) { if ( !class_exists( $filterHandlerClass ) ) { eZDebug::writeError( "Unknown asynchronous publishing filter handler class '$filterHandlerClass'", __METHOD__ ); continue; } $handler = new $filterHandlerClass( $versionObject ); if ( !( $handler instanceof ezpAsynchronousPublishingFilterInterface ) ) { eZDebug::writeError( "Asynchronous publishing filter handler class '$filterHandlerClass' does not implement ezpAsynchronousPublishingFilterInterface", __METHOD__ ); continue; } $accepted = $handler->accept(); if ( !$accepted ) { eZDebugSetting::writeDebug( "Object #{$objectId}/{$version} was excluded from asynchronous publishing by $filterHandlerClass", __METHOD__ ); break; } } } unset( $filterHandlerClasses, $handler ); } if ( $asyncEnabled && $accepted ) { // if the object is already in the process queue, we move ahead // this test should NOT be necessary since http://issues.ez.no/17840 was fixed if ( ezpContentPublishingQueue::isQueued( $objectId, $version ) ) { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } // the object isn't in the process queue, this means this is the first time we execute this method // the object must be queued else { ezpContentPublishingQueue::add( $objectId, $version ); return array( 'status' => eZModuleOperationInfo::STATUS_HALTED, 'redirect_url' => "content/queued/{$objectId}/{$version}" ); } } else { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } } } ?>
pbek/ezpublish-legacy
kernel/content/ezcontentoperationcollection.php
PHP
gpl-2.0
64,392
<?php /** * AliPay IPN Handler. * * Copyright: © 2009-2011 * {@link http://www.websharks-inc.com/ WebSharks, Inc.} * (coded in the USA) * * This WordPress plugin (s2Member Pro) is comprised of two parts: * * o (1) Its PHP code is licensed under the GPL license, as is WordPress. * You should have received a copy of the GNU General Public License, * along with this software. In the main directory, see: /licensing/ * If not, see: {@link http://www.gnu.org/licenses/}. * * o (2) All other parts of (s2Member Pro); including, but not limited to: * the CSS code, some JavaScript code, images, and design; * are licensed according to the license purchased. * See: {@link http://www.s2member.com/prices/} * * Unless you have our prior written consent, you must NOT directly or indirectly license, * sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module; * or make an offer to do any of these things. All of these things are strictly * prohibited with part (2) of the s2Member Pro Module. * * Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com * (i.e. new features, bug fixes, updates, improvements); along with full access * to our video tutorial library: {@link http://www.s2member.com/videos/} * * @package s2Member\AliPay * @since 1.5 */ if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"])) exit("Do not access this file directly."); if (!class_exists ("c_ws_plugin__s2member_pro_alipay_notify")) { /** * AliPay IPN Handler. * * @package s2Member\AliPay * @since 1.5 */ class c_ws_plugin__s2member_pro_alipay_notify { /** * Handles AliPay IPN URL processing. * * @package s2Member\AliPay * @since 1.5 * * @attaches-to ``add_action("init");`` * * @return null|inner Return-value of inner routine. */ public static function alipay_notify () { if (!empty($_POST["notify_type"]) && preg_match ("/^trade_status_sync$/i", $_POST["notify_type"])) { return c_ws_plugin__s2member_pro_alipay_notify_in::alipay_notify (); } } } } ?>
kydrenw/boca
wp-content/plugins/s2member-pro/includes/classes/gateways/alipay/alipay-notify.inc.php
PHP
gpl-2.0
2,106
<?php /** * Preview class. * * @package WPForms * @author WPForms * @since 1.1.5 * @license GPL-2.0+ * @copyright Copyright (c) 2016, WPForms LLC */ class WPForms_Preview { /** * Primary class constructor. * * @since 1.1.5 */ public function __construct() { // Maybe load a preview page add_action( 'init', array( $this, 'init' ) ); // Hide preview page from admin add_action( 'pre_get_posts', array( $this, 'form_preview_hide' ) ); } /** * Determing if the user should see a preview page, if so, party on. * * @since 1.1.5 */ public function init() { // Check for preview param with allowed values if ( empty( $_GET['wpforms_preview'] ) || !in_array( $_GET['wpforms_preview'], array( 'print', 'form' ) ) ) { return; } // Check for authenticated user with correct capabilities if ( !is_user_logged_in() || !current_user_can( apply_filters( 'wpforms_manage_cap', 'manage_options' ) ) ) { return; } // Print preview if ( 'print' == $_GET['wpforms_preview'] && !empty( $_GET['entry_id'] ) ) { $this->print_preview(); } // Form preview if ( 'form' == $_GET['wpforms_preview'] && !empty( $_GET['form_id'] ) ) { $this->form_preview(); } } /** * Print Preview. * * @since 1.1.5 */ public function print_preview() { // Load entry details $entry = wpforms()->entry->get( absint( $_GET['entry_id'] ) ); // Double check that we found a real entry if ( ! $entry || empty( $entry ) ) { return; } // Get form details $form_data = wpforms()->form->get( $entry->form_id, array( 'content_only' => true ) ); // Double check that we found a valid entry if ( ! $form_data || empty( $form_data ) ) { return; } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>WPForms Print Preview - <?php echo ucfirst( sanitize_text_field( $form_data['settings']['form_title'] ) ); ?> </title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="noindex,nofollow,noarchive"> <link rel="stylesheet" href="<?php echo includes_url('css/buttons.min.css'); ?>" type="text/css"> <link rel="stylesheet" href="<?php echo WPFORMS_PLUGIN_URL; ?>assets/css/wpforms-preview.css" type="text/css"> <script type="text/javascript" src="<?php echo includes_url('js/jquery/jquery.js'); ?>"></script> <script type="text/javascript" src="<?php echo WPFORMS_PLUGIN_URL; ?>assets/js/wpforms-preview.js"></script> </head> <body class="wp-core-ui"> <div class="wpforms-preview" id="print"> <h1> <?php echo sanitize_text_field( $form_data['settings']['form_title'] ); ?> <span> - <?php printf( __( 'Entry #%d', 'wpforms' ), absint( $entry->entry_id ) ); ?></span> <div class="buttons"> <a href="" class="button button-secondary close-window">Close</a> <a href="" class="button button-primary print">Print</a> </div> </h1> <?php $fields = apply_filters( 'wpforms_entry_single_data', wpforms_decode( $entry->fields ), $entry, $form_data ); if ( empty( $fields ) ) { // Whoops, no fields! This shouldn't happen under normal use cases. echo '<p class="no-fields">' . __( 'This entry does not have any fields', 'wpforms' ) . '</p>'; } else { echo '<div class="fields">'; // Display the fields and their values foreach ( $fields as $key => $field ) { $field_value = apply_filters( 'wpforms_html_field_value', wp_strip_all_tags( $field['value'] ), $field, $form_data ); $field_class = sanitize_html_class( 'wpforms-field-' . $field['type'] ); $field_class .= empty( $field_value ) ? ' empty' : ''; echo '<div class="wpforms-entry-field ' . $field_class . '">'; // Field name echo '<p class="wpforms-entry-field-name">'; echo !empty( $field['name'] ) ? wp_strip_all_tags( $field['name'] ) : sprintf( __( 'Field ID #%d', 'wpforms' ), absint( $field['id'] ) ); echo '</p>'; // Field value echo '<p class="wpforms-entry-field-value">'; echo !empty( $field_value ) ? nl2br( make_clickable( $field_value ) ) : __( 'Empty', 'wpforms' ); echo '</p>'; echo '</div>'; } echo '</div>'; } ?> </div><!-- .wrap --> <p class="site"><a href="<?php echo home_url(); ?>"><?php echo get_bloginfo( 'name'); ?></a></p> </body> <?php exit(); } /** * Check if preview page exists, if not create it. * * @since 1.1.9 */ public function form_preview_check() { if ( !is_admin() ) return; // Verify page exits $preview = get_option( 'wpforms_preview_page' ); if ( $preview ) { $preview_page = get_post( $preview ); // Check to see if the visibility has been changed, if so correct it if ( !empty( $preview_page ) && 'private' != $preview_page->post_status ) { $preview_page->post_status = 'private'; wp_update_post( $preview_page ); return; } elseif ( !empty( $preview_page ) ) { return; } } // Create the custom preview page $content = '<p>' . __( 'This is the WPForms preview page. All your form previews will be handled on this page.', 'wpforms' ) . '</p>'; $content .= '<p>' . __( 'The page is set to private, so it is not publically accessible. Please do not delete this page :) .', 'wpforms' ) . '</p>'; $args = array( 'post_type' => 'page', 'post_name' => 'wpforms-preview', 'post_author' => 1, 'post_title' => __( 'WPForms Preview', 'wpforms' ), 'post_status' => 'private', 'post_content' => $content, 'comment_status' => 'closed' ); $id = wp_insert_post( $args ); if ( $id ) { update_option( 'wpforms_preview_page', $id ); } } /** * Preview page URL. * * @since 1.1.9 * @param int $form_id * @return string */ public function form_preview_url( $form_id ) { $id = get_option( 'wpforms_preview_page' ); if ( ! $id ) { return home_url(); } $url = get_permalink( $id ); if ( ! $url ) { return home_url(); } return add_query_arg( array( 'wpforms_preview' => 'form', 'form_id' => absint( $form_id ) ), $url ); } /** * Fires when form preview might be detected. * * @since 1.1.9 */ public function form_preview() { add_filter( 'the_posts', array( $this, 'form_preview_query' ), 10, 2 ); } /** * Tweak the page content for form preview page requests. * * @since 1.1.9 * @param array $posts * @param object $query * @return array */ public function form_preview_query( $posts, $query ) { // One last cap check, just for fun. if ( !is_user_logged_in() || !current_user_can( apply_filters( 'wpforms_manage_cap', 'manage_options' ) ) ) { return $posts; } // Only target main query if ( ! $query->is_main_query() ) { return $posts; } // If our queried object ID does not match the preview page ID, return early. $preview_id = absint( get_option( 'wpforms_preview_page' ) ); $queried = $query->get_queried_object_id(); if ( $queried && $queried != $preview_id && isset( $query->query_vars['page_id'] ) && $preview_id != $query->query_vars['page_id'] ) { return $posts; } // Get the form details $form = wpforms()->form->get( absint( $_GET['form_id'] ), array( 'content_only' => true ) ); if ( ! $form || empty( $form ) ) { return $posts; } // Customize the page content $title = sanitize_text_field( $form['settings']['form_title'] ); $shortcode = '[wpforms id="' . absint( $form['id'] ) . '"]'; $content = __( 'This is a preview of your form. This page not publically accessible.', 'wpforms' ); if ( !empty( $_GET['new_window'] ) ) { $content .= ' <a href="javascript:window.close();">' . __( 'Close this window', 'wpforms' ) . '.</a>'; } $posts[0]->post_title = $title . __( ' Preview', 'wpforms' ); $posts[0]->post_content = $content . $shortcode; $posts[0]->post_status = 'public'; return $posts; } /** * Hide the preview page from admin * * @since 1.2.3 * @param object $query */ function form_preview_hide( $query ) { if( $query->is_main_query() && is_admin() && isset( $query->query_vars['post_type'] ) && 'page' == $query->query_vars['post_type'] ) { $wpforms_preview = intval( get_option( 'wpforms_preview_page' ) ); if( $wpforms_preview ) { $exclude = $query->query_vars['post__not_in']; $exclude[] = $wpforms_preview; $query->set( 'post__not_in', $exclude ); } } } }
kimcarey/beeline-web
wp-content/plugins/wpforms-lite/includes/class-preview.php
PHP
gpl-2.0
8,541
package raw import ( "fmt" "../../platforms/common" ) type FieldMacros struct {} func (FieldMacros) DecodeDW0() { macro := common.GetMacro() // Do not decode, print as is. macro.Add(fmt.Sprintf("0x%0.8x", macro.Register(common.PAD_CFG_DW0).ValueGet())) } func (FieldMacros) DecodeDW1() { macro := common.GetMacro() // Do not decode, print as is. macro.Add(fmt.Sprintf("0x%0.8x", macro.Register(common.PAD_CFG_DW1).ValueGet())) } // GenerateString - generates the entire string of bitfield macros. func (bitfields FieldMacros) GenerateString() { macro := common.GetMacro() macro.Add("_PAD_CFG_STRUCT(").Id().Add(", ") bitfields.DecodeDW0() macro.Add(", ") bitfields.DecodeDW1() macro.Add("),") }
felixsinger/coreboot
util/intelp2m/fields/raw/raw.go
GO
gpl-2.0
714
#ifndef __SOUND_PCM_H #define __SOUND_PCM_H /* * Digital Audio (PCM) abstract layer * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * Abramo Bagnara <abramo@alsa-project.org> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sound/asound.h> #include <sound/memalloc.h> #include <sound/minors.h> #include <linux/poll.h> #include <linux/mm.h> #include <linux/bitops.h> #include <linux/pm_qos.h> #define snd_pcm_substream_chip(substream) ((substream)->private_data) #define snd_pcm_chip(pcm) ((pcm)->private_data) #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) #include <sound/pcm_oss.h> #endif /* * Hardware (lowlevel) section */ struct snd_pcm_hardware { unsigned int info; /* SNDRV_PCM_INFO_* */ u64 formats; /* SNDRV_PCM_FMTBIT_* */ unsigned int rates; /* SNDRV_PCM_RATE_* */ unsigned int rate_min; /* min rate */ unsigned int rate_max; /* max rate */ unsigned int channels_min; /* min channels */ unsigned int channels_max; /* max channels */ size_t buffer_bytes_max; /* max buffer size */ size_t period_bytes_min; /* min period size */ size_t period_bytes_max; /* max period size */ unsigned int periods_min; /* min # of periods */ unsigned int periods_max; /* max # of periods */ size_t fifo_size; /* fifo size in bytes */ }; struct snd_pcm_substream; struct snd_pcm_ops { int (*open)(struct snd_pcm_substream *substream); int (*close)(struct snd_pcm_substream *substream); int (*ioctl)(struct snd_pcm_substream * substream, unsigned int cmd, void *arg); int (*hw_params)(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params); int (*hw_free)(struct snd_pcm_substream *substream); int (*prepare)(struct snd_pcm_substream *substream); int (*trigger)(struct snd_pcm_substream *substream, int cmd); snd_pcm_uframes_t (*pointer)(struct snd_pcm_substream *substream); int (*wall_clock)(struct snd_pcm_substream *substream, struct timespec *audio_ts); int (*copy)(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void __user *buf, snd_pcm_uframes_t count); int (*silence)(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, snd_pcm_uframes_t count); struct page *(*page)(struct snd_pcm_substream *substream, unsigned long offset); int (*mmap)(struct snd_pcm_substream *substream, struct vm_area_struct *vma); int (*ack)(struct snd_pcm_substream *substream); }; /* * */ #if defined(CONFIG_SND_DYNAMIC_MINORS) #define SNDRV_PCM_DEVICES (SNDRV_OS_MINORS-2) #else #define SNDRV_PCM_DEVICES 8 #endif #define SNDRV_PCM_IOCTL1_FALSE ((void *)0) #define SNDRV_PCM_IOCTL1_TRUE ((void *)1) #define SNDRV_PCM_IOCTL1_RESET 0 #define SNDRV_PCM_IOCTL1_INFO 1 #define SNDRV_PCM_IOCTL1_CHANNEL_INFO 2 #define SNDRV_PCM_IOCTL1_GSTATE 3 #define SNDRV_PCM_IOCTL1_FIFO_SIZE 4 #define SNDRV_PCM_TRIGGER_STOP 0 #define SNDRV_PCM_TRIGGER_START 1 #define SNDRV_PCM_TRIGGER_PAUSE_PUSH 3 #define SNDRV_PCM_TRIGGER_PAUSE_RELEASE 4 #define SNDRV_PCM_TRIGGER_SUSPEND 5 #define SNDRV_PCM_TRIGGER_RESUME 6 #define SNDRV_PCM_POS_XRUN ((snd_pcm_uframes_t)-1) /* If you change this don't forget to change rates[] table in pcm_native.c */ #define SNDRV_PCM_RATE_5512 (1<<0) /* 5512Hz */ #define SNDRV_PCM_RATE_8000 (1<<1) /* 8000Hz */ #define SNDRV_PCM_RATE_11025 (1<<2) /* 11025Hz */ #define SNDRV_PCM_RATE_16000 (1<<3) /* 16000Hz */ #define SNDRV_PCM_RATE_22050 (1<<4) /* 22050Hz */ #define SNDRV_PCM_RATE_32000 (1<<5) /* 32000Hz */ #define SNDRV_PCM_RATE_44100 (1<<6) /* 44100Hz */ #define SNDRV_PCM_RATE_48000 (1<<7) /* 48000Hz */ #define SNDRV_PCM_RATE_64000 (1<<8) /* 64000Hz */ #define SNDRV_PCM_RATE_88200 (1<<9) /* 88200Hz */ #define SNDRV_PCM_RATE_96000 (1<<10) /* 96000Hz */ #define SNDRV_PCM_RATE_176400 (1<<11) /* 176400Hz */ #define SNDRV_PCM_RATE_192000 (1<<12) /* 192000Hz */ #define SNDRV_PCM_RATE_352800 (1<<13) /* 352800Hz */ #define SNDRV_PCM_RATE_384000 (1<<14) /* 384000Hz */ #define SNDRV_PCM_RATE_CONTINUOUS (1<<30) /* continuous range */ #define SNDRV_PCM_RATE_KNOT (1<<31) /* supports more non-continuos rates */ #define SNDRV_PCM_RATE_8000_44100 (SNDRV_PCM_RATE_8000|SNDRV_PCM_RATE_11025|\ SNDRV_PCM_RATE_16000|SNDRV_PCM_RATE_22050|\ SNDRV_PCM_RATE_32000|SNDRV_PCM_RATE_44100) #define SNDRV_PCM_RATE_8000_48000 (SNDRV_PCM_RATE_8000_44100|SNDRV_PCM_RATE_48000) #define SNDRV_PCM_RATE_8000_96000 (SNDRV_PCM_RATE_8000_48000|SNDRV_PCM_RATE_64000|\ SNDRV_PCM_RATE_88200|SNDRV_PCM_RATE_96000) #define SNDRV_PCM_RATE_8000_192000 (SNDRV_PCM_RATE_8000_96000|SNDRV_PCM_RATE_176400|\ SNDRV_PCM_RATE_192000) #define SNDRV_PCM_RATE_8000_384000 (SNDRV_PCM_RATE_8000_192000|\ SNDRV_PCM_RATE_352800|\ SNDRV_PCM_RATE_384000) #define _SNDRV_PCM_FMTBIT(fmt) (1ULL << (__force int)SNDRV_PCM_FORMAT_##fmt) #define SNDRV_PCM_FMTBIT_S8 _SNDRV_PCM_FMTBIT(S8) #define SNDRV_PCM_FMTBIT_U8 _SNDRV_PCM_FMTBIT(U8) #define SNDRV_PCM_FMTBIT_S16_LE _SNDRV_PCM_FMTBIT(S16_LE) #define SNDRV_PCM_FMTBIT_S16_BE _SNDRV_PCM_FMTBIT(S16_BE) #define SNDRV_PCM_FMTBIT_U16_LE _SNDRV_PCM_FMTBIT(U16_LE) #define SNDRV_PCM_FMTBIT_U16_BE _SNDRV_PCM_FMTBIT(U16_BE) #define SNDRV_PCM_FMTBIT_S24_LE _SNDRV_PCM_FMTBIT(S24_LE) #define SNDRV_PCM_FMTBIT_S24_BE _SNDRV_PCM_FMTBIT(S24_BE) #define SNDRV_PCM_FMTBIT_U24_LE _SNDRV_PCM_FMTBIT(U24_LE) #define SNDRV_PCM_FMTBIT_U24_BE _SNDRV_PCM_FMTBIT(U24_BE) #define SNDRV_PCM_FMTBIT_S32_LE _SNDRV_PCM_FMTBIT(S32_LE) #define SNDRV_PCM_FMTBIT_S32_BE _SNDRV_PCM_FMTBIT(S32_BE) #define SNDRV_PCM_FMTBIT_U32_LE _SNDRV_PCM_FMTBIT(U32_LE) #define SNDRV_PCM_FMTBIT_U32_BE _SNDRV_PCM_FMTBIT(U32_BE) #define SNDRV_PCM_FMTBIT_FLOAT_LE _SNDRV_PCM_FMTBIT(FLOAT_LE) #define SNDRV_PCM_FMTBIT_FLOAT_BE _SNDRV_PCM_FMTBIT(FLOAT_BE) #define SNDRV_PCM_FMTBIT_FLOAT64_LE _SNDRV_PCM_FMTBIT(FLOAT64_LE) #define SNDRV_PCM_FMTBIT_FLOAT64_BE _SNDRV_PCM_FMTBIT(FLOAT64_BE) #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE _SNDRV_PCM_FMTBIT(IEC958_SUBFRAME_LE) #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_BE _SNDRV_PCM_FMTBIT(IEC958_SUBFRAME_BE) #define SNDRV_PCM_FMTBIT_MU_LAW _SNDRV_PCM_FMTBIT(MU_LAW) #define SNDRV_PCM_FMTBIT_A_LAW _SNDRV_PCM_FMTBIT(A_LAW) #define SNDRV_PCM_FMTBIT_IMA_ADPCM _SNDRV_PCM_FMTBIT(IMA_ADPCM) #define SNDRV_PCM_FMTBIT_MPEG _SNDRV_PCM_FMTBIT(MPEG) #define SNDRV_PCM_FMTBIT_GSM _SNDRV_PCM_FMTBIT(GSM) #define SNDRV_PCM_FMTBIT_SPECIAL _SNDRV_PCM_FMTBIT(SPECIAL) #define SNDRV_PCM_FMTBIT_S24_3LE _SNDRV_PCM_FMTBIT(S24_3LE) #define SNDRV_PCM_FMTBIT_U24_3LE _SNDRV_PCM_FMTBIT(U24_3LE) #define SNDRV_PCM_FMTBIT_S24_3BE _SNDRV_PCM_FMTBIT(S24_3BE) #define SNDRV_PCM_FMTBIT_U24_3BE _SNDRV_PCM_FMTBIT(U24_3BE) #define SNDRV_PCM_FMTBIT_S20_3LE _SNDRV_PCM_FMTBIT(S20_3LE) #define SNDRV_PCM_FMTBIT_U20_3LE _SNDRV_PCM_FMTBIT(U20_3LE) #define SNDRV_PCM_FMTBIT_S20_3BE _SNDRV_PCM_FMTBIT(S20_3BE) #define SNDRV_PCM_FMTBIT_U20_3BE _SNDRV_PCM_FMTBIT(U20_3BE) #define SNDRV_PCM_FMTBIT_S18_3LE _SNDRV_PCM_FMTBIT(S18_3LE) #define SNDRV_PCM_FMTBIT_U18_3LE _SNDRV_PCM_FMTBIT(U18_3LE) #define SNDRV_PCM_FMTBIT_S18_3BE _SNDRV_PCM_FMTBIT(S18_3BE) #define SNDRV_PCM_FMTBIT_U18_3BE _SNDRV_PCM_FMTBIT(U18_3BE) #define SNDRV_PCM_FMTBIT_G723_24 _SNDRV_PCM_FMTBIT(G723_24) #define SNDRV_PCM_FMTBIT_G723_24_1B _SNDRV_PCM_FMTBIT(G723_24_1B) #define SNDRV_PCM_FMTBIT_G723_40 _SNDRV_PCM_FMTBIT(G723_40) #define SNDRV_PCM_FMTBIT_G723_40_1B _SNDRV_PCM_FMTBIT(G723_40_1B) #define SNDRV_PCM_FMTBIT_DSD_U8 _SNDRV_PCM_FMTBIT(DSD_U8) #define SNDRV_PCM_FMTBIT_DSD_U16_LE _SNDRV_PCM_FMTBIT(DSD_U16_LE) #define SNDRV_PCM_FMTBIT_DSD_U32_LE _SNDRV_PCM_FMTBIT(DSD_U32_LE) #define SNDRV_PCM_FMTBIT_DSD_U16_BE _SNDRV_PCM_FMTBIT(DSD_U16_BE) #define SNDRV_PCM_FMTBIT_DSD_U32_BE _SNDRV_PCM_FMTBIT(DSD_U32_BE) #ifdef SNDRV_LITTLE_ENDIAN #define SNDRV_PCM_FMTBIT_S16 SNDRV_PCM_FMTBIT_S16_LE #define SNDRV_PCM_FMTBIT_U16 SNDRV_PCM_FMTBIT_U16_LE #define SNDRV_PCM_FMTBIT_S24 SNDRV_PCM_FMTBIT_S24_LE #define SNDRV_PCM_FMTBIT_U24 SNDRV_PCM_FMTBIT_U24_LE #define SNDRV_PCM_FMTBIT_S32 SNDRV_PCM_FMTBIT_S32_LE #define SNDRV_PCM_FMTBIT_U32 SNDRV_PCM_FMTBIT_U32_LE #define SNDRV_PCM_FMTBIT_FLOAT SNDRV_PCM_FMTBIT_FLOAT_LE #define SNDRV_PCM_FMTBIT_FLOAT64 SNDRV_PCM_FMTBIT_FLOAT64_LE #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_LE //#define SNDRV_PCM_FMTBIT_DSD_U16 SNRV_PCM_FMTBIT_DSD_U16_BE //#define SNDRV_PCM_FMTBIT_DSD_U32 SNRV_PCM_FMTBIT_DSD_U32_BE #endif #ifdef SNDRV_BIG_ENDIAN #define SNDRV_PCM_FMTBIT_S16 SNDRV_PCM_FMTBIT_S16_BE #define SNDRV_PCM_FMTBIT_U16 SNDRV_PCM_FMTBIT_U16_BE #define SNDRV_PCM_FMTBIT_S24 SNDRV_PCM_FMTBIT_S24_BE #define SNDRV_PCM_FMTBIT_U24 SNDRV_PCM_FMTBIT_U24_BE #define SNDRV_PCM_FMTBIT_S32 SNDRV_PCM_FMTBIT_S32_BE #define SNDRV_PCM_FMTBIT_U32 SNDRV_PCM_FMTBIT_U32_BE #define SNDRV_PCM_FMTBIT_FLOAT SNDRV_PCM_FMTBIT_FLOAT_BE #define SNDRV_PCM_FMTBIT_FLOAT64 SNDRV_PCM_FMTBIT_FLOAT64_BE #define SNDRV_PCM_FMTBIT_IEC958_SUBFRAME SNDRV_PCM_FMTBIT_IEC958_SUBFRAME_BE #endif struct snd_pcm_file { struct snd_pcm_substream *substream; int no_compat_mmap; }; struct snd_pcm_hw_rule; typedef int (*snd_pcm_hw_rule_func_t)(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule); struct snd_pcm_hw_rule { unsigned int cond; snd_pcm_hw_rule_func_t func; int var; int deps[4]; void *private; }; struct snd_pcm_hw_constraints { struct snd_mask masks[SNDRV_PCM_HW_PARAM_LAST_MASK - SNDRV_PCM_HW_PARAM_FIRST_MASK + 1]; struct snd_interval intervals[SNDRV_PCM_HW_PARAM_LAST_INTERVAL - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL + 1]; unsigned int rules_num; unsigned int rules_all; struct snd_pcm_hw_rule *rules; }; static inline struct snd_mask *constrs_mask(struct snd_pcm_hw_constraints *constrs, snd_pcm_hw_param_t var) { return &constrs->masks[var - SNDRV_PCM_HW_PARAM_FIRST_MASK]; } static inline struct snd_interval *constrs_interval(struct snd_pcm_hw_constraints *constrs, snd_pcm_hw_param_t var) { return &constrs->intervals[var - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]; } struct snd_ratnum { unsigned int num; unsigned int den_min, den_max, den_step; }; struct snd_ratden { unsigned int num_min, num_max, num_step; unsigned int den; }; struct snd_pcm_hw_constraint_ratnums { int nrats; struct snd_ratnum *rats; }; struct snd_pcm_hw_constraint_ratdens { int nrats; struct snd_ratden *rats; }; struct snd_pcm_hw_constraint_list { unsigned int count; const unsigned int *list; unsigned int mask; }; struct snd_pcm_hwptr_log; struct snd_pcm_runtime { /* -- Status -- */ struct snd_pcm_substream *trigger_master; struct timespec trigger_tstamp; /* trigger timestamp */ int overrange; snd_pcm_uframes_t avail_max; snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */ snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time */ unsigned long hw_ptr_jiffies; /* Time when hw_ptr is updated */ unsigned long hw_ptr_buffer_jiffies; /* buffer time in jiffies */ snd_pcm_sframes_t delay; /* extra delay; typically FIFO size */ u64 hw_ptr_wrap; /* offset for hw_ptr due to boundary wrap-around */ /* -- HW params -- */ snd_pcm_access_t access; /* access mode */ snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */ snd_pcm_subformat_t subformat; /* subformat */ unsigned int rate; /* rate in Hz */ unsigned int channels; /* channels */ snd_pcm_uframes_t period_size; /* period size */ unsigned int periods; /* periods */ snd_pcm_uframes_t buffer_size; /* buffer size */ snd_pcm_uframes_t min_align; /* Min alignment for the format */ size_t byte_align; unsigned int frame_bits; unsigned int sample_bits; unsigned int info; unsigned int rate_num; unsigned int rate_den; unsigned int no_period_wakeup: 1; /* -- SW params -- */ int tstamp_mode; /* mmap timestamp is updated */ unsigned int period_step; snd_pcm_uframes_t start_threshold; snd_pcm_uframes_t stop_threshold; snd_pcm_uframes_t silence_threshold; /* Silence filling happens when noise is nearest than this */ snd_pcm_uframes_t silence_size; /* Silence filling size */ snd_pcm_uframes_t boundary; /* pointers wrap point */ snd_pcm_uframes_t silence_start; /* starting pointer to silence area */ snd_pcm_uframes_t silence_filled; /* size filled with silence */ union snd_pcm_sync_id sync; /* hardware synchronization ID */ /* -- mmap -- */ struct snd_pcm_mmap_status *status; struct snd_pcm_mmap_control *control; /* -- locking / scheduling -- */ snd_pcm_uframes_t twake; /* do transfer (!poll) wakeup if non-zero */ wait_queue_head_t sleep; /* poll sleep */ wait_queue_head_t tsleep; /* transfer sleep */ struct fasync_struct *fasync; /* -- private section -- */ void *private_data; void (*private_free)(struct snd_pcm_runtime *runtime); /* -- hardware description -- */ struct snd_pcm_hardware hw; struct snd_pcm_hw_constraints hw_constraints; /* -- interrupt callbacks -- */ void (*transfer_ack_begin)(struct snd_pcm_substream *substream); void (*transfer_ack_end)(struct snd_pcm_substream *substream); /* -- timer -- */ unsigned int timer_resolution; /* timer resolution */ int tstamp_type; /* timestamp type */ /* -- DMA -- */ unsigned char *dma_area; /* DMA area */ dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */ size_t dma_bytes; /* size of DMA area */ struct snd_dma_buffer *dma_buffer_p; /* allocated buffer */ #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) /* -- OSS things -- */ struct snd_pcm_oss_runtime oss; #endif #ifdef CONFIG_SND_PCM_XRUN_DEBUG struct snd_pcm_hwptr_log *hwptr_log; #endif }; struct snd_pcm_group { /* keep linked substreams */ spinlock_t lock; struct list_head substreams; int count; }; struct pid; struct snd_pcm_substream { struct snd_pcm *pcm; struct snd_pcm_str *pstr; void *private_data; /* copied from pcm->private_data */ int number; char name[32]; /* substream name */ int stream; /* stream (direction) */ struct pm_qos_request latency_pm_qos_req; /* pm_qos request */ size_t buffer_bytes_max; /* limit ring buffer size */ struct snd_dma_buffer dma_buffer; size_t dma_max; /* -- hardware operations -- */ const struct snd_pcm_ops *ops; /* -- runtime information -- */ struct snd_pcm_runtime *runtime; /* -- timer section -- */ struct snd_timer *timer; /* timer */ unsigned timer_running: 1; /* time is running */ /* -- next substream -- */ struct snd_pcm_substream *next; /* -- linked substreams -- */ struct list_head link_list; /* linked list member */ struct snd_pcm_group self_group; /* fake group for non linked substream (with substream lock inside) */ struct snd_pcm_group *group; /* pointer to current group */ /* -- assigned files -- */ void *file; int ref_count; atomic_t mmap_count; unsigned int f_flags; void (*pcm_release)(struct snd_pcm_substream *); struct pid *pid; #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) /* -- OSS things -- */ struct snd_pcm_oss_substream oss; #endif #ifdef CONFIG_SND_VERBOSE_PROCFS struct snd_info_entry *proc_root; struct snd_info_entry *proc_info_entry; struct snd_info_entry *proc_hw_params_entry; struct snd_info_entry *proc_sw_params_entry; struct snd_info_entry *proc_status_entry; struct snd_info_entry *proc_prealloc_entry; struct snd_info_entry *proc_prealloc_max_entry; #endif /* misc flags */ unsigned int hw_opened: 1; }; #define SUBSTREAM_BUSY(substream) ((substream)->ref_count > 0) struct snd_pcm_str { int stream; /* stream (direction) */ struct snd_pcm *pcm; /* -- substreams -- */ unsigned int substream_count; unsigned int substream_opened; struct snd_pcm_substream *substream; #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) /* -- OSS things -- */ struct snd_pcm_oss_stream oss; #endif #ifdef CONFIG_SND_VERBOSE_PROCFS struct snd_info_entry *proc_root; struct snd_info_entry *proc_info_entry; #ifdef CONFIG_SND_PCM_XRUN_DEBUG unsigned int xrun_debug; /* 0 = disabled, 1 = verbose, 2 = stacktrace */ struct snd_info_entry *proc_xrun_debug_entry; #endif #endif struct snd_kcontrol *chmap_kctl; /* channel-mapping controls */ }; struct snd_pcm { struct snd_card *card; struct list_head list; int device; /* device number */ unsigned int info_flags; unsigned short dev_class; unsigned short dev_subclass; char id[64]; char name[80]; struct snd_pcm_str streams[2]; struct mutex open_mutex; wait_queue_head_t open_wait; void *private_data; void (*private_free) (struct snd_pcm *pcm); struct device *dev; /* actual hw device this belongs to */ bool internal; /* pcm is for internal use only */ #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE) struct snd_pcm_oss oss; #endif }; struct snd_pcm_notify { int (*n_register) (struct snd_pcm * pcm); int (*n_disconnect) (struct snd_pcm * pcm); int (*n_unregister) (struct snd_pcm * pcm); struct list_head list; }; /* * Registering */ extern const struct file_operations snd_pcm_f_ops[2]; int snd_pcm_new(struct snd_card *card, const char *id, int device, int playback_count, int capture_count, struct snd_pcm **rpcm); int snd_pcm_new_internal(struct snd_card *card, const char *id, int device, int playback_count, int capture_count, struct snd_pcm **rpcm); int snd_pcm_new_stream(struct snd_pcm *pcm, int stream, int substream_count); int snd_pcm_notify(struct snd_pcm_notify *notify, int nfree); /* * Native I/O */ extern rwlock_t snd_pcm_link_rwlock; int snd_pcm_info(struct snd_pcm_substream *substream, struct snd_pcm_info *info); int snd_pcm_info_user(struct snd_pcm_substream *substream, struct snd_pcm_info __user *info); int snd_pcm_status(struct snd_pcm_substream *substream, struct snd_pcm_status *status); int snd_pcm_start(struct snd_pcm_substream *substream); int snd_pcm_stop(struct snd_pcm_substream *substream, snd_pcm_state_t status); int snd_pcm_drain_done(struct snd_pcm_substream *substream); #ifdef CONFIG_PM int snd_pcm_suspend(struct snd_pcm_substream *substream); int snd_pcm_suspend_all(struct snd_pcm *pcm); #endif int snd_pcm_kernel_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg); int snd_pcm_open_substream(struct snd_pcm *pcm, int stream, struct file *file, struct snd_pcm_substream **rsubstream); void snd_pcm_release_substream(struct snd_pcm_substream *substream); int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream, struct file *file, struct snd_pcm_substream **rsubstream); void snd_pcm_detach_substream(struct snd_pcm_substream *substream); void snd_pcm_vma_notify_data(void *client, void *data); int snd_pcm_mmap_data(struct snd_pcm_substream *substream, struct file *file, struct vm_area_struct *area); #ifdef CONFIG_SND_DEBUG void snd_pcm_debug_name(struct snd_pcm_substream *substream, char *name, size_t len); #else static inline void snd_pcm_debug_name(struct snd_pcm_substream *substream, char *buf, size_t size) { *buf = 0; } #endif /* * PCM library */ static inline int snd_pcm_stream_linked(struct snd_pcm_substream *substream) { return substream->group != &substream->self_group; } static inline void snd_pcm_stream_lock(struct snd_pcm_substream *substream) { read_lock(&snd_pcm_link_rwlock); spin_lock(&substream->self_group.lock); } static inline void snd_pcm_stream_unlock(struct snd_pcm_substream *substream) { spin_unlock(&substream->self_group.lock); read_unlock(&snd_pcm_link_rwlock); } static inline void snd_pcm_stream_lock_irq(struct snd_pcm_substream *substream) { read_lock_irq(&snd_pcm_link_rwlock); spin_lock(&substream->self_group.lock); } static inline void snd_pcm_stream_unlock_irq(struct snd_pcm_substream *substream) { spin_unlock(&substream->self_group.lock); read_unlock_irq(&snd_pcm_link_rwlock); } #define snd_pcm_stream_lock_irqsave(substream, flags) \ do { \ read_lock_irqsave(&snd_pcm_link_rwlock, (flags)); \ spin_lock(&substream->self_group.lock); \ } while (0) #define snd_pcm_stream_unlock_irqrestore(substream, flags) \ do { \ spin_unlock(&substream->self_group.lock); \ read_unlock_irqrestore(&snd_pcm_link_rwlock, (flags)); \ } while (0) #define snd_pcm_group_for_each_entry(s, substream) \ list_for_each_entry(s, &substream->group->substreams, link_list) static inline int snd_pcm_running(struct snd_pcm_substream *substream) { return (substream->runtime->status->state == SNDRV_PCM_STATE_RUNNING || (substream->runtime->status->state == SNDRV_PCM_STATE_DRAINING && substream->stream == SNDRV_PCM_STREAM_PLAYBACK)); } static inline ssize_t bytes_to_samples(struct snd_pcm_runtime *runtime, ssize_t size) { return size * 8 / runtime->sample_bits; } static inline snd_pcm_sframes_t bytes_to_frames(struct snd_pcm_runtime *runtime, ssize_t size) { return size * 8 / runtime->frame_bits; } static inline ssize_t samples_to_bytes(struct snd_pcm_runtime *runtime, ssize_t size) { return size * runtime->sample_bits / 8; } static inline ssize_t frames_to_bytes(struct snd_pcm_runtime *runtime, snd_pcm_sframes_t size) { return size * runtime->frame_bits / 8; } static inline int frame_aligned(struct snd_pcm_runtime *runtime, ssize_t bytes) { return bytes % runtime->byte_align == 0; } static inline size_t snd_pcm_lib_buffer_bytes(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return frames_to_bytes(runtime, runtime->buffer_size); } static inline size_t snd_pcm_lib_period_bytes(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return frames_to_bytes(runtime, runtime->period_size); } /* * result is: 0 ... (boundary - 1) */ static inline snd_pcm_uframes_t snd_pcm_playback_avail(struct snd_pcm_runtime *runtime) { snd_pcm_sframes_t avail = runtime->status->hw_ptr + runtime->buffer_size - runtime->control->appl_ptr; if (avail < 0) avail += runtime->boundary; else if ((snd_pcm_uframes_t) avail >= runtime->boundary) avail -= runtime->boundary; return avail; } /* * result is: 0 ... (boundary - 1) */ static inline snd_pcm_uframes_t snd_pcm_capture_avail(struct snd_pcm_runtime *runtime) { snd_pcm_sframes_t avail = runtime->status->hw_ptr - runtime->control->appl_ptr; if (avail < 0) avail += runtime->boundary; return avail; } static inline snd_pcm_sframes_t snd_pcm_playback_hw_avail(struct snd_pcm_runtime *runtime) { return runtime->buffer_size - snd_pcm_playback_avail(runtime); } static inline snd_pcm_sframes_t snd_pcm_capture_hw_avail(struct snd_pcm_runtime *runtime) { return runtime->buffer_size - snd_pcm_capture_avail(runtime); } /** * snd_pcm_playback_ready - check whether the playback buffer is available * @substream: the pcm substream instance * * Checks whether enough free space is available on the playback buffer. * * Return: Non-zero if available, or zero if not. */ static inline int snd_pcm_playback_ready(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_playback_avail(runtime) >= runtime->control->avail_min; } /** * snd_pcm_capture_ready - check whether the capture buffer is available * @substream: the pcm substream instance * * Checks whether enough capture data is available on the capture buffer. * * Return: Non-zero if available, or zero if not. */ static inline int snd_pcm_capture_ready(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_capture_avail(runtime) >= runtime->control->avail_min; } /** * snd_pcm_playback_data - check whether any data exists on the playback buffer * @substream: the pcm substream instance * * Checks whether any data exists on the playback buffer. * * Return: Non-zero if any data exists, or zero if not. If stop_threshold * is bigger or equal to boundary, then this function returns always non-zero. */ static inline int snd_pcm_playback_data(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; if (runtime->stop_threshold >= runtime->boundary) return 1; return snd_pcm_playback_avail(runtime) < runtime->buffer_size; } /** * snd_pcm_playback_empty - check whether the playback buffer is empty * @substream: the pcm substream instance * * Checks whether the playback buffer is empty. * * Return: Non-zero if empty, or zero if not. */ static inline int snd_pcm_playback_empty(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_playback_avail(runtime) >= runtime->buffer_size; } /** * snd_pcm_capture_empty - check whether the capture buffer is empty * @substream: the pcm substream instance * * Checks whether the capture buffer is empty. * * Return: Non-zero if empty, or zero if not. */ static inline int snd_pcm_capture_empty(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; return snd_pcm_capture_avail(runtime) == 0; } static inline void snd_pcm_trigger_done(struct snd_pcm_substream *substream, struct snd_pcm_substream *master) { substream->runtime->trigger_master = master; } static inline int hw_is_mask(int var) { return var >= SNDRV_PCM_HW_PARAM_FIRST_MASK && var <= SNDRV_PCM_HW_PARAM_LAST_MASK; } static inline int hw_is_interval(int var) { return var >= SNDRV_PCM_HW_PARAM_FIRST_INTERVAL && var <= SNDRV_PCM_HW_PARAM_LAST_INTERVAL; } static inline struct snd_mask *hw_param_mask(struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->masks[var - SNDRV_PCM_HW_PARAM_FIRST_MASK]; } static inline struct snd_interval *hw_param_interval(struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->intervals[var - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]; } static inline const struct snd_mask *hw_param_mask_c(const struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->masks[var - SNDRV_PCM_HW_PARAM_FIRST_MASK]; } static inline const struct snd_interval *hw_param_interval_c(const struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var) { return &params->intervals[var - SNDRV_PCM_HW_PARAM_FIRST_INTERVAL]; } #define params_channels(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_CHANNELS)->min) #define params_rate(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_RATE)->min) #define params_period_size(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_PERIOD_SIZE)->min) #define params_periods(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_PERIODS)->min) #define params_buffer_size(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_BUFFER_SIZE)->min) #define params_buffer_bytes(p) \ (hw_param_interval_c((p), SNDRV_PCM_HW_PARAM_BUFFER_BYTES)->min) int snd_interval_refine(struct snd_interval *i, const struct snd_interval *v); void snd_interval_mul(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c); void snd_interval_div(const struct snd_interval *a, const struct snd_interval *b, struct snd_interval *c); void snd_interval_muldivk(const struct snd_interval *a, const struct snd_interval *b, unsigned int k, struct snd_interval *c); void snd_interval_mulkdiv(const struct snd_interval *a, unsigned int k, const struct snd_interval *b, struct snd_interval *c); int snd_interval_list(struct snd_interval *i, unsigned int count, const unsigned int *list, unsigned int mask); int snd_interval_ratnum(struct snd_interval *i, unsigned int rats_count, struct snd_ratnum *rats, unsigned int *nump, unsigned int *denp); void _snd_pcm_hw_params_any(struct snd_pcm_hw_params *params); void _snd_pcm_hw_param_setempty(struct snd_pcm_hw_params *params, snd_pcm_hw_param_t var); int snd_pcm_hw_params_choose(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params); int snd_pcm_hw_refine(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params); int snd_pcm_hw_constraints_init(struct snd_pcm_substream *substream); int snd_pcm_hw_constraints_complete(struct snd_pcm_substream *substream); int snd_pcm_hw_constraint_mask(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var, u_int32_t mask); int snd_pcm_hw_constraint_mask64(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var, u_int64_t mask); int snd_pcm_hw_constraint_minmax(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var, unsigned int min, unsigned int max); int snd_pcm_hw_constraint_integer(struct snd_pcm_runtime *runtime, snd_pcm_hw_param_t var); int snd_pcm_hw_constraint_list(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, const struct snd_pcm_hw_constraint_list *l); int snd_pcm_hw_constraint_ratnums(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, struct snd_pcm_hw_constraint_ratnums *r); int snd_pcm_hw_constraint_ratdens(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, struct snd_pcm_hw_constraint_ratdens *r); int snd_pcm_hw_constraint_msbits(struct snd_pcm_runtime *runtime, unsigned int cond, unsigned int width, unsigned int msbits); int snd_pcm_hw_constraint_step(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var, unsigned long step); int snd_pcm_hw_constraint_pow2(struct snd_pcm_runtime *runtime, unsigned int cond, snd_pcm_hw_param_t var); int snd_pcm_hw_rule_noresample(struct snd_pcm_runtime *runtime, unsigned int base_rate); int snd_pcm_hw_rule_add(struct snd_pcm_runtime *runtime, unsigned int cond, int var, snd_pcm_hw_rule_func_t func, void *private, int dep, ...); int snd_pcm_format_signed(snd_pcm_format_t format); int snd_pcm_format_unsigned(snd_pcm_format_t format); int snd_pcm_format_linear(snd_pcm_format_t format); int snd_pcm_format_little_endian(snd_pcm_format_t format); int snd_pcm_format_big_endian(snd_pcm_format_t format); #if 0 /* just for DocBook */ /** * snd_pcm_format_cpu_endian - Check the PCM format is CPU-endian * @format: the format to check * * Return: 1 if the given PCM format is CPU-endian, 0 if * opposite, or a negative error code if endian not specified. */ int snd_pcm_format_cpu_endian(snd_pcm_format_t format); #endif /* DocBook */ #ifdef SNDRV_LITTLE_ENDIAN #define snd_pcm_format_cpu_endian(format) snd_pcm_format_little_endian(format) #else #define snd_pcm_format_cpu_endian(format) snd_pcm_format_big_endian(format) #endif int snd_pcm_format_width(snd_pcm_format_t format); /* in bits */ int snd_pcm_format_physical_width(snd_pcm_format_t format); /* in bits */ ssize_t snd_pcm_format_size(snd_pcm_format_t format, size_t samples); const unsigned char *snd_pcm_format_silence_64(snd_pcm_format_t format); int snd_pcm_format_set_silence(snd_pcm_format_t format, void *buf, unsigned int frames); snd_pcm_format_t snd_pcm_build_linear_format(int width, int unsigned, int big_endian); void snd_pcm_set_ops(struct snd_pcm * pcm, int direction, const struct snd_pcm_ops *ops); void snd_pcm_set_sync(struct snd_pcm_substream *substream); int snd_pcm_lib_interleave_len(struct snd_pcm_substream *substream); int snd_pcm_lib_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg); int snd_pcm_update_state(struct snd_pcm_substream *substream, struct snd_pcm_runtime *runtime); int snd_pcm_update_hw_ptr(struct snd_pcm_substream *substream); int snd_pcm_playback_xrun_check(struct snd_pcm_substream *substream); int snd_pcm_capture_xrun_check(struct snd_pcm_substream *substream); int snd_pcm_playback_xrun_asap(struct snd_pcm_substream *substream); int snd_pcm_capture_xrun_asap(struct snd_pcm_substream *substream); void snd_pcm_playback_silence(struct snd_pcm_substream *substream, snd_pcm_uframes_t new_hw_ptr); void snd_pcm_period_elapsed(struct snd_pcm_substream *substream); snd_pcm_sframes_t snd_pcm_lib_write(struct snd_pcm_substream *substream, const void __user *buf, snd_pcm_uframes_t frames); snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *substream, void __user *buf, snd_pcm_uframes_t frames); snd_pcm_sframes_t snd_pcm_lib_writev(struct snd_pcm_substream *substream, void __user **bufs, snd_pcm_uframes_t frames); snd_pcm_sframes_t snd_pcm_lib_readv(struct snd_pcm_substream *substream, void __user **bufs, snd_pcm_uframes_t frames); extern const struct snd_pcm_hw_constraint_list snd_pcm_known_rates; int snd_pcm_limit_hw_rates(struct snd_pcm_runtime *runtime); unsigned int snd_pcm_rate_to_rate_bit(unsigned int rate); unsigned int snd_pcm_rate_bit_to_rate(unsigned int rate_bit); unsigned int snd_pcm_rate_mask_intersect(unsigned int rates_a, unsigned int rates_b); static inline void snd_pcm_set_runtime_buffer(struct snd_pcm_substream *substream, struct snd_dma_buffer *bufp) { struct snd_pcm_runtime *runtime = substream->runtime; if (bufp) { runtime->dma_buffer_p = bufp; runtime->dma_area = bufp->area; runtime->dma_addr = bufp->addr; runtime->dma_bytes = bufp->bytes; } else { runtime->dma_buffer_p = NULL; runtime->dma_area = NULL; runtime->dma_addr = 0; runtime->dma_bytes = 0; } } /* * Timer interface */ void snd_pcm_timer_resolution_change(struct snd_pcm_substream *substream); void snd_pcm_timer_init(struct snd_pcm_substream *substream); void snd_pcm_timer_done(struct snd_pcm_substream *substream); static inline void snd_pcm_gettime(struct snd_pcm_runtime *runtime, struct timespec *tv) { if (runtime->tstamp_type == SNDRV_PCM_TSTAMP_TYPE_MONOTONIC) do_posix_clock_monotonic_gettime(tv); else getnstimeofday(tv); } /* * Memory */ int snd_pcm_lib_preallocate_free(struct snd_pcm_substream *substream); int snd_pcm_lib_preallocate_free_for_all(struct snd_pcm *pcm); int snd_pcm_lib_preallocate_pages(struct snd_pcm_substream *substream, int type, struct device *data, size_t size, size_t max); int snd_pcm_lib_preallocate_pages_for_all(struct snd_pcm *pcm, int type, void *data, size_t size, size_t max); int snd_pcm_lib_malloc_pages(struct snd_pcm_substream *substream, size_t size); int snd_pcm_lib_free_pages(struct snd_pcm_substream *substream); int _snd_pcm_lib_alloc_vmalloc_buffer(struct snd_pcm_substream *substream, size_t size, gfp_t gfp_flags); int snd_pcm_lib_free_vmalloc_buffer(struct snd_pcm_substream *substream); struct page *snd_pcm_lib_get_vmalloc_page(struct snd_pcm_substream *substream, unsigned long offset); #if 0 /* for kernel-doc */ /** * snd_pcm_lib_alloc_vmalloc_buffer - allocate virtual DMA buffer * @substream: the substream to allocate the buffer to * @size: the requested buffer size, in bytes * * Allocates the PCM substream buffer using vmalloc(), i.e., the memory is * contiguous in kernel virtual space, but not in physical memory. Use this * if the buffer is accessed by kernel code but not by device DMA. * * Return: 1 if the buffer was changed, 0 if not changed, or a negative error * code. */ static int snd_pcm_lib_alloc_vmalloc_buffer (struct snd_pcm_substream *substream, size_t size); /** * snd_pcm_lib_alloc_vmalloc_32_buffer - allocate 32-bit-addressable buffer * @substream: the substream to allocate the buffer to * @size: the requested buffer size, in bytes * * This function works like snd_pcm_lib_alloc_vmalloc_buffer(), but uses * vmalloc_32(), i.e., the pages are allocated from 32-bit-addressable memory. * * Return: 1 if the buffer was changed, 0 if not changed, or a negative error * code. */ static int snd_pcm_lib_alloc_vmalloc_32_buffer (struct snd_pcm_substream *substream, size_t size); #endif #define snd_pcm_lib_alloc_vmalloc_buffer(subs, size) \ _snd_pcm_lib_alloc_vmalloc_buffer \ (subs, size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO) #define snd_pcm_lib_alloc_vmalloc_32_buffer(subs, size) \ _snd_pcm_lib_alloc_vmalloc_buffer \ (subs, size, GFP_KERNEL | GFP_DMA32 | __GFP_ZERO) #define snd_pcm_get_dma_buf(substream) ((substream)->runtime->dma_buffer_p) #ifdef CONFIG_SND_DMA_SGBUF /* * SG-buffer handling */ #define snd_pcm_substream_sgbuf(substream) \ snd_pcm_get_dma_buf(substream)->private_data struct page *snd_pcm_sgbuf_ops_page(struct snd_pcm_substream *substream, unsigned long offset); #else /* !SND_DMA_SGBUF */ /* * fake using a continuous buffer */ #define snd_pcm_sgbuf_ops_page NULL #endif /* SND_DMA_SGBUF */ static inline dma_addr_t snd_pcm_sgbuf_get_addr(struct snd_pcm_substream *substream, unsigned int ofs) { return snd_sgbuf_get_addr(snd_pcm_get_dma_buf(substream), ofs); } static inline void * snd_pcm_sgbuf_get_ptr(struct snd_pcm_substream *substream, unsigned int ofs) { return snd_sgbuf_get_ptr(snd_pcm_get_dma_buf(substream), ofs); } static inline unsigned int snd_pcm_sgbuf_get_chunk_size(struct snd_pcm_substream *substream, unsigned int ofs, unsigned int size) { return snd_sgbuf_get_chunk_size(snd_pcm_get_dma_buf(substream), ofs, size); } /* handle mmap counter - PCM mmap callback should handle this counter properly */ static inline void snd_pcm_mmap_data_open(struct vm_area_struct *area) { struct snd_pcm_substream *substream = (struct snd_pcm_substream *)area->vm_private_data; atomic_inc(&substream->mmap_count); } static inline void snd_pcm_mmap_data_close(struct vm_area_struct *area) { struct snd_pcm_substream *substream = (struct snd_pcm_substream *)area->vm_private_data; atomic_dec(&substream->mmap_count); } int snd_pcm_lib_default_mmap(struct snd_pcm_substream *substream, struct vm_area_struct *area); /* mmap for io-memory area */ #if defined(CONFIG_X86) || defined(CONFIG_PPC) || defined(CONFIG_ALPHA) #define SNDRV_PCM_INFO_MMAP_IOMEM SNDRV_PCM_INFO_MMAP int snd_pcm_lib_mmap_iomem(struct snd_pcm_substream *substream, struct vm_area_struct *area); #else #define SNDRV_PCM_INFO_MMAP_IOMEM 0 #define snd_pcm_lib_mmap_iomem NULL #endif #define snd_pcm_lib_mmap_vmalloc NULL static inline void snd_pcm_limit_isa_dma_size(int dma, size_t *max) { *max = dma < 4 ? 64 * 1024 : 128 * 1024; } /* * Misc */ #define SNDRV_PCM_DEFAULT_CON_SPDIF (IEC958_AES0_CON_EMPHASIS_NONE|\ (IEC958_AES1_CON_ORIGINAL<<8)|\ (IEC958_AES1_CON_PCM_CODER<<8)|\ (IEC958_AES3_CON_FS_48000<<24)) #define PCM_RUNTIME_CHECK(sub) snd_BUG_ON(!(sub) || !(sub)->runtime) const char *snd_pcm_format_name(snd_pcm_format_t format); /** * snd_pcm_stream_str - Get a string naming the direction of a stream * @substream: the pcm substream instance * * Return: A string naming the direction of the stream. */ static inline const char *snd_pcm_stream_str(struct snd_pcm_substream *substream) { if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) return "Playback"; else return "Capture"; } /* * PCM channel-mapping control API */ /* array element of channel maps */ struct snd_pcm_chmap_elem { unsigned char channels; unsigned char map[15]; }; /* channel map information; retrieved via snd_kcontrol_chip() */ struct snd_pcm_chmap { struct snd_pcm *pcm; /* assigned PCM instance */ int stream; /* PLAYBACK or CAPTURE */ struct snd_kcontrol *kctl; const struct snd_pcm_chmap_elem *chmap; unsigned int max_channels; unsigned int channel_mask; /* optional: active channels bitmask */ void *private_data; /* optional: private data pointer */ }; /* get the PCM substream assigned to the given chmap info */ static inline struct snd_pcm_substream * snd_pcm_chmap_substream(struct snd_pcm_chmap *info, unsigned int idx) { struct snd_pcm_substream *s; for (s = info->pcm->streams[info->stream].substream; s; s = s->next) if (s->number == idx) return s; return NULL; } /* ALSA-standard channel maps (RL/RR prior to C/LFE) */ extern const struct snd_pcm_chmap_elem snd_pcm_std_chmaps[]; /* Other world's standard channel maps (C/LFE prior to RL/RR) */ extern const struct snd_pcm_chmap_elem snd_pcm_alt_chmaps[]; /* bit masks to be passed to snd_pcm_chmap.channel_mask field */ #define SND_PCM_CHMAP_MASK_24 ((1U << 2) | (1U << 4)) #define SND_PCM_CHMAP_MASK_246 (SND_PCM_CHMAP_MASK_24 | (1U << 6)) #define SND_PCM_CHMAP_MASK_2468 (SND_PCM_CHMAP_MASK_246 | (1U << 8)) int snd_pcm_add_chmap_ctls(struct snd_pcm *pcm, int stream, const struct snd_pcm_chmap_elem *chmap, int max_channels, unsigned long private_value, struct snd_pcm_chmap **info_ret); /* Strong-typed conversion of pcm_format to bitwise */ static inline u64 pcm_format_to_bits(snd_pcm_format_t pcm_format) { return 1ULL << (__force int) pcm_format; } #endif /* __SOUND_PCM_H */
Raybuntu/linux
include/sound/pcm.h
C
gpl-2.0
41,323
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Tax * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Tax rate resource model * * @category Mage * @package Mage_Tax * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Tax_Model_Mysql4_Calculation_Rule extends Mage_Tax_Model_Resource_Calculation_Rule { }
miguelangelramirez/magento.dev
app/code/core/Mage/Tax/Model/Mysql4/Calculation/Rule.php
PHP
gpl-2.0
1,202
/* StreamHandler.java -- A class for publishing log messages to instances of java.io.OutputStream Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.util.logging; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; /** * A <code>StreamHandler</code> publishes <code>LogRecords</code> to * a instances of <code>java.io.OutputStream</code>. * * @author Sascha Brawer (brawer@acm.org) */ public class StreamHandler extends Handler { private OutputStream out; private Writer writer; /** * Indicates the current state of this StreamHandler. The value * should be one of STATE_FRESH, STATE_PUBLISHED, or STATE_CLOSED. */ private int streamState = STATE_FRESH; /** * streamState having this value indicates that the StreamHandler * has been created, but the publish(LogRecord) method has not been * called yet. If the StreamHandler has been constructed without an * OutputStream, writer will be null, otherwise it is set to a * freshly created OutputStreamWriter. */ private static final int STATE_FRESH = 0; /** * streamState having this value indicates that the publish(LocRecord) * method has been called at least once. */ private static final int STATE_PUBLISHED = 1; /** * streamState having this value indicates that the close() method * has been called. */ private static final int STATE_CLOSED = 2; /** * Creates a <code>StreamHandler</code> without an output stream. * Subclasses can later use {@link * #setOutputStream(java.io.OutputStream)} to associate an output * stream with this StreamHandler. */ public StreamHandler() { this(null, null); } /** * Creates a <code>StreamHandler</code> that formats log messages * with the specified Formatter and publishes them to the specified * output stream. * * @param out the output stream to which the formatted log messages * are published. * * @param formatter the <code>Formatter</code> that will be used * to format log messages. */ public StreamHandler(OutputStream out, Formatter formatter) { this(out, "java.util.logging.StreamHandler", Level.INFO, formatter, SimpleFormatter.class); } StreamHandler( OutputStream out, String propertyPrefix, Level defaultLevel, Formatter formatter, Class defaultFormatterClass) { this.level = LogManager.getLevelProperty(propertyPrefix + ".level", defaultLevel); this.filter = (Filter) LogManager.getInstanceProperty( propertyPrefix + ".filter", /* must be instance of */ Filter.class, /* default: new instance of */ null); if (formatter != null) this.formatter = formatter; else this.formatter = (Formatter) LogManager.getInstanceProperty( propertyPrefix + ".formatter", /* must be instance of */ Formatter.class, /* default: new instance of */ defaultFormatterClass); try { String enc = LogManager.getLogManager().getProperty(propertyPrefix + ".encoding"); /* make sure enc actually is a valid encoding */ if ((enc != null) && (enc.length() > 0)) new String(new byte[0], enc); this.encoding = enc; } catch (Exception _) { } if (out != null) { try { changeWriter(out, getEncoding()); } catch (UnsupportedEncodingException uex) { /* This should never happen, since the validity of the encoding * name has been checked above. */ throw new RuntimeException(uex.getMessage()); } } } private void checkOpen() { if (streamState == STATE_CLOSED) throw new IllegalStateException(this.toString() + " has been closed"); } private void checkFresh() { checkOpen(); if (streamState != STATE_FRESH) throw new IllegalStateException("some log records have been published to " + this); } private void changeWriter(OutputStream out, String encoding) throws UnsupportedEncodingException { OutputStreamWriter writer; /* The logging API says that a null encoding means the default * platform encoding. However, java.io.OutputStreamWriter needs * another constructor for the default platform encoding, * passing null would throw an exception. */ if (encoding == null) writer = new OutputStreamWriter(out); else writer = new OutputStreamWriter(out, encoding); /* Closing the stream has side effects -- do this only after * creating a new writer has been successful. */ if ((streamState != STATE_FRESH) || (this.writer != null)) close(); this.writer = writer; this.out = out; this.encoding = encoding; streamState = STATE_FRESH; } /** * Sets the character encoding which this handler uses for publishing * log records. The encoding of a <code>StreamHandler</code> must be * set before any log records have been published. * * @param encoding the name of a character encoding, or <code>null</code> * for the default encoding. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control the * the logging infrastructure. * * @exception IllegalStateException if any log records have been * published to this <code>StreamHandler</code> before. Please * be aware that this is a pecularity of the GNU implementation. * While the API specification indicates that it is an error * if the encoding is set after records have been published, * it does not mandate any specific behavior for that case. */ public void setEncoding(String encoding) throws SecurityException, UnsupportedEncodingException { /* The inherited implementation first checks whether the invoking * code indeed has the permission to control the logging infra- * structure, and throws a SecurityException if this was not the * case. * * Next, it verifies that the encoding is supported and throws * an UnsupportedEncodingExcpetion otherwise. Finally, it remembers * the name of the encoding. */ super.setEncoding(encoding); checkFresh(); /* If out is null, setEncoding is being called before an output * stream has been set. In that case, we need to check that the * encoding is valid, and remember it if this is the case. Since * this is exactly what the inherited implementation of * Handler.setEncoding does, we can delegate. */ if (out != null) { /* The logging API says that a null encoding means the default * platform encoding. However, java.io.OutputStreamWriter needs * another constructor for the default platform encoding, passing * null would throw an exception. */ if (encoding == null) writer = new OutputStreamWriter(out); else writer = new OutputStreamWriter(out, encoding); } } /** * Changes the output stream to which this handler publishes * logging records. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control * the logging infrastructure. * * @throws NullPointerException if <code>out</code> * is <code>null</code>. */ protected void setOutputStream(OutputStream out) throws SecurityException { LogManager.getLogManager().checkAccess(); /* Throw a NullPointerException if out is null. */ out.getClass(); try { changeWriter(out, getEncoding()); } catch (UnsupportedEncodingException ex) { /* This seems quite unlikely to happen, unless the underlying * implementation of java.io.OutputStreamWriter changes its * mind (at runtime) about the set of supported character * encodings. */ throw new RuntimeException(ex.getMessage()); } } /** * Publishes a <code>LogRecord</code> to the associated output * stream, provided the record passes all tests for being loggable. * The <code>StreamHandler</code> will localize the message of the * log record and substitute any message parameters. * * <p>Most applications do not need to call this method directly. * Instead, they will use use a {@link Logger}, which will create * LogRecords and distribute them to registered handlers. * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception. * * <p>If a log record is being published to a * <code>StreamHandler</code> that has been closed earlier, the Sun * J2SE 1.4 reference can be observed to silently ignore the * call. The GNU implementation, however, intentionally behaves * differently by informing the <code>ErrorManager</code> associated * with this <code>StreamHandler</code>. Since the condition * indicates a programming error, the programmer should be * informed. It also seems extremely unlikely that any application * would depend on the exact behavior in this rather obscure, * erroneous case -- especially since the API specification does not * prescribe what is supposed to happen. * * @param record the log event to be published. */ public void publish(LogRecord record) { String formattedMessage; if (!isLoggable(record)) return; if (streamState == STATE_FRESH) { try { writer.write(formatter.getHead(this)); } catch (java.io.IOException ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); return; } catch (Exception ex) { reportError(null, ex, ErrorManager.GENERIC_FAILURE); return; } streamState = STATE_PUBLISHED; } try { formattedMessage = formatter.format(record); } catch (Exception ex) { reportError(null, ex, ErrorManager.FORMAT_FAILURE); return; } try { writer.write(formattedMessage); } catch (Exception ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); } } /** * Checks whether or not a <code>LogRecord</code> would be logged * if it was passed to this <code>StreamHandler</code> for publication. * * <p>The <code>StreamHandler</code> implementation first checks * whether a writer is present and the handler's level is greater * than or equal to the severity level threshold. In a second step, * if a {@link Filter} has been installed, its {@link * Filter#isLoggable(LogRecord) isLoggable} method is * invoked. Subclasses of <code>StreamHandler</code> can override * this method to impose their own constraints. * * @param record the <code>LogRecord</code> to be checked. * * @return <code>true</code> if <code>record</code> would * be published by {@link #publish(LogRecord) publish}, * <code>false</code> if it would be discarded. * * @see #setLevel(Level) * @see #setFilter(Filter) * @see Filter#isLoggable(LogRecord) * * @throws NullPointerException if <code>record</code> is * <code>null</code>. */ public boolean isLoggable(LogRecord record) { return (writer != null) && super.isLoggable(record); } /** * Forces any data that may have been buffered to the underlying * output device. * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception. * * <p>If a <code>StreamHandler</code> that has been closed earlier * is closed a second time, the Sun J2SE 1.4 reference can be * observed to silently ignore the call. The GNU implementation, * however, intentionally behaves differently by informing the * <code>ErrorManager</code> associated with this * <code>StreamHandler</code>. Since the condition indicates a * programming error, the programmer should be informed. It also * seems extremely unlikely that any application would depend on the * exact behavior in this rather obscure, erroneous case -- * especially since the API specification does not prescribe what is * supposed to happen. */ public void flush() { try { checkOpen(); if (writer != null) writer.flush(); } catch (Exception ex) { reportError(null, ex, ErrorManager.FLUSH_FAILURE); } } /** * Closes this <code>StreamHandler</code> after having forced any * data that may have been buffered to the underlying output * device. * * <p>As soon as <code>close</code> has been called, * a <code>Handler</code> should not be used anymore. Attempts * to publish log records, to flush buffers, or to modify the * <code>Handler</code> in any other way may throw runtime * exceptions after calling <code>close</code>.</p> * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception.</p> * * <p>If a <code>StreamHandler</code> that has been closed earlier * is closed a second time, the Sun J2SE 1.4 reference can be * observed to silently ignore the call. The GNU implementation, * however, intentionally behaves differently by informing the * <code>ErrorManager</code> associated with this * <code>StreamHandler</code>. Since the condition indicates a * programming error, the programmer should be informed. It also * seems extremely unlikely that any application would depend on the * exact behavior in this rather obscure, erroneous case -- * especially since the API specification does not prescribe what is * supposed to happen. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control * the logging infrastructure. */ public void close() throws SecurityException { LogManager.getLogManager().checkAccess(); try { /* Although flush also calls checkOpen, it catches * any exceptions and reports them to the ErrorManager * as flush failures. However, we want to report * a closed stream as a close failure, not as a * flush failure here. Therefore, we call checkOpen() * before flush(). */ checkOpen(); flush(); if (writer != null) { if (formatter != null) { /* Even if the StreamHandler has never published a record, * it emits head and tail upon closing. An earlier version * of the GNU Classpath implementation did not emitted * anything. However, this had caused XML log files to be * entirely empty instead of containing no log records. */ if (streamState == STATE_FRESH) writer.write(formatter.getHead(this)); if (streamState != STATE_CLOSED) writer.write(formatter.getTail(this)); } streamState = STATE_CLOSED; writer.close(); } } catch (Exception ex) { reportError(null, ex, ErrorManager.CLOSE_FAILURE); } } }
aosm/gcc_40
libjava/java/util/logging/StreamHandler.java
Java
gpl-2.0
16,999
.njg-tooltip{ background: rgba(0, 0, 0, 0.5); border-radius: 3px; color: #fff; font-family: sans-serif; font-size: 13px; padding: 5px 10px; padding: 5px 10px; position: absolute; top: -2000px; } .njg-overlay{ background: #fbfbfb; border-radius: 2px; border: 1px solid #ccc; color: #6d6357; font-family: Arial, sans-serif; font-family: sans-serif; font-size: 14px; height: auto; max-width: 400px; min-width: 200px; padding: 0 15px; right: 10px; top: 10px; width: auto; } .njg-metadata{ background: #fbfbfb; border-radius: 2px; border: 1px solid #ccc; color: #6d6357; display: none; font-family: Arial, sans-serif; font-family: sans-serif; font-size: 14px; height: auto; left: 10px; max-width: 500px; min-width: 200px; padding: 0 15px; top: 10px; width: auto; } .njg-node{ stroke-opacity: 0.5; stroke-width: 7px; stroke: #fff; } .njg-node:hover, .njg-node.njg-open { stroke: rgba(0, 0, 0, 0.2); } .njg-link{ cursor: pointer; stroke: #999; stroke-width: 2; stroke-opacity: 0.25; } .njg-link:hover, .njg-link.njg-open{ stroke-width: 4 !important; stroke-opacity: 0.5; }
raydtang/kalua
openwrt-monitoring/netjsongraph-theme.css
CSS
gpl-2.0
1,264
/* * Copyright (c) 2014, 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 test.css.controls.api; import org.junit.Test; import client.test.Keywords; import client.test.Smoke; import org.junit.BeforeClass; import org.junit.Before; import test.javaclient.shared.TestBase; import static test.css.controls.ControlPage.ScrollPanes; import test.javaclient.shared.screenshots.ScreenshotUtils; /** * Generated test */ public class ScrollPanesAPICssTest extends TestBase { { ScreenshotUtils.setComparatorDistance(0.003f); } @BeforeClass public static void runUI() { test.css.controls.api.APIStylesApp.main(null); } @Before public void createPage () { ((test.css.controls.api.APIStylesApp)getApplication()).open(ScrollPanes); } /** * test ScrollPane with css: -fx-border-color */ @Test public void ScrollPanes_BORDER_COLOR() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-COLOR", true); } /** * test ScrollPane with css: -fx-border-width */ @Test public void ScrollPanes_BORDER_WIDTH() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH", true); } /** * test ScrollPane with css: -fx-border-width-dotted */ @Test public void ScrollPanes_BORDER_WIDTH_dotted() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dotted", true); } /** * test ScrollPane with css: -fx-border-width-dashed */ @Test public void ScrollPanes_BORDER_WIDTH_dashed() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dashed", true); } /** * test ScrollPane with css: -fx-border-inset */ @Test public void ScrollPanes_BORDER_INSET() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-INSET", true); } /** * test ScrollPane with css: -fx-border-style-dashed */ @Test public void ScrollPanes_BORDER_STYLE_DASHED() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DASHED", true); } /** * test ScrollPane with css: -fx-border-style-dotted */ @Test public void ScrollPanes_BORDER_STYLE_DOTTED() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DOTTED", true); } /** * test ScrollPane with css: -fx-image-border */ @Test public void ScrollPanes_IMAGE_BORDER() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER", true); } /** * test ScrollPane with css: -fx-image-border-insets */ @Test public void ScrollPanes_IMAGE_BORDER_INSETS() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-INSETS", true); } /** * test ScrollPane with css: -fx-image-border-no-repeat */ @Test public void ScrollPanes_IMAGE_BORDER_NO_REPEAT() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-NO-REPEAT", true); } /** * test ScrollPane with css: -fx-image-border-repeat-x */ @Test public void ScrollPanes_IMAGE_BORDER_REPEAT_X() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-X", true); } /** * test ScrollPane with css: -fx-image-border-repeat-y */ @Test public void ScrollPanes_IMAGE_BORDER_REPEAT_Y() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-Y", true); } /** * test ScrollPane with css: -fx-image-border-round */ @Test public void ScrollPanes_IMAGE_BORDER_ROUND() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-ROUND", true); } /** * test ScrollPane with css: -fx-image-border-space */ @Test public void ScrollPanes_IMAGE_BORDER_SPACE() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-SPACE", true); } public String getName() { return "ControlCss"; } }
teamfx/openjfx-8u-dev-tests
functional/FXCssTests/test/test/css/controls/api/ScrollPanesAPICssTest.java
Java
gpl-2.0
5,253
-- -- PacketFence SQL schema upgrade from 5.0.0 to 5.1.0 -- -- -- Setting the major/minor/sub-minor version of the DB -- SET @MAJOR_VERSION = 5; SET @MINOR_VERSION = 1; SET @SUBMINOR_VERSION = 0; -- -- The VERSION_INT to ensure proper ordering of the version in queries -- SET @VERSION_INT = @MAJOR_VERSION << 16 | @MINOR_VERSION << 8 | @SUBMINOR_VERSION; -- -- Alter Class for external_command -- ALTER TABLE class ADD `external_command` varchar(255) DEFAULT NULL; -- -- Insert new sms carrier -- INSERT INTO sms_carrier (id, name, email_pattern, created) VALUES (100119, 'Swisscom', '%s@sms.bluewin.ch', now()), (100120, 'Orange (CH)', '%s@orange.net', now()), (100121, 'Sunrise', '%s@gsm.sunrise.ch', now()); -- -- Add a column to radius_nas to order the nas list -- ALTER TABLE radius_nas ADD start_ip INT UNSIGNED DEFAULT 0, ADD end_ip INT UNSIGNED DEFAULT 0, ADD range_length INT DEFAULT 0; -- -- Table structure for table 'pf_version' -- CREATE TABLE pf_version ( `id` INT NOT NULL PRIMARY KEY, `version` VARCHAR(11) NOT NULL UNIQUE KEY); -- -- Updating to current version -- INSERT INTO pf_version (id, version) VALUES (@VERSION_INT, CONCAT_WS('.', @MAJOR_VERSION, @MINOR_VERSION, @SUBMINOR_VERSION)); -- IMPORTANT: KEEP THIS AT THE BOTTOM OF THIS FILE. -- TO BE EXECUTED AFTER EVERYTHING ELSE. CREATE DATABASE pf_graphite; use pf_graphite; GRANT ALL PRIVILEGES ON `pf_graphite`.* TO 'pf'@'%'; GRANT ALL PRIVILEGES ON `pf_graphite`.* TO 'pf'@'localhost'; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `account_mygraph` -- DROP TABLE IF EXISTS `account_mygraph`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_mygraph` ( `id` int(11) NOT NULL AUTO_INCREMENT, `profile_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, `url` longtext NOT NULL, PRIMARY KEY (`id`), KEY `account_mygraph_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_profile` -- DROP TABLE IF EXISTS `account_profile`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_profile` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `history` longtext NOT NULL, `advancedUI` tinyint(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_variable` -- DROP TABLE IF EXISTS `account_variable`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_variable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `profile_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, `value` varchar(64) NOT NULL, PRIMARY KEY (`id`), KEY `account_variable_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_view` -- DROP TABLE IF EXISTS `account_view`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_view` ( `id` int(11) NOT NULL AUTO_INCREMENT, `profile_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, PRIMARY KEY (`id`), KEY `account_view_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `account_window` -- DROP TABLE IF EXISTS `account_window`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account_window` ( `id` int(11) NOT NULL AUTO_INCREMENT, `view_id` int(11) NOT NULL, `name` varchar(64) NOT NULL, `top` int(11) NOT NULL, `left` int(11) NOT NULL, `width` int(11) NOT NULL, `height` int(11) NOT NULL, `url` longtext NOT NULL, `interval` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `account_window_189a3b91` (`view_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_group` -- DROP TABLE IF EXISTS `auth_group`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_group` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(80) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_group_permissions` -- DROP TABLE IF EXISTS `auth_group_permissions`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_group_permissions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `group_id` int(11) NOT NULL, `permission_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `group_id` (`group_id`,`permission_id`), KEY `auth_group_permissions_bda51c3c` (`group_id`), KEY `auth_group_permissions_1e014c8f` (`permission_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_permission` -- DROP TABLE IF EXISTS `auth_permission`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_permission` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `content_type_id` int(11) NOT NULL, `codename` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `content_type_id` (`content_type_id`,`codename`), KEY `auth_permission_e4470c6e` (`content_type_id`) ) ENGINE=MyISAM AUTO_INCREMENT=46 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_user` -- DROP TABLE IF EXISTS `auth_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) NOT NULL, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `email` varchar(75) NOT NULL, `password` varchar(128) NOT NULL, `is_staff` tinyint(1) NOT NULL, `is_active` tinyint(1) NOT NULL, `is_superuser` tinyint(1) NOT NULL, `last_login` datetime NOT NULL, `date_joined` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_user_groups` -- DROP TABLE IF EXISTS `auth_user_groups`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_user_groups` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `group_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`,`group_id`), KEY `auth_user_groups_fbfc09f1` (`user_id`), KEY `auth_user_groups_bda51c3c` (`group_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `auth_user_user_permissions` -- DROP TABLE IF EXISTS `auth_user_user_permissions`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `auth_user_user_permissions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `permission_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_id` (`user_id`,`permission_id`), KEY `auth_user_user_permissions_fbfc09f1` (`user_id`), KEY `auth_user_user_permissions_1e014c8f` (`permission_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `dashboard_dashboard` -- DROP TABLE IF EXISTS `dashboard_dashboard`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `dashboard_dashboard` ( `name` varchar(128) NOT NULL, `state` longtext NOT NULL, PRIMARY KEY (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `dashboard_dashboard_owners` -- DROP TABLE IF EXISTS `dashboard_dashboard_owners`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `dashboard_dashboard_owners` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dashboard_id` varchar(128) NOT NULL, `profile_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `dashboard_id` (`dashboard_id`,`profile_id`), KEY `dashboard_dashboard_owners_b26c2633` (`dashboard_id`), KEY `dashboard_dashboard_owners_141c6eec` (`profile_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `django_admin_log` -- DROP TABLE IF EXISTS `django_admin_log`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_admin_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `action_time` datetime NOT NULL, `user_id` int(11) NOT NULL, `content_type_id` int(11) DEFAULT NULL, `object_id` longtext, `object_repr` varchar(200) NOT NULL, `action_flag` smallint(5) unsigned NOT NULL, `change_message` longtext NOT NULL, PRIMARY KEY (`id`), KEY `django_admin_log_fbfc09f1` (`user_id`), KEY `django_admin_log_e4470c6e` (`content_type_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `django_content_type` -- DROP TABLE IF EXISTS `django_content_type`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_content_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `app_label` varchar(100) NOT NULL, `model` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `app_label` (`app_label`,`model`) ) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `django_session` -- DROP TABLE IF EXISTS `django_session`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_session` ( `session_key` varchar(40) NOT NULL, `session_data` longtext NOT NULL, `expire_date` datetime NOT NULL, PRIMARY KEY (`session_key`), KEY `django_session_c25c2c28` (`expire_date`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `events_event` -- DROP TABLE IF EXISTS `events_event`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `events_event` ( `id` int(11) NOT NULL AUTO_INCREMENT, `when` datetime NOT NULL, `what` varchar(255) NOT NULL, `data` longtext NOT NULL, `tags` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tagging_tag` -- DROP TABLE IF EXISTS `tagging_tag`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tagging_tag` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tagging_taggeditem` -- DROP TABLE IF EXISTS `tagging_taggeditem`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tagging_taggeditem` ( `id` int(11) NOT NULL AUTO_INCREMENT, `tag_id` int(11) NOT NULL, `content_type_id` int(11) NOT NULL, `object_id` int(10) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `tag_id` (`tag_id`,`content_type_id`,`object_id`), KEY `tagging_taggeditem_3747b463` (`tag_id`), KEY `tagging_taggeditem_e4470c6e` (`content_type_id`), KEY `tagging_taggeditem_829e37fd` (`object_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
inverse-inc/packetfence
db/upgrade-5.0.0-5.1.0.sql
SQL
gpl-2.0
13,720
<?php /** * @file * Contains \Drupal\Console\Command\Debug\UpdateCommand. */ namespace Drupal\Console\Command\Debug; use Drupal\Console\Command\Shared\UpdateTrait; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Drupal\Console\Core\Command\Command; use Drupal\Core\Update\UpdateRegistry; use Drupal\Console\Utils\Site; class UpdateCommand extends Command { use UpdateTrait; /** * @var Site */ protected $site; /** * @var UpdateRegistry */ protected $postUpdateRegistry; /** * DebugCommand constructor. * * @param Site $site * @param UpdateRegistry $postUpdateRegistry */ public function __construct( Site $site, UpdateRegistry $postUpdateRegistry ) { $this->site = $site; $this->postUpdateRegistry = $postUpdateRegistry; parent::__construct(); } /** * @inheritdoc */ protected function configure() { $this ->setName('debug:update') ->setDescription($this->trans('commands.debug.update.description')) ->setAliases(['du']); } /** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $this->site->loadLegacyFile('/core/includes/update.inc'); $this->site->loadLegacyFile('/core/includes/install.inc'); drupal_load_updates(); update_fix_compatibility(); $requirements = update_check_requirements(); $severity = drupal_requirements_severity($requirements); $updates = update_get_update_list(); $postUpdates = $this->postUpdateRegistry->getPendingUpdateInformation(); $this->getIo()->newLine(); if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING)) { $this->populateRequirements($requirements); } elseif (empty($updates) && empty($postUpdates)) { $this->getIo()->info($this->trans('commands.debug.update.messages.no-updates')); } else { $this->showUpdateTable($updates, $this->trans('commands.debug.update.messages.module-list')); $this->showPostUpdateTable($postUpdates, $this->trans('commands.debug.update.messages.module-list-post-update')); } } /** * @param $requirements */ private function populateRequirements($requirements) { $this->getIo()->info($this->trans('commands.debug.update.messages.requirements-error')); $tableHeader = [ $this->trans('commands.debug.update.messages.severity'), $this->trans('commands.debug.update.messages.title'), $this->trans('commands.debug.update.messages.value'), $this->trans('commands.debug.update.messages.description'), ]; $tableRows = []; foreach ($requirements as $requirement) { $minimum = in_array( $requirement['minimum schema'], [REQUIREMENT_ERROR, REQUIREMENT_WARNING] ); if ((isset($requirement['minimum schema'])) && ($minimum)) { $tableRows[] = [ $requirement['severity'], $requirement['title'], $requirement['value'], $requirement['description'], ]; } } $this->getIo()->table($tableHeader, $tableRows); } }
maskedjellybean/tee-prop
vendor/drupal/console/src/Command/Debug/UpdateCommand.php
PHP
gpl-2.0
3,484
/* This file is automatically generated. DO NOT EDIT! */ #ifndef _newfile_h #define _newfile_h off_t sf_byte (sf_file file); /*< Count the file data size (in bytes) >*/ /*------------------------------------------------------------*/ sf_file sf_tmpfile(char *format); /*< Create an temporary (rw mode) file structure. Lives within the program >*/ /*------------------------------------------------------------*/ void sf_filefresh(sf_file file); /*< used for temporary file only to recover the dataname >*/ void sf_filecopy(sf_file file, sf_file src, sf_datatype type); /*< copy the content in src->stream to file->stream >*/ void sf_tmpfileclose (sf_file file); /*< close a file and free allocated space >*/ #endif
TobbeTripitaka/src
user/cwp/newfile.h
C
gpl-2.0
727
<?php /** * @package SP Page Builder * @author JoomShaper http://www.joomshaper.com * @copyright Copyright (c) 2010 - 2016 JoomShaper * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later */ //no direct accees defined ('_JEXEC') or die ('restricted aceess'); class SppagebuilderAddonEmpty_space extends SppagebuilderAddons{ public function render() { $class = (isset($this->addon->settings->class) && $this->addon->settings->class) ? $this->addon->settings->class : ''; return '<div class="sppb-empty-space ' . $class . ' clearfix"></div>'; } public function css() { $addon_id = '#sppb-addon-' . $this->addon->id; $gap = (isset($this->addon->settings->gap) && $this->addon->settings->gap) ? 'padding-bottom: ' . (int) $this->addon->settings->gap . 'px;': ''; if($gap) { $css = $addon_id . ' .sppb-empty-space {'; $css .= $gap; $css .= '}'; } return $css; } }
cchin013/uecsite2017
components/com_sppagebuilder/addons/empty_space/site.php
PHP
gpl-2.0
916
/********************************************************************** * * * Voreen - The Volume Rendering Engine * * * * Created between 2005 and 2012 by The Voreen Team * * as listed in CREDITS.TXT <http://www.voreen.org> * * * * This file is part of the Voreen software package. Voreen is free * * software: you can redistribute it and/or modify it under the terms * * of the GNU General Public License version 2 as published by the * * Free Software Foundation. * * * * Voreen 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 * * in the file "LICENSE.txt" along with this program. * * If not, see <http://www.gnu.org/licenses/>. * * * * The authors reserve all rights not expressly granted herein. For * * non-commercial academic use see the license exception specified in * * the file "LICENSE-academic.txt". To get information about * * commercial licensing please contact the authors. * * * **********************************************************************/ #ifndef VRN_EVENTPROPERTYWIDGET_H #define VRN_EVENTPROPERTYWIDGET_H class QBoxLayout; #include "voreen/core/properties/propertywidget.h" #include <QWidget> class QCheckBox; class QComboBox; class QCheckBox; namespace voreen { class EventPropertyBase; class ModifierDetectorWidget; class KeyDetectorWidget; class EventPropertyWidget : public QWidget, public PropertyWidget { Q_OBJECT public: EventPropertyWidget(EventPropertyBase* property, QWidget* parent = 0); ~EventPropertyWidget(); virtual void setEnabled(bool enabled); virtual void setVisible(bool state); virtual void disconnect(); virtual void updateFromProperty(); public slots: void modifierChanged(Qt::KeyboardModifiers modifier); void keyChanged(int key); void buttonChanged(int button); void enabledChanged(bool enabled); void sharingChanged(bool shared); protected: void createEnabledBox(); void createSharingBox(); void createMouseWidgets(); void createKeyWidgets(); void adjustWidgetState(); QBoxLayout* layout_; EventPropertyBase* property_; QCheckBox* checkEnabled_; ModifierDetectorWidget* modifierWidget_; KeyDetectorWidget* keyWidget_; QComboBox* buttonBox_; QCheckBox* checkSharing_; bool disconnected_; }; } // namespace #endif // VRN_EVENTPROPERTYWIDGET_H
Elima85/bccfccraycaster
include/voreen/qt/widgets/eventpropertywidget.h
C
gpl-2.0
3,287
<? require_once("../../lib/bd/basedatosAdo.php"); class mysreportes { var $rep; var $bd; function mysreportes() { $this->rep=""; $this->bd=new basedatosAdo(); } function sqlreporte() { $sql="select refcom as referencia, codpre as codigo_presupuestario, monimp as monto from cpimpcom order by refcom"; return $sql; } function getAncho($pos) { $anchos=array(); $anchos[0]=75; $anchos[1]=60; $anchos[2]=20; $anchos[3]=30; $anchos[4]=30; $anchos[5]=30; $anchos[6]=30; /* $anchos[7]=30; $anchos[8]=30; $anchos[9]=30; $anchos[10]=30; $anchos[11]=30;*/ return $anchos[$pos]; } function getAncho2($pos) { $anchos2=array(); $anchos2[0]=20; $anchos2[1]=20; $anchos2[2]=20; $anchos2[3]=20; $anchos2[4]=40; $anchos2[5]=30; $anchos2[6]=30; $anchos2[7]=30; $anchos2[8]=30; $anchos2[9]=30; $anchos2[10]=30; $anchos2[11]=30; return $anchos2[$pos]; } } ?>
cidesa/siga-universitario
web/reportes/reportes/tesoreria/anchoTSRRELBAN.php
PHP
gpl-2.0
987
const express = require('express'); const path = require('path'); const compression = require('compression'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const webpack = require('webpack'); // Dev middleware const addDevMiddlewares = (app, options) => { const compiler = webpack(options); const middleware = webpackDevMiddleware(compiler, { noInfo: true, publicPath: options.output.publicPath, silent: true, }); app.use(middleware); app.use(webpackHotMiddleware(compiler)); // Since webpackDevMiddleware uses memory-fs internally to store build // artifacts, we use it instead const fs = middleware.fileSystem; app.get('*', (req, res) => { const file = fs.readFileSync(path.join(compiler.outputPath, 'index.html')); res.send(file.toString()); }); }; // Production middlewares const addProdMiddlewares = (app, options) => { // compression middleware compresses your server responses which makes them // smaller (applies also to assets). You can read more about that technique // and other good practices on official Express.js docs http://mxs.is/googmy app.use(compression()); app.use(options.output.publicPath, express.static(options.output.path)); app.get('*', (req, res) => res.sendFile(path.join(options.output.path, 'index.html'))); }; /** * Front-end middleware */ module.exports = (options) => { const isProd = process.env.NODE_ENV === 'production'; const app = express(); if (isProd) { addProdMiddlewares(app, options); } else { addDevMiddlewares(app, options); } return app; };
unicesi/pascani-library
web/dashboard/server/middlewares/frontendMiddleware.js
JavaScript
gpl-2.0
1,618
import unittest from PyFoam.Basics.MatplotlibTimelines import MatplotlibTimelines theSuite=unittest.TestSuite()
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam
unittests/Basics/test_MatplotlibTimelines.py
Python
gpl-2.0
114
/* $Id: VBoxUsbRt.cpp $ */ /** @file * VBox USB R0 runtime */ /* * Copyright (C) 2011 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #include "VBoxUsbCmn.h" #include "../cmn/VBoxUsbIdc.h" #include "../cmn/VBoxUsbTool.h" #include <VBox/usblib-win.h> #include <iprt/assert.h> #include <VBox/log.h> #define _USBD_ #define USBD_DEFAULT_PIPE_TRANSFER 0x00000008 #define VBOXUSB_MAGIC 0xABCF1423 typedef struct VBOXUSB_URB_CONTEXT { PURB pUrb; PMDL pMdlBuf; PVBOXUSBDEV_EXT pDevExt; PVOID pOut; ULONG ulTransferType; ULONG ulMagic; } VBOXUSB_URB_CONTEXT, * PVBOXUSB_URB_CONTEXT; typedef struct VBOXUSB_SETUP { uint8_t bmRequestType; uint8_t bRequest; uint16_t wValue; uint16_t wIndex; uint16_t wLength; } VBOXUSB_SETUP, *PVBOXUSB_SETUP; static bool vboxUsbRtCtxSetOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj) { bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, pFObj, NULL); if (bRc) { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) acquired\n", pFObj)); } else { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) FAILED!!\n", pFObj)); } return bRc; } static bool vboxUsbRtCtxReleaseOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj) { bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, NULL, pFObj); if (bRc) { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) released\n", pFObj)); } else { Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) release: is NOT an owner\n", pFObj)); } return bRc; } static bool vboxUsbRtCtxIsOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj) { PFILE_OBJECT pOwner = (PFILE_OBJECT)ASMAtomicReadPtr((void *volatile *)(&pDevExt->Rt.pOwner)); return pOwner == pFObj; } static NTSTATUS vboxUsbRtIdcSubmit(ULONG uCtl, void *pvBuffer) { /* we just reuse the standard usb tooling for simplicity here */ NTSTATUS Status = VBoxUsbToolIoInternalCtlSendSync(g_VBoxUsbGlobals.RtIdc.pDevice, uCtl, pvBuffer, NULL); Assert(Status == STATUS_SUCCESS); return Status; } static NTSTATUS vboxUsbRtIdcInit() { UNICODE_STRING UniName; RtlInitUnicodeString(&UniName, USBMON_DEVICE_NAME_NT); NTSTATUS Status = IoGetDeviceObjectPointer(&UniName, FILE_ALL_ACCESS, &g_VBoxUsbGlobals.RtIdc.pFile, &g_VBoxUsbGlobals.RtIdc.pDevice); if (NT_SUCCESS(Status)) { VBOXUSBIDC_VERSION Version; vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION, &Version); if (NT_SUCCESS(Status)) { if (Version.u32Major == VBOXUSBIDC_VERSION_MAJOR && Version.u32Minor >= VBOXUSBIDC_VERSION_MINOR) return STATUS_SUCCESS; AssertFailed(); } else { AssertFailed(); } /* this will as well dereference the dev obj */ ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile); } else { AssertFailed(); } memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc)); return Status; } static VOID vboxUsbRtIdcTerm() { Assert(g_VBoxUsbGlobals.RtIdc.pFile); Assert(g_VBoxUsbGlobals.RtIdc.pDevice); ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile); memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc)); } static NTSTATUS vboxUsbRtIdcReportDevStart(PDEVICE_OBJECT pPDO, HVBOXUSBIDCDEV *phDev) { VBOXUSBIDC_PROXY_STARTUP Start; Start.u.pPDO = pPDO; *phDev = NULL; NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP, &Start); Assert(Status == STATUS_SUCCESS); if (!NT_SUCCESS(Status)) return Status; *phDev = Start.u.hDev; return STATUS_SUCCESS; } static NTSTATUS vboxUsbRtIdcReportDevStop(HVBOXUSBIDCDEV hDev) { VBOXUSBIDC_PROXY_TEARDOWN Stop; Stop.hDev = hDev; NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN, &Stop); Assert(Status == STATUS_SUCCESS); return Status; } DECLHIDDEN(NTSTATUS) vboxUsbRtGlobalsInit() { return vboxUsbRtIdcInit(); } DECLHIDDEN(VOID) vboxUsbRtGlobalsTerm() { vboxUsbRtIdcTerm(); } DECLHIDDEN(NTSTATUS) vboxUsbRtInit(PVBOXUSBDEV_EXT pDevExt) { RtlZeroMemory(&pDevExt->Rt, sizeof (pDevExt->Rt)); NTSTATUS Status = IoRegisterDeviceInterface(pDevExt->pPDO, &GUID_CLASS_VBOXUSB, NULL, /* IN PUNICODE_STRING ReferenceString OPTIONAL */ &pDevExt->Rt.IfName); Assert(Status == STATUS_SUCCESS); if (NT_SUCCESS(Status)) { Status = vboxUsbRtIdcReportDevStart(pDevExt->pPDO, &pDevExt->Rt.hMonDev); Assert(Status == STATUS_SUCCESS); if (NT_SUCCESS(Status)) { Assert(pDevExt->Rt.hMonDev); return STATUS_SUCCESS; } NTSTATUS tmpStatus = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE); Assert(tmpStatus == STATUS_SUCCESS); if (NT_SUCCESS(tmpStatus)) { RtlFreeUnicodeString(&pDevExt->Rt.IfName); } } return Status; } /** * Free cached USB device/configuration descriptors * * @param pDevExt USB DevExt pointer */ static void vboxUsbRtFreeCachedDescriptors(PVBOXUSBDEV_EXT pDevExt) { if (pDevExt->Rt.devdescr) { vboxUsbMemFree(pDevExt->Rt.devdescr); pDevExt->Rt.devdescr = NULL; } for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i) { if (pDevExt->Rt.cfgdescr[i]) { vboxUsbMemFree(pDevExt->Rt.cfgdescr[i]); pDevExt->Rt.cfgdescr[i] = NULL; } } } /** * Free per-device interface info * * @param pDevExt USB DevExt pointer * @param fAbortPipes If true, also abort any open pipes */ static void vboxUsbRtFreeInterfaces(PVBOXUSBDEV_EXT pDevExt, BOOLEAN fAbortPipes) { unsigned i; unsigned j; /* * Free old interface info */ if (pDevExt->Rt.pVBIfaceInfo) { for (i=0;i<pDevExt->Rt.uNumInterfaces;i++) { if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo) { if (fAbortPipes) { for(j=0; j<pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++) { Log(("Aborting Pipe %d handle %x address %x\n", j, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress)); VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle, FALSE); } } vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo); } pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = NULL; if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo) vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo); pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL; } vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo); pDevExt->Rt.pVBIfaceInfo = NULL; } } DECLHIDDEN(VOID) vboxUsbRtClear(PVBOXUSBDEV_EXT pDevExt) { vboxUsbRtFreeCachedDescriptors(pDevExt); vboxUsbRtFreeInterfaces(pDevExt, FALSE); } DECLHIDDEN(NTSTATUS) vboxUsbRtRm(PVBOXUSBDEV_EXT pDevExt) { if (!pDevExt->Rt.IfName.Buffer) return STATUS_SUCCESS; NTSTATUS Status = vboxUsbRtIdcReportDevStop(pDevExt->Rt.hMonDev); Assert(Status == STATUS_SUCCESS); Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE); Assert(Status == STATUS_SUCCESS); if (NT_SUCCESS(Status)) { RtlFreeUnicodeString(&pDevExt->Rt.IfName); pDevExt->Rt.IfName.Buffer = NULL; } return Status; } DECLHIDDEN(NTSTATUS) vboxUsbRtStart(PVBOXUSBDEV_EXT pDevExt) { NTSTATUS Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, TRUE); Assert(Status == STATUS_SUCCESS); return Status; } static NTSTATUS vboxUsbRtCacheDescriptors(PVBOXUSBDEV_EXT pDevExt) { NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES; // uint32_t uTotalLength; // unsigned i; /* Read device descriptor */ Assert(!pDevExt->Rt.devdescr); pDevExt->Rt.devdescr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_DEVICE_DESCRIPTOR)); if (pDevExt->Rt.devdescr) { memset(pDevExt->Rt.devdescr, 0, sizeof (USB_DEVICE_DESCRIPTOR)); Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.devdescr, sizeof (USB_DEVICE_DESCRIPTOR), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status)) { Assert(pDevExt->Rt.devdescr->bNumConfigurations > 0); PUSB_CONFIGURATION_DESCRIPTOR pDr = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_CONFIGURATION_DESCRIPTOR)); Assert(pDr); if (pDr) { UCHAR i = 0; for (; i < pDevExt->Rt.devdescr->bNumConfigurations; ++i) { Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof (USB_CONFIGURATION_DESCRIPTOR), USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT); if (!NT_SUCCESS(Status)) { break; } USHORT uTotalLength = pDr->wTotalLength; pDevExt->Rt.cfgdescr[i] = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(uTotalLength); if (!pDevExt->Rt.cfgdescr[i]) { Status = STATUS_INSUFFICIENT_RESOURCES; break; } Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.cfgdescr[i], uTotalLength, USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT); if (!NT_SUCCESS(Status)) { break; } } vboxUsbMemFree(pDr); if (NT_SUCCESS(Status)) return Status; /* recources will be freed in vboxUsbRtFreeCachedDescriptors below */ } } vboxUsbRtFreeCachedDescriptors(pDevExt); } /* shoud be only on fail here */ Assert(!NT_SUCCESS(Status)); return Status; } static NTSTATUS vboxUsbRtDispatchClaimDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_CLAIMDEV pDev = (PUSBSUP_CLAIMDEV)pIrp->AssociatedIrp.SystemBuffer; ULONG cbOut = 0; NTSTATUS Status = STATUS_SUCCESS; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if ( !pDev || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pDev) || pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pDev)) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxSetOwner(pDevExt, pFObj)) { AssertFailed(); pDev->fClaimed = false; cbOut = sizeof (*pDev); break; } vboxUsbRtFreeCachedDescriptors(pDevExt); Status = vboxUsbRtCacheDescriptors(pDevExt); if (NT_SUCCESS(Status)) { pDev->fClaimed = true; cbOut = sizeof (*pDev); } } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, cbOut); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchReleaseDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; NTSTATUS Status= STATUS_SUCCESS; if (vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { vboxUsbRtFreeCachedDescriptors(pDevExt); bool bRc = vboxUsbRtCtxReleaseOwner(pDevExt, pFObj); Assert(bRc); } else { AssertFailed(); Status = STATUS_ACCESS_DENIED; } VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0); vboxUsbDdiStateRelease(pDevExt); return STATUS_SUCCESS; } static NTSTATUS vboxUsbRtGetDeviceDescription(PVBOXUSBDEV_EXT pDevExt) { NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES; PUSB_DEVICE_DESCRIPTOR pDr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAllocZ(sizeof (USB_DEVICE_DESCRIPTOR)); if (pDr) { Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof(*pDr), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status)) { pDevExt->Rt.idVendor = pDr->idVendor; pDevExt->Rt.idProduct = pDr->idProduct; pDevExt->Rt.bcdDevice = pDr->bcdDevice; pDevExt->Rt.szSerial[0] = 0; if (pDr->iSerialNumber #ifdef DEBUG || pDr->iProduct || pDr->iManufacturer #endif ) { int langId; Status = VBoxUsbToolGetLangID(pDevExt->pLowerDO, &langId, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status)) { Status = VBoxUsbToolGetStringDescriptorA(pDevExt->pLowerDO, pDevExt->Rt.szSerial, sizeof (pDevExt->Rt.szSerial), pDr->iSerialNumber, langId, RT_INDEFINITE_WAIT); } else { Status = STATUS_SUCCESS; } } } vboxUsbMemFree(pDr); } return Status; } static NTSTATUS vboxUsbRtDispatchGetDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PUSBSUP_GETDEV pDev = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; ULONG cbOut = 0; /* don't check for owner since this request is allowed for non-owners as well */ if (pDev && pSl->Parameters.DeviceIoControl.InputBufferLength == sizeof (*pDev) && pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pDev)) { Status = VBoxUsbToolGetDeviceSpeed(pDevExt->pLowerDO, &pDevExt->Rt.fIsHighSpeed); if (NT_SUCCESS(Status)) { pDev->hDevice = pDevExt->Rt.hMonDev; pDev->fAttached = true; pDev->fHiSpeed = pDevExt->Rt.fIsHighSpeed; cbOut = sizeof (*pDev); } } else { Status = STATUS_INVALID_PARAMETER; } Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, cbOut); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchUsbReset(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_GETDEV pDev = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if (pIrp->AssociatedIrp.SystemBuffer || pSl->Parameters.DeviceIoControl.InputBufferLength || pSl->Parameters.DeviceIoControl.OutputBufferLength) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } Status = VBoxUsbToolIoInternalCtlSendSync(pDevExt->pLowerDO, IOCTL_INTERNAL_USB_RESET_PORT, NULL, NULL); Assert(NT_SUCCESS(Status)); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static PUSB_CONFIGURATION_DESCRIPTOR vboxUsbRtFindConfigDesc(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration) { PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = NULL; for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i) { if (pDevExt->Rt.cfgdescr[i]) { if (pDevExt->Rt.cfgdescr[i]->bConfigurationValue == uConfiguration) { pCfgDr = pDevExt->Rt.cfgdescr[i]; break; } } } return pCfgDr; } static NTSTATUS vboxUsbRtSetConfig(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration) { PURB pUrb = NULL; NTSTATUS Status = STATUS_SUCCESS; uint32_t i; if (!uConfiguration) { pUrb = VBoxUsbToolUrbAllocZ(URB_FUNCTION_SELECT_CONFIGURATION, sizeof (struct _URB_SELECT_CONFIGURATION)); if(!pUrb) { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n")); return STATUS_INSUFFICIENT_RESOURCES; } vboxUsbRtFreeInterfaces(pDevExt, TRUE); pUrb->UrbSelectConfiguration.ConfigurationDescriptor = NULL; Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT); if(NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status)) { pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle; pDevExt->Rt.uConfigValue = uConfiguration; } else { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); } VBoxUsbToolUrbFree(pUrb); return Status; } PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, uConfiguration); if (!pCfgDr) { AssertMsgFailed((__FUNCTION__": VBoxUSBFindConfigDesc did not find cfg (%d)\n", uConfiguration)); return STATUS_INVALID_PARAMETER; } PUSBD_INTERFACE_LIST_ENTRY pIfLe = (PUSBD_INTERFACE_LIST_ENTRY)vboxUsbMemAllocZ((pCfgDr->bNumInterfaces + 1) * sizeof(USBD_INTERFACE_LIST_ENTRY)); if (!pIfLe) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ for pIfLe failed\n")); return STATUS_INSUFFICIENT_RESOURCES; } for (i = 0; i < pCfgDr->bNumInterfaces; i++) { pIfLe[i].InterfaceDescriptor = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, i, 0, -1, -1, -1); if (!pIfLe[i].InterfaceDescriptor) { AssertMsgFailed((__FUNCTION__": interface %d not found\n", i)); Status = STATUS_INVALID_PARAMETER; break; } } if (NT_SUCCESS(Status)) { pUrb = USBD_CreateConfigurationRequestEx(pCfgDr, pIfLe); if (pUrb) { Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status)) { vboxUsbRtFreeInterfaces(pDevExt, FALSE); pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle; pDevExt->Rt.uConfigValue = uConfiguration; pDevExt->Rt.uNumInterfaces = pCfgDr->bNumInterfaces; pDevExt->Rt.pVBIfaceInfo = (VBOXUSB_IFACE_INFO*)vboxUsbMemAllocZ(pDevExt->Rt.uNumInterfaces * sizeof (VBOXUSB_IFACE_INFO)); if (pDevExt->Rt.pVBIfaceInfo) { Assert(NT_SUCCESS(Status)); for (i = 0; i < pDevExt->Rt.uNumInterfaces; i++) { uint32_t uTotalIfaceInfoLength = sizeof (struct _URB_SELECT_INTERFACE) + ((pIfLe[i].Interface->NumberOfPipes > 0) ? (pIfLe[i].Interface->NumberOfPipes - 1) : 0) * sizeof(USBD_PIPE_INFORMATION); pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength); if (!pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; break; } if (pIfLe[i].Interface->NumberOfPipes > 0) { pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = (VBOXUSB_PIPE_INFO *)vboxUsbMemAlloc(pIfLe[i].Interface->NumberOfPipes * sizeof(VBOXUSB_PIPE_INFO)); if (!pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n")); Status = STATUS_NO_MEMORY; break; } } else { pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL; } *pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = *pIfLe[i].Interface; for (ULONG j = 0; j < pIfLe[i].Interface->NumberOfPipes; j++) { pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j] = pIfLe[i].Interface->Pipes[j]; pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress = pIfLe[i].Interface->Pipes[j].EndpointAddress; pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].NextScheduledFrame = 0; } } // if (NT_SUCCESS(Status)) // { // // } } else { AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ failed\n")); Status = STATUS_NO_MEMORY; } } else { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); } ExFreePool(pUrb); } else { AssertMsgFailed((__FUNCTION__": USBD_CreateConfigurationRequestEx failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; } } vboxUsbMemFree(pIfLe); return Status; } static NTSTATUS vboxUsbRtDispatchUsbSetConfig(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_SET_CONFIG pCfg = (PUSBSUP_SET_CONFIG)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pCfg || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCfg) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtSetConfig(pDevExt, pCfg->bConfigurationValue); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtSetInterface(PVBOXUSBDEV_EXT pDevExt, uint32_t InterfaceNumber, int AlternateSetting) { if (!pDevExt->Rt.uConfigValue) { AssertMsgFailed((__FUNCTION__": Can't select an interface without an active configuration\n")); return STATUS_INVALID_PARAMETER; } if (InterfaceNumber >= pDevExt->Rt.uNumInterfaces) { AssertMsgFailed((__FUNCTION__": InterfaceNumber %d too high!!\n", InterfaceNumber)); return STATUS_INVALID_PARAMETER; } PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, pDevExt->Rt.uConfigValue); if (!pCfgDr) { AssertMsgFailed((__FUNCTION__": configuration %d not found!!\n", pDevExt->Rt.uConfigValue)); return STATUS_INVALID_PARAMETER; } PUSB_INTERFACE_DESCRIPTOR pIfDr = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, InterfaceNumber, AlternateSetting, -1, -1, -1); if (!pIfDr) { AssertMsgFailed((__FUNCTION__": invalid interface %d or alternate setting %d\n", InterfaceNumber, AlternateSetting)); return STATUS_UNSUCCESSFUL; } USHORT uUrbSize = GET_SELECT_INTERFACE_REQUEST_SIZE(pIfDr->bNumEndpoints); ULONG uTotalIfaceInfoLength = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints); NTSTATUS Status = STATUS_SUCCESS; PURB pUrb = VBoxUsbToolUrbAllocZ(0, uUrbSize); if (!pUrb) { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n")); return STATUS_NO_MEMORY; } /* * Free old interface and pipe info, allocate new again */ if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo) { /* Clear pipes associated with the interface, else Windows may hang. */ for(ULONG i = 0; i < pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->NumberOfPipes; i++) { VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i].PipeHandle, FALSE); } vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo); } if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo) { vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo); } pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength); if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo) { if (pIfDr->bNumEndpoints > 0) { pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = (VBOXUSB_PIPE_INFO*)vboxUsbMemAlloc(pIfDr->bNumEndpoints * sizeof(VBOXUSB_PIPE_INFO)); if (!pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo) { AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n")); Status = STATUS_NO_MEMORY; } } else { pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = NULL; } if (NT_SUCCESS(Status)) { UsbBuildSelectInterfaceRequest(pUrb, uUrbSize, pDevExt->Rt.hConfiguration, InterfaceNumber, AlternateSetting); pUrb->UrbSelectInterface.Interface.Length = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints); Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT); if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status)) { USBD_INTERFACE_INFORMATION *pIfInfo = &pUrb->UrbSelectInterface.Interface; memcpy(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo, pIfInfo, GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints)); Assert(pIfInfo->NumberOfPipes == pIfDr->bNumEndpoints); for(ULONG i = 0; i < pIfInfo->NumberOfPipes; i++) { pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i] = pIfInfo->Pipes[i]; pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].EndpointAddress = pIfInfo->Pipes[i].EndpointAddress; pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].NextScheduledFrame = 0; } } else { AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x) usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); } } } else { AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n")); Status = STATUS_NO_MEMORY; } VBoxUsbToolUrbFree(pUrb); return Status; } static NTSTATUS vboxUsbRtDispatchUsbSelectInterface(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_SELECT_INTERFACE pIf = (PUSBSUP_SELECT_INTERFACE)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pIf || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pIf) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtSetInterface(pDevExt, pIf->bInterfaceNumber, pIf->bAlternateSetting); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static HANDLE vboxUsbRtGetPipeHandle(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress) { for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++) { for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++) { /* Note that bit 7 determines pipe direction, but is still significant * because endpoints may be numbered like 0x01, 0x81, 0x02, 0x82 etc. */ if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress == EndPointAddress) return pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle; } } return 0; } static VBOXUSB_PIPE_INFO* vboxUsbRtGetPipeInfo(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress) { for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++) { for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++) { if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress == EndPointAddress) return &pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j]; } } return NULL; } static NTSTATUS vboxUsbRtClearEndpoint(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress, bool fReset) { NTSTATUS Status = VBoxUsbToolPipeClear(pDevExt->pLowerDO, vboxUsbRtGetPipeHandle(pDevExt, EndPointAddress), fReset); if (!NT_SUCCESS(Status)) { AssertMsgFailed((__FUNCTION__": VBoxUsbToolPipeClear failed Status (0x%x)\n", Status)); } return Status; } static NTSTATUS vboxUsbRtDispatchUsbClearEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pCe || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, TRUE); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchUsbAbortEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pCe || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe) || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, FALSE); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtUrbSendCompletion(PDEVICE_OBJECT pDevObj, IRP *pIrp, void *pvContext) { if (!pvContext) { AssertMsgFailed((__FUNCTION__": context is NULL\n")); pIrp->IoStatus.Information = 0; return STATUS_CONTINUE_COMPLETION; } PVBOXUSB_URB_CONTEXT pContext = (PVBOXUSB_URB_CONTEXT)pvContext; if (pContext->ulMagic != VBOXUSB_MAGIC) { AssertMsgFailed((__FUNCTION__": Invalid context magic\n")); pIrp->IoStatus.Information = 0; return STATUS_CONTINUE_COMPLETION; } PURB pUrb = pContext->pUrb; PMDL pMdlBuf = pContext->pMdlBuf; PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pContext->pOut; PVBOXUSBDEV_EXT pDevExt = pContext->pDevExt; if (!pUrb || !pMdlBuf || !pUrbInfo | !pDevExt) { AssertMsgFailed((__FUNCTION__": Invalid args\n")); if (pDevExt) vboxUsbDdiStateRelease(pDevExt); pIrp->IoStatus.Information = 0; return STATUS_CONTINUE_COMPLETION; } NTSTATUS Status = pIrp->IoStatus.Status; if (Status == STATUS_SUCCESS) { switch(pUrb->UrbHeader.Status) { case USBD_STATUS_CRC: pUrbInfo->error = USBSUP_XFER_CRC; break; case USBD_STATUS_SUCCESS: pUrbInfo->error = USBSUP_XFER_OK; break; case USBD_STATUS_STALL_PID: pUrbInfo->error = USBSUP_XFER_STALL; break; case USBD_STATUS_INVALID_URB_FUNCTION: case USBD_STATUS_INVALID_PARAMETER: AssertMsgFailed((__FUNCTION__": sw error, urb Status (0x%x)\n", pUrb->UrbHeader.Status)); case USBD_STATUS_DEV_NOT_RESPONDING: default: pUrbInfo->error = USBSUP_XFER_DNR; break; } switch(pContext->ulTransferType) { case USBSUP_TRANSFER_TYPE_CTRL: case USBSUP_TRANSFER_TYPE_MSG: pUrbInfo->len = pUrb->UrbControlTransfer.TransferBufferLength; if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_MSG) { /* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special * the first 8 bytes of the buffer is the setup packet so the real * data length is therefore urb->len - 8 */ pUrbInfo->len += sizeof (pUrb->UrbControlTransfer.SetupPacket); } break; case USBSUP_TRANSFER_TYPE_ISOC: pUrbInfo->len = pUrb->UrbIsochronousTransfer.TransferBufferLength; break; case USBSUP_TRANSFER_TYPE_BULK: case USBSUP_TRANSFER_TYPE_INTR: if (pUrbInfo->dir == USBSUP_DIRECTION_IN && pUrbInfo->error == USBSUP_XFER_OK && !(pUrbInfo->flags & USBSUP_FLAG_SHORT_OK) && pUrbInfo->len > pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength ) { /* If we don't use the USBD_SHORT_TRANSFER_OK flag, the returned buffer lengths are * wrong for short transfers (always a multiple of max packet size?). So we just figure * out if this was a data underrun on our own. */ pUrbInfo->error = USBSUP_XFER_UNDERRUN; } pUrbInfo->len = pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength; break; default: break; } } else { pUrbInfo->len = 0; Log((__FUNCTION__": URB failed Status (0x%x) urb Status (0x%x)\n", Status, pUrb->UrbHeader.Status)); #ifdef DEBUG switch(pContext->ulTransferType) { case USBSUP_TRANSFER_TYPE_CTRL: case USBSUP_TRANSFER_TYPE_MSG: LogRel(("Ctrl/Msg length=%d\n", pUrb->UrbControlTransfer.TransferBufferLength)); break; case USBSUP_TRANSFER_TYPE_ISOC: LogRel(("ISOC length=%d\n", pUrb->UrbIsochronousTransfer.TransferBufferLength)); break; case USBSUP_TRANSFER_TYPE_BULK: case USBSUP_TRANSFER_TYPE_INTR: LogRel(("BULK/INTR length=%d\n", pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength)); break; } #endif switch(pUrb->UrbHeader.Status) { case USBD_STATUS_CRC: pUrbInfo->error = USBSUP_XFER_CRC; Status = STATUS_SUCCESS; break; case USBD_STATUS_STALL_PID: pUrbInfo->error = USBSUP_XFER_STALL; Status = STATUS_SUCCESS; break; case USBD_STATUS_DEV_NOT_RESPONDING: pUrbInfo->error = USBSUP_XFER_DNR; Status = STATUS_SUCCESS; break; case ((USBD_STATUS)0xC0010000L): // USBD_STATUS_CANCELED - too bad usbdi.h and usb.h aren't consistent! // TODO: What the heck are we really supposed to do here? pUrbInfo->error = USBSUP_XFER_STALL; Status = STATUS_SUCCESS; break; case USBD_STATUS_BAD_START_FRAME: // This one really shouldn't happen case USBD_STATUS_ISOCH_REQUEST_FAILED: pUrbInfo->error = USBSUP_XFER_NAC; Status = STATUS_SUCCESS; break; default: AssertMsgFailed((__FUNCTION__": err Status (0x%x) (0x%x)\n", Status, pUrb->UrbHeader.Status)); pUrbInfo->error = USBSUP_XFER_DNR; Status = STATUS_SUCCESS; break; } } // For isochronous transfers, always update the individual packets if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_ISOC) { Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets); for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i) { Assert(pUrbInfo->aIsoPkts[i].off == pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset); pUrbInfo->aIsoPkts[i].cb = (uint16_t)pUrb->UrbIsochronousTransfer.IsoPacket[i].Length; switch (pUrb->UrbIsochronousTransfer.IsoPacket[i].Status) { case USBD_STATUS_SUCCESS: pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_OK; break; case USBD_STATUS_NOT_ACCESSED: pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_NAC; break; default: pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_STALL; break; } } } MmUnlockPages(pMdlBuf); IoFreeMdl(pMdlBuf); vboxUsbMemFree(pContext); vboxUsbDdiStateRelease(pDevExt); Assert(pIrp->IoStatus.Status != STATUS_IO_TIMEOUT); pIrp->IoStatus.Information = sizeof(*pUrbInfo); pIrp->IoStatus.Status = Status; return STATUS_CONTINUE_COMPLETION; } static NTSTATUS vboxUsbRtUrbSend(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp, PUSBSUP_URB pUrbInfo) { NTSTATUS Status = STATUS_SUCCESS; PVBOXUSB_URB_CONTEXT pContext = NULL; PMDL pMdlBuf = NULL; ULONG cbUrb; Assert(pUrbInfo); if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_ISOC) { Assert(pUrbInfo->numIsoPkts <= 8); cbUrb = GET_ISO_URB_SIZE(pUrbInfo->numIsoPkts); } else cbUrb = sizeof (URB); do { pContext = (PVBOXUSB_URB_CONTEXT)vboxUsbMemAllocZ(cbUrb + sizeof (VBOXUSB_URB_CONTEXT)); if (!pContext) { AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; break; } PURB pUrb = (PURB)(pContext + 1); HANDLE hPipe = NULL; if (pUrbInfo->ep) { hPipe = vboxUsbRtGetPipeHandle(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00)); if (!hPipe) { AssertMsgFailed((__FUNCTION__": vboxUsbRtGetPipeHandle failed for endpoint (0x%x)\n", pUrbInfo->ep)); Status = STATUS_INVALID_PARAMETER; break; } } pMdlBuf = IoAllocateMdl(pUrbInfo->buf, (ULONG)pUrbInfo->len, FALSE, FALSE, NULL); if (!pMdlBuf) { AssertMsgFailed((__FUNCTION__": IoAllocateMdl failed for buffer (0x%p) length (%d)\n", pUrbInfo->buf, pUrbInfo->len)); Status = STATUS_INSUFFICIENT_RESOURCES; break; } __try { MmProbeAndLockPages(pMdlBuf, KernelMode, IoModifyAccess); } __except(EXCEPTION_EXECUTE_HANDLER) { Status = GetExceptionCode(); IoFreeMdl(pMdlBuf); pMdlBuf = NULL; AssertMsgFailed((__FUNCTION__": Exception Code (0x%x)\n", Status)); break; } /* For some reason, passing a MDL in the URB does not work reliably. Notably * the iPhone when used with iTunes fails. */ PVOID pBuffer = MmGetSystemAddressForMdlSafe(pMdlBuf, NormalPagePriority); if (!pBuffer) { AssertMsgFailed((__FUNCTION__": MmGetSystemAddressForMdlSafe failed\n")); Status = STATUS_INSUFFICIENT_RESOURCES; break; } switch (pUrbInfo->type) { case USBSUP_TRANSFER_TYPE_CTRL: case USBSUP_TRANSFER_TYPE_MSG: { pUrb->UrbHeader.Function = URB_FUNCTION_CONTROL_TRANSFER; pUrb->UrbHeader.Length = sizeof (struct _URB_CONTROL_TRANSFER); pUrb->UrbControlTransfer.PipeHandle = hPipe; pUrb->UrbControlTransfer.TransferBufferLength = (ULONG)pUrbInfo->len; pUrb->UrbControlTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT); pUrb->UrbControlTransfer.UrbLink = 0; if (!hPipe) pUrb->UrbControlTransfer.TransferFlags |= USBD_DEFAULT_PIPE_TRANSFER; if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_MSG) { /* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special * the first 8 bytes of the buffer is the setup packet so the real * data length is therefore pUrb->len - 8 */ PVBOXUSB_SETUP pSetup = (PVBOXUSB_SETUP)pUrb->UrbControlTransfer.SetupPacket; memcpy(pUrb->UrbControlTransfer.SetupPacket, pBuffer, min(sizeof (pUrb->UrbControlTransfer.SetupPacket), pUrbInfo->len)); if (pUrb->UrbControlTransfer.TransferBufferLength <= sizeof (pUrb->UrbControlTransfer.SetupPacket)) pUrb->UrbControlTransfer.TransferBufferLength = 0; else pUrb->UrbControlTransfer.TransferBufferLength -= sizeof (pUrb->UrbControlTransfer.SetupPacket); pUrb->UrbControlTransfer.TransferBuffer = (uint8_t *)pBuffer + sizeof(pUrb->UrbControlTransfer.SetupPacket); pUrb->UrbControlTransfer.TransferBufferMDL = 0; pUrb->UrbControlTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK; } else { pUrb->UrbControlTransfer.TransferBuffer = 0; pUrb->UrbControlTransfer.TransferBufferMDL = pMdlBuf; } break; } case USBSUP_TRANSFER_TYPE_ISOC: { Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK); Assert(hPipe); VBOXUSB_PIPE_INFO *pPipeInfo = vboxUsbRtGetPipeInfo(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00)); if (pPipeInfo == NULL) { /* Can happen if the isoc request comes in too early or late. */ AssertMsgFailed((__FUNCTION__": pPipeInfo not found\n")); Status = STATUS_INVALID_PARAMETER; break; } pUrb->UrbHeader.Function = URB_FUNCTION_ISOCH_TRANSFER; pUrb->UrbHeader.Length = (USHORT)cbUrb; pUrb->UrbIsochronousTransfer.PipeHandle = hPipe; pUrb->UrbIsochronousTransfer.TransferBufferLength = (ULONG)pUrbInfo->len; pUrb->UrbIsochronousTransfer.TransferBufferMDL = 0; pUrb->UrbIsochronousTransfer.TransferBuffer = pBuffer; pUrb->UrbIsochronousTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT); pUrb->UrbIsochronousTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK; // May be implied already pUrb->UrbIsochronousTransfer.NumberOfPackets = pUrbInfo->numIsoPkts; pUrb->UrbIsochronousTransfer.ErrorCount = 0; pUrb->UrbIsochronousTransfer.UrbLink = 0; Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets); for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i) { pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset = pUrbInfo->aIsoPkts[i].off; pUrb->UrbIsochronousTransfer.IsoPacket[i].Length = pUrbInfo->aIsoPkts[i].cb; } /* We have to schedule the URBs ourselves. There is an ASAP flag but * that can only be reliably used after pipe creation/reset, ie. it's * almost completely useless. */ ULONG iFrame, iStartFrame; VBoxUsbToolCurrentFrame(pDevExt->pLowerDO, pIrp, &iFrame); iFrame += 2; iStartFrame = pPipeInfo->NextScheduledFrame; if ((iFrame < iStartFrame) || (iStartFrame > iFrame + 512)) iFrame = iStartFrame; pPipeInfo->NextScheduledFrame = iFrame + pUrbInfo->numIsoPkts; pUrb->UrbIsochronousTransfer.StartFrame = iFrame; break; } case USBSUP_TRANSFER_TYPE_BULK: case USBSUP_TRANSFER_TYPE_INTR: { Assert(pUrbInfo->dir != USBSUP_DIRECTION_SETUP); Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK); Assert(hPipe); pUrb->UrbHeader.Function = URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER; pUrb->UrbHeader.Length = sizeof (struct _URB_BULK_OR_INTERRUPT_TRANSFER); pUrb->UrbBulkOrInterruptTransfer.PipeHandle = hPipe; pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength = (ULONG)pUrbInfo->len; pUrb->UrbBulkOrInterruptTransfer.TransferBufferMDL = 0; pUrb->UrbBulkOrInterruptTransfer.TransferBuffer = pBuffer; pUrb->UrbBulkOrInterruptTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT); if (pUrb->UrbBulkOrInterruptTransfer.TransferFlags & USBD_TRANSFER_DIRECTION_IN) pUrb->UrbBulkOrInterruptTransfer.TransferFlags |= (USBD_SHORT_TRANSFER_OK); pUrb->UrbBulkOrInterruptTransfer.UrbLink = 0; break; } default: { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } } if (!NT_SUCCESS(Status)) { break; } pContext->pDevExt = pDevExt; pContext->pMdlBuf = pMdlBuf; pContext->pUrb = pUrb; pContext->pOut = pUrbInfo; pContext->ulTransferType = pUrbInfo->type; pContext->ulMagic = VBOXUSB_MAGIC; PIO_STACK_LOCATION pSl = IoGetNextIrpStackLocation(pIrp); pSl->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; pSl->Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB; pSl->Parameters.Others.Argument1 = pUrb; pSl->Parameters.Others.Argument2 = NULL; IoSetCompletionRoutine(pIrp, vboxUsbRtUrbSendCompletion, pContext, TRUE, TRUE, TRUE); IoMarkIrpPending(pIrp); Status = IoCallDriver(pDevExt->pLowerDO, pIrp); AssertMsg(NT_SUCCESS(Status), (__FUNCTION__": IoCallDriver failed Status (0x%x)\n", Status)); return STATUS_PENDING; } while (0); Assert(!NT_SUCCESS(Status)); if (pMdlBuf) { MmUnlockPages(pMdlBuf); IoFreeMdl(pMdlBuf); } if (pContext) vboxUsbMemFree(pContext); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchSendUrb(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status; do { if (!pFObj) { AssertFailed(); Status = STATUS_INVALID_PARAMETER; break; } if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj)) { AssertFailed(); Status = STATUS_ACCESS_DENIED; break; } if ( !pUrbInfo || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pUrbInfo) || pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pUrbInfo)) { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; break; } return vboxUsbRtUrbSend(pDevExt, pIrp, pUrbInfo); } while (0); Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, 0); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchIsOperational(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0); vboxUsbDdiStateRelease(pDevExt); return STATUS_SUCCESS; } static NTSTATUS vboxUsbRtDispatchGetVersion(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PUSBSUP_VERSION pVer= (PUSBSUP_VERSION)pIrp->AssociatedIrp.SystemBuffer; NTSTATUS Status = STATUS_SUCCESS; if (pVer && pSl->Parameters.DeviceIoControl.InputBufferLength == 0 && pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pVer)) { pVer->u32Major = USBDRV_MAJOR_VERSION; pVer->u32Minor = USBDRV_MINOR_VERSION; } else { AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n")); Status = STATUS_INVALID_PARAMETER; } Assert(Status != STATUS_PENDING); VBoxDrvToolIoComplete(pIrp, Status, sizeof (*pVer)); vboxUsbDdiStateRelease(pDevExt); return Status; } static NTSTATUS vboxUsbRtDispatchDefault(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { VBoxDrvToolIoComplete(pIrp, STATUS_INVALID_DEVICE_REQUEST, 0); vboxUsbDdiStateRelease(pDevExt); return STATUS_INVALID_DEVICE_REQUEST; } DECLHIDDEN(NTSTATUS) vboxUsbRtCreate(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; if (!pFObj) { AssertFailed(); return STATUS_INVALID_PARAMETER; } return STATUS_SUCCESS; } DECLHIDDEN(NTSTATUS) vboxUsbRtClose(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); PFILE_OBJECT pFObj = pSl->FileObject; Assert(pFObj); vboxUsbRtCtxReleaseOwner(pDevExt, pFObj); return STATUS_SUCCESS; } DECLHIDDEN(NTSTATUS) vboxUsbRtDispatch(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp) { PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp); switch (pSl->Parameters.DeviceIoControl.IoControlCode) { case SUPUSB_IOCTL_USB_CLAIM_DEVICE: { return vboxUsbRtDispatchClaimDevice(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_RELEASE_DEVICE: { return vboxUsbRtDispatchReleaseDevice(pDevExt, pIrp); } case SUPUSB_IOCTL_GET_DEVICE: { return vboxUsbRtDispatchGetDevice(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_RESET: { return vboxUsbRtDispatchUsbReset(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_SET_CONFIG: { return vboxUsbRtDispatchUsbSetConfig(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_SELECT_INTERFACE: { return vboxUsbRtDispatchUsbSelectInterface(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_CLEAR_ENDPOINT: { return vboxUsbRtDispatchUsbClearEndpoint(pDevExt, pIrp); } case SUPUSB_IOCTL_USB_ABORT_ENDPOINT: { return vboxUsbRtDispatchUsbAbortEndpoint(pDevExt, pIrp); } case SUPUSB_IOCTL_SEND_URB: { return vboxUsbRtDispatchSendUrb(pDevExt, pIrp); } case SUPUSB_IOCTL_IS_OPERATIONAL: { return vboxUsbRtDispatchIsOperational(pDevExt, pIrp); } case SUPUSB_IOCTL_GET_VERSION: { return vboxUsbRtDispatchGetVersion(pDevExt, pIrp); } default: { return vboxUsbRtDispatchDefault(pDevExt, pIrp); } } }
evanphx/yoke
src/VBox/HostDrivers/VBoxUSB/win/dev/VBoxUsbRt.cpp
C++
gpl-2.0
55,450
#ifndef _ASM_X86_ELF_H #define _ASM_X86_ELF_H /* * ELF register definitions.. */ #include <asm/ptrace.h> #include <asm/user.h> #include <asm/auxvec.h> typedef unsigned long elf_greg_t; #define ELF_NGREG (sizeof(struct user_regs_struct) / sizeof(elf_greg_t)) typedef elf_greg_t elf_gregset_t[ELF_NGREG]; typedef struct user_i387_struct elf_fpregset_t; #ifdef __i386__ typedef struct user_fxsr_struct elf_fpxregset_t; #define R_386_NONE 0 #define R_386_32 1 #define R_386_PC32 2 #define R_386_GOT32 3 #define R_386_PLT32 4 #define R_386_COPY 5 #define R_386_GLOB_DAT 6 #define R_386_JMP_SLOT 7 #define R_386_RELATIVE 8 #define R_386_GOTOFF 9 #define R_386_GOTPC 10 #define R_386_NUM 11 /* * These are used to set parameters in the core dumps. */ #define ELF_CLASS ELFCLASS32 #define ELF_DATA ELFDATA2LSB #define ELF_ARCH EM_386 #else /* x86-64 relocation types */ #define R_X86_64_NONE 0 /* No reloc */ #define R_X86_64_64 1 /* Direct 64 bit */ #define R_X86_64_PC32 2 /* PC relative 32 bit signed */ #define R_X86_64_GOT32 3 /* 32 bit GOT entry */ #define R_X86_64_PLT32 4 /* 32 bit PLT address */ #define R_X86_64_COPY 5 /* Copy symbol at runtime */ #define R_X86_64_GLOB_DAT 6 /* Create GOT entry */ #define R_X86_64_JUMP_SLOT 7 /* Create PLT entry */ #define R_X86_64_RELATIVE 8 /* Adjust by program base */ #define R_X86_64_GOTPCREL 9 /* 32 bit signed pc relative offset to GOT */ #define R_X86_64_32 10 /* Direct 32 bit zero extended */ #define R_X86_64_32S 11 /* Direct 32 bit sign extended */ #define R_X86_64_16 12 /* Direct 16 bit zero extended */ #define R_X86_64_PC16 13 /* 16 bit sign extended pc relative */ #define R_X86_64_8 14 /* Direct 8 bit sign extended */ #define R_X86_64_PC8 15 /* 8 bit sign extended pc relative */ #define R_X86_64_NUM 16 /* * These are used to set parameters in the core dumps. */ #define ELF_CLASS ELFCLASS64 #define ELF_DATA ELFDATA2LSB #define ELF_ARCH EM_X86_64 #endif #include <asm/vdso.h> extern unsigned int vdso_enabled; /* * This is used to ensure we don't load something for the wrong architecture. */ #define elf_check_arch_ia32(x) \ (((x)->e_machine == EM_386) || ((x)->e_machine == EM_486)) #include <asm/processor.h> #include <asm/system.h> #ifdef CONFIG_X86_32 #include <asm/desc.h> #define elf_check_arch(x) elf_check_arch_ia32(x) /* SVR4/i386 ABI (pages 3-31, 3-32) says that when the program starts %edx contains a pointer to a function which might be registered using `atexit'. This provides a mean for the dynamic linker to call DT_FINI functions for shared libraries that have been loaded before the code runs. A value of 0 tells we have no such handler. We might as well make sure everything else is cleared too (except for %esp), just to make things more deterministic. */ #define ELF_PLAT_INIT(_r, load_addr) \ do { \ _r->bx = 0; _r->cx = 0; _r->dx = 0; \ _r->si = 0; _r->di = 0; _r->bp = 0; \ _r->ax = 0; \ } while (0) /* * regs is struct pt_regs, pr_reg is elf_gregset_t (which is * now struct_user_regs, they are different) */ #define ELF_CORE_COPY_REGS_COMMON(pr_reg, regs) \ do { \ pr_reg[0] = regs->bx; \ pr_reg[1] = regs->cx; \ pr_reg[2] = regs->dx; \ pr_reg[3] = regs->si; \ pr_reg[4] = regs->di; \ pr_reg[5] = regs->bp; \ pr_reg[6] = regs->ax; \ pr_reg[7] = regs->ds & 0xffff; \ pr_reg[8] = regs->es & 0xffff; \ pr_reg[9] = regs->fs & 0xffff; \ pr_reg[11] = regs->orig_ax; \ pr_reg[12] = regs->ip; \ pr_reg[13] = regs->cs & 0xffff; \ pr_reg[14] = regs->flags; \ pr_reg[15] = regs->sp; \ pr_reg[16] = regs->ss & 0xffff; \ } while (0); #define ELF_CORE_COPY_REGS(pr_reg, regs) \ do { \ ELF_CORE_COPY_REGS_COMMON(pr_reg, regs);\ pr_reg[10] = get_user_gs(regs); \ } while (0); #define ELF_CORE_COPY_KERNEL_REGS(pr_reg, regs) \ do { \ ELF_CORE_COPY_REGS_COMMON(pr_reg, regs);\ savesegment(gs, pr_reg[10]); \ } while (0); #define ELF_PLATFORM (utsname()->machine) #define set_personality_64bit() do { } while (0) #else /* CONFIG_X86_32 */ /* * This is used to ensure we don't load something for the wrong architecture. */ #define elf_check_arch(x) \ ((x)->e_machine == EM_X86_64) #define compat_elf_check_arch(x) elf_check_arch_ia32(x) static inline void elf_common_init(struct thread_struct *t, struct pt_regs *regs, const u16 ds) { regs->ax = regs->bx = regs->cx = regs->dx = 0; regs->si = regs->di = regs->bp = 0; regs->r8 = regs->r9 = regs->r10 = regs->r11 = 0; regs->r12 = regs->r13 = regs->r14 = regs->r15 = 0; t->fs = t->gs = 0; t->fsindex = t->gsindex = 0; t->ds = t->es = ds; } #define ELF_PLAT_INIT(_r, load_addr) \ elf_common_init(&current->thread, _r, 0) #define COMPAT_ELF_PLAT_INIT(regs, load_addr) \ elf_common_init(&current->thread, regs, __USER_DS) void start_thread_ia32(struct pt_regs *regs, u32 new_ip, u32 new_sp); #define compat_start_thread start_thread_ia32 void set_personality_ia32(void); #define COMPAT_SET_PERSONALITY(ex) set_personality_ia32() #define COMPAT_ELF_PLATFORM ("i686") /* * regs is struct pt_regs, pr_reg is elf_gregset_t (which is * now struct_user_regs, they are different). Assumes current is the process * getting dumped. */ #define ELF_CORE_COPY_REGS(pr_reg, regs) \ do { \ unsigned v; \ (pr_reg)[0] = (regs)->r15; \ (pr_reg)[1] = (regs)->r14; \ (pr_reg)[2] = (regs)->r13; \ (pr_reg)[3] = (regs)->r12; \ (pr_reg)[4] = (regs)->bp; \ (pr_reg)[5] = (regs)->bx; \ (pr_reg)[6] = (regs)->r11; \ (pr_reg)[7] = (regs)->r10; \ (pr_reg)[8] = (regs)->r9; \ (pr_reg)[9] = (regs)->r8; \ (pr_reg)[10] = (regs)->ax; \ (pr_reg)[11] = (regs)->cx; \ (pr_reg)[12] = (regs)->dx; \ (pr_reg)[13] = (regs)->si; \ (pr_reg)[14] = (regs)->di; \ (pr_reg)[15] = (regs)->orig_ax; \ (pr_reg)[16] = (regs)->ip; \ (pr_reg)[17] = (regs)->cs; \ (pr_reg)[18] = (regs)->flags; \ (pr_reg)[19] = (regs)->sp; \ (pr_reg)[20] = (regs)->ss; \ (pr_reg)[21] = current->thread.fs; \ (pr_reg)[22] = current->thread.gs; \ asm("movl %%ds,%0" : "=r" (v)); (pr_reg)[23] = v; \ asm("movl %%es,%0" : "=r" (v)); (pr_reg)[24] = v; \ asm("movl %%fs,%0" : "=r" (v)); (pr_reg)[25] = v; \ asm("movl %%gs,%0" : "=r" (v)); (pr_reg)[26] = v; \ } while (0); /* I'm not sure if we can use '-' here */ #define ELF_PLATFORM ("x86_64") extern void set_personality_64bit(void); extern unsigned int sysctl_vsyscall32; extern int force_personality32; #endif /* !CONFIG_X86_32 */ #define CORE_DUMP_USE_REGSET #define ELF_EXEC_PAGESIZE 4096 /* This is the location that an ET_DYN program is loaded if exec'ed. Typical use of this is to invoke "./ld.so someprog" to test out a new version of the loader. We need to make sure that it is out of the way of the program that it will "exec", and that there is sufficient room for the brk. */ #ifdef CONFIG_PAX_SEGMEXEC #define ELF_ET_DYN_BASE ((current->mm->pax_flags & MF_PAX_SEGMEXEC) ? SEGMEXEC_TASK_SIZE/3*2 : TASK_SIZE/3*2) #else #define ELF_ET_DYN_BASE (TASK_SIZE / 3 * 2) #endif #ifdef CONFIG_PAX_ASLR #ifdef CONFIG_X86_32 #define PAX_ELF_ET_DYN_BASE 0x10000000UL #define PAX_DELTA_MMAP_LEN (current->mm->pax_flags & MF_PAX_SEGMEXEC ? 15 : 16) #define PAX_DELTA_STACK_LEN (current->mm->pax_flags & MF_PAX_SEGMEXEC ? 15 : 16) #else #define PAX_ELF_ET_DYN_BASE 0x400000UL #define PAX_DELTA_MMAP_LEN ((test_thread_flag(TIF_IA32)) ? 16 : TASK_SIZE_MAX_SHIFT - PAGE_SHIFT - 3) #define PAX_DELTA_STACK_LEN ((test_thread_flag(TIF_IA32)) ? 16 : TASK_SIZE_MAX_SHIFT - PAGE_SHIFT - 3) #endif #endif /* This yields a mask that user programs can use to figure out what instruction set this CPU supports. This could be done in user space, but it's not easy, and we've already done it here. */ #define ELF_HWCAP (boot_cpu_data.x86_capability[0]) /* This yields a string that ld.so will use to load implementation specific libraries for optimization. This is more specific in intent than poking at uname or /proc/cpuinfo. For the moment, we have only optimizations for the Intel generations, but that could change... */ #define SET_PERSONALITY(ex) set_personality_64bit() /* * An executable for which elf_read_implies_exec() returns TRUE will * have the READ_IMPLIES_EXEC personality flag set automatically. */ #define elf_read_implies_exec(ex, executable_stack) \ (executable_stack != EXSTACK_DISABLE_X) struct task_struct; #define ARCH_DLINFO_IA32(vdso_enabled) \ do { \ if (vdso_enabled) { \ NEW_AUX_ENT(AT_SYSINFO, VDSO_ENTRY); \ NEW_AUX_ENT(AT_SYSINFO_EHDR, VDSO_CURRENT_BASE); \ } \ } while (0) #ifdef CONFIG_X86_32 #define STACK_RND_MASK (0x7ff) #define VDSO_HIGH_BASE (__fix_to_virt(FIX_VDSO)) #define ARCH_DLINFO ARCH_DLINFO_IA32(vdso_enabled) /* update AT_VECTOR_SIZE_ARCH if the number of NEW_AUX_ENT entries changes */ #else /* CONFIG_X86_32 */ #define VDSO_HIGH_BASE 0xffffe000U /* CONFIG_COMPAT_VDSO address */ /* 1GB for 64bit, 8MB for 32bit */ #define STACK_RND_MASK (test_thread_flag(TIF_IA32) ? 0x7ff : 0x3fffff) #define ARCH_DLINFO \ do { \ NEW_AUX_ENT(AT_SYSINFO_EHDR, current->mm->context.vdso); \ } while (0) #define AT_SYSINFO 32 #define COMPAT_ARCH_DLINFO ARCH_DLINFO_IA32(sysctl_vsyscall32) #define COMPAT_ELF_ET_DYN_BASE (TASK_UNMAPPED_BASE + 0x1000000) #endif /* !CONFIG_X86_32 */ #define VDSO_CURRENT_BASE (current->mm->context.vdso) #define VDSO_ENTRY \ ((unsigned long)VDSO32_SYMBOL(VDSO_CURRENT_BASE, vsyscall)) struct linux_binprm; #define ARCH_HAS_SETUP_ADDITIONAL_PAGES 1 extern int arch_setup_additional_pages(struct linux_binprm *bprm, int uses_interp); extern int syscall32_setup_pages(struct linux_binprm *, int exstack); #define compat_arch_setup_additional_pages syscall32_setup_pages #endif /* _ASM_X86_ELF_H */
renaudallard/gnexus_kernel
arch/x86/include/asm/elf.h
C
gpl-2.0
9,887
//----------------------------------------------------------------------------- // // Vampire - A code for atomistic simulation of magnetic materials // // Copyright (C) 2009-2012 R.F.L.Evans // // Email:richard.evans@york.ac.uk // // 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. // // ---------------------------------------------------------------------------- // // Headers #include "errors.hpp" #include "demag.hpp" #include "voronoi.hpp" #include "material.hpp" #include "sim.hpp" #include "random.hpp" #include "vio.hpp" #include "vmath.hpp" #include "vmpi.hpp" #include <cmath> #include <iostream> #include <sstream> //========================================================== // Namespace material_parameters //========================================================== namespace mp{ //---------------------------------- // Material Container //---------------------------------- //const int max_materials=100; int num_materials=1; std::vector <materials_t> material(1); //---------------------------------- //Input Integration parameters //---------------------------------- double dt_SI; double gamma_SI = 1.76E11; //---------------------------------- //Derived Integration parameters //---------------------------------- double dt; double half_dt; // Unrolled material parameters for speed std::vector <double> MaterialMuSSIArray(0); std::vector <zkval_t> MaterialScalarAnisotropyArray(0); std::vector <zkten_t> MaterialTensorAnisotropyArray(0); std::vector <double> material_second_order_anisotropy_constant_array(0); std::vector <double> material_sixth_order_anisotropy_constant_array(0); std::vector <double> material_spherical_harmonic_constants_array(0); std::vector <double> MaterialCubicAnisotropyArray(0); /// /// @brief Function to initialise program variables prior to system creation. /// /// @section License /// Use of this code, either in source or compiled form, is subject to license from the authors. /// Copyright \htmlonly &copy \endhtmlonly Richard Evans, 2009-2010. All Rights Reserved. /// /// @section Information /// @author Richard Evans, rfle500@york.ac.uk /// @version 1.0 /// @date 19/01/2010 /// /// @param[in] infile Main input file name for system initialisation /// @return EXIT_SUCCESS /// /// @internal /// Created: 19/01/2010 /// Revision: --- ///===================================================================================== /// int initialise(std::string const infile){ //---------------------------------------------------------- // check calling of routine if error checking is activated //---------------------------------------------------------- if(err::check==true){std::cout << "initialise_variables has been called" << std::endl;} if(vmpi::my_rank==0){ std::cout << "================================================================================" << std::endl; std::cout << "Initialising system variables" << std::endl; } // Setup default system settings mp::default_system(); // Read values from input files int iostat = vin::read(infile); if(iostat==EXIT_FAILURE){ terminaltextcolor(RED); std::cerr << "Error - input file \'" << infile << "\' not found, exiting" << std::endl; terminaltextcolor(WHITE); err::vexit(); } // Print out material properties //mp::material[0].print(); // Check for keyword parameter overide if(cs::single_spin==true){ mp::single_spin_system(); } // Set derived system parameters mp::set_derived_parameters(); // Return return EXIT_SUCCESS; } int default_system(){ // Initialise system creation flags to zero for (int i=0;i<10;i++){ cs::system_creation_flags[i] = 0; sim::hamiltonian_simulation_flags[i] = 0; } // Set system dimensions !Angstroms cs::unit_cell_size[0] = 3.0; cs::unit_cell_size[1] = 3.0; cs::unit_cell_size[2] = 3.0; cs::system_dimensions[0] = 100.0; cs::system_dimensions[1] = 100.0; cs::system_dimensions[2] = 100.0; cs::particle_scale = 50.0; cs::particle_spacing = 10.0; cs::particle_creation_parity=0; cs::crystal_structure = "sc"; // Voronoi Variables create_voronoi::voronoi_sd=0.1; create_voronoi::parity=0; // Setup Hamiltonian Flags sim::hamiltonian_simulation_flags[0] = 1; /// Exchange sim::hamiltonian_simulation_flags[1] = 1; /// Anisotropy sim::hamiltonian_simulation_flags[2] = 1; /// Applied sim::hamiltonian_simulation_flags[3] = 1; /// Thermal sim::hamiltonian_simulation_flags[4] = 0; /// Dipolar //Integration parameters dt_SI = 1.0e-15; // seconds dt = dt_SI*mp::gamma_SI; // Must be set before Hth half_dt = 0.5*dt; //------------------------------------------------------------------------------ // Material Definitions //------------------------------------------------------------------------------ num_materials=1; material.resize(num_materials); //------------------------------------------------------- // Material 0 //------------------------------------------------------- material[0].name="Co"; material[0].alpha=0.1; material[0].Jij_matrix_SI[0]=-11.2e-21; material[0].mu_s_SI=1.5*9.27400915e-24; material[0].Ku1_SI=-4.644e-24; material[0].gamma_rel=1.0; material[0].element="Ag "; // Disable Error Checking err::check=false; // Initialise random number generator mtrandom::grnd.seed(2106975519); return EXIT_SUCCESS; } int single_spin_system(){ // Reset system creation flags to zero for (int i=0;i<10;i++){ cs::system_creation_flags[i] = 0; } // Set system dimensions !Angstroms cs::unit_cell_size[0] = 3.0; cs::unit_cell_size[1] = 3.0; cs::unit_cell_size[2] = 3.0; cs::system_dimensions[0] = 2.0; cs::system_dimensions[1] = 2.0; cs::system_dimensions[2] = 2.0; cs::particle_scale = 50.0; cs::particle_spacing = 10.0; cs::particle_creation_parity=0; cs::crystal_structure = "sc"; // Turn off multi-spin Flags sim::hamiltonian_simulation_flags[0] = 0; /// Exchange sim::hamiltonian_simulation_flags[4] = 0; /// Dipolar // MPI Mode (Homogeneous execution) //vmpi::mpi_mode=0; //mpi_create_variables::mpi_interaction_range=2; // Unit cells //mpi_create_variables::mpi_comms_identify=false; return EXIT_SUCCESS; } // Simple function to check for valid input for hysteresis loop parameters void check_hysteresis_loop_parameters(){ // Only applies to hysteresis loop programs, all others return if(sim::program!=12) return; double min=sim::Hmin; double max=sim::Hmax; double inc=sim::Hinc; // + + + if(min>=0 && max>=0 && inc>0){ if(max<min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both positive, but minimum > maximum with a positive increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both positive, but minimum > maximum with a positive increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } // + + - else if(min>=0 && max>=0 && inc<0){ if(max>min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both positive, but maximum > minimum with a negative increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both positive, but maximum > minimum with a negative increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } // + - + else if(min>=0 && max<0 && inc>0){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum field is positive and maximum field is negative with a positive increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum field is positive and maximum field is negative with a positive increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } // - + - else if(min<0 && max>=0 && inc<0){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum field is negative and maximum field is positive with a negative increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum field is negative and maximum field is positive with a negative increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } // - - - else if(min<0 && max<0 && inc<0){ if(max>min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both negative, but minimum < maximum with a negative increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both negative, but minimum < maximum with a negative increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } // - - + else if(min<0 && max<0 && inc>0){ if(max<min){ if(vmpi::my_rank==0){ terminaltextcolor(RED); std::cout << "Error in hysteresis-loop parameters:" << std::endl; std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl; std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl; std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl; std::cout << "Minimum and maximum fields are both negative, but maximum < minimum with a positive increment, causing an infinite loop. Exiting." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl; zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl; zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl; zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl; zlog << zTs() << "Minimum and maximum fields are both positive, but maximum < minimum with a positive increment, causing an infinite loop. Exiting." << std::endl; err::vexit(); } } } return; } int set_derived_parameters(){ // Set integration constants mp::dt = mp::dt_SI*mp::gamma_SI; // Must be set before Hth mp::half_dt = 0.5*mp::dt; // Check to see if field direction is set by angle if(sim::applied_field_set_by_angle){ sim::H_vec[0]=sin(sim::applied_field_angle_phi*M_PI/180.0)*cos(sim::applied_field_angle_theta*M_PI/180.0); sim::H_vec[1]=sin(sim::applied_field_angle_phi*M_PI/180.0)*sin(sim::applied_field_angle_theta*M_PI/180.0); sim::H_vec[2]=cos(sim::applied_field_angle_phi*M_PI/180.0); } // Check for valid particle array offsets if(cs::particle_array_offset_x >= cs::system_dimensions[0]){ terminaltextcolor(RED); std::cerr << "Warning: requested particle-array-offset-x is greater than system dimensions." << std::endl; std::cerr << "Info: This will probably lead to no particles being created and generate an error." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Warning: requested particle-array-offset-x is greater than system dimensions." << std::endl; zlog << zTs() << "Info: This will probably lead to no particles being created and generate an error." << std::endl; } if(cs::particle_array_offset_y >= cs::system_dimensions[1]){ terminaltextcolor(RED); std::cerr << "Warning: requested particle-array-offset-y is greater than system dimensions." << std::endl; std::cerr << "Info: This will probably lead to no particles being created and generate an error." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Warning: requested particle-array-offset-y is greater than system dimensions." << std::endl; zlog << zTs() << "Info: This will probably lead to no particles being created and generate an error." << std::endl; } check_hysteresis_loop_parameters(); // Ensure H vector is unit length // **RE edit 21.11.12 - no longer necessary as value checked on user input** //double mod_H=1.0/sqrt(sim::H_vec[0]*sim::H_vec[0]+sim::H_vec[1]*sim::H_vec[1]+sim::H_vec[2]*sim::H_vec[2]); //sim::H_vec[0]*=mod_H; //sim::H_vec[1]*=mod_H; //sim::H_vec[2]*=mod_H; // Calculate moment, magnetisation, and anisotropy constants /*for(int mat=0;mat<mp::num_materials;mat++){ double V=cs::unit_cell_size[0]*cs::unit_cell_size[1]*cs::unit_cell_size[2]; // Set magnetisation from mu_s and a if(material[mat].moment_flag==true){ //material[mat].magnetisation=num_atoms_per_unit_cell*material[mat].mu_s_SI/V; } // Set mu_s from magnetisation and a else { //material[mat].mu_s_SI=material[mat].magnetisation*V/num_atoms_per_unit_cell; } // Set K as energy/atom if(material[mat].anis_flag==false){ material[mat].Ku1_SI=material[mat].Ku1_SI*V/num_atoms_per_unit_cell; std::cout << "setting " << material[mat].Ku1_SI << std::endl; } }*/ const string blank=""; // Check for symmetry of exchange matrix for(int mi = 0; mi < mp::num_materials; mi++){ for(int mj = 0; mj < mp::num_materials; mj++){ // Check for non-zero value (avoids divide by zero) if(fabs(material[mi].Jij_matrix_SI[mj]) > 0.0){ // Calculate ratio of i->j / j-> exchange constants double ratio = material[mj].Jij_matrix_SI[mi]/material[mi].Jij_matrix_SI[mj]; // Check that ratio ~ 1.0 for symmetric exchange interactions if( (ratio < 0.99999) || (ratio > 1.00001) ){ // Error found - report to user and terminate program terminaltextcolor(RED); std::cerr << "Error! Non-symmetric exchange interactions for materials " << mi+1 << " and " << mj+1 << ". Exiting" << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Error! Non-symmetric exchange interactions for materials " << mi+1 << " and " << mj+1 << std::endl; zlog << zTs() << "\tmaterial[" << mi+1 << "]:exchange-matrix[" << mj+1 << "] = " << material[mi].Jij_matrix_SI[mj] << std::endl; zlog << zTs() << "\tmaterial[" << mj+1 << "]:exchange-matrix[" << mi+1 << "] = " << material[mj].Jij_matrix_SI[mi] << std::endl; zlog << zTs() << "\tThe definition of Heisenberg exchange requires that these values are the same. Exiting." << std::endl; err::vexit(); } } } } // Set derived material parameters for(int mat=0;mat<mp::num_materials;mat++){ mp::material[mat].one_oneplusalpha_sq = -mp::material[mat].gamma_rel/(1.0+mp::material[mat].alpha*mp::material[mat].alpha); mp::material[mat].alpha_oneplusalpha_sq = mp::material[mat].alpha*mp::material[mat].one_oneplusalpha_sq; for(int j=0;j<mp::num_materials;j++){ material[mat].Jij_matrix[j] = mp::material[mat].Jij_matrix_SI[j]/mp::material[mat].mu_s_SI; } mp::material[mat].Ku = mp::material[mat].Ku1_SI/mp::material[mat].mu_s_SI; mp::material[mat].Ku2 = mp::material[mat].Ku2_SI/mp::material[mat].mu_s_SI; mp::material[mat].Ku3 = mp::material[mat].Ku3_SI/mp::material[mat].mu_s_SI; mp::material[mat].Klatt = mp::material[mat].Klatt_SI/mp::material[mat].mu_s_SI; mp::material[mat].Kc = mp::material[mat].Kc1_SI/mp::material[mat].mu_s_SI; mp::material[mat].Ks = mp::material[mat].Ks_SI/mp::material[mat].mu_s_SI; mp::material[mat].H_th_sigma = sqrt(2.0*mp::material[mat].alpha*1.3806503e-23/ (mp::material[mat].mu_s_SI*mp::material[mat].gamma_rel*dt)); // Rename un-named materials with material id std::string defname="material#n"; if(mp::material[mat].name==defname){ std::stringstream newname; newname << "material" << mat+1; mp::material[mat].name=newname.str(); } // initialise lattice anisotropy initialisation if(sim::lattice_anisotropy_flag==true) mp::material[mat].lattice_anisotropy.set_interpolation_table(); // output interpolated data to file //mp::material[mat].lattice_anisotropy.output_interpolated_function(mat); } // Check for which anisotropy function(s) are to be used if(sim::TensorAnisotropy==true){ sim::UniaxialScalarAnisotropy=false; // turn off scalar anisotropy calculation // loop over materials and convert all scalar anisotropy to tensor (along z) for(int mat=0;mat<mp::num_materials; mat++){ const double one_o_mu=1.0/mp::material[mat].mu_s_SI; // If tensor is unset if(mp::material.at(mat).KuVec_SI.size()==0){ const double ex = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(0); const double ey = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(1); const double ez = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(2); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ex); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ey); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ez); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ex); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ey); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ez); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ex); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ey); mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ez); } else if(mp::material.at(mat).KuVec_SI.size()==9){ mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(0)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(1)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(2)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(3)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(4)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(5)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(6)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(7)*one_o_mu); mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(8)*one_o_mu); } } } // Unroll anisotropy values for speed if(sim::UniaxialScalarAnisotropy==true){ zlog << zTs() << "Setting scalar uniaxial anisotropy." << std::endl; // Set global anisotropy type sim::AnisotropyType=0; MaterialScalarAnisotropyArray.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) MaterialScalarAnisotropyArray[mat].K=mp::material[mat].Ku; } else if(sim::TensorAnisotropy==true){ zlog << zTs() << "Setting tensor uniaxial anisotropy." << std::endl; // Set global anisotropy type sim::AnisotropyType=1; MaterialTensorAnisotropyArray.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++){ MaterialTensorAnisotropyArray[mat].K[0][0]=mp::material.at(mat).KuVec.at(0); MaterialTensorAnisotropyArray[mat].K[0][1]=mp::material.at(mat).KuVec.at(1); MaterialTensorAnisotropyArray[mat].K[0][2]=mp::material.at(mat).KuVec.at(2); MaterialTensorAnisotropyArray[mat].K[1][0]=mp::material.at(mat).KuVec.at(3); MaterialTensorAnisotropyArray[mat].K[1][1]=mp::material.at(mat).KuVec.at(4); MaterialTensorAnisotropyArray[mat].K[1][2]=mp::material.at(mat).KuVec.at(5); MaterialTensorAnisotropyArray[mat].K[2][0]=mp::material.at(mat).KuVec.at(6); MaterialTensorAnisotropyArray[mat].K[2][1]=mp::material.at(mat).KuVec.at(7); MaterialTensorAnisotropyArray[mat].K[2][2]=mp::material.at(mat).KuVec.at(8); } } // Unroll second order uniaxial anisotropy values for speed if(sim::second_order_uniaxial_anisotropy==true){ zlog << zTs() << "Setting scalar second order uniaxial anisotropy." << std::endl; mp::material_second_order_anisotropy_constant_array.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) mp::material_second_order_anisotropy_constant_array.at(mat)=mp::material[mat].Ku2; } // Unroll sixth order uniaxial anisotropy values for speed if(sim::second_order_uniaxial_anisotropy==true){ zlog << zTs() << "Setting scalar sixth order uniaxial anisotropy." << std::endl; mp::material_sixth_order_anisotropy_constant_array.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) mp::material_sixth_order_anisotropy_constant_array.at(mat)=mp::material[mat].Ku3; } // Unroll spherical harmonic anisotropy constants for speed if(sim::spherical_harmonics==true){ zlog << zTs() << "Setting spherical harmonics for uniaxial anisotropy" << std::endl; mp::material_spherical_harmonic_constants_array.resize(3*mp::num_materials); for(int mat=0; mat<mp::num_materials; mat++){ mp::material_spherical_harmonic_constants_array.at(3*mat+0)=mp::material[mat].sh2/mp::material[mat].mu_s_SI; mp::material_spherical_harmonic_constants_array.at(3*mat+1)=mp::material[mat].sh4/mp::material[mat].mu_s_SI; mp::material_spherical_harmonic_constants_array.at(3*mat+2)=mp::material[mat].sh6/mp::material[mat].mu_s_SI; } } // Unroll cubic anisotropy values for speed if(sim::CubicScalarAnisotropy==true){ zlog << zTs() << "Setting scalar cubic anisotropy." << std::endl; MaterialCubicAnisotropyArray.resize(mp::num_materials); for(int mat=0;mat<mp::num_materials; mat++) MaterialCubicAnisotropyArray.at(mat)=mp::material[mat].Kc; } // Loop over materials to check for invalid input and warn appropriately for(int mat=0;mat<mp::num_materials;mat++){ const double lmin=material[mat].min; const double lmax=material[mat].max; for(int nmat=0;nmat<mp::num_materials;nmat++){ if(nmat!=mat){ double min=material[nmat].min; double max=material[nmat].max; if(((lmin>min) && (lmin<max)) || ((lmax>min) && (lmax<max))){ terminaltextcolor(RED); std::cerr << "Warning: Overlapping material heights found. Check log for details." << std::endl; terminaltextcolor(WHITE); zlog << zTs() << "Warning: material " << mat+1 << " overlaps material " << nmat+1 << "." << std::endl; zlog << zTs() << "If you have defined geometry then this may be OK, or possibly you meant to specify alloy keyword instead." << std::endl; zlog << zTs() << "----------------------------------------------------" << std::endl; zlog << zTs() << " Material "<< mat+1 << ":minimum-height = " << lmin << std::endl; zlog << zTs() << " Material "<< mat+1 << ":maximum-height = " << lmax << std::endl; zlog << zTs() << " Material "<< nmat+1 << ":minimum-height = " << min << std::endl; zlog << zTs() << " Material "<< nmat+1 << ":maximum-height = " << max << std::endl; } } } } return EXIT_SUCCESS; } } // end of namespace mp
pchureemart/vampire
src/main/initialise_variables.cpp
C++
gpl-2.0
27,475
--DDD死偉王ヘル・アーマゲドン function c47198668.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --atk up local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_PZONE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCountLimit(1) e2:SetTarget(c47198668.atktg1) e2:SetOperation(c47198668.atkop1) c:RegisterEffect(e2) --atk up local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_ATKCHANGE) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_DESTROYED) e3:SetRange(LOCATION_MZONE) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e3:SetCountLimit(1) e3:SetCost(c47198668.atkcost) e3:SetTarget(c47198668.atktg2) e3:SetOperation(c47198668.atkop2) c:RegisterEffect(e3) --indes local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetRange(LOCATION_MZONE) e4:SetValue(c47198668.efilter) c:RegisterEffect(e4) end function c47198668.filter1(c) return c:IsFaceup() and c:IsSetCard(0xaf) end function c47198668.atktg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c47198668.filter1(chkc) end if chk==0 then return Duel.IsExistingTarget(c47198668.filter1,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c47198668.filter1,tp,LOCATION_MZONE,0,1,1,nil) end function c47198668.atkop1(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(800) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end function c47198668.filter2(c,e,tp) return c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:IsType(TYPE_MONSTER) and c:IsPreviousLocation(LOCATION_MZONE) and c:GetPreviousControler()==tp and c:IsLocation(LOCATION_GRAVE+LOCATION_REMOVED) and c:IsCanBeEffectTarget(e) end function c47198668.atkcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not e:GetHandler():IsDirectAttacked() end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_DIRECT_ATTACK) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) e:GetHandler():RegisterEffect(e1) end function c47198668.atktg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return eg:IsContains(chkc) and c47198668.filter2(chkc,e,tp) end if chk==0 then return eg:IsExists(c47198668.filter2,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=eg:FilterSelect(tp,c47198668.filter2,1,1,nil,e,tp) Duel.SetTargetCard(g) end function c47198668.atkop2(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsFaceup() and c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(tc:GetBaseAttack()) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end end function c47198668.efilter(e,re,rp) if not re:IsActiveType(TYPE_SPELL+TYPE_TRAP) then return false end if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return true end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) return not g:IsContains(e:GetHandler()) end
mercury233/ygopro-scripts
c47198668.lua
Lua
gpl-2.0
3,662
/****************************************************************** iLBC Speech Coder ANSI-C Source Code LPC_decode.h Copyright (C) The Internet Society (2004). All Rights Reserved. ******************************************************************/ #ifndef __iLBC_LPC_DECODE_H #define __iLBC_LPC_DECODE_H void LSFinterpolate2a_dec( float *a, /* (o) lpc coefficients for a sub-frame */ float *lsf1, /* (i) first lsf coefficient vector */ float *lsf2, /* (i) second lsf coefficient vector */ float coef, /* (i) interpolation weight */ int length /* (i) length of lsf vectors */ ); void SimplelsfDEQ( float *lsfdeq, /* (o) dequantized lsf coefficients */ int *index, /* (i) quantization index */ int lpc_n /* (i) number of LPCs */ ); void DecoderInterpolateLSF( float *syntdenum, /* (o) synthesis filter coefficients */ float *weightdenum, /* (o) weighting denumerator coefficients */ float *lsfdeq, /* (i) dequantized lsf coefficients */ int length, /* (i) length of lsf coefficient vector */ iLBC_Dec_Inst_t *iLBCdec_inst /* (i) the decoder state structure */ ); #endif
ryanrdetzel/pjsip
third_party/ilbc/LPCdecode.h
C
gpl-2.0
1,428
(function( $ ) { wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); })( jQuery );
thekirankumardash/bijithemecustomizer
project_downloads/2.5/js/theme-customizer.js
JavaScript
gpl-2.0
298
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <wangttao@cn.ibm.com> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ')
rajashreer7/autotest-client-tests
linux-tools/sblim_sfcb/sblim_sfcb.py
Python
gpl-2.0
1,610
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "halls_of_reflection.h" #include "Player.h" enum Yells { SAY_JAINA_INTRO_1 = 0, SAY_JAINA_INTRO_2 = 1, SAY_JAINA_INTRO_3 = 2, SAY_JAINA_INTRO_4 = 3, SAY_JAINA_INTRO_5 = 4, SAY_JAINA_INTRO_6 = 5, SAY_JAINA_INTRO_7 = 6, SAY_JAINA_INTRO_8 = 7, SAY_JAINA_INTRO_9 = 8, SAY_JAINA_INTRO_10 = 9, SAY_JAINA_INTRO_11 = 10, SAY_JAINA_INTRO_END = 11, SAY_SYLVANAS_INTRO_1 = 0, SAY_SYLVANAS_INTRO_2 = 1, SAY_SYLVANAS_INTRO_3 = 2, SAY_SYLVANAS_INTRO_4 = 3, SAY_SYLVANAS_INTRO_5 = 4, SAY_SYLVANAS_INTRO_6 = 5, SAY_SYLVANAS_INTRO_7 = 6, SAY_SYLVANAS_INTRO_8 = 7, SAY_SYLVANAS_INTRO_END = 8, SAY_UTHER_INTRO_A2_1 = 0, SAY_UTHER_INTRO_A2_2 = 1, SAY_UTHER_INTRO_A2_3 = 2, SAY_UTHER_INTRO_A2_4 = 3, SAY_UTHER_INTRO_A2_5 = 4, SAY_UTHER_INTRO_A2_6 = 5, SAY_UTHER_INTRO_A2_7 = 6, SAY_UTHER_INTRO_A2_8 = 7, SAY_UTHER_INTRO_A2_9 = 8, SAY_UTHER_INTRO_H2_1 = 9, SAY_UTHER_INTRO_H2_2 = 10, SAY_UTHER_INTRO_H2_3 = 11, SAY_UTHER_INTRO_H2_4 = 12, SAY_UTHER_INTRO_H2_5 = 13, SAY_UTHER_INTRO_H2_6 = 14, SAY_UTHER_INTRO_H2_7 = 15, SAY_LK_INTRO_1 = 0, SAY_LK_INTRO_2 = 1, SAY_LK_INTRO_3 = 2, SAY_FALRIC_INTRO_1 = 5, SAY_FALRIC_INTRO_2 = 6, SAY_MARWYN_INTRO_1 = 4 }; enum Events { EVENT_NONE, EVENT_START_INTRO, EVENT_SKIP_INTRO, EVENT_INTRO_A2_1, EVENT_INTRO_A2_2, EVENT_INTRO_A2_3, EVENT_INTRO_A2_4, EVENT_INTRO_A2_5, EVENT_INTRO_A2_6, EVENT_INTRO_A2_7, EVENT_INTRO_A2_8, EVENT_INTRO_A2_9, EVENT_INTRO_A2_10, EVENT_INTRO_A2_11, EVENT_INTRO_A2_12, EVENT_INTRO_A2_13, EVENT_INTRO_A2_14, EVENT_INTRO_A2_15, EVENT_INTRO_A2_16, EVENT_INTRO_A2_17, EVENT_INTRO_A2_18, EVENT_INTRO_A2_19, EVENT_INTRO_H2_1, EVENT_INTRO_H2_2, EVENT_INTRO_H2_3, EVENT_INTRO_H2_4, EVENT_INTRO_H2_5, EVENT_INTRO_H2_6, EVENT_INTRO_H2_7, EVENT_INTRO_H2_8, EVENT_INTRO_H2_9, EVENT_INTRO_H2_10, EVENT_INTRO_H2_11, EVENT_INTRO_H2_12, EVENT_INTRO_H2_13, EVENT_INTRO_H2_14, EVENT_INTRO_H2_15, EVENT_INTRO_LK_1, EVENT_INTRO_LK_2, EVENT_INTRO_LK_3, EVENT_INTRO_LK_4, EVENT_INTRO_LK_5, EVENT_INTRO_LK_6, EVENT_INTRO_LK_7, EVENT_INTRO_LK_8, EVENT_INTRO_LK_9, EVENT_INTRO_END, }; enum eEnum { ACTION_START_INTRO, ACTION_SKIP_INTRO, QUEST_DELIVRANCE_FROM_THE_PIT_A2 = 24710, QUEST_DELIVRANCE_FROM_THE_PIT_H2 = 24712, QUEST_WRATH_OF_THE_LICH_KING_A2 = 24500, QUEST_WRATH_OF_THE_LICH_KING_H2 = 24802, }; const Position HallsofReflectionLocs[]= { {5283.234863f, 1990.946777f, 707.695679f, 0.929097f}, // 2 Loralen Follows {5408.031250f, 2102.918213f, 707.695251f, 0.792756f}, // 9 Sylvanas Follows {5401.866699f, 2110.837402f, 707.695251f, 0.800610f}, // 10 Loralen follows }; const Position SpawnPos = {5262.540527f, 1949.693726f, 707.695007f, 0.808736f}; // Jaina/Sylvanas Beginning Position const Position MoveThronePos = {5306.952148f, 1998.499023f, 709.341431f, 1.277278f}; // Jaina/Sylvanas walks to throne const Position UtherSpawnPos = {5308.310059f, 2003.857178f, 709.341431f, 4.650315f}; const Position LichKingSpawnPos = {5362.917480f, 2062.307129f, 707.695374f, 3.945812f}; const Position LichKingMoveThronePos = {5312.080566f, 2009.172119f, 709.341431f, 3.973301f}; // Lich King walks to throne const Position LichKingMoveAwayPos = {5400.069824f, 2102.7131689f, 707.69525f, 0.843803f}; // Lich King walks away class npc_jaina_or_sylvanas_hor : public CreatureScript { private: bool m_isSylvana; public: npc_jaina_or_sylvanas_hor(bool isSylvana, const char* name) : CreatureScript(name), m_isSylvana(isSylvana) { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); switch (action) { case GOSSIP_ACTION_INFO_DEF+1: player->CLOSE_GOSSIP_MENU(); if (creature->AI()) creature->AI()->DoAction(ACTION_START_INTRO); creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); break; case GOSSIP_ACTION_INFO_DEF+2: player->CLOSE_GOSSIP_MENU(); if (creature->AI()) creature->AI()->DoAction(ACTION_SKIP_INTRO); creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); break; } return true; } bool OnGossipHello(Player* player, Creature* creature) { if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); QuestStatus status = player->GetQuestStatus(m_isSylvana ? QUEST_DELIVRANCE_FROM_THE_PIT_H2 : QUEST_DELIVRANCE_FROM_THE_PIT_A2); if (status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED) player->ADD_GOSSIP_ITEM( 0, "Can you remove the sword?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); // once last quest is completed, she offers this shortcut of the starting event status = player->GetQuestStatus(m_isSylvana ? QUEST_WRATH_OF_THE_LICH_KING_H2 : QUEST_WRATH_OF_THE_LICH_KING_A2); if (status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED) player->ADD_GOSSIP_ITEM( 0, "Dark Lady, I think I hear Arthas coming. Whatever you're going to do, do it quickly.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID()); return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_jaina_or_sylvanas_horAI(creature); } // AI of Part1: handle the intro till start of gauntlet event. struct npc_jaina_or_sylvanas_horAI : public ScriptedAI { npc_jaina_or_sylvanas_horAI(Creature* creature) : ScriptedAI(creature) { instance = me->GetInstanceScript(); } InstanceScript* instance; uint64 utherGUID; uint64 lichkingGUID; EventMap events; void Reset() { events.Reset(); utherGUID = 0; lichkingGUID = 0; me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); me->SetStandState(UNIT_STAND_STATE_STAND); me->SetVisible(true); } void DoAction(const int32 actionId) { switch (actionId) { case ACTION_START_INTRO: events.ScheduleEvent(EVENT_START_INTRO, 0); break; case ACTION_SKIP_INTRO: events.ScheduleEvent(EVENT_SKIP_INTRO, 0); break; } } void UpdateAI(const uint32 diff) { events.Update(diff); switch (events.ExecuteEvent()) { case EVENT_START_INTRO: me->GetMotionMaster()->MovePoint(0, MoveThronePos); // Begining of intro is differents between fActions as the speech sequence and timers are differents. if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) events.ScheduleEvent(EVENT_INTRO_A2_1, 0); else events.ScheduleEvent(EVENT_INTRO_H2_1, 0); break; // A2 Intro Events case EVENT_INTRO_A2_1: Talk(SAY_JAINA_INTRO_3); events.ScheduleEvent(EVENT_INTRO_A2_2, 5000); break; case EVENT_INTRO_A2_2: Talk(SAY_JAINA_INTRO_4); events.ScheduleEvent(EVENT_INTRO_A2_3, 10000); break; case EVENT_INTRO_A2_3: // TODO: she's doing some kind of spell casting emote instance->HandleGameObject(instance->GetData64(DATA_FROSTMOURNE), true); events.ScheduleEvent(EVENT_INTRO_A2_4, 10000); break; case EVENT_INTRO_A2_4: // spawn UTHER during speach 2 if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN)) { uther->GetMotionMaster()->MoveIdle(); uther->SetReactState(REACT_PASSIVE); // be sure he will not aggro arthas utherGUID = uther->GetGUID(); } events.ScheduleEvent(EVENT_INTRO_A2_5, 2000); break; case EVENT_INTRO_A2_5: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_1); events.ScheduleEvent(EVENT_INTRO_A2_6, 3000); break; case EVENT_INTRO_A2_6: Talk(SAY_JAINA_INTRO_5); events.ScheduleEvent(EVENT_INTRO_A2_7, 6000); break; case EVENT_INTRO_A2_7: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_2); events.ScheduleEvent(EVENT_INTRO_A2_8, 6500); break; case EVENT_INTRO_A2_8: Talk(SAY_JAINA_INTRO_6); events.ScheduleEvent(EVENT_INTRO_A2_9, 2000); break; case EVENT_INTRO_A2_9: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_3); events.ScheduleEvent(EVENT_INTRO_A2_10, 9000); break; case EVENT_INTRO_A2_10: Talk(SAY_JAINA_INTRO_7); events.ScheduleEvent(EVENT_INTRO_A2_11, 5000); break; case EVENT_INTRO_A2_11: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_4); events.ScheduleEvent(EVENT_INTRO_A2_12, 11000); break; case EVENT_INTRO_A2_12: Talk(SAY_JAINA_INTRO_8); events.ScheduleEvent(EVENT_INTRO_A2_13, 4000); break; case EVENT_INTRO_A2_13: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_5); events.ScheduleEvent(EVENT_INTRO_A2_14, 12500); break; case EVENT_INTRO_A2_14: Talk(SAY_JAINA_INTRO_9); events.ScheduleEvent(EVENT_INTRO_A2_15, 10000); break; case EVENT_INTRO_A2_15: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_6); events.ScheduleEvent(EVENT_INTRO_A2_16, 22000); break; case EVENT_INTRO_A2_16: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_7); events.ScheduleEvent(EVENT_INTRO_A2_17, 4000); break; case EVENT_INTRO_A2_17: Talk(SAY_JAINA_INTRO_10); events.ScheduleEvent(EVENT_INTRO_A2_18, 2000); break; case EVENT_INTRO_A2_18: if (Creature* uther = me->GetCreature(*me, utherGUID)) { uther->HandleEmoteCommand(EMOTE_ONESHOT_NO); uther->AI()->Talk(SAY_UTHER_INTRO_A2_8); } events.ScheduleEvent(EVENT_INTRO_A2_19, 11000); break; case EVENT_INTRO_A2_19: Talk(SAY_JAINA_INTRO_11); events.ScheduleEvent(EVENT_INTRO_LK_1, 2000); break; // H2 Intro Events case EVENT_INTRO_H2_1: Talk(SAY_SYLVANAS_INTRO_1); events.ScheduleEvent(EVENT_INTRO_H2_2, 8000); break; case EVENT_INTRO_H2_2: Talk(SAY_SYLVANAS_INTRO_2); events.ScheduleEvent(EVENT_INTRO_H2_3, 6000); break; case EVENT_INTRO_H2_3: Talk(SAY_SYLVANAS_INTRO_3); // TODO: she's doing some kind of spell casting emote events.ScheduleEvent(EVENT_INTRO_H2_4, 6000); break; case EVENT_INTRO_H2_4: // spawn UTHER during speach 2 if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN)) { uther->GetMotionMaster()->MoveIdle(); uther->SetReactState(REACT_PASSIVE); // be sure he will not aggro arthas utherGUID = uther->GetGUID(); } events.ScheduleEvent(EVENT_INTRO_H2_5, 2000); break; case EVENT_INTRO_H2_5: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_1); events.ScheduleEvent(EVENT_INTRO_H2_6, 11000); break; case EVENT_INTRO_H2_6: Talk(SAY_SYLVANAS_INTRO_4); events.ScheduleEvent(EVENT_INTRO_H2_7, 3000); break; case EVENT_INTRO_H2_7: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_2); events.ScheduleEvent(EVENT_INTRO_H2_8, 6000); break; case EVENT_INTRO_H2_8: Talk(SAY_SYLVANAS_INTRO_5); events.ScheduleEvent(EVENT_INTRO_H2_9, 5000); break; case EVENT_INTRO_H2_9: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_3); events.ScheduleEvent(EVENT_INTRO_H2_10, 19000); break; case EVENT_INTRO_H2_10: Talk(SAY_SYLVANAS_INTRO_6); events.ScheduleEvent(EVENT_INTRO_H2_11, 1500); break; case EVENT_INTRO_H2_11: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_4); events.ScheduleEvent(EVENT_INTRO_H2_12, 19500); break; case EVENT_INTRO_H2_12: Talk(SAY_SYLVANAS_INTRO_7); events.ScheduleEvent(EVENT_INTRO_H2_13, 2000); break; case EVENT_INTRO_H2_13: if (Creature* uther = me->GetCreature(*me, utherGUID)) { uther->HandleEmoteCommand(EMOTE_ONESHOT_NO); uther->AI()->Talk(SAY_UTHER_INTRO_H2_5); } events.ScheduleEvent(EVENT_INTRO_H2_14, 12000); break; case EVENT_INTRO_H2_14: if (Creature* uther = me->GetCreature(*me, utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_6); events.ScheduleEvent(EVENT_INTRO_H2_15, 8000); break; case EVENT_INTRO_H2_15: Talk(SAY_SYLVANAS_INTRO_8); events.ScheduleEvent(EVENT_INTRO_LK_1, 2000); break; // Remaining Intro Events common for both faction case EVENT_INTRO_LK_1: // Spawn LK in front of door, and make him move to the sword. if (Creature* lichking = me->SummonCreature(NPC_LICH_KING_EVENT, LichKingSpawnPos, TEMPSUMMON_MANUAL_DESPAWN)) { lichking->GetMotionMaster()->MovePoint(0, LichKingMoveThronePos); lichking->SetReactState(REACT_PASSIVE); lichkingGUID = lichking->GetGUID(); } if (Creature* uther = me->GetCreature(*me, utherGUID)) { if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) uther->AI()->Talk(SAY_UTHER_INTRO_A2_9); else uther->AI()->Talk(SAY_UTHER_INTRO_H2_7); } events.ScheduleEvent(EVENT_INTRO_LK_2, 11000); break; case EVENT_INTRO_LK_2: if (Creature* lichking = me->GetCreature(*me, lichkingGUID)) lichking->AI()->Talk(SAY_LK_INTRO_1); events.ScheduleEvent(EVENT_INTRO_LK_3, 2000); break; case EVENT_INTRO_LK_3: // The Lich King banishes Uther to the abyss. if (Creature* uther = me->GetCreature(*me, utherGUID)) { uther->DisappearAndDie(); utherGUID = 0; } // He steps forward and removes the runeblade from the heap of skulls. events.ScheduleEvent(EVENT_INTRO_LK_4, 4000); break; case EVENT_INTRO_LK_4: if (Creature* lichking = me->GetCreature(*me, lichkingGUID)) lichking->AI()->Talk(SAY_LK_INTRO_2); events.ScheduleEvent(EVENT_INTRO_LK_5, 10000); break; case EVENT_INTRO_LK_5: // summon Falric and Marwyn. then go back to the door if (Creature* pFalric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC))) pFalric->SetVisible(true); if (Creature* pMarwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN))) pMarwyn->SetVisible(true); if (Creature* lichking = me->GetCreature(*me, lichkingGUID)) { lichking->GetMotionMaster()->MovePoint(0, LichKingSpawnPos); lichking->AI()->Talk(SAY_LK_INTRO_3); } events.ScheduleEvent(EVENT_INTRO_LK_6, 8000); break; case EVENT_INTRO_LK_6: if (Creature* falric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC))) falric->AI()->Talk(SAY_FALRIC_INTRO_1); events.ScheduleEvent(EVENT_INTRO_LK_7, 2000); break; case EVENT_INTRO_LK_7: if (Creature* marwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN))) marwyn->AI()->Talk(SAY_MARWYN_INTRO_1); events.ScheduleEvent(EVENT_INTRO_LK_8, 2000); break; case EVENT_INTRO_LK_8: if (Creature* falric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC))) falric->AI()->Talk(SAY_FALRIC_INTRO_2); events.ScheduleEvent(EVENT_INTRO_LK_9, 5000); break; case EVENT_INTRO_LK_9: if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) Talk(SAY_JAINA_INTRO_END); else Talk(SAY_SYLVANAS_INTRO_END); me->GetMotionMaster()->MovePoint(0, LichKingSpawnPos); // TODO: Loralen/Koreln shall run also events.ScheduleEvent(EVENT_INTRO_END, 10000); break; case EVENT_INTRO_END: if (instance) instance->SetData(DATA_WAVE_COUNT, SPECIAL); // start first wave // Loralen or Koreln disappearAndDie() me->DisappearAndDie(); break; case EVENT_SKIP_INTRO: // TODO: implement if (Creature* pFalric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC))) pFalric->SetVisible(true); if (Creature* pMarwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN))) pMarwyn->SetVisible(true); me->GetMotionMaster()->MovePoint(0, LichKingSpawnPos); // TODO: Loralen/Koreln shall run also events.ScheduleEvent(EVENT_INTRO_END, 15000); break; } } }; }; enum TrashSpells { // Ghostly Priest SPELL_SHADOW_WORD_PAIN = 72318, SPELL_CIRCLE_OF_DESTRUCTION = 72320, SPELL_COWER_IN_FEAR = 72321, SPELL_DARK_MENDING = 72322, // Phantom Mage SPELL_FIREBALL = 72163, SPELL_FLAMESTRIKE = 72169, SPELL_FROSTBOLT = 72166, SPELL_CHAINS_OF_ICE = 72121, SPELL_HALLUCINATION = 72342, // Phantom Hallucination (same as phantom mage + HALLUCINATION_2 when dies) SPELL_HALLUCINATION_2 = 72344, // Shadowy Mercenary SPELL_SHADOW_STEP = 72326, SPELL_DEADLY_POISON = 72329, SPELL_ENVENOMED_DAGGER_THROW = 72333, SPELL_KIDNEY_SHOT = 72335, // Spectral Footman SPELL_SPECTRAL_STRIKE = 72198, SPELL_SHIELD_BASH = 72194, SPELL_TORTURED_ENRAGE = 72203, // Tortured Rifleman SPELL_SHOOT = 72208, SPELL_CURSED_ARROW = 72222, SPELL_FROST_TRAP = 72215, SPELL_ICE_SHOT = 72268, }; enum TrashEvents { EVENT_TRASH_NONE, // Ghostly Priest EVENT_SHADOW_WORD_PAIN, EVENT_CIRCLE_OF_DESTRUCTION, EVENT_COWER_IN_FEAR, EVENT_DARK_MENDING, // Phantom Mage EVENT_FIREBALL, EVENT_FLAMESTRIKE, EVENT_FROSTBOLT, EVENT_CHAINS_OF_ICE, EVENT_HALLUCINATION, // Shadowy Mercenary EVENT_SHADOW_STEP, EVENT_DEADLY_POISON, EVENT_ENVENOMED_DAGGER_THROW, EVENT_KIDNEY_SHOT, // Spectral Footman EVENT_SPECTRAL_STRIKE, EVENT_SHIELD_BASH, EVENT_TORTURED_ENRAGE, // Tortured Rifleman EVENT_SHOOT, EVENT_CURSED_ARROW, EVENT_FROST_TRAP, EVENT_ICE_SHOT, }; class npc_ghostly_priest : public CreatureScript { public: npc_ghostly_priest() : CreatureScript("npc_ghostly_priest") { } CreatureAI* GetAI(Creature* creature) const { return new npc_ghostly_priestAI(creature); } struct npc_ghostly_priestAI: public ScriptedAI { npc_ghostly_priestAI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit* /*who*/) { events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 8000); // TODO: adjust timers events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12000); events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10000); events.ScheduleEvent(EVENT_DARK_MENDING, 20000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SHADOW_WORD_PAIN: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_SHADOW_WORD_PAIN); events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 8000); return; case EVENT_CIRCLE_OF_DESTRUCTION: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_CIRCLE_OF_DESTRUCTION); events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12000); return; case EVENT_COWER_IN_FEAR: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_COWER_IN_FEAR); events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10000); return; case EVENT_DARK_MENDING: // find an ally with missing HP if (Unit* target = DoSelectLowestHpFriendly(40, DUNGEON_MODE(30000, 50000))) { DoCast(target, SPELL_DARK_MENDING); events.ScheduleEvent(EVENT_DARK_MENDING, 20000); } else { // no friendly unit with missing hp. re-check in just 5 sec. events.ScheduleEvent(EVENT_DARK_MENDING, 5000); } return; } } DoMeleeAttackIfReady(); } }; }; class npc_phantom_mage : public CreatureScript { public: npc_phantom_mage() : CreatureScript("npc_phantom_mage") { } CreatureAI* GetAI(Creature* creature) const { return new npc_phantom_mageAI(creature); } struct npc_phantom_mageAI: public ScriptedAI { npc_phantom_mageAI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit* /*who*/) { events.ScheduleEvent(EVENT_FIREBALL, 3000); // TODO: adjust timers events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000); events.ScheduleEvent(EVENT_FROSTBOLT, 9000); events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 12000); events.ScheduleEvent(EVENT_HALLUCINATION, 40000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FIREBALL: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_FIREBALL); events.ScheduleEvent(EVENT_FIREBALL, 15000); return; case EVENT_FLAMESTRIKE: DoCast(SPELL_FLAMESTRIKE); events.ScheduleEvent(EVENT_FLAMESTRIKE, 15000); return; case EVENT_FROSTBOLT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_FROSTBOLT); events.ScheduleEvent(EVENT_FROSTBOLT, 15000); return; case EVENT_CHAINS_OF_ICE: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_CHAINS_OF_ICE); events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 15000); return; case EVENT_HALLUCINATION: DoCast(SPELL_HALLUCINATION); return; } } DoMeleeAttackIfReady(); } }; }; class npc_phantom_hallucination : public CreatureScript { public: npc_phantom_hallucination() : CreatureScript("npc_phantom_hallucination") { } CreatureAI* GetAI(Creature* creature) const { return new npc_phantom_hallucinationAI(creature); } struct npc_phantom_hallucinationAI : public npc_phantom_mage::npc_phantom_mageAI { npc_phantom_hallucinationAI(Creature* creature) : npc_phantom_mage::npc_phantom_mageAI(creature) { } void JustDied(Unit* /*killer*/) { DoCast(SPELL_HALLUCINATION_2); } }; }; class npc_shadowy_mercenary : public CreatureScript { public: npc_shadowy_mercenary() : CreatureScript("npc_shadowy_mercenary") { } CreatureAI* GetAI(Creature* creature) const { return new npc_shadowy_mercenaryAI(creature); } struct npc_shadowy_mercenaryAI: public ScriptedAI { npc_shadowy_mercenaryAI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit* /*who*/) { events.ScheduleEvent(EVENT_SHADOW_STEP, 8000); // TODO: adjust timers events.ScheduleEvent(EVENT_DEADLY_POISON, 5000); events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10000); events.ScheduleEvent(EVENT_KIDNEY_SHOT, 12000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SHADOW_STEP: DoCast(SPELL_SHADOW_STEP); events.ScheduleEvent(EVENT_SHADOW_STEP, 8000); return; case EVENT_DEADLY_POISON: DoCast(me->getVictim(), SPELL_DEADLY_POISON); events.ScheduleEvent(EVENT_DEADLY_POISON, 10000); return; case EVENT_ENVENOMED_DAGGER_THROW: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_ENVENOMED_DAGGER_THROW); events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10000); return; case EVENT_KIDNEY_SHOT: DoCast(me->getVictim(), SPELL_KIDNEY_SHOT); events.ScheduleEvent(EVENT_KIDNEY_SHOT, 10000); return; } } DoMeleeAttackIfReady(); } }; }; class npc_spectral_footman : public CreatureScript { public: npc_spectral_footman() : CreatureScript("npc_spectral_footman") { } CreatureAI* GetAI(Creature* creature) const { return new npc_spectral_footmanAI(creature); } struct npc_spectral_footmanAI: public ScriptedAI { npc_spectral_footmanAI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit* /*who*/) { events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5000); // TODO: adjust timers events.ScheduleEvent(EVENT_SHIELD_BASH, 10000); events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SPECTRAL_STRIKE: DoCast(me->getVictim(), SPELL_SPECTRAL_STRIKE); events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5000); return; case EVENT_SHIELD_BASH: DoCast(me->getVictim(), SPELL_SHIELD_BASH); events.ScheduleEvent(EVENT_SHIELD_BASH, 5000); return; case EVENT_TORTURED_ENRAGE: DoCast(SPELL_TORTURED_ENRAGE); events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15000); return; } } DoMeleeAttackIfReady(); } }; }; class npc_tortured_rifleman : public CreatureScript { public: npc_tortured_rifleman() : CreatureScript("npc_tortured_rifleman") { } CreatureAI* GetAI(Creature* creature) const { return new npc_tortured_riflemanAI(creature); } struct npc_tortured_riflemanAI : public ScriptedAI { npc_tortured_riflemanAI(Creature* creature) : ScriptedAI(creature) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit* /*who*/) { events.ScheduleEvent(EVENT_SHOOT, 2000); // TODO: adjust timers events.ScheduleEvent(EVENT_CURSED_ARROW, 10000); events.ScheduleEvent(EVENT_FROST_TRAP, 1000); events.ScheduleEvent(EVENT_ICE_SHOT, 15000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SHOOT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_SHOOT); events.ScheduleEvent(EVENT_SHOOT, 2000); return; case EVENT_CURSED_ARROW: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_CURSED_ARROW); events.ScheduleEvent(EVENT_CURSED_ARROW, 10000); return; case EVENT_FROST_TRAP: DoCast(SPELL_FROST_TRAP); events.ScheduleEvent(EVENT_FROST_TRAP, 30000); return; case EVENT_ICE_SHOT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) DoCast(target, SPELL_ICE_SHOT); events.ScheduleEvent(EVENT_ICE_SHOT, 15000); return; } } DoMeleeAttackIfReady(); } }; }; void AddSC_halls_of_reflection() { new npc_jaina_or_sylvanas_hor(true, "npc_sylvanas_hor_part1"); new npc_jaina_or_sylvanas_hor(false, "npc_jaina_hor_part1"); new npc_ghostly_priest(); new npc_phantom_mage(); new npc_phantom_hallucination(); new npc_shadowy_mercenary(); new npc_spectral_footman(); new npc_tortured_rifleman(); }
LORDofDOOM/MMOCore
src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp
C++
gpl-2.0
37,732
""" Test cases adapted from the test_bsddb.py module in Python's regression test suite. """ import sys, os, string import unittest import tempfile from test_all import verbose try: # For Python 2.3 from bsddb import db, hashopen, btopen, rnopen except ImportError: # For earlier Pythons w/distutils pybsddb from bsddb3 import db, hashopen, btopen, rnopen class CompatibilityTestCase(unittest.TestCase): def setUp(self): self.filename = tempfile.mktemp() def tearDown(self): try: os.remove(self.filename) except os.error: pass def test01_btopen(self): self.do_bthash_test(btopen, 'btopen') def test02_hashopen(self): self.do_bthash_test(hashopen, 'hashopen') def test03_rnopen(self): data = string.split("The quick brown fox jumped over the lazy dog.") if verbose: print "\nTesting: rnopen" f = rnopen(self.filename, 'c') for x in range(len(data)): f[x+1] = data[x] getTest = (f[1], f[2], f[3]) if verbose: print '%s %s %s' % getTest assert getTest[1] == 'quick', 'data mismatch!' f[25] = 'twenty-five' f.close() del f f = rnopen(self.filename, 'w') f[20] = 'twenty' def noRec(f): rec = f[15] self.assertRaises(KeyError, noRec, f) def badKey(f): rec = f['a string'] self.assertRaises(TypeError, badKey, f) del f[3] rec = f.first() while rec: if verbose: print rec try: rec = f.next() except KeyError: break f.close() def test04_n_flag(self): f = hashopen(self.filename, 'n') f.close() def do_bthash_test(self, factory, what): if verbose: print '\nTesting: ', what f = factory(self.filename, 'c') if verbose: print 'creation...' # truth test if f: if verbose: print "truth test: true" else: if verbose: print "truth test: false" f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: assert rec == f.last(), 'Error, last <> last!' f.previous() break if verbose: print rec assert f.has_key('f'), 'Error, missing key!' f.sync() f.close() # truth test try: if f: if verbose: print "truth test: true" else: if verbose: print "truth test: false" except db.DBError: pass else: self.fail("Exception expected") del f if verbose: print 'modification...' f = factory(self.filename, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word def noRec(f): rec = f['no such key'] self.assertRaises(KeyError, noRec, f) def badKey(f): rec = f[15] self.assertRaises(TypeError, badKey, f) f.close() #---------------------------------------------------------------------- def test_suite(): return unittest.makeSuite(CompatibilityTestCase) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
trivoldus28/pulsarch-verilog
tools/local/bas-release/bas,3.9/lib/python/lib/python2.3/bsddb/test/test_compat.py
Python
gpl-2.0
3,862
<?php // no direct access defined('_JEXEC') or die('Restricted access'); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ jimport('joomla.application.component.view'); /** * Description of SocialcountViewSocialcount * * @author stuart */ class SocialstreamsViewStream extends JView { function display($tpl = null) { if(!$this->get(ucfirst($this->network) . 'Cache')){ $adminmodel = &$this->getModel(); } $this->assignRef('cache', $cache); parent::display($tpl); } } ?>
appsol/socialstreams-joomla-25
com_socialstreams/views/stream/view.html.php
PHP
gpl-2.0
583
/* Delay between tap_code register and unregister to fix flaky media keys. */ #undef TAP_CODE_DELAY #define TAP_CODE_DELAY 10 /* Turn off RGB lighting when the host goes to sleep. */ #define RGBLIGHT_SLEEP /* Keep backlight and RGB level increments consistent across keyboards. */ #undef BACKLIGHT_LEVELS #undef RGBLIGHT_HUE_STEP #undef RGBLIGHT_SAT_STEP #undef RGBLIGHT_VAL_STEP #define BACKLIGHT_LEVELS 7 #define RGBLIGHT_HUE_STEP 8 #define RGBLIGHT_SAT_STEP 17 #define RGBLIGHT_VAL_STEP 17 /* Make mouse operation smoother. */ #undef MOUSEKEY_DELAY #undef MOUSEKEY_INTERVAL #define MOUSEKEY_DELAY 0 #define MOUSEKEY_INTERVAL 16 /* Lower mouse speed to adjust for reduced MOUSEKEY_INTERVAL. */ #undef MOUSEKEY_MAX_SPEED #undef MOUSEKEY_TIME_TO_MAX #undef MOUSEKEY_WHEEL_MAX_SPEED #undef MOUSEKEY_WHEEL_TIME_TO_MAX #define MOUSEKEY_MAX_SPEED 7 #define MOUSEKEY_TIME_TO_MAX 150 #define MOUSEKEY_WHEEL_MAX_SPEED 3 #define MOUSEKEY_WHEEL_TIME_TO_MAX 150
paxy97/qmk_firmware
users/bcat/config.h
C
gpl-2.0
960
/******************************************************************************************* Copyright 2010 Broadcom Corporation. All rights reserved. Unless you and Broadcom execute a separate written software license agreement governing use of this software, this software is licensed to you under the terms of the GNU General Public License version 2, available at http://www.gnu.org/copyleft/gpl.html (the "GPL"). Notwithstanding the above, under no circumstances may you combine this software in any way with any other Broadcom software provided under a license other than the GPL, without Broadcom's express prior written consent. *******************************************************************************************/ /** * * @file capi2_cc_ds.h * * @brief This file defines the capi2 Call Control related data types * ****************************************************************************/ #ifndef _CAPI2_CC_DS_H_ #define _CAPI2_CC_DS_H_ /** * @addtogroup CAPI2_CCAPIGroup * @{ */ // Data Definitions used by CAPI2 only #define PHONE_NUMBER_LEN 82 /** Phone number dial string **/ typedef struct { char phone_number[PHONE_NUMBER_LEN]; ///< NULL terminated dial string } PHONE_NUMBER_STR_t; /** States for all non-idle calls **/ typedef struct { CCallStateList_t stateList; ///< Call state array UInt8 listSz; ///< Number of call states } ALL_CALL_STATE_t; /** Indices for all non-idle calls **/ typedef struct { CCallIndexList_t indexList; ///< Call index array UInt8 listSz; ///< Number of call indices } ALL_CALL_INDEX_t; /** @} */ #endif
WinKarbik/android_kernel_samsung_amazing
modules/drivers/char/brcm/fuse_ril/CAPI2_CIB/capi2/cc/capi2_cc_ds.h
C
gpl-2.0
1,608
/* * vhost-vdpa * * Copyright(c) 2017-2018 Intel Corporation. * Copyright(c) 2020 Red Hat, Inc. * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. * */ #include "qemu/osdep.h" #include <linux/vhost.h> #include <linux/vfio.h> #include <sys/eventfd.h> #include <sys/ioctl.h> #include "hw/virtio/vhost.h" #include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio-net.h" #include "hw/virtio/vhost-vdpa.h" #include "qemu/main-loop.h" #include "cpu.h" static bool vhost_vdpa_listener_skipped_section(MemoryRegionSection *section) { return (!memory_region_is_ram(section->mr) && !memory_region_is_iommu(section->mr)) || /* * Sizing an enabled 64-bit BAR can cause spurious mappings to * addresses in the upper part of the 64-bit address space. These * are never accessed by the CPU and beyond the address width of * some IOMMU hardware. TODO: VDPA should tell us the IOMMU width. */ section->offset_within_address_space & (1ULL << 63); } static int vhost_vdpa_dma_map(struct vhost_vdpa *v, hwaddr iova, hwaddr size, void *vaddr, bool readonly) { struct vhost_msg_v2 msg = {}; int fd = v->device_fd; int ret = 0; msg.type = v->msg_type; msg.iotlb.iova = iova; msg.iotlb.size = size; msg.iotlb.uaddr = (uint64_t)(uintptr_t)vaddr; msg.iotlb.perm = readonly ? VHOST_ACCESS_RO : VHOST_ACCESS_RW; msg.iotlb.type = VHOST_IOTLB_UPDATE; if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) { error_report("failed to write, fd=%d, errno=%d (%s)", fd, errno, strerror(errno)); return -EIO ; } return ret; } static int vhost_vdpa_dma_unmap(struct vhost_vdpa *v, hwaddr iova, hwaddr size) { struct vhost_msg_v2 msg = {}; int fd = v->device_fd; int ret = 0; msg.type = v->msg_type; msg.iotlb.iova = iova; msg.iotlb.size = size; msg.iotlb.type = VHOST_IOTLB_INVALIDATE; if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) { error_report("failed to write, fd=%d, errno=%d (%s)", fd, errno, strerror(errno)); return -EIO ; } return ret; } static void vhost_vdpa_listener_region_add(MemoryListener *listener, MemoryRegionSection *section) { struct vhost_vdpa *v = container_of(listener, struct vhost_vdpa, listener); hwaddr iova; Int128 llend, llsize; void *vaddr; int ret; if (vhost_vdpa_listener_skipped_section(section)) { return; } if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) != (section->offset_within_region & ~TARGET_PAGE_MASK))) { error_report("%s received unaligned region", __func__); return; } iova = TARGET_PAGE_ALIGN(section->offset_within_address_space); llend = int128_make64(section->offset_within_address_space); llend = int128_add(llend, section->size); llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK)); if (int128_ge(int128_make64(iova), llend)) { return; } memory_region_ref(section->mr); /* Here we assume that memory_region_is_ram(section->mr)==true */ vaddr = memory_region_get_ram_ptr(section->mr) + section->offset_within_region + (iova - section->offset_within_address_space); llsize = int128_sub(llend, int128_make64(iova)); ret = vhost_vdpa_dma_map(v, iova, int128_get64(llsize), vaddr, section->readonly); if (ret) { error_report("vhost vdpa map fail!"); if (memory_region_is_ram_device(section->mr)) { /* Allow unexpected mappings not to be fatal for RAM devices */ error_report("map ram fail!"); return ; } goto fail; } return; fail: if (memory_region_is_ram_device(section->mr)) { error_report("failed to vdpa_dma_map. pci p2p may not work"); return; } /* * On the initfn path, store the first error in the container so we * can gracefully fail. Runtime, there's not much we can do other * than throw a hardware error. */ error_report("vhost-vdpa: DMA mapping failed, unable to continue"); return; } static void vhost_vdpa_listener_region_del(MemoryListener *listener, MemoryRegionSection *section) { struct vhost_vdpa *v = container_of(listener, struct vhost_vdpa, listener); hwaddr iova; Int128 llend, llsize; int ret; bool try_unmap = true; if (vhost_vdpa_listener_skipped_section(section)) { return; } if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) != (section->offset_within_region & ~TARGET_PAGE_MASK))) { error_report("%s received unaligned region", __func__); return; } iova = TARGET_PAGE_ALIGN(section->offset_within_address_space); llend = int128_make64(section->offset_within_address_space); llend = int128_add(llend, section->size); llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK)); if (int128_ge(int128_make64(iova), llend)) { return; } llsize = int128_sub(llend, int128_make64(iova)); if (try_unmap) { ret = vhost_vdpa_dma_unmap(v, iova, int128_get64(llsize)); if (ret) { error_report("vhost_vdpa dma unmap error!"); } } memory_region_unref(section->mr); } /* * IOTLB API is used by vhost-vpda which requires incremental updating * of the mapping. So we can not use generic vhost memory listener which * depends on the addnop(). */ static const MemoryListener vhost_vdpa_memory_listener = { .region_add = vhost_vdpa_listener_region_add, .region_del = vhost_vdpa_listener_region_del, }; static int vhost_vdpa_call(struct vhost_dev *dev, unsigned long int request, void *arg) { struct vhost_vdpa *v = dev->opaque; int fd = v->device_fd; assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); return ioctl(fd, request, arg); } static void vhost_vdpa_add_status(struct vhost_dev *dev, uint8_t status) { uint8_t s; if (vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &s)) { return; } s |= status; vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &s); } static int vhost_vdpa_init(struct vhost_dev *dev, void *opaque) { struct vhost_vdpa *v; uint64_t features; assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); v = opaque; dev->opaque = opaque ; vhost_vdpa_call(dev, VHOST_GET_FEATURES, &features); dev->backend_features = features; v->listener = vhost_vdpa_memory_listener; v->msg_type = VHOST_IOTLB_MSG_V2; vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); return 0; } static int vhost_vdpa_cleanup(struct vhost_dev *dev) { struct vhost_vdpa *v; assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); v = dev->opaque; memory_listener_unregister(&v->listener); dev->opaque = NULL; return 0; } static int vhost_vdpa_memslots_limit(struct vhost_dev *dev) { return INT_MAX; } static int vhost_vdpa_set_mem_table(struct vhost_dev *dev, struct vhost_memory *mem) { if (mem->padding) { return -1; } return 0; } static int vhost_vdpa_set_features(struct vhost_dev *dev, uint64_t features) { int ret; ret = vhost_vdpa_call(dev, VHOST_SET_FEATURES, &features); uint8_t status = 0; if (ret) { return ret; } vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_FEATURES_OK); vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &status); return !(status & VIRTIO_CONFIG_S_FEATURES_OK); } int vhost_vdpa_get_device_id(struct vhost_dev *dev, uint32_t *device_id) { return vhost_vdpa_call(dev, VHOST_VDPA_GET_DEVICE_ID, device_id); } static int vhost_vdpa_reset_device(struct vhost_dev *dev) { uint8_t status = 0; return vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &status); } static int vhost_vdpa_get_vq_index(struct vhost_dev *dev, int idx) { assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); return idx - dev->vq_index; } static int vhost_vdpa_set_vring_ready(struct vhost_dev *dev) { int i; for (i = 0; i < dev->nvqs; ++i) { struct vhost_vring_state state = { .index = dev->vq_index + i, .num = 1, }; vhost_vdpa_call(dev, VHOST_VDPA_SET_VRING_ENABLE, &state); } return 0; } static int vhost_vdpa_set_config(struct vhost_dev *dev, const uint8_t *data, uint32_t offset, uint32_t size, uint32_t flags) { struct vhost_vdpa_config *config; int ret; unsigned long config_size = offsetof(struct vhost_vdpa_config, buf); config = g_malloc(size + config_size); if (config == NULL) { return -1; } config->off = offset; config->len = size; memcpy(config->buf, data, size); ret = vhost_vdpa_call(dev, VHOST_VDPA_SET_CONFIG, config); g_free(config); return ret; } static int vhost_vdpa_get_config(struct vhost_dev *dev, uint8_t *config, uint32_t config_len) { struct vhost_vdpa_config *v_config; unsigned long config_size = offsetof(struct vhost_vdpa_config, buf); int ret; v_config = g_malloc(config_len + config_size); if (v_config == NULL) { return -1; } v_config->len = config_len; v_config->off = 0; ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_CONFIG, v_config); memcpy(config, v_config->buf, config_len); g_free(v_config); return ret; } static int vhost_vdpa_dev_start(struct vhost_dev *dev, bool started) { struct vhost_vdpa *v = dev->opaque; if (started) { uint8_t status = 0; memory_listener_register(&v->listener, &address_space_memory); vhost_vdpa_set_vring_ready(dev); vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK); vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &status); return !(status & VIRTIO_CONFIG_S_DRIVER_OK); } else { vhost_vdpa_reset_device(dev); vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); memory_listener_unregister(&v->listener); return 0; } } static int vhost_vdpa_set_log_base(struct vhost_dev *dev, uint64_t base, struct vhost_log *log) { return vhost_vdpa_call(dev, VHOST_SET_LOG_BASE, &base); } static int vhost_vdpa_set_vring_addr(struct vhost_dev *dev, struct vhost_vring_addr *addr) { return vhost_vdpa_call(dev, VHOST_SET_VRING_ADDR, addr); } static int vhost_vdpa_set_vring_num(struct vhost_dev *dev, struct vhost_vring_state *ring) { return vhost_vdpa_call(dev, VHOST_SET_VRING_NUM, ring); } static int vhost_vdpa_set_vring_base(struct vhost_dev *dev, struct vhost_vring_state *ring) { return vhost_vdpa_call(dev, VHOST_SET_VRING_BASE, ring); } static int vhost_vdpa_get_vring_base(struct vhost_dev *dev, struct vhost_vring_state *ring) { return vhost_vdpa_call(dev, VHOST_GET_VRING_BASE, ring); } static int vhost_vdpa_set_vring_kick(struct vhost_dev *dev, struct vhost_vring_file *file) { return vhost_vdpa_call(dev, VHOST_SET_VRING_KICK, file); } static int vhost_vdpa_set_vring_call(struct vhost_dev *dev, struct vhost_vring_file *file) { return vhost_vdpa_call(dev, VHOST_SET_VRING_CALL, file); } static int vhost_vdpa_get_features(struct vhost_dev *dev, uint64_t *features) { return vhost_vdpa_call(dev, VHOST_GET_FEATURES, features); } static int vhost_vdpa_set_owner(struct vhost_dev *dev) { return vhost_vdpa_call(dev, VHOST_SET_OWNER, NULL); } static int vhost_vdpa_vq_get_addr(struct vhost_dev *dev, struct vhost_vring_addr *addr, struct vhost_virtqueue *vq) { assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); addr->desc_user_addr = (uint64_t)(unsigned long)vq->desc_phys; addr->avail_user_addr = (uint64_t)(unsigned long)vq->avail_phys; addr->used_user_addr = (uint64_t)(unsigned long)vq->used_phys; return 0; } static bool vhost_vdpa_force_iommu(struct vhost_dev *dev) { return true; } const VhostOps vdpa_ops = { .backend_type = VHOST_BACKEND_TYPE_VDPA, .vhost_backend_init = vhost_vdpa_init, .vhost_backend_cleanup = vhost_vdpa_cleanup, .vhost_set_log_base = vhost_vdpa_set_log_base, .vhost_set_vring_addr = vhost_vdpa_set_vring_addr, .vhost_set_vring_num = vhost_vdpa_set_vring_num, .vhost_set_vring_base = vhost_vdpa_set_vring_base, .vhost_get_vring_base = vhost_vdpa_get_vring_base, .vhost_set_vring_kick = vhost_vdpa_set_vring_kick, .vhost_set_vring_call = vhost_vdpa_set_vring_call, .vhost_get_features = vhost_vdpa_get_features, .vhost_set_owner = vhost_vdpa_set_owner, .vhost_set_vring_endian = NULL, .vhost_backend_memslots_limit = vhost_vdpa_memslots_limit, .vhost_set_mem_table = vhost_vdpa_set_mem_table, .vhost_set_features = vhost_vdpa_set_features, .vhost_reset_device = vhost_vdpa_reset_device, .vhost_get_vq_index = vhost_vdpa_get_vq_index, .vhost_get_config = vhost_vdpa_get_config, .vhost_set_config = vhost_vdpa_set_config, .vhost_requires_shm_log = NULL, .vhost_migration_done = NULL, .vhost_backend_can_merge = NULL, .vhost_net_set_mtu = NULL, .vhost_set_iotlb_callback = NULL, .vhost_send_device_iotlb_msg = NULL, .vhost_dev_start = vhost_vdpa_dev_start, .vhost_get_device_id = vhost_vdpa_get_device_id, .vhost_vq_get_addr = vhost_vdpa_vq_get_addr, .vhost_force_iommu = vhost_vdpa_force_iommu, };
dslutz/qemu
hw/virtio/vhost-vdpa.c
C
gpl-2.0
14,501
/* * Copyright (c) 2006 Boudewijn Rempt <boud@valdyas.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_transparency_mask.h" #include "kis_debug.h" #include <KoIcon.h> #include <KoColor.h> #include <KoColorSpace.h> #include <KoCompositeOpRegistry.h> #include "kis_paint_device.h" #include "kis_painter.h" #include "kis_node_visitor.h" #include "kis_processing_visitor.h" KisTransparencyMask::KisTransparencyMask() : KisEffectMask() { } KisTransparencyMask::KisTransparencyMask(const KisTransparencyMask& rhs) : KisEffectMask(rhs) { } KisTransparencyMask::~KisTransparencyMask() { } bool KisTransparencyMask::allowAsChild(KisNodeSP node) const { Q_UNUSED(node); return false; } QRect KisTransparencyMask::decorateRect(KisPaintDeviceSP &src, KisPaintDeviceSP &dst, const QRect & rc) const { if (src != dst) { KisPainter gc(dst); gc.setCompositeOp(src->colorSpace()->compositeOp(COMPOSITE_COPY)); gc.bitBlt(rc.topLeft(), src, rc); src->fill(rc, KoColor(Qt::transparent, src->colorSpace())); } return rc; } QRect KisTransparencyMask::extent() const { return parent() ? parent()->extent() : QRect(); } QRect KisTransparencyMask::exactBounds() const { return parent() ? parent()->exactBounds() : QRect(); } QRect KisTransparencyMask::changeRect(const QRect &rect, PositionToFilthy pos) const { /** * Selection on transparency masks have no special meaning: * They do crop both: change and need area */ return KisMask::changeRect(rect, pos); } QRect KisTransparencyMask::needRect(const QRect &rect, PositionToFilthy pos) const { /** * Selection on transparency masks have no special meaning: * They do crop both: change and need area */ return KisMask::needRect(rect, pos); } QIcon KisTransparencyMask::icon() const { return koIcon("view-filter"); } bool KisTransparencyMask::accept(KisNodeVisitor &v) { return v.visit(this); } void KisTransparencyMask::accept(KisProcessingVisitor &visitor, KisUndoAdapter *undoAdapter) { return visitor.visit(this, undoAdapter); } #include "kis_transparency_mask.moc"
harshitamistry/calligraRepository
krita/image/kis_transparency_mask.cc
C++
gpl-2.0
2,935
<?php /** * File containing a Test Case for LimitationType class * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.07.0 */ namespace eZ\Publish\Core\Limitation\Tests; use eZ\Publish\API\Repository\Values\ValueObject; use eZ\Publish\API\Repository\Values\Content\ContentInfo; use eZ\Publish\API\Repository\Values\Content\LocationCreateStruct; use eZ\Publish\API\Repository\Values\Content\Query\Criterion\Operator; use eZ\Publish\API\Repository\Values\User\Limitation; use eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation; use eZ\Publish\API\Repository\Values\User\Limitation\ObjectStateLimitation; use eZ\Publish\Core\Base\Exceptions\NotFoundException; use eZ\Publish\Core\Limitation\ParentContentTypeLimitationType; use eZ\Publish\Core\Repository\Values\Content\Location; use eZ\Publish\Core\Repository\Values\Content\ContentCreateStruct; use eZ\Publish\SPI\Persistence\Content\ContentInfo as SPIContentInfo; use eZ\Publish\SPI\Persistence\Content\Location as SPILocation; use eZ\Publish\SPI\Persistence\Content\Type as SPIContentType; /** * Test Case for LimitationType */ class ParentContentTypeLimitationTest extends Base { /** * @var \eZ\Publish\SPI\Persistence\Content\Location\Handler|\PHPUnit_Framework_MockObject_MockObject */ private $locationHandlerMock; /** * @var \eZ\Publish\SPI\Persistence\Content\Type\Handler|\PHPUnit_Framework_MockObject_MockObject */ private $contentTypeHandlerMock; /** * @var \eZ\Publish\SPI\Persistence\Content\Handler|\PHPUnit_Framework_MockObject_MockObject */ private $contentHandlerMock; /** * Setup Location Handler mock */ public function setUp() { parent::setUp(); $this->locationHandlerMock = $this->getMock( "eZ\\Publish\\SPI\\Persistence\\Content\\Location\\Handler", array(), array(), '', false ); $this->contentTypeHandlerMock = $this->getMock( "eZ\\Publish\\SPI\\Persistence\\Content\\Type\\Handler", array(), array(), '', false ); $this->contentHandlerMock = $this->getMock( "eZ\\Publish\\SPI\\Persistence\\Content\\Handler", array(), array(), '', false ); } /** * Tear down Location Handler mock */ public function tearDown() { unset( $this->locationHandlerMock ); unset( $this->contentTypeHandlerMock ); unset( $this->contentHandlerMock ); parent::tearDown(); } /** * * @return \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType */ public function testConstruct() { return new ParentContentTypeLimitationType( $this->getPersistenceMock() ); } /** * @return array */ public function providerForTestAcceptValue() { return array( array( new ParentContentTypeLimitation() ), array( new ParentContentTypeLimitation( array() ) ), array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '', 'true', '2', 's3fd4af32r' ) ) ) ), ); } /** * @dataProvider providerForTestAcceptValue * @depends testConstruct * * @param \eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation $limitation * @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType */ public function testAcceptValue( ParentContentTypeLimitation $limitation, ParentContentTypeLimitationType $limitationType ) { $limitationType->acceptValue( $limitation ); } /** * @return array */ public function providerForTestAcceptValueException() { return array( array( new ObjectStateLimitation() ), array( new ParentContentTypeLimitation( array( 'limitationValues' => array( true ) ) ) ), array( new ParentContentTypeLimitation( array( 'limitationValues' => array( new \DateTime ) ) ) ), ); } /** * @dataProvider providerForTestAcceptValueException * @depends testConstruct * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException * * @param \eZ\Publish\API\Repository\Values\User\Limitation $limitation * @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType */ public function testAcceptValueException( Limitation $limitation, ParentContentTypeLimitationType $limitationType ) { $limitationType->acceptValue( $limitation ); } /** * @return array */ public function providerForTestValidatePass() { return array( array( new ParentContentTypeLimitation() ), array( new ParentContentTypeLimitation( array() ) ), array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '1' ) ) ) ), ); } /** * @dataProvider providerForTestValidatePass * * @param \eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation $limitation */ public function testValidatePass( ParentContentTypeLimitation $limitation ) { if ( !empty( $limitation->limitationValues ) ) { $this->getPersistenceMock() ->expects( $this->any() ) ->method( "contentTypeHandler" ) ->will( $this->returnValue( $this->contentTypeHandlerMock ) ); foreach ( $limitation->limitationValues as $key => $value ) { $this->contentTypeHandlerMock ->expects( $this->at( $key ) ) ->method( "load" ) ->with( $value ) ->will( $this->returnValue( 42 ) ); } } // Need to create inline instead of depending on testConstruct() to get correct mock instance $limitationType = $this->testConstruct(); $validationErrors = $limitationType->validate( $limitation ); self::assertEmpty( $validationErrors ); } /** * @return array */ public function providerForTestValidateError() { return array( array( new ParentContentTypeLimitation(), 0 ), array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '/1/777/' ) ) ), 1 ), array( new ParentContentTypeLimitation( array( 'limitationValues' => array( '/1/888/', '/1/999/' ) ) ), 2 ), ); } /** * @dataProvider providerForTestValidateError * * @param \eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation $limitation * @param int $errorCount */ public function testValidateError( ParentContentTypeLimitation $limitation, $errorCount ) { if ( !empty( $limitation->limitationValues ) ) { $this->getPersistenceMock() ->expects( $this->any() ) ->method( "contentTypeHandler" ) ->will( $this->returnValue( $this->contentTypeHandlerMock ) ); foreach ( $limitation->limitationValues as $key => $value ) { $this->contentTypeHandlerMock ->expects( $this->at( $key ) ) ->method( "load" ) ->with( $value ) ->will( $this->throwException( new NotFoundException( 'location', $value ) ) ); } } else { $this->getPersistenceMock() ->expects( $this->never() ) ->method( $this->anything() ); } // Need to create inline instead of depending on testConstruct() to get correct mock instance $limitationType = $this->testConstruct(); $validationErrors = $limitationType->validate( $limitation ); self::assertCount( $errorCount, $validationErrors ); } /** * @depends testConstruct * * @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType */ public function testBuildValue( ParentContentTypeLimitationType $limitationType ) { $expected = array( 'test', 'test' => '1' ); $value = $limitationType->buildValue( $expected ); self::assertInstanceOf( '\eZ\Publish\API\Repository\Values\User\Limitation\ParentContentTypeLimitation', $value ); self::assertInternalType( 'array', $value->limitationValues ); self::assertEquals( $expected, $value->limitationValues ); } protected function getTestEvaluateContentMock() { $contentMock = $this->getMock( "eZ\\Publish\\API\\Repository\\Values\\Content\\Content", array(), array(), '', false ); $contentMock ->expects( $this->once() ) ->method( 'getVersionInfo' ) ->will( $this->returnValue( $this->getTestEvaluateVersionInfoMock() ) ); return $contentMock; } protected function getTestEvaluateVersionInfoMock() { $versionInfoMock = $this->getMock( "eZ\\Publish\\API\\Repository\\Values\\Content\\VersionInfo", array(), array(), '', false ); $versionInfoMock ->expects( $this->once() ) ->method( 'getContentInfo' ) ->will( $this->returnValue( new ContentInfo( array( 'published' => true ) ) ) ); return $versionInfoMock; } /** * @return array */ public function providerForTestEvaluate() { return array( // ContentInfo, with API targets, no access array( 'limitation' => new ParentContentTypeLimitation(), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 24 ) ) ) ) ), 'persistence' => array(), 'expected' => false ), // ContentInfo, with SPI targets, no access array( 'limitation' => new ParentContentTypeLimitation(), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array( new SPILocation( array( "contentId" => 42 ) ) ), 'persistence' => array( "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "24" ) ) ) ), 'expected' => false ), // ContentInfo, with API targets, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 24 ) ) ) ) ), 'persistence' => array(), 'expected' => false ), // ContentInfo, with SPI targets, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array( new SPILocation( array( "contentId" => 42 ) ) ), 'persistence' => array( "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "24" ) ) ) ), 'expected' => false ), // ContentInfo, with API targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 42 ) ) ) ) ), 'persistence' => array(), 'expected' => true ), // ContentInfo, with SPI targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array( new SPILocation( array( "contentId" => 24 ) ) ), 'persistence' => array( "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) ) ), 'expected' => true ), // ContentInfo, no targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array(), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ), "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) ) ), 'expected' => true ), // ContentInfo, no targets, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => true ) ), 'targets' => array(), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ), "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "4200" ) ) ) ), 'expected' => false ), // ContentInfo, no targets, un-published, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => false ) ), 'targets' => array(), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ), "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) ) ), 'expected' => true ), // ContentInfo, no targets, un-published, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentInfo( array( 'published' => false ) ), 'targets' => array(), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => '24' ) ) ), "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "4200" ) ) ) ), 'expected' => false ), // Content, with API targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => $this->getTestEvaluateContentMock(), 'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 42 ) ) ) ) ), 'persistence' => array(), 'expected' => true ), // Content, with SPI targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => $this->getTestEvaluateContentMock(), 'targets' => array( new SPILocation( array( 'contentId' => '24' ) ) ), 'persistence' => array( "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) ) ), 'expected' => true ), // VersionInfo, with API targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => $this->getTestEvaluateVersionInfoMock(), 'targets' => array( new Location( array( "contentInfo" => new ContentInfo( array( "contentTypeId" => 42 ) ) ) ) ), 'persistence' => array(), 'expected' => true ), // VersionInfo, with SPI targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => $this->getTestEvaluateVersionInfoMock(), 'targets' => array( new SPILocation( array( 'contentId' => '24' ) ) ), 'persistence' => array( "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) ) ), 'expected' => true ), // VersionInfo, with LocationCreateStruct targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => $this->getTestEvaluateVersionInfoMock(), 'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 24 ) ) ), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ), "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "42" ) ) ) ), 'expected' => true ), // Content, with LocationCreateStruct targets, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => $this->getTestEvaluateContentMock(), 'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 24 ) ) ), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ), "contentInfos" => array( new SPIContentInfo( array( "contentTypeId" => "24" ) ) ) ), 'expected' => false ), // ContentCreateStruct, no targets, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 42 ) ) ), 'object' => new ContentCreateStruct(), 'targets' => array(), 'persistence' => array(), 'expected' => false ), // ContentCreateStruct, with LocationCreateStruct targets, no access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 12, 23 ) ) ), 'object' => new ContentCreateStruct(), 'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 24 ) ) ), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ), "contentInfos" => array( new SPIContentInfo( array( 'contentTypeId' => 34 ) ) ) ), 'expected' => false ), // ContentCreateStruct, with LocationCreateStruct targets, with access array( 'limitation' => new ParentContentTypeLimitation( array( 'limitationValues' => array( 12, 23 ) ) ), 'object' => new ContentCreateStruct(), 'targets' => array( new LocationCreateStruct( array( 'parentLocationId' => 43 ) ) ), 'persistence' => array( "locations" => array( new SPILocation( array( 'contentId' => 100 ) ) ), "contentInfos" => array( new SPIContentInfo( array( 'contentTypeId' => 12 ) ) ) ), 'expected' => true ), ); } protected function assertContentHandlerExpectations( $callNo, $persistenceCalled, $contentId, $contentInfo ) { $this->getPersistenceMock() ->expects( $this->at( $callNo + ( $persistenceCalled ? 1 : 0 ) ) ) ->method( "contentHandler" ) ->will( $this->returnValue( $this->contentHandlerMock ) ); $this->contentHandlerMock ->expects( $this->at( $callNo ) ) ->method( "loadContentInfo" ) ->with( $contentId ) ->will( $this->returnValue( $contentInfo ) ); } /** * @dataProvider providerForTestEvaluate */ public function testEvaluate( ParentContentTypeLimitation $limitation, ValueObject $object, $targets, array $persistence, $expected ) { // Need to create inline instead of depending on testConstruct() to get correct mock instance $limitationType = $this->testConstruct(); $userMock = $this->getUserMock(); $userMock ->expects( $this->never() ) ->method( $this->anything() ); $persistenceMock = $this->getPersistenceMock(); // ContentTypeHandler is never used in evaluate() $persistenceMock ->expects( $this->never() ) ->method( "contentTypeHandler" ); if ( empty( $persistence ) ) { // Covers API targets, where no additional loading is required $persistenceMock ->expects( $this->never() ) ->method( $this->anything() ); } else if ( !empty( $targets ) ) { foreach ( $targets as $index => $target ) { if ( $target instanceof LocationCreateStruct ) { $this->getPersistenceMock() ->expects( $this->once( $index ) ) ->method( "locationHandler" ) ->will( $this->returnValue( $this->locationHandlerMock ) ); $this->locationHandlerMock ->expects( $this->at( $index ) ) ->method( "load" ) ->with( $target->parentLocationId ) ->will( $this->returnValue( $location = $persistence["locations"][$index] ) ); $contentId = $location->contentId; } else { $contentId = $target->contentId; } $this->assertContentHandlerExpectations( $index, $target instanceof LocationCreateStruct, $contentId, $persistence["contentInfos"][$index] ); } } else { $this->getPersistenceMock() ->expects( $this->at( 0 ) ) ->method( "locationHandler" ) ->will( $this->returnValue( $this->locationHandlerMock ) ); $this->locationHandlerMock ->expects( $this->once() ) ->method( $object instanceof ContentInfo && $object->published ? "loadLocationsByContent" : "loadParentLocationsForDraftContent" ) ->with( $object->id ) ->will( $this->returnValue( $persistence["locations"] ) ); foreach ( $persistence["locations"] as $index => $location ) { $this->assertContentHandlerExpectations( $index, true, $location->contentId, $persistence["contentInfos"][$index] ); } } $value = $limitationType->evaluate( $limitation, $userMock, $object, $targets ); self::assertInternalType( 'boolean', $value ); self::assertEquals( $expected, $value ); } /** * @return array */ public function providerForTestEvaluateInvalidArgument() { return array( // invalid limitation array( 'limitation' => new ObjectStateLimitation(), 'object' => new ContentInfo(), 'targets' => array( new Location() ), 'persistence' => array(), ), // invalid object array( 'limitation' => new ParentContentTypeLimitation(), 'object' => new ObjectStateLimitation(), 'targets' => array(), 'persistence' => array(), ), // invalid target when using ContentCreateStruct array( 'limitation' => new ParentContentTypeLimitation(), 'object' => new ContentCreateStruct(), 'targets' => array( new Location() ), 'persistence' => array(), ), // invalid target when not using ContentCreateStruct array( 'limitation' => new ParentContentTypeLimitation(), 'object' => new ContentInfo(), 'targets' => array( new ObjectStateLimitation() ), 'persistence' => array(), ), ); } /** * @dataProvider providerForTestEvaluateInvalidArgument * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException */ public function testEvaluateInvalidArgument( Limitation $limitation, ValueObject $object, $targets ) { // Need to create inline instead of depending on testConstruct() to get correct mock instance $limitationType = $this->testConstruct(); $userMock = $this->getUserMock(); $userMock ->expects( $this->never() ) ->method( $this->anything() ); $persistenceMock = $this->getPersistenceMock(); $persistenceMock ->expects( $this->never() ) ->method( $this->anything() ); $limitationType->evaluate( $limitation, $userMock, $object, $targets ); } /** * @depends testConstruct * @expectedException \eZ\Publish\API\Repository\Exceptions\NotImplementedException * * @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType */ public function testGetCriterionInvalidValue( ParentContentTypeLimitationType $limitationType ) { $limitationType->getCriterion( new ParentContentTypeLimitation( array() ), $this->getUserMock() ); } /** * @depends testConstruct * * @param \eZ\Publish\Core\Limitation\ParentContentTypeLimitationType $limitationType */ public function testValueSchema( ParentContentTypeLimitationType $limitationType ) { $this->markTestIncomplete( "Method is not implemented yet: " . __METHOD__ ); } }
brookinsconsulting/ezpedia
vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/Limitation/Tests/ParentContentTypeLimitationTypeTest.php
PHP
gpl-2.0
27,600
package Lacuna::DB::Result::Building::SSLa; use Moose; use utf8; no warnings qw(uninitialized); extends 'Lacuna::DB::Result::Building'; use Lacuna::Constants qw(ORE_TYPES INFLATION); around 'build_tags' => sub { my ($orig, $class) = @_; return ($orig->($class), qw(Construction Ships)); }; use constant university_prereq => 20; use constant max_instances_per_planet => 1; use constant controller_class => 'Lacuna::RPC::Building::SSLa'; use constant image => 'ssla'; use constant name => 'Space Station Lab (A)'; use constant food_to_build => 230; use constant energy_to_build => 350; use constant ore_to_build => 370; use constant water_to_build => 260; use constant waste_to_build => 100; use constant time_to_build => 60 * 2; use constant food_consumption => 5; use constant energy_consumption => 20; use constant ore_consumption => 15; use constant water_consumption => 6; use constant waste_production => 20; before 'can_demolish' => sub { my $self = shift; my $sslb = $self->body->get_building_of_class('Lacuna::DB::Result::Building::SSLb'); if (defined $sslb) { confess [1013, 'You have to demolish your Space Station Lab (B) before you can demolish your Space Station Lab (A).']; } }; before can_build => sub { my $self = shift; if ($self->x == 5 || $self->y == -5 || (($self->y == 1 || $self->y == 0) && ($self->x == -1 || $self->x == 0))) { confess [1009, 'Space Station Lab cannot be placed in that location.']; } }; sub makeable_plans { return { command => 'Lacuna::DB::Result::Building::Module::StationCommand', ibs => 'Lacuna::DB::Result::Building::Module::IBS', art => 'Lacuna::DB::Result::Building::Module::ArtMuseum', opera => 'Lacuna::DB::Result::Building::Module::OperaHouse', food => 'Lacuna::DB::Result::Building::Module::CulinaryInstitute', parliament => 'Lacuna::DB::Result::Building::Module::Parliament', warehouse => 'Lacuna::DB::Result::Building::Module::Warehouse', policestation => 'Lacuna::DB::Result::Building::Module::PoliceStation', }; } sub makeable_plans_formatted { my $self = shift; my @out; my $makeable_plans = $self->makeable_plans; while (my ($type, $class) = each %{$makeable_plans}) { push @out, { image => $class->image, name => $class->name, url => $class->controller_class->app_url, type => $type, }; } @out = sort { $a->{name} cmp $b->{name} } @out; return \@out; } sub level_costs_formatted { my $self = shift; my $max = $self->max_level; return [] if $max == 0; my @costs; my $resource_cost = $self->plan_resource_cost; my $time_cost = $self->plan_time_cost; foreach my $level (1..$max) { my $resource = $self->plan_cost_at_level($level, $resource_cost); push @costs, { level => $level, ore => $resource, water => $resource, energy => $resource, food => $resource, waste => sprintf('%.0f', $resource/2), time => $self->plan_time_at_level($level, $time_cost), }; } return \@costs; } has plan_resource_cost => ( is => 'rw', lazy => 1, default => sub { my $self = shift; return 850_000; } ); has plan_time_cost => ( is => 'rw', lazy => 1, default => sub { my $self = shift; return 150; } ); sub plan_time_at_level { my ($self, $level, $base) = @_; my $inflate = INFLATION - (($self->max_level + $self->body->empire->effective_manufacturing_affinity * 5)/200); my $time_cost = int($base * ($inflate ** $level)); $time_cost = 15 if ($time_cost < 15); $time_cost = 5184000 if ($time_cost > 5184000); return $time_cost; } sub plan_cost_at_level { my ($self, $level, $base) = @_; my $inflate = INFLATION - (($self->max_level + $self->body->empire->effective_research_affinity * 5)/200); my $cost = int($base * ($inflate ** $level)); return $cost; } has max_level => ( is => 'rw', lazy => 1, default => sub { my $self = shift; my $level = $self->effective_level; my $body = $self->body; foreach my $part (qw(b c d)) { my $building = $body->get_building_of_class('Lacuna::DB::Result::Building::SSL'.$part); if (defined $building) { $level = ($level > $building->effective_level) ? $building->effective_level : $level; } else { $level = 0; last; } } return $level; }, ); sub can_make_plan { my ($self, $type, $level) = @_; if ($self->is_working) { confess [1010, 'The Space Station Lab is already making a plan.']; } $level ||= 1; if ($level > $self->max_level) { confess [1013, 'This Space Station Lab is not a high enough level to make that plan.']; } my $makeable = $self->makeable_plans; unless ($type ~~ [keys %{$makeable}]) { confess [1009, 'Cannot make that type of plan.']; } my $resource_cost = $self->plan_cost_at_level($level, $self->plan_resource_cost); my $fraction = sprintf('%.0f',$resource_cost * 0.01); my $body = $self->body; foreach my $ore (ORE_TYPES) { if ($body->type_stored($ore) < $fraction) { confess [1011, 'Not enough '.$ore.' in storage. You need at least '.$fraction.'.']; } } foreach my $resource (qw(ore water food energy)) { if ($body->type_stored($resource) < $resource_cost) { confess [1011, 'Not enough '.$resource.' in storage. You need at least '.$resource_cost.'.']; } } return 1; } sub make_plan { my ($self, $type, $level) = @_; $level ||= 1; my $makeable = $self->makeable_plans; my $resource_cost = $self->plan_cost_at_level($level, $self->plan_resource_cost); my $time_cost = $self->plan_time_at_level($level, $self->plan_time_cost); my $body = $self->body; $body->spend_ore($resource_cost); $body->spend_water($resource_cost); $body->spend_food($resource_cost, 0); $body->spend_energy($resource_cost); $body->add_waste($resource_cost/4); $body->update; $self->start_work({ class => $makeable->{$type}, level => $level, }, $time_cost)->update; } before finish_work => sub { my $self = shift; my $planet = $self->body; $planet->add_plan($self->work->{class}, $self->work->{level}); }; no Moose; __PACKAGE__->meta->make_immutable(inline_constructor => 0);
plainblack/Lacuna-Server-Open
lib/Lacuna/DB/Result/Building/SSLa.pm
Perl
gpl-2.0
6,766
<?php /** * @version $Id: imgmanager.php 46 2009-05-26 16:59:42Z happynoodleboy $ * @package JCE * @copyright Copyright (C) 2005 - 2009 Ryan Demmer. All rights reserved. * @author Ryan Demmer * @license GNU/GPL * JCE 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. */ defined('_JEXEC') or die('Restricted access'); require_once(JCE_LIBRARIES .DS. 'classes' .DS. 'manager.php'); class ImageManager extends Manager { var $_ext = 'image=jpg,jpeg,gif,png'; /** * @access protected */ function __construct() { parent::__construct(); // Set the file type map from parameters $this->setFileTypes($this->getPluginParam('imgmanager_extensions', $this->_ext)); // Init plugin $this->init(); } /** * Returns a reference to a editor object * * This method must be invoked as: * <pre> $browser = &JCE::getInstance();</pre> * * @access public * @return JCE The editor object. * @since 1.5 */ function &getInstance() { static $instance; if (!is_object($instance)) { $instance = new ImageManager(); } return $instance; } /** * Initialise the plugin */ function init() { // check the user/group has editor permissions $this->checkPlugin() or die(JError::raiseError(403, JText::_('Access Forbidden'))); parent::init(); // Setup plugin XHR callback functions $this->setXHR(array($this, 'getDimensions')); // Set javascript file array $this->script(array('imgmanager'), 'plugins'); // Set css file array $this->css(array('imgmanager'), 'plugins'); // Load extensions if any $this->loadExtensions(); } /** * Get the dimensions of an image * @return array Dimensions as array * @param object $file Relative path to image */ function getDimensions($file) { $path = Utils::makePath($this->getBaseDir(), rawurldecode($file)); $h = array( 'width' => '', 'height' => '' ); if (file_exists($path)) { $dim = @getimagesize($path); $h = array( 'width' => $dim[0], 'height' => $dim[1] ); } return $h; } /** * Get list of uploadable extensions * @return Mapped extension list (list mapped to type object eg: 'images', 'jpeg,jpg,gif,png') */ function getUploadFileTypes() { $list = $this->getPluginParam('imgmanager_extensions', 'image=jpg,jpeg,gif,png'); return $this->mapUploadFileTypes($list); } } ?>
jahama/cbhondarribia.com
plugins/editors/jce/tiny_mce/plugins/imgmanager/classes/imgmanager.php
PHP
gpl-2.0
2,679
/* $Id: fileaio.h $ */ /** @file * IPRT - Internal RTFileAio header. */ /* * Copyright (C) 2009-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #ifndef ___internal_fileaio_h #define ___internal_fileaio_h #include <iprt/file.h> #include "internal/magics.h" /******************************************************************************* * Structures and Typedefs * *******************************************************************************/ /** * Defined request states. */ typedef enum RTFILEAIOREQSTATE { /** Prepared. */ RTFILEAIOREQSTATE_PREPARED = 0, /** Submitted. */ RTFILEAIOREQSTATE_SUBMITTED, /** Completed. */ RTFILEAIOREQSTATE_COMPLETED, /** Omni present 32bit hack. */ RTFILEAIOREQSTATE_32BIT_HACK = 0x7fffffff } RTFILEAIOREQSTATE; /******************************************************************************* * Defined Constants And Macros * *******************************************************************************/ /** Return true if the specified request is not valid, false otherwise. */ #define RTFILEAIOREQ_IS_NOT_VALID(pReq) \ (RT_UNLIKELY(!VALID_PTR(pReq) || (pReq->u32Magic != RTFILEAIOREQ_MAGIC))) /** Validates a context handle and returns VERR_INVALID_HANDLE if not valid. */ #define RTFILEAIOREQ_VALID_RETURN_RC(pReq, rc) \ do { \ AssertPtrReturn((pReq), (rc)); \ AssertReturn((pReq)->u32Magic == RTFILEAIOREQ_MAGIC, (rc)); \ } while (0) /** Validates a context handle and returns VERR_INVALID_HANDLE if not valid. */ #define RTFILEAIOREQ_VALID_RETURN(pReq) RTFILEAIOREQ_VALID_RETURN_RC((pReq), VERR_INVALID_HANDLE) /** Validates a context handle and returns (void) if not valid. */ #define RTFILEAIOREQ_VALID_RETURN_VOID(pReq) \ do { \ AssertPtrReturnVoid(pReq); \ AssertReturnVoid((pReq)->u32Magic == RTFILEAIOREQ_MAGIC); \ } while (0) /** Validates a context handle and returns the specified rc if not valid. */ #define RTFILEAIOCTX_VALID_RETURN_RC(pCtx, rc) \ do { \ AssertPtrReturn((pCtx), (rc)); \ AssertReturn((pCtx)->u32Magic == RTFILEAIOCTX_MAGIC, (rc)); \ } while (0) /** Validates a context handle and returns VERR_INVALID_HANDLE if not valid. */ #define RTFILEAIOCTX_VALID_RETURN(pCtx) RTFILEAIOCTX_VALID_RETURN_RC((pCtx), VERR_INVALID_HANDLE) /** Checks if a request is in the specified state and returns the specified rc if not. */ #define RTFILEAIOREQ_STATE_RETURN_RC(pReq, State, rc) \ do { \ if (RT_UNLIKELY(pReq->enmState != RTFILEAIOREQSTATE_##State)) \ return rc; \ } while (0) /** Checks if a request is not in the specified state and returns the specified rc if it is. */ #define RTFILEAIOREQ_NOT_STATE_RETURN_RC(pReq, State, rc) \ do { \ if (RT_UNLIKELY(pReq->enmState == RTFILEAIOREQSTATE_##State)) \ return rc; \ } while (0) /** Checks if a request in the given states and sserts if not. */ #define RTFIELAIOREQ_ASSERT_STATE(pReq, State) \ do { \ AssertPtr((pReq)); \ Assert((pReq)->u32Magic == RTFILEAIOREQ_MAGIC); \ Assert((pReq)->enmState == RTFILEAIOREQSTATE_##State); \ } while (0) /** Sets the request into a specific state. */ #define RTFILEAIOREQ_SET_STATE(pReq, State) \ do { \ pReq->enmState = RTFILEAIOREQSTATE_##State; \ } while (0) RT_C_DECLS_BEGIN RT_C_DECLS_END #endif
sobomax/virtualbox_64bit_edd
src/VBox/Runtime/include/internal/fileaio.h
C
gpl-2.0
4,411
/* EventON Generate Google maps function */ (function($){ $.fn.evoGenmaps = function(opt){ var defaults = { delay: 0, fnt: 1, cal: '', mapSpotId: '', _action:'' }; var options = $.extend({}, defaults, opt); var geocoder; // popup lightbox generation if(options._action=='lightbox'){ var cur_window_top = parseInt($(window).scrollTop()) + 50; $('.evo_popin').css({'margin-top':cur_window_top}); $('.evo_pop_body').html(''); var event_list = this.closest('.eventon_events_list'); var content = this.siblings('.event_description').html(); var content_front = this.html(); var _content = $(content).not('.evcal_close'); // RTL if(event_list.hasClass('evortl')){ $('.evo_popin').addClass('evortl'); } $('.evo_pop_body').append('<div class="evopop_top">'+content_front+'</div>').append(_content); var this_map = $('.evo_pop_body').find('.evcal_gmaps'); var idd = this_map.attr('id'); this_map.attr({'id':idd+'_evop'}); $('.evo_popup').fadeIn(300); $('.evo_popbg').fadeIn(300); // check if gmaps should run if( this.attr('data-gmtrig')=='1' && this.attr('data-gmap_status')!='null'){ var cal = this.closest('div.ajde_evcal_calendar '); loadl_gmaps_in(this, cal, idd+'_evop'); } } // functions if(options.fnt==1){ this.each(function(){ var eventcard = $(this).attr('eventcard'); if(eventcard=='1'){ $(this).find('a.desc_trig').each(function(elm){ //$(this).siblings('.event_description').slideDown(); var obj = $(this); if(options.delay==0){ load_googlemaps_here(obj); }else{ setTimeout(load_googlemaps_here, options.delay, obj); } }); } }); } if(options.fnt==2){ if(options.delay==0){ load_googlemaps_here(this); }else{ setTimeout(load_googlemaps_here, options.delay, this); } } if(options.fnt==3){ loadl_gmaps_in(this, options.cal, ''); } // gmaps on popup if(options.fnt==4){ // check if gmaps should run if( this.attr('data-gmtrig')=='1' && this.attr('data-gmap_status')!='null'){ var cal = this.closest('div.ajde_evcal_calendar '); loadl_gmaps_in(this, cal, options.mapSpotId); } } // function to load google maps for eventcard function load_googlemaps_here(obj){ if( obj.data('gmstat')!= '1'){ obj.attr({'data-gmstat':'1'}); } var cal = obj.closest('div.ajde_evcal_calendar '); if( obj.attr('data-gmtrig')=='1' && obj.attr('data-gmap_status')!='null'){ loadl_gmaps_in(obj, cal, ''); } } // Load the google map on the object function loadl_gmaps_in(obj, cal, mapId){ var evodata = cal.find('.evo-data'); var mapformat = evodata.data('mapformat'); var ev_location = obj.find('.evcal_desc'); var location_type = ev_location.attr('data-location_type'); if(location_type=='address'){ var address = ev_location.attr('data-location_address'); var location_type = 'add'; }else{ var address = ev_location.attr('data-latlng'); var location_type = 'latlng'; } var map_canvas_id= (mapId!=='')? mapId: obj.siblings('.event_description').find('.evcal_gmaps').attr('id'); // google maps styles // @since 2.2.22 var styles = ''; if(gmapstyles != 'default'){ styles = $.parseJSON(gmapstyles); } var zoom = evodata.data('mapzoom'); var zoomlevel = (typeof zoom !== 'undefined' && zoom !== false)? parseInt(zoom):12; var scroll = evodata.data('mapscroll'); //console.log(map_canvas_id+' '+mapformat+' '+ location_type +' '+scroll +' '+ address); //obj.siblings('.event_description').find('.evcal_gmaps').html(address); initialize(map_canvas_id, address, mapformat, zoomlevel, location_type, scroll, styles); } //console.log(options); }; }(jQuery));
sabdev1/sabhoa
wp-content/plugins/eventON/assets/js/maps/eventon_gen_maps.js
JavaScript
gpl-2.0
4,157
<?php /** * @package Joomla.Administrator * @subpackage com_admin * * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * Script file of Joomla CMS * * @since 1.6.4 */ class JoomlaInstallerScript { /** * Method to update Joomla! * * @param JInstallerAdapterFile $installer The class calling this method * * @return void */ public function update($installer) { $options['format'] = '{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}'; $options['text_file'] = 'joomla_update.php'; JLog::addLogger($options, JLog::INFO, array('Update', 'databasequery', 'jerror')); JLog::add(JText::_('COM_JOOMLAUPDATE_UPDATE_LOG_DELETE_FILES'), JLog::INFO, 'Update'); // This needs to stay for 2.5 update compatibility $this->deleteUnexistingFiles(); $this->updateManifestCaches(); $this->updateDatabase(); $this->clearRadCache(); $this->updateAssets(); $this->clearStatsCache(); $this->convertTablesToUtf8mb4(true); $this->cleanJoomlaCache(); // VERY IMPORTANT! THIS METHOD SHOULD BE CALLED LAST, SINCE IT COULD // LOGOUT ALL THE USERS $this->flushSessions(); } /** * Method to clear our stats plugin cache to ensure we get fresh data on Joomla Update * * @return void * * @since 3.5 */ protected function clearStatsCache() { $db = JFactory::getDbo(); try { // Get the params for the stats plugin $params = $db->setQuery( $db->getQuery(true) ->select($db->quoteName('params')) ->from($db->quoteName('#__extensions')) ->where($db->quoteName('type') . ' = ' . $db->quote('plugin')) ->where($db->quoteName('folder') . ' = ' . $db->quote('system')) ->where($db->quoteName('element') . ' = ' . $db->quote('stats')) )->loadResult(); } catch (Exception $e) { echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />'; return; } $params = json_decode($params, true); // Reset the last run parameter if (isset($params['lastrun'])) { $params['lastrun'] = ''; } $params = json_encode($params); $query = $db->getQuery(true) ->update($db->quoteName('#__extensions')) ->set($db->quoteName('params') . ' = ' . $db->quote($params)) ->where($db->quoteName('type') . ' = ' . $db->quote('plugin')) ->where($db->quoteName('folder') . ' = ' . $db->quote('system')) ->where($db->quoteName('element') . ' = ' . $db->quote('stats')); try { $db->setQuery($query)->execute(); } catch (Exception $e) { echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />'; return; } } /** * Method to update Database * * @return void */ protected function updateDatabase() { $db = JFactory::getDbo(); if (strpos($db->name, 'mysql') !== false) { $this->updateDatabaseMysql(); } $this->uninstallEosPlugin(); } /** * Method to update MySQL Database * * @return void */ protected function updateDatabaseMysql() { $db = JFactory::getDbo(); $db->setQuery('SHOW ENGINES'); try { $results = $db->loadObjectList(); } catch (Exception $e) { echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />'; return; } foreach ($results as $result) { if ($result->Support != 'DEFAULT') { continue; } $db->setQuery('ALTER TABLE #__update_sites_extensions ENGINE = ' . $result->Engine); try { $db->execute(); } catch (Exception $e) { echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />'; return; } break; } } /** * Uninstall the 2.5 EOS plugin * * @return void */ protected function uninstallEosPlugin() { $db = JFactory::getDbo(); // Check if the 2.5 EOS plugin is present and uninstall it if so $id = $db->setQuery( $db->getQuery(true) ->select('extension_id') ->from('#__extensions') ->where('name = ' . $db->quote('PLG_EOSNOTIFY')) )->loadResult(); if (!$id) { return; } // We need to unprotect the plugin so we can uninstall it $db->setQuery( $db->getQuery(true) ->update('#__extensions') ->set('protected = 0') ->where($db->quoteName('extension_id') . ' = ' . $id) )->execute(); $installer = new JInstaller; $installer->uninstall('plugin', $id); } /** * Update the manifest caches * * @return void */ protected function updateManifestCaches() { $extensions = array( // Components // `type`, `element`, `folder`, `client_id` array('component', 'com_mailto', '', 0), array('component', 'com_wrapper', '', 0), array('component', 'com_admin', '', 1), array('component', 'com_ajax', '', 1), array('component', 'com_banners', '', 1), array('component', 'com_cache', '', 1), array('component', 'com_categories', '', 1), array('component', 'com_checkin', '', 1), array('component', 'com_contact', '', 1), array('component', 'com_cpanel', '', 1), array('component', 'com_installer', '', 1), array('component', 'com_languages', '', 1), array('component', 'com_login', '', 1), array('component', 'com_media', '', 1), array('component', 'com_menus', '', 1), array('component', 'com_messages', '', 1), array('component', 'com_modules', '', 1), array('component', 'com_newsfeeds', '', 1), array('component', 'com_plugins', '', 1), array('component', 'com_search', '', 1), array('component', 'com_templates', '', 1), array('component', 'com_content', '', 1), array('component', 'com_config', '', 1), array('component', 'com_redirect', '', 1), array('component', 'com_users', '', 1), array('component', 'com_finder', '', 1), array('component', 'com_tags', '', 1), array('component', 'com_contenthistory', '', 1), array('component', 'com_postinstall', '', 1), array('component', 'com_joomlaupdate', '', 1), // Libraries array('library', 'phputf8', '', 0), array('library', 'joomla', '', 0), array('library', 'idna_convert', '', 0), array('library', 'fof', '', 0), array('library', 'phpass', '', 0), // Modules // - Site array('module', 'mod_articles_archive', '', 0), array('module', 'mod_articles_latest', '', 0), array('module', 'mod_articles_popular', '', 0), array('module', 'mod_banners', '', 0), array('module', 'mod_breadcrumbs', '', 0), array('module', 'mod_custom', '', 0), array('module', 'mod_feed', '', 0), array('module', 'mod_footer', '', 0), array('module', 'mod_login', '', 0), array('module', 'mod_menu', '', 0), array('module', 'mod_articles_news', '', 0), array('module', 'mod_random_image', '', 0), array('module', 'mod_related_items', '', 0), array('module', 'mod_search', '', 0), array('module', 'mod_stats', '', 0), array('module', 'mod_syndicate', '', 0), array('module', 'mod_users_latest', '', 0), array('module', 'mod_whosonline', '', 0), array('module', 'mod_wrapper', '', 0), array('module', 'mod_articles_category', '', 0), array('module', 'mod_articles_categories', '', 0), array('module', 'mod_languages', '', 0), array('module', 'mod_tags_popular', '', 0), array('module', 'mod_tags_similar', '', 0), // - Administrator array('module', 'mod_custom', '', 1), array('module', 'mod_feed', '', 1), array('module', 'mod_latest', '', 1), array('module', 'mod_logged', '', 1), array('module', 'mod_login', '', 1), array('module', 'mod_menu', '', 1), array('module', 'mod_popular', '', 1), array('module', 'mod_quickicon', '', 1), array('module', 'mod_stats_admin', '', 1), array('module', 'mod_status', '', 1), array('module', 'mod_submenu', '', 1), array('module', 'mod_title', '', 1), array('module', 'mod_toolbar', '', 1), array('module', 'mod_multilangstatus', '', 1), // Plugins array('plugin', 'gmail', 'authentication', 0), array('plugin', 'joomla', 'authentication', 0), array('plugin', 'ldap', 'authentication', 0), array('plugin', 'contact', 'content', 0), array('plugin', 'emailcloak', 'content', 0), array('plugin', 'loadmodule', 'content', 0), array('plugin', 'pagebreak', 'content', 0), array('plugin', 'pagenavigation', 'content', 0), array('plugin', 'vote', 'content', 0), array('plugin', 'codemirror', 'editors', 0), array('plugin', 'none', 'editors', 0), array('plugin', 'tinymce', 'editors', 0), array('plugin', 'article', 'editors-xtd', 0), array('plugin', 'image', 'editors-xtd', 0), array('plugin', 'pagebreak', 'editors-xtd', 0), array('plugin', 'readmore', 'editors-xtd', 0), array('plugin', 'categories', 'search', 0), array('plugin', 'contacts', 'search', 0), array('plugin', 'content', 'search', 0), array('plugin', 'newsfeeds', 'search', 0), array('plugin', 'tags', 'search', 0), array('plugin', 'languagefilter', 'system', 0), array('plugin', 'p3p', 'system', 0), array('plugin', 'cache', 'system', 0), array('plugin', 'debug', 'system', 0), array('plugin', 'log', 'system', 0), array('plugin', 'redirect', 'system', 0), array('plugin', 'remember', 'system', 0), array('plugin', 'sef', 'system', 0), array('plugin', 'logout', 'system', 0), array('plugin', 'contactcreator', 'user', 0), array('plugin', 'joomla', 'user', 0), array('plugin', 'profile', 'user', 0), array('plugin', 'joomla', 'extension', 0), array('plugin', 'joomla', 'content', 0), array('plugin', 'languagecode', 'system', 0), array('plugin', 'joomlaupdate', 'quickicon', 0), array('plugin', 'extensionupdate', 'quickicon', 0), array('plugin', 'recaptcha', 'captcha', 0), array('plugin', 'categories', 'finder', 0), array('plugin', 'contacts', 'finder', 0), array('plugin', 'content', 'finder', 0), array('plugin', 'newsfeeds', 'finder', 0), array('plugin', 'tags', 'finder', 0), array('plugin', 'totp', 'twofactorauth', 0), array('plugin', 'yubikey', 'twofactorauth', 0), array('plugin', 'updatenotification', 'system', 0), array('plugin', 'module', 'editors-xtd', 0), array('plugin', 'stats', 'system', 0), array('plugin', 'packageinstaller', 'installer', 0), array('plugin', 'folderinstaller', 'installer', 0), array('plugin', 'urlinstaller', 'installer', 0), array('plugin', 'phpversioncheck', 'quickicon', 0), array('plugin', 'menu', 'editors-xtd', 0), array('plugin', 'contact', 'editors-xtd', 0), // Templates array('template', 'beez3', '', 0), array('template', 'hathor', '', 1), array('template', 'protostar', '', 0), array('template', 'isis', '', 1), // Languages array('language', 'en-GB', '', 0), array('language', 'en-GB', '', 1), // Files array('file', 'joomla', '', 0), // Packages array('package', 'pkg_en-GB', '', 0), ); // Attempt to refresh manifest caches $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('*') ->from('#__extensions'); foreach ($extensions as $extension) { $query->where( 'type=' . $db->quote($extension[0]) . ' AND element=' . $db->quote($extension[1]) . ' AND folder=' . $db->quote($extension[2]) . ' AND client_id=' . $extension[3], 'OR' ); } $db->setQuery($query); try { $extensions = $db->loadObjectList(); } catch (Exception $e) { echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />'; return; } $installer = new JInstaller; foreach ($extensions as $extension) { if (!$installer->refreshManifestCache($extension->extension_id)) { echo JText::sprintf('FILES_JOOMLA_ERROR_MANIFEST', $extension->type, $extension->element, $extension->name, $extension->client_id) . '<br />'; } } } /** * Delete files that should not exist * * @return void */ public function deleteUnexistingFiles() { $files = array( // Joomla 1.6 - 1.7 - 2.5 '/libraries/cms/cmsloader.php', '/libraries/joomla/database/databaseexception.php', '/libraries/joomla/database/databasequery.php', '/libraries/joomla/environment/response.php', '/libraries/joomla/form/fields/templatestyle.php', '/libraries/joomla/form/fields/user.php', '/libraries/joomla/form/fields/menu.php', '/libraries/joomla/form/fields/helpsite.php', '/libraries/joomla/github/gists.php', '/libraries/joomla/github/issues.php', '/libraries/joomla/github/pulls.php', '/libraries/joomla/log/logentry.php', '/administrator/components/com_admin/sql/updates/mysql/1.7.0.sql', '/administrator/components/com_admin/sql/updates/sqlsrv/2.5.2-2012-03-05.sql', '/administrator/components/com_admin/sql/updates/sqlsrv/2.5.3-2012-03-13.sql', '/administrator/components/com_admin/sql/updates/sqlsrv/index.html', '/administrator/components/com_content/models/fields/filters.php', '/administrator/components/com_users/controllers/config.php', '/administrator/components/com_users/helpers/levels.php', '/administrator/language/en-GB/en-GB.plg_system_finder.ini', '/administrator/language/en-GB/en-GB.plg_system_finder.sys.ini', '/administrator/modules/mod_quickicon/tmpl/default_button.php', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/print/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/save/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/editor_plugin_src.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/editor_template_src.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/editor_template_src.js', '/media/editors/tinymce/jscripts/tiny_mce/tiny_mce_src.js', '/media/com_finder/images/calendar.png', '/media/com_finder/images/mime/index.html', '/media/com_finder/images/mime/pdf.png', '/components/com_media/controller.php', '/components/com_media/helpers/index.html', '/components/com_media/helpers/media.php', // Joomla 3.0 '/administrator/components/com_admin/sql/updates/mysql/1.7.0-2011-06-06-2.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.0-2011-06-06.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.0.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-2.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-3.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-4.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-17.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-20.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-10-15.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-10-19.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-11-10.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-11-19.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-11-23.sql', '/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-12-12.sql', '/administrator/components/com_admin/views/sysinfo/tmpl/default_navigation.php', '/administrator/components/com_categories/config.xml', '/administrator/components/com_categories/helpers/categoriesadministrator.php', '/administrator/components/com_contact/elements/contact.php', '/administrator/components/com_contact/elements/index.html', '/administrator/components/com_content/elements/article.php', '/administrator/components/com_content/elements/author.php', '/administrator/components/com_content/elements/index.html', '/administrator/components/com_installer/models/fields/client.php', '/administrator/components/com_installer/models/fields/group.php', '/administrator/components/com_installer/models/fields/index.html', '/administrator/components/com_installer/models/fields/search.php', '/administrator/components/com_installer/models/forms/index.html', '/administrator/components/com_installer/models/forms/manage.xml', '/administrator/components/com_installer/views/install/tmpl/default_form.php', '/administrator/components/com_installer/views/manage/tmpl/default_filter.php', '/administrator/components/com_languages/views/installed/tmpl/default_ftp.php', '/administrator/components/com_languages/views/installed/tmpl/default_navigation.php', '/administrator/components/com_modules/models/fields/index.html', '/administrator/components/com_modules/models/fields/moduleorder.php', '/administrator/components/com_modules/models/fields/moduleposition.php', '/administrator/components/com_newsfeeds/elements/index.html', '/administrator/components/com_newsfeeds/elements/newsfeed.php', '/administrator/components/com_templates/views/prevuuw/index.html', '/administrator/components/com_templates/views/prevuuw/tmpl/default.php', '/administrator/components/com_templates/views/prevuuw/tmpl/index.html', '/administrator/components/com_templates/views/prevuuw/view.html.php', '/administrator/includes/menu.php', '/administrator/includes/router.php', '/administrator/manifests/packages/pkg_joomla.xml', '/administrator/modules/mod_submenu/helper.php', '/administrator/templates/hathor/css/ie6.css', '/administrator/templates/hathor/html/mod_submenu/index.html', '/administrator/templates/hathor/html/mod_submenu/default.php', '/components/com_media/controller.php', '/components/com_media/helpers/index.html', '/components/com_media/helpers/media.php', '/includes/menu.php', '/includes/pathway.php', '/includes/router.php', '/language/en-GB/en-GB.pkg_joomla.sys.ini', '/libraries/cms/controller/index.html', '/libraries/cms/controller/legacy.php', '/libraries/cms/model/index.html', '/libraries/cms/model/legacy.php', '/libraries/cms/schema/changeitemmysql.php', '/libraries/cms/schema/changeitemsqlazure.php', '/libraries/cms/schema/changeitemsqlsrv.php', '/libraries/cms/view/index.html', '/libraries/cms/view/legacy.php', '/libraries/joomla/application/application.php', '/libraries/joomla/application/categories.php', '/libraries/joomla/application/cli/daemon.php', '/libraries/joomla/application/cli/index.html', '/libraries/joomla/application/component/controller.php', '/libraries/joomla/application/component/controlleradmin.php', '/libraries/joomla/application/component/controllerform.php', '/libraries/joomla/application/component/helper.php', '/libraries/joomla/application/component/index.html', '/libraries/joomla/application/component/model.php', '/libraries/joomla/application/component/modeladmin.php', '/libraries/joomla/application/component/modelform.php', '/libraries/joomla/application/component/modelitem.php', '/libraries/joomla/application/component/modellist.php', '/libraries/joomla/application/component/view.php', '/libraries/joomla/application/helper.php', '/libraries/joomla/application/input.php', '/libraries/joomla/application/input/cli.php', '/libraries/joomla/application/input/cookie.php', '/libraries/joomla/application/input/files.php', '/libraries/joomla/application/input/index.html', '/libraries/joomla/application/menu.php', '/libraries/joomla/application/module/helper.php', '/libraries/joomla/application/module/index.html', '/libraries/joomla/application/pathway.php', '/libraries/joomla/application/web/webclient.php', '/libraries/joomla/base/node.php', '/libraries/joomla/base/object.php', '/libraries/joomla/base/observable.php', '/libraries/joomla/base/observer.php', '/libraries/joomla/base/tree.php', '/libraries/joomla/cache/storage/eaccelerator.php', '/libraries/joomla/cache/storage/helpers/helper.php', '/libraries/joomla/cache/storage/helpers/index.html', '/libraries/joomla/database/database/index.html', '/libraries/joomla/database/database/mysql.php', '/libraries/joomla/database/database/mysqlexporter.php', '/libraries/joomla/database/database/mysqli.php', '/libraries/joomla/database/database/mysqliexporter.php', '/libraries/joomla/database/database/mysqliimporter.php', '/libraries/joomla/database/database/mysqlimporter.php', '/libraries/joomla/database/database/mysqliquery.php', '/libraries/joomla/database/database/mysqlquery.php', '/libraries/joomla/database/database/sqlazure.php', '/libraries/joomla/database/database/sqlazurequery.php', '/libraries/joomla/database/database/sqlsrv.php', '/libraries/joomla/database/database/sqlsrvquery.php', '/libraries/joomla/database/exception.php', '/libraries/joomla/database/table.php', '/libraries/joomla/database/table/asset.php', '/libraries/joomla/database/table/category.php', '/libraries/joomla/database/table/content.php', '/libraries/joomla/database/table/extension.php', '/libraries/joomla/database/table/index.html', '/libraries/joomla/database/table/language.php', '/libraries/joomla/database/table/menu.php', '/libraries/joomla/database/table/menutype.php', '/libraries/joomla/database/table/module.php', '/libraries/joomla/database/table/session.php', '/libraries/joomla/database/table/update.php', '/libraries/joomla/database/table/user.php', '/libraries/joomla/database/table/usergroup.php', '/libraries/joomla/database/table/viewlevel.php', '/libraries/joomla/database/tablenested.php', '/libraries/joomla/environment/request.php', '/libraries/joomla/environment/uri.php', '/libraries/joomla/error/error.php', '/libraries/joomla/error/exception.php', '/libraries/joomla/error/index.html', '/libraries/joomla/error/log.php', '/libraries/joomla/error/profiler.php', '/libraries/joomla/filesystem/archive.php', '/libraries/joomla/filesystem/archive/bzip2.php', '/libraries/joomla/filesystem/archive/gzip.php', '/libraries/joomla/filesystem/archive/index.html', '/libraries/joomla/filesystem/archive/tar.php', '/libraries/joomla/filesystem/archive/zip.php', '/libraries/joomla/form/fields/category.php', '/libraries/joomla/form/fields/componentlayout.php', '/libraries/joomla/form/fields/contentlanguage.php', '/libraries/joomla/form/fields/editor.php', '/libraries/joomla/form/fields/editors.php', '/libraries/joomla/form/fields/media.php', '/libraries/joomla/form/fields/menuitem.php', '/libraries/joomla/form/fields/modulelayout.php', '/libraries/joomla/html/editor.php', '/libraries/joomla/html/html/access.php', '/libraries/joomla/html/html/batch.php', '/libraries/joomla/html/html/behavior.php', '/libraries/joomla/html/html/category.php', '/libraries/joomla/html/html/content.php', '/libraries/joomla/html/html/contentlanguage.php', '/libraries/joomla/html/html/date.php', '/libraries/joomla/html/html/email.php', '/libraries/joomla/html/html/form.php', '/libraries/joomla/html/html/grid.php', '/libraries/joomla/html/html/image.php', '/libraries/joomla/html/html/index.html', '/libraries/joomla/html/html/jgrid.php', '/libraries/joomla/html/html/list.php', '/libraries/joomla/html/html/menu.php', '/libraries/joomla/html/html/number.php', '/libraries/joomla/html/html/rules.php', '/libraries/joomla/html/html/select.php', '/libraries/joomla/html/html/sliders.php', '/libraries/joomla/html/html/string.php', '/libraries/joomla/html/html/tabs.php', '/libraries/joomla/html/html/tel.php', '/libraries/joomla/html/html/user.php', '/libraries/joomla/html/pagination.php', '/libraries/joomla/html/pane.php', '/libraries/joomla/html/parameter.php', '/libraries/joomla/html/parameter/element.php', '/libraries/joomla/html/parameter/element/calendar.php', '/libraries/joomla/html/parameter/element/category.php', '/libraries/joomla/html/parameter/element/componentlayouts.php', '/libraries/joomla/html/parameter/element/contentlanguages.php', '/libraries/joomla/html/parameter/element/editors.php', '/libraries/joomla/html/parameter/element/filelist.php', '/libraries/joomla/html/parameter/element/folderlist.php', '/libraries/joomla/html/parameter/element/helpsites.php', '/libraries/joomla/html/parameter/element/hidden.php', '/libraries/joomla/html/parameter/element/imagelist.php', '/libraries/joomla/html/parameter/element/index.html', '/libraries/joomla/html/parameter/element/languages.php', '/libraries/joomla/html/parameter/element/list.php', '/libraries/joomla/html/parameter/element/menu.php', '/libraries/joomla/html/parameter/element/menuitem.php', '/libraries/joomla/html/parameter/element/modulelayouts.php', '/libraries/joomla/html/parameter/element/password.php', '/libraries/joomla/html/parameter/element/radio.php', '/libraries/joomla/html/parameter/element/spacer.php', '/libraries/joomla/html/parameter/element/sql.php', '/libraries/joomla/html/parameter/element/templatestyle.php', '/libraries/joomla/html/parameter/element/text.php', '/libraries/joomla/html/parameter/element/textarea.php', '/libraries/joomla/html/parameter/element/timezones.php', '/libraries/joomla/html/parameter/element/usergroup.php', '/libraries/joomla/html/parameter/index.html', '/libraries/joomla/html/toolbar.php', '/libraries/joomla/html/toolbar/button.php', '/libraries/joomla/html/toolbar/button/confirm.php', '/libraries/joomla/html/toolbar/button/custom.php', '/libraries/joomla/html/toolbar/button/help.php', '/libraries/joomla/html/toolbar/button/index.html', '/libraries/joomla/html/toolbar/button/link.php', '/libraries/joomla/html/toolbar/button/popup.php', '/libraries/joomla/html/toolbar/button/separator.php', '/libraries/joomla/html/toolbar/button/standard.php', '/libraries/joomla/html/toolbar/index.html', '/libraries/joomla/image/filters/brightness.php', '/libraries/joomla/image/filters/contrast.php', '/libraries/joomla/image/filters/edgedetect.php', '/libraries/joomla/image/filters/emboss.php', '/libraries/joomla/image/filters/grayscale.php', '/libraries/joomla/image/filters/index.html', '/libraries/joomla/image/filters/negate.php', '/libraries/joomla/image/filters/sketchy.php', '/libraries/joomla/image/filters/smooth.php', '/libraries/joomla/language/help.php', '/libraries/joomla/language/latin_transliterate.php', '/libraries/joomla/log/logexception.php', '/libraries/joomla/log/loggers/database.php', '/libraries/joomla/log/loggers/echo.php', '/libraries/joomla/log/loggers/formattedtext.php', '/libraries/joomla/log/loggers/index.html', '/libraries/joomla/log/loggers/messagequeue.php', '/libraries/joomla/log/loggers/syslog.php', '/libraries/joomla/log/loggers/w3c.php', '/libraries/joomla/methods.php', '/libraries/joomla/session/storage/eaccelerator.php', '/libraries/joomla/string/stringnormalize.php', '/libraries/joomla/utilities/date.php', '/libraries/joomla/utilities/simplecrypt.php', '/libraries/joomla/utilities/simplexml.php', '/libraries/joomla/utilities/string.php', '/libraries/joomla/utilities/xmlelement.php', '/media/plg_quickicon_extensionupdate/extensionupdatecheck.js', '/media/plg_quickicon_joomlaupdate/jupdatecheck.js', // Joomla! 3.1 '/libraries/joomla/application/router.php', '/libraries/joomla/form/rules/boolean.php', '/libraries/joomla/form/rules/color.php', '/libraries/joomla/form/rules/email.php', '/libraries/joomla/form/rules/equals.php', '/libraries/joomla/form/rules/index.html', '/libraries/joomla/form/rules/options.php', '/libraries/joomla/form/rules/rules.php', '/libraries/joomla/form/rules/tel.php', '/libraries/joomla/form/rules/url.php', '/libraries/joomla/form/rules/username.php', '/libraries/joomla/html/access.php', '/libraries/joomla/html/behavior.php', '/libraries/joomla/html/content.php', '/libraries/joomla/html/date.php', '/libraries/joomla/html/email.php', '/libraries/joomla/html/form.php', '/libraries/joomla/html/grid.php', '/libraries/joomla/html/html.php', '/libraries/joomla/html/index.html', '/libraries/joomla/html/jgrid.php', '/libraries/joomla/html/list.php', '/libraries/joomla/html/number.php', '/libraries/joomla/html/rules.php', '/libraries/joomla/html/select.php', '/libraries/joomla/html/sliders.php', '/libraries/joomla/html/string.php', '/libraries/joomla/html/tabs.php', '/libraries/joomla/html/tel.php', '/libraries/joomla/html/user.php', '/libraries/joomla/html/language/index.html', '/libraries/joomla/html/language/en-GB/en-GB.jhtmldate.ini', '/libraries/joomla/html/language/en-GB/index.html', '/libraries/joomla/installer/adapters/component.php', '/libraries/joomla/installer/adapters/file.php', '/libraries/joomla/installer/adapters/index.html', '/libraries/joomla/installer/adapters/language.php', '/libraries/joomla/installer/adapters/library.php', '/libraries/joomla/installer/adapters/module.php', '/libraries/joomla/installer/adapters/package.php', '/libraries/joomla/installer/adapters/plugin.php', '/libraries/joomla/installer/adapters/template.php', '/libraries/joomla/installer/extension.php', '/libraries/joomla/installer/helper.php', '/libraries/joomla/installer/index.html', '/libraries/joomla/installer/librarymanifest.php', '/libraries/joomla/installer/packagemanifest.php', '/libraries/joomla/pagination/index.html', '/libraries/joomla/pagination/object.php', '/libraries/joomla/pagination/pagination.php', '/libraries/legacy/html/contentlanguage.php', '/libraries/legacy/html/index.html', '/libraries/legacy/html/menu.php', '/libraries/legacy/menu/index.html', '/libraries/legacy/menu/menu.php', '/libraries/legacy/pathway/index.html', '/libraries/legacy/pathway/pathway.php', '/media/system/css/mooRainbow.css', '/media/system/js/mooRainbow-uncompressed.js', '/media/system/js/mooRainbow.js', '/media/system/js/swf-uncompressed.js', '/media/system/js/swf.js', '/media/system/js/uploader-uncompressed.js', '/media/system/js/uploader.js', '/media/system/swf/index.html', '/media/system/swf/uploader.swf', // Joomla! 3.2 '/administrator/components/com_contact/models/fields/modal/contacts.php', '/administrator/components/com_newsfeeds/models/fields/modal/newsfeeds.php', '/libraries/idna_convert/example.php', '/media/editors/tinymce/jscripts/tiny_mce/index.html', '/media/editors/tinymce/jscripts/tiny_mce/license.txt', '/media/editors/tinymce/jscripts/tiny_mce/tiny_mce.js', '/media/editors/tinymce/jscripts/tiny_mce/tiny_mce_popup.js', '/media/editors/tinymce/jscripts/tiny_mce/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/langs/en.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/rule.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/css/advhr.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/js/rule.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/css/advimage.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/img/sample.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/js/image.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/css/advlink.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/js/advlink.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/langs/en.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/editable_selects.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/form_utils.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/mctabs.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/tiny_mce_popup.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/validate.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/emotions.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-cool.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-cry.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-embarassed.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-foot-in-mouth.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-frown.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-innocent.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-kiss.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-laughing.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-money-mouth.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-sealed.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-smile.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-surprised.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-tongue-out.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-undecided.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-wink.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-yell.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/js/emotions.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/fullpage.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/css/fullpage.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/js/fullpage.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/fullscreen.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/template.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/window.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/alert.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/button.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/confirm.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/corners.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/horizontal.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/vertical.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/media.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/moxieplayer.swf', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/css/media.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/embed.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/media.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/media/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/pastetext.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/pastetext.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/pastetext.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/pasteword.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/example.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/preview.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/jscripts/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/jscripts/embed.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/print/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/print/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/save/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/save/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/searchreplace.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/css/searchreplace.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/js/searchreplace.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/css/content.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/img/wline.gif', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/props.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/readme.txt', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/css/props.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/js/props.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/style/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/cell.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/merge_cells.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/row.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/table.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/cell.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/row.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/table.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/cell.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/merge_cells.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/row.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/table.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/table/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/blank.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/template.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/css/template.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/js/template.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/template/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/css/visualblocks.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/abbr.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/acronym.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/attributes.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/cite.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/del.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/editor_plugin.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/ins.htm', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/attributes.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/popup.css', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/abbr.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/acronym.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/attributes.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/cite.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/del.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/element_common.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/ins.js', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/about.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/anchor.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/charmap.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/color_picker.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/editor_template.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/image.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/link.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/shortcuts.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/source_editor.htm', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/colorpicker.jpg', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/flash.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/icons.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/iframe.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/pagebreak.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/quicktime.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/realmedia.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/shockwave.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/trans.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/video.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/windowsmedia.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/about.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/anchor.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/charmap.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/color_picker.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/image.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/link.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/source_editor.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/en.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/en_dlg.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/content.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialog.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/ui.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/buttons.png', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/items.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/menu_arrow.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/menu_check.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/progress.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/tabs.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/content.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/dialog.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/ui.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/content.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/dialog.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui_black.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui_silver.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg.png', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg_black.png', '/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg_silver.png', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/editor_template.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/img/icons.gif', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/langs/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/langs/en.js', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/content.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/ui.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/content.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/ui.css', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/img/index.html', '/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/img/button_bg.png', '/media/editors/tinymce/jscripts/tiny_mce/utils/index.html', '/media/editors/tinymce/jscripts/tiny_mce/utils/editable_selects.js', '/media/editors/tinymce/jscripts/tiny_mce/utils/form_utils.js', '/media/editors/tinymce/jscripts/tiny_mce/utils/mctabs.js', '/media/editors/tinymce/jscripts/tiny_mce/utils/validate.js', '/administrator/components/com_banners/models/fields/ordering.php', '/administrator/components/com_contact/models/fields/ordering.php', '/administrator/components/com_newsfeeds/models/fields/ordering.php', '/administrator/components/com_plugins/models/fields/ordering.php', '/administrator/components/com_weblinks/models/fields/ordering.php', '/administrator/includes/application.php', '/includes/application.php', '/libraries/legacy/application/helper.php', '/libraries/joomla/plugin/helper.php', '/libraries/joomla/plugin/index.html', '/libraries/joomla/plugin/plugin.php', '/libraries/legacy/component/helper.php', '/libraries/legacy/component/index.html', '/libraries/legacy/module/helper.php', '/libraries/legacy/module/index.html', '/administrator/components/com_templates/controllers/source.php', '/administrator/components/com_templates/models/source.php', '/administrator/components/com_templates/views/source/index.html', '/administrator/components/com_templates/views/source/tmpl/edit.php', '/administrator/components/com_templates/views/source/tmpl/edit_ftp.php', '/administrator/components/com_templates/views/source/tmpl/index.html', '/administrator/components/com_templates/views/source/view.html.php', '/media/editors/codemirror/css/csscolors.css', '/media/editors/codemirror/css/jscolors.css', '/media/editors/codemirror/css/phpcolors.css', '/media/editors/codemirror/css/sparqlcolors.css', '/media/editors/codemirror/css/xmlcolors.css', '/media/editors/codemirror/js/basefiles-uncompressed.js', '/media/editors/codemirror/js/basefiles.js', '/media/editors/codemirror/js/codemirror-uncompressed.js', '/media/editors/codemirror/js/editor.js', '/media/editors/codemirror/js/highlight.js', '/media/editors/codemirror/js/mirrorframe.js', '/media/editors/codemirror/js/parsecss.js', '/media/editors/codemirror/js/parsedummy.js', '/media/editors/codemirror/js/parsehtmlmixed.js', '/media/editors/codemirror/js/parsejavascript.js', '/media/editors/codemirror/js/parsephp.js', '/media/editors/codemirror/js/parsephphtmlmixed.js', '/media/editors/codemirror/js/parsesparql.js', '/media/editors/codemirror/js/parsexml.js', '/media/editors/codemirror/js/select.js', '/media/editors/codemirror/js/stringstream.js', '/media/editors/codemirror/js/tokenize.js', '/media/editors/codemirror/js/tokenizejavascript.js', '/media/editors/codemirror/js/tokenizephp.js', '/media/editors/codemirror/js/undo.js', '/media/editors/codemirror/js/util.js', '/administrator/components/com_weblinks/models/fields/index.html', '/plugins/user/joomla/postinstall/actions.php', '/plugins/user/joomla/postinstall/index.html', '/media/com_finder/js/finder.js', '/media/com_finder/js/highlighter.js', '/libraries/joomla/registry/format.php', '/libraries/joomla/registry/index.html', '/libraries/joomla/registry/registry.php', '/libraries/joomla/registry/format/index.html', '/libraries/joomla/registry/format/ini.php', '/libraries/joomla/registry/format/json.php', '/libraries/joomla/registry/format/php.php', '/libraries/joomla/registry/format/xml.php', // Joomla 3.3.1 '/administrator/templates/isis/html/message.php', // Joomla 3.3.6 '/media/editors/tinymce/plugins/compat3x/editable_selects.js', '/media/editors/tinymce/plugins/compat3x/form_utils.js', '/media/editors/tinymce/plugins/compat3x/mctabs.js', '/media/editors/tinymce/plugins/compat3x/tiny_mce_popup.js', '/media/editors/tinymce/plugins/compat3x/validate.js', // Joomla! 3.4 '/administrator/components/com_tags/helpers/html/index.html', '/administrator/components/com_tags/models/fields/index.html', '/administrator/manifests/libraries/phpmailer.xml', '/administrator/templates/hathor/html/com_finder/filter/index.html', '/administrator/templates/hathor/html/com_finder/statistics/index.html', '/components/com_contact/helpers/icon.php', '/language/en-GB/en-GB.lib_phpmailer.sys.ini', '/libraries/compat/jsonserializable.php', '/libraries/compat/password/lib/index.html', '/libraries/compat/password/lib/password.php', '/libraries/compat/password/lib/version_test.php', '/libraries/compat/password/index.html', '/libraries/compat/password/LICENSE.md', '/libraries/compat/index.html', '/libraries/fof/controller.php', '/libraries/fof/dispatcher.php', '/libraries/fof/inflector.php', '/libraries/fof/input.php', '/libraries/fof/model.php', '/libraries/fof/query.abstract.php', '/libraries/fof/query.element.php', '/libraries/fof/query.mysql.php', '/libraries/fof/query.mysqli.php', '/libraries/fof/query.sqlazure.php', '/libraries/fof/query.sqlsrv.php', '/libraries/fof/render.abstract.php', '/libraries/fof/render.joomla.php', '/libraries/fof/render.joomla3.php', '/libraries/fof/render.strapper.php', '/libraries/fof/string.utils.php', '/libraries/fof/table.php', '/libraries/fof/template.utils.php', '/libraries/fof/toolbar.php', '/libraries/fof/view.csv.php', '/libraries/fof/view.html.php', '/libraries/fof/view.json.php', '/libraries/fof/view.php', '/libraries/framework/Joomla/Application/Cli/Output/Processor/ColorProcessor.php', '/libraries/framework/Joomla/Application/Cli/Output/Processor/ProcessorInterface.php', '/libraries/framework/Joomla/Application/Cli/Output/Stdout.php', '/libraries/framework/Joomla/Application/Cli/Output/Xml.php', '/libraries/framework/Joomla/Application/Cli/CliOutput.php', '/libraries/framework/Joomla/Application/Cli/ColorProcessor.php', '/libraries/framework/Joomla/Application/Cli/ColorStyle.php', '/libraries/framework/index.html', '/libraries/framework/Joomla/DI/Exception/DependencyResolutionException.php', '/libraries/framework/Joomla/DI/Exception/index.html', '/libraries/framework/Joomla/DI/Container.php', '/libraries/framework/Joomla/DI/ContainerAwareInterface.php', '/libraries/framework/Joomla/DI/index.html', '/libraries/framework/Joomla/DI/ServiceProviderInterface.php', '/libraries/framework/Joomla/Registry/Format/index.html', '/libraries/framework/Joomla/Registry/Format/Ini.php', '/libraries/framework/Joomla/Registry/Format/Json.php', '/libraries/framework/Joomla/Registry/Format/Php.php', '/libraries/framework/Joomla/Registry/Format/Xml.php', '/libraries/framework/Joomla/Registry/Format/Yaml.php', '/libraries/framework/Joomla/Registry/AbstractRegistryFormat.php', '/libraries/framework/Joomla/Registry/index.html', '/libraries/framework/Joomla/Registry/Registry.php', '/libraries/framework/Symfony/Component/Yaml/Exception/DumpException.php', '/libraries/framework/Symfony/Component/Yaml/Exception/ExceptionInterface.php', '/libraries/framework/Symfony/Component/Yaml/Exception/index.html', '/libraries/framework/Symfony/Component/Yaml/Exception/ParseException.php', '/libraries/framework/Symfony/Component/Yaml/Exception/RuntimeException.php', '/libraries/framework/Symfony/Component/Yaml/Dumper.php', '/libraries/framework/Symfony/Component/Yaml/Escaper.php', '/libraries/framework/Symfony/Component/Yaml/index.html', '/libraries/framework/Symfony/Component/Yaml/Inline.php', '/libraries/framework/Symfony/Component/Yaml/LICENSE', '/libraries/framework/Symfony/Component/Yaml/Parser.php', '/libraries/framework/Symfony/Component/Yaml/Unescaper.php', '/libraries/framework/Symfony/Component/Yaml/Yaml.php', '/libraries/joomla/string/inflector.php', '/libraries/joomla/string/normalise.php', '/libraries/phpmailer/language/index.html', '/libraries/phpmailer/language/phpmailer.lang-joomla.php', '/libraries/phpmailer/index.html', '/libraries/phpmailer/LICENSE', '/libraries/phpmailer/phpmailer.php', '/libraries/phpmailer/pop.php', '/libraries/phpmailer/smtp.php', '/media/editors/codemirror/css/ambiance.css', '/media/editors/codemirror/css/codemirror.css', '/media/editors/codemirror/css/configuration.css', '/media/editors/codemirror/css/index.html', '/media/editors/codemirror/js/brace-fold.js', '/media/editors/codemirror/js/clike.js', '/media/editors/codemirror/js/closebrackets.js', '/media/editors/codemirror/js/closetag.js', '/media/editors/codemirror/js/codemirror.js', '/media/editors/codemirror/js/css.js', '/media/editors/codemirror/js/foldcode.js', '/media/editors/codemirror/js/foldgutter.js', '/media/editors/codemirror/js/fullscreen.js', '/media/editors/codemirror/js/htmlmixed.js', '/media/editors/codemirror/js/indent-fold.js', '/media/editors/codemirror/js/index.html', '/media/editors/codemirror/js/javascript.js', '/media/editors/codemirror/js/less.js', '/media/editors/codemirror/js/matchbrackets.js', '/media/editors/codemirror/js/matchtags.js', '/media/editors/codemirror/js/php.js', '/media/editors/codemirror/js/xml-fold.js', '/media/editors/codemirror/js/xml.js', '/media/editors/tinymce/skins/lightgray/fonts/icomoon.svg', '/media/editors/tinymce/skins/lightgray/fonts/icomoon.ttf', '/media/editors/tinymce/skins/lightgray/fonts/icomoon.woff', '/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.eot', '/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.svg', '/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.ttf', '/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.woff', '/media/editors/tinymce/skins/lightgray/fonts/readme.md', '/media/editors/tinymce/skins/lightgray/fonts/tinymce.dev.svg', '/media/editors/tinymce/skins/lightgray/fonts/tinymce-small.dev.svg', '/media/editors/tinymce/skins/lightgray/img/wline.gif', '/plugins/editors/codemirror/styles.css', '/plugins/editors/codemirror/styles.min.css', // Joomla! 3.4.1 '/libraries/joomla/environment/request.php', '/media/editors/tinymce/templates/template_list.js', '/media/editors/codemirror/lib/addons-uncompressed.js', '/media/editors/codemirror/lib/codemirror-uncompressed.css', '/media/editors/codemirror/lib/codemirror-uncompressed.js', '/administrator/help/en-GB/Components_Banners_Banners.html', '/administrator/help/en-GB/Components_Banners_Banners_Edit.html', '/administrator/help/en-GB/Components_Banners_Categories.html', '/administrator/help/en-GB/Components_Banners_Category_Edit.html', '/administrator/help/en-GB/Components_Banners_Clients.html', '/administrator/help/en-GB/Components_Banners_Clients_Edit.html', '/administrator/help/en-GB/Components_Banners_Tracks.html', '/administrator/help/en-GB/Components_Contact_Categories.html', '/administrator/help/en-GB/Components_Contact_Category_Edit.html', '/administrator/help/en-GB/Components_Contacts_Contacts.html', '/administrator/help/en-GB/Components_Contacts_Contacts_Edit.html', '/administrator/help/en-GB/Components_Content_Categories.html', '/administrator/help/en-GB/Components_Content_Category_Edit.html', '/administrator/help/en-GB/Components_Messaging_Inbox.html', '/administrator/help/en-GB/Components_Messaging_Read.html', '/administrator/help/en-GB/Components_Messaging_Write.html', '/administrator/help/en-GB/Components_Newsfeeds_Categories.html', '/administrator/help/en-GB/Components_Newsfeeds_Category_Edit.html', '/administrator/help/en-GB/Components_Newsfeeds_Feeds.html', '/administrator/help/en-GB/Components_Newsfeeds_Feeds_Edit.html', '/administrator/help/en-GB/Components_Redirect_Manager.html', '/administrator/help/en-GB/Components_Redirect_Manager_Edit.html', '/administrator/help/en-GB/Components_Search.html', '/administrator/help/en-GB/Components_Weblinks_Categories.html', '/administrator/help/en-GB/Components_Weblinks_Category_Edit.html', '/administrator/help/en-GB/Components_Weblinks_Links.html', '/administrator/help/en-GB/Components_Weblinks_Links_Edit.html', '/administrator/help/en-GB/Content_Article_Manager.html', '/administrator/help/en-GB/Content_Article_Manager_Edit.html', '/administrator/help/en-GB/Content_Featured_Articles.html', '/administrator/help/en-GB/Content_Media_Manager.html', '/administrator/help/en-GB/Extensions_Extension_Manager_Discover.html', '/administrator/help/en-GB/Extensions_Extension_Manager_Install.html', '/administrator/help/en-GB/Extensions_Extension_Manager_Manage.html', '/administrator/help/en-GB/Extensions_Extension_Manager_Update.html', '/administrator/help/en-GB/Extensions_Extension_Manager_Warnings.html', '/administrator/help/en-GB/Extensions_Language_Manager_Content.html', '/administrator/help/en-GB/Extensions_Language_Manager_Edit.html', '/administrator/help/en-GB/Extensions_Language_Manager_Installed.html', '/administrator/help/en-GB/Extensions_Module_Manager.html', '/administrator/help/en-GB/Extensions_Module_Manager_Edit.html', '/administrator/help/en-GB/Extensions_Plugin_Manager.html', '/administrator/help/en-GB/Extensions_Plugin_Manager_Edit.html', '/administrator/help/en-GB/Extensions_Template_Manager_Styles.html', '/administrator/help/en-GB/Extensions_Template_Manager_Styles_Edit.html', '/administrator/help/en-GB/Extensions_Template_Manager_Templates.html', '/administrator/help/en-GB/Extensions_Template_Manager_Templates_Edit.html', '/administrator/help/en-GB/Extensions_Template_Manager_Templates_Edit_Source.html', '/administrator/help/en-GB/Glossary.html', '/administrator/help/en-GB/Menus_Menu_Item_Manager.html', '/administrator/help/en-GB/Menus_Menu_Item_Manager_Edit.html', '/administrator/help/en-GB/Menus_Menu_Manager.html', '/administrator/help/en-GB/Menus_Menu_Manager_Edit.html', '/administrator/help/en-GB/Site_Global_Configuration.html', '/administrator/help/en-GB/Site_Maintenance_Clear_Cache.html', '/administrator/help/en-GB/Site_Maintenance_Global_Check-in.html', '/administrator/help/en-GB/Site_Maintenance_Purge_Expired_Cache.html', '/administrator/help/en-GB/Site_System_Information.html', '/administrator/help/en-GB/Start_Here.html', '/administrator/help/en-GB/Users_Access_Levels.html', '/administrator/help/en-GB/Users_Access_Levels_Edit.html', '/administrator/help/en-GB/Users_Debug_Users.html', '/administrator/help/en-GB/Users_Groups.html', '/administrator/help/en-GB/Users_Groups_Edit.html', '/administrator/help/en-GB/Users_Mass_Mail_Users.html', '/administrator/help/en-GB/Users_User_Manager.html', '/administrator/help/en-GB/Users_User_Manager_Edit.html', '/administrator/components/com_config/views/index.html', '/administrator/components/com_config/views/application/index.html', '/administrator/components/com_config/views/application/view.html.php', '/administrator/components/com_config/views/application/tmpl/default.php', '/administrator/components/com_config/views/application/tmpl/default_cache.php', '/administrator/components/com_config/views/application/tmpl/default_cookie.php', '/administrator/components/com_config/views/application/tmpl/default_database.php', '/administrator/components/com_config/views/application/tmpl/default_debug.php', '/administrator/components/com_config/views/application/tmpl/default_filters.php', '/administrator/components/com_config/views/application/tmpl/default_ftp.php', '/administrator/components/com_config/views/application/tmpl/default_ftplogin.php', '/administrator/components/com_config/views/application/tmpl/default_locale.php', '/administrator/components/com_config/views/application/tmpl/default_mail.php', '/administrator/components/com_config/views/application/tmpl/default_metadata.php', '/administrator/components/com_config/views/application/tmpl/default_navigation.php', '/administrator/components/com_config/views/application/tmpl/default_permissions.php', '/administrator/components/com_config/views/application/tmpl/default_seo.php', '/administrator/components/com_config/views/application/tmpl/default_server.php', '/administrator/components/com_config/views/application/tmpl/default_session.php', '/administrator/components/com_config/views/application/tmpl/default_site.php', '/administrator/components/com_config/views/application/tmpl/default_system.php', '/administrator/components/com_config/views/application/tmpl/index.html', '/administrator/components/com_config/views/close/index.html', '/administrator/components/com_config/views/close/view.html.php', '/administrator/components/com_config/views/component/index.html', '/administrator/components/com_config/views/component/view.html.php', '/administrator/components/com_config/views/component/tmpl/default.php', '/administrator/components/com_config/views/component/tmpl/index.html', '/administrator/components/com_config/models/fields/filters.php', '/administrator/components/com_config/models/fields/index.html', '/administrator/components/com_config/models/forms/application.xml', '/administrator/components/com_config/models/forms/index.html', // Joomla 3.4.2 '/libraries/composer_autoload.php', '/administrator/templates/hathor/html/com_categories/categories/default_batch.php', '/administrator/templates/hathor/html/com_tags/tags/default_batch.php', '/media/editors/codemirror/mode/clike/scala.html', '/media/editors/codemirror/mode/css/less.html', '/media/editors/codemirror/mode/css/less_test.js', '/media/editors/codemirror/mode/css/scss.html', '/media/editors/codemirror/mode/css/scss_test.js', '/media/editors/codemirror/mode/css/test.js', '/media/editors/codemirror/mode/gfm/test.js', '/media/editors/codemirror/mode/haml/test.js', '/media/editors/codemirror/mode/javascript/json-ld.html', '/media/editors/codemirror/mode/javascript/test.js', '/media/editors/codemirror/mode/javascript/typescript.html', '/media/editors/codemirror/mode/markdown/test.js', '/media/editors/codemirror/mode/php/test.js', '/media/editors/codemirror/mode/ruby/test.js', '/media/editors/codemirror/mode/shell/test.js', '/media/editors/codemirror/mode/slim/test.js', '/media/editors/codemirror/mode/stex/test.js', '/media/editors/codemirror/mode/textile/test.js', '/media/editors/codemirror/mode/verilog/test.js', '/media/editors/codemirror/mode/xml/test.js', '/media/editors/codemirror/mode/xquery/test.js', // Joomla 3.4.3 '/libraries/classloader.php', '/libraries/ClassLoader.php', // Joomla 3.4.6 '/components/com_wrapper/views/wrapper/metadata.xml', // Joomla 3.5.0 '/media/com_joomlaupdate/default.js', '/media/com_joomlaupdate/encryption.js', '/media/com_joomlaupdate/json2.js', '/media/com_joomlaupdate/update.js', '/media/com_finder/css/finder-rtl.css', '/media/com_finder/css/selectfilter.css', '/media/com_finder/css/sliderfilter.css', '/media/com_finder/js/sliderfilter.js', '/media/editors/codemirror/mode/kotlin/kotlin.js', '/media/editors/codemirror/mode/kotlin/kotlin.min.js', '/media/editors/tinymce/plugins/compat3x/editable_selects.js', '/media/editors/tinymce/plugins/compat3x/form_utils.js', '/media/editors/tinymce/plugins/compat3x/mctabs.js', '/media/editors/tinymce/plugins/compat3x/tiny_mce_popup.js', '/media/editors/tinymce/plugins/compat3x/validate.js', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Dumper.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Escaper.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Inline.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/LICENSE', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Parser.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Unescaper.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Yaml.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.php', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php', '/libraries/vendor/phpmailer/phpmailer/extras/class.html2text.php', '/libraries/joomla/document/error/error.php', '/libraries/joomla/document/feed/feed.php', '/libraries/joomla/document/html/html.php', '/libraries/joomla/document/image/image.php', '/libraries/joomla/document/json/json.php', '/libraries/joomla/document/opensearch/opensearch.php', '/libraries/joomla/document/raw/raw.php', '/libraries/joomla/document/xml/xml.php', '/plugins/editors/tinymce/fields/skins.php', '/plugins/user/profile/fields/dob.php', '/plugins/user/profile/fields/tos.php', '/administrator/components/com_installer/views/languages/tmpl/default_filter.php', '/administrator/components/com_joomlaupdate/helpers/download.php', '/administrator/components/com_config/controller/application/refreshhelp.php', '/administrator/components/com_media/models/forms/index.html', // Joomla 3.6.0 '/libraries/simplepie/README.txt', '/libraries/simplepie/simplepie.php', '/libraries/simplepie/LICENSE.txt', '/libraries/simplepie/idn/LICENCE', '/libraries/simplepie/idn/ReadMe.txt', '/libraries/simplepie/idn/idna_convert.class.php', '/libraries/simplepie/idn/npdata.ser', '/administrator/manifests/libraries/simplepie.xml', '/administrator/templates/isis/js/jquery.js', '/administrator/templates/isis/js/bootstrap.min.js', '/media/system/js/permissions.min.js', '/libraries/platform.php', '/plugins/user/profile/fields/tos.php', '/libraries/joomla/application/web/client.php', // Joomla! 3.6.1 '/libraries/joomla/database/iterator/azure.php', '/media/editors/tinymce/skins/lightgray/fonts/icomoon.eot', // Joomla! 3.6.3 '/media/editors/codemirror/mode/jade/jade.js', '/media/editors/codemirror/mode/jade/jade.min.js', // Joomla __DEPLOY_VERSION__ '/libraries/joomla/user/authentication.php', '/libraries/platform.php', '/libraries/joomla/data/data.php', '/libraries/joomla/data/dumpable.php', '/libraries/joomla/data/set.php', '/administrator/components/com_banners/views/banners/tmpl/default_batch.php', '/administrator/components/com_categories/views/category/tmpl/edit_extrafields.php', '/administrator/components/com_categories/views/category/tmpl/edit_options.php', '/administrator/components/com_categories/views/categories/tmpl/default_batch.php', '/administrator/components/com_content/views/articles/tmpl/default_batch.php', '/administrator/components/com_menus/views/items/tmpl/default_batch.php', '/administrator/components/com_modules/views/modules/tmpl/default_batch.php', '/administrator/components/com_newsfeeds/views/newsfeeds/tmpl/default_batch.php', '/administrator/components/com_redirect/views/links/tmpl/default_batch.php', '/administrator/components/com_tags/views/tags/tmpl/default_batch.php', '/administrator/components/com_users/views/users/tmpl/default_batch.php', ); // TODO There is an issue while deleting folders using the ftp mode $folders = array( '/administrator/components/com_admin/sql/updates/sqlsrv', '/media/com_finder/images/mime', '/media/com_finder/images', '/components/com_media/helpers', // Joomla 3.0 '/administrator/components/com_contact/elements', '/administrator/components/com_content/elements', '/administrator/components/com_newsfeeds/elements', '/administrator/components/com_templates/views/prevuuw/tmpl', '/administrator/components/com_templates/views/prevuuw', '/libraries/cms/controller', '/libraries/cms/model', '/libraries/cms/view', '/libraries/joomla/application/cli', '/libraries/joomla/application/component', '/libraries/joomla/application/input', '/libraries/joomla/application/module', '/libraries/joomla/cache/storage/helpers', '/libraries/joomla/database/table', '/libraries/joomla/database/database', '/libraries/joomla/error', '/libraries/joomla/filesystem/archive', '/libraries/joomla/html/html', '/libraries/joomla/html/toolbar', '/libraries/joomla/html/toolbar/button', '/libraries/joomla/html/parameter', '/libraries/joomla/html/parameter/element', '/libraries/joomla/image/filters', '/libraries/joomla/log/loggers', // Joomla! 3.1 '/libraries/joomla/form/rules', '/libraries/joomla/html/language/en-GB', '/libraries/joomla/html/language', '/libraries/joomla/html', '/libraries/joomla/installer/adapters', '/libraries/joomla/installer', '/libraries/joomla/pagination', '/libraries/legacy/html', '/libraries/legacy/menu', '/libraries/legacy/pathway', '/media/system/swf/', '/media/editors/tinymce/jscripts', // Joomla! 3.2 '/libraries/joomla/plugin', '/libraries/legacy/component', '/libraries/legacy/module', '/administrator/components/com_weblinks/models/fields', '/plugins/user/joomla/postinstall', '/libraries/joomla/registry/format', '/libraries/joomla/registry', // Joomla! 3.3 '/plugins/user/profile/fields', '/media/editors/tinymce/plugins/compat3x', // Joomla! 3.4 '/administrator/components/com_tags/helpers/html', '/administrator/components/com_tags/models/fields', '/administrator/templates/hathor/html/com_finder/filter', '/administrator/templates/hathor/html/com_finder/statistics', '/libraries/compat/password/lib', '/libraries/compat/password', '/libraries/compat', '/libraries/framework/Joomla/Application/Cli/Output/Processor', '/libraries/framework/Joomla/Application/Cli/Output', '/libraries/framework/Joomla/Application/Cli', '/libraries/framework/Joomla/Application', '/libraries/framework/Joomla/DI/Exception', '/libraries/framework/Joomla/DI', '/libraries/framework/Joomla/Registry/Format', '/libraries/framework/Joomla/Registry', '/libraries/framework/Joomla', '/libraries/framework/Symfony/Component/Yaml/Exception', '/libraries/framework/Symfony/Component/Yaml', '/libraries/framework', '/libraries/phpmailer/language', '/libraries/phpmailer', '/media/editors/codemirror/css', '/media/editors/codemirror/js', '/media/com_banners', // Joomla! 3.4.1 '/administrator/components/com_config/views', '/administrator/components/com_config/models/fields', '/administrator/components/com_config/models/forms', // Joomla! 3.4.2 '/media/editors/codemirror/mode/smartymixed', // Joomla! 3.5 '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception', '/libraries/vendor/symfony/yaml/Symfony/Component/Yaml', '/libraries/vendor/symfony/yaml/Symfony/Component', '/libraries/vendor/symfony/yaml/Symfony', '/libraries/joomla/document/error', '/libraries/joomla/document/image', '/libraries/joomla/document/json', '/libraries/joomla/document/opensearch', '/libraries/joomla/document/raw', '/libraries/joomla/document/xml', '/administrator/components/com_media/models/forms', '/media/editors/codemirror/mode/kotlin', '/media/editors/tinymce/plugins/compat3x', '/plugins/editors/tinymce/fields', '/plugins/user/profile/fields', // Joomla 3.6 '/libraries/simplepie/idn', '/libraries/simplepie', // Joomla! 3.6.3 '/media/editors/codemirror/mode/jade', // Joomla __DEPLOY_VERSION__ '/libraries/joomla/data', ); jimport('joomla.filesystem.file'); foreach ($files as $file) { if (JFile::exists(JPATH_ROOT . $file) && !JFile::delete(JPATH_ROOT . $file)) { echo JText::sprintf('FILES_JOOMLA_ERROR_FILE_FOLDER', $file) . '<br />'; } } jimport('joomla.filesystem.folder'); foreach ($folders as $folder) { if (JFolder::exists(JPATH_ROOT . $folder) && !JFolder::delete(JPATH_ROOT . $folder)) { echo JText::sprintf('FILES_JOOMLA_ERROR_FILE_FOLDER', $folder) . '<br />'; } } /* * Needed for updates post-3.4 * If com_weblinks doesn't exist then assume we can delete the weblinks package manifest (included in the update packages) */ if (!JFile::exists(JPATH_ROOT . '/administrator/components/com_weblinks/weblinks.php') && JFile::exists(JPATH_ROOT . '/administrator/manifests/packages/pkg_weblinks.xml')) { JFile::delete(JPATH_ROOT . '/administrator/manifests/packages/pkg_weblinks.xml'); } } /** * Clears the RAD layer's table cache. * * The cache vastly improves performance but needs to be cleared every time you update the database schema. * * @return void * * @since 3.2 */ protected function clearRadCache() { jimport('joomla.filesystem.file'); if (JFile::exists(JPATH_ROOT . '/cache/fof/cache.php')) { JFile::delete(JPATH_ROOT . '/cache/fof/cache.php'); } } /** * Method to create assets for newly installed components * * @return boolean * * @since 3.2 */ public function updateAssets() { // List all components added since 1.6 $newComponents = array( 'com_finder', 'com_joomlaupdate', 'com_tags', 'com_contenthistory', 'com_ajax', 'com_postinstall' ); foreach ($newComponents as $component) { /** @var JTableAsset $asset */ $asset = JTable::getInstance('Asset'); if ($asset->loadByName($component)) { continue; } $asset->name = $component; $asset->parent_id = 1; $asset->rules = '{}'; $asset->title = $component; $asset->setLocation(1, 'last-child'); if (!$asset->store()) { // Install failed, roll back changes $this->parent->abort(JText::sprintf('JLIB_INSTALLER_ABORT_COMP_INSTALL_ROLLBACK', $asset->stderr(true))); return false; } } return true; } /** * If we migrated the session from the previous system, flush all the active sessions. * Otherwise users will be logged in, but not able to do anything since they don't have * a valid session * * @return boolean */ public function flushSessions() { /** * The session may have not been started yet (e.g. CLI-based Joomla! update scripts). Let's make sure we do * have a valid session. */ $session = JFactory::getSession(); /** * Restarting the Session require a new login for the current user so lets check if we have an active session * and only restart it if not. * For B/C reasons we need to use getState as isActive is not available in 2.5 */ if ($session->getState() !== 'active') { $session->restart(); } // If $_SESSION['__default'] is no longer set we do not have a migrated session, therefore we can quit. if (!isset($_SESSION['__default'])) { return true; } $db = JFactory::getDbo(); try { switch ($db->name) { // MySQL database, use TRUNCATE (faster, more resilient) case 'pdomysql': case 'mysql': case 'mysqli': $db->truncateTable('#__session'); break; // Non-MySQL databases, use a simple DELETE FROM query default: $query = $db->getQuery(true) ->delete($db->qn('#__session')); $db->setQuery($query)->execute(); break; } } catch (Exception $e) { echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />'; return false; } return true; } /** * Converts the site's database tables to support UTF-8 Multibyte. * * @param boolean $doDbFixMsg Flag if message to be shown to check db fix * * @return void * * @since 3.5 */ public function convertTablesToUtf8mb4($doDbFixMsg = false) { $db = JFactory::getDbo(); // This is only required for MySQL databases $serverType = $db->getServerType(); if ($serverType != 'mysql') { return; } // Set required conversion status if ($db->hasUTF8mb4Support()) { $converted = 2; } else { $converted = 1; } // Check conversion status in database $db->setQuery('SELECT ' . $db->quoteName('converted') . ' FROM ' . $db->quoteName('#__utf8_conversion') ); try { $convertedDB = $db->loadResult(); } catch (Exception $e) { // Render the error message from the Exception object JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error'); if ($doDbFixMsg) { // Show an error message telling to check database problems JFactory::getApplication()->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_UPGRADE_FAILED'), 'error'); } return; } // Nothing to do, saved conversion status from DB is equal to required if ($convertedDB == $converted) { return; } // Step 1: Drop indexes later to be added again with column lengths limitations at step 2 $fileName1 = JPATH_ROOT . "/administrator/components/com_admin/sql/others/mysql/utf8mb4-conversion-01.sql"; if (is_file($fileName1)) { $fileContents1 = @file_get_contents($fileName1); $queries1 = $db->splitSql($fileContents1); if (!empty($queries1)) { foreach ($queries1 as $query1) { try { $db->setQuery($query1)->execute(); } catch (Exception $e) { // If the query fails we will go on. It just means the index to be dropped does not exist. } } } } // Step 2: Perform the index modifications and conversions $fileName2 = JPATH_ROOT . "/administrator/components/com_admin/sql/others/mysql/utf8mb4-conversion-02.sql"; if (is_file($fileName2)) { $fileContents2 = @file_get_contents($fileName2); $queries2 = $db->splitSql($fileContents2); if (!empty($queries2)) { foreach ($queries2 as $query2) { try { $db->setQuery($db->convertUtf8mb4QueryToUtf8($query2))->execute(); } catch (Exception $e) { $converted = 0; // Still render the error message from the Exception object JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error'); } } } } if ($doDbFixMsg && $converted == 0) { // Show an error message telling to check database problems JFactory::getApplication()->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_UPGRADE_FAILED'), 'error'); } // Set flag in database if the update is done. $db->setQuery('UPDATE ' . $db->quoteName('#__utf8_conversion') . ' SET ' . $db->quoteName('converted') . ' = ' . $converted . ';')->execute(); } /** * This method clean the Joomla Cache using the method `clean` from the com_cache model * * @return void * * @since 3.5.1 */ private function cleanJoomlaCache() { JModelLegacy::addIncludePath(JPATH_ROOT . '/administrator/components/com_cache/models'); $model = JModelLegacy::getInstance('cache', 'CacheModel'); // Clean frontend cache $model->clean(); // Clean admin cache $model->setState('client_id', 1); $model->clean(); } }
demis-palma/joomla-cms
administrator/components/com_admin/script.php
PHP
gpl-2.0
93,249
<?php /** * LDAP configuration test class * * PHP version 5 * * Copyright (C) Villanova University 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind * @package Tests * @author Franck Borel <franck.borel@gbv.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/unit_tests Wiki */ require_once dirname(__FILE__) . '/../../prepend.inc.php'; require_once 'PEAR.php'; require_once 'sys/authn/LDAPConfigurationParameter.php'; /** * LDAP configuration test class * * @category VuFind * @package Tests * @author Franck Borel <franck.borel@gbv.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/unit_tests Wiki */ class LDAPConfigurationParameterTest extends PHPUnit_Framework_TestCase { /** * Standard setup method. * * @return void * @access public */ public function setUp() { $this->pathToTestConfigurationFiles = dirname(__FILE__) . '/../../conf'; } /** * Verify that missing host causes failure. * * @return void * @access public */ public function testWithMissingHost() { try { $ldapConfigurationParameter = new LDAPConfigurationParameter( $this->pathToTestConfigurationFiles . "/authn/ldap/without-ldap-host-config.ini" ); $parameters = $ldapConfigurationParameter->getParameter(); } catch (InvalidArgumentException $expected) { return; } $this->fail('An expected InvalidArgumentException has not been raised'); } /** * Verify that missing port causes failure. * * @return void * @access public */ public function testWithMissingPort() { try { $ldapConfigurationParameter = new LDAPConfigurationParameter( $this->pathToTestConfigurationFiles . "/authn/ldap/without-ldap-port-config.ini" ); $parameters = $ldapConfigurationParameter->getParameter(); } catch (InvalidArgumentException $expected) { return; } $this->fail('An expected InvalidArgumentException has not been raised'); } /** * Verify that missing baseDN causes failure. * * @return void * @access public */ public function testWithMissingBaseDN() { try { $ldapConfigurationParameter = new LDAPConfigurationParameter( $this->pathToTestConfigurationFiles . "/authn/ldap/without-ldap-basedn-config.ini" ); $parameters = $ldapConfigurationParameter->getParameter(); } catch (InvalidArgumentException $expected) { return; } $this->fail('An expected InvalidArgumentException has not been raised'); } /** * Verify that missing UID causes failure. * * @return void * @access public */ public function testWithMissingUid() { try { $ldapConfigurationParameter = new LDAPConfigurationParameter( $this->pathToTestConfigurationFiles . "/authn/ldap/without-ldap-uid-config.ini" ); $parameters = $ldapConfigurationParameter->getParameter(); } catch (InvalidArgumentException $expected) { return; } $this->fail('An expected InvalidArgumentException has not been raised'); } /** * Verify that good parameters parse correctly. * * @return void * @access public */ public function testWithWorkingParameters() { try { $ldapConfigurationParameter = new LDAPConfigurationParameter(); $parameters = $ldapConfigurationParameter->getParameter(); $this->assertTrue(is_array($parameters)); } catch (InvalidArgumentException $unexpected) { $this->fail( "An unexpected InvalidArgumentException has been raised: " . $unexpected ); } } /** * Verify lowercasing of parameter values. * * @return void * @access public */ public function testIfParametersAreConvertedToLowercase() { try { $ldapConfigurationParameter = new LDAPConfigurationParameter( $this->pathToTestConfigurationFiles . "/authn/ldap/unconverted-parameter-values-config.ini" ); $parameters = $ldapConfigurationParameter->getParameter(); foreach ($parameters as $index => $value) { if ($index == "username") { $this->assertTrue($value == "uid"); } if ($index == "college") { $this->assertTrue($value == "employeetype"); } } } catch (InvalidArgumentException $unexpected) { $this->fail( "An unexpected InvalidArgumentException has been raised: " . $unexpected ); } } } ?>
marktriggs/vufind
tests/web/sys/authn/LDAPConfigurationParameterTest.php
PHP
gpl-2.0
5,799
/* Copyright (C) 2013 Rainmeter Project Developers * * This Source Code Form is subject to the terms of the GNU General Public * License; either version 2 of the License, or (at your option) any later * version. If a copy of the GPL was not distributed with this file, You can * obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */ #include "StdAfx.h" #include "StringUtil.h" namespace { // Is the character a end of sentence punctuation character? // English only? bool IsEOSPunct(wchar_t ch) { return ch == '?' || ch == '!' || ch == '.'; } } namespace StringUtil { std::string Narrow(const WCHAR* str, int strLen, int cp) { std::string narrowStr; if (str && *str) { if (strLen == -1) { strLen = (int)wcslen(str); } int bufLen = WideCharToMultiByte(cp, 0, str, strLen, nullptr, 0, nullptr, nullptr); if (bufLen > 0) { narrowStr.resize(bufLen); WideCharToMultiByte(cp, 0, str, strLen, &narrowStr[0], bufLen, nullptr, nullptr); } } return narrowStr; } std::wstring Widen(const char* str, int strLen, int cp) { std::wstring wideStr; if (str && *str) { if (strLen == -1) { strLen = (int)strlen(str); } int bufLen = MultiByteToWideChar(cp, 0, str, strLen, nullptr, 0); if (bufLen > 0) { wideStr.resize(bufLen); MultiByteToWideChar(cp, 0, str, strLen, &wideStr[0], bufLen); } } return wideStr; } void ToLowerCase(std::wstring& str) { WCHAR* srcAndDest = &str[0]; int strAndDestLen = (int)str.length(); LCMapString(LOCALE_USER_DEFAULT, LCMAP_LOWERCASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen); } void ToUpperCase(std::wstring& str) { WCHAR* srcAndDest = &str[0]; int strAndDestLen = (int)str.length(); LCMapString(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen); } void ToProperCase(std::wstring& str) { WCHAR* srcAndDest = &str[0]; int strAndDestLen = (int)str.length(); LCMapString(LOCALE_USER_DEFAULT, LCMAP_TITLECASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen); } void ToSentenceCase(std::wstring& str) { if (!str.empty()) { ToLowerCase(str); bool isCapped = false; for (size_t i = 0; i < str.length(); ++i) { if (IsEOSPunct(str[i])) isCapped = false; if (!isCapped && iswalpha(str[i]) != 0) { WCHAR* srcAndDest = &str[i]; LCMapString(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, srcAndDest, 1, srcAndDest, 1); isCapped = true; } } } } /* ** Escapes reserved PCRE regex metacharacters. */ void EscapeRegExp(std::wstring& str) { size_t start = 0; while ((start = str.find_first_of(L"\\^$|()[{.+*?", start)) != std::wstring::npos) { str.insert(start, L"\\"); start += 2; } } /* ** Escapes reserved URL characters. */ void EncodeUrl(std::wstring& str) { size_t pos = 0; while ((pos = str.find_first_of(L" !*'();:@&=+$,/?#[]", pos)) != std::wstring::npos) { WCHAR buffer[3]; _snwprintf_s(buffer, _countof(buffer), L"%.2X", str[pos]); str[pos] = L'%'; str.insert(pos + 1, buffer); pos += 3; } } /* ** Case insensitive comparison of strings. If equal, strip str2 from str1 and any leading whitespace. */ bool CaseInsensitiveCompareN(std::wstring& str1, const std::wstring& str2) { size_t pos = str2.length(); if (_wcsnicmp(str1.c_str(), str2.c_str(), pos) == 0) { str1 = str1.substr(pos); // remove str2 from str1 str1.erase(0, str1.find_first_not_of(L" \t\r\n")); // remove any leading whitespace return true; } return false; } } // namespace StringUtil
haroruhomer/rainmeter
Common/StringUtil.cpp
C++
gpl-2.0
3,637
var icms = icms || {}; icms.wall = (function ($) { var self = this; this.add = function (parent_id) { var form = $('#wall_add_form'); if (typeof (parent_id) === 'undefined') { parent_id = 0; } $('#wall_widget #wall_add_link').show(); $('#wall_widget #entries_list .links *').removeClass('disabled'); if (parent_id == 0){ $('#wall_widget #wall_add_link').hide(); form.detach().prependTo('#wall_widget #entries_list'); } else { $('#wall_widget #entries_list #entry_'+parent_id+' > .media-body > .links .reply').addClass('disabled'); form.detach().appendTo('#wall_widget #entries_list #entry_'+parent_id+' > .media-body'); } form.show(); $('input[name=parent_id]', form).val(parent_id); $('input[name=id]', form).val(''); $('input[name=action]', form).val('add'); $('input[name=submit]', form).val( LANG_SEND ); icms.forms.wysiwygInit('content').wysiwygInsertText('content', ''); return false; }; this.submit = function (action) { var form = $('#wall_add_form form'); var form_data = icms.forms.toJSON( form ); var url = form.attr('action'); if (action) {form_data.action = action;} $('.buttons > *', form).addClass('disabled'); $('.button-'+form_data.action, form).addClass('is-busy'); $('textarea', form).prop('disabled', true); $.post(url, form_data, function(result){ if (form_data.action === 'add') { self.result(result);} if (form_data.action === 'preview') { self.previewResult(result);} if (form_data.action === 'update') { self.updateResult(result);} }, "json"); }; this.preview = function () { this.submit('preview'); }; this.previewResult = function (result) { if (result.error){ this.error(result.message); return; } var form = $('#wall_add_form'); var preview_box = $('.preview_box', form).html(result.html); $(preview_box).addClass('shadow').removeClass('d-none'); setTimeout(function (){ $(preview_box).removeClass('shadow'); }, 1000); this.restoreForm(false); }; this.more = function(){ var widget = $('#wall_widget'); $('.show_more', widget).hide(); $('.entry', widget).show(); $('.wall_pages', widget).show(); return false; }; this.replies = function(id, callback){ var e = $('#wall_widget #entry_'+id); if (!e.data('replies')) { return false; } var url = $('#wall_urls').data('replies-url'); $('.icms-wall-item__btn_replies', e).addClass('is-busy'); $.post(url, {id: id}, function(result){ $('.icms-wall-item__btn_replies', e).removeClass('is-busy').hide(); if (result.error){ self.error(result.message); return false; } $('.replies', e).html( result.html ); if (typeof(callback)=='function'){ callback(); } }, "json"); return false; }; this.append = function(entry){ $('#wall_widget #entries_list .no_entries').remove(); if (entry.parent_id == 0){ $('#wall_widget #entries_list').prepend( entry.html ); return; } if (entry.parent_id > 0){ $('#wall_widget #entry_'+entry.parent_id+' .replies').append( entry.html ); return; } }; this.result = function(result){ if (result.error){ this.error(result.message); return; } this.append(result); this.restoreForm(); }; this.updateResult = function(result){ if (result.error){ this.error(result.message); return; } $('#entries_list #entry_'+result.id+'> .media-body > .icms-wall-html').html(result.html); this.restoreForm(); }; this.edit = function (id){ var form = $('#wall_add_form'); $('#wall_widget #wall_add_link').show(); $('#wall_widget #entries_list .links *').removeClass('disabled'); $('#wall_widget #entries_list #entry_'+id+' > .media-body > .links .edit').addClass('is-busy disabled'); form.detach().insertAfter('#wall_widget #entries_list #entry_'+id+' > .media-body > .links').show(); $('input[name=id]', form).val(id); $('input[name=action]', form).val('update'); $('input[name=submit]', form).val( LANG_SAVE ); $('textarea', form).prop('disabled', true); icms.forms.wysiwygInit('content'); var url = $('#wall_urls').data('get-url'); $.post(url, {id: id}, function(result){ $('#wall_widget #entries_list #entry_'+id+' > .media-body > .links .edit').removeClass('is-busy'); if (result.error){ self.error(result.message); return; } self.restoreForm(false); icms.forms.wysiwygInsertText('content', result.html); }, 'json'); return false; }; this.remove = function (id){ var c = $('#entries_list #entry_'+id); var username = $('> .media-body > h6 .user', c).text(); if (!confirm(LANG_WALL_ENTRY_DELETE_CONFIRM.replace('%s', username))) { return false; } var url = $('#wall_urls').data('delete-url'); $.post(url, {id: id}, function(result){ if (result.error){ self.error(result.message); return; } c.remove(); self.restoreForm(); }, "json"); return false; }; this.show = function(id, reply_id, go_reply){ var e = $('#entry_'+id); if (e.length){ $.scrollTo( e, 500, { offset: { left:0, top:-10 }, onAfter: function(){ self.replies(id, function(){ if (reply_id>0){ self.show(reply_id); } }); if (go_reply){ self.add(id); } } }); } else { if (go_reply){ $.scrollTo( $('#wall_widget'), 500, { offset: { left:0, top:-10 }, onAfter: function(){ self.add(); } }); } } return false; }; this.error = function(message){ icms.modal.alert(message); this.restoreForm(false); }; this.restoreForm = function(clear_text){ if (typeof (clear_text) === 'undefined') { clear_text = true; } var form = $('#wall_add_form'); $('.buttons *', form).removeClass('disabled is-busy'); $('textarea', form).prop('disabled', false); if (clear_text) { form.hide(); icms.forms.wysiwygInsertText('content', ''); $('#wall_widget #wall_add_link').show(); $('#wall_widget #entries_list .links *').removeClass('disabled'); $('.preview_box', form).html('').hide(); } }; return this; }).call(icms.wall || {},jQuery);
Loadir/icms2
templates/modern/js/wall.js
JavaScript
gpl-2.0
7,610
<html> <head> <title> TEAMMATES - Instructor </title> <link href="/favicon.png" rel="shortcut icon"> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <link href="https://unpkg.com/bootstrap@3.1.1/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link href="https://unpkg.com/bootstrap@3.1.1/dist/css/bootstrap-theme.min.css" rel="stylesheet" type="text/css"> <link href="/stylesheets/teammatesCommon.css" rel="stylesheet" type="text/css"> <link href="/stylesheets/datepicker.css" media="screen" rel="stylesheet" type="text/css"> <link href="https://unpkg.com/tinymce@4.5.1/skins/lightgray/skin.min.css" id="u0" rel="stylesheet" type="text/css"> <link href="https://unpkg.com/tinymce@4.5.1/skins/lightgray/content.inline.min.css" rel="stylesheet"> </head> <body spellcheck="false"> <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button class="navbar-toggle" data-target="#contentLinks" data-toggle="collapse" type="button"> <span class="sr-only"> Toggle navigation </span> <span class="icon-bar"> </span> <span class="icon-bar"> </span> <span class="icon-bar"> </span> </button> <a class="navbar-brand" href="/index.jsp"> TEAMMATES </a> </div> <div class="collapse navbar-collapse" id="contentLinks"> <ul class="nav navbar-nav"> <li> <a class="nav home" data-link="instructorHome" href="/page/instructorHomePage?user=CFeedbackUiT.nocourses"> Home </a> </li> <li> <a class="nav courses" data-link="instructorCourse" href="/page/instructorCoursesPage?user=CFeedbackUiT.nocourses"> Courses </a> </li> <li class="active"> <a class="nav evaluations" data-link="instructorEval" href="/page/instructorFeedbacksPage?user=CFeedbackUiT.nocourses"> Sessions </a> </li> <li> <a class="nav students" data-link="instructorStudent" href="/page/instructorStudentListPage?user=CFeedbackUiT.nocourses"> Students </a> </li> <li> <a class="nav comments" data-link="instructorComments" href="/page/instructorCommentsPage?user=CFeedbackUiT.nocourses"> Comments </a> </li> <li> <a class="nav search" data-link="instructorSearch" href="/page/instructorSearchPage?user=CFeedbackUiT.nocourses"> Search </a> </li> <li> <a class="nav help" href="/instructorHelp.jsp" rel="noopener noreferrer" target="_blank"> Help </a> </li> </ul> <ul class="nav navbar-nav pull-right"> <li> <a class="nav logout" href="/logout" id="btnLogout"> Logout ( <span class="text-info tool-tip-decorate" data-original-title="CFeedbackUiT.nocourses" data-placement="bottom" data-toggle="tooltip" title=""> CFeedbackUiT.nocourses </span> ) </a> </li> </ul> </div> </div> </div> <div class="container" id="mainContent"> <div id="topOfPage"> </div> <h1> Add New Feedback Session </h1> <br> <div class="well well-plain"> <form action="/page/instructorFeedbackAdd" class="form-group" id="form_feedbacksession" method="post"> <div class="row"> <h4 class="label-control col-md-2 text-md"> Create new </h4> <div class="col-md-5"> <div class="col-xs-10 tablet-no-padding" data-original-title="Select a session type here." data-placement="top" data-toggle="tooltip" title=""> <select class="form-control" id="fstype" name="fstype"> <option value="STANDARD"> Session with your own questions </option> <option selected="" value="TEAMEVALUATION"> Team peer evaluation session </option> </select> </div> <div class="col-xs-1"> <h5> <a href="/instructorHelp.jsp#fbSetupSession" rel="noopener noreferrer" target="_blank"> <span class="glyphicon glyphicon-info-sign"> </span> </a> </h5> </div> </div> <h4 class="label-control col-xs-12 col-md-1 text-md"> Or: </h4> <div class="col-xs-12 col-md-3"> <a class="btn btn-info" id="button_copy" style="vertical-align:middle;"> Copy from previous feedback sessions </a> </div> </div> <br> <div class="panel panel-primary"> <div class="panel-body"> <div class="row"> <div class="col-sm-12 col-md-6" data-original-title="Please select the course for which the feedback session is to be created." data-placement="top" data-toggle="tooltip" title=""> <div class="form-group has-error"> <h5 class="col-sm-2 col-md-4"> <label class="control-label" for="courseid"> Course ID </label> </h5> <div class="col-sm-10 col-md-8"> <select class="form-control text-color-red" id="courseid" name="courseid"> <option selected="" value=""> No un-archived courses </option> </select> </div> </div> </div> <div class="col-sm-12 col-md-6 tablet-no-mobile-margin-top-20px" data-original-title="You should not need to change this as your timezone is auto-detected. <br><br>However, note that daylight saving is not taken into account i.e. if you are in UTC -8:00 and there is daylight saving, you should choose UTC -7:00 and its corresponding timings." data-placement="top" data-toggle="tooltip" title=""> <div class="form-group"> <h5 class="col-sm-2 col-md-4"> <label class="control-label" for="timezone"> Timezone </label> </h5> <div class="col-sm-10 col-md-8"> <select class="form-control" id="timezone" name="timezone"> <option value="-12"> (UTC -12:00) Baker Island, Howland Island </option> <option value="-11"> (UTC -11:00) American Samoa, Niue </option> <option value="-10"> (UTC -10:00) Hawaii, Cook Islands </option> <option value="-9.5"> (UTC -09:30) Marquesas Islands </option> <option value="-9"> (UTC -09:00) Gambier Islands, Alaska </option> <option value="-8"> (UTC -08:00) Los Angeles, Vancouver, Tijuana </option> <option value="-7"> (UTC -07:00) Phoenix, Calgary, Ciudad Juárez </option> <option value="-6"> (UTC -06:00) Chicago, Guatemala City, Mexico City, San José, San Salvador, Tegucigalpa, Winnipeg </option> <option value="-5"> (UTC -05:00) New York, Lima, Toronto, Bogotá, Havana, Kingston </option> <option value="-4.5"> (UTC -04:30) Caracas </option> <option value="-4"> (UTC -04:00) Santiago, La Paz, San Juan de Puerto Rico, Manaus, Halifax </option> <option value="-3.5"> (UTC -03:30) St. John's </option> <option value="-3"> (UTC -03:00) Buenos Aires, Montevideo, São Paulo </option> <option value="-2"> (UTC -02:00) Fernando de Noronha, South Georgia and the South Sandwich Islands </option> <option value="-1"> (UTC -01:00) Cape Verde, Greenland, Azores islands </option> <option value="0"> (UTC) Accra, Abidjan, Casablanca, Dakar, Dublin, Lisbon, London </option> <option value="1"> (UTC +01:00) Belgrade, Berlin, Brussels, Lagos, Madrid, Paris, Rome, Tunis, Vienna, Warsaw </option> <option value="2"> (UTC +02:00) Athens, Sofia, Cairo, Kiev, Istanbul, Beirut, Helsinki, Jerusalem, Johannesburg, Bucharest </option> <option value="3"> (UTC +03:00) Nairobi, Baghdad, Doha, Khartoum, Minsk, Riyadh </option> <option value="3.5"> (UTC +03:30) Tehran </option> <option value="4"> (UTC +04:00) Baku, Dubai, Moscow </option> <option value="4.5"> (UTC +04:30) Kabul </option> <option value="5"> (UTC +05:00) Karachi, Tashkent </option> <option value="5.5"> (UTC +05:30) Colombo, Delhi </option> <option value="5.75"> (UTC +05:45) Kathmandu </option> <option value="6"> (UTC +06:00) Almaty, Dhaka, Yekaterinburg </option> <option value="6.5"> (UTC +06:30) Yangon </option> <option value="7"> (UTC +07:00) Jakarta, Bangkok, Novosibirsk, Hanoi </option> <option value="8"> (UTC +08:00) Perth, Beijing, Manila, Singapore, Kuala Lumpur, Denpasar, Krasnoyarsk </option> <option value="8.75"> (UTC +08:45) Eucla </option> <option value="9"> (UTC +09:00) Seoul, Tokyo, Pyongyang, Ambon, Irkutsk </option> <option value="9.5"> (UTC +09:30) Adelaide </option> <option value="10"> (UTC +10:00) Canberra, Yakutsk, Port Moresby </option> <option value="10.5"> (UTC +10:30) Lord Howe Islands </option> <option value="11"> (UTC +11:00) Vladivostok, Noumea </option> <option value="12"> (UTC +12:00) Auckland, Suva </option> <option value="12.75"> (UTC +12:45) Chatham Islands </option> <option value="13"> (UTC +13:00) Phoenix Islands, Tokelau, Tonga </option> <option value="14"> (UTC +14:00) Line Islands </option> </select> </div> </div> </div> </div> <br class="hidden-xs"> <div class="row"> <div class="col-sm-12" data-original-title="Enter the name of the feedback session e.g. Feedback Session 1." data-placement="top" data-toggle="tooltip" title=""> <div class="form-group"> <h5 class="col-sm-2"> <label class="control-label" for="fsname"> Session name </label> </h5> <div class="col-sm-10"> <input class="form-control" id="fsname" maxlength="38" name="fsname" placeholder="e.g. Feedback for Project Presentation 1" type="text" value=""> </div> </div> </div> </div> <br class="hidden-xs"> <div class="row" id="instructionsRow"> <div class="col-sm-12" data-original-title="Enter instructions for this feedback session. e.g. Avoid comments which are too critical.<br> It will be displayed at the top of the page when users respond to the session." data-placement="top" data-toggle="tooltip" title=""> <div class="form-group"> <h5 class="col-sm-2 margin-top-0"> <label class="control-label" for="instructions"> Instructions </label> </h5> <div class="col-sm-10"> <div id="richtext-toolbar-container"> </div> <div class="panel panel-default panel-body mce-content-body content-editor" contenteditable="true" id="instructions" spellcheck="false" style="position: relative;"> <p> Please answer all the given questions. </p> </div> <input name="instructions" type="hidden"> </div> </div> </div> </div> </div> </div> <div class="panel panel-primary" id="timeFramePanel"> <div class="panel-body"> <div class="row"> <div class="col-md-5" data-original-title="Please select the date and time for which users can start submitting responses for the feedback session." data-placement="top" data-toggle="tooltip" title=""> <div class="row"> <div class="col-xs-12"> <label class="label-control" for="startdate"> Submission opening time </label> </div> </div> <div class="row"> <div class="col-xs-6"> <input class="form-control col-sm-2 hasDatepicker" id="startdate" name="startdate" placeholder="Date" type="text" value="${date.nexthour}"> </div> <div class="col-xs-6"> <select class="form-control" id="starttime" name="starttime"> <option value="1"> 0100H </option> <option value="2"> 0200H </option> <option value="3"> 0300H </option> <option value="4"> 0400H </option> <option value="5"> 0500H </option> <option value="6"> 0600H </option> <option value="7"> 0700H </option> <option value="8"> 0800H </option> <option value="9"> 0900H </option> <option value="10"> 1000H </option> <option value="11"> 1100H </option> <option value="12"> 1200H </option> <option value="13"> 1300H </option> <option value="14"> 1400H </option> <option value="15"> 1500H </option> <option value="16"> 1600H </option> <option value="17"> 1700H </option> <option value="18"> 1800H </option> <option value="19"> 1900H </option> <option value="20"> 2000H </option> <option value="21"> 2100H </option> <option value="22"> 2200H </option> <option value="23"> 2300H </option> <option selected="" value="24"> 2359H </option> </select> </div> </div> </div> <div class="col-md-5 border-left-gray" data-original-title="Please select the date and time after which the feedback session will no longer accept submissions from users." data-placement="top" data-toggle="tooltip" title=""> <div class="row"> <div class="col-xs-12"> <label class="label-control" for="enddate"> Submission closing time </label> </div> </div> <div class="row"> <div class="col-xs-6"> <input class="form-control col-sm-2 hasDatepicker" id="enddate" name="enddate" placeholder="Date" type="text" value=""> </div> <div class="col-xs-6"> <select class="form-control" id="endtime" name="endtime"> <option value="1"> 0100H </option> <option value="2"> 0200H </option> <option value="3"> 0300H </option> <option value="4"> 0400H </option> <option value="5"> 0500H </option> <option value="6"> 0600H </option> <option value="7"> 0700H </option> <option value="8"> 0800H </option> <option value="9"> 0900H </option> <option value="10"> 1000H </option> <option value="11"> 1100H </option> <option value="12"> 1200H </option> <option value="13"> 1300H </option> <option value="14"> 1400H </option> <option value="15"> 1500H </option> <option value="16"> 1600H </option> <option value="17"> 1700H </option> <option value="18"> 1800H </option> <option value="19"> 1900H </option> <option value="20"> 2000H </option> <option value="21"> 2100H </option> <option value="22"> 2200H </option> <option value="23"> 2300H </option> <option selected="" value="24"> 2359H </option> </select> </div> </div> </div> <div class="col-md-2 border-left-gray" data-original-title="Please select the amount of time that the system will continue accepting <br>submissions after the specified deadline." data-placement="top" data-toggle="tooltip" title=""> <div class="row"> <div class="col-xs-12"> <label class="control-label" for="graceperiod"> Grace period </label> </div> </div> <div class="row"> <div class="col-xs-12"> <select class="form-control" id="graceperiod" name="graceperiod"> <option value="0"> 0 mins </option> <option value="5"> 5 mins </option> <option value="10"> 10 mins </option> <option selected="" value="15"> 15 mins </option> <option value="20"> 20 mins </option> <option value="25"> 25 mins </option> <option value="30"> 30 mins </option> </select> </div> </div> </div> </div> </div> </div> <div id="uncommonSettingsSection"> <div class="panel panel-primary" id="sessionResponsesVisiblePanel" style="display:none;"> <div class="panel-body"> <div class="row"> <div class="col-xs-12 col-md-6"> <div class="row"> <div class="col-xs-12" data-original-title="Please select when you want the questions for the feedback session to be visible to users who need to participate. Note that users cannot submit their responses until the submissions opening time set below." data-placement="top" data-toggle="tooltip" title=""> <label class="label-control"> Session visible from </label> </div> </div> <div class="row radio"> <h5 class="col-xs-2" data-original-title="Select this option to enter in a custom date and time for which the feedback session will become visible.<br>Note that you can make a session visible before it is open for submissions so that users can preview the questions." data-placement="top" data-toggle="tooltip" title=""> <label for="sessionVisibleFromButton_custom"> At </label> <input id="sessionVisibleFromButton_custom" name="sessionVisibleFromButton" type="radio" value="custom"> </h5> <div class="col-xs-5"> <input class="form-control col-sm-2 hasDatepicker" disabled="" id="visibledate" name="visibledate" type="text" value=""> </div> <div class="col-xs-5"> <select class="form-control" disabled="" id="visibletime" name="visibletime"> <option value="1"> 0100H </option> <option value="2"> 0200H </option> <option value="3"> 0300H </option> <option value="4"> 0400H </option> <option value="5"> 0500H </option> <option value="6"> 0600H </option> <option value="7"> 0700H </option> <option value="8"> 0800H </option> <option value="9"> 0900H </option> <option value="10"> 1000H </option> <option value="11"> 1100H </option> <option value="12"> 1200H </option> <option value="13"> 1300H </option> <option value="14"> 1400H </option> <option value="15"> 1500H </option> <option value="16"> 1600H </option> <option value="17"> 1700H </option> <option value="18"> 1800H </option> <option value="19"> 1900H </option> <option value="20"> 2000H </option> <option value="21"> 2100H </option> <option value="22"> 2200H </option> <option value="23"> 2300H </option> <option selected="" value="24"> 2359H </option> </select> </div> </div> <div class="row radio"> <div class="col-xs-12" data-original-title="Select this option to have the feedback session become visible when it is open for submissions (as selected above)." data-placement="top" data-toggle="tooltip" title=""> <label for="sessionVisibleFromButton_atopen"> Submission opening time </label> <input checked="" id="sessionVisibleFromButton_atopen" name="sessionVisibleFromButton" type="radio" value="atopen"> </div> </div> <div class="row radio"> <div class="col-xs-12" data-original-title="Select this option if you want the feedback session to be private. A private session is never visible to anyone. Private sessions can be used to record your own comments about others, for your own reference." data-placement="top" data-toggle="tooltip" title=""> <label for="sessionVisibleFromButton_never"> Never </label> <input id="sessionVisibleFromButton_never" name="sessionVisibleFromButton" type="radio" value="never"> </div> </div> </div> <div class="col-xs-12 col-md-6 border-left-gray" id="responsesVisibleFromColumn"> <div class="row"> <div class="col-xs-12" data-original-title="Please select when the responses for the feedback session will be visible to the designated recipients.<br>You can select the response visibility for each type of user and question later." data-placement="top" data-toggle="tooltip" title=""> <label class="label-control"> Responses visible from </label> </div> </div> <div class="row radio"> <h5 class="col-xs-2" data-original-title="Select this option to use a custom time for when the responses of the feedback session<br>will be visible to the designated recipients." data-placement="top" data-toggle="tooltip" title=""> <label for="resultsVisibleFromButton_custom"> At </label> <input id="resultsVisibleFromButton_custom" name="resultsVisibleFromButton" type="radio" value="custom"> </h5> <div class="col-xs-5"> <input class="form-control hasDatepicker" disabled="" id="publishdate" name="publishdate" type="text" value=""> </div> <div class="col-xs-5"> <select class="form-control" data-original-title="Select this option to enter in a custom date and time for which</br>the responses for this feedback session will become visible." data-placement="top" data-toggle="tooltip" disabled="" id="publishtime" name="publishtime" title=""> <option value="1"> 0100H </option> <option value="2"> 0200H </option> <option value="3"> 0300H </option> <option value="4"> 0400H </option> <option value="5"> 0500H </option> <option value="6"> 0600H </option> <option value="7"> 0700H </option> <option value="8"> 0800H </option> <option value="9"> 0900H </option> <option value="10"> 1000H </option> <option value="11"> 1100H </option> <option value="12"> 1200H </option> <option value="13"> 1300H </option> <option value="14"> 1400H </option> <option value="15"> 1500H </option> <option value="16"> 1600H </option> <option value="17"> 1700H </option> <option value="18"> 1800H </option> <option value="19"> 1900H </option> <option value="20"> 2000H </option> <option value="21"> 2100H </option> <option value="22"> 2200H </option> <option value="23"> 2300H </option> <option selected="" value="24"> 2359H </option> </select> </div> </div> <div class="row radio"> <div class="col-xs-12" data-original-title="Select this option to have the feedback responses be immediately visible<br>when the session becomes visible to users." data-placement="top" data-toggle="tooltip" title=""> <label for="resultsVisibleFromButton_atvisible"> Immediately </label> <input id="resultsVisibleFromButton_atvisible" name="resultsVisibleFromButton" type="radio" value="atvisible"> </div> </div> <div class="row radio"> <div class="col-xs-12" data-original-title="Select this option if you intend to manually publish the responses for this session later on." data-placement="top" data-toggle="tooltip" title=""> <label for="resultsVisibleFromButton_later"> Publish manually </label> <input checked="" id="resultsVisibleFromButton_later" name="resultsVisibleFromButton" type="radio" value="later"> </div> </div> <div class="row radio"> <div class="col-xs-12" data-original-title="Select this option if you intend never to publish the responses." data-placement="top" data-toggle="tooltip" title=""> <label for="resultsVisibleFromButton_never"> Never </label> <input id="resultsVisibleFromButton_never" name="resultsVisibleFromButton" type="radio" value="never"> </div> </div> </div> </div> </div> </div> <div class="panel panel-primary" id="sendEmailsForPanel" style="display:none;"> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <label class="control-label"> Send emails for </label> </div> </div> <div class="row"> <div class="col-md-3" data-original-title="Select this option to automatically send an email to students to notify them when the session is open for submission." data-placement="top" data-toggle="tooltip" title=""> <div class="checkbox"> <label> Session opening reminder </label> <input checked="" disabled="" id="sendreminderemail_open" name="sendreminderemail" type="checkbox" value="FEEDBACK_OPENING"> </div> </div> <div class="col-md-3" data-original-title="Select this option to automatically send an email to students to remind them to submit 24 hours before the end of the session." data-placement="top" data-toggle="tooltip" title=""> <div class="checkbox"> <label for="sendreminderemail_closing"> Session closing reminder </label> <input checked="" id="sendreminderemail_closing" name="sendreminderemail" type="checkbox" value="FEEDBACK_CLOSING"> </div> </div> <div class="col-md-4" data-original-title="Select this option to automatically send an email to students to notify them when the session results is published." data-placement="top" data-toggle="tooltip" title=""> <div class="checkbox"> <label for="sendreminderemail_published"> Results published announcement </label> <input checked="" id="sendreminderemail_published" name="sendreminderemail" type="checkbox" value="FEEDBACK_PUBLISHED"> </div> </div> </div> </div> </div> <div class="margin-bottom-15px text-muted" id="uncommonSettingsSessionResponsesVisible"> <span id="uncommonSettingsSessionResponsesVisibleInfoText"> Session is visible at submission opening time, responses are only visible when you publish the results. </span> <a class="editUncommonSettingsButton" data-done="[Done]" data-edit="[Edit]" id="editUncommonSettingsSessionResponsesVisibleButton"> [Change] </a> </div> <div class="margin-bottom-15px text-muted" id="uncommonSettingsSendEmails"> <span id="uncommonSettingsSendEmailsInfoText"> Emails are sent when session opens (within 15 mins), 24 hrs before session closes and when results are published. </span> <a class="editUncommonSettingsButton" data-done="[Done]" data-edit="[Edit]" id="editUncommonSettingsSendEmailsButton"> [Change] </a> </div> </div> <div class="form-group"> <div class="row"> <div class="col-md-offset-5 col-md-3"> <button class="btn btn-primary" disabled="" id="button_submit" type="submit"> Create Feedback Session </button> </div> </div> </div> <div class="row"> <div class="col-md-12 text-center"> <b> You need to have an active(unarchived) course to create a session! </b> </div> </div> <input name="user" type="hidden" value="CFeedbackUiT.nocourses"> </form> </div> <form action="/page/instructorFeedbacksPage" class="ajaxForSessionsForm" id="ajaxForSessions" style="display:none;"> <input name="user" type="hidden" value="CFeedbackUiT.nocourses"> <input name="isusingAjax" type="hidden" value="on"> </form> <br> <div id="statusMessagesToUser" style="display: block;"> <div class="overflow-auto alert alert-warning statusMessage"> You have not created any courses yet, or you have no active courses. Go <a href="/page/instructorCoursesPage?user=CFeedbackUiT.nocourses"> here </a> to create or unarchive a course. </div> </div> <script defer="" src="/js/statusMessage.js" type="text/javascript"> </script> <br> <div class="" id="sessionList"> <table class="table-responsive table table-striped table-bordered" id="table-sessions"> <thead> <tr class="fill-primary"> <th class="button-sort-ascending course-id-table-width" id="button_sortid" onclick="toggleSort(this);"> Course ID <span class="icon-sort unsorted"> </span> </th> <th class="button-sort-none session-name-table-width" id="button_sortname" onclick="toggleSort(this)"> Session Name <span class="icon-sort unsorted"> </span> </th> <th> Status </th> <th> <span class="tool-tip-decorate" data-original-title="Number of students submitted / Class size" data-placement="top" data-toggle="tooltip" title=""> Response Rate </span> </th> <th class="no-print"> Action(s) </th> </tr> </thead> <tbody> <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </tbody> </table> <p class="col-md-12 text-muted"> Note: The table above doesn't contain sessions from archived courses. To view sessions from an archived course, unarchive the course first. </p> <br> <br> <br> <div class="align-center"> No records found. </div> <br> <br> <br> </div> <div aria-hidden="true" aria-labelledby="remindModal" class="modal fade" id="remindModal" role="dialog" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <form action="/page/instructorFeedbackRemindParticularStudents?next=%2Fpage%2FinstructorFeedbacksPage" method="post" name="form_remind_list" role="form"> <div class="modal-header"> <button aria-hidden="true" class="close" data-dismiss="modal" type="button"> × </button> <h4 class="modal-title"> Remind Particular Students <small> (Select the student(s) you want to remind) </small> </h4> </div> <div class="modal-body"> <div class="form-group" id="studentList"> </div> </div> <div class="modal-footer"> <button class="btn btn-default" data-dismiss="modal" type="button"> Cancel </button> <input class="btn btn-primary" type="submit" value="Remind"> <input name="user" type="hidden" value="CFeedbackUiT.nocourses"> </div> </form> </div> </div> </div> <div aria-hidden="true" aria-labelledby="copyModalTitle" class="modal fade" id="copyModal" role="dialog" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button class="close" data-dismiss="modal" type="button"> <span aria-hidden="true"> × </span> <span class="sr-only"> Close </span> </button> <h4 class="modal-title" id="copyModalTitle"> Creating a new session by copying a previous session </h4> </div> <div class="modal-body" id="copySessionsBody"> <form action="/page/instructorFeedbackCopy" class="form" id="copyModalForm" method="post" role="form"> <div class="form-group"> <label class="control-label" for="modalCopiedCourseId"> Create in course </label> <select class="form-control" id="modalCopiedCourseId" name="copiedcourseid"> <option selected="" value=""> No un-archived courses </option> </select> </div> <div class="form-group"> <label class="control-label" for="modalCopiedSessionName"> Name for new session </label> <input class="form-control" id="modalCopiedSessionName" maxlength="38" name="copiedfsname" placeholder="e.g. Feedback for Project Presentation 1" type="text" value=""> </div> <label> Copy sessions/questions from </label> <table class="table-responsive table table-bordered table-hover margin-0" id="copyTableModal"> <thead class="fill-primary"> <tr> <th style="width:20px;">   </th> <th> Course ID </th> <th> Feedback Session Name </th> </tr> </thead> </table> <input id="modalSessionName" name="fsname" type="hidden" value=""> <input id="modalCourseId" name="courseid" type="hidden" value=""> <input name="user" type="hidden" value="CFeedbackUiT.nocourses"> </form> </div> <div class="modal-footer margin-0"> <button class="btn btn-primary" disabled="" id="button_copy_submit" type="button"> Copy </button> <button class="btn btn-default" data-dismiss="modal" type="button"> Cancel </button> </div> </div> </div> </div> <div aria-hidden="true" aria-labelledby="fsCopyModal" class="modal fade" id="fsCopyModal" role="dialog" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <form action="/page/instructorFeedbackEditCopy?next=%2Fpage%2FinstructorFeedbacksPage" id="instructorCopyModalForm" method="post" role="form"> <div class="modal-header"> <button aria-hidden="true" class="close" data-dismiss="modal" type="button"> × </button> <h4 class="modal-title"> Copy this feedback session to other courses <br> <small> (Select the course(s) you want to copy this feedback session to) </small> </h4> </div> <div class="modal-body"> <div class="form-group" id="courseList"> </div> </div> <div class="modal-footer"> <button class="btn btn-default" data-dismiss="modal" type="button"> Cancel </button> <input class="btn btn-primary" id="fscopy_submit" type="submit" value="Copy"> <input name="user" type="hidden" value="CFeedbackUiT.nocourses"> </div> </form> </div> </div> </div> </div> <div class="container-fluid" id="footerComponent"> <div class="container"> <div class="row"> <div class="col-md-2"> <span> [ <a href="/index.jsp"> TEAMMATES </a> V${version}] </span> </div> <div class="col-md-8"> [for <span class="highlight-white"> TEAMMATES Test Institute 1 </span> ] </div> <div class="col-md-2"> <span> [Send <a class="link" href="/contact.jsp" rel="noopener noreferrer" target="_blank"> Feedback </a> ] </span> </div> </div> </div> </div> <script async="" src="https://ssl.google-analytics.com/ga.js" type="text/javascript"> </script> <script src="/js/googleAnalytics.js" type="text/javascript"> </script> <script src="https://unpkg.com/jquery@1.12.4/dist/jquery.min.js" type="text/javascript"> </script> <script src="https://unpkg.com/jquery-ui-dist@1.12.1/jquery-ui.min.js" type="text/javascript"> </script> <script src="https://unpkg.com/bootstrap@3.1.1/dist/js/bootstrap.min.js" type="text/javascript"> </script> <script src="https://unpkg.com/bootbox@4.4.0/bootbox.min.js" type="text/javascript"> </script> <script src="/js/common.js" type="text/javascript"> </script> <script src="https://unpkg.com/tinymce@4.5.1/tinymce.min.js" type="text/javascript"> </script> <script src="/js/richTextEditor.js" type="text/javascript"> </script> <script src="/js/datepicker.js" type="text/javascript"> </script> <script src="/js/instructor.js" type="text/javascript"> </script> <script src="/js/ajaxResponseRate.js" type="text/javascript"> </script> <script src="/js/instructorFeedbackAjaxRemindModal.js" type="text/javascript"> </script> <script src="/js/instructorFeedbacksAjax.js" type="text/javascript"> </script> <script src="/js/instructorFeedbacks.js" type="text/javascript"> </script> <script src="/js/instructorFeedbacksSpecific.js" type="text/javascript"> </script> <div class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" id="ui-datepicker-div"> </div> </body> </html>
karthikaacharya/teammates
src/test/resources/pages/instructorFeedbackEmptyAll.html
HTML
gpl-2.0
47,060
<?php //////////////////////////////////////////////////////////////////////////////// // // // 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. // // // // This product released under GNU General Public License v2 // //////////////////////////////////////////////////////////////////////////////// /** * Debug on/off */ define("DEBUG", 0); $query_counter = 0; if (!extension_loaded('mysql')) { /** * MySQLi database layer * */ if (!($db_config = @parse_ini_file('config/' . 'signup.ini'))) { print('Cannot load mysql configuration'); exit; } $dbport = (empty($db_config['port'])) ? 3306 : $db_config['port']; $loginDB = new mysqli($db_config['server'], $db_config['username'], $db_config['password'], $db_config['db'], $dbport); if ($loginDB->connect_error) { die('Connection error (' . $loginDB->connect_errno . ') ' . $loginDB->connect_error); } else { $loginDB->query("set character_set_client='" . $db_config['character'] . "'"); $loginDB->query("set character_set_results='" . $db_config['character'] . "'"); $loginDB->query("set collation_connection='" . $db_config['character'] . "_general_ci'"); } /** * Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection * * @global mysqli $loginDB * @param aata to filter $parametr * * @return string */ function loginDB_real_escape_string($parametr) { global $loginDB; $result = $loginDB->real_escape_string($parametr); return($result); } if (!function_exists('mysql_real_escape_string')) { /** * Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection * * @param string $data * * @return string */ function mysql_real_escape_string($data) { return(loginDB_real_escape_string($data)); } } /** * Executing query and returns result as array * * @global int $query_counter * @param string $query * @return array */ function simple_queryall($query) { global $loginDB, $query_counter; if (DEBUG) { print ($query . "\n"); } $result = array(); $queried = $loginDB->query($query) or die('wrong data input: ' . $query); while ($row = mysqli_fetch_assoc($queried)) { $result[] = $row; } $query_counter++; return($result); } /** * Executing query and returns array of first result * * @global int $query_counter * @param string $query * @return array */ function simple_query($query) { global $loginDB, $query_counter; if (DEBUG) { print ($query . "\n"); } $queried = $loginDB->query($query) or die('wrong data input: ' . $query); $result = mysqli_fetch_assoc($queried); $query_counter++; return($result); } /** * Updates single field in table with where expression * * @param string $tablename * @param string $field * @param string $value * @param string $where * @param bool $NoQuotesAroundValue */ function simple_update_field($tablename, $field, $value, $where = '', $NoQuotesAroundValue = false) { $tablename = loginDB_real_escape_string($tablename); $value = loginDB_real_escape_string($value); $field = loginDB_real_escape_string($field); if ($NoQuotesAroundValue) { $query = "UPDATE `" . $tablename . "` SET `" . $field . "` = " . $value . " " . $where . ""; } else { $query = "UPDATE `" . $tablename . "` SET `" . $field . "` = '" . $value . "' " . $where . ""; } nr_query($query); } /** * Returns last used `id` field available in some table * * @param string $tablename * @return int */ function simple_get_lastid($tablename) { $tablename = loginDB_real_escape_string($tablename); $query = "SELECT `id` from `" . $tablename . "` ORDER BY `id` DESC LIMIT 1"; $result = simple_query($query); return($result['id']); } /** * Just executing single query * * @global int $query_counter * @param string $query * @return mixed */ function nr_query($query) { global $loginDB, $query_counter; if (DEBUG) { print ($query . "\n"); } $queried = $loginDB->query($query) or die('wrong data input: ' . $query); $query_counter++; return($queried); } } else { /** * MySQL database old driver abstraction class * */ class MySQLDB { var $connection; var $last_query_num = 0; var $db_config = array(); /** * last query result id * * @var MySQL result */ var $lastresult; /** * last query assoc value * * @var bool */ var $assoc = true; /** * Initialises connection with MySQL database server and selects needed db * * @param MySQL Connection Id $connection * @return MySQLDB */ public function __construct($connection = false) { if ($connection) $this->connection = $connection; else { if (!($this->db_config = @parse_ini_file('config/' . 'signup.ini'))) { print(('Cannot load mysql configuration')); return false; } if (!extension_loaded('mysql')) { print(('Unable to load module for database server "mysql": PHP mysql extension not available!')); return false; } $dbport = (empty($this->db_config['port'])) ? 3306 : $this->db_config['port']; $this->connection = @mysql_connect($this->db_config['server'] . ':' . $dbport, $this->db_config['username'], $this->db_config['password']); } if (empty($this->connection)) { print(('Unable to connect to database server!')); return false; } else if (!@mysql_select_db($this->db_config['db'], $this->connection)) { $this->db_error(); return false; } mysql_query("set character_set_client='" . $this->db_config['character'] . "'"); mysql_query("set character_set_results='" . $this->db_config['character'] . "'"); mysql_query("set collation_connection='" . $this->db_config['character'] . "_general_ci'"); return true; } /** * Executes query and returns result identifier * * @param string $query * @return MySQL result */ function query($query) { // use escape/vf function for input data. $result = @mysql_query($query, $this->connection) or $this->db_error(0, $query); $this->last_query_num++; return $result; } /** * Executes query and makes abstract data read available * * @param string $query * @param bool $assoc */ function ExecuteReader($query, $assoc = true) { $this->lastresult = $this->query($query); $this->assoc = $assoc; } /** * Link to query method * * @param string $query * @return MySQL result */ function ExecuteNonQuery($query) { $result = $this->query($query); return (mysql_affected_rows() == 0 ? false : $result); } /** * Returns array with from the current query result * * @return array */ function Read() { if ($this->assoc) { $result = @mysql_fetch_assoc($this->lastresult) or false; } else { $result = @mysql_fetch_row($this->lastresult) or false; } return $result; } /** * Returns one row from the current query result * * @param int $row * @return string */ function ReadSingleRow($row) { return mysql_result($this->lastresult, $row) or false; } /** * Prints MySQL error message; swithing DEBUG, prints MySQL error description or sends it to administrator * */ function db_error($show = 0, $query = '') { global $system; if (!in_array(mysql_errno(), array(1062, 1065, 1191))) { // Errcodes in array are handled at another way :) if (DEBUG == 1 || $show == 1) { $warning = '<br><b>' . ('MySQL Error') . ':</b><br><i>'; $warning.=mysql_errno() . ' : ' . mysql_error() . (empty($query) ? '</i>' : '<br>In query: <textarea cols="50" rows="7">' . $query . '</textarea></i>'); print($warning) or print($warning); } else { print('An error occured. Please, try again later. Thank You !'); @$message.=mysql_errno() . ':' . mysql_error() . "\r\n"; $message.=(empty($query) ? '' : "In query: \r\n" . $query . "\r\n"); die('MySQL error ' . $message); } } } /** * Escapes string to use in SQL query * * @param string $string * @return string */ function escape($string) { if (!get_magic_quotes_gpc()) return mysql_real_escape_string($string, $this->connection); else return mysql_real_escape_string(stripslashes($string), $this->connection); } /** * Disconnects from database server * */ function disconnect() { @mysql_close($this->connection); } } /** * Executing query and returns result as array * * @global int $query_counter * @param string $query * @return array */ function simple_queryall($query) { global $query_counter; if (DEBUG) { print ($query . "\n"); } $result = ''; $queried = mysql_query($query) or die('wrong data input: ' . $query); while ($row = mysql_fetch_assoc($queried)) { $result[] = $row; } $query_counter++; return($result); } /** * Executing query and returns array of first result * * @global int $query_counter * @param string $query * @return array */ function simple_query($query) { global $query_counter; if (DEBUG) { print ($query . "\n"); } $queried = mysql_query($query) or die('wrong data input: ' . $query); $result = mysql_fetch_assoc($queried); $query_counter++; return($result); } /** * Updates single field in table with where expression * * @param string $tablename * @param string $field * @param string $value * @param string $where * @param bool $NoQuotesAroundValue */ function simple_update_field($tablename, $field, $value, $where = '', $NoQuotesAroundValue = false) { $tablename = mysql_real_escape_string($tablename); $value = mysql_real_escape_string($value); $field = mysql_real_escape_string($field); if ($NoQuotesAroundValue) { $query = "UPDATE `" . $tablename . "` SET `" . $field . "` = " . $value . " " . $where . ""; } else { $query = "UPDATE `" . $tablename . "` SET `" . $field . "` = '" . $value . "' " . $where . ""; } nr_query($query); } /** * Returns last used `id` field available in some table * * @param string $tablename * @return int */ function simple_get_lastid($tablename) { $tablename = mysql_real_escape_string($tablename); $query = "SELECT `id` from `" . $tablename . "` ORDER BY `id` DESC LIMIT 1"; $result = simple_query($query); return ($result['id']); } /** * Just executing single query * * @global int $query_counter * @param string $query * @return mixed */ function nr_query($query) { global $query_counter; if (DEBUG) { print ($query . "\n"); } $queried = mysql_query($query) or die('wrong data input: ' . $query); $query_counter++; return($queried); } //creating mysql connection object instance $db = new MySQLDB(); } /** * Returns cutted down data entry * Available modes: * 1 - digits, letters * 2 - only letters * 3 - only digits * 4 - digits, letters, "-", "_", "." * 5 - current lang alphabet + digits + punctuation * default - filter only blacklist chars * * @param string $data * @param int $mode * @return string */ function vf($data, $mode = 0) { switch ($mode) { case 1: return preg_replace("#[^a-z0-9A-Z]#Uis", '', $data); // digits, letters break; case 2: return preg_replace("#[^a-zA-Z]#Uis", '', $data); // letters break; case 3: return preg_replace("#[^0-9]#Uis", '', $data); // digits break; case 4: return preg_replace("#[^a-z0-9A-Z\-_\.]#Uis", '', $data); // digits, letters, "-", "_", "." break; case 5: return preg_replace("#[^ [:punct:]" . ('a-zA-Z') . "0-9]#Uis", '', $data); // current lang alphabet + digits + punctuation break; default: return preg_replace("#[~@\+\?\%\/\;=\*\>\<\"\'\-]#Uis", '', $data); // black list anyway break; } } ?>
nightflyza/Ubilling
docs/signup2/modules/engine/api.mysql.php
PHP
gpl-2.0
14,501
/*************************************************************************** qgsnewnamedialog.cpp ------------------- begin : May, 2015 copyright : (C) 2015 Radim Blazek email : radim.blazek@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QRegExpValidator> #include <QSizePolicy> #include "qgslogger.h" #include "qgsnewnamedialog.h" QgsNewNameDialog::QgsNewNameDialog( const QString& source, const QString& initial, const QStringList& extensions, const QStringList& existing, const QRegExp& regexp, Qt::CaseSensitivity cs, QWidget *parent, Qt::WindowFlags flags ) : QgsDialog( parent, flags, QDialogButtonBox::Ok | QDialogButtonBox::Cancel ) , mExiting( existing ) , mExtensions( extensions ) , mCaseSensitivity( cs ) , mNamesLabel( 0 ) , mRegexp( regexp ) { setWindowTitle( tr( "New name" ) ); QDialog::layout()->setSizeConstraint( QLayout::SetMinimumSize ); layout()->setSizeConstraint( QLayout::SetMinimumSize ); layout()->setSpacing( 6 ); mOkString = buttonBox()->button( QDialogButtonBox::Ok )->text(); QString hintString; QString nameDesc = mExtensions.isEmpty() ? tr( "name" ) : tr( "base name" ); if ( source.isEmpty() ) { hintString = tr( "Enter new %1" ).arg( nameDesc ); } else { hintString = tr( "Enter new %1 for %2" ).arg( nameDesc ).arg( source ); } QLabel* hintLabel = new QLabel( hintString, this ); layout()->addWidget( hintLabel ); mLineEdit = new QLineEdit( initial, this ); if ( !regexp.isEmpty() ) { QRegExpValidator *validator = new QRegExpValidator( regexp, this ); mLineEdit->setValidator( validator ); } connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( nameChanged() ) ); layout()->addWidget( mLineEdit ); mNamesLabel = new QLabel( " ", this ); mNamesLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); if ( !mExtensions.isEmpty() ) { mNamesLabel->setWordWrap( true ); layout()->addWidget( mNamesLabel ); } mErrorLabel = new QLabel( " ", this ); mErrorLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); mErrorLabel->setWordWrap( true ); layout()->addWidget( mErrorLabel ); nameChanged(); } QString QgsNewNameDialog::highlightText( const QString& text ) { return "<b>" + text + "</b>"; } void QgsNewNameDialog::nameChanged() { QgsDebugMsg( "entered" ); QString namesString = tr( "Full names" ) + ": "; if ( !mExtensions.isEmpty() ) { mNamesLabel->setText( namesString ); } mErrorLabel->setText( " " ); // space to keep vertical space QPushButton* okButton = buttonBox()->button( QDialogButtonBox::Ok ); okButton->setText( mOkString ); okButton->setEnabled( true ); QString newName = name(); if ( newName.length() == 0 || ( !mRegexp.isEmpty() && !mRegexp.exactMatch( newName ) ) ) { //mErrorLabel->setText( highlightText( tr( "Enter new name" ) ); okButton->setEnabled( false ); return; } QStringList newNames = fullNames( newName, mExtensions ); if ( !mExtensions.isEmpty() ) { namesString += " " + newNames.join( ", " ); mNamesLabel->setText( namesString ); } QStringList conflicts = matching( newNames, mExiting, mCaseSensitivity ); if ( !conflicts.isEmpty() ) { mErrorLabel->setText( highlightText( tr( "%n Name(s) %1 exists", 0, conflicts.size() ).arg( conflicts.join( ", " ) ) ) ); okButton->setText( tr( "Overwrite" ) ); return; } } QString QgsNewNameDialog::name() const { return mLineEdit->text().trimmed(); } QStringList QgsNewNameDialog::fullNames( const QString& name, const QStringList& extensions ) { QStringList list; foreach ( QString ext, extensions ) { list << name + ext; } if ( list.isEmpty() ) { list << name; } return list; } QStringList QgsNewNameDialog::matching( const QStringList& newNames, const QStringList& existingNames, Qt::CaseSensitivity cs ) { QStringList list; foreach ( QString newName, newNames ) { foreach ( QString existingName, existingNames ) { if ( existingName.compare( newName, cs ) == 0 ) { list << existingName; } } } return list; } bool QgsNewNameDialog::exists( const QString& name, const QStringList& extensions, const QStringList& existing, Qt::CaseSensitivity cs ) { QStringList newNames = fullNames( name, extensions ); QStringList conflicts = matching( newNames, existing, cs ); return conflicts.size() > 0; }
michaelkirk/QGIS
src/gui/qgsnewnamedialog.cpp
C++
gpl-2.0
5,422
<?php /** * Download a package by passing in its location * * @var modX $this->modx * * @package modx * @subpackage processors.workspace.packages.rest */ class modPackageDownloadProcessor extends modProcessor { /** @var modTransportProvider $provider */ public $provider; /** @var string $location The actual file location of the download */ public $location; /** @var string $signature The signature of the transport package */ public $signature; /** @var modTransportPackage $package */ public $package; /** * Ensure user has access to do this * * {@inheritDoc} * @return boolean */ public function checkPermissions() { return $this->modx->hasPermission('packages'); } /** * The language topics to load * * {@inheritDoc} * @return array */ public function getLanguageTopics() { return array('workspace'); } /** * Ensure the info was properly passed and initialize the processor * * {@inheritDoc} * @return boolean */ public function initialize() { @set_time_limit(0); $info = $this->getProperty('info',''); if (empty($info)) return $this->modx->lexicon('package_download_err_ns'); if (!$this->parseInfo($info)) { return $this->modx->lexicon('invalid_data'); } return parent::initialize(); } /** * Run the processor, downloading and transferring the package, and creating the metadata in the database * {@inheritDoc} * @return mixed */ public function process() { if (!$this->loadProvider()) { return $this->failure($this->modx->lexicon('provider_err_nf')); } $this->package = $this->provider->transfer($this->signature, null, array('location' => $this->location)); if (!$this->package) { return $this->failure($this->modx->lexicon('package_download_err_create', array('signature' => $this->signature))); } return $this->success('', $this->package); } /** * Load the provider for the package * @return boolean */ public function loadProvider() { $provider = $this->getProperty('provider'); if (empty($provider)) { $c = $this->modx->newQuery('transport.modTransportProvider'); $c->where(array( 'name:=' => 'modxcms.com', 'OR:name:=' => 'modx.com', )); $this->provider = $this->modx->getObject('transport.modTransportProvider',$c); if (!empty($this->provider)) { $this->setProperty('provider',$this->provider->get('id')); } } else { $this->provider = $this->modx->getObject('transport.modTransportProvider',$provider); } return !empty($this->provider); } /** * Parse the information sent to the processor * @param string $info * @return boolean */ public function parseInfo($info) { $parsed = false; $parsedInfo = explode('::',$info); if (!empty($parsedInfo) && !empty($parsedInfo[1])) { $this->location = $parsedInfo[0]; $this->signature = $parsedInfo[1]; $parsed = true; } return $parsed; } } return 'modPackageDownloadProcessor';
sergeiforward/gl
core_gl_xVCs4l0eEu/model/modx/processors/workspace/packages/rest/download.class.php
PHP
gpl-2.0
3,377
make clean rm -v Makefile Makefile.inc config.log config.status src/config.h src/config.inc
Klaudit/pce
scripts/a0-clean.sh
Shell
gpl-2.0
91
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'find', 'cs', { find: 'Hledat', findOptions: 'Možnosti hledání', findWhat: 'Co hledat:', matchCase: 'Rozlišovat velikost písma', matchCyclic: 'Procházet opakovaně', matchWord: 'Pouze celá slova', notFoundMsg: 'Hledaný text nebyl nalezen.', replace: 'Nahradit', replaceAll: 'Nahradit vše', replaceSuccessMsg: '%1 nahrazení.', replaceWith: 'Čím nahradit:', title: 'Najít a nahradit' } );
shophelfer/shophelfer.com-shop
admin/includes/modules/ckeditor/plugins/find/lang/cs.js
JavaScript
gpl-2.0
581
/* about */ body#about label, body#about input[type='radio']{ display: inline; float: none; }
mambax7/257
htdocs/modules/about/assets/css/admin_style.css
CSS
gpl-2.0
102
//>>built define("dojox/editor/plugins/nls/zh-tw/SafePaste",({"instructions":"已停用直接貼上。請使用標準瀏覽器鍵盤或功能表貼上控制項,在這個對話框中貼上內容。當您滿意要插入的內容之後,請按貼上按鈕。若要中斷插入內容,請按取消按鈕。"}));
hariomkumarmth/champaranexpress
wp-content/plugins/dojo/dojox/editor/plugins/nls/zh-tw/SafePaste.js
JavaScript
gpl-2.0
314
{extends} {#language.function.extends} ========= `{extends}` tags are used in child templates in template inheritance for extending parent templates. For details see section of [Template Interitance](#advanced.features.template.inheritance). - The `{extends}` tag must be on the first line of the template. - If a child template extends a parent template with the `{extends}` tag it may contain only `{block}` tags. Any other template content is ignored. - Use the syntax for [template resources](#resources) to extend files outside of the [`$template_dir`](#variable.template.dir) directory. > **Note** > > When extending a variable parent like `{extends file=$parent_file}`, > make sure you include `$parent_file` in the > [`$compile_id`](#variable.compile.id). Otherwise Smarty cannot > distinguish between different `$parent_file`s. **Attributes:** Attribute Name Type Required Default Description ---------------- -------- ---------- --------- ------------------------------------------------- file string Yes *n/a* The name of the template file which is extended {extends file='parent.tpl'} {extends 'parent.tpl'} {* short-hand *} See also [Template Interitance](#advanced.features.template.inheritance) and [`{block}`](#language.function.block).
Admidio/admidio
adm_program/libs/server/smarty/smarty/docs/designers/language-builtin-functions/language-function-extends.md
Markdown
gpl-2.0
1,339
/* * * Copyright (C) 2009 Texas Instruments Inc * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/cdev.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/uaccess.h> #include <linux/platform_device.h> #include <linux/major.h> #include <media/davinci/dm365_a3_hw.h> #include <media/davinci/vpss.h> /* Global structure */ static struct class *aew_class; struct aew_device *aew_dev_configptr; struct device *aewdev; /* device structure to make entry in device*/ static dev_t dev; /* For registeration of charatcer device*/ static struct cdev c_dev; int aew_validate_parameters(void) { int result = 0; /* Check horizontal Count */ if ((aew_dev_configptr->config->window_config.hz_cnt < AEW_WINDOW_HORIZONTAL_COUNT_MIN) || (aew_dev_configptr->config->window_config.hz_cnt > AEW_WINDOW_HORIZONTAL_COUNT_MAX)) { dev_err(aewdev, "\n Horizontal Count is incorrect"); result = -EINVAL; } /* Check Vertical Count */ if ((aew_dev_configptr->config->window_config.vt_cnt < AEW_WINDOW_VERTICAL_COUNT_MIN) || (aew_dev_configptr->config->window_config.vt_cnt > AEW_WINDOW_VERTICAL_COUNT_MAX)) { dev_err(aewdev, "\n Vertical Count is incorrect"); result = -EINVAL; } /* Check line increment */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config. hz_line_incr)) || (aew_dev_configptr->config->window_config.hz_line_incr < AEW_HZ_LINEINCR_MIN) || (aew_dev_configptr->config->window_config.hz_line_incr > AEW_HZ_LINEINCR_MAX)) { dev_err(aewdev, "\n Invalid Parameters"); dev_err(aewdev, "\n Horizontal Line Increment is incorrect"); result = -EINVAL; } /* Check line increment */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config. vt_line_incr)) || (aew_dev_configptr->config->window_config.vt_line_incr < AEW_VT_LINEINCR_MIN) || (aew_dev_configptr->config->window_config.vt_line_incr > AEW_VT_LINEINCR_MAX)) { dev_err(aewdev, "\n Invalid Parameters"); dev_err(aewdev, "\n Vertical Line Increment is incorrect"); result = -EINVAL; } /* Check width */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config.width)) || (aew_dev_configptr->config->window_config.width < AEW_WIDTH_MIN) || (aew_dev_configptr->config->window_config.width > AEW_WIDTH_MAX)) { dev_err(aewdev, "\n Width is incorrect"); result = -EINVAL; } /* Check Height */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config.height)) || (aew_dev_configptr->config->window_config.height < AEW_HEIGHT_MIN) || (aew_dev_configptr->config->window_config.height > AEW_HEIGHT_MAX)) { dev_err(aewdev, "\n height incorrect"); result = -EINVAL; } /* Check Horizontal Start */ if ((aew_dev_configptr->config->window_config.hz_start < AEW_HZSTART_MIN) || (aew_dev_configptr->config->window_config.hz_start > AEW_HZSTART_MAX)) { dev_err(aewdev, "\n horizontal start is incorrect"); result = -EINVAL; } if ((aew_dev_configptr->config->window_config.vt_start > AEW_VTSTART_MAX)) { dev_err(aewdev, "\n Vertical start is incorrect"); result = -EINVAL; } if ((aew_dev_configptr->config->alaw_enable > H3A_AEW_ENABLE) || (aew_dev_configptr->config->alaw_enable < H3A_AEW_DISABLE)) { dev_err(aewdev, "\n A Law setting is incorrect"); result = -EINVAL; } if (aew_dev_configptr->config->saturation_limit > AEW_AVELMT_MAX) { dev_err(aewdev, "\n Saturation Limit is incorrect"); result = -EINVAL; } /* Check Black Window Height */ if (NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->blackwindow_config.height) || (aew_dev_configptr->config->blackwindow_config.height < AEW_BLKWINHEIGHT_MIN) || (aew_dev_configptr->config->blackwindow_config.height > AEW_BLKWINHEIGHT_MAX)) { dev_err(aewdev, "\n Black Window height incorrect"); result = -EINVAL; } /* Check Black Window Height */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->blackwindow_config. height)) || (aew_dev_configptr->config->blackwindow_config.vt_start < AEW_BLKWINVTSTART_MIN) || (aew_dev_configptr->config->blackwindow_config.vt_start > AEW_BLKWINVTSTART_MAX)) { dev_err(aewdev, "\n Black Window vertical Start is incorrect"); result = -EINVAL; } if (aew_dev_configptr->config->out_format < AEW_OUT_SUM_OF_SQUARES || aew_dev_configptr->config->out_format > AEW_OUT_SUM_ONLY) { dev_err(aewdev, "\n Invalid out_format"); result = -EINVAL; } if (aew_dev_configptr->config->sum_shift > AEW_SUMSHIFT_MAX) { dev_err(aewdev, "\n sum_shift param is invalid, max = %d", AEW_SUMSHIFT_MAX); result = -EINVAL; } return result; } /* inline function to free reserver pages */ inline void aew_free_pages(unsigned long addr, unsigned long bufsize) { unsigned long tempaddr; unsigned long size; tempaddr = addr; if (!addr) return; size = PAGE_SIZE << (get_order(bufsize)); while (size > 0) { ClearPageReserved(virt_to_page(addr)); addr += PAGE_SIZE; size -= PAGE_SIZE; } free_pages(tempaddr, get_order(bufsize)); } /* Function to perform hardware Configuration */ int aew_hardware_setup(void) { int result; /* Size for buffer in bytes */ int buff_size = 0; unsigned long adr; unsigned long size; unsigned int busyaew; /* Get the value of PCR register */ busyaew = aew_get_hw_state(); /* If H3A Engine is busy then return */ if (busyaew == 1) { dev_err(aewdev, "\n Error : AEW Engine is busy"); return -EBUSY; } result = aew_validate_parameters(); dev_dbg(aewdev, "Result = %d\n", result); if (result < 0) { dev_err(aewdev, "Error : Parameters are incorrect \n"); return result; } /* Deallocate the previously allocated buffers */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr->buff_old, aew_dev_configptr->size_window); if (aew_dev_configptr->buff_curr) aew_free_pages((unsigned long)aew_dev_configptr-> buff_curr, aew_dev_configptr->size_window); if (aew_dev_configptr->buff_app) aew_free_pages((unsigned long)aew_dev_configptr-> buff_app, aew_dev_configptr->size_window); /* * Allocat the buffers as per the new buffer size * Allocate memory for old buffer */ if (aew_dev_configptr->config->out_format == AEW_OUT_SUM_ONLY) buff_size = (aew_dev_configptr->config->window_config.hz_cnt) * (aew_dev_configptr->config->window_config.vt_cnt) * AEW_WINDOW_SIZE_SUM_ONLY; else buff_size = (aew_dev_configptr->config->window_config.hz_cnt) * (aew_dev_configptr->config->window_config.vt_cnt) * AEW_WINDOW_SIZE; aew_dev_configptr->buff_old = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, get_order(buff_size)); if (aew_dev_configptr->buff_old == NULL) return -ENOMEM; /* Make pges reserved so that they will be swapped out */ adr = (unsigned long)aew_dev_configptr->buff_old; size = PAGE_SIZE << (get_order(buff_size)); while (size > 0) { /* * make sure the frame buffers * are never swapped out of memory */ SetPageReserved(virt_to_page(adr)); adr += PAGE_SIZE; size -= PAGE_SIZE; } /* Allocate memory for current buffer */ aew_dev_configptr->buff_curr = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, get_order(buff_size)); if (aew_dev_configptr->buff_curr == NULL) { /*Free all buffer that are allocated */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr-> buff_old, buff_size); return -ENOMEM; } /* Make pges reserved so that they will be swapped out */ adr = (unsigned long)aew_dev_configptr->buff_curr; size = PAGE_SIZE << (get_order(buff_size)); while (size > 0) { /* * make sure the frame buffers * are never swapped out of memory */ SetPageReserved(virt_to_page(adr)); adr += PAGE_SIZE; size -= PAGE_SIZE; } /* Allocate memory for application buffer */ aew_dev_configptr->buff_app = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, get_order(buff_size)); if (aew_dev_configptr->buff_app == NULL) { /* Free all buffer that were allocated previously */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr-> buff_old, buff_size); if (aew_dev_configptr->buff_curr) aew_free_pages((unsigned long)aew_dev_configptr-> buff_curr, buff_size); return -ENOMEM; } /* Make pages reserved so that they will be swapped out */ adr = (unsigned long)aew_dev_configptr->buff_app; size = PAGE_SIZE << (get_order(buff_size)); while (size > 0) { /* * make sure the frame buffers * are never swapped out of memory */ SetPageReserved(virt_to_page(adr)); adr += PAGE_SIZE; size -= PAGE_SIZE; } /* Set the registers */ aew_register_setup(aewdev, aew_dev_configptr); aew_dev_configptr->size_window = buff_size; aew_dev_configptr->aew_config = H3A_AEW_CONFIG; return 0; } /* This Function is called when driver is opened */ static int aew_open(struct inode *inode, struct file *filp) { /* Return if Device is in use (Single Channel Support is provided) */ if (aew_dev_configptr->in_use == AEW_IN_USE) return -EBUSY; /* Set the aew_dev_configptr structure */ aew_dev_configptr->config = NULL; /* Allocate memory for configuration structure of this channel */ aew_dev_configptr->config = (struct aew_configuration *) kmalloc(sizeof(struct aew_configuration), GFP_KERNEL); if (aew_dev_configptr->config == NULL) { dev_err(aewdev, "Error : Kmalloc fail\n"); return -ENOMEM; } /* Initiaze the wait queue */ init_waitqueue_head(&(aew_dev_configptr->aew_wait_queue)); /* Device is in use */ aew_dev_configptr->in_use = AEW_IN_USE; /* No Hardware Set up done */ aew_dev_configptr->aew_config = H3A_AEW_CONFIG_NOT_DONE; /* No statistics are available */ aew_dev_configptr->buffer_filled = 0; /* Set Window Size to 0 */ aew_dev_configptr->size_window = 0; /* Initialize the mutex */ mutex_init(&(aew_dev_configptr->read_blocked)); return 0; } static void aew_platform_release(struct device *device) { /* This is called when the reference count goes to zero */ } static int aew_probe(struct device *device) { aewdev = device; return 0; } static int aew_remove(struct device *device) { return 0; } /* This Function is called when driver is closed */ static int aew_release(struct inode *inode, struct file *filp) { aew_engine_setup(aewdev, 0); /* The Application has closed device so device is not in use */ aew_dev_configptr->in_use = AEW_NOT_IN_USE; /* Release memory for configuration structure of this channel */ kfree(aew_dev_configptr->config); /* Free Old Buffer */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr->buff_old, aew_dev_configptr->size_window); /* Free Current Buffer */ if (aew_dev_configptr->buff_curr) aew_free_pages((unsigned long)aew_dev_configptr-> buff_curr, aew_dev_configptr->size_window); /* Free Application Buffer */ if (aew_dev_configptr->buff_app) aew_free_pages((unsigned long)aew_dev_configptr->buff_app, aew_dev_configptr->size_window); aew_dev_configptr->buff_old = NULL; aew_dev_configptr->buff_curr = NULL; aew_dev_configptr->config = NULL; aew_dev_configptr->buff_app = NULL; return 0; } /* * This function will process IOCTL commands sent by the application and * control the devices IO operations. */ static int aew_ioctl(struct inode *inode, struct file *filep, unsigned int cmd, unsigned long arg) { /* Stores Previous Configurations */ struct aew_configuration aewconfig = *(aew_dev_configptr->config); int result = 0; /* Decrement the semaphore */ result = mutex_lock_interruptible(&aew_dev_configptr->read_blocked); if (result) return result; /* * Extract the type and number bitfields, and don't decode wrong cmds: * verify the magic number */ if (_IOC_TYPE(cmd) != AEW_MAGIC_NO) { mutex_unlock(&aew_dev_configptr->read_blocked); return -ENOTTY; } /* verify the command number */ if (_IOC_NR(cmd) > AEW_IOC_MAXNR) { /* Release mutex in case of fault */ mutex_unlock(&aew_dev_configptr->read_blocked); return -ENOTTY; } /* check for the permission of the operation */ if (_IOC_DIR(cmd) & _IOC_READ) result = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) result = !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd)); if (result) { /* Release mutex in case of fault */ mutex_unlock(&aew_dev_configptr->read_blocked); return -EFAULT; } /* Switch according to IOCTL command */ switch (cmd) { /* * This ioctl is used to perform hardware set up * and will set all the registers for AF engine */ case AEW_S_PARAM: /* Copy config structure passed by user */ if (copy_from_user(aew_dev_configptr->config, (struct aew_configuration *)arg, sizeof(struct aew_configuration))) { *(aew_dev_configptr->config) = aewconfig; mutex_unlock(&aew_dev_configptr->read_blocked); return -EFAULT; } /* Call aew_hardware_setup to perform register configuration */ result = aew_hardware_setup(); if (!result) { /* * Hardware Set up is successful * Return the no of bytes required for buffer */ result = aew_dev_configptr->size_window; } else { /* Change Configuration Structure to original */ *(aew_dev_configptr->config) = aewconfig; dev_err(aewdev, "Error : AEW_S_PARAM failed\n"); } break; /* This ioctl is used to return parameters in user space */ case AEW_G_PARAM: if (aew_dev_configptr->aew_config == H3A_AEW_CONFIG) { if (copy_to_user ((struct aew_configuration *)arg, aew_dev_configptr->config, sizeof(struct aew_configuration))) { mutex_unlock(&aew_dev_configptr->read_blocked); return -EFAULT; } else result = aew_dev_configptr->size_window; } else { dev_err(aewdev, "Error : AEW Hardware is not configured.\n"); result = -EINVAL; } break; /* This ioctl is used to enable AEW Engine */ case AEW_ENABLE: /* Enable AEW Engine if Hardware set up is done */ if (aew_dev_configptr->aew_config == H3A_AEW_CONFIG_NOT_DONE) { dev_err(aewdev, "Error : AEW Hardware is not configured.\n"); result = -EINVAL; } else /* Enable AF Engine */ aew_engine_setup(aewdev, 1); break; /* This ioctl is used to disable AEW Engine */ case AEW_DISABLE: /* Disable AEW Engine */ aew_engine_setup(aewdev, 0); break; /* Invalid Command */ default: dev_err(aewdev, "Error: It should not come here!!\n"); result = -ENOTTY; break; } /* Release the mutex */ mutex_unlock(&aew_dev_configptr->read_blocked); return result; } /* This function will return statistics to user */ static ssize_t aew_read(struct file *filep, char *kbuff, size_t size, loff_t *offset) { void *buffer_temp; int result = 0; int ret; /* Semaphore will return immediately if read call is busy */ ret = mutex_trylock(&(aew_dev_configptr->read_blocked)); if (!ret) { dev_dbg(aewdev, "Read Call : busy : %d\n", ret); return -EBUSY; } /* First Check the size given by user */ if (size < aew_dev_configptr->size_window) { /* * Return Failure to applicaiton * if size is less than required size */ dev_dbg(aewdev, "Error : Invalid size of buffer\n"); mutex_unlock(&(aew_dev_configptr->read_blocked)); return -EINVAL; } /* * The value of buffer_filled flag determines * the status of statistics */ if (aew_dev_configptr->buffer_filled == 0) { /* Decrement the semaphore */ dev_dbg(aewdev, "READ CALL IS BLOCKED............\n"); /* Block the read call */ wait_event_interruptible_timeout(aew_dev_configptr-> aew_wait_queue, aew_dev_configptr-> buffer_filled, AEW_TIMEOUT); dev_dbg(aewdev, "Read Call is unbloked and waking up.......\n"); dev_dbg(aewdev, "Buffer Filled.... %d\n", aew_dev_configptr->buffer_filled); } if (aew_dev_configptr->buffer_filled == 1) { /* Disable the interrupts and then swap the buffers */ dev_dbg(aewdev, "READING............\n"); disable_irq(6); /* New Statistics are availaible */ aew_dev_configptr->buffer_filled = 0; /* Swap application buffer and old buffer */ buffer_temp = aew_dev_configptr->buff_old; aew_dev_configptr->buff_old = aew_dev_configptr->buff_app; aew_dev_configptr->buff_app = buffer_temp; /* Interrupts are enabled */ enable_irq(6); /* * Copy the entire statistics located in application * buffer to user space */ if (copy_to_user(kbuff, aew_dev_configptr->buff_app, aew_dev_configptr->size_window)) { dev_err(aewdev, "Error : Read Fault\n"); mutex_unlock(&(aew_dev_configptr->read_blocked)); return -EFAULT; } else result = aew_dev_configptr->size_window; dev_dbg(aewdev, "Reading Done........................\n"); } dev_dbg(aewdev, "APP BUFF VALUE %x\n", (*((unsigned int *)(aew_dev_configptr->buff_app)))); /* release the mutex */ mutex_unlock(&(aew_dev_configptr->read_blocked)); return result; } /* This function will handle interrupt generated by H3A Engine. */ static irqreturn_t aew_isr(int irq, void *dev_id) { /* EN AF Bit */ unsigned int enaew; /* Temporary Buffer for Swapping */ void *buffer_temp; /* Get the value of PCR register */ enaew = aew_get_enable(); /* If AEW engine is not enabled, interrupt is not for AEW */ if (!enaew) return IRQ_RETVAL(IRQ_NONE); /* * Interrupt is generated by AEW, so Service the Interrupt * Swap current buffer and old buffer */ if (aew_dev_configptr) { buffer_temp = aew_dev_configptr->buff_curr; aew_dev_configptr->buff_curr = aew_dev_configptr->buff_old; aew_dev_configptr->buff_old = buffer_temp; /* Set the AEWBUFSTAT REgister to current buffer Address */ aew_set_address(aewdev, (unsigned long)(virt_to_phys(aew_dev_configptr->buff_curr))); /* * Set buffer filled flag to indicate statistics are available */ aew_dev_configptr->buffer_filled = 1; /* new statistics are available. Wake up the read call */ wake_up(&(aew_dev_configptr->aew_wait_queue)); return IRQ_RETVAL(IRQ_HANDLED); } return IRQ_RETVAL(IRQ_NONE); } /* file Operation Structure*/ static const struct file_operations aew_fops = { .owner = THIS_MODULE, .open = aew_open, .read = aew_read, .ioctl = aew_ioctl, .release = aew_release, }; static struct platform_device aewdevice = { .name = "dm365_aew", .id = 2, .dev = { .release = aew_platform_release, } }; static struct device_driver aew_driver = { .name = "dm365_aew", .bus = &platform_bus_type, .probe = aew_probe, .remove = aew_remove, }; #define DRIVERNAME "DM365AEW" /* Function to register the AF character device driver. */ int __init aew_init(void) { int err; int result = 0; /* * Register the driver in the kernel * dynmically get the major number for the driver using * alloc_chrdev_region function */ result = alloc_chrdev_region(&dev, 0, 1, DRIVERNAME); if (result < 0) { printk(KERN_ERR "Error : Could not register character device"); return -ENODEV; } printk(KERN_INFO "aew major#: %d, minor# %d\n", MAJOR(dev), MINOR(dev)); /* allocate memory for device structure and initialize it with 0 */ aew_dev_configptr = kmalloc(sizeof(struct aew_device), GFP_KERNEL); if (!aew_dev_configptr) { printk(KERN_ERR "Error : kmalloc fail"); unregister_chrdev_region(dev, AEW_NR_DEVS); return -ENOMEM; } /* Initialize character device */ cdev_init(&c_dev, &aew_fops); c_dev.owner = THIS_MODULE; c_dev.ops = &aew_fops; err = cdev_add(&c_dev, dev, 1); if (err) { printk(KERN_ERR "Error : Error in Adding Davinci AEW"); unregister_chrdev_region(dev, AEW_NR_DEVS); kfree(aew_dev_configptr); return -err; } /* register driver as a platform driver */ if (driver_register(&aew_driver) != 0) { unregister_chrdev_region(dev, 1); cdev_del(&c_dev); return -EINVAL; } /* Register the drive as a platform device */ if (platform_device_register(&aewdevice) != 0) { driver_unregister(&aew_driver); unregister_chrdev_region(dev, 1); cdev_del(&c_dev); return -EINVAL; } aew_class = class_create(THIS_MODULE, "dm365_aew"); if (!aew_class) { printk(KERN_ERR "aew_init: error in creating device class\n"); driver_unregister(&aew_driver); platform_device_unregister(&aewdevice); unregister_chrdev_region(dev, 1); unregister_chrdev(MAJOR(dev), DRIVERNAME); cdev_del(&c_dev); return -EINVAL; } device_create(aew_class, NULL, dev, NULL, "dm365_aew"); /* Set up the Interrupt handler for H3AINT interrupt */ result = request_irq(6, aew_isr, IRQF_SHARED, "dm365_h3a_aew", (void *)aew_dev_configptr); if (result != 0) { printk(KERN_ERR "Error : Request IRQ Failed"); unregister_chrdev_region(dev, AEW_NR_DEVS); device_destroy(aew_class, dev); class_destroy(aew_class); kfree(aew_dev_configptr); driver_unregister(&aew_driver); platform_device_unregister(&aewdevice); cdev_del(&c_dev); return result; } /* Initialize device structure */ memset(aew_dev_configptr, 0, sizeof(struct aew_device)); aew_dev_configptr->in_use = AEW_NOT_IN_USE; aew_dev_configptr->buffer_filled = 0; printk(KERN_NOTICE "AEW Driver initialized\n"); return 0; } /* * This Function is called by the kernel while unloading the driver * This will unregister the Character Device Driver */ void __exit aew_cleanup(void) { /* Device is in use */ if (aew_dev_configptr->in_use == AEW_IN_USE) { printk(KERN_ERR "Error : Driver in use"); return; } free_irq(6, aew_dev_configptr); /* Free device structure */ kfree(aew_dev_configptr); aew_dev_configptr = NULL; unregister_chrdev_region(dev, AEW_NR_DEVS); driver_unregister(&aew_driver); device_destroy(aew_class, dev); class_destroy(aew_class); platform_device_unregister(&aewdevice); cdev_del(&c_dev); /* unregistering the driver from the kernel */ unregister_chrdev(MAJOR(dev), DRIVERNAME); } module_init(aew_init) module_exit(aew_cleanup) MODULE_LICENSE("GPL");
merlinholland/kernel
drivers/media/video/davinci/dm365_aew.c
C
gpl-2.0
22,941
// This file has been generated by the GUI designer. Do not modify. namespace Smuxi.Frontend.Gnome { public partial class EngineAssistantNameWidget { private global::Gtk.VBox vbox2; private global::Gtk.VBox vbox3; private global::Gtk.Label f_EngineNameLabel; private global::Gtk.Entry f_EngineNameEntry; private global::Gtk.Label label2; private global::Gtk.VBox vbox4; private global::Gtk.Label label7; private global::Gtk.CheckButton f_MakeDefaultEngineCheckButton; private global::Gtk.Label label8; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget Smuxi.Frontend.Gnome.EngineAssistantNameWidget global::Stetic.BinContainer.Attach (this); this.Name = "Smuxi.Frontend.Gnome.EngineAssistantNameWidget"; // Container child Smuxi.Frontend.Gnome.EngineAssistantNameWidget.Gtk.Container+ContainerChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 10; this.vbox2.BorderWidth = ((uint)(5)); // Container child vbox2.Gtk.Box+BoxChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.f_EngineNameLabel = new global::Gtk.Label (); this.f_EngineNameLabel.Name = "f_EngineNameLabel"; this.f_EngineNameLabel.Xalign = 0f; this.f_EngineNameLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("_Engine Name:"); this.f_EngineNameLabel.UseUnderline = true; this.vbox3.Add (this.f_EngineNameLabel); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.f_EngineNameLabel])); w1.Position = 0; w1.Expand = false; w1.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.f_EngineNameEntry = new global::Gtk.Entry (); this.f_EngineNameEntry.CanFocus = true; this.f_EngineNameEntry.Name = "f_EngineNameEntry"; this.f_EngineNameEntry.IsEditable = true; this.f_EngineNameEntry.InvisibleChar = '●'; this.vbox3.Add (this.f_EngineNameEntry); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.f_EngineNameEntry])); w2.Position = 1; w2.Expand = false; w2.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.Xpad = 50; this.label2.Xalign = 0f; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size=\"small\">Profile name of the new engine</span>"); this.label2.UseMarkup = true; this.vbox3.Add (this.label2); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label2])); w3.Position = 2; w3.Expand = false; w3.Fill = false; this.vbox2.Add (this.vbox3); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.vbox3])); w4.Position = 0; w4.Expand = false; w4.Fill = false; // Container child vbox2.Gtk.Box+BoxChild this.vbox4 = new global::Gtk.VBox (); this.vbox4.Name = "vbox4"; this.vbox4.Spacing = 6; this.vbox4.BorderWidth = ((uint)(5)); // Container child vbox4.Gtk.Box+BoxChild this.label7 = new global::Gtk.Label (); this.label7.Name = "label7"; this.label7.Xalign = 0f; this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("_Default Engine:"); this.label7.UseUnderline = true; this.vbox4.Add (this.label7); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label7])); w5.Position = 0; w5.Expand = false; w5.Fill = false; // Container child vbox4.Gtk.Box+BoxChild this.f_MakeDefaultEngineCheckButton = new global::Gtk.CheckButton (); this.f_MakeDefaultEngineCheckButton.CanFocus = true; this.f_MakeDefaultEngineCheckButton.Name = "f_MakeDefaultEngineCheckButton"; this.f_MakeDefaultEngineCheckButton.Label = global::Mono.Unix.Catalog.GetString ("Use as new default engine"); this.f_MakeDefaultEngineCheckButton.DrawIndicator = true; this.f_MakeDefaultEngineCheckButton.UseUnderline = true; this.vbox4.Add (this.f_MakeDefaultEngineCheckButton); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.f_MakeDefaultEngineCheckButton])); w6.Position = 1; w6.Expand = false; w6.Fill = false; // Container child vbox4.Gtk.Box+BoxChild this.label8 = new global::Gtk.Label (); this.label8.Name = "label8"; this.label8.Xpad = 50; this.label8.Xalign = 0f; this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size=\"small\">If enabled, the current engine will be the default next time Smuxi is started</span>"); this.label8.UseMarkup = true; this.label8.Wrap = true; this.vbox4.Add (this.label8); global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label8])); w7.Position = 2; w7.Expand = false; w7.Fill = false; this.vbox2.Add (this.vbox4); global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.vbox4])); w8.Position = 1; w8.Expand = false; w8.Fill = false; this.Add (this.vbox2); if ((this.Child != null)) { this.Child.ShowAll (); } this.f_EngineNameLabel.MnemonicWidget = this.f_EngineNameEntry; this.label7.MnemonicWidget = this.f_MakeDefaultEngineCheckButton; this.Hide (); } } }
tuukka/smuxi
src/Frontend-GNOME/gtk-gui/Smuxi.Frontend.Gnome.EngineAssistantNameWidget.cs
C#
gpl-2.0
5,273
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.threshd; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.xml.event.Event; import org.springframework.util.Assert; /** * Implements a relative change threshold check. A 'value' setting of * less than 1.0 means that a threshold will fire if the current value * is less than or equal to the previous value multiplied by the 'value' * setting. A 'value' setting greater than 1.0 causes the threshold to * fire if the current value is greater than or equal to the previous * value multiplied by the 'value' setting. A 'value' setting of 1.0 * (unity) is not allowed, as it represents no change. Zero valued * samples (0.0) are ignored, as 0.0 multiplied by anything is 0.0 (if * they were not ignored, an interface that gets no traffic would always * trigger a threshold, for example). * * @author ranger * @version $Id: $ */ public class ThresholdEvaluatorRelativeChange implements ThresholdEvaluator { private static final String TYPE = "relativeChange"; /** {@inheritDoc} */ @Override public ThresholdEvaluatorState getThresholdEvaluatorState(BaseThresholdDefConfigWrapper threshold) { return new ThresholdEvaluatorStateRelativeChange(threshold); } /** {@inheritDoc} */ @Override public boolean supportsType(String type) { return TYPE.equals(type); } public static class ThresholdEvaluatorStateRelativeChange extends AbstractThresholdEvaluatorState { private BaseThresholdDefConfigWrapper m_thresholdConfig; private double m_multiplier; private double m_lastSample = 0.0; private double m_previousTriggeringSample; public ThresholdEvaluatorStateRelativeChange(BaseThresholdDefConfigWrapper threshold) { Assert.notNull(threshold, "threshold argument cannot be null"); setThresholdConfig(threshold); } public void setThresholdConfig(BaseThresholdDefConfigWrapper thresholdConfig) { Assert.notNull(thresholdConfig.getType(), "threshold must have a 'type' value set"); Assert.notNull(thresholdConfig.getDatasourceExpression(), "threshold must have a 'ds-name' value set"); Assert.notNull(thresholdConfig.getDsType(), "threshold must have a 'ds-type' value set"); Assert.isTrue(thresholdConfig.hasValue(), "threshold must have a 'value' value set"); Assert.isTrue(thresholdConfig.hasRearm(), "threshold must have a 'rearm' value set"); Assert.isTrue(thresholdConfig.hasTrigger(), "threshold must have a 'trigger' value set"); Assert.isTrue(TYPE.equals(thresholdConfig.getType()), "threshold for ds-name '" + thresholdConfig.getDatasourceExpression() + "' has type of '" + thresholdConfig.getType() + "', but this evaluator only supports thresholds with a 'type' value of '" + TYPE + "'"); Assert.isTrue(!Double.isNaN(thresholdConfig.getValue()), "threshold must have a 'value' value that is a number"); Assert.isTrue(thresholdConfig.getValue() != Double.POSITIVE_INFINITY && thresholdConfig.getValue() != Double.NEGATIVE_INFINITY, "threshold must have a 'value' value that is not positive or negative infinity"); Assert.isTrue(thresholdConfig.getValue() != 1.0, "threshold must not be unity (1.0)"); m_thresholdConfig = thresholdConfig; setMultiplier(thresholdConfig.getValue()); } @Override public BaseThresholdDefConfigWrapper getThresholdConfig() { return m_thresholdConfig; } @Override public Status evaluate(double dsValue) { //Fix for Bug 2275 so we handle negative numbers //It will not handle values which cross the 0 boundary (from - to +, or v.v.) properly, but // after some discussion, we can't come up with a sensible scenario when that would actually happen. // If such a scenario eventuates, reconsider dsValue=Math.abs(dsValue); if (getLastSample() != 0.0) { double threshold = getMultiplier() * getLastSample(); if (getMultiplier() < 1.0) { if (dsValue <= threshold) { setPreviousTriggeringSample(getLastSample()); setLastSample(dsValue); return Status.TRIGGERED; } } else { if (dsValue >= threshold) { setPreviousTriggeringSample(getLastSample()); setLastSample(dsValue); return Status.TRIGGERED; } } setLastSample(dsValue); } setLastSample(dsValue); return Status.NO_CHANGE; } public Double getLastSample() { return m_lastSample; } public void setLastSample(double lastSample) { m_lastSample = lastSample; } @Override public Event getEventForState(Status status, Date date, double dsValue, CollectionResourceWrapper resource) { if (status == Status.TRIGGERED) { String uei=getThresholdConfig().getTriggeredUEI(); if(uei==null || "".equals(uei)) { uei=EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI; } return createBasicEvent(uei, date, dsValue, resource); } else { return null; } } private Event createBasicEvent(String uei, Date date, double dsValue, CollectionResourceWrapper resource) { Map<String,String> params = new HashMap<String,String>(); params.put("previousValue", formatValue(getPreviousTriggeringSample())); params.put("multiplier", Double.toString(getThresholdConfig().getValue())); // params.put("trigger", Integer.toString(getThresholdConfig().getTrigger())); // params.put("rearm", Double.toString(getThresholdConfig().getRearm())); return createBasicEvent(uei, date, dsValue, resource, params); } public double getPreviousTriggeringSample() { return m_previousTriggeringSample; } public void setPreviousTriggeringSample(double previousTriggeringSample) { m_previousTriggeringSample = previousTriggeringSample; } public double getMultiplier() { return m_multiplier; } public void setMultiplier(double multiplier) { m_multiplier = multiplier; } @Override public ThresholdEvaluatorState getCleanClone() { return new ThresholdEvaluatorStateRelativeChange(m_thresholdConfig); } // FIXME This must be implemented correctly @Override public boolean isTriggered() { return false; } // FIXME This must be implemented correctly @Override public void clearState() { } } }
rfdrake/opennms
opennms-services/src/main/java/org/opennms/netmgt/threshd/ThresholdEvaluatorRelativeChange.java
Java
gpl-2.0
8,358
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class add_o32_rAX_Id extends Executable { final int immd; public add_o32_rAX_Id(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); immd = Modrm.Id(input); } public Branch execute(Processor cpu) { cpu.flagOp1 = cpu.r_eax.get32(); cpu.flagOp2 = immd; cpu.flagResult = (cpu.flagOp1 + cpu.flagOp2); cpu.r_eax.set32(cpu.flagResult); cpu.flagIns = UCodes.ADD32; cpu.flagStatus = OSZAPC; return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
ianopolous/JPC
src/org/jpc/emulator/execution/opcodes/vm/add_o32_rAX_Id.java
Java
gpl-2.0
1,923
/****************************************************************************** * Warmux is a convivial mass murder game. * Copyright (C) 2001-2011 Warmux Team. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 ****************************************************************************** * Team handling *****************************************************************************/ #include <algorithm> #include <iostream> #include <WARMUX_file_tools.h> #include <WARMUX_team_config.h> #include "character/character.h" #include "character/body_list.h" #include "game/config.h" #include "network/network.h" #include "network/randomsync.h" #include "team/team.h" #include "team/team_energy.h" #include "team/teams_list.h" #include "tool/ansi_convert.h" //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TeamsList::TeamsList(): full_list(), playing_list(), selection(), groups(), active_group(groups.end()) { LoadList(); } TeamsList::~TeamsList() { UnloadGamingData(); Clear(); for (full_iterator it = full_list.begin(); it != full_list.end(); ++it) delete (*it); full_list.clear(); groups.clear(); } //----------------------------------------------------------------------------- void TeamsList::NextTeam() { ActiveCharacter().StopPlaying(); Team* next = GetNextTeam(); SetActive(next->GetId()); next->NextCharacter(true); printf("\nPlaying character : %i %s\n", ActiveCharacter().GetCharacterIndex(), ActiveCharacter().GetName().c_str()); printf("Playing team : %i %s\n", ActiveCharacter().GetTeamIndex(), ActiveTeam().GetName().c_str()); printf("Alive characters: %i / %i\n\n", ActiveTeam().NbAliveCharacter(),ActiveTeam().GetNbCharacters()); } //----------------------------------------------------------------------------- Team* TeamsList::GetNextTeam() { // Next group GroupList::iterator git = active_group; std::vector<Team*>::iterator it; do { ++git; if (git == groups.end()) git = groups.begin(); it = git->second.active_team; do { ++it; if (it == git->second.end()) it = git->second.begin(); } while (!(*it)->NbAliveCharacter() && it != git->second.active_team); } while (git != active_group && !(*it)->NbAliveCharacter()); return (*it); } //----------------------------------------------------------------------------- Team& TeamsList::ActiveTeam() { return **(active_group->second.active_team); } //----------------------------------------------------------------------------- bool TeamsList::LoadOneTeam(const std::string &dir, const std::string &team_name) { // Skip '.', '..' and hidden files if (team_name[0] == '.' || team_name == "SVN~1") return false; // Is it a directory ? if (!DoesFolderExist(dir+team_name)) return false; // Add the team std::string real_name = ANSIToUTF8(dir, team_name); std::string error; Team *team = Team::LoadTeam(dir, real_name, error); if (team) { full_list.push_back(team); std::cout << ((1<full_list.size())?", ":" ") << real_name; std::cout.flush(); return true; } std::cerr << std::endl << Format(_("Error loading team :")) << real_name <<":"<< error << std::endl; return false; } //----------------------------------------------------------------------------- void TeamsList::LoadList() { playing_list.clear(); std::cout << "o " << _("Load teams:"); const Config * config = Config::GetInstance(); // Load Warmux teams std::string dirname = config->GetDataDir() + "team" PATH_SEPARATOR; FolderSearch *f = OpenFolder(dirname); if (f) { const char *name; bool search_file = false; while ((name = FolderSearchNext(f, search_file)) != NULL) LoadOneTeam(dirname, name); CloseFolder(f); } else { Error(Format(_("Cannot open teams directory (%s)!"), dirname.c_str())); } // Load personal teams dirname = config->GetPersonalDataDir() + "team" PATH_SEPARATOR; f = OpenFolder(dirname); if (f) { bool search_files = false; const char *name; while ((name = FolderSearchNext(f, search_files)) != NULL) LoadOneTeam(dirname, name); CloseFolder(f); } else { std::cerr << std::endl << Format(_("Cannot open personal teams directory (%s)!"), dirname.c_str()) << std::endl; } full_list.sort(compareTeams); // We need at least 2 teams if (full_list.size() < 2) Error(_("You need at least two valid teams!")); // Default selection std::list<uint> nv_selection; nv_selection.push_back(0); nv_selection.push_back(1); ChangeSelection(nv_selection); std::cout << std::endl; InitList(Config::GetInstance()->AccessTeamList()); } //----------------------------------------------------------------------------- void TeamsList::LoadGamingData(WeaponsList * weapons_list) { //std::sort(playing_list.begin(), playing_list.end(), compareTeams); // needed to fix bug #9820 iterator it=playing_list.begin(), end=playing_list.end(); // Load the data of all teams for (; it != end; ++it) { (*it)->LoadGamingData(weapons_list); } groups.clear(); for (it=playing_list.begin(); it != end; ++it) { groups[ (*it)->GetGroup() ].push_back(*it); if ((*it)->IsLocalAI()) (*it)->LoadAI(); } } void TeamsList::RandomizeFirstPlayer() { MSG_DEBUG("random.get", "TeamList::RandomizeFirstPlayer()"); int skip = RandomSync().GetInt(0, groups.size()-1); for (GroupList::iterator git = groups.begin(); git != groups.end(); ++git) { if (!(skip--)) active_group = git; TeamGroup& g = git->second; int skip2 = RandomSync().GetInt(1, g.size()); g.active_team = g.begin(); while (--skip2) g.active_team++; } } //----------------------------------------------------------------------------- void TeamsList::UnloadGamingData() { groups.clear(); // Iterate over all teams not just he playing ones // in order to unload leaver teams. full_iterator it=full_list.begin(), end = full_list.end(); // Unload the data of all teams for (; it != end; ++it) (**it).UnloadGamingData(); // Run this now as no reference from Character are left BodyList::GetRef().FreeMem(); } //----------------------------------------------------------------------------- Team *TeamsList::FindById(const std::string &id, int &pos) { full_iterator it=full_list.begin(), end = full_list.end(); int i=0; for (; it != end; ++it, ++i) { if ((*it)->GetId() == id) { pos = i; return (*it); } } pos = -1; return NULL; } //----------------------------------------------------------------------------- Team *TeamsList::FindByIndex(uint index) { if (full_list.size() < index+1) { ASSERT(false); return NULL; } full_iterator it = full_list.begin(), end = full_list.end(); uint i=0; for (; it != end; ++it, ++i) { if (i == index) return (*it); } return NULL; } //----------------------------------------------------------------------------- Team* TeamsList::FindPlayingById(const std::string &id, int &index) { iterator it = playing_list.begin(), end = playing_list.end(); index=0; for (; it != end; ++it, ++index) { if ((*it) -> GetId() == id) return *it; } index = -1; ASSERT(false); return NULL; } //----------------------------------------------------------------------------- void TeamsList::InitList(const std::list<ConfigTeam> &lst) { Clear(); std::list<ConfigTeam>::const_iterator it=lst.begin(), end=lst.end(); for (; it != end; ++it) AddTeam(*it, true, false); } //----------------------------------------------------------------------------- void TeamsList::InitEnergy() { // Looking at team with the greatest energy // (in case teams does not have same amount of character) iterator it = playing_list.begin(), end = playing_list.end(); uint max = 0; for (; it != end; ++it) { if ((**it).ReadEnergy() > max) max = (**it).ReadEnergy(); } // Init each team's energy bar it=playing_list.begin(); for (; it != end; ++it) (**it).InitEnergy(max); // Initial ranking it=playing_list.begin(); for (; it != end; ++it) { uint rank = 0; iterator it2=playing_list.begin(); for (; it2 != end; ++it2) { if (it != it2 && (**it2).ReadEnergy() > (**it).ReadEnergy()) ++rank; } (**it).energy.rank_tmp = rank; } it=playing_list.begin(); for (; it != end; ++it) { uint rank = (**it).energy.rank_tmp; iterator it2=playing_list.begin(); for (it2 = it; it2 != end; ++it2) { if (it != it2 && (**it2).ReadEnergy() == (**it).ReadEnergy()) ++rank; } (**it).energy.SetRanking(rank); } } //----------------------------------------------------------------------------- void TeamsList::RefreshEnergy() { // In the order of the priorit : // - finish current action // - change a teams energy // - change ranking // - prepare energy bar for next event iterator it=playing_list.begin(), end = playing_list.end(); energy_t status; bool waiting = true; // every energy bar are waiting for (; it != end; ++it) { if ((**it).energy.status != EnergyStatusWait) { waiting = false; break; } } // one of the energy bar is changing ? if (!waiting) { status = EnergyStatusOK; // change an energy bar value ? for (it=playing_list.begin(); it != end; ++it) { if ((**it).energy.status == EnergyStatusValueChange) { status = EnergyStatusValueChange; break; } } // change a ranking ? for (it=playing_list.begin(); it != end; ++it) { if ((**it).energy.status == EnergyStatusRankChange && ((**it).energy.IsMoving() || status == EnergyStatusOK)) { status = EnergyStatusRankChange; break; } } } else { // every energy bar are waiting // -> set state ready for a new event status = EnergyStatusOK; } // Setting event to process in every energy bar if (status != EnergyStatusOK || waiting) { it = playing_list.begin(); for (; it != end; ++it) { (**it).energy.status = status; } } // Actualisation des valeurs (pas d'actualisation de l'affichage) for (it=playing_list.begin(); it != end; ++it) { (**it).UpdateEnergyBar(); } RefreshSort(); } //----------------------------------------------------------------------------- void TeamsList::RefreshSort() { iterator it=playing_list.begin(), end = playing_list.end(); uint rank; // Find a ranking without taking acount of the equalities it = playing_list.begin(); for (; it != end; ++it) { rank = 0; iterator it2=playing_list.begin(); for (; it2 != end; ++it2) { if (it != it2 && (**it2).ReadEnergy() > (**it).ReadEnergy()) ++rank; } (**it).energy.rank_tmp = rank; } // Fix equalities it = playing_list.begin(); for (; it != end; ++it) { rank = (**it).energy.rank_tmp; iterator it2=playing_list.begin(); for (it2 = it; it2 != end; ++it2) { if (it != it2 && (**it2).ReadEnergy() == (**it).ReadEnergy()) ++rank; } (**it).energy.NewRanking(rank); } } //----------------------------------------------------------------------------- void TeamsList::ChangeSelection(const std::list<uint>& nv_selection) { selection = nv_selection; selection_iterator it=selection.begin(), end = selection.end(); playing_list.clear(); for (; it != end; ++it) playing_list.push_back(FindByIndex(*it)); } //----------------------------------------------------------------------------- bool TeamsList::IsSelected(uint index) { selection_iterator pos = std::find(selection.begin(), selection.end(), index); return pos != selection.end(); } //----------------------------------------------------------------------------- void TeamsList::AddTeam(Team* the_team, int pos, const ConfigTeam &the_team_cfg, bool is_local) { ASSERT(the_team != NULL); the_team->SetRemote(!is_local); UpdateTeam(the_team, the_team_cfg); selection.push_back(pos); playing_list.push_back(the_team); } void TeamsList::AddTeam(const ConfigTeam &the_team_cfg, bool is_local, bool generate_error) { MSG_DEBUG("team", "%s, local: %d\n", the_team_cfg.id.c_str(), is_local); int pos; Team *the_team = FindById(the_team_cfg.id, pos); if (the_team != NULL) { AddTeam(the_team, pos, the_team_cfg, is_local); } else { std::string msg = Format(_("Can't find team %s!"), the_team_cfg.id.c_str()); if (generate_error) Error (msg); else std::cout << "! " << msg << std::endl; } } //----------------------------------------------------------------------------- void TeamsList::UpdateTeam(Team* the_team, const ConfigTeam &the_team_cfg) { ASSERT(the_team); // set the player name and number of characters the_team->SetPlayerName(the_team_cfg.player_name); the_team->SetNbCharacters(the_team_cfg.nb_characters); the_team->SetAIName(the_team_cfg.ai); the_team->SetGroup(the_team_cfg.group); } Team* TeamsList::UpdateTeam(const std::string& old_team_id, const ConfigTeam &the_team_cfg) { int pos; Team *the_team = NULL; MSG_DEBUG("team", "%s/%s\n", old_team_id.c_str(), the_team_cfg.id.c_str()); if (old_team_id == the_team_cfg.id) { // this is a simple update the_team = FindById(the_team_cfg.id, pos); if (the_team) { UpdateTeam(the_team, the_team_cfg); } else { Error(Format(_("Can't find team %s!"), the_team_cfg.id.c_str())); } return the_team; } // here we are replacing a team by another one Team *the_old_team = FindById(old_team_id, pos); if (!the_old_team) { Error(Format(_("Can't find team %s!"), old_team_id.c_str())); return NULL; } the_team = FindById(the_team_cfg.id, pos); if (!the_team) { Error(Format(_("Can't find team %s!"), old_team_id.c_str())); return NULL; } bool is_local = the_old_team->IsLocal(); DelTeam(the_old_team); AddTeam(the_team, pos, the_team_cfg, is_local); return the_team; } //----------------------------------------------------------------------------- void TeamsList::DelTeam(Team* the_team) { uint pos = 0; ASSERT(the_team); MSG_DEBUG("team", "%s\n", the_team->GetId().c_str()); the_team->SetDefaultPlayingConfig(); selection_iterator it = std::find(selection.begin(), selection.end(), pos); if (it != selection.end()) selection.erase(it); iterator playing_it = std::find(playing_list.begin(), playing_list.end(), the_team); ASSERT(playing_it != playing_list.end()); if (playing_it != playing_list.end()) playing_list.erase(playing_it); } void TeamsList::DelTeam(const std::string &id) { int pos; Team *the_team = FindById(id, pos); DelTeam(the_team); } //----------------------------------------------------------------------------- void TeamsList::SetActive(const std::string &id) { for (GroupList::iterator git = groups.begin(); git != groups.end(); ++git) { for (TeamGroup::iterator it = git->second.begin(); it != git->second.end(); ++it) { if ((*it)->GetId() == id) { active_group = git; git->second.active_team = it; (*it)->PrepareTurn(); return; } } } Error(Format(_("Can't find team %s!"), id.c_str())); } Character& ActiveCharacter() { return ActiveTeam().ActiveCharacter(); } bool compareTeams(const Team *a, const Team *b) { return a->GetName() < b->GetName(); }
yeKcim/warmux
trunk/src/team/teams_list.cpp
C++
gpl-2.0
16,291
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fdiv_ST1_ST1 extends Executable { public fdiv_ST1_ST1(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(1); double freg1 = cpu.fpu.ST(1); if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1))) cpu.fpu.setInvalidOperation(); if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1)) cpu.fpu.setZeroDivide(); cpu.fpu.setST(1, freg0/freg1); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/vm/fdiv_ST1_ST1.java
Java
gpl-2.0
2,046
/* * COM1 NS16550 support * originally from linux source (arch/ppc/boot/ns16550.c) * modified to use CONFIG_SYS_ISA_MEM and new defines */ #include <config.h> #include <ns16550.h> #define LCRVAL LCR_8N1 /* 8 data, 1 stop, no parity */ #define MCRVAL (MCR_DTR | MCR_RTS) /* RTS/DTR */ #define FCRVAL (FCR_FIFO_EN | FCR_RXSR | FCR_TXSR) /* Clear & enable FIFOs */ void NS16550_init (NS16550_t com_port, int baud_divisor) { com_port->ier = 0x00; #ifdef CONFIG_OMAP com_port->mdr1 = 0x7; /* mode select reset TL16C750*/ #endif com_port->lcr = LCR_BKSE | LCRVAL; com_port->dll = 0; com_port->dlm = 0; com_port->lcr = LCRVAL; com_port->mcr = MCRVAL; com_port->fcr = FCRVAL; com_port->lcr = LCR_BKSE | LCRVAL; com_port->dll = baud_divisor & 0xff; com_port->dlm = (baud_divisor >> 8) & 0xff; com_port->lcr = LCRVAL; #if defined(CONFIG_OMAP) #if defined(CONFIG_APTIX) com_port->mdr1 = 3; /* /13 mode so Aptix 6MHz can hit 115200 */ #else com_port->mdr1 = 0; /* /16 is proper to hit 115200 with 48MHz */ #endif #endif /* CONFIG_OMAP */ } #ifndef CONFIG_NS16550_MIN_FUNCTIONS void NS16550_reinit (NS16550_t com_port, int baud_divisor) { com_port->ier = 0x00; com_port->lcr = LCR_BKSE | LCRVAL; com_port->dll = 0; com_port->dlm = 0; com_port->lcr = LCRVAL; com_port->mcr = MCRVAL; com_port->fcr = FCRVAL; com_port->lcr = LCR_BKSE; com_port->dll = baud_divisor & 0xff; com_port->dlm = (baud_divisor >> 8) & 0xff; com_port->lcr = LCRVAL; } #endif /* CONFIG_NS16550_MIN_FUNCTIONS */ void NS16550_putc (NS16550_t com_port, char c) { while ((com_port->lsr & LSR_THRE) == 0); com_port->thr = c; } #ifndef CONFIG_NS16550_MIN_FUNCTIONS char NS16550_getc (NS16550_t com_port) { while ((com_port->lsr & LSR_DR) == 0) { #ifdef CONFIG_USB_TTY extern void usbtty_poll(void); usbtty_poll(); #endif } return (com_port->rbr); } int NS16550_tstc (NS16550_t com_port) { return ((com_port->lsr & LSR_DR) != 0); } #endif /* CONFIG_NS16550_MIN_FUNCTIONS */
diverger/uboot-lpc32xx
drivers/serial/ns16550.c
C
gpl-2.0
1,977
<?php /** * Joomla! component Creative Contact Form * * @version $Id: 2012-04-05 14:30:25 svn $ * @author creative-solutions.net * @package Creative Contact Form * @subpackage com_creativecontactform * @license GNU/GPL * */ // no direct access defined('_JEXEC') or die('Restircted access'); abstract class JHtmlCreativeForm { /** * @param int $value The featured value * @param int $i * @param bool $canChange Whether the value can be changed or not * * @return string The anchor tag to toggle featured/unfeatured contacts. * @since 1.6 */ static function featured($value = 0, $i, $canChange = true) { // Array of image, task, title, action $states = array( 0 => array('disabled.png', 'creativeforms.featured', 'COM_CREATIVECONTACTFORM_UNFEATURED', 'COM_CREATIVECONTACTFORM_UNFEATURED'), 1 => array('featured.png', 'creativeforms.unfeatured', 'COM_CREATIVECONTACTFORM_FEATURED', 'COM_CREATIVECONTACTFORM_FEATURED'), ); $state = JArrayHelper::getValue($states, (int) $value, $states[1]); $html = JHtml::_('image', 'admin/'.$state[0], JText::_($state[2]), NULL, true); if ($canChange) { $html = '<a href="#" onclick="return listItemTask(\'cb'.$i.'\',\''.$state[1].'\')" title="'.JText::_($state[3]).'">' . $html .'</a>'; } return $html; } }
ankibalyan/businesssetup
administrator/components/com_creativecontactform/helpers/html/creativeform.php
PHP
gpl-2.0
1,299
/* * ProFTPD - mod_sftp RFC4716 keystore * Copyright (c) 2008-2016 TJ Saunders * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, TJ Saunders and other respective copyright holders * give permission to link this program with OpenSSL, and distribute the * resulting executable, without including the source code for OpenSSL in the * source distribution. */ #include "mod_sftp.h" #include "keys.h" #include "keystore.h" #include "crypto.h" #include "rfc4716.h" /* File-based keystore implementation */ struct filestore_key { /* Supported headers. We don't really care about the Comment header * at the moment. */ const char *subject; /* Key data */ unsigned char *key_data; uint32_t key_datalen; }; struct filestore_data { pr_fh_t *fh; const char *path; unsigned int lineno; }; static const char *trace_channel = "ssh2"; /* This getline() function is quite similar to pr_fsio_getline(), except * that it a) enforces the 72-byte max line length from RFC4716, and b) * properly handles lines ending with CR, LF, or CRLF. * * Technically it allows one more byte than necessary, since the worst case * is 74 bytes (72 + CRLF); this also means 73 + CR or 73 + LF. The extra * byte is for the terminating NUL. */ static char *filestore_getline(sftp_keystore_t *store, pool *p) { char linebuf[75], *line = "", *res; struct filestore_data *store_data = store->keystore_data; while (TRUE) { size_t linelen; pr_signals_handle(); memset(&linebuf, '\0', sizeof(linebuf)); res = pr_fsio_gets(linebuf, sizeof(linebuf) - 1, store_data->fh); if (res == NULL) { if (errno == EINTR) { continue; } pr_trace_msg(trace_channel, 10, "reached end of '%s', no matching " "key found", store_data->path); errno = EOF; return NULL; } linelen = strlen(linebuf); if (linelen >= 1) { if (linebuf[linelen - 1] == '\r' || linebuf[linelen - 1] == '\n') { char *tmp; unsigned int header_taglen, header_valuelen; int have_line_continuation = FALSE; store_data->lineno++; linebuf[linelen - 1] = '\0'; line = pstrcat(p, line, linebuf, NULL); if (line[strlen(line) - 1] == '\\') { have_line_continuation = TRUE; line[strlen(line) - 1] = '\0'; } tmp = strchr(line, ':'); if (tmp == NULL) { return line; } /* We have a header. Make sure the header tag is not longer than * the specified length of 64 bytes, and that the header value is * not longer than 1024 bytes. */ header_taglen = tmp - line; if (header_taglen > 64) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header tag too long (%u) on line %u of '%s'", header_taglen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } /* Header value starts at 2 after the ':' (one for the mandatory * space character. */ header_valuelen = strlen(line) - (header_taglen + 2); if (header_valuelen > 1024) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header value too long (%u) on line %u of '%s'", header_valuelen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } if (!have_line_continuation) { return line; } continue; } else if (linelen >= 2 && linebuf[linelen - 2] == '\r' && linebuf[linelen - 1] == '\n') { char *tmp; unsigned int header_taglen, header_valuelen; int have_line_continuation = FALSE; store_data->lineno++; linebuf[linelen - 2] = '\0'; linebuf[linelen - 1] = '\0'; line = pstrcat(p, line, linebuf, NULL); if (line[strlen(line) - 1] == '\\') { have_line_continuation = TRUE; line[strlen(line) - 1] = '\0'; } tmp = strchr(line, ':'); if (tmp == NULL) { return line; } /* We have a header. Make sure the header tag is not longer than * the specified length of 64 bytes, and that the header value is * not longer than 1024 bytes. */ header_taglen = tmp - line; if (header_taglen > 64) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header tag too long (%u) on line %u of '%s'", header_taglen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } /* Header value starts at 2 after the ':' (one for the mandatory * space character. */ header_valuelen = strlen(line) - (header_taglen + 2); if (header_valuelen > 1024) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header value too long (%u) on line %u of '%s'", header_valuelen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } if (!have_line_continuation) { return line; } continue; } else if (linelen < sizeof(linebuf)) { /* No CR or LF terminator; maybe a badly formatted file? Try to * work with the data, if we can. */ line = pstrcat(p, line, linebuf, NULL); return line; } else { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "line too long (%lu) on line %u of '%s'", (unsigned long) linelen, store_data->lineno, store_data->path); (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "Make sure that '%s' is a RFC4716 formatted key", store_data->path); errno = EINVAL; break; } } } return NULL; } static struct filestore_key *filestore_get_key(sftp_keystore_t *store, pool *p) { char *line; BIO *bio = NULL; struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; size_t begin_markerlen = 0, end_markerlen = 0; line = filestore_getline(store, p); while (line == NULL && errno == EINVAL) { line = filestore_getline(store, p); } begin_markerlen = strlen(SFTP_SSH2_PUBKEY_BEGIN_MARKER); end_markerlen = strlen(SFTP_SSH2_PUBKEY_END_MARKER); while (line) { pr_signals_handle(); if (key == NULL && strncmp(line, SFTP_SSH2_PUBKEY_BEGIN_MARKER, begin_markerlen + 1) == 0) { key = pcalloc(p, sizeof(struct filestore_key)); bio = BIO_new(BIO_s_mem()); } else if (key != NULL && strncmp(line, SFTP_SSH2_PUBKEY_END_MARKER, end_markerlen + 1) == 0) { if (bio) { BIO *b64 = NULL, *bmem = NULL; char chunk[1024], *data = NULL; int chunklen; long datalen = 0; /* Add a base64 filter BIO, and read the data out, thus base64-decoding * the key. Write the decoded data into another memory BIO. */ b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_push(b64, bio); bmem = BIO_new(BIO_s_mem()); memset(chunk, '\0', sizeof(chunk)); chunklen = BIO_read(bio, chunk, sizeof(chunk)); if (chunklen < 0 && !BIO_should_retry(bio)) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "unable to base64-decode data in '%s': %s", store_data->path, sftp_crypto_get_errors()); BIO_free_all(bio); BIO_free_all(bmem); errno = EPERM; return NULL; } while (chunklen > 0) { pr_signals_handle(); if (BIO_write(bmem, chunk, chunklen) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error writing to memory BIO: %s", sftp_crypto_get_errors()); BIO_free_all(bio); BIO_free_all(bmem); errno = EPERM; return NULL; } memset(chunk, '\0', sizeof(chunk)); chunklen = BIO_read(bio, chunk, sizeof(chunk)); } datalen = BIO_get_mem_data(bmem, &data); if (data != NULL && datalen > 0) { key->key_data = palloc(p, datalen); key->key_datalen = datalen; memcpy(key->key_data, data, datalen); } else { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error base64-decoding key data in '%s'", store_data->path); } BIO_free_all(bio); bio = NULL; BIO_free_all(bmem); } break; } else { if (key) { if (strstr(line, ": ") != NULL) { if (strncasecmp(line, "Subject: ", 9) == 0) { key->subject = pstrdup(p, line + 9); } } else { if (BIO_write(bio, line, strlen(line)) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error buffering base64 data"); } } } } line = filestore_getline(store, p); while (line == NULL && errno == EINVAL) { line = filestore_getline(store, p); } } return key; } static int filestore_verify_host_key(sftp_keystore_t *store, pool *p, const char *user, const char *host_fqdn, const char *host_user, unsigned char *key_data, uint32_t key_len) { struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; int res = -1; if (!store_data->path) { errno = EPERM; return -1; } /* XXX Note that this will scan the file from the beginning, each time. * There's room for improvement; perhaps mmap() the file into memory? */ key = filestore_get_key(store, p); while (key) { int ok; pr_signals_handle(); ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data, key->key_datalen); if (ok != TRUE) { if (ok == -1) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error comparing keys from '%s': %s", store_data->path, strerror(errno)); } } else { /* XXX Verify that the user and the host_user match?? */ res = 0; break; } key = filestore_get_key(store, p); } if (res == 0) { pr_trace_msg(trace_channel, 10, "found matching public key for host '%s' " "in '%s'", host_fqdn, store_data->path); } if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error seeking to start of '%s': %s", store_data->path, strerror(errno)); return -1; } store_data->lineno = 0; return res; } static int filestore_verify_user_key(sftp_keystore_t *store, pool *p, const char *user, unsigned char *key_data, uint32_t key_len) { struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; unsigned int count = 0; int res = -1; if (!store_data->path) { errno = EPERM; return -1; } /* XXX Note that this will scan the file from the beginning, each time. * There's room for improvement; perhaps mmap() the file into memory? */ key = filestore_get_key(store, p); while (key) { int ok; pr_signals_handle(); count++; ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data, key->key_datalen); if (ok != TRUE) { if (ok == -1) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error comparing keys from '%s': %s", store_data->path, strerror(errno)); } else { pr_trace_msg(trace_channel, 10, "failed to match key #%u from file '%s'", count, store_data->path); } } else { /* If we are configured to check for Subject headers, and if the file key * has a Subject header, and that header value does not match the * logging in user, then continue looking. */ if ((sftp_opts & SFTP_OPT_MATCH_KEY_SUBJECT) && key->subject != NULL) { if (strcmp(key->subject, user) != 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "found matching key for user '%s' in '%s', but Subject " "header ('%s') does not match, skipping key", user, store_data->path, key->subject); } else { res = 0; break; } } else { res = 0; break; } } key = filestore_get_key(store, p); } if (res == 0) { pr_trace_msg(trace_channel, 10, "found matching public key for user '%s' " "in '%s'", user, store_data->path); } if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error seeking to start of '%s': %s", store_data->path, strerror(errno)); return -1; } store_data->lineno = 0; return res; } static int filestore_close(sftp_keystore_t *store) { struct filestore_data *store_data = store->keystore_data; pr_fsio_close(store_data->fh); return 0; } static sftp_keystore_t *filestore_open(pool *parent_pool, int requested_key_type, const char *store_info, const char *user) { int xerrno; sftp_keystore_t *store; pool *filestore_pool; struct filestore_data *store_data; pr_fh_t *fh; char buf[PR_TUNABLE_PATH_MAX+1], *path; struct stat st; filestore_pool = make_sub_pool(parent_pool); pr_pool_tag(filestore_pool, "SFTP File-based Keystore Pool"); store = pcalloc(filestore_pool, sizeof(sftp_keystore_t)); store->keystore_pool = filestore_pool; /* Open the file. The given path (store_info) may need to be * interpolated. */ session.user = (char *) user; memset(buf, '\0', sizeof(buf)); switch (pr_fs_interpolate(store_info, buf, sizeof(buf)-1)) { case 1: /* Interpolate occurred; make a copy of the interpolated path. */ path = pstrdup(filestore_pool, buf); break; default: /* Otherwise, use the path as is. */ path = pstrdup(filestore_pool, store_info); break; } session.user = NULL; PRIVS_ROOT fh = pr_fsio_open(path, O_RDONLY|O_NONBLOCK); xerrno = errno; PRIVS_RELINQUISH if (fh == NULL) { destroy_pool(filestore_pool); errno = xerrno; return NULL; } if (pr_fsio_set_block(fh) < 0) { xerrno = errno; destroy_pool(filestore_pool); (void) pr_fsio_close(fh); errno = xerrno; return NULL; } /* Stat the opened file to determine the optimal buffer size for IO. */ memset(&st, 0, sizeof(st)); if (pr_fsio_fstat(fh, &st) < 0) { xerrno = errno; destroy_pool(filestore_pool); (void) pr_fsio_close(fh); errno = xerrno; return NULL; } if (S_ISDIR(st.st_mode)) { destroy_pool(filestore_pool); (void) pr_fsio_close(fh); errno = EISDIR; return NULL; } fh->fh_iosz = st.st_blksize; store_data = pcalloc(filestore_pool, sizeof(struct filestore_data)); store->keystore_data = store_data; store_data->path = path; store_data->fh = fh; store_data->lineno = 0; store->store_ktypes = requested_key_type; switch (requested_key_type) { case SFTP_SSH2_HOST_KEY_STORE: store->verify_host_key = filestore_verify_host_key; break; case SFTP_SSH2_USER_KEY_STORE: store->verify_user_key = filestore_verify_user_key; break; } store->store_close = filestore_close; return store; } int sftp_rfc4716_init(void) { sftp_keystore_register_store("file", filestore_open, SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE); return 0; } int sftp_rfc4716_free(void) { sftp_keystore_unregister_store("file", SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE); return 0; }
pghmcfc/proftpd
contrib/mod_sftp/rfc4716.c
C
gpl-2.0
16,496
<?php class FrmListEntries extends WP_Widget { function __construct() { $widget_ops = array( 'description' => __( "Display a list of Formidable entries", 'formidable') ); $this->WP_Widget('frm_list_items', __('Formidable Entries List', 'formidable'), $widget_ops); } function widget( $args, $instance ) { global $frmdb, $wpdb, $frm_entry, $frmpro_display, $frm_entry_meta; extract($args); $display = $frmpro_display->getOne($instance['display_id'], false, true); $title = apply_filters('widget_title', (empty($instance['title']) and $display) ? $display->post_title : $instance['title']); $limit = empty($instance['limit']) ? ' LIMIT 100' : " LIMIT {$instance['limit']}"; $post_id = (!$display or empty($display->frm_post_id)) ? $instance['post_id'] : $display->frm_post_id; $page_url = get_permalink($post_id); $order_by = ''; if ($display && is_numeric($display->frm_form_id) && !empty($display->frm_form_id) ) { //Set up order for Entries List Widget if ( isset($display->frm_order_by) && !empty($display->frm_order_by) ) { //Get only the first order field and order $order_field = reset($display->frm_order_by); $order = reset($display->frm_order); if ( $order_field == 'rand' ) {//If random is set, set the order to random $order_by = ' RAND()'; } else if ( is_numeric($order_field) ) {//If ordering by a field //Get all post IDs for this form $posts = $wpdb->get_results($wpdb->prepare("SELECT id, post_id FROM {$wpdb->prefix}frm_items WHERE form_id=%d and post_id>%d AND is_draft=%d", $display->frm_form_id, 1, 0)); $linked_posts = array(); foreach ( $posts as $post_meta ) { $linked_posts[$post_meta->post_id] = $post_meta->id; } //Get all field information $frm_field = new FrmField(); $o_field = $frm_field->getOne($order_field); //create query with ordered values if ( isset($o_field->field_options['post_field']) and $o_field->field_options['post_field'] ) { //if field is some type of post field if ( $o_field->field_options['post_field'] == 'post_custom' && ! empty($linked_posts) ) { //if field is custom field $query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->postmeta} pm ON pm.post_id=m.post_id AND pm.meta_key='". $o_field->field_options['custom_field']."' WHERE pm.post_id in (". implode(',', array_keys($linked_posts)).") ORDER BY CASE when pm.meta_value IS NULL THEN 1 ELSE 0 END, pm.meta_value {$order}"; } else if ( $o_field->field_options['post_field'] != 'post_category' && ! empty($linked_posts) ) {//if field is a non-category post field $query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->posts} p ON p.ID=m.post_id WHERE p.ID in (". implode(',', array_keys($linked_posts)).") ORDER BY CASE p.".$o_field->field_options['post_field']." WHEN '' THEN 1 ELSE 0 END, p.".$o_field->field_options['post_field']." {$order}"; } } else { //if field is a normal, non-post field $query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->prefix}frm_item_metas em ON em.item_id=m.id WHERE em.field_id=$o_field->id ORDER BY CASE when em.meta_value IS NULL THEN 1 ELSE 0 END, em.meta_value".($o_field->type == 'number' ? ' +0 ' : '')." {$order}"; } //Get ordered values $metas = $wpdb->get_results($query); unset($query); if (is_array($metas) and !empty($metas)){ $desc_order = ' DESC'; foreach ($metas as $meta) $order_by .= $wpdb->prepare('it.id=%d'. $desc_order.', ', $meta->id); $order_by = rtrim($order_by, ', '); } else { $order_by .= 'it.created_at '. $order; } } else if ( !empty($order_field) ) { //If ordering by created_at or updated_at $order_by = 'it.'.$order_field.' '.$order; } if ( !empty($order_by) ) { $order_by = ' ORDER BY '. $order_by; } } if (isset($instance['cat_list']) and (int)$instance['cat_list'] == 1 and is_numeric($instance['cat_id'])){ global $frm_field; if ($cat_field = $frm_field->getOne($instance['cat_id'])) $categories = maybe_unserialize($cat_field->options); } } echo $before_widget; if ( $title ) echo $before_title . $title . $after_title; echo "<ul id='frm_entry_list". (($display) ? $display->frm_form_id : '') ."'>\n"; //if Listing entries by category if ( isset($instance['cat_list']) and (int)$instance['cat_list'] == 1 and isset($categories) and is_array($categories) ) { foreach ($categories as $cat_order => $cat){ if ($cat == '') continue; echo '<li>'; if (isset($instance['cat_name']) and (int)$instance['cat_name'] == 1) echo '<a href="'. add_query_arg(array('frm_cat' => $cat_field->field_key, 'frm_cat_id' => $cat_order), $page_url) .'">'; echo $cat; if (isset($instance['cat_count']) and (int)$instance['cat_count'] == 1) echo ' ('. FrmProFieldsHelper::get_field_stats($instance['cat_id'], 'count', false, $cat) .')'; if (isset($instance['cat_name']) and (int)$instance['cat_name'] == 1){ echo '</a>'; }else{ $entry_ids = $frm_entry_meta->getEntryIds("meta_value LIKE '%$cat%' and fi.id=". $instance['cat_id']); $items = false; if ($entry_ids) $items = $frm_entry->getAll("it.id in (". implode(',', $entry_ids) .") and it.form_id =". (int)$display->frm_form_id, $order_by, $limit); if ($items){ echo '<ul>'; foreach ($items as $item){ $url_id = $display->frm_type == 'id' ? $item->id : $item->item_key; $current = (isset($_GET[$display->frm_param]) and $_GET[$display->frm_param] == $url_id) ? ' class="current_page"' : ''; if($item->post_id) $entry_link = get_permalink($item->post_id); else $entry_link = add_query_arg(array($display->frm_param => $url_id), $page_url); echo '<li'. $current .'><a href="'. $entry_link .'">'. $item->name .'</a></li>'. "\n"; } echo '</ul>'; } } echo '</li>'; } }else{ // if not listing entries by category if($display) $items = $frm_entry->getAll(array('it.form_id' => $display->frm_form_id, 'is_draft' => '0'), $order_by, $limit); else $items = array(); foreach ($items as $item){ $url_id = $display->frm_type == 'id' ? $item->id : $item->item_key; $current = (isset($_GET[$display->frm_param]) and $_GET[$display->frm_param] == $url_id) ? ' class="current_page"' : ''; echo "<li". $current ."><a href='".add_query_arg(array($display->frm_param => $url_id), $page_url)."'>". $item->name ."</a></li>\n"; } } echo "</ul>\n"; echo $after_widget; } function update( $new_instance, $old_instance ) { return $new_instance; } function form( $instance ) { global $frmpro_display; $pages = get_posts( array('post_type' => 'page', 'post_status' => 'publish', 'numberposts' => 999, 'order_by' => 'post_title', 'order' => 'ASC')); $displays = $frmpro_display->getAll(array('meta_key' => 'show_count', 'meta_value' => 'dynamic')); //Defaults $instance = wp_parse_args( (array) $instance, array('title' => false, 'display_id' => false, 'post_id' => false, 'title_id' => false, 'cat_list' => false, 'cat_name' => false, 'cat_count' => false, 'cat_id' => false, 'limit' => false) ); $cat_opts = false; if ($instance['display_id']){ global $frm_field; $selected_display = $frmpro_display->getOne($instance['display_id']); if($selected_display){ $selected_form_id = get_post_meta($selected_display->ID, 'frm_form_id', true); $title_opts = $frm_field->getAll("fi.form_id=". (int)$selected_form_id ." and type not in ('divider','captcha','break','html')", ' ORDER BY field_order'); $instance['display_id'] = $selected_display->ID; } } ?> <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'formidable') ?>:</label> <input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr( stripslashes($instance['title']) ); ?>" /></p> <p><label for="<?php echo $this->get_field_id('display_id'); ?>"><?php _e('Use Settings from View', 'formidable') ?>:</label> <select name="<?php echo $this->get_field_name('display_id'); ?>" id="<?php echo $this->get_field_id('display_id'); ?>" class="widefat" onchange="frm_get_display_fields(this.value)"> <option value=""></option> <?php foreach ($displays as $display) echo "<option value=". $display->ID . selected( $instance['display_id'], $display->ID ) .">" . $display->post_title . "</option>"; ?> </select> </p> <p class="description"><?php _e('Views with a "Both (Dynamic)" format will show here.', 'formidable') ?></p> <p><label for="<?php echo $this->get_field_id('post_id'); ?>"><?php _e('Page if not specified in View settings', 'formidable') ?>:</label> <select name="<?php echo $this->get_field_name('post_id'); ?>" id="<?php echo $this->get_field_id('post_id'); ?>" class="widefat"> <option value=""></option> <?php foreach ($pages as $page) echo "<option value=". $page->ID . selected( $instance['post_id'], $page->ID ) . ">" . $page->post_title . "</option>"; ?> </select> </p> <p><label for="<?php echo $this->get_field_id('title_id'); ?>"><?php _e('Title Field', 'formidable') ?>:</label> <select name="<?php echo $this->get_field_name('title_id'); ?>" id="<?php echo $this->get_field_id('title_id'); ?>" class="widefat"> <option value=""></option> <?php if (isset($title_opts) and $title_opts){ foreach ($title_opts as $title_opt) if($title_opt->type != 'checkbox') echo "<option value=". $title_opt->id . selected( $instance['title_id'], $title_opt->id ) . ">" . $title_opt->name . "</option>"; } ?> </select> </p> <p><label for="<?php echo $this->get_field_id('cat_list'); ?>"><input class="checkbox" type="checkbox" <?php checked($instance['cat_list'], true) ?> id="<?php echo $this->get_field_id('cat_list'); ?>" name="<?php echo $this->get_field_name('cat_list'); ?>" value="1" onclick="frm_toggle_cat_opt(this.checked)"/> <?php _e('List Entries by Category', 'formidable') ?></label></p> <div id="<?php echo $this->get_field_id('hide_cat_opts'); ?>"> <p><label for="<?php echo $this->get_field_id('cat_id'); ?>"><?php _e('Category Field', 'formidable') ?>:</label> <select name="<?php echo $this->get_field_name('cat_id'); ?>" id="<?php echo $this->get_field_id('cat_id'); ?>" class="widefat"> <option value=""></option> <?php if (isset($title_opts) and $title_opts){ foreach ($title_opts as $title_opt){ if(in_array($title_opt->type, array('select', 'radio', 'checkbox'))) echo "<option value=". $title_opt->id . selected( $instance['cat_id'], $title_opt->id ) . ">" . $title_opt->name . "</option>"; } } ?> </select> </p> <p><label for="<?php echo $this->get_field_id('cat_count'); ?>"><input class="checkbox" type="checkbox" <?php checked($instance['cat_count'], true) ?> id="<?php echo $this->get_field_id('cat_count'); ?>" name="<?php echo $this->get_field_name('cat_count'); ?>" value="1" /> <?php _e('Show Entry Counts', 'formidable') ?></label></p> <p><input class="checkbox" type="radio" <?php checked($instance['cat_name'], 1) ?> id="<?php echo $this->get_field_id('cat_name'); ?>" name="<?php echo $this->get_field_name('cat_name'); ?>" value="1" /> <label for="<?php echo $this->get_field_id('cat_name'); ?>"><?php _e('Show Only Category Name', 'formidable') ?></label><br/> <input class="checkbox" type="radio" <?php checked($instance['cat_name'], 0) ?> id="<?php echo $this->get_field_id('cat_name'); ?>" name="<?php echo $this->get_field_name('cat_name'); ?>" value="0" /> <label for="<?php echo $this->get_field_id('cat_name'); ?>"><?php _e('Show Entries Beneath Categories', 'formidable') ?></label></p> </div> <p><label for="<?php echo $this->get_field_id('limit'); ?>"><?php _e('Entry Limit (leave blank to list all)', 'formidable') ?>:</label> <input type="text" class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" value="<?php echo esc_attr( $instance['limit'] ); ?>" /></p> <script type="text/javascript"> jQuery(document).ready(function($){ jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").hide(); if (jQuery("#<?php echo $this->get_field_id('cat_list'); ?>").attr("checked")) jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").show(); }); function frm_toggle_cat_opt(checked){ if (checked) jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").fadeIn('slow'); else jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").fadeOut('slow'); } function frm_get_display_fields(display_id){ if (display_id != ''){ jQuery.ajax({ type:"POST", url:"<?php echo admin_url('admin-ajax.php') ?>", data:"action=frm_get_cat_opts&display_id="+display_id, success:function(msg){jQuery("#<?php echo $this->get_field_id('cat_id'); ?>").html(msg);} }); jQuery.ajax({ type:"POST", url:"<?php echo admin_url('admin-ajax.php') ?>", data:"action=frm_get_title_opts&display_id="+display_id, success:function(msg){jQuery("#<?php echo $this->get_field_id('title_id'); ?>").html(msg);} }); } } </script> <?php } } ?>
rafapires/souza-aranha
wp-content/plugins/formidable/pro/classes/widgets/FrmListEntries.php
PHP
gpl-2.0
15,104
<?php defined('_JEXEC') or die('Restricted access'); ?> <?php $form = @$this->form; ?> <?php $row = @$this->row; JFilterOutput::objectHTMLSafe( $row ); ?> <form action="<?php echo JRoute::_( @$form['action'] ) ?>" method="post" class="adminform" name="adminForm" > <fieldset> <legend><?php echo JText::_('Form'); ?></legend> <table class="admintable"> <tr> <td width="100" align="right" class="key"> <label for="tax_class_name"> <?php echo JText::_( 'Name' ); ?>: </label> </td> <td> <input type="text" name="tax_class_name" id="tax_class_name" size="48" maxlength="250" value="<?php echo @$row->tax_class_name; ?>" /> </td> </tr> <tr> <td width="100" align="right" class="key"> <label for="tax_class_description"> <?php echo JText::_( 'Description' ); ?>: </label> </td> <td> <textarea name="tax_class_description" id="tax_class_description" rows="10" cols="25"><?php echo @$row->tax_class_description; ?></textarea> </td> </tr> </table> <input type="hidden" name="id" value="<?php echo @$row->tax_class_id; ?>" /> <input type="hidden" name="task" value="" /> </fieldset> </form>
zuverza/se
tmp/install_4f46ab24b6733/admin/views/taxclasses/tmpl/form.php
PHP
gpl-2.0
1,203
div.contemplate-input .form-textarea { height: 200px; border: 1px solid #666; font-family: Profont, 'lucida console', Monaco, monospace; } div.contemplate-scroller { padding: 0 1em; height: 150px; overflow: auto; border: 1px solid #666; }
iaminawe/Animation-SA
sites/all/modules/contemplate/contemplate.css
CSS
gpl-2.0
253
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML ><HEAD ><TITLE >The Traces Menu</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK REL="HOME" TITLE="The Klusters Handbook" HREF="index.html"><LINK REL="UP" TITLE="Menu Entries" HREF="c1059.html"><LINK REL="PREVIOUS" TITLE="The Correlations Menu" HREF="x1391.html"><LINK REL="NEXT" TITLE="The Displays Menu" HREF="x1498.html"></HEAD ><BODY CLASS="sect1" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#840084" ALINK="#0000FF" ><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="3" ALIGN="center" >The Klusters Handbook</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="bottom" ><A HREF="x1391.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="80%" ALIGN="center" VALIGN="bottom" >Chapter 5. Menu Entries</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="bottom" ><A HREF="x1498.html" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="sect1" ><H1 CLASS="sect1" ><A NAME="menu-traces" >5.7. The Traces Menu</A ></H1 ><P >&#13;<P ></P ><DIV CLASS="variablelist" ><DL ><DT ><SPAN CLASS="guimenu" >Traces</SPAN >-&gt;<SPAN CLASS="guimenuitem" >Increase Channel Amplitudes</SPAN > (<B CLASS="shortcut" ><B CLASS="keycap" >Ctrl</B >-<B CLASS="keycap" >Shift</B >-<B CLASS="keycap" >I</B ></B >)</DT ><DD ><P >Increases the channel amplitudes</P ></DD ><DT ><SPAN CLASS="guimenu" >Traces</SPAN >-&gt;<SPAN CLASS="guimenuitem" >Decrease Channel Amplitudes</SPAN > (<B CLASS="shortcut" ><B CLASS="keycap" >Ctrl</B >-<B CLASS="keycap" >Shift</B >-<B CLASS="keycap" >D</B ></B >)</DT ><DD ><P >Decreases the channel amplitudes</P ></DD ><DT ><SPAN CLASS="guimenu" >Traces</SPAN >-&gt;<SPAN CLASS="guimenuitem" >Show Labels</SPAN > (<B CLASS="shortcut" ><B CLASS="keycap" >Ctrl</B >-<B CLASS="keycap" >L</B ></B >)</DT ><DD ><P >Shows or hides the labels (channel IDs and gains).</P ></DD ></DL ></DIV > </P ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="x1391.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.html" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="x1498.html" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >The Correlations Menu</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="c1059.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >The Displays Menu</TD ></TR ></TABLE ></DIV ></BODY ></HTML >
neurosuite/ndmanager
doc/en/html/x1459.html
HTML
gpl-2.0
2,809
<?php class FlipMegazineImageHelper { /** * @param int $parentNodeId * @param eZCLI $cli */ public static function deleteThumb( $parentNodeId, $cli = null ) { /** @var eZContentObjectTreeNode[] $children */ $children = eZContentObjectTreeNode::subTreeByNodeID( array( 'ClassFilterType' => 'include', 'ClassFilterArray' => array( 'image' ) ), $parentNodeId ); if ( count( $children ) > 0 ) { $message = "Remove " . count( $children ) . " images from node $parentNodeId"; if ( $cli ) { $cli->output( $message ); } else { eZDebug::writeNotice( $message , __METHOD__ ); } foreach ( $children as $node ) { $node->removeNodeFromTree(); } } } /** * @param string $directory * @param string $imageName * @param string $parentNodeId * @return eZContentObject|false */ public static function createThumb( $directory, $imageName, $parentNodeId ) { $user = eZUser::currentUser(); $params = array(); $params['class_identifier'] = 'image'; $params['creator_id'] = $user->attribute( 'contentobject_id' ); $params['parent_node_id'] = $parentNodeId; $params['storage_dir'] = eZSys::rootDir() . eZSys::fileSeparator() . $directory . '/'; $attributesData = array ( ) ; $attributesData['name'] = $imageName; $attributesData['image'] = $imageName; $params['attributes'] = $attributesData; $imageContentObject = eZContentFunctions::createAndPublishObject($params); return $imageContentObject; } } ?>
Opencontent/ezflip
classes/handlers/megazine/megazineimagehelper.php
PHP
gpl-2.0
1,790
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.icmp; import java.net.InetAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>SinglePingResponseCallback class.</p> * * @author <a href="mailto:ranger@opennms.org">Ben Reed</a> * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> */ public class SinglePingResponseCallback implements PingResponseCallback { private static final Logger LOG = LoggerFactory .getLogger(SinglePingResponseCallback.class); /** * Value of round-trip-time for the ping in microseconds. */ private Long m_responseTime = null; private InetAddress m_host; private Throwable m_error = null; private CountDownLatch m_latch = new CountDownLatch(1); /** * <p>Constructor for SinglePingResponseCallback.</p> * * @param host a {@link java.net.InetAddress} object. */ public SinglePingResponseCallback(InetAddress host) { m_host = host; } /** {@inheritDoc} */ @Override public void handleResponse(InetAddress address, EchoPacket response) { try { info("got response for address " + address + ", thread " + response.getIdentifier() + ", seq " + response.getSequenceNumber() + " with a responseTime "+response.elapsedTime(TimeUnit.MILLISECONDS)+"ms"); m_responseTime = (long)Math.round(response.elapsedTime(TimeUnit.MICROSECONDS)); } finally { m_latch.countDown(); } } /** {@inheritDoc} */ @Override public void handleTimeout(InetAddress address, EchoPacket request) { try { assert(request != null); info("timed out pinging address " + address + ", thread " + request.getIdentifier() + ", seq " + request.getSequenceNumber()); } finally { m_latch.countDown(); } } /** {@inheritDoc} */ @Override public void handleError(InetAddress address, EchoPacket request, Throwable t) { try { m_error = t; info("an error occurred pinging " + address, t); } finally { m_latch.countDown(); } } /** * <p>waitFor</p> * * @param timeout a long. * @throws java.lang.InterruptedException if any. */ public void waitFor(long timeout) throws InterruptedException { m_latch.await(timeout, TimeUnit.MILLISECONDS); } /** * <p>waitFor</p> * * @throws java.lang.InterruptedException if any. */ public void waitFor() throws InterruptedException { info("waiting for ping to "+m_host+" to finish"); m_latch.await(); info("finished waiting for ping to "+m_host+" to finish"); } public void rethrowError() throws Exception { if (m_error instanceof Error) { throw (Error)m_error; } else if (m_error instanceof Exception) { throw (Exception)m_error; } } /** * <p>Getter for the field <code>responseTime</code>.</p> * * @return a {@link java.lang.Long} object. */ public Long getResponseTime() { return m_responseTime; } public Throwable getError() { return m_error; } /** * <p>info</p> * * @param msg a {@link java.lang.String} object. */ public void info(String msg) { LOG.info(msg); } /** * <p>info</p> * * @param msg a {@link java.lang.String} object. * @param t a {@link java.lang.Throwable} object. */ public void info(String msg, Throwable t) { LOG.info(msg, t); } }
rfdrake/opennms
opennms-icmp/opennms-icmp-api/src/main/java/org/opennms/netmgt/icmp/SinglePingResponseCallback.java
Java
gpl-2.0
4,879
/* * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MANGOSSERVER_GOSSIP_H #define MANGOSSERVER_GOSSIP_H #include "Common.h" #include "QuestDef.h" #include "NPCHandler.h" class WorldSession; #define GOSSIP_MAX_MENU_ITEMS 64 // client supported items unknown, but provided number must be enough #define DEFAULT_GOSSIP_MESSAGE 0xffffff enum Gossip_Option { GOSSIP_OPTION_NONE = 0, //UNIT_NPC_FLAG_NONE (0) GOSSIP_OPTION_GOSSIP = 1, //UNIT_NPC_FLAG_GOSSIP (1) GOSSIP_OPTION_QUESTGIVER = 2, //UNIT_NPC_FLAG_QUESTGIVER (2) GOSSIP_OPTION_VENDOR = 3, //UNIT_NPC_FLAG_VENDOR (128) GOSSIP_OPTION_TAXIVENDOR = 4, //UNIT_NPC_FLAG_TAXIVENDOR (8192) GOSSIP_OPTION_TRAINER = 5, //UNIT_NPC_FLAG_TRAINER (16) GOSSIP_OPTION_SPIRITHEALER = 6, //UNIT_NPC_FLAG_SPIRITHEALER (16384) GOSSIP_OPTION_SPIRITGUIDE = 7, //UNIT_NPC_FLAG_SPIRITGUIDE (32768) GOSSIP_OPTION_INNKEEPER = 8, //UNIT_NPC_FLAG_INNKEEPER (65536) GOSSIP_OPTION_BANKER = 9, //UNIT_NPC_FLAG_BANKER (131072) GOSSIP_OPTION_PETITIONER = 10, //UNIT_NPC_FLAG_PETITIONER (262144) GOSSIP_OPTION_TABARDDESIGNER = 11, //UNIT_NPC_FLAG_TABARDDESIGNER (524288) GOSSIP_OPTION_BATTLEFIELD = 12, //UNIT_NPC_FLAG_BATTLEFIELDPERSON (1048576) GOSSIP_OPTION_AUCTIONEER = 13, //UNIT_NPC_FLAG_AUCTIONEER (2097152) GOSSIP_OPTION_STABLEPET = 14, //UNIT_NPC_FLAG_STABLE (4194304) GOSSIP_OPTION_ARMORER = 15, //UNIT_NPC_FLAG_ARMORER (4096) GOSSIP_OPTION_UNLEARNTALENTS = 16, //UNIT_NPC_FLAG_TRAINER (16) (bonus option for GOSSIP_OPTION_TRAINER) GOSSIP_OPTION_UNLEARNPETSKILLS = 17, //UNIT_NPC_FLAG_TRAINER (16) (bonus option for GOSSIP_OPTION_TRAINER) GOSSIP_OPTION_MAX }; enum GossipOptionIcon { GOSSIP_ICON_CHAT = 0, //white chat bubble GOSSIP_ICON_VENDOR = 1, //brown bag GOSSIP_ICON_TAXI = 2, //flight GOSSIP_ICON_TRAINER = 3, //book GOSSIP_ICON_INTERACT_1 = 4, //interaction wheel GOSSIP_ICON_INTERACT_2 = 5, //interaction wheel GOSSIP_ICON_MONEY_BAG = 6, //brown bag with yellow dot GOSSIP_ICON_TALK = 7, //white chat bubble with black dots GOSSIP_ICON_TABARD = 8, //tabard GOSSIP_ICON_BATTLE = 9, //two swords GOSSIP_ICON_DOT = 10, //yellow dot GOSSIP_ICON_CHAT_11 = 11, //This and below are most the same visual as GOSSIP_ICON_CHAT GOSSIP_ICON_CHAT_12 = 12, //but are still used for unknown reasons. GOSSIP_ICON_CHAT_13 = 13, GOSSIP_ICON_CHAT_14 = 14, // probably invalid GOSSIP_ICON_CHAT_15 = 15, // probably invalid GOSSIP_ICON_CHAT_16 = 16, GOSSIP_ICON_CHAT_17 = 17, GOSSIP_ICON_CHAT_18 = 18, GOSSIP_ICON_CHAT_19 = 19, GOSSIP_ICON_CHAT_20 = 20, GOSSIP_ICON_MAX }; //POI icons. Many more exist, list not complete. enum Poi_Icon { ICON_POI_BLANK = 0, // Blank (not visible), in 2.4.3 have value 15 with 1..15 values in 0..14 range ICON_POI_GREY_AV_MINE = 1, // Grey mine lorry ICON_POI_RED_AV_MINE = 2, // Red mine lorry ICON_POI_BLUE_AV_MINE = 3, // Blue mine lorry ICON_POI_BWTOMB = 4, // Blue and White Tomb Stone ICON_POI_SMALL_HOUSE = 5, // Small house ICON_POI_GREYTOWER = 6, // Grey Tower ICON_POI_REDFLAG = 7, // Red Flag w/Yellow ! ICON_POI_TOMBSTONE = 8, // Normal tomb stone (brown) ICON_POI_BWTOWER = 9, // Blue and White Tower ICON_POI_REDTOWER = 10, // Red Tower ICON_POI_BLUETOWER = 11, // Blue Tower ICON_POI_RWTOWER = 12, // Red and White Tower ICON_POI_REDTOMB = 13, // Red Tomb Stone ICON_POI_RWTOMB = 14, // Red and White Tomb Stone ICON_POI_BLUETOMB = 15, // Blue Tomb Stone ICON_POI_16 = 16, // Grey ? ICON_POI_17 = 17, // Blue/White ? ICON_POI_18 = 18, // Blue ? ICON_POI_19 = 19, // Red and White ? ICON_POI_20 = 20, // Red ? ICON_POI_GREYLOGS = 21, // Grey Wood Logs ICON_POI_BWLOGS = 22, // Blue and White Wood Logs ICON_POI_BLUELOGS = 23, // Blue Wood Logs ICON_POI_RWLOGS = 24, // Red and White Wood Logs ICON_POI_REDLOGS = 25, // Red Wood Logs ICON_POI_26 = 26, // Grey ? ICON_POI_27 = 27, // Blue and White ? ICON_POI_28 = 28, // Blue ? ICON_POI_29 = 29, // Red and White ? ICON_POI_30 = 30, // Red ? ICON_POI_GREYHOUSE = 31, // Grey House ICON_POI_BWHOUSE = 32, // Blue and White House ICON_POI_BLUEHOUSE = 33, // Blue House ICON_POI_RWHOUSE = 34, // Red and White House ICON_POI_REDHOUSE = 35, // Red House ICON_POI_GREYHORSE = 36, // Grey Horse ICON_POI_BWHORSE = 37, // Blue and White Horse ICON_POI_BLUEHORSE = 38, // Blue Horse ICON_POI_RWHORSE = 39, // Red and White Horse ICON_POI_REDHORSE = 40 // Red Horse }; struct GossipMenuItem { uint8 m_gIcon; bool m_gCoded; std::string m_gMessage; uint32 m_gSender; uint32 m_gOptionId; std::string m_gBoxMessage; uint32 m_gBoxMoney; }; typedef std::vector<GossipMenuItem> GossipMenuItemList; struct GossipMenuItemData { uint32 m_gAction_menu; uint32 m_gAction_poi; uint32 m_gAction_script; }; typedef std::vector<GossipMenuItemData> GossipMenuItemDataList; struct QuestMenuItem { uint32 m_qId; uint8 m_qIcon; }; typedef std::vector<QuestMenuItem> QuestMenuItemList; class MANGOS_DLL_SPEC GossipMenu { public: explicit GossipMenu(WorldSession* session); ~GossipMenu(); void AddMenuItem(uint8 Icon, const std::string& Message, bool Coded = false); void AddMenuItem(uint8 Icon, const std::string& Message, uint32 dtSender, uint32 dtAction, const std::string& BoxMessage, uint32 BoxMoney, bool Coded = false); // for using from scripts, don't must be inlined void AddMenuItem(uint8 Icon, char const* Message, bool Coded = false); void AddMenuItem(uint8 Icon, char const* Message, uint32 dtSender, uint32 dtAction, char const* BoxMessage, uint32 BoxMoney, bool Coded = false); void AddMenuItem(uint8 Icon, int32 itemText, uint32 dtSender, uint32 dtAction, int32 boxText, uint32 BoxMoney, bool Coded = false); void SetMenuId(uint32 menu_id) { m_gMenuId = menu_id; } uint32 GetMenuId() { return m_gMenuId; } void AddGossipMenuItemData(uint32 action_menu, uint32 action_poi, uint32 action_script); unsigned int MenuItemCount() const { return m_gItems.size(); } bool Empty() const { return m_gItems.empty(); } GossipMenuItem const& GetItem( unsigned int Id ) { return m_gItems[ Id ]; } GossipMenuItemData const& GetItemData(unsigned int indexId) { return m_gItemsData[indexId]; } uint32 MenuItemSender( unsigned int ItemId ); uint32 MenuItemAction( unsigned int ItemId ); bool MenuItemCoded( unsigned int ItemId ); void ClearMenu(); WorldSession* GetMenuSession() const { return m_session; } protected: GossipMenuItemList m_gItems; GossipMenuItemDataList m_gItemsData; uint32 m_gMenuId; private: WorldSession* m_session; }; class QuestMenu { public: QuestMenu(); ~QuestMenu(); void AddMenuItem( uint32 QuestId, uint8 Icon); void ClearMenu(); uint8 MenuItemCount() const { return m_qItems.size(); } bool Empty() const { return m_qItems.empty(); } bool HasItem( uint32 questid ); QuestMenuItem const& GetItem( uint16 Id ) { return m_qItems[ Id ]; } protected: QuestMenuItemList m_qItems; }; class MANGOS_DLL_SPEC PlayerMenu { private: GossipMenu mGossipMenu; QuestMenu mQuestMenu; public: explicit PlayerMenu(WorldSession *Session); ~PlayerMenu(); GossipMenu& GetGossipMenu() { return mGossipMenu; } QuestMenu& GetQuestMenu() { return mQuestMenu; } WorldSession* GetMenuSession() const { return mGossipMenu.GetMenuSession(); } bool Empty() const { return mGossipMenu.Empty() && mQuestMenu.Empty(); } void ClearMenus(); uint32 GossipOptionSender( unsigned int Selection ); uint32 GossipOptionAction( unsigned int Selection ); bool GossipOptionCoded( unsigned int Selection ); void SendGossipMenu( uint32 TitleTextId, uint64 npcGUID ); void CloseGossip(); void SendPointOfInterest( float X, float Y, uint32 Icon, uint32 Flags, uint32 Data, const char * locName ); void SendPointOfInterest( uint32 poi_id ); void SendTalking( uint32 textID ); void SendTalking( char const * title, char const * text ); /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ void SendQuestGiverStatus( uint8 questStatus, uint64 npcGUID ); void SendQuestGiverQuestList( QEmote eEmote, const std::string& Title, uint64 npcGUID ); void SendQuestQueryResponse ( Quest const *pQuest ); void SendQuestGiverQuestDetails( Quest const *pQuest, uint64 npcGUID, bool ActivateAccept); void SendQuestGiverOfferReward( Quest const* pQuest, uint64 npcGUID, bool EnbleNext ); void SendQuestGiverRequestItems( Quest const *pQuest, uint64 npcGUID, bool Completable, bool CloseOnCancel ); }; #endif
gmltA/mangos_alternative
src/game/GossipDef.h
C
gpl-2.0
12,801
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Layer.js */ /** * Class: OpenLayers.Layer.Markers * * Inherits from: * - <OpenLayers.Layer> */ OpenLayers.Layer.Markers = OpenLayers.Class(OpenLayers.Layer, { /** * APIProperty: isBaseLayer * {Boolean} Markers layer is never a base layer. */ isBaseLayer: false, /** * APIProperty: markers * {Array(<OpenLayers.Marker>)} internal marker list */ markers: null, /** * Property: drawn * {Boolean} internal state of drawing. This is a workaround for the fact * that the map does not call moveTo with a zoomChanged when the map is * first starting up. This lets us catch the case where we have *never* * drawn the layer, and draw it even if the zoom hasn't changed. */ drawn: false, /** * Constructor: OpenLayers.Layer.Markers * Create a Markers layer. * * Parameters: * name - {String} * options - {Object} Hashtable of extra options to tag onto the layer */ initialize: function(name, options) { OpenLayers.Layer.prototype.initialize.apply(this, arguments); this.markers = []; }, /** * APIMethod: destroy */ destroy: function() { this.clearMarkers(); this.markers = null; OpenLayers.Layer.prototype.destroy.apply(this, arguments); }, /** * APIMethod: setOpacity * Sets the opacity for all the markers. * * Parameter: * opacity - {Float} */ setOpacity: function(opacity) { if (opacity != this.opacity) { this.opacity = opacity; for (var i=0, len=this.markers.length; i<len; i++) { this.markers[i].setOpacity(this.opacity); } } }, /** * Method: moveTo * * Parameters: * bounds - {<OpenLayers.Bounds>} * zoomChanged - {Boolean} * dragging - {Boolean} */ moveTo:function(bounds, zoomChanged, dragging) { OpenLayers.Layer.prototype.moveTo.apply(this, arguments); if (zoomChanged || !this.drawn) { for(var i=0, len=this.markers.length; i<len; i++) { this.drawMarker(this.markers[i]); } this.drawn = true; } }, /** * APIMethod: addMarker * * Parameters: * marker - {<OpenLayers.Marker>} */ addMarker: function(marker) { this.markers.push(marker); if (this.opacity != null) { marker.setOpacity(this.opacity); } if (this.map && this.map.getExtent()) { marker.map = this.map; this.drawMarker(marker); } }, /** * APIMethod: removeMarker * * Parameters: * marker - {<OpenLayers.Marker>} */ removeMarker: function(marker) { if (this.markers && this.markers.length) { OpenLayers.Util.removeItem(this.markers, marker); marker.erase(); } }, /** * Method: clearMarkers * This method removes all markers from a layer. The markers are not * destroyed by this function, but are removed from the list of markers. */ clearMarkers: function() { if (this.markers != null) { while(this.markers.length > 0) { this.removeMarker(this.markers[0]); } } }, /** * Method: drawMarker * Calculate the pixel location for the marker, create it, and * add it to the layer's div * * Parameters: * marker - {<OpenLayers.Marker>} */ drawMarker: function(marker) { var px = this.map.getLayerPxFromLonLat(marker.lonlat); if (px == null) { marker.display(false); } else { if (!marker.isDrawn()) { var markerImg = marker.draw(px); this.div.appendChild(markerImg); } else if(marker.icon) { marker.icon.moveTo(px); } } }, /** * APIMethod: getDataExtent * Calculates the max extent which includes all of the markers. * * Returns: * {<OpenLayers.Bounds>} */ getDataExtent: function () { var maxExtent = null; if ( this.markers && (this.markers.length > 0)) { var maxExtent = new OpenLayers.Bounds(); for(var i=0, len=this.markers.length; i<len; i++) { var marker = this.markers[i]; maxExtent.extend(marker.lonlat); } } return maxExtent; }, CLASS_NAME: "OpenLayers.Layer.Markers" });
blahoink/grassroots
phpmyadmin/js/openlayers/src/openlayers/lib/OpenLayers/Layer/Markers.js
JavaScript
gpl-2.0
5,107
<?php /** * Add Site Administration Screen * * @package WordPress * @subpackage Multisite * @since 3.1.0 */ /** Load WordPress Administration Bootstrap */ require_once( dirname( __FILE__ ) . '/admin.php' ); /** WordPress Translation Install API */ require_once( ABSPATH . 'wp-admin/includes/translation-install.php' ); if ( ! is_multisite() ) wp_die( __( 'Multisite support is not enabled.' ) ); if ( ! current_user_can( 'manage_sites' ) ) wp_die( __( 'You do not have sufficient permissions to add sites to this network.' ) ); get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('This screen is for Super Admins to add new sites to the network. This is not affected by the registration settings.') . '</p>' . '<p>' . __('If the admin email for the new site does not exist in the database, a new user will also be created.') . '</p>' ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="https://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' . '<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>' ); if ( wp_validate_action( 'add-site' ) ) { check_admin_referer( 'add-blog', '_wpnonce_add-blog' ); if ( ! is_array( $_POST['blog'] ) ) wp_die( __( 'Can&#8217;t create an empty site.' ) ); $blog = $_POST['blog']; $domain = ''; if ( preg_match( '|^([a-zA-Z0-9-])+$|', $blog['domain'] ) ) $domain = strtolower( $blog['domain'] ); // If not a subdomain install, make sure the domain isn't a reserved word if ( ! is_subdomain_install() ) { /** This filter is documented in wp-includes/ms-functions.php */ $subdirectory_reserved_names = apply_filters( 'subdirectory_reserved_names', array( 'page', 'comments', 'blog', 'files', 'feed', 'wp-admin', 'wp-content', 'wp-includes' ) ); if ( in_array( $domain, $subdirectory_reserved_names ) ) wp_die( sprintf( __('The following words are reserved for use by WordPress functions and cannot be used as blog names: <code>%s</code>' ), implode( '</code>, <code>', $subdirectory_reserved_names ) ) ); } $title = $blog['title']; $meta = array( 'public' => 1 ); // Handle translation install for the new site. if ( ! empty( $_POST['WPLANG'] ) && wp_can_install_language_pack() ) { $language = wp_download_language_pack( wp_unslash( $_POST['WPLANG'] ) ); if ( $language ) { $meta['WPLANG'] = $language; } } if ( empty( $domain ) ) wp_die( __( 'Missing or invalid site address.' ) ); if ( isset( $blog['email'] ) && '' === trim( $blog['email'] ) ) { wp_die( __( 'Missing email address.' ) ); } $email = sanitize_email( $blog['email'] ); if ( ! is_email( $email ) ) { wp_die( __( 'Invalid email address.' ) ); } if ( is_subdomain_install() ) { $newdomain = $domain . '.' . preg_replace( '|^www\.|', '', $current_site->domain ); $path = $current_site->path; } else { $newdomain = $current_site->domain; $path = $current_site->path . $domain . '/'; } $password = 'N/A'; $user_id = email_exists($email); if ( !$user_id ) { // Create a new user with a random password $password = wp_generate_password( 12, false ); $user_id = wpmu_create_user( $domain, $password, $email ); if ( false === $user_id ) wp_die( __( 'There was an error creating the user.' ) ); else wp_new_user_notification( $user_id, null, 'both' ); } $wpdb->hide_errors(); $id = wpmu_create_blog( $newdomain, $path, $title, $user_id, $meta, $current_site->id ); $wpdb->show_errors(); if ( ! is_wp_error( $id ) ) { if ( ! is_super_admin( $user_id ) && !get_user_option( 'primary_blog', $user_id ) ) { update_user_option( $user_id, 'primary_blog', $id, true ); } $content_mail = sprintf( /* translators: 1: user login, 2: site url, 3: site name/title */ __( 'New site created by %1$s Address: %2$s Name: %3$s' ), $current_user->user_login, get_site_url( $id ), wp_unslash( $title ) ); wp_mail( get_site_option('admin_email'), sprintf( __( '[%s] New Site Created' ), $current_site->site_name ), $content_mail, 'From: "Site Admin" <' . get_site_option( 'admin_email' ) . '>' ); wpmu_welcome_notification( $id, $user_id, $password, $title, array( 'public' => 1 ) ); wp_redirect( add_query_arg( array( 'update' => 'added', 'id' => $id ), 'site-new.php' ) ); exit; } else { wp_die( $id->get_error_message() ); } } if ( isset($_GET['update']) ) { $messages = array(); if ( 'added' == $_GET['update'] ) $messages[] = sprintf( /* translators: 1: dashboard url, 2: network admin edit url */ __( 'Site added. <a href="%1$s">Visit Dashboard</a> or <a href="%2$s">Edit Site</a>' ), esc_url( get_admin_url( absint( $_GET['id'] ) ) ), network_admin_url( 'site-info.php?id=' . absint( $_GET['id'] ) ) ); } $title = __('Add New Site'); $parent_file = 'sites.php'; wp_enqueue_script( 'user-suggest' ); require( ABSPATH . 'wp-admin/admin-header.php' ); ?> <div class="wrap"> <h1 id="add-new-site"><?php _e( 'Add New Site' ); ?></h1> <?php if ( ! empty( $messages ) ) { foreach ( $messages as $msg ) echo '<div id="message" class="updated notice is-dismissible"><p>' . $msg . '</p></div>'; } ?> <form method="post" action="<?php echo network_admin_url( 'site-new.php?action=add-site' ); ?>" novalidate="novalidate"> <?php wp_nonce_field( 'add-blog', '_wpnonce_add-blog' ) ?> <table class="form-table"> <tr class="form-field form-required"> <th scope="row"><label for="site-address"><?php _e( 'Site Address' ) ?></label></th> <td> <?php if ( is_subdomain_install() ) { ?> <input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off"/><span class="no-break">.<?php echo preg_replace( '|^www\.|', '', $current_site->domain ); ?></span> <?php } else { echo $current_site->domain . $current_site->path ?><input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off" /> <?php } echo '<p id="site-address-desc">' . __( 'Only lowercase letters (a-z) and numbers are allowed.' ) . '</p>'; ?> </td> </tr> <tr class="form-field form-required"> <th scope="row"><label for="site-title"><?php _e( 'Site Title' ) ?></label></th> <td><input name="blog[title]" type="text" class="regular-text" id="site-title" /></td> </tr> <?php $languages = get_available_languages(); $translations = wp_get_available_translations(); if ( ! empty( $languages ) || ! empty( $translations ) ) : ?> <tr class="form-field form-required"> <th scope="row"><label for="site-language"><?php _e( 'Site Language' ); ?></label></th> <td> <?php // Network default. $lang = get_site_option( 'WPLANG' ); // Use English if the default isn't available. if ( ! in_array( $lang, $languages ) ) { $lang = ''; } wp_dropdown_languages( array( 'name' => 'WPLANG', 'id' => 'site-language', 'selected' => $lang, 'languages' => $languages, 'translations' => $translations, 'show_available_translations' => wp_can_install_language_pack(), ) ); ?> </td> </tr> <?php endif; // Languages. ?> <tr class="form-field form-required"> <th scope="row"><label for="admin-email"><?php _e( 'Admin Email' ) ?></label></th> <td><input name="blog[email]" type="email" class="regular-text wp-suggest-user" id="admin-email" data-autocomplete-type="search" data-autocomplete-field="user_email" /></td> </tr> <tr class="form-field"> <td colspan="2"><?php _e( 'A new user will be created if the above email address is not in the database.' ) ?><br /><?php _e( 'The username and password will be mailed to this email address.' ) ?></td> </tr> </table> <?php submit_button( __('Add Site'), 'primary', 'add-site' ); ?> </form> </div> <?php require( ABSPATH . 'wp-admin/admin-footer.php' );
pk0nstantin/WordPress
wp-admin/network/site-new.php
PHP
gpl-2.0
8,230
// Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #pragma once #include <array> #include <fstream> #include <functional> #include <cstddef> #include <cstdio> #include <string> #include <vector> #include "common/common_types.h" // User directory indices for GetUserPath enum { D_USER_IDX, D_ROOT_IDX, D_CONFIG_IDX, D_GAMECONFIG_IDX, D_MAPS_IDX, D_CACHE_IDX, D_SHADERCACHE_IDX, D_SHADERS_IDX, D_STATESAVES_IDX, D_SCREENSHOTS_IDX, D_SDMC_IDX, D_NAND_IDX, D_SYSDATA_IDX, D_HIRESTEXTURES_IDX, D_DUMP_IDX, D_DUMPFRAMES_IDX, D_DUMPAUDIO_IDX, D_DUMPTEXTURES_IDX, D_DUMPDSP_IDX, D_LOGS_IDX, D_SYSCONF_IDX, F_EMUCONFIG_IDX, F_DEBUGGERCONFIG_IDX, F_LOGGERCONFIG_IDX, F_MAINLOG_IDX, F_RAMDUMP_IDX, F_ARAMDUMP_IDX, F_SYSCONF_IDX, NUM_PATH_INDICES }; namespace FileUtil { // FileSystem tree node/ struct FSTEntry { bool isDirectory; u64 size; // file length or number of entries from children std::string physicalName; // name on disk std::string virtualName; // name in FST names table std::vector<FSTEntry> children; }; // Returns true if file filename exists bool Exists(const std::string &filename); // Returns true if filename is a directory bool IsDirectory(const std::string &filename); // Returns the size of filename (64bit) u64 GetSize(const std::string &filename); // Overloaded GetSize, accepts file descriptor u64 GetSize(const int fd); // Overloaded GetSize, accepts FILE* u64 GetSize(FILE *f); // Returns true if successful, or path already exists. bool CreateDir(const std::string &filename); // Creates the full path of fullPath returns true on success bool CreateFullPath(const std::string &fullPath); // Deletes a given filename, return true on success // Doesn't supports deleting a directory bool Delete(const std::string &filename); // Deletes a directory filename, returns true on success bool DeleteDir(const std::string &filename); // renames file srcFilename to destFilename, returns true on success bool Rename(const std::string &srcFilename, const std::string &destFilename); // copies file srcFilename to destFilename, returns true on success bool Copy(const std::string &srcFilename, const std::string &destFilename); // creates an empty file filename, returns true on success bool CreateEmptyFile(const std::string &filename); /** * Scans the directory tree, calling the callback for each file/directory found. * The callback must return the number of files and directories which the provided path contains. * If the callback's return value is -1, the callback loop is broken immediately. * If the callback's return value is otherwise negative, the callback loop is broken immediately * and the callback's return value is returned from this function (to allow for error handling). * @param directory the parent directory to start scanning from * @param callback The callback which will be called for each file/directory. It is called * with the arguments (const std::string& directory, const std::string& virtual_name). * The `directory `parameter is the path to the directory which contains the file/directory. * The `virtual_name` parameter is the incomplete file path, without any directory info. * @return the total number of files/directories found */ int ScanDirectoryTreeAndCallback(const std::string &directory, std::function<int(const std::string&, const std::string&)> callback); /** * Scans the directory tree, storing the results. * @param directory the parent directory to start scanning from * @param parent_entry FSTEntry where the filesystem tree results will be stored. * @return the total number of files/directories found */ int ScanDirectoryTree(const std::string &directory, FSTEntry& parent_entry); // deletes the given directory and anything under it. Returns true on success. bool DeleteDirRecursively(const std::string &directory); // Returns the current directory std::string GetCurrentDir(); // Create directory and copy contents (does not overwrite existing files) void CopyDir(const std::string &source_path, const std::string &dest_path); // Set the current directory to given directory bool SetCurrentDir(const std::string &directory); // Returns a pointer to a string with a Citra data dir in the user's home // directory. To be used in "multi-user" mode (that is, installed). const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath=""); // Returns the path to where the sys file are std::string GetSysDirectory(); #ifdef __APPLE__ std::string GetBundleDirectory(); #endif #ifdef _WIN32 std::string &GetExeDirectory(); #endif size_t WriteStringToFile(bool text_file, const std::string &str, const char *filename); size_t ReadFileToString(bool text_file, const char *filename, std::string &str); /** * Splits the filename into 8.3 format * Loosely implemented following https://en.wikipedia.org/wiki/8.3_filename * @param filename The normal filename to use * @param short_name A 9-char array in which the short name will be written * @param extension A 4-char array in which the extension will be written */ void SplitFilename83(const std::string& filename, std::array<char, 9>& short_name, std::array<char, 4>& extension); // simple wrapper for cstdlib file functions to // hopefully will make error checking easier // and make forgetting an fclose() harder class IOFile : public NonCopyable { public: IOFile(); IOFile(std::FILE* file); IOFile(const std::string& filename, const char openmode[]); ~IOFile(); IOFile(IOFile&& other); IOFile& operator=(IOFile&& other); void Swap(IOFile& other); bool Open(const std::string& filename, const char openmode[]); bool Close(); template <typename T> size_t ReadArray(T* data, size_t length) { if (!IsOpen()) { m_good = false; return -1; } size_t items_read = std::fread(data, sizeof(T), length, m_file); if (items_read != length) m_good = false; return items_read; } template <typename T> size_t WriteArray(const T* data, size_t length) { static_assert(std::is_standard_layout<T>::value, "Given array does not consist of standard layout objects"); // TODO: gcc 4.8 does not support is_trivially_copyable, but we really should check for it here. //static_assert(std::is_trivially_copyable<T>::value, "Given array does not consist of trivially copyable objects"); if (!IsOpen()) { m_good = false; return -1; } size_t items_written = std::fwrite(data, sizeof(T), length, m_file); if (items_written != length) m_good = false; return items_written; } size_t ReadBytes(void* data, size_t length) { return ReadArray(reinterpret_cast<char*>(data), length); } size_t WriteBytes(const void* data, size_t length) { return WriteArray(reinterpret_cast<const char*>(data), length); } template<typename T> size_t WriteObject(const T& object) { static_assert(!std::is_pointer<T>::value, "Given object is a pointer"); return WriteArray(&object, 1); } bool IsOpen() { return nullptr != m_file; } // m_good is set to false when a read, write or other function fails bool IsGood() { return m_good; } operator void*() { return m_good ? m_file : nullptr; } std::FILE* ReleaseHandle(); std::FILE* GetHandle() { return m_file; } void SetHandle(std::FILE* file); bool Seek(s64 off, int origin); u64 Tell(); u64 GetSize(); bool Resize(u64 size); bool Flush(); // clear error state void Clear() { m_good = true; std::clearerr(m_file); } std::FILE* m_file; bool m_good; private: IOFile(IOFile&); IOFile& operator=(IOFile& other); }; } // namespace // To deal with Windows being dumb at unicode: template <typename T> void OpenFStream(T& fstream, const std::string& filename, std::ios_base::openmode openmode) { #ifdef _MSC_VER fstream.open(Common::UTF8ToTStr(filename).c_str(), openmode); #else fstream.open(filename.c_str(), openmode); #endif }
ichfly/citra
src/common/file_util.h
C
gpl-2.0
8,428
<?php birch_ns( 'birchschedule.upgrader', function( $ns ) { $ns->init = function() use ( $ns ) { add_action( 'birchschedule_upgrade_core_after', array( $ns, 'upgrade_core' ) ); }; $ns->get_staff_all_schedule_1_0 = function( $staff ) { $schedule = $staff['_birs_staff_schedule']; if ( !isset( $schedule ) ) { $schedule = array(); } else { $schedule = unserialize( $schedule ); } $schedule = $schedule ? $schedule : array(); return $schedule; }; $ns->upgrade_staff_schedule_from_1_0_to_1_1 = function() use ( $ns ) { global $birchpress; $version = $ns->get_staff_schedule_version(); if ( $version != '1.0' ) { return; } $staff = $birchpress->db->query( array( 'post_type' => 'birs_staff' ), array( 'meta_keys' => array( '_birs_staff_schedule' ), 'base_keys' => array() ) ); foreach ( $staff as $thestaff ) { $schedules = $ns->get_staff_all_schedule_1_0( $thestaff ); $new_all_schedules = array(); foreach ( $schedules as $location_id => $schedule ) { if ( isset( $schedule['exceptions'] ) ) { $exceptions = $schedule['exceptions']; } else { $exceptions = array(); } $new_schedules = array(); foreach ( $schedule as $week_day => $day_schedule ) { if ( isset( $day_schedule['enabled'] ) ) { $start = $day_schedule['minutes_start']; $end = $day_schedule['minutes_end']; $new_schedule = array( 'minutes_start' => $day_schedule['minutes_start'], 'minutes_end' => $day_schedule['minutes_end'], 'weeks' => array( $week_day => 'on' ) ); if ( isset( $new_schedules['s'. $start. $end] ) ) { $new_schedules['s'. $start. $end]['weeks'][$week_day] = 'on'; } else { $new_schedules['s'. $start. $end] = $new_schedule; } } } $new_loc_schedules = array(); foreach ( $new_schedules as $tmp_id => $new_schedule ) { $uid = uniqid(); $new_loc_schedules[$uid] = $new_schedule; } $new_all_schedules[$location_id] = array( 'schedules' => $new_loc_schedules, 'exceptions' => $exceptions ); update_post_meta( $thestaff['ID'], '_birs_staff_schedule', serialize( $new_all_schedules ) ); } } update_option( 'birs_staff_schedule_version', '1.1' ); }; $ns->get_staff_schedule_version = function() { return get_option( 'birs_staff_schedule_version', '1.0' ); }; $ns->upgrade_appointment_from_1_0_to_1_1 = function() use ( $ns ) { global $birchpress, $birchschedule; $version = $ns->get_db_version_appointment(); if ( $version != '1.0' ) { return; } $appointment_fields = array( '_birs_appointment_price', '_birs_appointment_client', '_birs_appointment_notes', '_birs_appointment_payment_status', '_birs_appointment_reminded' ); $appointment1on1_fields = array( '_birs_appointment_id', '_birs_client_id', '_birs_appointment1on1_payment_status', '_birs_appointment1on1_reminded', '_birs_appointment1on1_price', '_birs_appointment1on1_uid' ); $appointment1on1_custom_fields = array( '_birs_appointment_notes' ); $options = get_option( 'birchschedule_options_form' ); if ( $options != false ) { $fields_options = $options['fields']; foreach ( $fields_options as $field_id => $field ) { if ( $field['belong_to'] == 'appointment' ) { $meta_key = '_birs_' . $field_id; if ( !in_array( $meta_key, array( '_birs_appointment_notes' ) ) ) { $appointment_fields[] = $meta_key; $appointment1on1_custom_fields[] = $meta_key; } } } } $appointments = $birchschedule->model->query( array( 'post_type' => 'birs_appointment', 'post_status' => array( 'publish', 'pending' ) ), array( 'base_keys' => array(), 'meta_keys' => $appointment_fields ) ); foreach ( $appointments as $appointment ) { if ( isset( $appointment['ID'] ) && isset( $appointment['_birs_appointment_client'] ) ) { $appointment1on1 = array( 'post_type' => 'birs_appointment1on1', '_birs_appointment_id' => $appointment['ID'], '_birs_client_id' => $appointment['_birs_appointment_client'] ); if ( isset( $appointment['_birs_appointment_price'] ) ) { $appointment1on1['_birs_appointment1on1_price'] = $appointment['_birs_appointment_price']; } if ( isset( $appointment['_birs_appointment_payment_status'] ) ) { $appointment1on1['_birs_appointment1on1_payment_status'] = $appointment['_birs_appointment_payment_status']; } if ( isset( $appointment['_birs_appointment_reminded'] ) ) { $appointment1on1['_birs_appointment1on1_reminded'] = $appointment['_birs_appointment_reminded']; } $appointment1on1['_birs_appointment1on1_uid'] = uniqid(); foreach ( $appointment1on1_custom_fields as $appointment1on1_custom_field ) { if ( isset( $appointment[$appointment1on1_custom_field] ) ) { $appointment1on1[$appointment1on1_custom_field] = $appointment[$appointment1on1_custom_field]; } } $appointment1on1_meta_keys = array_merge( $appointment1on1_fields, $appointment1on1_custom_fields ); $birchpress->db->save( $appointment1on1, array( 'base_keys' => array(), 'meta_keys' => $appointment1on1_meta_keys ) ); foreach ( $appointment1on1_custom_fields as $appointment1on1_custom_field ) { delete_post_meta( $appointment['ID'], $appointment1on1_custom_field ); } delete_post_meta( $appointment['ID'], '_birs_appointment_client' ); delete_post_meta( $appointment['ID'], '_birs_appointment_notes' ); delete_post_meta( $appointment['ID'], '_birs_appointment_reminded' ); delete_post_meta( $appointment['ID'], '_birs_appointment_price' ); delete_post_meta( $appointment['ID'], '_birs_appointment_payment_status' ); } } update_option( 'birs_db_version_appointment', '1.1' ); }; $ns->upgrade_appointment_from_1_1_to_1_2 = function() use ( $ns ) { global $birchpress, $birchschedule; $version = $ns->get_db_version_appointment(); if ( $version != '1.1' ) { return; } $appointments = $birchschedule->model->query( array( 'post_type' => 'birs_appointment', 'post_status' => array( 'any' ) ), array( 'base_keys' => array( 'post_author' ), 'meta_keys' => array( '_birs_appointment_staff' ) ) ); if ( $appointments ) { foreach ( $appointments as $appointment_id => $appointment ) { $staff = $birchschedule->model->get( $appointment['_birs_appointment_staff'], array( 'base_keys' => array(), 'meta_keys' => array( '_birs_staff_email' ) ) ); if ( $staff ) { $user = WP_User::get_data_by( 'email', $staff['_birs_staff_email'] ); if ( $user ) { $appointment['post_author'] = $user->ID; $birchschedule->model->save( $appointment, array( 'base_keys' => array( 'post_author' ), 'meta_keys' => array() ) ); } } } } update_option( 'birs_db_version_appointment', '1.2' ); }; $ns->get_db_version_appointment = function() { return get_option( 'birs_db_version_appointment', '1.0' ); }; $ns->upgrade_core = function() use ( $ns ) { $ns->upgrade_staff_schedule_from_1_0_to_1_1(); $ns->upgrade_appointment_from_1_0_to_1_1(); $ns->upgrade_appointment_from_1_1_to_1_2(); }; } );
stanislav-chechun/campus-rize
wp-content/plugins/birchschedule/includes/upgrader/package.php
PHP
gpl-2.0
7,346
/* packet-hdmi.c * Routines for HDMI dissection * Copyright 2014 Martin Kaiser <martin@kaiser.cx> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* this dissector handles I2C messages on the HDMI Display Data Channel (DDC) * * EDID (Extended Display Identification Data) messages are dissected here, * HDCP messages are passed on to the HDCP dissector */ #include "config.h" #include <glib.h> #include <epan/packet.h> #include <epan/ptvcursor.h> #include <epan/expert.h> #include <epan/wmem/wmem.h> #include "packet-hdmi.h" void proto_register_hdmi(void); void proto_reg_handoff_hdmi(void); static int proto_hdmi = -1; static dissector_handle_t hdcp_handle; static gint ett_hdmi = -1; static gint ett_hdmi_edid = -1; static int hf_hdmi_addr = -1; static int hf_hdmi_edid_offset = -1; static int hf_hdmi_edid_hdr = -1; static int hf_hdmi_edid_manf_id = -1; static int hf_hdmi_edid_manf_prod_code = -1; static int hf_hdmi_edid_manf_serial = -1; static int hf_hdmi_edid_manf_week = -1; static int hf_hdmi_edid_mod_year = -1; static int hf_hdmi_edid_manf_year = -1; /* also called Source and Sink in the HDMI spec */ #define ADDR_TRX "Transmitter" #define ADDR_RCV "Receiver" /* we use 8bit I2C addresses, including the direction bit */ #define ADDR8_HDCP_WRITE 0x74 /* transmitter->receiver */ #define ADDR8_HDCP_READ 0x75 /* r->t */ #define ADDR8_EDID_WRITE 0xA0 /* t->r */ #define ADDR8_EDID_READ 0xA1 /* r->t */ #define HDCP_ADDR8(x) (x==ADDR8_HDCP_WRITE || x==ADDR8_HDCP_READ) static const value_string hdmi_addr[] = { { ADDR8_HDCP_WRITE, "transmitter writes HDCP data for receiver" }, { ADDR8_HDCP_READ, "transmitter reads HDCP data from receiver" }, { ADDR8_EDID_WRITE, "EDID request" }, { ADDR8_EDID_READ, "EDID read" }, { 0, NULL } }; #define EDID_HDR_VALUE G_GUINT64_CONSTANT(0x00ffffffffffff00) /* grab 5 bits, from bit n to n+4, from a big-endian number x map those bits to a capital letter such that A==1, B==2, ... */ #define CAPITAL_LETTER(x, n) ('A'-1 + (((x) & (0x1F<<n)) >> n)) gboolean sub_check_hdmi(packet_info *pinfo _U_) { /* by looking at the i2c_phdr only, we can't decide if this packet is HDMI this function is called when the user explicitly selected HDMI in the preferences therefore, we always return TRUE and hand the data to the (new style) dissector who sees the 8bit address and the packet content */ return TRUE; } /* dissect EDID data from the receiver return the offset after the dissected data */ static gint dissect_hdmi_edid(tvbuff_t *tvb, gint offset, packet_info *pinfo, proto_tree *tree) { proto_item *ti, *yi; proto_tree *edid_tree; guint64 edid_hdr; guint16 manf_id; gchar manf_id_str[4]; /* 3 letters + 0-termination */ guint8 week, year; int year_hf; guint8 edid_ver, edid_rev; ti = proto_tree_add_text(tree, tvb, offset, tvb_reported_length_remaining(tvb, offset), "Extended Display Identification Data (EDID)"); edid_tree = proto_item_add_subtree(ti, ett_hdmi_edid); edid_hdr = tvb_get_ntoh64(tvb, offset); if (edid_hdr != EDID_HDR_VALUE) return offset; /* XXX handle fragmented EDID messages */ col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "EDID"); proto_tree_add_item(edid_tree, hf_hdmi_edid_hdr, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; /* read as big endian for easier splitting */ manf_id = tvb_get_ntohs(tvb, offset); /* XXX check that MSB is 0 */ manf_id_str[0] = CAPITAL_LETTER(manf_id, 10); manf_id_str[1] = CAPITAL_LETTER(manf_id, 5); manf_id_str[2] = CAPITAL_LETTER(manf_id, 0); manf_id_str[3] = 0; proto_tree_add_string(edid_tree, hf_hdmi_edid_manf_id, tvb, offset, 2, manf_id_str); offset += 2; proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_prod_code, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_serial, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; week = tvb_get_guint8(tvb, offset); proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_week, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; year_hf = week==255 ? hf_hdmi_edid_mod_year : hf_hdmi_edid_manf_year; year = tvb_get_guint8(tvb, offset); yi = proto_tree_add_item(edid_tree, year_hf, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_item_append_text(yi, " (year %d)", 1990+year); offset++; edid_ver = tvb_get_guint8(tvb, offset); edid_rev = tvb_get_guint8(tvb, offset+1); /* XXX make this filterable */ proto_tree_add_text(edid_tree, tvb, offset, 2, "EDID Version %d.%d", edid_ver, edid_rev); /* XXX dissect the parts following the EDID header */ return tvb_reported_length(tvb); } static int dissect_hdmi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { guint8 addr; gint offset=0; proto_item *pi; proto_tree *hdmi_tree; /* the I2C address in the first byte is always handled by the HDMI dissector, even if the packet contains HDCP data */ addr = tvb_get_guint8(tvb, 0); if (!try_val_to_str(addr, hdmi_addr)) return 0; /* no HDMI packet */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "HDMI"); col_clear(pinfo->cinfo, COL_INFO); pi = proto_tree_add_protocol_format(tree, proto_hdmi, tvb, 0, tvb_reported_length(tvb), "HDMI"); hdmi_tree = proto_item_add_subtree(pi, ett_hdmi); if (addr&0x01) { SET_ADDRESS(&pinfo->src, AT_STRINGZ, (int)strlen(ADDR_RCV)+1, ADDR_RCV); SET_ADDRESS(&pinfo->dst, AT_STRINGZ, (int)strlen(ADDR_TRX)+1, ADDR_TRX); pinfo->p2p_dir = P2P_DIR_RECV; } else { SET_ADDRESS(&pinfo->src, AT_STRINGZ, (int)strlen(ADDR_TRX)+1, ADDR_TRX); SET_ADDRESS(&pinfo->dst, AT_STRINGZ, (int)strlen(ADDR_RCV)+1, ADDR_RCV); pinfo->p2p_dir = P2P_DIR_SENT; } /* there's no explicit statement in the spec saying that the protocol is big or little endian there's three cases: one byte values, symmetrical values or values that are explicitly marked as little endian for the sake of simplicity, we use little endian everywhere */ proto_tree_add_item(hdmi_tree, hf_hdmi_addr, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; if (HDCP_ADDR8(addr)) { gint hdcp_len; tvbuff_t *hdcp_tvb; hdcp_len = tvb_reported_length_remaining(tvb, offset); hdcp_tvb = tvb_new_subset(tvb, offset, hdcp_len, hdcp_len); return call_dissector(hdcp_handle, hdcp_tvb, pinfo, hdmi_tree); } if (addr==ADDR8_EDID_WRITE) { col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "EDID request"); proto_tree_add_item(hdmi_tree, hf_hdmi_edid_offset, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; return offset; } return dissect_hdmi_edid(tvb, offset, pinfo, hdmi_tree); } void proto_register_hdmi(void) { static hf_register_info hf[] = { { &hf_hdmi_addr, { "8bit I2C address", "hdmi.addr", FT_UINT8, BASE_HEX, VALS(hdmi_addr), 0, NULL, HFILL } }, { &hf_hdmi_edid_offset, { "Offset", "hdmi.edid.offset", FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_hdr, { "EDID header", "hdmi.edid.hdr", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_id, { "Manufacturer ID", "hdmi.edid.manf_id", FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_prod_code, { "Manufacturer product code", "hdmi.edid.manf_prod_code", FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_serial, { "Serial number", "hdmi.edid.serial_num", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_week, { "Week of manufacture", "hdmi.edid.manf_week", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_mod_year, { "Model year", "hdmi.edid.model_year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_year, { "Year of manufacture", "hdmi.edid.manf_year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } } }; static gint *ett[] = { &ett_hdmi, &ett_hdmi_edid }; proto_hdmi = proto_register_protocol( "High-Definition Multimedia Interface", "HDMI", "hdmi"); proto_register_field_array(proto_hdmi, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); new_register_dissector("hdmi", dissect_hdmi, proto_hdmi); } void proto_reg_handoff_hdmi(void) { hdcp_handle = find_dissector("hdcp"); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
jfzazo/wireshark-hwgen
src/epan/dissectors/packet-hdmi.c
C
gpl-2.0
10,017
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Silverpine_Forest SD%Complete: 100 SDComment: Quest support: 435 SDCategory: Silverpine Forest EndScriptData */ /* ContentData npc_deathstalker_erland EndContentData */ #include "ScriptMgr.h" #include "Player.h" #include "ScriptedEscortAI.h" /*###### ## npc_deathstalker_erland ######*/ enum eErland { SAY_QUESTACCEPT = 0, SAY_START = 1, SAY_AGGRO = 2, SAY_PROGRESS = 3, SAY_LAST = 4, SAY_RANE = 0, SAY_RANE_ANSWER = 5, SAY_MOVE_QUINN = 6, SAY_QUINN = 7, SAY_QUINN_ANSWER = 0, SAY_BYE = 8, QUEST_ESCORTING = 435, NPC_RANE = 1950, NPC_QUINN = 1951 }; class npc_deathstalker_erland : public CreatureScript { public: npc_deathstalker_erland() : CreatureScript("npc_deathstalker_erland") { } struct npc_deathstalker_erlandAI : public EscortAI { npc_deathstalker_erlandAI(Creature* creature) : EscortAI(creature) { } void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override { Player* player = GetPlayerForEscort(); if (!player) return; switch (waypointId) { case 1: Talk(SAY_START, player); break; case 10: Talk(SAY_PROGRESS); break; case 13: Talk(SAY_LAST, player); player->GroupEventHappens(QUEST_ESCORTING, me); break; case 15: if (Creature* rane = me->FindNearestCreature(NPC_RANE, 20.0f)) rane->AI()->Talk(SAY_RANE); break; case 16: Talk(SAY_RANE_ANSWER); break; case 17: Talk(SAY_MOVE_QUINN); break; case 24: Talk(SAY_QUINN); break; case 25: if (Creature* quinn = me->FindNearestCreature(NPC_QUINN, 20.0f)) quinn->AI()->Talk(SAY_QUINN_ANSWER); break; case 26: Talk(SAY_BYE); break; } } void Reset() override { } void EnterCombat(Unit* who) override { Talk(SAY_AGGRO, who); } void QuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_ESCORTING) { Talk(SAY_QUESTACCEPT, player); Start(true, false, player->GetGUID()); } } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_deathstalker_erlandAI(creature); } }; /*###### ## AddSC ######*/ void AddSC_silverpine_forest() { new npc_deathstalker_erland(); }
Nalliestrasza/LegionHearth
src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp
C++
gpl-2.0
3,786
<?php if (cfr('CUSTMAP')) { $altCfg = $ubillingConfig->getAlter(); if ($altCfg['CUSTMAP_ENABLED']) { $custmaps = new CustomMaps(); // new custom map creation if (wf_CheckPost(array('newmapname'))) { if (cfr('CUSTMAPEDIT')) { $custmaps->mapCreate($_POST['newmapname']); rcms_redirect('?module=custmaps'); } else { show_error(__('Permission denied')); } } //custom map deletion if (wf_CheckGet(array('deletemap'))) { if (cfr('CUSTMAPEDIT')) { $custmaps->mapDelete($_GET['deletemap']); rcms_redirect('?module=custmaps'); } else { show_error(__('Permission denied')); } } //editing existing custom map name if (wf_CheckPost(array('editmapid', 'editmapname'))) { if (cfr('CUSTMAPEDIT')) { $custmaps->mapEdit($_POST['editmapid'], $_POST['editmapname']); rcms_redirect('?module=custmaps'); } else { show_error(__('Permission denied')); } } //creating new map item if (wf_CheckPost(array('newitemgeo', 'newitemtype'))) { if (wf_CheckGet(array('showmap'))) { if (cfr('CUSTMAPEDIT')) { $custmaps->itemCreate($_GET['showmap'], $_POST['newitemtype'], $_POST['newitemgeo'], $_POST['newitemname'], $_POST['newitemlocation']); rcms_redirect('?module=custmaps&showmap=' . $_GET['showmap'] . '&mapedit=true'); } else { show_error(__('Permission denied')); } } } //deleting map item if (wf_CheckGet(array('deleteitem'))) { if (cfr('CUSTMAPEDIT')) { $deleteResult = $custmaps->itemDelete($_GET['deleteitem']); rcms_redirect('?module=custmaps&showitems=' . $deleteResult); } else { show_error(__('Permission denied')); } } //items upload as KML if (wf_CheckPost(array('itemsUploadTypes'))) { $custmaps->catchFileUpload(); } if (!wf_CheckGet(array('showmap'))) { if (!wf_CheckGet(array('showitems'))) { if (!wf_CheckGet(array('edititem'))) { //render existing custom maps list show_window(__('Available custom maps'), $custmaps->renderMapList()); zb_BillingStats(true); } else { $editItemId = $_GET['edititem']; //editing item if (wf_CheckPost(array('edititemid', 'edititemtype'))) { if (cfr('CUSTMAPEDIT')) { $custmaps->itemEdit($editItemId, $_POST['edititemtype'], $_POST['edititemgeo'], $_POST['edititemname'], $_POST['edititemlocation']); rcms_redirect('?module=custmaps&edititem=' . $editItemId); } else { show_error(__('Permission denied')); } } //show item edit form show_window(__('Edit'), $custmaps->itemEditForm($editItemId)); //photostorage link if ($altCfg['PHOTOSTORAGE_ENABLED']) { $imageControl = wf_Link('?module=photostorage&scope=CUSTMAPSITEMS&itemid=' . $editItemId . '&mode=list', wf_img('skins/photostorage.png') . ' ' . __('Upload images'), false, 'ubButton'); show_window('', $imageControl); } //additional comments if ($altCfg['ADCOMMENTS_ENABLED']) { $adcomments = new ADcomments('CUSTMAPITEMS'); show_window(__('Additional comments'), $adcomments->renderComments($editItemId)); } } } else { if (!wf_CheckGet(array('duplicates'))) { //render items list json data in background if (wf_CheckGet(array('ajax'))) { $custmaps->renderItemsListJsonData($_GET['showitems']); } //render map items list container show_window(__('Objects') . ': ' . $custmaps->mapGetName($_GET['showitems']), $custmaps->renderItemsListFast($_GET['showitems'])); } else { //show duplicate map objects show_window(__('Show duplicates') . ': ' . $custmaps->mapGetName($_GET['showitems']), $custmaps->renderItemDuplicateList($_GET['showitems'])); } } } else { $mapId = $_GET['showmap']; $placemarks = ''; //additional centering and zoom if (wf_CheckGet(array('locateitem', 'zoom'))) { $custmaps->setCenter($_GET['locateitem']); $custmaps->setZoom($_GET['zoom']); $searchRadius = 30; $placemarks.=$custmaps->mapAddCircle($_GET['locateitem'], $searchRadius, __('Search area radius') . ' ' . $searchRadius . ' ' . __('meters'), __('Search area')); } $placemarks.= $custmaps->mapGetPlacemarks($mapId); //custom map layers processing if (wf_CheckGet(array('cl'))) { if (!empty($_GET['cl'])) { $custLayers = explode('z', $_GET['cl']); if (!empty($custLayers)) { foreach ($custLayers as $eachCustLayerId) { if (!empty($eachCustLayerId)) { $placemarks.=$custmaps->mapGetPlacemarks($eachCustLayerId); } } } } } if (wf_CheckGet(array('layers'))) { $layers = $_GET['layers']; //switches layer if (ispos($layers, 'sw')) { $placemarks.=sm_MapDrawSwitches(); } //switches uplinks layer if (ispos($layers, 'ul')) { $placemarks.=sm_MapDrawSwitchUplinks(); } //builds layer if (ispos($layers, 'bs')) { $placemarks.=um_MapDrawBuilds(); } } if (wf_CheckGet(array('mapedit', 'showmap'))) { $editor = $custmaps->mapLocationEditor(); } else { $editor = ''; } show_window($custmaps->mapGetName($mapId), $custmaps->mapInit($placemarks, $editor)); } } else { show_error(__('This module is disabled')); } } else { show_error(__('Access denied')); } ?>
l1ght13aby/Ubilling
modules/general/custmaps/index.php
PHP
gpl-2.0
6,971
/* lv2_event_helpers.h - Helper functions for the LV2 events extension. * * Copyright (C) 2008 Dave Robillard <dave@drobilla.net> * * This header 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 of the License, or * (at your option) any later version. * * This header 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 header; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA */ #ifndef LV2_EVENT_HELPERS_H #define LV2_EVENT_HELPERS_H #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <string.h> #include "lv2_event.h" /** @file * This header defines some helper functions for the the LV2 events extension * with URI <http://lv2plug.in/ns/ext/event> ('lv2ev'). * * These functions are provided for convenience only, use of them is not * required for supporting lv2ev (i.e. the events extension is defined by the * raw buffer format described in lv2_event.h and NOT by this API). * * Note that these functions are all static inline which basically means: * do not take the address of these functions. */ /** Pad a size to 64 bits (for event sizes) */ static inline uint16_t lv2_event_pad_size(uint16_t size) { return (size + 7) & (~7); } /** Initialize (empty, reset..) an existing event buffer. * The contents of buf are ignored entirely and overwritten, except capacity * which is unmodified. */ static inline void lv2_event_buffer_reset(LV2_Event_Buffer* buf, uint16_t stamp_type, uint8_t *data) { buf->data = data; buf->header_size = sizeof(LV2_Event_Buffer); buf->stamp_type = stamp_type; buf->event_count = 0; buf->size = 0; } /** Allocate a new, empty event buffer. */ static inline LV2_Event_Buffer* lv2_event_buffer_new(uint32_t capacity, uint16_t stamp_type) { LV2_Event_Buffer* buf = (LV2_Event_Buffer*)malloc(sizeof(LV2_Event_Buffer) + capacity); if (buf != NULL) { buf->capacity = capacity; lv2_event_buffer_reset(buf, stamp_type, (uint8_t *)(buf + 1)); return buf; } else { return NULL; } } /** An iterator over an LV2_Event_Buffer. * * Multiple simultaneous read iterators over a single buffer is fine, * but changing the buffer invalidates all iterators (e.g. RW Lock). */ typedef struct { LV2_Event_Buffer* buf; uint32_t offset; } LV2_Event_Iterator; /** Reset an iterator to point to the start of @a buf. * @return True if @a iter is valid, otherwise false (buffer is empty) */ static inline bool lv2_event_begin(LV2_Event_Iterator* iter, LV2_Event_Buffer* buf) { iter->buf = buf; iter->offset = 0; return (buf->size > 0); } /** Check if @a iter is valid.. * @return True if @a iter is valid, otherwise false (past end of buffer) */ static inline bool lv2_event_is_valid(LV2_Event_Iterator* iter) { return (iter->offset < iter->buf->size); } /** Advance @a iter forward one event. * @a iter must be valid. * @return True if @a iter is valid, otherwise false (reached end of buffer) */ static inline bool lv2_event_increment(LV2_Event_Iterator* iter) { assert(lv2_event_is_valid(iter)); LV2_Event* const ev = (LV2_Event*)( (uint8_t*)iter->buf->data + iter->offset); iter->offset += lv2_event_pad_size(sizeof(LV2_Event) + ev->size); return true; } /** Dereference an event iterator (get the event currently pointed at). * @a iter must be valid. * @a data if non-NULL, will be set to point to the contents of the event * returned. * @return A Pointer to the event @a iter is currently pointing at, or NULL * if the end of the buffer is reached (in which case @a data is * also set to NULL). */ static inline LV2_Event* lv2_event_get(LV2_Event_Iterator* iter, uint8_t** data) { assert(lv2_event_is_valid(iter)); LV2_Event* const ev = (LV2_Event*)( (uint8_t*)iter->buf->data + iter->offset); if (data) *data = (uint8_t*)ev + sizeof(LV2_Event); return ev; } /** Get the type of the non-POD event referenced by an event iterator. * @a iter must be valid. * @return The type of the non-POD event, or 0 if the event is not non-POD. */ static inline uint16_t lv2_event_get_nonpod_type(LV2_Event_Iterator* iter) { assert(lv2_event_is_valid(iter)); LV2_Event* const ev = (LV2_Event*)( (uint8_t*)iter->buf->data + iter->offset); if (ev->type != 0 || ev->size < 2) return 0; return *(uint16_t*)((uint8_t*)ev + sizeof(LV2_Event)); } /** Write an event at @a iter. * The event (if any) pointed to by @iter will be overwritten, and @a iter * incremented to point to the following event (i.e. several calls to this * function can be done in sequence without twiddling iter in-between). * @return True if event was written, otherwise false (buffer is full). */ static inline bool lv2_event_write(LV2_Event_Iterator* iter, uint32_t frames, uint32_t subframes, uint16_t type, uint16_t size, const uint8_t* data) { if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + size) return false; LV2_Event* const ev = (LV2_Event*)( (uint8_t*)iter->buf->data + iter->offset); ev->frames = frames; ev->subframes = subframes; ev->type = type; ev->size = size; memcpy((uint8_t*)ev + sizeof(LV2_Event), data, size); ++iter->buf->event_count; size = lv2_event_pad_size(sizeof(LV2_Event) + size); iter->buf->size += size; iter->offset += size; return true; } /** Reserve space for an event in the buffer and return a pointer to * the memory where the caller can write the event data, or NULL if there * is not enough room in the buffer. */ static inline uint8_t* lv2_event_reserve(LV2_Event_Iterator* iter, uint32_t frames, uint32_t subframes, uint16_t type, uint16_t size) { size = lv2_event_pad_size(size); if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + size) return NULL; LV2_Event* const ev = (LV2_Event*)((uint8_t*)iter->buf->data + iter->offset); ev->frames = frames; ev->subframes = subframes; ev->type = type; ev->size = size; ++iter->buf->event_count; size = lv2_event_pad_size(sizeof(LV2_Event) + size); iter->buf->size += size; iter->offset += size; return (uint8_t*)ev + sizeof(LV2_Event); } /** Write an event at @a iter. * The event (if any) pointed to by @iter will be overwritten, and @a iter * incremented to point to the following event (i.e. several calls to this * function can be done in sequence without twiddling iter in-between). * @return True if event was written, otherwise false (buffer is full). */ static inline bool lv2_event_write_event(LV2_Event_Iterator* iter, const LV2_Event* ev, const uint8_t* data) { if (iter->buf->capacity - iter->buf->size < sizeof(LV2_Event) + ev->size) return false; LV2_Event* const write_ev = (LV2_Event*)( (uint8_t*)iter->buf->data + iter->offset); *write_ev = *ev; memcpy((uint8_t*)write_ev + sizeof(LV2_Event), data, ev->size); ++iter->buf->event_count; const uint16_t size = lv2_event_pad_size(sizeof(LV2_Event) + ev->size); iter->buf->size += size; iter->offset += size; return true; } #endif // LV2_EVENT_HELPERS_H
artm/Audacity-for-Watch-That-Sound
src/effects/lv2/lv2_event_helpers.h
C
gpl-2.0
8,518
/* * xplus4-main.c - Watcom main.c for xplus4 wrapper. * * Written by * Marco van den Heuvel <blackystardust68@yahoo.com> * * This file is part of VICE, the Versatile Commodore Emulator. * See README for copyright notice. * * 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 "main.c"
AreaScout/vice-gles2
src/arch/watcom-source-wrappers/xplus4-main.c
C
gpl-2.0
987
/* * Copyright (c) 2008, 2010, 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 com.codename1.ui; import com.codename1.ui.animations.CommonTransitions; import com.codename1.ui.animations.Transition; import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import com.codename1.ui.geom.Rectangle; import com.codename1.impl.VirtualKeyboardInterface; import com.codename1.ui.layouts.BorderLayout; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.plaf.Style; import com.codename1.ui.plaf.UIManager; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * This class represent the Codename One Light Weight Virtual Keyboard * * @author Chen Fishbein */ public class VirtualKeyboard extends Dialog implements VirtualKeyboardInterface{ private static final String MARKER_COMMIT_ON_DISPOSE = "$VKB_COM$"; private static final String MARKER_TINT_COLOR = "$VKB_TINT$"; private static final String MARKER_VKB = "$VKB$"; private static Transition transitionIn = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500); private static Transition transitionOut = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500); private int inputType; /** * This keymap represents qwerty keyboard */ public static final String[][] DEFAULT_QWERTY = new String[][]{ {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}, {"a", "s", "d", "f", "g", "h", "j", "k", "l"}, {"$Shift$", "z", "x", "c", "v", "b", "n", "m", "$Delete$"}, {"$Mode$", "$T9$", "$Space$", "$OK$"} }; /** * This keymap represents numbers keyboard */ public static final String[][] DEFAULT_NUMBERS = new String[][]{ {"1", "2", "3",}, {"4", "5", "6",}, {"7", "8", "9",}, {"*", "0", "#",}, {"$Mode$", "$Space$", "$Delete$", "$OK$"} }; /** * This keymap represents numbers and symbols keyboard */ public static final String[][] DEFAULT_NUMBERS_SYMBOLS = new String[][]{ {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}, {"-", "/", ":", ";", "(", ")", "$", "&", "@"}, {".", ",", "?", "!", "'", "\"", "$Delete$"}, {"$Mode$", "$Space$", "$OK$"} }; /** * This keymap represents symbols keyboard */ public static final String[][] DEFAULT_SYMBOLS = new String[][]{ {"[", "]", "{", "}", "#", "%", "^", "*", "+", "="}, {"_", "\\", "|", "~", "<", ">", "\u00A3", "\u00A5"}, {":-0", ";-)", ":-)", ":-(", ":P", ":D", "$Delete$"}, {"$Mode$", "$Space$", "$OK$"} }; /** * The String that represent the qwerty mode. */ public static final String QWERTY_MODE = "ABC"; /** * The String that represent the numbers mode. */ public static final String NUMBERS_MODE = "123"; /** * The String that represent the numbers sybols mode. */ public static final String NUMBERS_SYMBOLS_MODE = ".,123"; /** * The String that represent the symbols mode. */ public static final String SYMBOLS_MODE = ".,?"; private static Hashtable modesMap = new Hashtable(); private static String[] defaultInputModeOrder = {QWERTY_MODE, NUMBERS_SYMBOLS_MODE, NUMBERS_MODE, SYMBOLS_MODE}; private String currentMode = defaultInputModeOrder[0]; private String[] inputModeOrder = defaultInputModeOrder; private TextField inputField; private Container buttons = new Container(new BoxLayout(BoxLayout.Y_AXIS)); private TextPainter txtPainter = new TextPainter(); private boolean upperCase = false; private Button currentButton; public static final int INSERT_CHAR = 1; public static final int DELETE_CHAR = 2; public static final int CHANGE_MODE = 3; public static final int SHIFT = 4; public static final int OK = 5; public static final int SPACE = 6; public static final int T9 = 7; private Hashtable specialButtons = new Hashtable(); private TextArea field; private boolean finishedT9Edit = true; private String originalText; private boolean useSoftKeys = false; private static boolean showTooltips = true; private boolean okPressed; private static Class vkbClass; private VirtualKeyboard vkb; public final static String NAME = "CodenameOne_VirtualKeyboard"; private boolean isShowing = false; private static Hashtable defaultInputModes = null; /** * Creates a new instance of VirtualKeyboard */ public VirtualKeyboard() { setLayout(new BorderLayout()); setDialogUIID("Container"); getContentPane().setUIID("VKB"); setAutoDispose(false); setDisposeWhenPointerOutOfBounds(true); setTransitionInAnimator(transitionIn); setTransitionOutAnimator(transitionOut); getTitleComponent().getParent().removeComponent(getTitleComponent()); if(showTooltips) { setGlassPane(txtPainter); } } public void setInputType(int inputType) { if((inputType & TextArea.NUMERIC) == TextArea.NUMERIC || (inputType & TextArea.PHONENUMBER) == TextArea.PHONENUMBER) { setInputModeOrder(new String []{NUMBERS_MODE}); return; } if((inputType & TextArea.DECIMAL) == TextArea.DECIMAL) { setInputModeOrder(new String []{NUMBERS_SYMBOLS_MODE}); return; } setInputModeOrder(defaultInputModeOrder); } static class InputField extends TextField { private TextArea field; InputField(TextArea field) { this.field = field; setInputMode(field.getInputMode()); setConstraint(field.getConstraint()); } public boolean hasFocus() { return true; } public String getUIID() { return "VKBTextInput"; } public void deleteChar() { super.deleteChar(); field.setText(getText()); if (field instanceof TextField) { ((TextField) field).setCursorPosition(getCursorPosition()); } } public void setCursorPosition(int i) { super.setCursorPosition(i); // this can happen since this method is invoked from a constructor of the base class... if(field != null && field.getText().length() > i && field instanceof TextField) { ((TextField) field).setCursorPosition(i); } } public void setText(String t) { super.setText(t); // this can happen since this method is invoked from a constructor of the base class... if(field != null) { // mirror events into the parent field.setText(t); } } public boolean validChar(String c) { if (field instanceof TextField) { return ((TextField) field).validChar(c); } return true; } } /** * Invoked internally by the implementation to indicate the text field that will be * edited by the virtual keyboard * * @param field the text field instance */ public void setTextField(final TextArea field) { this.field = field; removeAll(); okPressed = false; if(field instanceof TextField){ useSoftKeys = ((TextField)field).isUseSoftkeys(); ((TextField)field).setUseSoftkeys(false); } originalText = field.getText(); inputField = new InputField(field); inputField.setText(originalText); inputField.setCursorPosition(field.getCursorPosition()); inputField.setConstraint(field.getConstraint()); inputField.setInputModeOrder(new String[]{"ABC"}); inputField.setMaxSize(field.getMaxSize()); initModes(); setInputType(field.getConstraint()); initSpecialButtons(); addComponent(BorderLayout.NORTH, inputField); buttons.getStyle().setPadding(0, 0, 0, 0); addComponent(BorderLayout.CENTER, buttons); initInputButtons(upperCase); inputField.setUseSoftkeys(false); applyRTL(false); } /** * @inheritDoc */ public void show() { super.showPacked(BorderLayout.SOUTH, true); } /** * @inheritDoc */ protected void autoAdjust(int w, int h) { //if the t9 input is currently editing do not dispose dialog if (finishedT9Edit) { setTransitionOutAnimator(CommonTransitions.createEmpty()); dispose(); } } /** * init all virtual keyboard modes, such as QWERTY_MODE, NUMBERS_SYMBOLS_MODE... * to add an addtitional mode a developer needs to override this method and * add a mode by calling addInputMode method */ protected void initModes() { addInputMode(QWERTY_MODE, DEFAULT_QWERTY); addInputMode(NUMBERS_SYMBOLS_MODE, DEFAULT_NUMBERS_SYMBOLS); addInputMode(SYMBOLS_MODE, DEFAULT_SYMBOLS); addInputMode(NUMBERS_MODE, DEFAULT_NUMBERS); if(defaultInputModes != null) { Enumeration e = defaultInputModes.keys(); while(e.hasMoreElements()) { String key = (String)e.nextElement(); addInputMode(key, (String[][])defaultInputModes.get(key)); } } } /** * Sets the current virtual keyboard mode. * * @param mode the String that represents the mode(QWERTY_MODE, * SYMBOLS_MODE, ...) */ protected void setCurrentMode(String mode) { this.currentMode = mode; } /** * Gets the current mode. * * @return the String that represents the current mode(QWERTY_MODE, * SYMBOLS_MODE, ...) */ protected String getCurrentMode() { return currentMode; } private void initInputButtons(boolean upperCase) { buttons.removeAll(); int largestLine = 0; String[][] currentKeyboardChars = (String[][]) modesMap.get(currentMode); for (int i = 1; i < currentKeyboardChars.length; i++) { if (currentKeyboardChars[i].length > currentKeyboardChars[largestLine].length) { largestLine = i; } } int length = currentKeyboardChars[largestLine].length; if(length == 0) { return; } Button dummy = createButton(new Command("dummy"), 0); int buttonMargins = dummy.getUnselectedStyle().getMargin(dummy.isRTL(), LEFT) + dummy.getUnselectedStyle().getMargin(dummy.isRTL(), RIGHT); Container row = null; int rowW = (Display.getInstance().getDisplayWidth() - getDialogStyle().getPadding(false, LEFT) - getDialogStyle().getPadding(false, RIGHT) - getDialogStyle().getMargin(false, LEFT) - getDialogStyle().getMargin(false, RIGHT)); int availableSpace = rowW - length * buttonMargins; int buttonSpace = (availableSpace) / length; for (int i = 0; i < currentKeyboardChars.length; i++) { int rowWidth = rowW; row = new Container(new BoxLayout(BoxLayout.X_AXIS)); row.getUnselectedStyle().setMargin(0, 0, 0, 0); Vector specialsButtons = new Vector(); for (int j = 0; j < currentKeyboardChars[i].length; j++) { String txt = currentKeyboardChars[i][j]; Button b = null; if (txt.startsWith("$") && txt.endsWith("$") && txt.length() > 1) { //add a special button Button cmd = (Button) specialButtons.get(txt.substring(1, txt.length() - 1)); Command c = null; int prefW = 0; if(cmd != null){ c = cmd.getCommand(); int space = ((Integer) cmd.getClientProperty("space")).intValue(); if (space != -1) { prefW = availableSpace * space / 100; } } b = createButton(c, prefW, "VKBSpecialButton"); if (prefW != 0) { rowWidth -= (b.getPreferredW() + buttonMargins); } else { //if we can't determind the size at this stage, wait until //the loops ends and give the remains size to the special //button specialsButtons.addElement(b); } } else { if (upperCase) { txt = txt.toUpperCase(); } b = createInputButton(txt, buttonSpace); rowWidth -= (b.getPreferredW() + buttonMargins); } if (currentButton != null) { if (currentButton.getCommand() != null && b.getCommand() != null && currentButton.getCommand().getId() == b.getCommand().getId()) { currentButton = b; } if (currentButton.getText().equals(b.getText())) { currentButton = b; } } row.addComponent(b); } int emptySpace = Math.max(rowWidth, 0); //if we have special buttons on the keyboard give them the size or //else give the remain size to the row margins if (specialsButtons.size() > 0) { int prefW = emptySpace / specialsButtons.size(); for (int j = 0; j < specialsButtons.size(); j++) { Button special = (Button) specialsButtons.elementAt(j); special.setPreferredW(prefW); } } else { row.getUnselectedStyle().setPadding(Component.LEFT, 0); row.getUnselectedStyle().setPadding(Component.RIGHT, 0); row.getUnselectedStyle().setMarginUnit(new byte[]{Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS}); row.getUnselectedStyle().setMargin(Component.LEFT, emptySpace / 2); row.getUnselectedStyle().setMargin(Component.RIGHT, emptySpace / 2); } buttons.addComponent(row); } applyRTL(false); } private Button createInputButton(String text, int prefSize) { Button b = createButton(new Command(text, INSERT_CHAR), prefSize); b.putClientProperty("glasspane", "true"); return b; } private Button createButton(Command cmd, int prefSize) { return createButton(cmd, prefSize, "VKBButton"); } private Button createButton(Command cmd, int prefSize, String uiid) { Button btn; if(cmd != null){ btn = new Button(cmd); }else{ btn = new Button(); btn.setVisible(false); } final Button b = btn; b.setUIID(uiid); b.setEndsWith3Points(false); b.setAlignment(Component.CENTER); prefSize = Math.max(prefSize, b.getPreferredW()); b.setPreferredW(prefSize); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { currentButton = b; } }); return b; } /** * Add an input mode to the virtual keyboard * * @param mode a string that represents the identifier of the mode * @param inputChars 2 dimensional String array that contains buttons String * and special buttons (a special button is identified with $...$ marks * e.g: "$Space$") */ public static void addDefaultInputMode(String mode, String[][] inputChars) { if(defaultInputModes == null) { defaultInputModes = new Hashtable(); } defaultInputModes.put(mode, inputChars); } /** * Add an input mode to the virtual keyboard * * @param mode a string that represents the identifier of the mode * @param inputChars 2 dimentional String array that contains buttons String * and special buttons (a special button is identified with $...$ marks * e.g: "$Space$") */ public void addInputMode(String mode, String[][] inputChars) { modesMap.put(mode, inputChars); } /** * This method adds a special button to the virtual keyboard * * @param key the string identifier from within the relevant input mode * @param cmd the Command to invoke when this button is invoked. */ public void addSpecialButton(String key, Command cmd) { addSpecialButton(key, cmd, -1); } /** * This method adds a special button to the virtual keyboard * * @param key the string identifier from within the relevant input mode * @param cmd the Command to invoke when this button is invoked. * @param space how much space in percentage from the overall row * the special button should occupy */ public void addSpecialButton(String key, Command cmd, int space) { Button b = new Button(cmd); b.putClientProperty("space", new Integer(space)); specialButtons.put(key, b); } private String getNextMode(String current) { for (int i = 0; i < inputModeOrder.length - 1; i++) { String mode = inputModeOrder[i]; if(mode.equals(current)){ return inputModeOrder[i + 1]; } } return inputModeOrder[0]; } /** * @inheritDoc */ public void pointerPressed(int x, int y) { super.pointerPressed(x, y); Component cmp = getComponentAt(x, y); if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) { txtPainter.showButtonOnGlasspane((Button) cmp); } } /** * @inheritDoc */ public void pointerDragged(int x, int y) { super.pointerDragged(x, y); Component cmp = getComponentAt(x, y); if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) { txtPainter.showButtonOnGlasspane((Button) cmp); } } /** * @inheritDoc */ public void pointerReleased(int x, int y) { if(showTooltips) { txtPainter.clear(); } super.pointerReleased(x, y); } /** * This method initialize all the virtual keyboard special buttons. */ protected void initSpecialButtons() { //specialButtons.clear(); addSpecialButton("Shift", new Command("SH", SHIFT), 15); addSpecialButton("Delete", new Command("Del", DELETE_CHAR), 15); addSpecialButton("T9", new Command("T9", T9), 15); addSpecialButton("Mode", new Command(getNextMode(currentMode), CHANGE_MODE)); addSpecialButton("Space", new Command("Space", SPACE), 50); addSpecialButton("OK", new Command("Ok", OK)); } /** * Returns the order in which input modes are toggled * * @return the order of the input modes */ public String[] getInputModeOrder() { return inputModeOrder; } /** * Sets the order in which input modes are toggled and allows disabling/hiding * an input mode * * @param order the order for the input modes in this field */ public void setInputModeOrder(String[] order) { inputModeOrder = order; setCurrentMode(order[0]); } /** * Returns the order in which input modes are toggled by default * * @return the default order of the input mode */ public static String[] getDefaultInputModeOrder() { return defaultInputModeOrder; } /** * Sets the order in which input modes are toggled by default and allows * disabling/hiding an input mode * * @param order the order for the input modes in all future created fields */ public static void setDefaultInputModeOrder(String[] order) { defaultInputModeOrder = order; } class TextPainter implements Painter { private Label label = new Label(); private boolean paint = true; public TextPainter() { label = new Label(); label.setUIID("VKBtooltip"); } public void showButtonOnGlasspane(Button button) { if(label.getText().equals(button.getText())){ return; } paint = true; repaint(label.getAbsoluteX()-2, label.getAbsoluteY()-2, label.getWidth()+4, label.getHeight()+4); label.setText(button.getText()); label.setSize(label.getPreferredSize()); label.setX(button.getAbsoluteX() + (button.getWidth() - label.getWidth()) / 2); label.setY(button.getAbsoluteY() - label.getPreferredH() * 4 / 3); repaint(label.getAbsoluteX()-2, label.getAbsoluteY()-2, label.getPreferredW()+4, label.getPreferredH()+4); } public void paint(Graphics g, Rectangle rect) { if (paint) { label.paintComponent(g); } } private void clear() { paint = false; repaint(); } } private void updateText(String txt) { field.setText(txt); if(field instanceof TextField){ ((TextField)field).setCursorPosition(txt.length()); } if(okPressed){ field.fireActionEvent(); if(field instanceof TextField){ ((TextField)field).fireDoneEvent(); } } } /** * @inheritDoc */ protected void actionCommand(Command cmd) { super.actionCommand(cmd); switch (cmd.getId()) { case OK: okPressed = true; updateText(inputField.getText()); dispose(); break; case INSERT_CHAR: Button btn = currentButton; String text = btn.getText(); if (inputField.getText().length() == 0) { inputField.setText(text); inputField.setCursorPosition(text.length()); } else { inputField.insertChars(text); } break; case SPACE: if (inputField.getText().length() == 0) { inputField.setText(" "); } else { inputField.insertChars(" "); } break; case DELETE_CHAR: inputField.deleteChar(); break; case CHANGE_MODE: currentMode = getNextMode(currentMode); Display.getInstance().callSerially(new Runnable() { public void run() { initInputButtons(upperCase); String next = getNextMode(currentMode); currentButton.setText(next); currentButton.getCommand().setCommandName(next); setTransitionOutAnimator(CommonTransitions.createEmpty()); setTransitionInAnimator(CommonTransitions.createEmpty()); revalidate(); show(); } }); return; case SHIFT: if (currentMode.equals(QWERTY_MODE)) { upperCase = !upperCase; Display.getInstance().callSerially(new Runnable() { public void run() { initInputButtons(upperCase); revalidate(); } }); } return; case T9: finishedT9Edit = false; if(field != null){ Display.getInstance().editString(field, field.getMaxSize(), field.getConstraint(), field.getText()); }else{ Display.getInstance().editString(inputField, inputField.getMaxSize(), inputField.getConstraint(), inputField.getText()); } dispose(); finishedT9Edit = true; } } /** * @inheritDoc */ public void dispose() { if (field != null) { if (!okPressed && !isCommitOnDispose(field) && finishedT9Edit) { field.setText(originalText); } if(field instanceof TextField){ ((TextField)field).setUseSoftkeys(useSoftKeys); } setTransitionInAnimator(transitionIn); field = null; } currentMode = inputModeOrder[0]; super.dispose(); } /** * @inheritDoc */ protected void onShow() { super.onShow(); setTransitionOutAnimator(transitionOut); } /** * This method returns the Virtual Keyboard TextField. * * @return the the Virtual Keyboard TextField. */ protected TextField getInputField() { return inputField; } /** * Indicates whether the VKB should commit changes to the text field when the VKB * is closed not via the OK button. This might be useful for some situations such * as searches * * @param tf the text field to mark as commit on dispose * @param b the value of commit on dispose, true to always commit changes */ public static void setCommitOnDispose(TextField tf, boolean b) { tf.putClientProperty(MARKER_COMMIT_ON_DISPOSE, new Boolean(b)); } /** * This method is used to bind a specific instance of a virtual keyboard to a specific TextField. * For example if a specific TextField requires only numeric input consider using this method as follows: * * TextField tf = new TextField(); * tf.setConstraint(TextField.NUMERIC); * tf.setInputModeOrder(new String[]{"123"}); * VirtualKeyboard vkb = new VirtualKeyboard(); * vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE}); * VirtualKeyboard.bindVirtualKeyboard(tf, vkb); * * @param t the TextField to bind a VirualKeyboard to. * @param vkb the binded VirualKeyboard. */ public static void bindVirtualKeyboard(TextArea t, VirtualKeyboard vkb) { t.putClientProperty(MARKER_VKB, vkb); } /** * This method returns the Textfield associated VirtualKeyboard, * see bindVirtualKeyboard(TextField tf, VirtualKeyboard vkb) method. * * @param t a TextField.that might have an associated VirtualKeyboard instance * @return a VirtualKeyboard instance or null if not exists. */ public static VirtualKeyboard getVirtualKeyboard(TextArea t) { return (VirtualKeyboard) t.getClientProperty(MARKER_VKB); } /** * Indicates whether the given text field should commit on dispose * * @param tf the text field * @return true if the text field should save the data despite the fact that it * was disposed in an irregular way */ public static boolean isCommitOnDispose(TextArea tf) { Boolean b = (Boolean)tf.getClientProperty(MARKER_COMMIT_ON_DISPOSE); return (b != null) && b.booleanValue(); } /** * Sets the tint color for the virtual keyboard when shown on top of this text field * see the form tint methods for more information * * @param tf the relevant text field * @param tint the tint color with an alpha channel */ public static void setVKBTint(TextField tf, int tint) { tf.putClientProperty(MARKER_TINT_COLOR, new Integer(tint)); } /** * The tint color for the virtual keyboard when shown on top of this text field * see the form tint methods for more information * * @param tf the relevant text field * @return the tint color with an alpha channel */ public static int getVKBTint(TextArea tf) { Integer v = (Integer)tf.getClientProperty(MARKER_TINT_COLOR); if(v != null) { return v.intValue(); } Form current = Display.getInstance().getCurrent(); return current.getUIManager().getLookAndFeel().getDefaultFormTintColor(); } /** * Indicates whether tooltips should be shown when the keys in the VKB are pressed * * @return the showTooltips */ public static boolean isShowTooltips() { return showTooltips; } /** * Indicates whether tooltips should be shown when the keys in the VKB are pressed * * @param aShowTooltips true to show tooltips */ public static void setShowTooltips(boolean aShowTooltips) { showTooltips = aShowTooltips; } /** * The transition in for the VKB * * @return the transitionIn */ public static Transition getTransitionIn() { return transitionIn; } /** * The transition in for the VKB * * @param aTransitionIn the transitionIn to set */ public static void setTransitionIn(Transition aTransitionIn) { transitionIn = aTransitionIn; } /** * The transition out for the VKB * * @return the transitionOut */ public static Transition getTransitionOut() { return transitionOut; } /** * The transition out for the VKB * * @param aTransitionOut the transitionOut to set */ public static void setTransitionOut(Transition aTransitionOut) { transitionOut = aTransitionOut; } /** * Shows the virtual keyboard that is assoiciated with the displayed TextField * or displays the default virtual keyboard. * * @param show it show is true open the relevant keyboard, if close dispose * the displayed keyboard */ public void showKeyboard(boolean show) { isShowing = show; Form current = Display.getInstance().getCurrent(); if (show) { Component foc = current.getFocused(); if(foc instanceof Container) { foc = ((Container)foc).getLeadComponent(); } TextArea txtCmp = (TextArea) foc; if (txtCmp != null) { if(vkb != null && vkb.contains(txtCmp)){ return; } vkb = VirtualKeyboard.getVirtualKeyboard(txtCmp); if(vkb == null){ vkb = createVirtualKeyboard(); } vkb.setTextField(txtCmp); int oldTint = current.getTintColor(); current.setTintColor(VirtualKeyboard.getVKBTint(txtCmp)); boolean third = com.codename1.ui.Display.getInstance().isThirdSoftButton(); com.codename1.ui.Display.getInstance().setThirdSoftButton(false); boolean qwerty = txtCmp.isQwertyInput(); if(txtCmp instanceof TextField){ ((TextField) txtCmp).setQwertyInput(true); } vkb.showDialog(); if (txtCmp instanceof TextField) { ((TextField) txtCmp).setQwertyInput(qwerty); } com.codename1.ui.Display.getInstance().setThirdSoftButton(third); current.setTintColor(oldTint); } } } /** * Sets the default virtual keyboard class for the com.codename1.ui.VirtualKeyboard * type * This class is used as the default virtual keyboard class if the current * platform VirtualKeyboard is com.codename1.ui.VirtualKeyboard. * Platform VirtualKeyboard is defined here: * Display.getIntance().setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb) * * @param vkbClazz this class must extend VirtualKeyboard. */ public static void setDefaultVirtualKeyboardClass(Class vkbClazz){ vkbClass = vkbClazz; } private VirtualKeyboard createVirtualKeyboard() { try { if(vkbClass != null){ return (VirtualKeyboard) vkbClass.newInstance(); }else{ return new VirtualKeyboard(); } } catch (Exception ex) { ex.printStackTrace(); return new VirtualKeyboard(); } } /** * @see VirtualKeyboardInterface */ public String getVirtualKeyboardName() { return NAME; } /** * @see VirtualKeyboardInterface */ public boolean isVirtualKeyboardShowing() { return isShowing; } }
skyHALud/codenameone
CodenameOne/src/com/codename1/ui/VirtualKeyboard.java
Java
gpl-2.0
34,489
<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="../../common/docs.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale = 1.0" /> <link href="/assets/favicon.ico" rel="shortcut icon" /> <title>Webix : Samples</title></title> </head> <body> <div class='abstop_header'> <div class='content_area'> &nbsp; </div> </div> <div class="page_header"> <div class='page_inner_header'> <a href='http://webix.com'><div class='top_webix_logo'></div></a> Samples </div> </div> <div class="page_space"> <div class="webixdoc_page webixdoc_start"> <div id="webixContent" class='webixdoc_content'> <div class="webixdoc_content_inner"> <div class="webixdoc_breadcrumb nav_breadcrumb"> <a href="http://docs.webix.com/" class="webixdoc_back">Documentation</a> <a href="../../index.html" class="webixdoc_back">Samples</a> <a href='../index.html' class='webixdoc_back'>17 Datatree</a><a href='../../index.html' class='webixdoc_back'>04 Api</a> </div> <table class='nav_table'> <tr> <td style='width:30px;'> <a href='01_selection.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='01_selection.html'>Selection</a> </td> </tr> <tr> <td style='width:30px;'> <a href='02_sort.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='02_sort.html'>Sorting</a> </td> </tr> <tr> <td style='width:30px;'> <a href='03_filter.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='03_filter.html'>Filtering</a> </td> </tr> <tr> <td style='width:30px;'> <a href='04_multi_select.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='04_multi_select.html'>Multiline Selection</a> </td> </tr> <tr> <td style='width:30px;'> <a href='05_sort_custom.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='05_sort_custom.html'>Custom Sorting</a> </td> </tr> <tr> <td style='width:30px;'> <a href='06_add_delete.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='06_add_delete.html'>Adding and deleting Nodes</a> </td> </tr> <tr> <td style='width:30px;'> <a href='07_sync.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='07_sync.html'>Data sync</a> </td> </tr> <tr> <td style='width:30px;'> <a href='08_bind.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='08_bind.html'>Data binding</a> </td> </tr> <tr> <td style='width:30px;'> <a href='09_subdata.html'><div class='nav_folder_img'>&nbsp;</div></a> </td><td> <a href='09_subdata.html'>Data binding - subdata</a> </td> </tr> </table> </div> </div> </div> </div> </body> </html>
Hana-Lee/web-sentence-generator
web/js/webix/samples/17_datatree/04_api/index.html
HTML
gpl-2.0
2,877
<?php /** * File containing the eZProductCollectionTest class * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.07.0 * @package tests */ class eZProductCollectionTest extends ezpDatabaseTestCase { protected $backupGlobals = false; /** * Unit test for eZProductCollection::cleanupList() * * Outline: * 1) Create 10 eZProductCollection objects * 2) Pick 5 random ID of created items * 3) Call cleanupList() on these 5 items * 4) Check that the 5 items have been removed * 5) Check that the 5 other items haven't been removed */ public function testCleanupList() { // Create a few collections $row = array( 'created' => time(), 'currency_code' => 'EUR' ); $collection = new eZProductCollection( $row ); $collection->store(); $collectionIDArray[] = $collection->attribute( 'id' ); for( $i = 0; $i < 1500; $i++ ) { $newCollection = $collection->copy(); $collectionIDArray[] = $newCollection->attribute( 'id' ); } // pick a few random ID to delete $deleteIDArray = array_rand( $collectionIDArray, round( count( $collectionIDArray ) / 2 ) ); $remainingIDArray = array_diff( $collectionIDArray, $deleteIDArray ); eZProductCollection::cleanupList( $deleteIDArray ); // Check that each item of deleteIDArray has been removed foreach( $deleteIDArray as $id ) { $this->assertNull( eZProductCollection::fetch( $id ) ); } // And check that each item of remainingIDArray hasn't been deleted foreach( $remainingIDArray as $id ) { $this->assertInstanceOf( 'eZProductCollection', eZProductCollection::fetch( $id ) ); } } } ?>
tonvinh/ez
ezpublish_legacy/tests/tests/kernel/classes/ezproductcollection_test.php
PHP
gpl-2.0
1,934
/* * Copyright (c) 2016, 2018, 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. * * 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 org.graalvm.compiler.lir.asm; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import org.graalvm.compiler.core.common.type.DataPointerConstant; /** * Class for chunks of data that go into the data section. */ public class ArrayDataPointerConstant extends DataPointerConstant { private final byte[] data; public ArrayDataPointerConstant(byte[] array, int alignment) { super(alignment); data = array.clone(); } public ArrayDataPointerConstant(short[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 2); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asShortBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(int[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asIntBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(float[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asFloatBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(double[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asDoubleBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(long[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asLongBuffer().put(array); data = byteBuffer.array(); } @Override public boolean isDefaultForKind() { return false; } @Override public void serialize(ByteBuffer buffer) { buffer.put(data); } @Override public int getSerializedSize() { return data.length; } @Override public String toValueString() { return "ArrayDataPointerConstant" + Arrays.toString(data); } }
md-5/jdk10
src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir/src/org/graalvm/compiler/lir/asm/ArrayDataPointerConstant.java
Java
gpl-2.0
3,453