repo_name
string
path
string
copies
string
size
string
content
string
license
string
Evervolv/android_kernel_grouper
drivers/ata/pata_rb532_cf.c
3094
5560
/* * A low-level PATA driver to handle a Compact Flash connected on the * Mikrotik's RouterBoard 532 board. * * Copyright (C) 2007 Gabor Juhos <juhosg at openwrt.org> * Copyright (C) 2008 Florian Fainelli <florian@openwrt.org> * * This file was based on: drivers/ata/pata_ixp4xx_cf.c * Copyright (C) 2006-07 Tower Technologies * Author: Alessandro Zummo <a.zummo@towertech.it> * * Also was based on the driver for Linux 2.4.xx published by Mikrotik for * their RouterBoard 1xx and 5xx series devices. The original Mikrotik code * seems not to have a license. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/gfp.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/libata.h> #include <scsi/scsi_host.h> #include <asm/gpio.h> #define DRV_NAME "pata-rb532-cf" #define DRV_VERSION "0.1.0" #define DRV_DESC "PATA driver for RouterBOARD 532 Compact Flash" #define RB500_CF_MAXPORTS 1 #define RB500_CF_IO_DELAY 400 #define RB500_CF_REG_BASE 0x0800 #define RB500_CF_REG_ERR 0x080D #define RB500_CF_REG_CTRL 0x080E /* 32bit buffered data register offset */ #define RB500_CF_REG_DBUF32 0x0C00 struct rb532_cf_info { void __iomem *iobase; unsigned int gpio_line; unsigned int irq; }; /* ------------------------------------------------------------------------ */ static irqreturn_t rb532_pata_irq_handler(int irq, void *dev_instance) { struct ata_host *ah = dev_instance; struct rb532_cf_info *info = ah->private_data; if (gpio_get_value(info->gpio_line)) { irq_set_irq_type(info->irq, IRQ_TYPE_LEVEL_LOW); ata_sff_interrupt(info->irq, dev_instance); } else { irq_set_irq_type(info->irq, IRQ_TYPE_LEVEL_HIGH); } return IRQ_HANDLED; } static struct ata_port_operations rb532_pata_port_ops = { .inherits = &ata_sff_port_ops, .sff_data_xfer = ata_sff_data_xfer32, }; /* ------------------------------------------------------------------------ */ static struct scsi_host_template rb532_pata_sht = { ATA_PIO_SHT(DRV_NAME), }; /* ------------------------------------------------------------------------ */ static void rb532_pata_setup_ports(struct ata_host *ah) { struct rb532_cf_info *info = ah->private_data; struct ata_port *ap; ap = ah->ports[0]; ap->ops = &rb532_pata_port_ops; ap->pio_mask = ATA_PIO4; ap->ioaddr.cmd_addr = info->iobase + RB500_CF_REG_BASE; ap->ioaddr.ctl_addr = info->iobase + RB500_CF_REG_CTRL; ap->ioaddr.altstatus_addr = info->iobase + RB500_CF_REG_CTRL; ata_sff_std_ports(&ap->ioaddr); ap->ioaddr.data_addr = info->iobase + RB500_CF_REG_DBUF32; ap->ioaddr.error_addr = info->iobase + RB500_CF_REG_ERR; } static __devinit int rb532_pata_driver_probe(struct platform_device *pdev) { int irq; int gpio; struct resource *res; struct ata_host *ah; struct rb532_cf_info *info; int ret; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "no IOMEM resource found\n"); return -EINVAL; } irq = platform_get_irq(pdev, 0); if (irq <= 0) { dev_err(&pdev->dev, "no IRQ resource found\n"); return -ENOENT; } gpio = irq_to_gpio(irq); if (gpio < 0) { dev_err(&pdev->dev, "no GPIO found for irq%d\n", irq); return -ENOENT; } ret = gpio_request(gpio, DRV_NAME); if (ret) { dev_err(&pdev->dev, "GPIO request failed\n"); return ret; } /* allocate host */ ah = ata_host_alloc(&pdev->dev, RB500_CF_MAXPORTS); if (!ah) return -ENOMEM; platform_set_drvdata(pdev, ah); info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; ah->private_data = info; info->gpio_line = gpio; info->irq = irq; info->iobase = devm_ioremap_nocache(&pdev->dev, res->start, resource_size(res)); if (!info->iobase) return -ENOMEM; ret = gpio_direction_input(gpio); if (ret) { dev_err(&pdev->dev, "unable to set GPIO direction, err=%d\n", ret); goto err_free_gpio; } rb532_pata_setup_ports(ah); ret = ata_host_activate(ah, irq, rb532_pata_irq_handler, IRQF_TRIGGER_LOW, &rb532_pata_sht); if (ret) goto err_free_gpio; return 0; err_free_gpio: gpio_free(gpio); return ret; } static __devexit int rb532_pata_driver_remove(struct platform_device *pdev) { struct ata_host *ah = platform_get_drvdata(pdev); struct rb532_cf_info *info = ah->private_data; ata_host_detach(ah); gpio_free(info->gpio_line); return 0; } /* work with hotplug and coldplug */ MODULE_ALIAS("platform:" DRV_NAME); static struct platform_driver rb532_pata_platform_driver = { .probe = rb532_pata_driver_probe, .remove = __devexit_p(rb532_pata_driver_remove), .driver = { .name = DRV_NAME, .owner = THIS_MODULE, }, }; /* ------------------------------------------------------------------------ */ #define DRV_INFO DRV_DESC " version " DRV_VERSION static int __init rb532_pata_module_init(void) { printk(KERN_INFO DRV_INFO "\n"); return platform_driver_register(&rb532_pata_platform_driver); } static void __exit rb532_pata_module_exit(void) { platform_driver_unregister(&rb532_pata_platform_driver); } MODULE_AUTHOR("Gabor Juhos <juhosg at openwrt.org>"); MODULE_AUTHOR("Florian Fainelli <florian@openwrt.org>"); MODULE_DESCRIPTION(DRV_DESC); MODULE_VERSION(DRV_VERSION); MODULE_LICENSE("GPL"); module_init(rb532_pata_module_init); module_exit(rb532_pata_module_exit);
gpl-2.0
ztemt/NX511J_kernel
drivers/parport/parport_cs.c
4630
5672
/*====================================================================== A driver for PCMCIA parallel port adapters (specifically, for the Quatech SPP-100 EPP card: other cards will probably require driver tweaks) parport_cs.c 1.29 2002/10/11 06:57:41 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The initial developer of the original code is David A. Hinds <dahinds@users.sourceforge.net>. Portions created by David A. Hinds are Copyright (C) 1999 David A. Hinds. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU General Public License version 2 (the "GPL"), in which case the provisions of the GPL are applicable instead of the above. If you wish to allow the use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. ======================================================================*/ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/ioport.h> #include <linux/major.h> #include <linux/interrupt.h> #include <linux/parport.h> #include <linux/parport_pc.h> #include <pcmcia/cistpl.h> #include <pcmcia/ds.h> #include <pcmcia/cisreg.h> #include <pcmcia/ciscode.h> /*====================================================================*/ /* Module parameters */ MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>"); MODULE_DESCRIPTION("PCMCIA parallel port card driver"); MODULE_LICENSE("Dual MPL/GPL"); #define INT_MODULE_PARM(n, v) static int n = v; module_param(n, int, 0) INT_MODULE_PARM(epp_mode, 1); /*====================================================================*/ #define FORCE_EPP_MODE 0x08 typedef struct parport_info_t { struct pcmcia_device *p_dev; int ndev; struct parport *port; } parport_info_t; static void parport_detach(struct pcmcia_device *p_dev); static int parport_config(struct pcmcia_device *link); static void parport_cs_release(struct pcmcia_device *); static int parport_probe(struct pcmcia_device *link) { parport_info_t *info; dev_dbg(&link->dev, "parport_attach()\n"); /* Create new parport device */ info = kzalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; link->priv = info; info->p_dev = link; link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO; return parport_config(link); } /* parport_attach */ static void parport_detach(struct pcmcia_device *link) { dev_dbg(&link->dev, "parport_detach\n"); parport_cs_release(link); kfree(link->priv); } /* parport_detach */ static int parport_config_check(struct pcmcia_device *p_dev, void *priv_data) { p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH; p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_8; p_dev->resource[1]->flags &= ~IO_DATA_PATH_WIDTH; p_dev->resource[1]->flags |= IO_DATA_PATH_WIDTH_8; return pcmcia_request_io(p_dev); } static int parport_config(struct pcmcia_device *link) { parport_info_t *info = link->priv; struct parport *p; int ret; dev_dbg(&link->dev, "parport_config\n"); if (epp_mode) link->config_index |= FORCE_EPP_MODE; ret = pcmcia_loop_config(link, parport_config_check, NULL); if (ret) goto failed; if (!link->irq) goto failed; ret = pcmcia_enable_device(link); if (ret) goto failed; p = parport_pc_probe_port(link->resource[0]->start, link->resource[1]->start, link->irq, PARPORT_DMA_NONE, &link->dev, IRQF_SHARED); if (p == NULL) { printk(KERN_NOTICE "parport_cs: parport_pc_probe_port() at " "0x%3x, irq %u failed\n", (unsigned int) link->resource[0]->start, link->irq); goto failed; } p->modes |= PARPORT_MODE_PCSPP; if (epp_mode) p->modes |= PARPORT_MODE_TRISTATE | PARPORT_MODE_EPP; info->ndev = 1; info->port = p; return 0; failed: parport_cs_release(link); return -ENODEV; } /* parport_config */ static void parport_cs_release(struct pcmcia_device *link) { parport_info_t *info = link->priv; dev_dbg(&link->dev, "parport_release\n"); if (info->ndev) { struct parport *p = info->port; parport_pc_unregister_port(p); } info->ndev = 0; pcmcia_disable_device(link); } /* parport_cs_release */ static const struct pcmcia_device_id parport_ids[] = { PCMCIA_DEVICE_FUNC_ID(3), PCMCIA_MFC_DEVICE_PROD_ID12(1,"Elan","Serial+Parallel Port: SP230",0x3beb8cf2,0xdb9e58bc), PCMCIA_DEVICE_MANF_CARD(0x0137, 0x0003), PCMCIA_DEVICE_NULL }; MODULE_DEVICE_TABLE(pcmcia, parport_ids); static struct pcmcia_driver parport_cs_driver = { .owner = THIS_MODULE, .name = "parport_cs", .probe = parport_probe, .remove = parport_detach, .id_table = parport_ids, }; module_pcmcia_driver(parport_cs_driver);
gpl-2.0
peyo-hd/kernel_odrc
arch/arm/kernel/kprobes-common.c
6678
14512
/* * arch/arm/kernel/kprobes-common.c * * Copyright (C) 2011 Jon Medhurst <tixy@yxit.co.uk>. * * Some contents moved here from arch/arm/include/asm/kprobes-arm.c which is * Copyright (C) 2006, 2007 Motorola Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/kprobes.h> #include <asm/system_info.h> #include "kprobes.h" #ifndef find_str_pc_offset /* * For STR and STM instructions, an ARM core may choose to use either * a +8 or a +12 displacement from the current instruction's address. * Whichever value is chosen for a given core, it must be the same for * both instructions and may not change. This function measures it. */ int str_pc_offset; void __init find_str_pc_offset(void) { int addr, scratch, ret; __asm__ ( "sub %[ret], pc, #4 \n\t" "str pc, %[addr] \n\t" "ldr %[scr], %[addr] \n\t" "sub %[ret], %[scr], %[ret] \n\t" : [ret] "=r" (ret), [scr] "=r" (scratch), [addr] "+m" (addr)); str_pc_offset = ret; } #endif /* !find_str_pc_offset */ #ifndef test_load_write_pc_interworking bool load_write_pc_interworks; void __init test_load_write_pc_interworking(void) { int arch = cpu_architecture(); BUG_ON(arch == CPU_ARCH_UNKNOWN); load_write_pc_interworks = arch >= CPU_ARCH_ARMv5T; } #endif /* !test_load_write_pc_interworking */ #ifndef test_alu_write_pc_interworking bool alu_write_pc_interworks; void __init test_alu_write_pc_interworking(void) { int arch = cpu_architecture(); BUG_ON(arch == CPU_ARCH_UNKNOWN); alu_write_pc_interworks = arch >= CPU_ARCH_ARMv7; } #endif /* !test_alu_write_pc_interworking */ void __init arm_kprobe_decode_init(void) { find_str_pc_offset(); test_load_write_pc_interworking(); test_alu_write_pc_interworking(); } static unsigned long __kprobes __check_eq(unsigned long cpsr) { return cpsr & PSR_Z_BIT; } static unsigned long __kprobes __check_ne(unsigned long cpsr) { return (~cpsr) & PSR_Z_BIT; } static unsigned long __kprobes __check_cs(unsigned long cpsr) { return cpsr & PSR_C_BIT; } static unsigned long __kprobes __check_cc(unsigned long cpsr) { return (~cpsr) & PSR_C_BIT; } static unsigned long __kprobes __check_mi(unsigned long cpsr) { return cpsr & PSR_N_BIT; } static unsigned long __kprobes __check_pl(unsigned long cpsr) { return (~cpsr) & PSR_N_BIT; } static unsigned long __kprobes __check_vs(unsigned long cpsr) { return cpsr & PSR_V_BIT; } static unsigned long __kprobes __check_vc(unsigned long cpsr) { return (~cpsr) & PSR_V_BIT; } static unsigned long __kprobes __check_hi(unsigned long cpsr) { cpsr &= ~(cpsr >> 1); /* PSR_C_BIT &= ~PSR_Z_BIT */ return cpsr & PSR_C_BIT; } static unsigned long __kprobes __check_ls(unsigned long cpsr) { cpsr &= ~(cpsr >> 1); /* PSR_C_BIT &= ~PSR_Z_BIT */ return (~cpsr) & PSR_C_BIT; } static unsigned long __kprobes __check_ge(unsigned long cpsr) { cpsr ^= (cpsr << 3); /* PSR_N_BIT ^= PSR_V_BIT */ return (~cpsr) & PSR_N_BIT; } static unsigned long __kprobes __check_lt(unsigned long cpsr) { cpsr ^= (cpsr << 3); /* PSR_N_BIT ^= PSR_V_BIT */ return cpsr & PSR_N_BIT; } static unsigned long __kprobes __check_gt(unsigned long cpsr) { unsigned long temp = cpsr ^ (cpsr << 3); /* PSR_N_BIT ^= PSR_V_BIT */ temp |= (cpsr << 1); /* PSR_N_BIT |= PSR_Z_BIT */ return (~temp) & PSR_N_BIT; } static unsigned long __kprobes __check_le(unsigned long cpsr) { unsigned long temp = cpsr ^ (cpsr << 3); /* PSR_N_BIT ^= PSR_V_BIT */ temp |= (cpsr << 1); /* PSR_N_BIT |= PSR_Z_BIT */ return temp & PSR_N_BIT; } static unsigned long __kprobes __check_al(unsigned long cpsr) { return true; } kprobe_check_cc * const kprobe_condition_checks[16] = { &__check_eq, &__check_ne, &__check_cs, &__check_cc, &__check_mi, &__check_pl, &__check_vs, &__check_vc, &__check_hi, &__check_ls, &__check_ge, &__check_lt, &__check_gt, &__check_le, &__check_al, &__check_al }; void __kprobes kprobe_simulate_nop(struct kprobe *p, struct pt_regs *regs) { } void __kprobes kprobe_emulate_none(struct kprobe *p, struct pt_regs *regs) { p->ainsn.insn_fn(); } static void __kprobes simulate_ldm1stm1(struct kprobe *p, struct pt_regs *regs) { kprobe_opcode_t insn = p->opcode; int rn = (insn >> 16) & 0xf; int lbit = insn & (1 << 20); int wbit = insn & (1 << 21); int ubit = insn & (1 << 23); int pbit = insn & (1 << 24); long *addr = (long *)regs->uregs[rn]; int reg_bit_vector; int reg_count; reg_count = 0; reg_bit_vector = insn & 0xffff; while (reg_bit_vector) { reg_bit_vector &= (reg_bit_vector - 1); ++reg_count; } if (!ubit) addr -= reg_count; addr += (!pbit == !ubit); reg_bit_vector = insn & 0xffff; while (reg_bit_vector) { int reg = __ffs(reg_bit_vector); reg_bit_vector &= (reg_bit_vector - 1); if (lbit) regs->uregs[reg] = *addr++; else *addr++ = regs->uregs[reg]; } if (wbit) { if (!ubit) addr -= reg_count; addr -= (!pbit == !ubit); regs->uregs[rn] = (long)addr; } } static void __kprobes simulate_stm1_pc(struct kprobe *p, struct pt_regs *regs) { regs->ARM_pc = (long)p->addr + str_pc_offset; simulate_ldm1stm1(p, regs); regs->ARM_pc = (long)p->addr + 4; } static void __kprobes simulate_ldm1_pc(struct kprobe *p, struct pt_regs *regs) { simulate_ldm1stm1(p, regs); load_write_pc(regs->ARM_pc, regs); } static void __kprobes emulate_generic_r0_12_noflags(struct kprobe *p, struct pt_regs *regs) { register void *rregs asm("r1") = regs; register void *rfn asm("lr") = p->ainsn.insn_fn; __asm__ __volatile__ ( "stmdb sp!, {%[regs], r11} \n\t" "ldmia %[regs], {r0-r12} \n\t" #if __LINUX_ARM_ARCH__ >= 6 "blx %[fn] \n\t" #else "str %[fn], [sp, #-4]! \n\t" "adr lr, 1f \n\t" "ldr pc, [sp], #4 \n\t" "1: \n\t" #endif "ldr lr, [sp], #4 \n\t" /* lr = regs */ "stmia lr, {r0-r12} \n\t" "ldr r11, [sp], #4 \n\t" : [regs] "=r" (rregs), [fn] "=r" (rfn) : "0" (rregs), "1" (rfn) : "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r12", "memory", "cc" ); } static void __kprobes emulate_generic_r2_14_noflags(struct kprobe *p, struct pt_regs *regs) { emulate_generic_r0_12_noflags(p, (struct pt_regs *)(regs->uregs+2)); } static void __kprobes emulate_ldm_r3_15(struct kprobe *p, struct pt_regs *regs) { emulate_generic_r0_12_noflags(p, (struct pt_regs *)(regs->uregs+3)); load_write_pc(regs->ARM_pc, regs); } enum kprobe_insn __kprobes kprobe_decode_ldmstm(kprobe_opcode_t insn, struct arch_specific_insn *asi) { kprobe_insn_handler_t *handler = 0; unsigned reglist = insn & 0xffff; int is_ldm = insn & 0x100000; int rn = (insn >> 16) & 0xf; if (rn <= 12 && (reglist & 0xe000) == 0) { /* Instruction only uses registers in the range R0..R12 */ handler = emulate_generic_r0_12_noflags; } else if (rn >= 2 && (reglist & 0x8003) == 0) { /* Instruction only uses registers in the range R2..R14 */ rn -= 2; reglist >>= 2; handler = emulate_generic_r2_14_noflags; } else if (rn >= 3 && (reglist & 0x0007) == 0) { /* Instruction only uses registers in the range R3..R15 */ if (is_ldm && (reglist & 0x8000)) { rn -= 3; reglist >>= 3; handler = emulate_ldm_r3_15; } } if (handler) { /* We can emulate the instruction in (possibly) modified form */ asi->insn[0] = (insn & 0xfff00000) | (rn << 16) | reglist; asi->insn_handler = handler; return INSN_GOOD; } /* Fallback to slower simulation... */ if (reglist & 0x8000) handler = is_ldm ? simulate_ldm1_pc : simulate_stm1_pc; else handler = simulate_ldm1stm1; asi->insn_handler = handler; return INSN_GOOD_NO_SLOT; } /* * Prepare an instruction slot to receive an instruction for emulating. * This is done by placing a subroutine return after the location where the * instruction will be placed. We also modify ARM instructions to be * unconditional as the condition code will already be checked before any * emulation handler is called. */ static kprobe_opcode_t __kprobes prepare_emulated_insn(kprobe_opcode_t insn, struct arch_specific_insn *asi, bool thumb) { #ifdef CONFIG_THUMB2_KERNEL if (thumb) { u16 *thumb_insn = (u16 *)asi->insn; thumb_insn[1] = 0x4770; /* Thumb bx lr */ thumb_insn[2] = 0x4770; /* Thumb bx lr */ return insn; } asi->insn[1] = 0xe12fff1e; /* ARM bx lr */ #else asi->insn[1] = 0xe1a0f00e; /* mov pc, lr */ #endif /* Make an ARM instruction unconditional */ if (insn < 0xe0000000) insn = (insn | 0xe0000000) & ~0x10000000; return insn; } /* * Write a (probably modified) instruction into the slot previously prepared by * prepare_emulated_insn */ static void __kprobes set_emulated_insn(kprobe_opcode_t insn, struct arch_specific_insn *asi, bool thumb) { #ifdef CONFIG_THUMB2_KERNEL if (thumb) { u16 *ip = (u16 *)asi->insn; if (is_wide_instruction(insn)) *ip++ = insn >> 16; *ip++ = insn; return; } #endif asi->insn[0] = insn; } /* * When we modify the register numbers encoded in an instruction to be emulated, * the new values come from this define. For ARM and 32-bit Thumb instructions * this gives... * * bit position 16 12 8 4 0 * ---------------+---+---+---+---+---+ * register r2 r0 r1 -- r3 */ #define INSN_NEW_BITS 0x00020103 /* Each nibble has same value as that at INSN_NEW_BITS bit 16 */ #define INSN_SAMEAS16_BITS 0x22222222 /* * Validate and modify each of the registers encoded in an instruction. * * Each nibble in regs contains a value from enum decode_reg_type. For each * non-zero value, the corresponding nibble in pinsn is validated and modified * according to the type. */ static bool __kprobes decode_regs(kprobe_opcode_t* pinsn, u32 regs) { kprobe_opcode_t insn = *pinsn; kprobe_opcode_t mask = 0xf; /* Start at least significant nibble */ for (; regs != 0; regs >>= 4, mask <<= 4) { kprobe_opcode_t new_bits = INSN_NEW_BITS; switch (regs & 0xf) { case REG_TYPE_NONE: /* Nibble not a register, skip to next */ continue; case REG_TYPE_ANY: /* Any register is allowed */ break; case REG_TYPE_SAMEAS16: /* Replace register with same as at bit position 16 */ new_bits = INSN_SAMEAS16_BITS; break; case REG_TYPE_SP: /* Only allow SP (R13) */ if ((insn ^ 0xdddddddd) & mask) goto reject; break; case REG_TYPE_PC: /* Only allow PC (R15) */ if ((insn ^ 0xffffffff) & mask) goto reject; break; case REG_TYPE_NOSP: /* Reject SP (R13) */ if (((insn ^ 0xdddddddd) & mask) == 0) goto reject; break; case REG_TYPE_NOSPPC: case REG_TYPE_NOSPPCX: /* Reject SP and PC (R13 and R15) */ if (((insn ^ 0xdddddddd) & 0xdddddddd & mask) == 0) goto reject; break; case REG_TYPE_NOPCWB: if (!is_writeback(insn)) break; /* No writeback, so any register is OK */ /* fall through... */ case REG_TYPE_NOPC: case REG_TYPE_NOPCX: /* Reject PC (R15) */ if (((insn ^ 0xffffffff) & mask) == 0) goto reject; break; } /* Replace value of nibble with new register number... */ insn &= ~mask; insn |= new_bits & mask; } *pinsn = insn; return true; reject: return false; } static const int decode_struct_sizes[NUM_DECODE_TYPES] = { [DECODE_TYPE_TABLE] = sizeof(struct decode_table), [DECODE_TYPE_CUSTOM] = sizeof(struct decode_custom), [DECODE_TYPE_SIMULATE] = sizeof(struct decode_simulate), [DECODE_TYPE_EMULATE] = sizeof(struct decode_emulate), [DECODE_TYPE_OR] = sizeof(struct decode_or), [DECODE_TYPE_REJECT] = sizeof(struct decode_reject) }; /* * kprobe_decode_insn operates on data tables in order to decode an ARM * architecture instruction onto which a kprobe has been placed. * * These instruction decoding tables are a concatenation of entries each * of which consist of one of the following structs: * * decode_table * decode_custom * decode_simulate * decode_emulate * decode_or * decode_reject * * Each of these starts with a struct decode_header which has the following * fields: * * type_regs * mask * value * * The least significant DECODE_TYPE_BITS of type_regs contains a value * from enum decode_type, this indicates which of the decode_* structs * the entry contains. The value DECODE_TYPE_END indicates the end of the * table. * * When the table is parsed, each entry is checked in turn to see if it * matches the instruction to be decoded using the test: * * (insn & mask) == value * * If no match is found before the end of the table is reached then decoding * fails with INSN_REJECTED. * * When a match is found, decode_regs() is called to validate and modify each * of the registers encoded in the instruction; the data it uses to do this * is (type_regs >> DECODE_TYPE_BITS). A validation failure will cause decoding * to fail with INSN_REJECTED. * * Once the instruction has passed the above tests, further processing * depends on the type of the table entry's decode struct. * */ int __kprobes kprobe_decode_insn(kprobe_opcode_t insn, struct arch_specific_insn *asi, const union decode_item *table, bool thumb) { const struct decode_header *h = (struct decode_header *)table; const struct decode_header *next; bool matched = false; insn = prepare_emulated_insn(insn, asi, thumb); for (;; h = next) { enum decode_type type = h->type_regs.bits & DECODE_TYPE_MASK; u32 regs = h->type_regs.bits >> DECODE_TYPE_BITS; if (type == DECODE_TYPE_END) return INSN_REJECTED; next = (struct decode_header *) ((uintptr_t)h + decode_struct_sizes[type]); if (!matched && (insn & h->mask.bits) != h->value.bits) continue; if (!decode_regs(&insn, regs)) return INSN_REJECTED; switch (type) { case DECODE_TYPE_TABLE: { struct decode_table *d = (struct decode_table *)h; next = (struct decode_header *)d->table.table; break; } case DECODE_TYPE_CUSTOM: { struct decode_custom *d = (struct decode_custom *)h; return (*d->decoder.decoder)(insn, asi); } case DECODE_TYPE_SIMULATE: { struct decode_simulate *d = (struct decode_simulate *)h; asi->insn_handler = d->handler.handler; return INSN_GOOD_NO_SLOT; } case DECODE_TYPE_EMULATE: { struct decode_emulate *d = (struct decode_emulate *)h; asi->insn_handler = d->handler.handler; set_emulated_insn(insn, asi, thumb); return INSN_GOOD; } case DECODE_TYPE_OR: matched = true; break; case DECODE_TYPE_REJECT: default: return INSN_REJECTED; } } }
gpl-2.0
wiktorek140/android_kernel_sony_msm8x60
arch/m68k/platform/5249/gpio.c
7446
1841
/* * Coldfire generic GPIO support * * (C) Copyright 2009, Steven King <sfking@fdwdc.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; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/init.h> #include <asm/coldfire.h> #include <asm/mcfsim.h> #include <asm/mcfgpio.h> static struct mcf_gpio_chip mcf_gpio_chips[] = { { .gpio_chip = { .label = "GPIO0", .request = mcf_gpio_request, .free = mcf_gpio_free, .direction_input = mcf_gpio_direction_input, .direction_output = mcf_gpio_direction_output, .get = mcf_gpio_get_value, .set = mcf_gpio_set_value, .ngpio = 32, }, .pddr = (void __iomem *) MCFSIM2_GPIOENABLE, .podr = (void __iomem *) MCFSIM2_GPIOWRITE, .ppdr = (void __iomem *) MCFSIM2_GPIOREAD, }, { .gpio_chip = { .label = "GPIO1", .request = mcf_gpio_request, .free = mcf_gpio_free, .direction_input = mcf_gpio_direction_input, .direction_output = mcf_gpio_direction_output, .get = mcf_gpio_get_value, .set = mcf_gpio_set_value, .base = 32, .ngpio = 32, }, .pddr = (void __iomem *) MCFSIM2_GPIO1ENABLE, .podr = (void __iomem *) MCFSIM2_GPIO1WRITE, .ppdr = (void __iomem *) MCFSIM2_GPIO1READ, }, }; static int __init mcf_gpio_init(void) { unsigned i = 0; while (i < ARRAY_SIZE(mcf_gpio_chips)) (void)gpiochip_add((struct gpio_chip *)&mcf_gpio_chips[i++]); return 0; } core_initcall(mcf_gpio_init);
gpl-2.0
JustBeYou/linux
drivers/net/wireless/rtl818x/rtl8187/leds.c
7958
6568
/* * Linux LED driver for RTL8187 * * Copyright 2009 Larry Finger <Larry.Finger@lwfinger.net> * * Based on the LED handling in the r8187 driver, which is: * Copyright (c) Realtek Semiconductor Corp. All rights reserved. * * Thanks to Realtek for their support! * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifdef CONFIG_RTL8187_LEDS #include <net/mac80211.h> #include <linux/usb.h> #include <linux/eeprom_93cx6.h> #include "rtl8187.h" #include "leds.h" static void led_turn_on(struct work_struct *work) { /* As this routine does read/write operations on the hardware, it must * be run from a work queue. */ u8 reg; struct rtl8187_priv *priv = container_of(work, struct rtl8187_priv, led_on.work); struct rtl8187_led *led = &priv->led_tx; /* Don't change the LED, when the device is down. */ if (!priv->vif || priv->vif->type == NL80211_IFTYPE_UNSPECIFIED) return ; /* Skip if the LED is not registered. */ if (!led->dev) return; mutex_lock(&priv->conf_mutex); switch (led->ledpin) { case LED_PIN_GPIO0: rtl818x_iowrite8(priv, &priv->map->GPIO0, 0x01); rtl818x_iowrite8(priv, &priv->map->GP_ENABLE, 0x00); break; case LED_PIN_LED0: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) & ~(1 << 4); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_LED1: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) & ~(1 << 5); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_HW: default: break; } mutex_unlock(&priv->conf_mutex); } static void led_turn_off(struct work_struct *work) { /* As this routine does read/write operations on the hardware, it must * be run from a work queue. */ u8 reg; struct rtl8187_priv *priv = container_of(work, struct rtl8187_priv, led_off.work); struct rtl8187_led *led = &priv->led_tx; /* Don't change the LED, when the device is down. */ if (!priv->vif || priv->vif->type == NL80211_IFTYPE_UNSPECIFIED) return ; /* Skip if the LED is not registered. */ if (!led->dev) return; mutex_lock(&priv->conf_mutex); switch (led->ledpin) { case LED_PIN_GPIO0: rtl818x_iowrite8(priv, &priv->map->GPIO0, 0x01); rtl818x_iowrite8(priv, &priv->map->GP_ENABLE, 0x01); break; case LED_PIN_LED0: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) | (1 << 4); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_LED1: reg = rtl818x_ioread8(priv, &priv->map->PGSELECT) | (1 << 5); rtl818x_iowrite8(priv, &priv->map->PGSELECT, reg); break; case LED_PIN_HW: default: break; } mutex_unlock(&priv->conf_mutex); } /* Callback from the LED subsystem. */ static void rtl8187_led_brightness_set(struct led_classdev *led_dev, enum led_brightness brightness) { struct rtl8187_led *led = container_of(led_dev, struct rtl8187_led, led_dev); struct ieee80211_hw *hw = led->dev; struct rtl8187_priv *priv; static bool radio_on; if (!hw) return; priv = hw->priv; if (led->is_radio) { if (brightness == LED_FULL) { ieee80211_queue_delayed_work(hw, &priv->led_on, 0); radio_on = true; } else if (radio_on) { radio_on = false; cancel_delayed_work(&priv->led_on); ieee80211_queue_delayed_work(hw, &priv->led_off, 0); } } else if (radio_on) { if (brightness == LED_OFF) { ieee80211_queue_delayed_work(hw, &priv->led_off, 0); /* The LED is off for 1/20 sec - it just blinks. */ ieee80211_queue_delayed_work(hw, &priv->led_on, HZ / 20); } else ieee80211_queue_delayed_work(hw, &priv->led_on, 0); } } static int rtl8187_register_led(struct ieee80211_hw *dev, struct rtl8187_led *led, const char *name, const char *default_trigger, u8 ledpin, bool is_radio) { int err; struct rtl8187_priv *priv = dev->priv; if (led->dev) return -EEXIST; if (!default_trigger) return -EINVAL; led->dev = dev; led->ledpin = ledpin; led->is_radio = is_radio; strncpy(led->name, name, sizeof(led->name)); led->led_dev.name = led->name; led->led_dev.default_trigger = default_trigger; led->led_dev.brightness_set = rtl8187_led_brightness_set; err = led_classdev_register(&priv->udev->dev, &led->led_dev); if (err) { printk(KERN_INFO "LEDs: Failed to register %s\n", name); led->dev = NULL; return err; } return 0; } static void rtl8187_unregister_led(struct rtl8187_led *led) { struct ieee80211_hw *hw = led->dev; struct rtl8187_priv *priv = hw->priv; led_classdev_unregister(&led->led_dev); flush_delayed_work(&priv->led_off); led->dev = NULL; } void rtl8187_leds_init(struct ieee80211_hw *dev, u16 custid) { struct rtl8187_priv *priv = dev->priv; char name[RTL8187_LED_MAX_NAME_LEN + 1]; u8 ledpin; int err; /* According to the vendor driver, the LED operation depends on the * customer ID encoded in the EEPROM */ printk(KERN_INFO "rtl8187: Customer ID is 0x%02X\n", custid); switch (custid) { case EEPROM_CID_RSVD0: case EEPROM_CID_RSVD1: case EEPROM_CID_SERCOMM_PS: case EEPROM_CID_QMI: case EEPROM_CID_DELL: case EEPROM_CID_TOSHIBA: ledpin = LED_PIN_GPIO0; break; case EEPROM_CID_ALPHA0: ledpin = LED_PIN_LED0; break; case EEPROM_CID_HW: ledpin = LED_PIN_HW; break; default: ledpin = LED_PIN_GPIO0; } INIT_DELAYED_WORK(&priv->led_on, led_turn_on); INIT_DELAYED_WORK(&priv->led_off, led_turn_off); snprintf(name, sizeof(name), "rtl8187-%s::radio", wiphy_name(dev->wiphy)); err = rtl8187_register_led(dev, &priv->led_radio, name, ieee80211_get_radio_led_name(dev), ledpin, true); if (err) return; snprintf(name, sizeof(name), "rtl8187-%s::tx", wiphy_name(dev->wiphy)); err = rtl8187_register_led(dev, &priv->led_tx, name, ieee80211_get_tx_led_name(dev), ledpin, false); if (err) goto err_tx; snprintf(name, sizeof(name), "rtl8187-%s::rx", wiphy_name(dev->wiphy)); err = rtl8187_register_led(dev, &priv->led_rx, name, ieee80211_get_rx_led_name(dev), ledpin, false); if (!err) return; /* registration of RX LED failed - unregister */ rtl8187_unregister_led(&priv->led_tx); err_tx: rtl8187_unregister_led(&priv->led_radio); } void rtl8187_leds_exit(struct ieee80211_hw *dev) { struct rtl8187_priv *priv = dev->priv; rtl8187_unregister_led(&priv->led_radio); rtl8187_unregister_led(&priv->led_rx); rtl8187_unregister_led(&priv->led_tx); cancel_delayed_work_sync(&priv->led_off); cancel_delayed_work_sync(&priv->led_on); } #endif /* def CONFIG_RTL8187_LEDS */
gpl-2.0
mifl/android_kernel_pantech_ef63-common
arch/sh/mm/tlb-sh4.c
9238
2609
/* * arch/sh/mm/tlb-sh4.c * * SH-4 specific TLB operations * * Copyright (C) 1999 Niibe Yutaka * Copyright (C) 2002 - 2007 Paul Mundt * * Released under the terms of the GNU GPL v2.0. */ #include <linux/kernel.h> #include <linux/mm.h> #include <linux/io.h> #include <asm/mmu_context.h> #include <asm/cacheflush.h> void __update_tlb(struct vm_area_struct *vma, unsigned long address, pte_t pte) { unsigned long flags, pteval, vpn; /* * Handle debugger faulting in for debugee. */ if (vma && current->active_mm != vma->vm_mm) return; local_irq_save(flags); /* Set PTEH register */ vpn = (address & MMU_VPN_MASK) | get_asid(); __raw_writel(vpn, MMU_PTEH); pteval = pte.pte_low; /* Set PTEA register */ #ifdef CONFIG_X2TLB /* * For the extended mode TLB this is trivial, only the ESZ and * EPR bits need to be written out to PTEA, with the remainder of * the protection bits (with the exception of the compat-mode SZ * and PR bits, which are cleared) being written out in PTEL. */ __raw_writel(pte.pte_high, MMU_PTEA); #else if (cpu_data->flags & CPU_HAS_PTEA) { /* The last 3 bits and the first one of pteval contains * the PTEA timing control and space attribute bits */ __raw_writel(copy_ptea_attributes(pteval), MMU_PTEA); } #endif /* Set PTEL register */ pteval &= _PAGE_FLAGS_HARDWARE_MASK; /* drop software flags */ #ifdef CONFIG_CACHE_WRITETHROUGH pteval |= _PAGE_WT; #endif /* conveniently, we want all the software flags to be 0 anyway */ __raw_writel(pteval, MMU_PTEL); /* Load the TLB */ asm volatile("ldtlb": /* no output */ : /* no input */ : "memory"); local_irq_restore(flags); } void local_flush_tlb_one(unsigned long asid, unsigned long page) { unsigned long addr, data; /* * NOTE: PTEH.ASID should be set to this MM * _AND_ we need to write ASID to the array. * * It would be simple if we didn't need to set PTEH.ASID... */ addr = MMU_UTLB_ADDRESS_ARRAY | MMU_PAGE_ASSOC_BIT; data = page | asid; /* VALID bit is off */ jump_to_uncached(); __raw_writel(data, addr); back_to_cached(); } void local_flush_tlb_all(void) { unsigned long flags, status; int i; /* * Flush all the TLB. */ local_irq_save(flags); jump_to_uncached(); status = __raw_readl(MMUCR); status = ((status & MMUCR_URB) >> MMUCR_URB_SHIFT); if (status == 0) status = MMUCR_URB_NENTRIES; for (i = 0; i < status; i++) __raw_writel(0x0, MMU_UTLB_ADDRESS_ARRAY | (i << 8)); for (i = 0; i < 4; i++) __raw_writel(0x0, MMU_ITLB_ADDRESS_ARRAY | (i << 8)); back_to_cached(); ctrl_barrier(); local_irq_restore(flags); }
gpl-2.0
cristianhristea/linux_kernel
drivers/parport/share.c
10518
29890
/* * Parallel-port resource manager code. * * Authors: David Campbell <campbell@tirian.che.curtin.edu.au> * Tim Waugh <tim@cyberelk.demon.co.uk> * Jose Renau <renau@acm.org> * Philip Blundell <philb@gnu.org> * Andrea Arcangeli * * based on work by Grant Guenther <grant@torque.net> * and Philip Blundell * * Any part of this program may be used in documents licensed under * the GNU Free Documentation License, Version 1.1 or any later version * published by the Free Software Foundation. */ #undef PARPORT_DEBUG_SHARING /* undef for production */ #include <linux/module.h> #include <linux/string.h> #include <linux/threads.h> #include <linux/parport.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <asm/irq.h> #undef PARPORT_PARANOID #define PARPORT_DEFAULT_TIMESLICE (HZ/5) unsigned long parport_default_timeslice = PARPORT_DEFAULT_TIMESLICE; int parport_default_spintime = DEFAULT_SPIN_TIME; static LIST_HEAD(portlist); static DEFINE_SPINLOCK(parportlist_lock); /* list of all allocated ports, sorted by ->number */ static LIST_HEAD(all_ports); static DEFINE_SPINLOCK(full_list_lock); static LIST_HEAD(drivers); static DEFINE_MUTEX(registration_lock); /* What you can do to a port that's gone away.. */ static void dead_write_lines (struct parport *p, unsigned char b){} static unsigned char dead_read_lines (struct parport *p) { return 0; } static unsigned char dead_frob_lines (struct parport *p, unsigned char b, unsigned char c) { return 0; } static void dead_onearg (struct parport *p){} static void dead_initstate (struct pardevice *d, struct parport_state *s) { } static void dead_state (struct parport *p, struct parport_state *s) { } static size_t dead_write (struct parport *p, const void *b, size_t l, int f) { return 0; } static size_t dead_read (struct parport *p, void *b, size_t l, int f) { return 0; } static struct parport_operations dead_ops = { .write_data = dead_write_lines, /* data */ .read_data = dead_read_lines, .write_control = dead_write_lines, /* control */ .read_control = dead_read_lines, .frob_control = dead_frob_lines, .read_status = dead_read_lines, /* status */ .enable_irq = dead_onearg, /* enable_irq */ .disable_irq = dead_onearg, /* disable_irq */ .data_forward = dead_onearg, /* data_forward */ .data_reverse = dead_onearg, /* data_reverse */ .init_state = dead_initstate, /* init_state */ .save_state = dead_state, .restore_state = dead_state, .epp_write_data = dead_write, /* epp */ .epp_read_data = dead_read, .epp_write_addr = dead_write, .epp_read_addr = dead_read, .ecp_write_data = dead_write, /* ecp */ .ecp_read_data = dead_read, .ecp_write_addr = dead_write, .compat_write_data = dead_write, /* compat */ .nibble_read_data = dead_read, /* nibble */ .byte_read_data = dead_read, /* byte */ .owner = NULL, }; /* Call attach(port) for each registered driver. */ static void attach_driver_chain(struct parport *port) { /* caller has exclusive registration_lock */ struct parport_driver *drv; list_for_each_entry(drv, &drivers, list) drv->attach(port); } /* Call detach(port) for each registered driver. */ static void detach_driver_chain(struct parport *port) { struct parport_driver *drv; /* caller has exclusive registration_lock */ list_for_each_entry(drv, &drivers, list) drv->detach (port); } /* Ask kmod for some lowlevel drivers. */ static void get_lowlevel_driver (void) { /* There is no actual module called this: you should set * up an alias for modutils. */ request_module ("parport_lowlevel"); } /** * parport_register_driver - register a parallel port device driver * @drv: structure describing the driver * * This can be called by a parallel port device driver in order * to receive notifications about ports being found in the * system, as well as ports no longer available. * * The @drv structure is allocated by the caller and must not be * deallocated until after calling parport_unregister_driver(). * * The driver's attach() function may block. The port that * attach() is given will be valid for the duration of the * callback, but if the driver wants to take a copy of the * pointer it must call parport_get_port() to do so. Calling * parport_register_device() on that port will do this for you. * * The driver's detach() function may block. The port that * detach() is given will be valid for the duration of the * callback, but if the driver wants to take a copy of the * pointer it must call parport_get_port() to do so. * * Returns 0 on success. Currently it always succeeds. **/ int parport_register_driver (struct parport_driver *drv) { struct parport *port; if (list_empty(&portlist)) get_lowlevel_driver (); mutex_lock(&registration_lock); list_for_each_entry(port, &portlist, list) drv->attach(port); list_add(&drv->list, &drivers); mutex_unlock(&registration_lock); return 0; } /** * parport_unregister_driver - deregister a parallel port device driver * @drv: structure describing the driver that was given to * parport_register_driver() * * This should be called by a parallel port device driver that * has registered itself using parport_register_driver() when it * is about to be unloaded. * * When it returns, the driver's attach() routine will no longer * be called, and for each port that attach() was called for, the * detach() routine will have been called. * * All the driver's attach() and detach() calls are guaranteed to have * finished by the time this function returns. **/ void parport_unregister_driver (struct parport_driver *drv) { struct parport *port; mutex_lock(&registration_lock); list_del_init(&drv->list); list_for_each_entry(port, &portlist, list) drv->detach(port); mutex_unlock(&registration_lock); } static void free_port (struct parport *port) { int d; spin_lock(&full_list_lock); list_del(&port->full_list); spin_unlock(&full_list_lock); for (d = 0; d < 5; d++) { kfree(port->probe_info[d].class_name); kfree(port->probe_info[d].mfr); kfree(port->probe_info[d].model); kfree(port->probe_info[d].cmdset); kfree(port->probe_info[d].description); } kfree(port->name); kfree(port); } /** * parport_get_port - increment a port's reference count * @port: the port * * This ensures that a struct parport pointer remains valid * until the matching parport_put_port() call. **/ struct parport *parport_get_port (struct parport *port) { atomic_inc (&port->ref_count); return port; } /** * parport_put_port - decrement a port's reference count * @port: the port * * This should be called once for each call to parport_get_port(), * once the port is no longer needed. **/ void parport_put_port (struct parport *port) { if (atomic_dec_and_test (&port->ref_count)) /* Can destroy it now. */ free_port (port); return; } /** * parport_register_port - register a parallel port * @base: base I/O address * @irq: IRQ line * @dma: DMA channel * @ops: pointer to the port driver's port operations structure * * When a parallel port (lowlevel) driver finds a port that * should be made available to parallel port device drivers, it * should call parport_register_port(). The @base, @irq, and * @dma parameters are for the convenience of port drivers, and * for ports where they aren't meaningful needn't be set to * anything special. They can be altered afterwards by adjusting * the relevant members of the parport structure that is returned * and represents the port. They should not be tampered with * after calling parport_announce_port, however. * * If there are parallel port device drivers in the system that * have registered themselves using parport_register_driver(), * they are not told about the port at this time; that is done by * parport_announce_port(). * * The @ops structure is allocated by the caller, and must not be * deallocated before calling parport_remove_port(). * * If there is no memory to allocate a new parport structure, * this function will return %NULL. **/ struct parport *parport_register_port(unsigned long base, int irq, int dma, struct parport_operations *ops) { struct list_head *l; struct parport *tmp; int num; int device; char *name; tmp = kmalloc(sizeof(struct parport), GFP_KERNEL); if (!tmp) { printk(KERN_WARNING "parport: memory squeeze\n"); return NULL; } /* Init our structure */ memset(tmp, 0, sizeof(struct parport)); tmp->base = base; tmp->irq = irq; tmp->dma = dma; tmp->muxport = tmp->daisy = tmp->muxsel = -1; tmp->modes = 0; INIT_LIST_HEAD(&tmp->list); tmp->devices = tmp->cad = NULL; tmp->flags = 0; tmp->ops = ops; tmp->physport = tmp; memset (tmp->probe_info, 0, 5 * sizeof (struct parport_device_info)); rwlock_init(&tmp->cad_lock); spin_lock_init(&tmp->waitlist_lock); spin_lock_init(&tmp->pardevice_lock); tmp->ieee1284.mode = IEEE1284_MODE_COMPAT; tmp->ieee1284.phase = IEEE1284_PH_FWD_IDLE; sema_init(&tmp->ieee1284.irq, 0); tmp->spintime = parport_default_spintime; atomic_set (&tmp->ref_count, 1); INIT_LIST_HEAD(&tmp->full_list); name = kmalloc(15, GFP_KERNEL); if (!name) { printk(KERN_ERR "parport: memory squeeze\n"); kfree(tmp); return NULL; } /* Search for the lowest free parport number. */ spin_lock(&full_list_lock); for (l = all_ports.next, num = 0; l != &all_ports; l = l->next, num++) { struct parport *p = list_entry(l, struct parport, full_list); if (p->number != num) break; } tmp->portnum = tmp->number = num; list_add_tail(&tmp->full_list, l); spin_unlock(&full_list_lock); /* * Now that the portnum is known finish doing the Init. */ sprintf(name, "parport%d", tmp->portnum = tmp->number); tmp->name = name; for (device = 0; device < 5; device++) /* assume the worst */ tmp->probe_info[device].class = PARPORT_CLASS_LEGACY; tmp->waithead = tmp->waittail = NULL; return tmp; } /** * parport_announce_port - tell device drivers about a parallel port * @port: parallel port to announce * * After a port driver has registered a parallel port with * parport_register_port, and performed any necessary * initialisation or adjustments, it should call * parport_announce_port() in order to notify all device drivers * that have called parport_register_driver(). Their attach() * functions will be called, with @port as the parameter. **/ void parport_announce_port (struct parport *port) { int i; #ifdef CONFIG_PARPORT_1284 /* Analyse the IEEE1284.3 topology of the port. */ parport_daisy_init(port); #endif if (!port->dev) printk(KERN_WARNING "%s: fix this legacy " "no-device port driver!\n", port->name); parport_proc_register(port); mutex_lock(&registration_lock); spin_lock_irq(&parportlist_lock); list_add_tail(&port->list, &portlist); for (i = 1; i < 3; i++) { struct parport *slave = port->slaves[i-1]; if (slave) list_add_tail(&slave->list, &portlist); } spin_unlock_irq(&parportlist_lock); /* Let drivers know that new port(s) has arrived. */ attach_driver_chain (port); for (i = 1; i < 3; i++) { struct parport *slave = port->slaves[i-1]; if (slave) attach_driver_chain(slave); } mutex_unlock(&registration_lock); } /** * parport_remove_port - deregister a parallel port * @port: parallel port to deregister * * When a parallel port driver is forcibly unloaded, or a * parallel port becomes inaccessible, the port driver must call * this function in order to deal with device drivers that still * want to use it. * * The parport structure associated with the port has its * operations structure replaced with one containing 'null' * operations that return errors or just don't do anything. * * Any drivers that have registered themselves using * parport_register_driver() are notified that the port is no * longer accessible by having their detach() routines called * with @port as the parameter. **/ void parport_remove_port(struct parport *port) { int i; mutex_lock(&registration_lock); /* Spread the word. */ detach_driver_chain (port); #ifdef CONFIG_PARPORT_1284 /* Forget the IEEE1284.3 topology of the port. */ parport_daisy_fini(port); for (i = 1; i < 3; i++) { struct parport *slave = port->slaves[i-1]; if (!slave) continue; detach_driver_chain(slave); parport_daisy_fini(slave); } #endif port->ops = &dead_ops; spin_lock(&parportlist_lock); list_del_init(&port->list); for (i = 1; i < 3; i++) { struct parport *slave = port->slaves[i-1]; if (slave) list_del_init(&slave->list); } spin_unlock(&parportlist_lock); mutex_unlock(&registration_lock); parport_proc_unregister(port); for (i = 1; i < 3; i++) { struct parport *slave = port->slaves[i-1]; if (slave) parport_put_port(slave); } } /** * parport_register_device - register a device on a parallel port * @port: port to which the device is attached * @name: a name to refer to the device * @pf: preemption callback * @kf: kick callback (wake-up) * @irq_func: interrupt handler * @flags: registration flags * @handle: data for callback functions * * This function, called by parallel port device drivers, * declares that a device is connected to a port, and tells the * system all it needs to know. * * The @name is allocated by the caller and must not be * deallocated until the caller calls @parport_unregister_device * for that device. * * The preemption callback function, @pf, is called when this * device driver has claimed access to the port but another * device driver wants to use it. It is given @handle as its * parameter, and should return zero if it is willing for the * system to release the port to another driver on its behalf. * If it wants to keep control of the port it should return * non-zero, and no action will be taken. It is good manners for * the driver to try to release the port at the earliest * opportunity after its preemption callback rejects a preemption * attempt. Note that if a preemption callback is happy for * preemption to go ahead, there is no need to release the port; * it is done automatically. This function may not block, as it * may be called from interrupt context. If the device driver * does not support preemption, @pf can be %NULL. * * The wake-up ("kick") callback function, @kf, is called when * the port is available to be claimed for exclusive access; that * is, parport_claim() is guaranteed to succeed when called from * inside the wake-up callback function. If the driver wants to * claim the port it should do so; otherwise, it need not take * any action. This function may not block, as it may be called * from interrupt context. If the device driver does not want to * be explicitly invited to claim the port in this way, @kf can * be %NULL. * * The interrupt handler, @irq_func, is called when an interrupt * arrives from the parallel port. Note that if a device driver * wants to use interrupts it should use parport_enable_irq(), * and can also check the irq member of the parport structure * representing the port. * * The parallel port (lowlevel) driver is the one that has called * request_irq() and whose interrupt handler is called first. * This handler does whatever needs to be done to the hardware to * acknowledge the interrupt (for PC-style ports there is nothing * special to be done). It then tells the IEEE 1284 code about * the interrupt, which may involve reacting to an IEEE 1284 * event depending on the current IEEE 1284 phase. After this, * it calls @irq_func. Needless to say, @irq_func will be called * from interrupt context, and may not block. * * The %PARPORT_DEV_EXCL flag is for preventing port sharing, and * so should only be used when sharing the port with other device * drivers is impossible and would lead to incorrect behaviour. * Use it sparingly! Normally, @flags will be zero. * * This function returns a pointer to a structure that represents * the device on the port, or %NULL if there is not enough memory * to allocate space for that structure. **/ struct pardevice * parport_register_device(struct parport *port, const char *name, int (*pf)(void *), void (*kf)(void *), void (*irq_func)(void *), int flags, void *handle) { struct pardevice *tmp; if (port->physport->flags & PARPORT_FLAG_EXCL) { /* An exclusive device is registered. */ printk (KERN_DEBUG "%s: no more devices allowed\n", port->name); return NULL; } if (flags & PARPORT_DEV_LURK) { if (!pf || !kf) { printk(KERN_INFO "%s: refused to register lurking device (%s) without callbacks\n", port->name, name); return NULL; } } /* We up our own module reference count, and that of the port on which a device is to be registered, to ensure that neither of us gets unloaded while we sleep in (e.g.) kmalloc. */ if (!try_module_get(port->ops->owner)) { return NULL; } parport_get_port (port); tmp = kmalloc(sizeof(struct pardevice), GFP_KERNEL); if (tmp == NULL) { printk(KERN_WARNING "%s: memory squeeze, couldn't register %s.\n", port->name, name); goto out; } tmp->state = kmalloc(sizeof(struct parport_state), GFP_KERNEL); if (tmp->state == NULL) { printk(KERN_WARNING "%s: memory squeeze, couldn't register %s.\n", port->name, name); goto out_free_pardevice; } tmp->name = name; tmp->port = port; tmp->daisy = -1; tmp->preempt = pf; tmp->wakeup = kf; tmp->private = handle; tmp->flags = flags; tmp->irq_func = irq_func; tmp->waiting = 0; tmp->timeout = 5 * HZ; /* Chain this onto the list */ tmp->prev = NULL; /* * This function must not run from an irq handler so we don' t need * to clear irq on the local CPU. -arca */ spin_lock(&port->physport->pardevice_lock); if (flags & PARPORT_DEV_EXCL) { if (port->physport->devices) { spin_unlock (&port->physport->pardevice_lock); printk (KERN_DEBUG "%s: cannot grant exclusive access for " "device %s\n", port->name, name); goto out_free_all; } port->flags |= PARPORT_FLAG_EXCL; } tmp->next = port->physport->devices; wmb(); /* Make sure that tmp->next is written before it's added to the list; see comments marked 'no locking required' */ if (port->physport->devices) port->physport->devices->prev = tmp; port->physport->devices = tmp; spin_unlock(&port->physport->pardevice_lock); init_waitqueue_head(&tmp->wait_q); tmp->timeslice = parport_default_timeslice; tmp->waitnext = tmp->waitprev = NULL; /* * This has to be run as last thing since init_state may need other * pardevice fields. -arca */ port->ops->init_state(tmp, tmp->state); if (!test_and_set_bit(PARPORT_DEVPROC_REGISTERED, &port->devflags)) { port->proc_device = tmp; parport_device_proc_register(tmp); } return tmp; out_free_all: kfree(tmp->state); out_free_pardevice: kfree(tmp); out: parport_put_port (port); module_put(port->ops->owner); return NULL; } /** * parport_unregister_device - deregister a device on a parallel port * @dev: pointer to structure representing device * * This undoes the effect of parport_register_device(). **/ void parport_unregister_device(struct pardevice *dev) { struct parport *port; #ifdef PARPORT_PARANOID if (dev == NULL) { printk(KERN_ERR "parport_unregister_device: passed NULL\n"); return; } #endif port = dev->port->physport; if (port->proc_device == dev) { port->proc_device = NULL; clear_bit(PARPORT_DEVPROC_REGISTERED, &port->devflags); parport_device_proc_unregister(dev); } if (port->cad == dev) { printk(KERN_DEBUG "%s: %s forgot to release port\n", port->name, dev->name); parport_release (dev); } spin_lock(&port->pardevice_lock); if (dev->next) dev->next->prev = dev->prev; if (dev->prev) dev->prev->next = dev->next; else port->devices = dev->next; if (dev->flags & PARPORT_DEV_EXCL) port->flags &= ~PARPORT_FLAG_EXCL; spin_unlock(&port->pardevice_lock); /* Make sure we haven't left any pointers around in the wait * list. */ spin_lock_irq(&port->waitlist_lock); if (dev->waitprev || dev->waitnext || port->waithead == dev) { if (dev->waitprev) dev->waitprev->waitnext = dev->waitnext; else port->waithead = dev->waitnext; if (dev->waitnext) dev->waitnext->waitprev = dev->waitprev; else port->waittail = dev->waitprev; } spin_unlock_irq(&port->waitlist_lock); kfree(dev->state); kfree(dev); module_put(port->ops->owner); parport_put_port (port); } /** * parport_find_number - find a parallel port by number * @number: parallel port number * * This returns the parallel port with the specified number, or * %NULL if there is none. * * There is an implicit parport_get_port() done already; to throw * away the reference to the port that parport_find_number() * gives you, use parport_put_port(). */ struct parport *parport_find_number (int number) { struct parport *port, *result = NULL; if (list_empty(&portlist)) get_lowlevel_driver (); spin_lock (&parportlist_lock); list_for_each_entry(port, &portlist, list) { if (port->number == number) { result = parport_get_port (port); break; } } spin_unlock (&parportlist_lock); return result; } /** * parport_find_base - find a parallel port by base address * @base: base I/O address * * This returns the parallel port with the specified base * address, or %NULL if there is none. * * There is an implicit parport_get_port() done already; to throw * away the reference to the port that parport_find_base() * gives you, use parport_put_port(). */ struct parport *parport_find_base (unsigned long base) { struct parport *port, *result = NULL; if (list_empty(&portlist)) get_lowlevel_driver (); spin_lock (&parportlist_lock); list_for_each_entry(port, &portlist, list) { if (port->base == base) { result = parport_get_port (port); break; } } spin_unlock (&parportlist_lock); return result; } /** * parport_claim - claim access to a parallel port device * @dev: pointer to structure representing a device on the port * * This function will not block and so can be used from interrupt * context. If parport_claim() succeeds in claiming access to * the port it returns zero and the port is available to use. It * may fail (returning non-zero) if the port is in use by another * driver and that driver is not willing to relinquish control of * the port. **/ int parport_claim(struct pardevice *dev) { struct pardevice *oldcad; struct parport *port = dev->port->physport; unsigned long flags; if (port->cad == dev) { printk(KERN_INFO "%s: %s already owner\n", dev->port->name,dev->name); return 0; } /* Preempt any current device */ write_lock_irqsave (&port->cad_lock, flags); if ((oldcad = port->cad) != NULL) { if (oldcad->preempt) { if (oldcad->preempt(oldcad->private)) goto blocked; port->ops->save_state(port, dev->state); } else goto blocked; if (port->cad != oldcad) { /* I think we'll actually deadlock rather than get here, but just in case.. */ printk(KERN_WARNING "%s: %s released port when preempted!\n", port->name, oldcad->name); if (port->cad) goto blocked; } } /* Can't fail from now on, so mark ourselves as no longer waiting. */ if (dev->waiting & 1) { dev->waiting = 0; /* Take ourselves out of the wait list again. */ spin_lock_irq (&port->waitlist_lock); if (dev->waitprev) dev->waitprev->waitnext = dev->waitnext; else port->waithead = dev->waitnext; if (dev->waitnext) dev->waitnext->waitprev = dev->waitprev; else port->waittail = dev->waitprev; spin_unlock_irq (&port->waitlist_lock); dev->waitprev = dev->waitnext = NULL; } /* Now we do the change of devices */ port->cad = dev; #ifdef CONFIG_PARPORT_1284 /* If it's a mux port, select it. */ if (dev->port->muxport >= 0) { /* FIXME */ port->muxsel = dev->port->muxport; } /* If it's a daisy chain device, select it. */ if (dev->daisy >= 0) { /* This could be lazier. */ if (!parport_daisy_select (port, dev->daisy, IEEE1284_MODE_COMPAT)) port->daisy = dev->daisy; } #endif /* IEEE1284.3 support */ /* Restore control registers */ port->ops->restore_state(port, dev->state); write_unlock_irqrestore(&port->cad_lock, flags); dev->time = jiffies; return 0; blocked: /* If this is the first time we tried to claim the port, register an interest. This is only allowed for devices sleeping in parport_claim_or_block(), or those with a wakeup function. */ /* The cad_lock is still held for writing here */ if (dev->waiting & 2 || dev->wakeup) { spin_lock (&port->waitlist_lock); if (test_and_set_bit(0, &dev->waiting) == 0) { /* First add ourselves to the end of the wait list. */ dev->waitnext = NULL; dev->waitprev = port->waittail; if (port->waittail) { port->waittail->waitnext = dev; port->waittail = dev; } else port->waithead = port->waittail = dev; } spin_unlock (&port->waitlist_lock); } write_unlock_irqrestore (&port->cad_lock, flags); return -EAGAIN; } /** * parport_claim_or_block - claim access to a parallel port device * @dev: pointer to structure representing a device on the port * * This behaves like parport_claim(), but will block if necessary * to wait for the port to be free. A return value of 1 * indicates that it slept; 0 means that it succeeded without * needing to sleep. A negative error code indicates failure. **/ int parport_claim_or_block(struct pardevice *dev) { int r; /* Signal to parport_claim() that we can wait even without a wakeup function. */ dev->waiting = 2; /* Try to claim the port. If this fails, we need to sleep. */ r = parport_claim(dev); if (r == -EAGAIN) { #ifdef PARPORT_DEBUG_SHARING printk(KERN_DEBUG "%s: parport_claim() returned -EAGAIN\n", dev->name); #endif /* * FIXME!!! Use the proper locking for dev->waiting, * and make this use the "wait_event_interruptible()" * interfaces. The cli/sti that used to be here * did nothing. * * See also parport_release() */ /* If dev->waiting is clear now, an interrupt gave us the port and we would deadlock if we slept. */ if (dev->waiting) { interruptible_sleep_on (&dev->wait_q); if (signal_pending (current)) { return -EINTR; } r = 1; } else { r = 0; #ifdef PARPORT_DEBUG_SHARING printk(KERN_DEBUG "%s: didn't sleep in parport_claim_or_block()\n", dev->name); #endif } #ifdef PARPORT_DEBUG_SHARING if (dev->port->physport->cad != dev) printk(KERN_DEBUG "%s: exiting parport_claim_or_block " "but %s owns port!\n", dev->name, dev->port->physport->cad ? dev->port->physport->cad->name:"nobody"); #endif } dev->waiting = 0; return r; } /** * parport_release - give up access to a parallel port device * @dev: pointer to structure representing parallel port device * * This function cannot fail, but it should not be called without * the port claimed. Similarly, if the port is already claimed * you should not try claiming it again. **/ void parport_release(struct pardevice *dev) { struct parport *port = dev->port->physport; struct pardevice *pd; unsigned long flags; /* Make sure that dev is the current device */ write_lock_irqsave(&port->cad_lock, flags); if (port->cad != dev) { write_unlock_irqrestore (&port->cad_lock, flags); printk(KERN_WARNING "%s: %s tried to release parport " "when not owner\n", port->name, dev->name); return; } #ifdef CONFIG_PARPORT_1284 /* If this is on a mux port, deselect it. */ if (dev->port->muxport >= 0) { /* FIXME */ port->muxsel = -1; } /* If this is a daisy device, deselect it. */ if (dev->daisy >= 0) { parport_daisy_deselect_all (port); port->daisy = -1; } #endif port->cad = NULL; write_unlock_irqrestore(&port->cad_lock, flags); /* Save control registers */ port->ops->save_state(port, dev->state); /* If anybody is waiting, find out who's been there longest and then wake them up. (Note: no locking required) */ /* !!! LOCKING IS NEEDED HERE */ for (pd = port->waithead; pd; pd = pd->waitnext) { if (pd->waiting & 2) { /* sleeping in claim_or_block */ parport_claim(pd); if (waitqueue_active(&pd->wait_q)) wake_up_interruptible(&pd->wait_q); return; } else if (pd->wakeup) { pd->wakeup(pd->private); if (dev->port->cad) /* racy but no matter */ return; } else { printk(KERN_ERR "%s: don't know how to wake %s\n", port->name, pd->name); } } /* Nobody was waiting, so walk the list to see if anyone is interested in being woken up. (Note: no locking required) */ /* !!! LOCKING IS NEEDED HERE */ for (pd = port->devices; (port->cad == NULL) && pd; pd = pd->next) { if (pd->wakeup && pd != dev) pd->wakeup(pd->private); } } irqreturn_t parport_irq_handler(int irq, void *dev_id) { struct parport *port = dev_id; parport_generic_irq(port); return IRQ_HANDLED; } /* Exported symbols for modules. */ EXPORT_SYMBOL(parport_claim); EXPORT_SYMBOL(parport_claim_or_block); EXPORT_SYMBOL(parport_release); EXPORT_SYMBOL(parport_register_port); EXPORT_SYMBOL(parport_announce_port); EXPORT_SYMBOL(parport_remove_port); EXPORT_SYMBOL(parport_register_driver); EXPORT_SYMBOL(parport_unregister_driver); EXPORT_SYMBOL(parport_register_device); EXPORT_SYMBOL(parport_unregister_device); EXPORT_SYMBOL(parport_get_port); EXPORT_SYMBOL(parport_put_port); EXPORT_SYMBOL(parport_find_number); EXPORT_SYMBOL(parport_find_base); EXPORT_SYMBOL(parport_irq_handler); MODULE_LICENSE("GPL");
gpl-2.0
Alucard24/SGS4-SAMMY-Kernel
fs/nls/nls_iso8859-7.c
12566
13558
/* * linux/fs/nls/nls_iso8859-7.c * * Charset iso8859-7 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, /* 0x90*/ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, /* 0xa0*/ 0x00a0, 0x02bd, 0x02bc, 0x00a3, 0x0000, 0x0000, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x0000, 0x00ab, 0x00ac, 0x00ad, 0x0000, 0x2015, /* 0xb0*/ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x0384, 0x0385, 0x0386, 0x00b7, 0x0388, 0x0389, 0x038a, 0x00bb, 0x038c, 0x00bd, 0x038e, 0x038f, /* 0xc0*/ 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f, /* 0xd0*/ 0x03a0, 0x03a1, 0x0000, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7, 0x03a8, 0x03a9, 0x03aa, 0x03ab, 0x03ac, 0x03ad, 0x03ae, 0x03af, /* 0xe0*/ 0x03b0, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7, 0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf, /* 0xf0*/ 0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7, 0x03c8, 0x03c9, 0x03ca, 0x03cb, 0x03cc, 0x03cd, 0x03ce, 0x0000, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0x00, 0x00, 0xa3, 0x00, 0x00, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0x00, 0xab, 0xac, 0xad, 0x00, 0x00, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0x00, 0x00, 0x00, 0xb7, /* 0xb0-0xb7 */ 0x00, 0x00, 0x00, 0xbb, 0x00, 0xbd, 0x00, 0x00, /* 0xb8-0xbf */ }; static const unsigned char page02[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */ 0x00, 0x00, 0x00, 0x00, 0xa2, 0xa1, 0x00, 0x00, /* 0xb8-0xbf */ }; static const unsigned char page03[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0xb5, 0xb6, 0x00, /* 0x80-0x87 */ 0xb8, 0xb9, 0xba, 0x00, 0xbc, 0x00, 0xbe, 0xbf, /* 0x88-0x8f */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0x90-0x97 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0x98-0x9f */ 0xd0, 0xd1, 0x00, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xa0-0xa7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xa8-0xaf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xb0-0xb7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xb8-0xbf */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xc0-0xc7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0x00, /* 0xc8-0xcf */ }; static const unsigned char page20[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0xaf, 0x00, 0x00, /* 0x10-0x17 */ }; static const unsigned char *const page_uni2charset[256] = { page00, NULL, page02, page03, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page20, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0x00, 0x00, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0x00, 0xab, 0xac, 0xad, 0x00, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xdc, 0xb7, /* 0xb0-0xb7 */ 0xdd, 0xde, 0xdf, 0xbb, 0xfc, 0xbd, 0xfd, 0xfe, /* 0xb8-0xbf */ 0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xc0-0xc7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xc8-0xcf */ 0xf0, 0xf1, 0x00, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xd0-0xd7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0x00, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0x00, 0x00, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0x00, 0xab, 0xac, 0xad, 0x00, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0x00, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xb6, 0xb8, 0xb9, 0xba, /* 0xd8-0xdf */ 0xe0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xe0-0xe7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xe8-0xef */ 0xd0, 0xd1, 0xd3, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xf0-0xf7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xbc, 0xbe, 0xbf, 0x00, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "iso8859-7", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, .owner = THIS_MODULE, }; static int __init init_nls_iso8859_7(void) { return register_nls(&table); } static void __exit exit_nls_iso8859_7(void) { unregister_nls(&table); } module_init(init_nls_iso8859_7) module_exit(exit_nls_iso8859_7) MODULE_LICENSE("Dual BSD/GPL");
gpl-2.0
WildfireDEV/android_kernel_htc_holiday
fs/nls/nls_cp852.c
12566
14830
/* * linux/fs/nls/nls_cp852.c * * Charset cp852 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x016f, 0x0107, 0x00e7, 0x0142, 0x00eb, 0x0150, 0x0151, 0x00ee, 0x0179, 0x00c4, 0x0106, /* 0x90*/ 0x00c9, 0x0139, 0x013a, 0x00f4, 0x00f6, 0x013d, 0x013e, 0x015a, 0x015b, 0x00d6, 0x00dc, 0x0164, 0x0165, 0x0141, 0x00d7, 0x010d, /* 0xa0*/ 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x0104, 0x0105, 0x017d, 0x017e, 0x0118, 0x0119, 0x00ac, 0x017a, 0x010c, 0x015f, 0x00ab, 0x00bb, /* 0xb0*/ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00c1, 0x00c2, 0x011a, 0x015e, 0x2563, 0x2551, 0x2557, 0x255d, 0x017b, 0x017c, 0x2510, /* 0xc0*/ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x0102, 0x0103, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x00a4, /* 0xd0*/ 0x0111, 0x0110, 0x010e, 0x00cb, 0x010f, 0x0147, 0x00cd, 0x00ce, 0x011b, 0x2518, 0x250c, 0x2588, 0x2584, 0x0162, 0x016e, 0x2580, /* 0xe0*/ 0x00d3, 0x00df, 0x00d4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00da, 0x0155, 0x0170, 0x00fd, 0x00dd, 0x0163, 0x00b4, /* 0xf0*/ 0x00ad, 0x02dd, 0x02db, 0x02c7, 0x02d8, 0x00a7, 0x00f7, 0x00b8, 0x00b0, 0x00a8, 0x02d9, 0x0171, 0x0158, 0x0159, 0x25a0, 0x00a0, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xff, 0x00, 0x00, 0x00, 0xcf, 0x00, 0x00, 0xf5, /* 0xa0-0xa7 */ 0xf9, 0x00, 0x00, 0xae, 0xaa, 0xf0, 0x00, 0x00, /* 0xa8-0xaf */ 0xf8, 0x00, 0x00, 0x00, 0xef, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */ 0xf7, 0x00, 0x00, 0xaf, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */ 0x00, 0xb5, 0xb6, 0x00, 0x8e, 0x00, 0x00, 0x80, /* 0xc0-0xc7 */ 0x00, 0x90, 0x00, 0xd3, 0x00, 0xd6, 0xd7, 0x00, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0xe0, 0xe2, 0x00, 0x99, 0x9e, /* 0xd0-0xd7 */ 0x00, 0x00, 0xe9, 0x00, 0x9a, 0xed, 0x00, 0xe1, /* 0xd8-0xdf */ 0x00, 0xa0, 0x83, 0x00, 0x84, 0x00, 0x00, 0x87, /* 0xe0-0xe7 */ 0x00, 0x82, 0x00, 0x89, 0x00, 0xa1, 0x8c, 0x00, /* 0xe8-0xef */ 0x00, 0x00, 0x00, 0xa2, 0x93, 0x00, 0x94, 0xf6, /* 0xf0-0xf7 */ 0x00, 0x00, 0xa3, 0x00, 0x81, 0xec, 0x00, 0x00, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0x00, 0x00, 0xc6, 0xc7, 0xa4, 0xa5, 0x8f, 0x86, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xac, 0x9f, 0xd2, 0xd4, /* 0x08-0x0f */ 0xd1, 0xd0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xa8, 0xa9, 0xb7, 0xd8, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x91, 0x92, 0x00, 0x00, 0x95, 0x96, 0x00, /* 0x38-0x3f */ 0x00, 0x9d, 0x88, 0xe3, 0xe4, 0x00, 0x00, 0xd5, /* 0x40-0x47 */ 0xe5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x8a, 0x8b, 0x00, 0x00, 0xe8, 0xea, 0x00, 0x00, /* 0x50-0x57 */ 0xfc, 0xfd, 0x97, 0x98, 0x00, 0x00, 0xb8, 0xad, /* 0x58-0x5f */ 0xe6, 0xe7, 0xdd, 0xee, 0x9b, 0x9c, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0x85, /* 0x68-0x6f */ 0xeb, 0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x8d, 0xab, 0xbd, 0xbe, 0xa6, 0xa7, 0x00, /* 0x78-0x7f */ }; static const unsigned char page02[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, /* 0xc0-0xc7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */ 0xf4, 0xfa, 0x00, 0xf2, 0x00, 0xf1, 0x00, 0x00, /* 0xd8-0xdf */ }; static const unsigned char page25[256] = { 0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xcd, 0xba, 0x00, 0x00, 0xc9, 0x00, 0x00, 0xbb, /* 0x50-0x57 */ 0x00, 0x00, 0xc8, 0x00, 0x00, 0xbc, 0x00, 0x00, /* 0x58-0x5f */ 0xcc, 0x00, 0x00, 0xb9, 0x00, 0x00, 0xcb, 0x00, /* 0x60-0x67 */ 0x00, 0xca, 0x00, 0x00, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0xdb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, page02, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8b, 0x8b, 0x8c, 0xab, 0x84, 0x86, /* 0x88-0x8f */ 0x82, 0x92, 0x92, 0x93, 0x94, 0x96, 0x96, 0x98, /* 0x90-0x97 */ 0x98, 0x94, 0x81, 0x9c, 0x9c, 0x88, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa5, 0xa5, 0xa7, 0xa7, /* 0xa0-0xa7 */ 0xa9, 0xa9, 0xaa, 0xab, 0x9f, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xa0, 0x83, 0xd8, /* 0xb0-0xb7 */ 0xad, 0xb9, 0xba, 0xbb, 0xbc, 0xbe, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc7, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd0, 0xd4, 0x89, 0xd4, 0xe5, 0xa1, 0x8c, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xee, 0x85, 0xdf, /* 0xd8-0xdf */ 0xa2, 0xe1, 0x93, 0xe4, 0xe4, 0xe5, 0xe7, 0xe7, /* 0xe0-0xe7 */ 0xea, 0xa3, 0xea, 0xfb, 0xec, 0xec, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfd, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x9a, 0x90, 0xb6, 0x8e, 0xde, 0x8f, 0x80, /* 0x80-0x87 */ 0x9d, 0xd3, 0x8a, 0x8a, 0xd7, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x91, 0xe2, 0x99, 0x95, 0x95, 0x97, /* 0x90-0x97 */ 0x97, 0x99, 0x9a, 0x9b, 0x9b, 0x9d, 0x9e, 0xac, /* 0x98-0x9f */ 0xb5, 0xd6, 0xe0, 0xe9, 0xa4, 0xa4, 0xa6, 0xa6, /* 0xa0-0xa7 */ 0xa8, 0xa8, 0xaa, 0x8d, 0xac, 0xb8, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbd, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd1, 0xd1, 0xd2, 0xd3, 0xd2, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xb7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe3, 0xd5, 0xe6, 0xe6, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xe8, 0xeb, 0xed, 0xed, 0xdd, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xeb, 0xfc, 0xfc, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "cp852", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, .owner = THIS_MODULE, }; static int __init init_nls_cp852(void) { return register_nls(&table); } static void __exit exit_nls_cp852(void) { unregister_nls(&table); } module_init(init_nls_cp852) module_exit(exit_nls_cp852) MODULE_LICENSE("Dual BSD/GPL");
gpl-2.0
varigit/wl18xx
fs/nls/nls_cp775.c
12566
13576
/* * linux/fs/nls/nls_cp775.c * * Charset cp775 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x0106, 0x00fc, 0x00e9, 0x0101, 0x00e4, 0x0123, 0x00e5, 0x0107, 0x0142, 0x0113, 0x0156, 0x0157, 0x012b, 0x0179, 0x00c4, 0x00c5, /* 0x90*/ 0x00c9, 0x00e6, 0x00c6, 0x014d, 0x00f6, 0x0122, 0x00a2, 0x015a, 0x015b, 0x00d6, 0x00dc, 0x00f8, 0x00a3, 0x00d8, 0x00d7, 0x00a4, /* 0xa0*/ 0x0100, 0x012a, 0x00f3, 0x017b, 0x017c, 0x017a, 0x201d, 0x00a6, 0x00a9, 0x00ae, 0x00ac, 0x00bd, 0x00bc, 0x0141, 0x00ab, 0x00bb, /* 0xb0*/ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0104, 0x010c, 0x0118, 0x0116, 0x2563, 0x2551, 0x2557, 0x255d, 0x012e, 0x0160, 0x2510, /* 0xc0*/ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x0172, 0x016a, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x017d, /* 0xd0*/ 0x0105, 0x010d, 0x0119, 0x0117, 0x012f, 0x0161, 0x0173, 0x016b, 0x017e, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, /* 0xe0*/ 0x00d3, 0x00df, 0x014c, 0x0143, 0x00f5, 0x00d5, 0x00b5, 0x0144, 0x0136, 0x0137, 0x013b, 0x013c, 0x0146, 0x0112, 0x0145, 0x2019, /* 0xf0*/ 0x00ad, 0x00b1, 0x201c, 0x00be, 0x00b6, 0x00a7, 0x00f7, 0x201e, 0x00b0, 0x2219, 0x00b7, 0x00b9, 0x00b3, 0x00b2, 0x25a0, 0x00a0, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xff, 0x00, 0x96, 0x9c, 0x9f, 0x00, 0xa7, 0xf5, /* 0xa0-0xa7 */ 0x00, 0xa8, 0x00, 0xae, 0xaa, 0xf0, 0xa9, 0x00, /* 0xa8-0xaf */ 0xf8, 0xf1, 0xfd, 0xfc, 0x00, 0xe6, 0xf4, 0xfa, /* 0xb0-0xb7 */ 0x00, 0xfb, 0x00, 0xaf, 0xac, 0xab, 0xf3, 0x00, /* 0xb8-0xbf */ 0x00, 0x00, 0x00, 0x00, 0x8e, 0x8f, 0x92, 0x00, /* 0xc0-0xc7 */ 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0xe0, 0x00, 0xe5, 0x99, 0x9e, /* 0xd0-0xd7 */ 0x9d, 0x00, 0x00, 0x00, 0x9a, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */ 0x00, 0x00, 0x00, 0x00, 0x84, 0x86, 0x91, 0x00, /* 0xe0-0xe7 */ 0x00, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */ 0x00, 0x00, 0x00, 0xa2, 0x00, 0xe4, 0x94, 0xf6, /* 0xf0-0xf7 */ 0x9b, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0xa0, 0x83, 0x00, 0x00, 0xb5, 0xd0, 0x80, 0x87, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xb6, 0xd1, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0xed, 0x89, 0x00, 0x00, 0xb8, 0xd3, /* 0x10-0x17 */ 0xb7, 0xd2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x95, 0x85, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0xa1, 0x8c, 0x00, 0x00, 0xbd, 0xd4, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0xe9, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0xea, 0xeb, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0xad, 0x88, 0xe3, 0xe7, 0xee, 0xec, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0xe2, 0x93, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8a, 0x8b, /* 0x50-0x57 */ 0x00, 0x00, 0x97, 0x98, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0xbe, 0xd5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0xc7, 0xd7, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0xc6, 0xd6, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x8d, 0xa5, 0xa3, 0xa4, 0xcf, 0xd8, 0x00, /* 0x78-0x7f */ }; static const unsigned char page20[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0xef, 0x00, 0x00, 0xf2, 0xa6, 0xf7, 0x00, /* 0x18-0x1f */ }; static const unsigned char page22[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ }; static const unsigned char page25[256] = { 0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xcd, 0xba, 0x00, 0x00, 0xc9, 0x00, 0x00, 0xbb, /* 0x50-0x57 */ 0x00, 0x00, 0xc8, 0x00, 0x00, 0xbc, 0x00, 0x00, /* 0x58-0x5f */ 0xcc, 0x00, 0x00, 0xb9, 0x00, 0x00, 0xcb, 0x00, /* 0x60-0x67 */ 0x00, 0xca, 0x00, 0x00, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page20, NULL, page22, NULL, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8b, 0x8b, 0x8c, 0xa5, 0x84, 0x86, /* 0x88-0x8f */ 0x82, 0x91, 0x91, 0x93, 0x94, 0x85, 0x96, 0x98, /* 0x90-0x97 */ 0x98, 0x94, 0x81, 0x9b, 0x9c, 0x9b, 0x9e, 0x9f, /* 0x98-0x9f */ 0x83, 0x8c, 0xa2, 0xa4, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0x88, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xd0, 0xd1, 0xd2, /* 0xb0-0xb7 */ 0xd3, 0xb9, 0xba, 0xbb, 0xbc, 0xd4, 0xd5, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xd6, 0xd7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xd8, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xa2, 0xe1, 0x93, 0xe7, 0xe4, 0xe4, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe9, 0xe9, 0xeb, 0xeb, 0xec, 0x89, 0xec, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x9a, 0x90, 0xa0, 0x8e, 0x95, 0x8f, 0x80, /* 0x80-0x87 */ 0xad, 0xed, 0x8a, 0x8a, 0xa1, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x92, 0x92, 0xe2, 0x99, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x97, 0x99, 0x9a, 0x9d, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xe0, 0xa3, 0xa3, 0x8d, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xb5, 0xb6, 0xb7, 0xb8, 0xbd, 0xbe, 0xc6, 0xc7, /* 0xd0-0xd7 */ 0xcf, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe5, 0xe5, 0x00, 0xe3, /* 0xe0-0xe7 */ 0xe8, 0xe8, 0xea, 0xea, 0xee, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "cp775", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, .owner = THIS_MODULE, }; static int __init init_nls_cp775(void) { return register_nls(&table); } static void __exit exit_nls_cp775(void) { unregister_nls(&table); } module_init(init_nls_cp775) module_exit(exit_nls_cp775) MODULE_LICENSE("Dual BSD/GPL");
gpl-2.0
Entropy512/linux_kernel_sgh-i997r
fs/nls/nls_cp865.c
12566
17508
/* * linux/fs/nls/nls_cp865.c * * Charset cp865 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00e4, 0x00e0, 0x00e5, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x00ec, 0x00c4, 0x00c5, /* 0x90*/ 0x00c9, 0x00e6, 0x00c6, 0x00f4, 0x00f6, 0x00f2, 0x00fb, 0x00f9, 0x00ff, 0x00d6, 0x00dc, 0x00f8, 0x00a3, 0x00d8, 0x20a7, 0x0192, /* 0xa0*/ 0x00e1, 0x00ed, 0x00f3, 0x00fa, 0x00f1, 0x00d1, 0x00aa, 0x00ba, 0x00bf, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00a1, 0x00ab, 0x00a4, /* 0xb0*/ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510, /* 0xc0*/ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567, /* 0xd0*/ 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, /* 0xe0*/ 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229, /* 0xf0*/ 0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xff, 0xad, 0x00, 0x9c, 0xaf, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ 0x00, 0x00, 0xa6, 0xae, 0xaa, 0x00, 0x00, 0x00, /* 0xa8-0xaf */ 0xf8, 0xf1, 0xfd, 0x00, 0x00, 0xe6, 0x00, 0xfa, /* 0xb0-0xb7 */ 0x00, 0x00, 0xa7, 0x00, 0xac, 0xab, 0x00, 0xa8, /* 0xb8-0xbf */ 0x00, 0x00, 0x00, 0x00, 0x8e, 0x8f, 0x92, 0x80, /* 0xc0-0xc7 */ 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */ 0x00, 0xa5, 0x00, 0x00, 0x00, 0x00, 0x99, 0x00, /* 0xd0-0xd7 */ 0x9d, 0x00, 0x00, 0x00, 0x9a, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */ 0x85, 0xa0, 0x83, 0x00, 0x84, 0x86, 0x91, 0x87, /* 0xe0-0xe7 */ 0x8a, 0x82, 0x88, 0x89, 0x8d, 0xa1, 0x8c, 0x8b, /* 0xe8-0xef */ 0x00, 0xa4, 0x95, 0xa2, 0x93, 0x00, 0x94, 0xf6, /* 0xf0-0xf7 */ 0x9b, 0x97, 0xa3, 0x96, 0x81, 0x00, 0x00, 0x98, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ }; static const unsigned char page03[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0xe9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0xe8, 0x00, /* 0xa0-0xa7 */ 0x00, 0xea, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */ 0x00, 0xe0, 0x00, 0x00, 0xeb, 0xee, 0x00, 0x00, /* 0xb0-0xb7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */ 0xe3, 0x00, 0x00, 0xe5, 0xe7, 0x00, 0xed, 0x00, /* 0xc0-0xc7 */ }; static const unsigned char page20[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9e, /* 0xa0-0xa7 */ }; static const unsigned char page22[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0xec, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0xf0, 0x00, 0x00, 0xf3, 0xf2, 0x00, 0x00, /* 0x60-0x67 */ }; static const unsigned char page23[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0xf4, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ }; static const unsigned char page25[256] = { 0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */ 0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */ 0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */ 0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, NULL, page03, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page20, NULL, page22, page23, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x87, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x84, 0x86, /* 0x88-0x8f */ 0x82, 0x91, 0x91, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x94, 0x81, 0x9b, 0x9c, 0x9b, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa4, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0x00, 0xe3, 0xe5, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xed, 0x00, 0x00, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x9a, 0x90, 0x00, 0x8e, 0x00, 0x8f, 0x80, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x92, 0x92, 0x00, 0x99, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x99, 0x9a, 0x9d, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */ 0x00, 0x00, 0x00, 0x00, 0xa5, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0x00, 0xe1, 0xe2, 0x00, 0xe4, 0xe4, 0x00, 0x00, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0x00, 0xec, 0xe8, 0x00, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "cp865", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, .owner = THIS_MODULE, }; static int __init init_nls_cp865(void) { return register_nls(&table); } static void __exit exit_nls_cp865(void) { unregister_nls(&table); } module_init(init_nls_cp865) module_exit(exit_nls_cp865) MODULE_LICENSE("Dual BSD/GPL");
gpl-2.0
jobermayr/pcsx2
plugins/CDVDisoEFP/src/Win32/CDVDiso.c
23
15302
/* CDVDiso.c * Copyright (C) 2002-2005 PCSX2 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * PCSX2 members can be contacted through their website at www.pcsx2.net. */ #include <windows.h> // BOOL, CALLBACK, APIENTRY #include <windef.h> // NULL #define CDVDdefs #include "../PS2Edefs.h" #include "conf.h" #include "actualfile.h" #include "../isofile.h" #include "logfile.h" #include "../convert.h" #include "../version.h" #include "screens.h" #include "mainbox.h" // Initialize mainboxwindow #include "progressbox.h" // Initialize progressboxwindow #include "conversionbox.h" // Initialize conversionboxwindow #include "devicebox.h" // Initialize deviceboxwindow #include "CDVDiso.h" struct IsoFile *isofile; char isobuffer[2448]; char isocdcheck[2048]; int isomode; int deviceopencount; HINSTANCE progmodule; BOOL APIENTRY DllMain(HANDLE hModule, DWORD param, LPVOID reserved) { switch (param) { case DLL_PROCESS_ATTACH: progmodule = hModule; // mainboxwindow = NULL; // progressboxwindow = NULL; // conversionboxwindow = NULL; // deviceboxwindow = NULL; return(TRUE); break; case DLL_PROCESS_DETACH: // CDVDshutdown(); return(TRUE); break; case DLL_THREAD_ATTACH: return(TRUE); break; case DLL_THREAD_DETACH: return(TRUE); break; } // ENDSWITCH param- What does the OS want with us? return(FALSE); // Wasn't on list? Wasn't handled. } // END DllMain() char* CALLBACK PS2EgetLibName() { return(libname); } // END PS2EgetLibName() u32 CALLBACK PS2EgetLibType() { return(PS2E_LT_CDVD); } // END PS2getLibType() u32 CALLBACK PS2EgetLibVersion2(u32 type) { return((version << 16) | (revision << 8) | build); } // END PS2EgetLibVersion2() s32 CALLBACK CDVDinit() { int i; InitLog(); if (OpenLog() != 0) return(-1); // Couldn't open Log File? Abort. #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDinit()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ InitConf(); isofile = NULL; isomode = -1; deviceopencount = 0; for (i = 0; i < 2048; i++) isocdcheck[i] = 0; mainboxwindow = NULL; progressboxwindow = NULL; conversionboxwindow = NULL; deviceboxwindow = NULL; return(0); } // END CDVDinit() void CALLBACK CDVDshutdown() { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDshutdown()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ isofile = IsoFileClose(isofile); // Close Windows as well? (Just in case) CloseLog(); } // END CDVDshutdown() s32 CALLBACK CDVDopen(const char* pTitleFilename) { HWND lastwindow; int i; int retval; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDopen()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ lastwindow = GetActiveWindow(); LoadConf(); if (pTitleFilename != NULL) strcpy(conf.isoname, pTitleFilename); if ((conf.isoname[0] == 0) || (conf.isoname[0] == '[') || ((conf.startconfigure == 1) && (deviceopencount == 0)) || ((conf.restartconfigure == 1) && (deviceopencount > 0))) { DialogBox(progmodule, MAKEINTRESOURCE(DLG_0200), lastwindow, (DLGPROC)MainBoxCallback); SetActiveWindow(lastwindow); LoadConf(); // Blank out the name in config file afterwards? Seems excessive. } // ENDIF- Haven't initialized the configure program yet? Do so now. lastwindow = NULL; isofile = IsoFileOpenForRead(conf.isoname); if (isofile == NULL) { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: Failed to open ISO file!"); #endif /* VERBOSE_FUNCTION_INTERFACE */ // return(-1); // Removed to simulate disc not in drive. for (i = 0; i < 2048; i++) isocdcheck[i] = 0; return(0); } // ENDIF- Trouble opening file? Abort. retval = IsoFileSeek(isofile, 16); if (retval != 0) return(-1); retval = IsoFileRead(isofile, isobuffer); if (retval != 0) return(-1); if (deviceopencount > 0) { i = 0; while ((i < 2048) && (isocdcheck[i] == isobuffer[i])) i++; if (i == 2048) deviceopencount = 0; // Same CD/DVD? No delay. } // ENDIF- Is this a restart? Check for disc change. for (i = 0; i < 2048; i++) isocdcheck[i] = isobuffer[i]; return(0); } // END CDVDopen() void CALLBACK CDVDclose() { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDclose()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ isofile = IsoFileClose(isofile); deviceopencount = 50; } // END CDVDclose() s32 CALLBACK CDVDreadSubQ(u32 lsn, cdvdSubQ* subq) { char temptime[3]; int i; int pos; u32 tracklsn; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDreadSubQ()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(-1); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(-1); } // ENDIF- Still simulating device tray open? if ((isofile->cdvdtype == CDVD_TYPE_PS2DVD) || (isofile->cdvdtype == CDVD_TYPE_DVDV)) { return(-1); // DVDs don't have SubQ data } // ENDIF- Trying to get a SubQ from a DVD? // fake it i = BCDTOHEX(isofile->toc[7]); pos = i * 10; pos += 30; temptime[0] = BCDTOHEX(isofile->toc[pos + 7]); temptime[1] = BCDTOHEX(isofile->toc[pos + 8]); temptime[2] = BCDTOHEX(isofile->toc[pos + 9]); tracklsn = MSFtoLBA(temptime); while ((i < BCDTOHEX(isofile->toc[17])) && (tracklsn < lsn)) { i++; pos = i * 10; pos += 30; temptime[0] = BCDTOHEX(isofile->toc[pos + 7]); temptime[1] = BCDTOHEX(isofile->toc[pos + 8]); temptime[2] = BCDTOHEX(isofile->toc[pos + 9]); tracklsn = MSFtoLBA(temptime); } // ENDIF- Loop through tracks searching for lsn track i--; subq->ctrl = 4; subq->mode = 1; subq->trackNum = HEXTOBCD(i); subq->trackIndex = HEXTOBCD(i); LBAtoMSF(lsn - tracklsn, temptime); subq->trackM = HEXTOBCD(temptime[0]); subq->trackS = HEXTOBCD(temptime[1]); subq->trackF = HEXTOBCD(temptime[2]); subq->pad = 0; // lba_to_msf(lsn + (2*75), &min, &sec, &frm); LBAtoMSF(lsn, temptime); subq->discM = HEXTOBCD(temptime[0]); subq->discS = HEXTOBCD(temptime[1]); subq->discF = HEXTOBCD(temptime[2]); return(0); } // END CDVDreadSubQ() s32 CALLBACK CDVDgetTN(cdvdTN *Buffer) { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDgetTN()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(-1); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(-1); } // ENDIF- Still simulating device tray open? if ((isofile->cdvdtype == CDVD_TYPE_PS2DVD) || (isofile->cdvdtype == CDVD_TYPE_DVDV)) { Buffer->strack = 1; Buffer->etrack = 1; } else { Buffer->strack = BCDTOHEX(isofile->toc[7]); Buffer->etrack = BCDTOHEX(isofile->toc[17]); } // ENDIF- Retrieve track info from a DVD? (or a CD?) return(0); } // END CDVDgetTN() s32 CALLBACK CDVDgetTD(u8 track, cdvdTD *Buffer) { u8 actualtrack; int pos; char temptime[3]; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDgetTD()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(-1); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(-1); } // ENDIF- Still simulating device tray open? actualtrack = track; if (actualtrack == 0xaa) actualtrack = 0; if ((isofile->cdvdtype == CDVD_TYPE_PS2DVD) || (isofile->cdvdtype == CDVD_TYPE_DVDV)) { if (actualtrack <= 1) { Buffer->type = 0; Buffer->lsn = isofile->filesectorsize; } else { Buffer->type = CDVD_MODE1_TRACK; Buffer->lsn = 0; } // ENDIF- Whole disc? (or single track?) } else { if (actualtrack == 0) { Buffer->type = 0; temptime[0] = BCDTOHEX(isofile->toc[27]); temptime[1] = BCDTOHEX(isofile->toc[28]); temptime[2] = BCDTOHEX(isofile->toc[29]); Buffer->lsn = MSFtoLBA(temptime); } else { pos = actualtrack * 10; pos += 30; Buffer->type = isofile->toc[pos]; temptime[0] = BCDTOHEX(isofile->toc[pos + 7]); temptime[1] = BCDTOHEX(isofile->toc[pos + 8]); temptime[2] = BCDTOHEX(isofile->toc[pos + 9]); Buffer->lsn = MSFtoLBA(temptime); } // ENDIF- Whole disc? (or single track?) } // ENDIF- Retrieve track info from a DVD? (or a CD?) return(0); } // END CDVDgetTD() s32 CALLBACK CDVDgetTOC(void* toc) { int i; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDgetTOC()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(-1); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(-1); } // ENDIF- Still simulating device tray open? for (i = 0; i < 2048; i++) *(((char *) toc) + i) = isofile->toc[i]; return(0); } // END CDVDgetTOC() s32 CALLBACK CDVDreadTrack(u32 lsn, int mode) { int retval; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDreadTrack(%u)", lsn); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(-1); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(-1); } // ENDIF- Still simulating device tray open? retval = IsoFileSeek(isofile, (off64_t) lsn); if (retval != 0) { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: Trouble finding the sector!"); #endif /* VERBOSE_FUNCTION_INTERFACE */ return(-1); } // ENDIF- Trouble finding the sector? retval = IsoFileRead(isofile, isobuffer); if (retval != 0) { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: Trouble reading the sector!"); #endif /* VERBOSE_FUNCTION_INTERFACE */ return(-1); } // ENDIF- Trouble finding the sector? isomode = mode; return(0); } // END CDVDreadTrack() u8* CALLBACK CDVDgetBuffer() { int offset; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDgetBuffer()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(NULL); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(NULL); } // ENDIF- Still simulating device tray open? offset = 0; switch (isomode) { case CDVD_MODE_2352: offset = 0; break; case CDVD_MODE_2340: offset = 12; break; case CDVD_MODE_2328: case CDVD_MODE_2048: offset = 24; break; } // ENDSWITCH isomode- offset to where data it wants is. if (offset > isofile->blockoffset) offset = isofile->blockoffset; return(isobuffer + offset); } // END CDVDgetBuffer() s32 CALLBACK CDVDgetDiskType() { #ifdef VERBOSE_FUNCTION_INTERFACE // PrintLog("CDVDiso interface: CDVDgetDiskType()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(CDVD_TYPE_NODISC); if (deviceopencount > 0) { deviceopencount--; if (deviceopencount > 0) return(CDVD_TYPE_DETCT); } // ENDIF- Still simulating device tray open? return(isofile->cdvdtype); } // END CDVDgetDiskType() s32 CALLBACK CDVDgetTrayStatus() { #ifdef VERBOSE_FUNCTION_INTERFACE // PrintLog("CDVDiso interface: CDVDgetTrayStatus()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ if (isofile == NULL) return(CDVD_TRAY_OPEN); if (deviceopencount > 30) { deviceopencount--; return(CDVD_TRAY_OPEN); } // ENDIF- Still simulating device tray open? return(CDVD_TRAY_CLOSE); } // END CDVDgetTrayStatus() s32 CALLBACK CDVDctrlTrayOpen() { HWND lastwindow; int i; int retval; #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDctrlTrayOpen()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ // CDVDclose(); isofile = IsoFileClose(isofile); deviceopencount = 50; // CDVDopen(); lastwindow = GetActiveWindow(); LoadConf(); if ((conf.isoname[0] == 0) || (conf.isoname[0] == '[') || ((conf.restartconfigure == 1) && (deviceopencount > 0))) { DialogBox(progmodule, MAKEINTRESOURCE(DLG_0200), lastwindow, (DLGPROC)MainBoxCallback); SetActiveWindow(lastwindow); LoadConf(); // Blank out the name in config file afterwards? Seems excessive. } // ENDIF- Haven't initialized the configure program yet? Do so now. lastwindow = NULL; deviceopencount = 0; // Temp line! // NOTE: What happened to repetitive polling when disc not in drive? isofile = IsoFileOpenForRead(conf.isoname); if (isofile == NULL) { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: Failed to open ISO file!"); #endif /* VERBOSE_FUNCTION_INTERFACE */ // return(-1); // Removed to simulate disc not in drive. for (i = 0; i < 2048; i++) isocdcheck[i] = 0; return(0); } // ENDIF- Trouble opening file? Abort. retval = IsoFileSeek(isofile, 16); if (retval != 0) return(-1); retval = IsoFileRead(isofile, isobuffer); if (retval != 0) return(-1); if (deviceopencount > 0) { i = 0; while ((i < 2048) && (isocdcheck[i] == isobuffer[i])) i++; if (i == 2048) deviceopencount = 0; // Same CD/DVD? No delay. } // ENDIF- Is this a restart? Check for disc change. for (i = 0; i < 2048; i++) isocdcheck[i] = isobuffer[i]; return(0); } // END CDVDctrlTrayOpen() s32 CALLBACK CDVDctrlTrayClose() { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDctrlTrayClose()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ return(0); } // END CDVDctrlTrayClose() s32 CALLBACK CDVDtest() { #ifdef VERBOSE_FUNCTION_INTERFACE PrintLog("CDVDiso interface: CDVDtest()"); #endif /* VERBOSE_FUNCTION_INTERFACE */ // InitConf(); // Shouldn't need this. Doesn't CDVDInit() get called first? LoadConf(); if (conf.isoname[0] == 0) return(0); // No name chosen yet. Catch on Open() if (IsIsoFile(conf.isoname) == 0) return(0); // Valid name. Go. return(-1); // Invalid name - reconfigure first. // Note really need this? Why not just return(0)... } // END CDVDtest() void CALLBACK CDVDconfigure() { HWND lastwindow; lastwindow = GetActiveWindow(); DialogBox(progmodule, MAKEINTRESOURCE(DLG_0200), lastwindow, (DLGPROC)MainBoxCallback); SetActiveWindow(lastwindow); lastwindow = NULL; return; } // END CDVDconfigure() BOOL CALLBACK AboutCallback(HWND window, UINT msg, WPARAM param, LPARAM param2) { switch (msg) { case WM_COMMAND: switch (LOWORD(param)) { case IDC_0104: // "Ok" Button EndDialog(window, FALSE); return(TRUE); break; } // ENDSWITCH param- Which Windows Message Command? case WM_CLOSE: EndDialog(window, FALSE); return(TRUE); break; } // ENDSWITCH msg- what message has been sent to this window? return(FALSE); // Not a recognisable message. Pass it back to the OS. } // END AboutCallback() void CALLBACK CDVDabout() { HWND lastwindow; lastwindow = GetActiveWindow(); DialogBox(progmodule, MAKEINTRESOURCE(DLG_0100), lastwindow, (DLGPROC)AboutCallback); SetActiveWindow(lastwindow); return; } // END CDVDabout()
gpl-2.0
speef/linux
kernel/time/tick-broadcast.c
23
16916
/* * linux/kernel/time/tick-broadcast.c * * This file contains functions which emulate a local clock-event * device via a broadcast event source. * * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de> * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar * Copyright(C) 2006-2007, Timesys Corp., Thomas Gleixner * * This code is licenced under the GPL version 2. For details see * kernel-base/COPYING. */ #include <linux/cpu.h> #include <linux/err.h> #include <linux/hrtimer.h> #include <linux/interrupt.h> #include <linux/percpu.h> #include <linux/profile.h> #include <linux/sched.h> #include <linux/smp.h> #include "tick-internal.h" /* * Broadcast support for broken x86 hardware, where the local apic * timer stops in C3 state. */ static struct tick_device tick_broadcast_device; /* FIXME: Use cpumask_var_t. */ static DECLARE_BITMAP(tick_broadcast_mask, NR_CPUS); static DECLARE_BITMAP(tmpmask, NR_CPUS); static DEFINE_RAW_SPINLOCK(tick_broadcast_lock); static int tick_broadcast_force; #ifdef CONFIG_TICK_ONESHOT static void tick_broadcast_clear_oneshot(int cpu); #else static inline void tick_broadcast_clear_oneshot(int cpu) { } #endif /* * Debugging: see timer_list.c */ struct tick_device *tick_get_broadcast_device(void) { return &tick_broadcast_device; } struct cpumask *tick_get_broadcast_mask(void) { return to_cpumask(tick_broadcast_mask); } /* * Start the device in periodic mode */ static void tick_broadcast_start_periodic(struct clock_event_device *bc) { if (bc) tick_setup_periodic(bc, 1); } /* * Check, if the device can be utilized as broadcast device: */ int tick_check_broadcast_device(struct clock_event_device *dev) { if ((tick_broadcast_device.evtdev && tick_broadcast_device.evtdev->rating >= dev->rating) || (dev->features & CLOCK_EVT_FEAT_C3STOP)) return 0; clockevents_exchange_device(tick_broadcast_device.evtdev, dev); tick_broadcast_device.evtdev = dev; if (!cpumask_empty(tick_get_broadcast_mask())) tick_broadcast_start_periodic(dev); return 1; } /* * Check, if the device is the broadcast device */ int tick_is_broadcast_device(struct clock_event_device *dev) { return (dev && tick_broadcast_device.evtdev == dev); } static void err_broadcast(const struct cpumask *mask) { pr_crit_once("Failed to broadcast timer tick. Some CPUs may be unresponsive.\n"); } static void tick_device_setup_broadcast_func(struct clock_event_device *dev) { if (!dev->broadcast) dev->broadcast = tick_broadcast; if (!dev->broadcast) { pr_warn_once("%s depends on broadcast, but no broadcast function available\n", dev->name); dev->broadcast = err_broadcast; } } /* * Check, if the device is disfunctional and a place holder, which * needs to be handled by the broadcast device. */ int tick_device_uses_broadcast(struct clock_event_device *dev, int cpu) { unsigned long flags; int ret = 0; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); /* * Devices might be registered with both periodic and oneshot * mode disabled. This signals, that the device needs to be * operated from the broadcast device and is a placeholder for * the cpu local device. */ if (!tick_device_is_functional(dev)) { dev->event_handler = tick_handle_periodic; tick_device_setup_broadcast_func(dev); cpumask_set_cpu(cpu, tick_get_broadcast_mask()); tick_broadcast_start_periodic(tick_broadcast_device.evtdev); ret = 1; } else { /* * When the new device is not affected by the stop * feature and the cpu is marked in the broadcast mask * then clear the broadcast bit. */ if (!(dev->features & CLOCK_EVT_FEAT_C3STOP)) { int cpu = smp_processor_id(); cpumask_clear_cpu(cpu, tick_get_broadcast_mask()); tick_broadcast_clear_oneshot(cpu); } else { tick_device_setup_broadcast_func(dev); } } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); return ret; } #ifdef CONFIG_GENERIC_CLOCKEVENTS_BROADCAST int tick_receive_broadcast(void) { struct tick_device *td = this_cpu_ptr(&tick_cpu_device); struct clock_event_device *evt = td->evtdev; if (!evt) return -ENODEV; if (!evt->event_handler) return -EINVAL; evt->event_handler(evt); return 0; } #endif /* * Broadcast the event to the cpus, which are set in the mask (mangled). */ static void tick_do_broadcast(struct cpumask *mask) { int cpu = smp_processor_id(); struct tick_device *td; /* * Check, if the current cpu is in the mask */ if (cpumask_test_cpu(cpu, mask)) { cpumask_clear_cpu(cpu, mask); td = &per_cpu(tick_cpu_device, cpu); td->evtdev->event_handler(td->evtdev); } if (!cpumask_empty(mask)) { /* * It might be necessary to actually check whether the devices * have different broadcast functions. For now, just use the * one of the first device. This works as long as we have this * misfeature only on x86 (lapic) */ td = &per_cpu(tick_cpu_device, cpumask_first(mask)); td->evtdev->broadcast(mask); } } /* * Periodic broadcast: * - invoke the broadcast handlers */ static void tick_do_periodic_broadcast(void) { raw_spin_lock(&tick_broadcast_lock); cpumask_and(to_cpumask(tmpmask), cpu_online_mask, tick_get_broadcast_mask()); tick_do_broadcast(to_cpumask(tmpmask)); raw_spin_unlock(&tick_broadcast_lock); } /* * Event handler for periodic broadcast ticks */ static void tick_handle_periodic_broadcast(struct clock_event_device *dev) { ktime_t next; tick_do_periodic_broadcast(); /* * The device is in periodic mode. No reprogramming necessary: */ if (dev->mode == CLOCK_EVT_MODE_PERIODIC) return; /* * Setup the next period for devices, which do not have * periodic mode. We read dev->next_event first and add to it * when the event already expired. clockevents_program_event() * sets dev->next_event only when the event is really * programmed to the device. */ for (next = dev->next_event; ;) { next = ktime_add(next, tick_period); if (!clockevents_program_event(dev, next, false)) return; tick_do_periodic_broadcast(); } } /* * Powerstate information: The system enters/leaves a state, where * affected devices might stop */ static void tick_do_broadcast_on_off(unsigned long *reason) { struct clock_event_device *bc, *dev; struct tick_device *td; unsigned long flags; int cpu, bc_stopped; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); cpu = smp_processor_id(); td = &per_cpu(tick_cpu_device, cpu); dev = td->evtdev; bc = tick_broadcast_device.evtdev; /* * Is the device not affected by the powerstate ? */ if (!dev || !(dev->features & CLOCK_EVT_FEAT_C3STOP)) goto out; if (!tick_device_is_functional(dev)) goto out; bc_stopped = cpumask_empty(tick_get_broadcast_mask()); switch (*reason) { case CLOCK_EVT_NOTIFY_BROADCAST_ON: case CLOCK_EVT_NOTIFY_BROADCAST_FORCE: if (!cpumask_test_cpu(cpu, tick_get_broadcast_mask())) { cpumask_set_cpu(cpu, tick_get_broadcast_mask()); if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) clockevents_shutdown(dev); } if (*reason == CLOCK_EVT_NOTIFY_BROADCAST_FORCE) tick_broadcast_force = 1; break; case CLOCK_EVT_NOTIFY_BROADCAST_OFF: if (!tick_broadcast_force && cpumask_test_cpu(cpu, tick_get_broadcast_mask())) { cpumask_clear_cpu(cpu, tick_get_broadcast_mask()); if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) tick_setup_periodic(dev, 0); } break; } if (cpumask_empty(tick_get_broadcast_mask())) { if (!bc_stopped) clockevents_shutdown(bc); } else if (bc_stopped) { if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) tick_broadcast_start_periodic(bc); else tick_broadcast_setup_oneshot(bc); } out: raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Powerstate information: The system enters/leaves a state, where * affected devices might stop. */ void tick_broadcast_on_off(unsigned long reason, int *oncpu) { if (!cpumask_test_cpu(*oncpu, cpu_online_mask)) printk(KERN_ERR "tick-broadcast: ignoring broadcast for " "offline CPU #%d\n", *oncpu); else tick_do_broadcast_on_off(&reason); } /* * Set the periodic handler depending on broadcast on/off */ void tick_set_periodic_handler(struct clock_event_device *dev, int broadcast) { if (!broadcast) dev->event_handler = tick_handle_periodic; else dev->event_handler = tick_handle_periodic_broadcast; } /* * Remove a CPU from broadcasting */ void tick_shutdown_broadcast(unsigned int *cpup) { struct clock_event_device *bc; unsigned long flags; unsigned int cpu = *cpup; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); bc = tick_broadcast_device.evtdev; cpumask_clear_cpu(cpu, tick_get_broadcast_mask()); if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) { if (bc && cpumask_empty(tick_get_broadcast_mask())) clockevents_shutdown(bc); } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } void tick_suspend_broadcast(void) { struct clock_event_device *bc; unsigned long flags; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); bc = tick_broadcast_device.evtdev; if (bc) clockevents_shutdown(bc); raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } int tick_resume_broadcast(void) { struct clock_event_device *bc; unsigned long flags; int broadcast = 0; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); bc = tick_broadcast_device.evtdev; if (bc) { clockevents_set_mode(bc, CLOCK_EVT_MODE_RESUME); switch (tick_broadcast_device.mode) { case TICKDEV_MODE_PERIODIC: if (!cpumask_empty(tick_get_broadcast_mask())) tick_broadcast_start_periodic(bc); broadcast = cpumask_test_cpu(smp_processor_id(), tick_get_broadcast_mask()); break; case TICKDEV_MODE_ONESHOT: if (!cpumask_empty(tick_get_broadcast_mask())) broadcast = tick_resume_broadcast_oneshot(bc); break; } } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); return broadcast; } #ifdef CONFIG_TICK_ONESHOT /* FIXME: use cpumask_var_t. */ static DECLARE_BITMAP(tick_broadcast_oneshot_mask, NR_CPUS); /* * Exposed for debugging: see timer_list.c */ struct cpumask *tick_get_broadcast_oneshot_mask(void) { return to_cpumask(tick_broadcast_oneshot_mask); } static int tick_broadcast_set_event(ktime_t expires, int force) { struct clock_event_device *bc = tick_broadcast_device.evtdev; if (bc->mode != CLOCK_EVT_MODE_ONESHOT) clockevents_set_mode(bc, CLOCK_EVT_MODE_ONESHOT); return clockevents_program_event(bc, expires, force); } int tick_resume_broadcast_oneshot(struct clock_event_device *bc) { clockevents_set_mode(bc, CLOCK_EVT_MODE_ONESHOT); return 0; } /* * Called from irq_enter() when idle was interrupted to reenable the * per cpu device. */ void tick_check_oneshot_broadcast(int cpu) { if (cpumask_test_cpu(cpu, to_cpumask(tick_broadcast_oneshot_mask))) { struct tick_device *td = &per_cpu(tick_cpu_device, cpu); clockevents_set_mode(td->evtdev, CLOCK_EVT_MODE_ONESHOT); } } /* * Handle oneshot mode broadcasting */ static void tick_handle_oneshot_broadcast(struct clock_event_device *dev) { struct tick_device *td; ktime_t now, next_event; int cpu; raw_spin_lock(&tick_broadcast_lock); again: dev->next_event.tv64 = KTIME_MAX; next_event.tv64 = KTIME_MAX; cpumask_clear(to_cpumask(tmpmask)); now = ktime_get(); /* Find all expired events */ for_each_cpu(cpu, tick_get_broadcast_oneshot_mask()) { td = &per_cpu(tick_cpu_device, cpu); if (td->evtdev->next_event.tv64 <= now.tv64) cpumask_set_cpu(cpu, to_cpumask(tmpmask)); else if (td->evtdev->next_event.tv64 < next_event.tv64) next_event.tv64 = td->evtdev->next_event.tv64; } /* * Wakeup the cpus which have an expired event. */ tick_do_broadcast(to_cpumask(tmpmask)); /* * Two reasons for reprogram: * * - The global event did not expire any CPU local * events. This happens in dyntick mode, as the maximum PIT * delta is quite small. * * - There are pending events on sleeping CPUs which were not * in the event mask */ if (next_event.tv64 != KTIME_MAX) { /* * Rearm the broadcast device. If event expired, * repeat the above */ if (tick_broadcast_set_event(next_event, 0)) goto again; } raw_spin_unlock(&tick_broadcast_lock); } /* * Powerstate information: The system enters/leaves a state, where * affected devices might stop */ void tick_broadcast_oneshot_control(unsigned long reason) { struct clock_event_device *bc, *dev; struct tick_device *td; unsigned long flags; int cpu; /* * Periodic mode does not care about the enter/exit of power * states */ if (tick_broadcast_device.mode == TICKDEV_MODE_PERIODIC) return; /* * We are called with preemtion disabled from the depth of the * idle code, so we can't be moved away. */ cpu = smp_processor_id(); td = &per_cpu(tick_cpu_device, cpu); dev = td->evtdev; if (!(dev->features & CLOCK_EVT_FEAT_C3STOP)) return; bc = tick_broadcast_device.evtdev; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); if (reason == CLOCK_EVT_NOTIFY_BROADCAST_ENTER) { if (!cpumask_test_cpu(cpu, tick_get_broadcast_oneshot_mask())) { cpumask_set_cpu(cpu, tick_get_broadcast_oneshot_mask()); clockevents_set_mode(dev, CLOCK_EVT_MODE_SHUTDOWN); if (dev->next_event.tv64 < bc->next_event.tv64) tick_broadcast_set_event(dev->next_event, 1); } } else { if (cpumask_test_cpu(cpu, tick_get_broadcast_oneshot_mask())) { cpumask_clear_cpu(cpu, tick_get_broadcast_oneshot_mask()); clockevents_set_mode(dev, CLOCK_EVT_MODE_ONESHOT); if (dev->next_event.tv64 != KTIME_MAX) tick_program_event(dev->next_event, 1); } } raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Reset the one shot broadcast for a cpu * * Called with tick_broadcast_lock held */ static void tick_broadcast_clear_oneshot(int cpu) { cpumask_clear_cpu(cpu, tick_get_broadcast_oneshot_mask()); } static void tick_broadcast_init_next_event(struct cpumask *mask, ktime_t expires) { struct tick_device *td; int cpu; for_each_cpu(cpu, mask) { td = &per_cpu(tick_cpu_device, cpu); if (td->evtdev) td->evtdev->next_event = expires; } } /** * tick_broadcast_setup_oneshot - setup the broadcast device */ void tick_broadcast_setup_oneshot(struct clock_event_device *bc) { int cpu = smp_processor_id(); /* Set it up only once ! */ if (bc->event_handler != tick_handle_oneshot_broadcast) { int was_periodic = bc->mode == CLOCK_EVT_MODE_PERIODIC; bc->event_handler = tick_handle_oneshot_broadcast; /* Take the do_timer update */ tick_do_timer_cpu = cpu; /* * We must be careful here. There might be other CPUs * waiting for periodic broadcast. We need to set the * oneshot_mask bits for those and program the * broadcast device to fire. */ cpumask_copy(to_cpumask(tmpmask), tick_get_broadcast_mask()); cpumask_clear_cpu(cpu, to_cpumask(tmpmask)); cpumask_or(tick_get_broadcast_oneshot_mask(), tick_get_broadcast_oneshot_mask(), to_cpumask(tmpmask)); if (was_periodic && !cpumask_empty(to_cpumask(tmpmask))) { clockevents_set_mode(bc, CLOCK_EVT_MODE_ONESHOT); tick_broadcast_init_next_event(to_cpumask(tmpmask), tick_next_period); tick_broadcast_set_event(tick_next_period, 1); } else bc->next_event.tv64 = KTIME_MAX; } else { /* * The first cpu which switches to oneshot mode sets * the bit for all other cpus which are in the general * (periodic) broadcast mask. So the bit is set and * would prevent the first broadcast enter after this * to program the bc device. */ tick_broadcast_clear_oneshot(cpu); } } /* * Select oneshot operating mode for the broadcast device */ void tick_broadcast_switch_to_oneshot(void) { struct clock_event_device *bc; unsigned long flags; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); tick_broadcast_device.mode = TICKDEV_MODE_ONESHOT; bc = tick_broadcast_device.evtdev; if (bc) tick_broadcast_setup_oneshot(bc); raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Remove a dead CPU from broadcasting */ void tick_shutdown_broadcast_oneshot(unsigned int *cpup) { unsigned long flags; unsigned int cpu = *cpup; raw_spin_lock_irqsave(&tick_broadcast_lock, flags); /* * Clear the broadcast mask flag for the dead cpu, but do not * stop the broadcast device! */ cpumask_clear_cpu(cpu, tick_get_broadcast_oneshot_mask()); raw_spin_unlock_irqrestore(&tick_broadcast_lock, flags); } /* * Check, whether the broadcast device is in one shot mode */ int tick_broadcast_oneshot_active(void) { return tick_broadcast_device.mode == TICKDEV_MODE_ONESHOT; } /* * Check whether the broadcast device supports oneshot. */ bool tick_broadcast_oneshot_available(void) { struct clock_event_device *bc = tick_broadcast_device.evtdev; return bc ? bc->features & CLOCK_EVT_FEAT_ONESHOT : false; } #endif
gpl-2.0
cyox93/s3c-linux-2.6.21
fs/jffs2/xattr_user.c
23
1401
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright (C) 2006 NEC Corporation * * Created by KaiGai Kohei <kaigai@ak.jp.nec.com> * * For licensing information, see the file 'LICENCE' in this directory. * */ #include <linux/kernel.h> #include <linux/fs.h> #include <linux/jffs2.h> #include <linux/xattr.h> #include <linux/mtd/mtd.h> #include "nodelist.h" static int jffs2_user_getxattr(struct inode *inode, const char *name, void *buffer, size_t size) { if (!strcmp(name, "")) return -EINVAL; return do_jffs2_getxattr(inode, JFFS2_XPREFIX_USER, name, buffer, size); } static int jffs2_user_setxattr(struct inode *inode, const char *name, const void *buffer, size_t size, int flags) { if (!strcmp(name, "")) return -EINVAL; return do_jffs2_setxattr(inode, JFFS2_XPREFIX_USER, name, buffer, size, flags); } static size_t jffs2_user_listxattr(struct inode *inode, char *list, size_t list_size, const char *name, size_t name_len) { size_t retlen = XATTR_USER_PREFIX_LEN + name_len + 1; if (list && retlen <= list_size) { strcpy(list, XATTR_USER_PREFIX); strcpy(list + XATTR_USER_PREFIX_LEN, name); } return retlen; } struct xattr_handler jffs2_user_xattr_handler = { .prefix = XATTR_USER_PREFIX, .list = jffs2_user_listxattr, .set = jffs2_user_setxattr, .get = jffs2_user_getxattr };
gpl-2.0
mihadyuk/wandboard-linux
drivers/media/common/tuners/xc4000.c
23
43216
/* * Driver for Xceive XC4000 "QAM/8VSB single chip tuner" * * Copyright (c) 2007 Xceive Corporation * Copyright (c) 2007 Steven Toth <stoth@linuxtv.org> * Copyright (c) 2009 Devin Heitmueller <dheitmueller@kernellabs.com> * Copyright (c) 2009 Davide Ferri <d.ferri@zero11.it> * Copyright (c) 2010 Istvan Varga <istvan_v@mailbox.hu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/videodev2.h> #include <linux/delay.h> #include <linux/dvb/frontend.h> #include <linux/i2c.h> #include <linux/mutex.h> #include <asm/unaligned.h> #include "dvb_frontend.h" #include "xc4000.h" #include "tuner-i2c.h" #include "tuner-xc2028-types.h" static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Debugging level (0 to 2, default: 0 (off))."); static int no_poweroff; module_param(no_poweroff, int, 0644); MODULE_PARM_DESC(no_poweroff, "Power management (1: disabled, 2: enabled, " "0 (default): use device-specific default mode)."); static int audio_std; module_param(audio_std, int, 0644); MODULE_PARM_DESC(audio_std, "Audio standard. XC4000 audio decoder explicitly " "needs to know what audio standard is needed for some video standards " "with audio A2 or NICAM. The valid settings are a sum of:\n" " 1: use NICAM/B or A2/B instead of NICAM/A or A2/A\n" " 2: use A2 instead of NICAM or BTSC\n" " 4: use SECAM/K3 instead of K1\n" " 8: use PAL-D/K audio for SECAM-D/K\n" "16: use FM radio input 1 instead of input 2\n" "32: use mono audio (the lower three bits are ignored)"); static char firmware_name[30]; module_param_string(firmware_name, firmware_name, sizeof(firmware_name), 0); MODULE_PARM_DESC(firmware_name, "Firmware file name. Allows overriding the " "default firmware name."); static DEFINE_MUTEX(xc4000_list_mutex); static LIST_HEAD(hybrid_tuner_instance_list); #define dprintk(level, fmt, arg...) if (debug >= level) \ printk(KERN_INFO "%s: " fmt, "xc4000", ## arg) /* struct for storing firmware table */ struct firmware_description { unsigned int type; v4l2_std_id id; __u16 int_freq; unsigned char *ptr; unsigned int size; }; struct firmware_properties { unsigned int type; v4l2_std_id id; v4l2_std_id std_req; __u16 int_freq; unsigned int scode_table; int scode_nr; }; struct xc4000_priv { struct tuner_i2c_props i2c_props; struct list_head hybrid_tuner_instance_list; struct firmware_description *firm; int firm_size; u32 if_khz; u32 freq_hz; u32 bandwidth; u8 video_standard; u8 rf_mode; u8 default_pm; u8 dvb_amplitude; u8 set_smoothedcvbs; u8 ignore_i2c_write_errors; __u16 firm_version; struct firmware_properties cur_fw; __u16 hwmodel; __u16 hwvers; struct mutex lock; }; #define XC4000_AUDIO_STD_B 1 #define XC4000_AUDIO_STD_A2 2 #define XC4000_AUDIO_STD_K3 4 #define XC4000_AUDIO_STD_L 8 #define XC4000_AUDIO_STD_INPUT1 16 #define XC4000_AUDIO_STD_MONO 32 #define XC4000_DEFAULT_FIRMWARE "dvb-fe-xc4000-1.4.fw" /* Misc Defines */ #define MAX_TV_STANDARD 24 #define XC_MAX_I2C_WRITE_LENGTH 64 #define XC_POWERED_DOWN 0x80000000U /* Signal Types */ #define XC_RF_MODE_AIR 0 #define XC_RF_MODE_CABLE 1 /* Product id */ #define XC_PRODUCT_ID_FW_NOT_LOADED 0x2000 #define XC_PRODUCT_ID_XC4000 0x0FA0 #define XC_PRODUCT_ID_XC4100 0x1004 /* Registers (Write-only) */ #define XREG_INIT 0x00 #define XREG_VIDEO_MODE 0x01 #define XREG_AUDIO_MODE 0x02 #define XREG_RF_FREQ 0x03 #define XREG_D_CODE 0x04 #define XREG_DIRECTSITTING_MODE 0x05 #define XREG_SEEK_MODE 0x06 #define XREG_POWER_DOWN 0x08 #define XREG_SIGNALSOURCE 0x0A #define XREG_SMOOTHEDCVBS 0x0E #define XREG_AMPLITUDE 0x10 /* Registers (Read-only) */ #define XREG_ADC_ENV 0x00 #define XREG_QUALITY 0x01 #define XREG_FRAME_LINES 0x02 #define XREG_HSYNC_FREQ 0x03 #define XREG_LOCK 0x04 #define XREG_FREQ_ERROR 0x05 #define XREG_SNR 0x06 #define XREG_VERSION 0x07 #define XREG_PRODUCT_ID 0x08 /* Basic firmware description. This will remain with the driver for documentation purposes. This represents an I2C firmware file encoded as a string of unsigned char. Format is as follows: char[0 ]=len0_MSB -> len = len_MSB * 256 + len_LSB char[1 ]=len0_LSB -> length of first write transaction char[2 ]=data0 -> first byte to be sent char[3 ]=data1 char[4 ]=data2 char[ ]=... char[M ]=dataN -> last byte to be sent char[M+1]=len1_MSB -> len = len_MSB * 256 + len_LSB char[M+2]=len1_LSB -> length of second write transaction char[M+3]=data0 char[M+4]=data1 ... etc. The [len] value should be interpreted as follows: len= len_MSB _ len_LSB len=1111_1111_1111_1111 : End of I2C_SEQUENCE len=0000_0000_0000_0000 : Reset command: Do hardware reset len=0NNN_NNNN_NNNN_NNNN : Normal transaction: number of bytes = {1:32767) len=1WWW_WWWW_WWWW_WWWW : Wait command: wait for {1:32767} ms For the RESET and WAIT commands, the two following bytes will contain immediately the length of the following transaction. */ struct XC_TV_STANDARD { const char *Name; u16 audio_mode; u16 video_mode; u16 int_freq; }; /* Tuner standards */ #define XC4000_MN_NTSC_PAL_BTSC 0 #define XC4000_MN_NTSC_PAL_A2 1 #define XC4000_MN_NTSC_PAL_EIAJ 2 #define XC4000_MN_NTSC_PAL_Mono 3 #define XC4000_BG_PAL_A2 4 #define XC4000_BG_PAL_NICAM 5 #define XC4000_BG_PAL_MONO 6 #define XC4000_I_PAL_NICAM 7 #define XC4000_I_PAL_NICAM_MONO 8 #define XC4000_DK_PAL_A2 9 #define XC4000_DK_PAL_NICAM 10 #define XC4000_DK_PAL_MONO 11 #define XC4000_DK_SECAM_A2DK1 12 #define XC4000_DK_SECAM_A2LDK3 13 #define XC4000_DK_SECAM_A2MONO 14 #define XC4000_DK_SECAM_NICAM 15 #define XC4000_L_SECAM_NICAM 16 #define XC4000_LC_SECAM_NICAM 17 #define XC4000_DTV6 18 #define XC4000_DTV8 19 #define XC4000_DTV7_8 20 #define XC4000_DTV7 21 #define XC4000_FM_Radio_INPUT2 22 #define XC4000_FM_Radio_INPUT1 23 static struct XC_TV_STANDARD xc4000_standard[MAX_TV_STANDARD] = { {"M/N-NTSC/PAL-BTSC", 0x0000, 0x80A0, 4500}, {"M/N-NTSC/PAL-A2", 0x0000, 0x80A0, 4600}, {"M/N-NTSC/PAL-EIAJ", 0x0040, 0x80A0, 4500}, {"M/N-NTSC/PAL-Mono", 0x0078, 0x80A0, 4500}, {"B/G-PAL-A2", 0x0000, 0x8159, 5640}, {"B/G-PAL-NICAM", 0x0004, 0x8159, 5740}, {"B/G-PAL-MONO", 0x0078, 0x8159, 5500}, {"I-PAL-NICAM", 0x0080, 0x8049, 6240}, {"I-PAL-NICAM-MONO", 0x0078, 0x8049, 6000}, {"D/K-PAL-A2", 0x0000, 0x8049, 6380}, {"D/K-PAL-NICAM", 0x0080, 0x8049, 6200}, {"D/K-PAL-MONO", 0x0078, 0x8049, 6500}, {"D/K-SECAM-A2 DK1", 0x0000, 0x8049, 6340}, {"D/K-SECAM-A2 L/DK3", 0x0000, 0x8049, 6000}, {"D/K-SECAM-A2 MONO", 0x0078, 0x8049, 6500}, {"D/K-SECAM-NICAM", 0x0080, 0x8049, 6200}, {"L-SECAM-NICAM", 0x8080, 0x0009, 6200}, {"L'-SECAM-NICAM", 0x8080, 0x4009, 6200}, {"DTV6", 0x00C0, 0x8002, 0}, {"DTV8", 0x00C0, 0x800B, 0}, {"DTV7/8", 0x00C0, 0x801B, 0}, {"DTV7", 0x00C0, 0x8007, 0}, {"FM Radio-INPUT2", 0x0008, 0x9800, 10700}, {"FM Radio-INPUT1", 0x0008, 0x9000, 10700} }; static int xc4000_readreg(struct xc4000_priv *priv, u16 reg, u16 *val); static int xc4000_tuner_reset(struct dvb_frontend *fe); static void xc_debug_dump(struct xc4000_priv *priv); static int xc_send_i2c_data(struct xc4000_priv *priv, u8 *buf, int len) { struct i2c_msg msg = { .addr = priv->i2c_props.addr, .flags = 0, .buf = buf, .len = len }; if (i2c_transfer(priv->i2c_props.adap, &msg, 1) != 1) { if (priv->ignore_i2c_write_errors == 0) { printk(KERN_ERR "xc4000: I2C write failed (len=%i)\n", len); if (len == 4) { printk(KERN_ERR "bytes %02x %02x %02x %02x\n", buf[0], buf[1], buf[2], buf[3]); } return -EREMOTEIO; } } return 0; } static int xc4000_tuner_reset(struct dvb_frontend *fe) { struct xc4000_priv *priv = fe->tuner_priv; int ret; dprintk(1, "%s()\n", __func__); if (fe->callback) { ret = fe->callback(((fe->dvb) && (fe->dvb->priv)) ? fe->dvb->priv : priv->i2c_props.adap->algo_data, DVB_FRONTEND_COMPONENT_TUNER, XC4000_TUNER_RESET, 0); if (ret) { printk(KERN_ERR "xc4000: reset failed\n"); return -EREMOTEIO; } } else { printk(KERN_ERR "xc4000: no tuner reset callback function, " "fatal\n"); return -EINVAL; } return 0; } static int xc_write_reg(struct xc4000_priv *priv, u16 regAddr, u16 i2cData) { u8 buf[4]; int result; buf[0] = (regAddr >> 8) & 0xFF; buf[1] = regAddr & 0xFF; buf[2] = (i2cData >> 8) & 0xFF; buf[3] = i2cData & 0xFF; result = xc_send_i2c_data(priv, buf, 4); return result; } static int xc_load_i2c_sequence(struct dvb_frontend *fe, const u8 *i2c_sequence) { struct xc4000_priv *priv = fe->tuner_priv; int i, nbytes_to_send, result; unsigned int len, pos, index; u8 buf[XC_MAX_I2C_WRITE_LENGTH]; index = 0; while ((i2c_sequence[index] != 0xFF) || (i2c_sequence[index + 1] != 0xFF)) { len = i2c_sequence[index] * 256 + i2c_sequence[index+1]; if (len == 0x0000) { /* RESET command */ /* NOTE: this is ignored, as the reset callback was */ /* already called by check_firmware() */ index += 2; } else if (len & 0x8000) { /* WAIT command */ msleep(len & 0x7FFF); index += 2; } else { /* Send i2c data whilst ensuring individual transactions * do not exceed XC_MAX_I2C_WRITE_LENGTH bytes. */ index += 2; buf[0] = i2c_sequence[index]; buf[1] = i2c_sequence[index + 1]; pos = 2; while (pos < len) { if ((len - pos) > XC_MAX_I2C_WRITE_LENGTH - 2) nbytes_to_send = XC_MAX_I2C_WRITE_LENGTH; else nbytes_to_send = (len - pos + 2); for (i = 2; i < nbytes_to_send; i++) { buf[i] = i2c_sequence[index + pos + i - 2]; } result = xc_send_i2c_data(priv, buf, nbytes_to_send); if (result != 0) return result; pos += nbytes_to_send - 2; } index += len; } } return 0; } static int xc_set_tv_standard(struct xc4000_priv *priv, u16 video_mode, u16 audio_mode) { int ret; dprintk(1, "%s(0x%04x,0x%04x)\n", __func__, video_mode, audio_mode); dprintk(1, "%s() Standard = %s\n", __func__, xc4000_standard[priv->video_standard].Name); /* Don't complain when the request fails because of i2c stretching */ priv->ignore_i2c_write_errors = 1; ret = xc_write_reg(priv, XREG_VIDEO_MODE, video_mode); if (ret == 0) ret = xc_write_reg(priv, XREG_AUDIO_MODE, audio_mode); priv->ignore_i2c_write_errors = 0; return ret; } static int xc_set_signal_source(struct xc4000_priv *priv, u16 rf_mode) { dprintk(1, "%s(%d) Source = %s\n", __func__, rf_mode, rf_mode == XC_RF_MODE_AIR ? "ANTENNA" : "CABLE"); if ((rf_mode != XC_RF_MODE_AIR) && (rf_mode != XC_RF_MODE_CABLE)) { rf_mode = XC_RF_MODE_CABLE; printk(KERN_ERR "%s(), Invalid mode, defaulting to CABLE", __func__); } return xc_write_reg(priv, XREG_SIGNALSOURCE, rf_mode); } static const struct dvb_tuner_ops xc4000_tuner_ops; static int xc_set_rf_frequency(struct xc4000_priv *priv, u32 freq_hz) { u16 freq_code; dprintk(1, "%s(%u)\n", __func__, freq_hz); if ((freq_hz > xc4000_tuner_ops.info.frequency_max) || (freq_hz < xc4000_tuner_ops.info.frequency_min)) return -EINVAL; freq_code = (u16)(freq_hz / 15625); /* WAS: Starting in firmware version 1.1.44, Xceive recommends using the FINERFREQ for all normal tuning (the doc indicates reg 0x03 should only be used for fast scanning for channel lock) */ /* WAS: XREG_FINERFREQ */ return xc_write_reg(priv, XREG_RF_FREQ, freq_code); } static int xc_get_adc_envelope(struct xc4000_priv *priv, u16 *adc_envelope) { return xc4000_readreg(priv, XREG_ADC_ENV, adc_envelope); } static int xc_get_frequency_error(struct xc4000_priv *priv, u32 *freq_error_hz) { int result; u16 regData; u32 tmp; result = xc4000_readreg(priv, XREG_FREQ_ERROR, &regData); if (result != 0) return result; tmp = (u32)regData & 0xFFFFU; tmp = (tmp < 0x8000U ? tmp : 0x10000U - tmp); (*freq_error_hz) = tmp * 15625; return result; } static int xc_get_lock_status(struct xc4000_priv *priv, u16 *lock_status) { return xc4000_readreg(priv, XREG_LOCK, lock_status); } static int xc_get_version(struct xc4000_priv *priv, u8 *hw_majorversion, u8 *hw_minorversion, u8 *fw_majorversion, u8 *fw_minorversion) { u16 data; int result; result = xc4000_readreg(priv, XREG_VERSION, &data); if (result != 0) return result; (*hw_majorversion) = (data >> 12) & 0x0F; (*hw_minorversion) = (data >> 8) & 0x0F; (*fw_majorversion) = (data >> 4) & 0x0F; (*fw_minorversion) = data & 0x0F; return 0; } static int xc_get_hsync_freq(struct xc4000_priv *priv, u32 *hsync_freq_hz) { u16 regData; int result; result = xc4000_readreg(priv, XREG_HSYNC_FREQ, &regData); if (result != 0) return result; (*hsync_freq_hz) = ((regData & 0x0fff) * 763)/100; return result; } static int xc_get_frame_lines(struct xc4000_priv *priv, u16 *frame_lines) { return xc4000_readreg(priv, XREG_FRAME_LINES, frame_lines); } static int xc_get_quality(struct xc4000_priv *priv, u16 *quality) { return xc4000_readreg(priv, XREG_QUALITY, quality); } static u16 xc_wait_for_lock(struct xc4000_priv *priv) { u16 lock_state = 0; int watchdog_count = 40; while ((lock_state == 0) && (watchdog_count > 0)) { xc_get_lock_status(priv, &lock_state); if (lock_state != 1) { msleep(5); watchdog_count--; } } return lock_state; } static int xc_tune_channel(struct xc4000_priv *priv, u32 freq_hz) { int found = 1; int result; dprintk(1, "%s(%u)\n", __func__, freq_hz); /* Don't complain when the request fails because of i2c stretching */ priv->ignore_i2c_write_errors = 1; result = xc_set_rf_frequency(priv, freq_hz); priv->ignore_i2c_write_errors = 0; if (result != 0) return 0; /* wait for lock only in analog TV mode */ if ((priv->cur_fw.type & (FM | DTV6 | DTV7 | DTV78 | DTV8)) == 0) { if (xc_wait_for_lock(priv) != 1) found = 0; } /* Wait for stats to stabilize. * Frame Lines needs two frame times after initial lock * before it is valid. */ msleep(debug ? 100 : 10); if (debug) xc_debug_dump(priv); return found; } static int xc4000_readreg(struct xc4000_priv *priv, u16 reg, u16 *val) { u8 buf[2] = { reg >> 8, reg & 0xff }; u8 bval[2] = { 0, 0 }; struct i2c_msg msg[2] = { { .addr = priv->i2c_props.addr, .flags = 0, .buf = &buf[0], .len = 2 }, { .addr = priv->i2c_props.addr, .flags = I2C_M_RD, .buf = &bval[0], .len = 2 }, }; if (i2c_transfer(priv->i2c_props.adap, msg, 2) != 2) { printk(KERN_ERR "xc4000: I2C read failed\n"); return -EREMOTEIO; } *val = (bval[0] << 8) | bval[1]; return 0; } #define dump_firm_type(t) dump_firm_type_and_int_freq(t, 0) static void dump_firm_type_and_int_freq(unsigned int type, u16 int_freq) { if (type & BASE) printk(KERN_CONT "BASE "); if (type & INIT1) printk(KERN_CONT "INIT1 "); if (type & F8MHZ) printk(KERN_CONT "F8MHZ "); if (type & MTS) printk(KERN_CONT "MTS "); if (type & D2620) printk(KERN_CONT "D2620 "); if (type & D2633) printk(KERN_CONT "D2633 "); if (type & DTV6) printk(KERN_CONT "DTV6 "); if (type & QAM) printk(KERN_CONT "QAM "); if (type & DTV7) printk(KERN_CONT "DTV7 "); if (type & DTV78) printk(KERN_CONT "DTV78 "); if (type & DTV8) printk(KERN_CONT "DTV8 "); if (type & FM) printk(KERN_CONT "FM "); if (type & INPUT1) printk(KERN_CONT "INPUT1 "); if (type & LCD) printk(KERN_CONT "LCD "); if (type & NOGD) printk(KERN_CONT "NOGD "); if (type & MONO) printk(KERN_CONT "MONO "); if (type & ATSC) printk(KERN_CONT "ATSC "); if (type & IF) printk(KERN_CONT "IF "); if (type & LG60) printk(KERN_CONT "LG60 "); if (type & ATI638) printk(KERN_CONT "ATI638 "); if (type & OREN538) printk(KERN_CONT "OREN538 "); if (type & OREN36) printk(KERN_CONT "OREN36 "); if (type & TOYOTA388) printk(KERN_CONT "TOYOTA388 "); if (type & TOYOTA794) printk(KERN_CONT "TOYOTA794 "); if (type & DIBCOM52) printk(KERN_CONT "DIBCOM52 "); if (type & ZARLINK456) printk(KERN_CONT "ZARLINK456 "); if (type & CHINA) printk(KERN_CONT "CHINA "); if (type & F6MHZ) printk(KERN_CONT "F6MHZ "); if (type & INPUT2) printk(KERN_CONT "INPUT2 "); if (type & SCODE) printk(KERN_CONT "SCODE "); if (type & HAS_IF) printk(KERN_CONT "HAS_IF_%d ", int_freq); } static int seek_firmware(struct dvb_frontend *fe, unsigned int type, v4l2_std_id *id) { struct xc4000_priv *priv = fe->tuner_priv; int i, best_i = -1; unsigned int best_nr_diffs = 255U; if (!priv->firm) { printk(KERN_ERR "Error! firmware not loaded\n"); return -EINVAL; } if (((type & ~SCODE) == 0) && (*id == 0)) *id = V4L2_STD_PAL; /* Seek for generic video standard match */ for (i = 0; i < priv->firm_size; i++) { v4l2_std_id id_diff_mask = (priv->firm[i].id ^ (*id)) & (*id); unsigned int type_diff_mask = (priv->firm[i].type ^ type) & (BASE_TYPES | DTV_TYPES | LCD | NOGD | MONO | SCODE); unsigned int nr_diffs; if (type_diff_mask & (BASE | INIT1 | FM | DTV6 | DTV7 | DTV78 | DTV8 | SCODE)) continue; nr_diffs = hweight64(id_diff_mask) + hweight32(type_diff_mask); if (!nr_diffs) /* Supports all the requested standards */ goto found; if (nr_diffs < best_nr_diffs) { best_nr_diffs = nr_diffs; best_i = i; } } /* FIXME: Would make sense to seek for type "hint" match ? */ if (best_i < 0) { i = -ENOENT; goto ret; } if (best_nr_diffs > 0U) { printk(KERN_WARNING "Selecting best matching firmware (%u bits differ) for " "type=(%x), id %016llx:\n", best_nr_diffs, type, (unsigned long long)*id); i = best_i; } found: *id = priv->firm[i].id; ret: if (debug) { printk(KERN_DEBUG "%s firmware for type=", (i < 0) ? "Can't find" : "Found"); dump_firm_type(type); printk(KERN_DEBUG "(%x), id %016llx.\n", type, (unsigned long long)*id); } return i; } static int load_firmware(struct dvb_frontend *fe, unsigned int type, v4l2_std_id *id) { struct xc4000_priv *priv = fe->tuner_priv; int pos, rc; unsigned char *p; pos = seek_firmware(fe, type, id); if (pos < 0) return pos; p = priv->firm[pos].ptr; /* Don't complain when the request fails because of i2c stretching */ priv->ignore_i2c_write_errors = 1; rc = xc_load_i2c_sequence(fe, p); priv->ignore_i2c_write_errors = 0; return rc; } static int xc4000_fwupload(struct dvb_frontend *fe) { struct xc4000_priv *priv = fe->tuner_priv; const struct firmware *fw = NULL; const unsigned char *p, *endp; int rc = 0; int n, n_array; char name[33]; const char *fname; if (firmware_name[0] != '\0') fname = firmware_name; else fname = XC4000_DEFAULT_FIRMWARE; dprintk(1, "Reading firmware %s\n", fname); rc = request_firmware(&fw, fname, priv->i2c_props.adap->dev.parent); if (rc < 0) { if (rc == -ENOENT) printk(KERN_ERR "Error: firmware %s not found.\n", fname); else printk(KERN_ERR "Error %d while requesting firmware %s\n", rc, fname); return rc; } p = fw->data; endp = p + fw->size; if (fw->size < sizeof(name) - 1 + 2 + 2) { printk(KERN_ERR "Error: firmware file %s has invalid size!\n", fname); goto corrupt; } memcpy(name, p, sizeof(name) - 1); name[sizeof(name) - 1] = '\0'; p += sizeof(name) - 1; priv->firm_version = get_unaligned_le16(p); p += 2; n_array = get_unaligned_le16(p); p += 2; dprintk(1, "Loading %d firmware images from %s, type: %s, ver %d.%d\n", n_array, fname, name, priv->firm_version >> 8, priv->firm_version & 0xff); priv->firm = kcalloc(n_array, sizeof(*priv->firm), GFP_KERNEL); if (priv->firm == NULL) { printk(KERN_ERR "Not enough memory to load firmware file.\n"); rc = -ENOMEM; goto done; } priv->firm_size = n_array; n = -1; while (p < endp) { __u32 type, size; v4l2_std_id id; __u16 int_freq = 0; n++; if (n >= n_array) { printk(KERN_ERR "More firmware images in file than " "were expected!\n"); goto corrupt; } /* Checks if there's enough bytes to read */ if (endp - p < sizeof(type) + sizeof(id) + sizeof(size)) goto header; type = get_unaligned_le32(p); p += sizeof(type); id = get_unaligned_le64(p); p += sizeof(id); if (type & HAS_IF) { int_freq = get_unaligned_le16(p); p += sizeof(int_freq); if (endp - p < sizeof(size)) goto header; } size = get_unaligned_le32(p); p += sizeof(size); if (!size || size > endp - p) { printk(KERN_ERR "Firmware type (%x), id %llx is corrupted (size=%d, expected %d)\n", type, (unsigned long long)id, (unsigned)(endp - p), size); goto corrupt; } priv->firm[n].ptr = kzalloc(size, GFP_KERNEL); if (priv->firm[n].ptr == NULL) { printk(KERN_ERR "Not enough memory to load firmware file.\n"); rc = -ENOMEM; goto done; } if (debug) { printk(KERN_DEBUG "Reading firmware type "); dump_firm_type_and_int_freq(type, int_freq); printk(KERN_DEBUG "(%x), id %llx, size=%d.\n", type, (unsigned long long)id, size); } memcpy(priv->firm[n].ptr, p, size); priv->firm[n].type = type; priv->firm[n].id = id; priv->firm[n].size = size; priv->firm[n].int_freq = int_freq; p += size; } if (n + 1 != priv->firm_size) { printk(KERN_ERR "Firmware file is incomplete!\n"); goto corrupt; } goto done; header: printk(KERN_ERR "Firmware header is incomplete!\n"); corrupt: rc = -EINVAL; printk(KERN_ERR "Error: firmware file is corrupted!\n"); done: release_firmware(fw); if (rc == 0) dprintk(1, "Firmware files loaded.\n"); return rc; } static int load_scode(struct dvb_frontend *fe, unsigned int type, v4l2_std_id *id, __u16 int_freq, int scode) { struct xc4000_priv *priv = fe->tuner_priv; int pos, rc; unsigned char *p; u8 scode_buf[13]; u8 indirect_mode[5]; dprintk(1, "%s called int_freq=%d\n", __func__, int_freq); if (!int_freq) { pos = seek_firmware(fe, type, id); if (pos < 0) return pos; } else { for (pos = 0; pos < priv->firm_size; pos++) { if ((priv->firm[pos].int_freq == int_freq) && (priv->firm[pos].type & HAS_IF)) break; } if (pos == priv->firm_size) return -ENOENT; } p = priv->firm[pos].ptr; if (priv->firm[pos].size != 12 * 16 || scode >= 16) return -EINVAL; p += 12 * scode; if (debug) { tuner_info("Loading SCODE for type="); dump_firm_type_and_int_freq(priv->firm[pos].type, priv->firm[pos].int_freq); printk(KERN_CONT "(%x), id %016llx.\n", priv->firm[pos].type, (unsigned long long)*id); } scode_buf[0] = 0x00; memcpy(&scode_buf[1], p, 12); /* Enter direct-mode */ rc = xc_write_reg(priv, XREG_DIRECTSITTING_MODE, 0); if (rc < 0) { printk(KERN_ERR "failed to put device into direct mode!\n"); return -EIO; } rc = xc_send_i2c_data(priv, scode_buf, 13); if (rc != 0) { /* Even if the send failed, make sure we set back to indirect mode */ printk(KERN_ERR "Failed to set scode %d\n", rc); } /* Switch back to indirect-mode */ memset(indirect_mode, 0, sizeof(indirect_mode)); indirect_mode[4] = 0x88; xc_send_i2c_data(priv, indirect_mode, sizeof(indirect_mode)); msleep(10); return 0; } static int check_firmware(struct dvb_frontend *fe, unsigned int type, v4l2_std_id std, __u16 int_freq) { struct xc4000_priv *priv = fe->tuner_priv; struct firmware_properties new_fw; int rc = 0, is_retry = 0; u16 hwmodel; v4l2_std_id std0; u8 hw_major, hw_minor, fw_major, fw_minor; dprintk(1, "%s called\n", __func__); if (!priv->firm) { rc = xc4000_fwupload(fe); if (rc < 0) return rc; } retry: new_fw.type = type; new_fw.id = std; new_fw.std_req = std; new_fw.scode_table = SCODE; new_fw.scode_nr = 0; new_fw.int_freq = int_freq; dprintk(1, "checking firmware, user requested type="); if (debug) { dump_firm_type(new_fw.type); printk(KERN_CONT "(%x), id %016llx, ", new_fw.type, (unsigned long long)new_fw.std_req); if (!int_freq) printk(KERN_CONT "scode_tbl "); else printk(KERN_CONT "int_freq %d, ", new_fw.int_freq); printk(KERN_CONT "scode_nr %d\n", new_fw.scode_nr); } /* No need to reload base firmware if it matches */ if (priv->cur_fw.type & BASE) { dprintk(1, "BASE firmware not changed.\n"); goto skip_base; } /* Updating BASE - forget about all currently loaded firmware */ memset(&priv->cur_fw, 0, sizeof(priv->cur_fw)); /* Reset is needed before loading firmware */ rc = xc4000_tuner_reset(fe); if (rc < 0) goto fail; /* BASE firmwares are all std0 */ std0 = 0; rc = load_firmware(fe, BASE, &std0); if (rc < 0) { printk(KERN_ERR "Error %d while loading base firmware\n", rc); goto fail; } /* Load INIT1, if needed */ dprintk(1, "Load init1 firmware, if exists\n"); rc = load_firmware(fe, BASE | INIT1, &std0); if (rc == -ENOENT) rc = load_firmware(fe, BASE | INIT1, &std0); if (rc < 0 && rc != -ENOENT) { tuner_err("Error %d while loading init1 firmware\n", rc); goto fail; } skip_base: /* * No need to reload standard specific firmware if base firmware * was not reloaded and requested video standards have not changed. */ if (priv->cur_fw.type == (BASE | new_fw.type) && priv->cur_fw.std_req == std) { dprintk(1, "Std-specific firmware already loaded.\n"); goto skip_std_specific; } /* Reloading std-specific firmware forces a SCODE update */ priv->cur_fw.scode_table = 0; /* Load the standard firmware */ rc = load_firmware(fe, new_fw.type, &new_fw.id); if (rc < 0) goto fail; skip_std_specific: if (priv->cur_fw.scode_table == new_fw.scode_table && priv->cur_fw.scode_nr == new_fw.scode_nr) { dprintk(1, "SCODE firmware already loaded.\n"); goto check_device; } /* Load SCODE firmware, if exists */ rc = load_scode(fe, new_fw.type | new_fw.scode_table, &new_fw.id, new_fw.int_freq, new_fw.scode_nr); if (rc != 0) dprintk(1, "load scode failed %d\n", rc); check_device: rc = xc4000_readreg(priv, XREG_PRODUCT_ID, &hwmodel); if (xc_get_version(priv, &hw_major, &hw_minor, &fw_major, &fw_minor) != 0) { printk(KERN_ERR "Unable to read tuner registers.\n"); goto fail; } dprintk(1, "Device is Xceive %d version %d.%d, " "firmware version %d.%d\n", hwmodel, hw_major, hw_minor, fw_major, fw_minor); /* Check firmware version against what we downloaded. */ if (priv->firm_version != ((fw_major << 8) | fw_minor)) { printk(KERN_WARNING "Incorrect readback of firmware version %d.%d.\n", fw_major, fw_minor); goto fail; } /* Check that the tuner hardware model remains consistent over time. */ if (priv->hwmodel == 0 && (hwmodel == XC_PRODUCT_ID_XC4000 || hwmodel == XC_PRODUCT_ID_XC4100)) { priv->hwmodel = hwmodel; priv->hwvers = (hw_major << 8) | hw_minor; } else if (priv->hwmodel == 0 || priv->hwmodel != hwmodel || priv->hwvers != ((hw_major << 8) | hw_minor)) { printk(KERN_WARNING "Read invalid device hardware information - tuner " "hung?\n"); goto fail; } memcpy(&priv->cur_fw, &new_fw, sizeof(priv->cur_fw)); /* * By setting BASE in cur_fw.type only after successfully loading all * firmwares, we can: * 1. Identify that BASE firmware with type=0 has been loaded; * 2. Tell whether BASE firmware was just changed the next time through. */ priv->cur_fw.type |= BASE; return 0; fail: memset(&priv->cur_fw, 0, sizeof(priv->cur_fw)); if (!is_retry) { msleep(50); is_retry = 1; dprintk(1, "Retrying firmware load\n"); goto retry; } if (rc == -ENOENT) rc = -EINVAL; return rc; } static void xc_debug_dump(struct xc4000_priv *priv) { u16 adc_envelope; u32 freq_error_hz = 0; u16 lock_status; u32 hsync_freq_hz = 0; u16 frame_lines; u16 quality; u8 hw_majorversion = 0, hw_minorversion = 0; u8 fw_majorversion = 0, fw_minorversion = 0; xc_get_adc_envelope(priv, &adc_envelope); dprintk(1, "*** ADC envelope (0-1023) = %d\n", adc_envelope); xc_get_frequency_error(priv, &freq_error_hz); dprintk(1, "*** Frequency error = %d Hz\n", freq_error_hz); xc_get_lock_status(priv, &lock_status); dprintk(1, "*** Lock status (0-Wait, 1-Locked, 2-No-signal) = %d\n", lock_status); xc_get_version(priv, &hw_majorversion, &hw_minorversion, &fw_majorversion, &fw_minorversion); dprintk(1, "*** HW: V%02x.%02x, FW: V%02x.%02x\n", hw_majorversion, hw_minorversion, fw_majorversion, fw_minorversion); if (priv->video_standard < XC4000_DTV6) { xc_get_hsync_freq(priv, &hsync_freq_hz); dprintk(1, "*** Horizontal sync frequency = %d Hz\n", hsync_freq_hz); xc_get_frame_lines(priv, &frame_lines); dprintk(1, "*** Frame lines = %d\n", frame_lines); } xc_get_quality(priv, &quality); dprintk(1, "*** Quality (0:<8dB, 7:>56dB) = %d\n", quality); } static int xc4000_set_params(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; u32 delsys = c->delivery_system; u32 bw = c->bandwidth_hz; struct xc4000_priv *priv = fe->tuner_priv; unsigned int type; int ret = -EREMOTEIO; dprintk(1, "%s() frequency=%d (Hz)\n", __func__, c->frequency); mutex_lock(&priv->lock); switch (delsys) { case SYS_ATSC: dprintk(1, "%s() VSB modulation\n", __func__); priv->rf_mode = XC_RF_MODE_AIR; priv->freq_hz = c->frequency - 1750000; priv->video_standard = XC4000_DTV6; type = DTV6; break; case SYS_DVBC_ANNEX_B: dprintk(1, "%s() QAM modulation\n", __func__); priv->rf_mode = XC_RF_MODE_CABLE; priv->freq_hz = c->frequency - 1750000; priv->video_standard = XC4000_DTV6; type = DTV6; break; case SYS_DVBT: case SYS_DVBT2: dprintk(1, "%s() OFDM\n", __func__); if (bw == 0) { if (c->frequency < 400000000) { priv->freq_hz = c->frequency - 2250000; } else { priv->freq_hz = c->frequency - 2750000; } priv->video_standard = XC4000_DTV7_8; type = DTV78; } else if (bw <= 6000000) { priv->video_standard = XC4000_DTV6; priv->freq_hz = c->frequency - 1750000; type = DTV6; } else if (bw <= 7000000) { priv->video_standard = XC4000_DTV7; priv->freq_hz = c->frequency - 2250000; type = DTV7; } else { priv->video_standard = XC4000_DTV8; priv->freq_hz = c->frequency - 2750000; type = DTV8; } priv->rf_mode = XC_RF_MODE_AIR; break; default: printk(KERN_ERR "xc4000 delivery system not supported!\n"); ret = -EINVAL; goto fail; } dprintk(1, "%s() frequency=%d (compensated)\n", __func__, priv->freq_hz); /* Make sure the correct firmware type is loaded */ if (check_firmware(fe, type, 0, priv->if_khz) != 0) goto fail; priv->bandwidth = c->bandwidth_hz; ret = xc_set_signal_source(priv, priv->rf_mode); if (ret != 0) { printk(KERN_ERR "xc4000: xc_set_signal_source(%d) failed\n", priv->rf_mode); goto fail; } else { u16 video_mode, audio_mode; video_mode = xc4000_standard[priv->video_standard].video_mode; audio_mode = xc4000_standard[priv->video_standard].audio_mode; if (type == DTV6 && priv->firm_version != 0x0102) video_mode |= 0x0001; ret = xc_set_tv_standard(priv, video_mode, audio_mode); if (ret != 0) { printk(KERN_ERR "xc4000: xc_set_tv_standard failed\n"); /* DJH - do not return when it fails... */ /* goto fail; */ } } if (xc_write_reg(priv, XREG_D_CODE, 0) == 0) ret = 0; if (priv->dvb_amplitude != 0) { if (xc_write_reg(priv, XREG_AMPLITUDE, (priv->firm_version != 0x0102 || priv->dvb_amplitude != 134 ? priv->dvb_amplitude : 132)) != 0) ret = -EREMOTEIO; } if (priv->set_smoothedcvbs != 0) { if (xc_write_reg(priv, XREG_SMOOTHEDCVBS, 1) != 0) ret = -EREMOTEIO; } if (ret != 0) { printk(KERN_ERR "xc4000: setting registers failed\n"); /* goto fail; */ } xc_tune_channel(priv, priv->freq_hz); ret = 0; fail: mutex_unlock(&priv->lock); return ret; } static int xc4000_set_analog_params(struct dvb_frontend *fe, struct analog_parameters *params) { struct xc4000_priv *priv = fe->tuner_priv; unsigned int type = 0; int ret = -EREMOTEIO; if (params->mode == V4L2_TUNER_RADIO) { dprintk(1, "%s() frequency=%d (in units of 62.5Hz)\n", __func__, params->frequency); mutex_lock(&priv->lock); params->std = 0; priv->freq_hz = params->frequency * 125L / 2; if (audio_std & XC4000_AUDIO_STD_INPUT1) { priv->video_standard = XC4000_FM_Radio_INPUT1; type = FM | INPUT1; } else { priv->video_standard = XC4000_FM_Radio_INPUT2; type = FM | INPUT2; } goto tune_channel; } dprintk(1, "%s() frequency=%d (in units of 62.5khz)\n", __func__, params->frequency); mutex_lock(&priv->lock); /* params->frequency is in units of 62.5khz */ priv->freq_hz = params->frequency * 62500; params->std &= V4L2_STD_ALL; /* if std is not defined, choose one */ if (!params->std) params->std = V4L2_STD_PAL_BG; if (audio_std & XC4000_AUDIO_STD_MONO) type = MONO; if (params->std & V4L2_STD_MN) { params->std = V4L2_STD_MN; if (audio_std & XC4000_AUDIO_STD_MONO) { priv->video_standard = XC4000_MN_NTSC_PAL_Mono; } else if (audio_std & XC4000_AUDIO_STD_A2) { params->std |= V4L2_STD_A2; priv->video_standard = XC4000_MN_NTSC_PAL_A2; } else { params->std |= V4L2_STD_BTSC; priv->video_standard = XC4000_MN_NTSC_PAL_BTSC; } goto tune_channel; } if (params->std & V4L2_STD_PAL_BG) { params->std = V4L2_STD_PAL_BG; if (audio_std & XC4000_AUDIO_STD_MONO) { priv->video_standard = XC4000_BG_PAL_MONO; } else if (!(audio_std & XC4000_AUDIO_STD_A2)) { if (!(audio_std & XC4000_AUDIO_STD_B)) { params->std |= V4L2_STD_NICAM_A; priv->video_standard = XC4000_BG_PAL_NICAM; } else { params->std |= V4L2_STD_NICAM_B; priv->video_standard = XC4000_BG_PAL_NICAM; } } else { if (!(audio_std & XC4000_AUDIO_STD_B)) { params->std |= V4L2_STD_A2_A; priv->video_standard = XC4000_BG_PAL_A2; } else { params->std |= V4L2_STD_A2_B; priv->video_standard = XC4000_BG_PAL_A2; } } goto tune_channel; } if (params->std & V4L2_STD_PAL_I) { /* default to NICAM audio standard */ params->std = V4L2_STD_PAL_I | V4L2_STD_NICAM; if (audio_std & XC4000_AUDIO_STD_MONO) priv->video_standard = XC4000_I_PAL_NICAM_MONO; else priv->video_standard = XC4000_I_PAL_NICAM; goto tune_channel; } if (params->std & V4L2_STD_PAL_DK) { params->std = V4L2_STD_PAL_DK; if (audio_std & XC4000_AUDIO_STD_MONO) { priv->video_standard = XC4000_DK_PAL_MONO; } else if (audio_std & XC4000_AUDIO_STD_A2) { params->std |= V4L2_STD_A2; priv->video_standard = XC4000_DK_PAL_A2; } else { params->std |= V4L2_STD_NICAM; priv->video_standard = XC4000_DK_PAL_NICAM; } goto tune_channel; } if (params->std & V4L2_STD_SECAM_DK) { /* default to A2 audio standard */ params->std = V4L2_STD_SECAM_DK | V4L2_STD_A2; if (audio_std & XC4000_AUDIO_STD_L) { type = 0; priv->video_standard = XC4000_DK_SECAM_NICAM; } else if (audio_std & XC4000_AUDIO_STD_MONO) { priv->video_standard = XC4000_DK_SECAM_A2MONO; } else if (audio_std & XC4000_AUDIO_STD_K3) { params->std |= V4L2_STD_SECAM_K3; priv->video_standard = XC4000_DK_SECAM_A2LDK3; } else { priv->video_standard = XC4000_DK_SECAM_A2DK1; } goto tune_channel; } if (params->std & V4L2_STD_SECAM_L) { /* default to NICAM audio standard */ type = 0; params->std = V4L2_STD_SECAM_L | V4L2_STD_NICAM; priv->video_standard = XC4000_L_SECAM_NICAM; goto tune_channel; } if (params->std & V4L2_STD_SECAM_LC) { /* default to NICAM audio standard */ type = 0; params->std = V4L2_STD_SECAM_LC | V4L2_STD_NICAM; priv->video_standard = XC4000_LC_SECAM_NICAM; goto tune_channel; } tune_channel: /* FIXME: it could be air. */ priv->rf_mode = XC_RF_MODE_CABLE; if (check_firmware(fe, type, params->std, xc4000_standard[priv->video_standard].int_freq) != 0) goto fail; ret = xc_set_signal_source(priv, priv->rf_mode); if (ret != 0) { printk(KERN_ERR "xc4000: xc_set_signal_source(%d) failed\n", priv->rf_mode); goto fail; } else { u16 video_mode, audio_mode; video_mode = xc4000_standard[priv->video_standard].video_mode; audio_mode = xc4000_standard[priv->video_standard].audio_mode; if (priv->video_standard < XC4000_BG_PAL_A2) { if (type & NOGD) video_mode &= 0xFF7F; } else if (priv->video_standard < XC4000_I_PAL_NICAM) { if (priv->firm_version == 0x0102) video_mode &= 0xFEFF; if (audio_std & XC4000_AUDIO_STD_B) video_mode |= 0x0080; } ret = xc_set_tv_standard(priv, video_mode, audio_mode); if (ret != 0) { printk(KERN_ERR "xc4000: xc_set_tv_standard failed\n"); goto fail; } } if (xc_write_reg(priv, XREG_D_CODE, 0) == 0) ret = 0; if (xc_write_reg(priv, XREG_AMPLITUDE, 1) != 0) ret = -EREMOTEIO; if (priv->set_smoothedcvbs != 0) { if (xc_write_reg(priv, XREG_SMOOTHEDCVBS, 1) != 0) ret = -EREMOTEIO; } if (ret != 0) { printk(KERN_ERR "xc4000: setting registers failed\n"); goto fail; } xc_tune_channel(priv, priv->freq_hz); ret = 0; fail: mutex_unlock(&priv->lock); return ret; } static int xc4000_get_frequency(struct dvb_frontend *fe, u32 *freq) { struct xc4000_priv *priv = fe->tuner_priv; *freq = priv->freq_hz; if (debug) { mutex_lock(&priv->lock); if ((priv->cur_fw.type & (BASE | FM | DTV6 | DTV7 | DTV78 | DTV8)) == BASE) { u16 snr = 0; if (xc4000_readreg(priv, XREG_SNR, &snr) == 0) { mutex_unlock(&priv->lock); dprintk(1, "%s() freq = %u, SNR = %d\n", __func__, *freq, snr); return 0; } } mutex_unlock(&priv->lock); } dprintk(1, "%s()\n", __func__); return 0; } static int xc4000_get_bandwidth(struct dvb_frontend *fe, u32 *bw) { struct xc4000_priv *priv = fe->tuner_priv; dprintk(1, "%s()\n", __func__); *bw = priv->bandwidth; return 0; } static int xc4000_get_status(struct dvb_frontend *fe, u32 *status) { struct xc4000_priv *priv = fe->tuner_priv; u16 lock_status = 0; mutex_lock(&priv->lock); if (priv->cur_fw.type & BASE) xc_get_lock_status(priv, &lock_status); *status = (lock_status == 1 ? TUNER_STATUS_LOCKED | TUNER_STATUS_STEREO : 0); if (priv->cur_fw.type & (DTV6 | DTV7 | DTV78 | DTV8)) *status &= (~TUNER_STATUS_STEREO); mutex_unlock(&priv->lock); dprintk(2, "%s() lock_status = %d\n", __func__, lock_status); return 0; } static int xc4000_sleep(struct dvb_frontend *fe) { struct xc4000_priv *priv = fe->tuner_priv; int ret = 0; dprintk(1, "%s()\n", __func__); mutex_lock(&priv->lock); /* Avoid firmware reload on slow devices */ if ((no_poweroff == 2 || (no_poweroff == 0 && priv->default_pm != 0)) && (priv->cur_fw.type & BASE) != 0) { /* force reset and firmware reload */ priv->cur_fw.type = XC_POWERED_DOWN; if (xc_write_reg(priv, XREG_POWER_DOWN, 0) != 0) { printk(KERN_ERR "xc4000: %s() unable to shutdown tuner\n", __func__); ret = -EREMOTEIO; } msleep(20); } mutex_unlock(&priv->lock); return ret; } static int xc4000_init(struct dvb_frontend *fe) { dprintk(1, "%s()\n", __func__); return 0; } static int xc4000_release(struct dvb_frontend *fe) { struct xc4000_priv *priv = fe->tuner_priv; dprintk(1, "%s()\n", __func__); mutex_lock(&xc4000_list_mutex); if (priv) hybrid_tuner_release_state(priv); mutex_unlock(&xc4000_list_mutex); fe->tuner_priv = NULL; return 0; } static const struct dvb_tuner_ops xc4000_tuner_ops = { .info = { .name = "Xceive XC4000", .frequency_min = 1000000, .frequency_max = 1023000000, .frequency_step = 50000, }, .release = xc4000_release, .init = xc4000_init, .sleep = xc4000_sleep, .set_params = xc4000_set_params, .set_analog_params = xc4000_set_analog_params, .get_frequency = xc4000_get_frequency, .get_bandwidth = xc4000_get_bandwidth, .get_status = xc4000_get_status }; struct dvb_frontend *xc4000_attach(struct dvb_frontend *fe, struct i2c_adapter *i2c, struct xc4000_config *cfg) { struct xc4000_priv *priv = NULL; int instance; u16 id = 0; dprintk(1, "%s(%d-%04x)\n", __func__, i2c ? i2c_adapter_id(i2c) : -1, cfg ? cfg->i2c_address : -1); mutex_lock(&xc4000_list_mutex); instance = hybrid_tuner_request_state(struct xc4000_priv, priv, hybrid_tuner_instance_list, i2c, cfg->i2c_address, "xc4000"); switch (instance) { case 0: goto fail; break; case 1: /* new tuner instance */ priv->bandwidth = 6000000; /* set default configuration */ priv->if_khz = 4560; priv->default_pm = 0; priv->dvb_amplitude = 134; priv->set_smoothedcvbs = 1; mutex_init(&priv->lock); fe->tuner_priv = priv; break; default: /* existing tuner instance */ fe->tuner_priv = priv; break; } if (cfg->if_khz != 0) { /* copy configuration if provided by the caller */ priv->if_khz = cfg->if_khz; priv->default_pm = cfg->default_pm; priv->dvb_amplitude = cfg->dvb_amplitude; priv->set_smoothedcvbs = cfg->set_smoothedcvbs; } /* Check if firmware has been loaded. It is possible that another instance of the driver has loaded the firmware. */ if (instance == 1) { if (xc4000_readreg(priv, XREG_PRODUCT_ID, &id) != 0) goto fail; } else { id = ((priv->cur_fw.type & BASE) != 0 ? priv->hwmodel : XC_PRODUCT_ID_FW_NOT_LOADED); } switch (id) { case XC_PRODUCT_ID_XC4000: case XC_PRODUCT_ID_XC4100: printk(KERN_INFO "xc4000: Successfully identified at address 0x%02x\n", cfg->i2c_address); printk(KERN_INFO "xc4000: Firmware has been loaded previously\n"); break; case XC_PRODUCT_ID_FW_NOT_LOADED: printk(KERN_INFO "xc4000: Successfully identified at address 0x%02x\n", cfg->i2c_address); printk(KERN_INFO "xc4000: Firmware has not been loaded previously\n"); break; default: printk(KERN_ERR "xc4000: Device not found at addr 0x%02x (0x%x)\n", cfg->i2c_address, id); goto fail; } mutex_unlock(&xc4000_list_mutex); memcpy(&fe->ops.tuner_ops, &xc4000_tuner_ops, sizeof(struct dvb_tuner_ops)); if (instance == 1) { int ret; mutex_lock(&priv->lock); ret = xc4000_fwupload(fe); mutex_unlock(&priv->lock); if (ret != 0) goto fail2; } return fe; fail: mutex_unlock(&xc4000_list_mutex); fail2: xc4000_release(fe); return NULL; } EXPORT_SYMBOL(xc4000_attach); MODULE_AUTHOR("Steven Toth, Davide Ferri"); MODULE_DESCRIPTION("Xceive xc4000 silicon tuner driver"); MODULE_LICENSE("GPL");
gpl-2.0
puskyer/android_kernel_motorola_olympus
drivers/gpu/drm/ttm/ttm_bo_util.c
535
16883
/************************************************************************** * * Copyright (c) 2007-2009 VMware, Inc., Palo Alto, CA., USA * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ /* * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com> */ #include "ttm/ttm_bo_driver.h" #include "ttm/ttm_placement.h" #include <linux/io.h> #include <linux/highmem.h> #include <linux/wait.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/module.h> void ttm_bo_free_old_node(struct ttm_buffer_object *bo) { ttm_bo_mem_put(bo, &bo->mem); } int ttm_bo_move_ttm(struct ttm_buffer_object *bo, bool evict, bool no_wait_reserve, bool no_wait_gpu, struct ttm_mem_reg *new_mem) { struct ttm_tt *ttm = bo->ttm; struct ttm_mem_reg *old_mem = &bo->mem; int ret; if (old_mem->mem_type != TTM_PL_SYSTEM) { ttm_tt_unbind(ttm); ttm_bo_free_old_node(bo); ttm_flag_masked(&old_mem->placement, TTM_PL_FLAG_SYSTEM, TTM_PL_MASK_MEM); old_mem->mem_type = TTM_PL_SYSTEM; } ret = ttm_tt_set_placement_caching(ttm, new_mem->placement); if (unlikely(ret != 0)) return ret; if (new_mem->mem_type != TTM_PL_SYSTEM) { ret = ttm_tt_bind(ttm, new_mem); if (unlikely(ret != 0)) return ret; } *old_mem = *new_mem; new_mem->mm_node = NULL; return 0; } EXPORT_SYMBOL(ttm_bo_move_ttm); int ttm_mem_io_lock(struct ttm_mem_type_manager *man, bool interruptible) { if (likely(man->io_reserve_fastpath)) return 0; if (interruptible) return mutex_lock_interruptible(&man->io_reserve_mutex); mutex_lock(&man->io_reserve_mutex); return 0; } void ttm_mem_io_unlock(struct ttm_mem_type_manager *man) { if (likely(man->io_reserve_fastpath)) return; mutex_unlock(&man->io_reserve_mutex); } static int ttm_mem_io_evict(struct ttm_mem_type_manager *man) { struct ttm_buffer_object *bo; if (!man->use_io_reserve_lru || list_empty(&man->io_reserve_lru)) return -EAGAIN; bo = list_first_entry(&man->io_reserve_lru, struct ttm_buffer_object, io_reserve_lru); list_del_init(&bo->io_reserve_lru); ttm_bo_unmap_virtual_locked(bo); return 0; } static int ttm_mem_io_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; int ret = 0; if (!bdev->driver->io_mem_reserve) return 0; if (likely(man->io_reserve_fastpath)) return bdev->driver->io_mem_reserve(bdev, mem); if (bdev->driver->io_mem_reserve && mem->bus.io_reserved_count++ == 0) { retry: ret = bdev->driver->io_mem_reserve(bdev, mem); if (ret == -EAGAIN) { ret = ttm_mem_io_evict(man); if (ret == 0) goto retry; } } return ret; } static void ttm_mem_io_free(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; if (likely(man->io_reserve_fastpath)) return; if (bdev->driver->io_mem_reserve && --mem->bus.io_reserved_count == 0 && bdev->driver->io_mem_free) bdev->driver->io_mem_free(bdev, mem); } int ttm_mem_io_reserve_vm(struct ttm_buffer_object *bo) { struct ttm_mem_reg *mem = &bo->mem; int ret; if (!mem->bus.io_reserved_vm) { struct ttm_mem_type_manager *man = &bo->bdev->man[mem->mem_type]; ret = ttm_mem_io_reserve(bo->bdev, mem); if (unlikely(ret != 0)) return ret; mem->bus.io_reserved_vm = true; if (man->use_io_reserve_lru) list_add_tail(&bo->io_reserve_lru, &man->io_reserve_lru); } return 0; } void ttm_mem_io_free_vm(struct ttm_buffer_object *bo) { struct ttm_mem_reg *mem = &bo->mem; if (mem->bus.io_reserved_vm) { mem->bus.io_reserved_vm = false; list_del_init(&bo->io_reserve_lru); ttm_mem_io_free(bo->bdev, mem); } } int ttm_mem_reg_ioremap(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem, void **virtual) { struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type]; int ret; void *addr; *virtual = NULL; (void) ttm_mem_io_lock(man, false); ret = ttm_mem_io_reserve(bdev, mem); ttm_mem_io_unlock(man); if (ret || !mem->bus.is_iomem) return ret; if (mem->bus.addr) { addr = mem->bus.addr; } else { if (mem->placement & TTM_PL_FLAG_WC) addr = ioremap_wc(mem->bus.base + mem->bus.offset, mem->bus.size); else addr = ioremap_nocache(mem->bus.base + mem->bus.offset, mem->bus.size); if (!addr) { (void) ttm_mem_io_lock(man, false); ttm_mem_io_free(bdev, mem); ttm_mem_io_unlock(man); return -ENOMEM; } } *virtual = addr; return 0; } void ttm_mem_reg_iounmap(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem, void *virtual) { struct ttm_mem_type_manager *man; man = &bdev->man[mem->mem_type]; if (virtual && mem->bus.addr == NULL) iounmap(virtual); (void) ttm_mem_io_lock(man, false); ttm_mem_io_free(bdev, mem); ttm_mem_io_unlock(man); } static int ttm_copy_io_page(void *dst, void *src, unsigned long page) { uint32_t *dstP = (uint32_t *) ((unsigned long)dst + (page << PAGE_SHIFT)); uint32_t *srcP = (uint32_t *) ((unsigned long)src + (page << PAGE_SHIFT)); int i; for (i = 0; i < PAGE_SIZE / sizeof(uint32_t); ++i) iowrite32(ioread32(srcP++), dstP++); return 0; } static int ttm_copy_io_ttm_page(struct ttm_tt *ttm, void *src, unsigned long page, pgprot_t prot) { struct page *d = ttm_tt_get_page(ttm, page); void *dst; if (!d) return -ENOMEM; src = (void *)((unsigned long)src + (page << PAGE_SHIFT)); #ifdef CONFIG_X86 dst = kmap_atomic_prot(d, prot); #else if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL)) dst = vmap(&d, 1, 0, prot); else dst = kmap(d); #endif if (!dst) return -ENOMEM; memcpy_fromio(dst, src, PAGE_SIZE); #ifdef CONFIG_X86 kunmap_atomic(dst); #else if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL)) vunmap(dst); else kunmap(d); #endif return 0; } static int ttm_copy_ttm_io_page(struct ttm_tt *ttm, void *dst, unsigned long page, pgprot_t prot) { struct page *s = ttm_tt_get_page(ttm, page); void *src; if (!s) return -ENOMEM; dst = (void *)((unsigned long)dst + (page << PAGE_SHIFT)); #ifdef CONFIG_X86 src = kmap_atomic_prot(s, prot); #else if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL)) src = vmap(&s, 1, 0, prot); else src = kmap(s); #endif if (!src) return -ENOMEM; memcpy_toio(dst, src, PAGE_SIZE); #ifdef CONFIG_X86 kunmap_atomic(src); #else if (pgprot_val(prot) != pgprot_val(PAGE_KERNEL)) vunmap(src); else kunmap(s); #endif return 0; } int ttm_bo_move_memcpy(struct ttm_buffer_object *bo, bool evict, bool no_wait_reserve, bool no_wait_gpu, struct ttm_mem_reg *new_mem) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_mem_type_manager *man = &bdev->man[new_mem->mem_type]; struct ttm_tt *ttm = bo->ttm; struct ttm_mem_reg *old_mem = &bo->mem; struct ttm_mem_reg old_copy = *old_mem; void *old_iomap; void *new_iomap; int ret; unsigned long i; unsigned long page; unsigned long add = 0; int dir; ret = ttm_mem_reg_ioremap(bdev, old_mem, &old_iomap); if (ret) return ret; ret = ttm_mem_reg_ioremap(bdev, new_mem, &new_iomap); if (ret) goto out; if (old_iomap == NULL && new_iomap == NULL) goto out2; if (old_iomap == NULL && ttm == NULL) goto out2; add = 0; dir = 1; if ((old_mem->mem_type == new_mem->mem_type) && (new_mem->start < old_mem->start + old_mem->size)) { dir = -1; add = new_mem->num_pages - 1; } for (i = 0; i < new_mem->num_pages; ++i) { page = i * dir + add; if (old_iomap == NULL) { pgprot_t prot = ttm_io_prot(old_mem->placement, PAGE_KERNEL); ret = ttm_copy_ttm_io_page(ttm, new_iomap, page, prot); } else if (new_iomap == NULL) { pgprot_t prot = ttm_io_prot(new_mem->placement, PAGE_KERNEL); ret = ttm_copy_io_ttm_page(ttm, old_iomap, page, prot); } else ret = ttm_copy_io_page(new_iomap, old_iomap, page); if (ret) goto out1; } mb(); out2: old_copy = *old_mem; *old_mem = *new_mem; new_mem->mm_node = NULL; if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) && (ttm != NULL)) { ttm_tt_unbind(ttm); ttm_tt_destroy(ttm); bo->ttm = NULL; } out1: ttm_mem_reg_iounmap(bdev, old_mem, new_iomap); out: ttm_mem_reg_iounmap(bdev, &old_copy, old_iomap); ttm_bo_mem_put(bo, &old_copy); return ret; } EXPORT_SYMBOL(ttm_bo_move_memcpy); static void ttm_transfered_destroy(struct ttm_buffer_object *bo) { kfree(bo); } /** * ttm_buffer_object_transfer * * @bo: A pointer to a struct ttm_buffer_object. * @new_obj: A pointer to a pointer to a newly created ttm_buffer_object, * holding the data of @bo with the old placement. * * This is a utility function that may be called after an accelerated move * has been scheduled. A new buffer object is created as a placeholder for * the old data while it's being copied. When that buffer object is idle, * it can be destroyed, releasing the space of the old placement. * Returns: * !0: Failure. */ static int ttm_buffer_object_transfer(struct ttm_buffer_object *bo, struct ttm_buffer_object **new_obj) { struct ttm_buffer_object *fbo; struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_driver *driver = bdev->driver; fbo = kzalloc(sizeof(*fbo), GFP_KERNEL); if (!fbo) return -ENOMEM; *fbo = *bo; /** * Fix up members that we shouldn't copy directly: * TODO: Explicit member copy would probably be better here. */ init_waitqueue_head(&fbo->event_queue); INIT_LIST_HEAD(&fbo->ddestroy); INIT_LIST_HEAD(&fbo->lru); INIT_LIST_HEAD(&fbo->swap); INIT_LIST_HEAD(&fbo->io_reserve_lru); fbo->vm_node = NULL; atomic_set(&fbo->cpu_writers, 0); fbo->sync_obj = driver->sync_obj_ref(bo->sync_obj); kref_init(&fbo->list_kref); kref_init(&fbo->kref); fbo->destroy = &ttm_transfered_destroy; *new_obj = fbo; return 0; } pgprot_t ttm_io_prot(uint32_t caching_flags, pgprot_t tmp) { #if defined(__i386__) || defined(__x86_64__) if (caching_flags & TTM_PL_FLAG_WC) tmp = pgprot_writecombine(tmp); else if (boot_cpu_data.x86 > 3) tmp = pgprot_noncached(tmp); #elif defined(__powerpc__) if (!(caching_flags & TTM_PL_FLAG_CACHED)) { pgprot_val(tmp) |= _PAGE_NO_CACHE; if (caching_flags & TTM_PL_FLAG_UNCACHED) pgprot_val(tmp) |= _PAGE_GUARDED; } #endif #if defined(__ia64__) if (caching_flags & TTM_PL_FLAG_WC) tmp = pgprot_writecombine(tmp); else tmp = pgprot_noncached(tmp); #endif #if defined(__sparc__) if (!(caching_flags & TTM_PL_FLAG_CACHED)) tmp = pgprot_noncached(tmp); #endif return tmp; } EXPORT_SYMBOL(ttm_io_prot); static int ttm_bo_ioremap(struct ttm_buffer_object *bo, unsigned long offset, unsigned long size, struct ttm_bo_kmap_obj *map) { struct ttm_mem_reg *mem = &bo->mem; if (bo->mem.bus.addr) { map->bo_kmap_type = ttm_bo_map_premapped; map->virtual = (void *)(((u8 *)bo->mem.bus.addr) + offset); } else { map->bo_kmap_type = ttm_bo_map_iomap; if (mem->placement & TTM_PL_FLAG_WC) map->virtual = ioremap_wc(bo->mem.bus.base + bo->mem.bus.offset + offset, size); else map->virtual = ioremap_nocache(bo->mem.bus.base + bo->mem.bus.offset + offset, size); } return (!map->virtual) ? -ENOMEM : 0; } static int ttm_bo_kmap_ttm(struct ttm_buffer_object *bo, unsigned long start_page, unsigned long num_pages, struct ttm_bo_kmap_obj *map) { struct ttm_mem_reg *mem = &bo->mem; pgprot_t prot; struct ttm_tt *ttm = bo->ttm; struct page *d; int i; BUG_ON(!ttm); if (num_pages == 1 && (mem->placement & TTM_PL_FLAG_CACHED)) { /* * We're mapping a single page, and the desired * page protection is consistent with the bo. */ map->bo_kmap_type = ttm_bo_map_kmap; map->page = ttm_tt_get_page(ttm, start_page); map->virtual = kmap(map->page); } else { /* * Populate the part we're mapping; */ for (i = start_page; i < start_page + num_pages; ++i) { d = ttm_tt_get_page(ttm, i); if (!d) return -ENOMEM; } /* * We need to use vmap to get the desired page protection * or to make the buffer object look contiguous. */ prot = (mem->placement & TTM_PL_FLAG_CACHED) ? PAGE_KERNEL : ttm_io_prot(mem->placement, PAGE_KERNEL); map->bo_kmap_type = ttm_bo_map_vmap; map->virtual = vmap(ttm->pages + start_page, num_pages, 0, prot); } return (!map->virtual) ? -ENOMEM : 0; } int ttm_bo_kmap(struct ttm_buffer_object *bo, unsigned long start_page, unsigned long num_pages, struct ttm_bo_kmap_obj *map) { struct ttm_mem_type_manager *man = &bo->bdev->man[bo->mem.mem_type]; unsigned long offset, size; int ret; BUG_ON(!list_empty(&bo->swap)); map->virtual = NULL; map->bo = bo; if (num_pages > bo->num_pages) return -EINVAL; if (start_page > bo->num_pages) return -EINVAL; #if 0 if (num_pages > 1 && !DRM_SUSER(DRM_CURPROC)) return -EPERM; #endif (void) ttm_mem_io_lock(man, false); ret = ttm_mem_io_reserve(bo->bdev, &bo->mem); ttm_mem_io_unlock(man); if (ret) return ret; if (!bo->mem.bus.is_iomem) { return ttm_bo_kmap_ttm(bo, start_page, num_pages, map); } else { offset = start_page << PAGE_SHIFT; size = num_pages << PAGE_SHIFT; return ttm_bo_ioremap(bo, offset, size, map); } } EXPORT_SYMBOL(ttm_bo_kmap); void ttm_bo_kunmap(struct ttm_bo_kmap_obj *map) { struct ttm_buffer_object *bo = map->bo; struct ttm_mem_type_manager *man = &bo->bdev->man[bo->mem.mem_type]; if (!map->virtual) return; switch (map->bo_kmap_type) { case ttm_bo_map_iomap: iounmap(map->virtual); break; case ttm_bo_map_vmap: vunmap(map->virtual); break; case ttm_bo_map_kmap: kunmap(map->page); break; case ttm_bo_map_premapped: break; default: BUG(); } (void) ttm_mem_io_lock(man, false); ttm_mem_io_free(map->bo->bdev, &map->bo->mem); ttm_mem_io_unlock(man); map->virtual = NULL; map->page = NULL; } EXPORT_SYMBOL(ttm_bo_kunmap); int ttm_bo_move_accel_cleanup(struct ttm_buffer_object *bo, void *sync_obj, void *sync_obj_arg, bool evict, bool no_wait_reserve, bool no_wait_gpu, struct ttm_mem_reg *new_mem) { struct ttm_bo_device *bdev = bo->bdev; struct ttm_bo_driver *driver = bdev->driver; struct ttm_mem_type_manager *man = &bdev->man[new_mem->mem_type]; struct ttm_mem_reg *old_mem = &bo->mem; int ret; struct ttm_buffer_object *ghost_obj; void *tmp_obj = NULL; spin_lock(&bdev->fence_lock); if (bo->sync_obj) { tmp_obj = bo->sync_obj; bo->sync_obj = NULL; } bo->sync_obj = driver->sync_obj_ref(sync_obj); bo->sync_obj_arg = sync_obj_arg; if (evict) { ret = ttm_bo_wait(bo, false, false, false); spin_unlock(&bdev->fence_lock); if (tmp_obj) driver->sync_obj_unref(&tmp_obj); if (ret) return ret; if ((man->flags & TTM_MEMTYPE_FLAG_FIXED) && (bo->ttm != NULL)) { ttm_tt_unbind(bo->ttm); ttm_tt_destroy(bo->ttm); bo->ttm = NULL; } ttm_bo_free_old_node(bo); } else { /** * This should help pipeline ordinary buffer moves. * * Hang old buffer memory on a new buffer object, * and leave it to be released when the GPU * operation has completed. */ set_bit(TTM_BO_PRIV_FLAG_MOVING, &bo->priv_flags); spin_unlock(&bdev->fence_lock); if (tmp_obj) driver->sync_obj_unref(&tmp_obj); ret = ttm_buffer_object_transfer(bo, &ghost_obj); if (ret) return ret; /** * If we're not moving to fixed memory, the TTM object * needs to stay alive. Otherwhise hang it on the ghost * bo to be unbound and destroyed. */ if (!(man->flags & TTM_MEMTYPE_FLAG_FIXED)) ghost_obj->ttm = NULL; else bo->ttm = NULL; ttm_bo_unreserve(ghost_obj); ttm_bo_unref(&ghost_obj); } *old_mem = *new_mem; new_mem->mm_node = NULL; return 0; } EXPORT_SYMBOL(ttm_bo_move_accel_cleanup);
gpl-2.0
casso/Mysteria4
dep/ACE_wrappers/ace/Signal.cpp
535
6135
// $Id: Signal.cpp 91286 2010-08-05 09:04:31Z johnnyw $ #include "ace/Signal.h" // #include "ace/Log_Msg.h" #if !defined (__ACE_INLINE__) #include "ace/Signal.inl" #endif /* __ACE_INLINE__ */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Action) void ACE_Sig_Action::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_Sig_Action::dump"); #endif /* ACE_HAS_DUMP */ } ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Set) ACE_Sig_Set::~ACE_Sig_Set (void) { ACE_TRACE ("ACE_Sig_Set::~ACE_Sig_Set"); ACE_OS::sigemptyset (&this->sigset_); } ACE_Sig_Action::~ACE_Sig_Action (void) { ACE_TRACE ("ACE_Sig_Action::~ACE_Sig_Action"); } // Restore the signal mask. ACE_Sig_Guard::~ACE_Sig_Guard (void) { //ACE_TRACE ("ACE_Sig_Guard::~ACE_Sig_Guard"); if (!this->condition_) return; #if !defined (ACE_LACKS_UNIX_SIGNALS) #if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) ACE_OS::sigprocmask (SIG_SETMASK, (sigset_t *) this->omask_, 0); #else ACE_OS::thr_sigsetmask (SIG_SETMASK, (sigset_t *) this->omask_, 0); #endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ #endif /* !ACE_LACKS_UNIX_SIGNALS */ } void ACE_Sig_Set::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_Sig_Set::dump"); #endif /* ACE_HAS_DUMP */ } ACE_ALLOC_HOOK_DEFINE(ACE_Sig_Guard) void ACE_Sig_Guard::dump (void) const { #if defined (ACE_HAS_DUMP) ACE_TRACE ("ACE_Sig_Guard::dump"); #endif /* ACE_HAS_DUMP */ } ACE_Sig_Action::ACE_Sig_Action (void) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = 0; // Since Service_Config::signal_handler_ is static and has an // ACE_Sig_Action instance, Win32 will get errno set unless this is // commented out. #if !defined (ACE_WIN32) ACE_OS::sigemptyset (&this->sa_.sa_mask); #endif /* ACE_WIN32 */ this->sa_.sa_handler = 0; } ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, sigset_t *sig_mask, int sig_flags) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = sig_flags; if (sig_mask == 0) ACE_OS::sigemptyset (&this->sa_.sa_mask); else this->sa_.sa_mask = *sig_mask; // Structure assignment... #if !defined(ACE_HAS_TANDEM_SIGNALS) this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); #else this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); #endif /* !ACE_HAS_TANDEM_SIGNALS */ } ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, const ACE_Sig_Set &sig_mask, int sig_flags) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = sig_flags; // Structure assignment... this->sa_.sa_mask = sig_mask.sigset (); #if !defined(ACE_HAS_TANDEM_SIGNALS) this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); #else this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); #endif /* !ACE_HAS_TANDEM_SIGNALS */ } ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, int signum, sigset_t *sig_mask, int sig_flags) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = sig_flags; if (sig_mask == 0) ACE_OS::sigemptyset (&this->sa_.sa_mask); else this->sa_.sa_mask = *sig_mask; // Structure assignment... #if !defined(ACE_HAS_TANDEM_SIGNALS) this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); #else this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); #endif /* !ACE_HAS_TANDEM_SIGNALS */ ACE_OS::sigaction (signum, &this->sa_, 0); } ACE_Sig_Action::ACE_Sig_Action (ACE_SignalHandler sig_handler, int signum, const ACE_Sig_Set &sig_mask, int sig_flags) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = sig_flags; // Structure assignment... this->sa_.sa_mask = sig_mask.sigset (); #if !defined(ACE_HAS_TANDEM_SIGNALS) this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); #else this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); #endif /* !ACE_HAS_TANDEM_SIGNALS */ ACE_OS::sigaction (signum, &this->sa_, 0); } ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Set &signals, ACE_SignalHandler sig_handler, const ACE_Sig_Set &sig_mask, int sig_flags) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = sig_flags; // Structure assignment... this->sa_.sa_mask = sig_mask.sigset (); #if !defined(ACE_HAS_TANDEM_SIGNALS) this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); #else this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); #endif /* !ACE_HAS_TANDEM_SIGNALS */ #if (ACE_NSIG > 0) for (int s = 1; s < ACE_NSIG; s++) if ((signals.is_member (s)) == 1) ACE_OS::sigaction (s, &this->sa_, 0); #else /* ACE_NSIG <= 0 */ ACE_UNUSED_ARG (signals); #endif /* ACE_NSIG <= 0 */ } ACE_Sig_Action::ACE_Sig_Action (const ACE_Sig_Set &signals, ACE_SignalHandler sig_handler, sigset_t *sig_mask, int sig_flags) { // ACE_TRACE ("ACE_Sig_Action::ACE_Sig_Action"); this->sa_.sa_flags = sig_flags; if (sig_mask == 0) ACE_OS::sigemptyset (&this->sa_.sa_mask); else this->sa_.sa_mask = *sig_mask; // Structure assignment... #if !defined(ACE_HAS_TANDEM_SIGNALS) this->sa_.sa_handler = ACE_SignalHandlerV (sig_handler); #else this->sa_.sa_handler = (void (*)()) ACE_SignalHandlerV (sig_handler); #endif /* !ACE_HAS_TANDEM_SIGNALS */ #if (ACE_NSIG > 0) for (int s = 1; s < ACE_NSIG; s++) if ((signals.is_member (s)) == 1) ACE_OS::sigaction (s, &this->sa_, 0); #else /* ACE_NSIG <= 0 */ ACE_UNUSED_ARG (signals); #endif /* ACE_NSIG <= 0 */ } ACE_END_VERSIONED_NAMESPACE_DECL
gpl-2.0
ftCommunity/ft-TXT
board/knobloch/TXT/board-support/ti-linux/arch/x86/pci/broadcom_bus.c
1815
3334
/* * Read address ranges from a Broadcom CNB20LE Host Bridge * * Copyright (c) 2010 Ira W. Snyder <iws@ovro.caltech.edu> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/acpi.h> #include <linux/delay.h> #include <linux/dmi.h> #include <linux/pci.h> #include <linux/init.h> #include <asm/pci_x86.h> #include <asm/pci-direct.h> #include "bus_numa.h" static void __init cnb20le_res(u8 bus, u8 slot, u8 func) { struct pci_root_info *info; struct pci_root_res *root_res; struct resource res; u16 word1, word2; u8 fbus, lbus; /* read the PCI bus numbers */ fbus = read_pci_config_byte(bus, slot, func, 0x44); lbus = read_pci_config_byte(bus, slot, func, 0x45); info = alloc_pci_root_info(fbus, lbus, 0, 0); /* * Add the legacy IDE ports on bus 0 * * These do not exist anywhere in the bridge registers, AFAICT. I do * not have the datasheet, so this is the best I can do. */ if (fbus == 0) { update_res(info, 0x01f0, 0x01f7, IORESOURCE_IO, 0); update_res(info, 0x03f6, 0x03f6, IORESOURCE_IO, 0); update_res(info, 0x0170, 0x0177, IORESOURCE_IO, 0); update_res(info, 0x0376, 0x0376, IORESOURCE_IO, 0); update_res(info, 0xffa0, 0xffaf, IORESOURCE_IO, 0); } /* read the non-prefetchable memory window */ word1 = read_pci_config_16(bus, slot, func, 0xc0); word2 = read_pci_config_16(bus, slot, func, 0xc2); if (word1 != word2) { res.start = (word1 << 16) | 0x0000; res.end = (word2 << 16) | 0xffff; res.flags = IORESOURCE_MEM; update_res(info, res.start, res.end, res.flags, 0); } /* read the prefetchable memory window */ word1 = read_pci_config_16(bus, slot, func, 0xc4); word2 = read_pci_config_16(bus, slot, func, 0xc6); if (word1 != word2) { res.start = ((resource_size_t) word1 << 16) | 0x0000; res.end = ((resource_size_t) word2 << 16) | 0xffff; res.flags = IORESOURCE_MEM | IORESOURCE_PREFETCH; update_res(info, res.start, res.end, res.flags, 0); } /* read the IO port window */ word1 = read_pci_config_16(bus, slot, func, 0xd0); word2 = read_pci_config_16(bus, slot, func, 0xd2); if (word1 != word2) { res.start = word1; res.end = word2; res.flags = IORESOURCE_IO; update_res(info, res.start, res.end, res.flags, 0); } /* print information about this host bridge */ res.start = fbus; res.end = lbus; res.flags = IORESOURCE_BUS; printk(KERN_INFO "CNB20LE PCI Host Bridge (domain 0000 %pR)\n", &res); list_for_each_entry(root_res, &info->resources, list) printk(KERN_INFO "host bridge window %pR\n", &root_res->res); } static int __init broadcom_postcore_init(void) { u8 bus = 0, slot = 0; u32 id; u16 vendor, device; #ifdef CONFIG_ACPI /* * We should get host bridge information from ACPI unless the BIOS * doesn't support it. */ if (acpi_os_get_root_pointer()) return 0; #endif id = read_pci_config(bus, slot, 0, PCI_VENDOR_ID); vendor = id & 0xffff; device = (id >> 16) & 0xffff; if (vendor == PCI_VENDOR_ID_SERVERWORKS && device == PCI_DEVICE_ID_SERVERWORKS_LE) { cnb20le_res(bus, slot, 0); cnb20le_res(bus, slot, 1); } return 0; } postcore_initcall(broadcom_postcore_init);
gpl-2.0
Forest1971/forest-cm11
arch/powerpc/kernel/dma.c
2327
5208
/* * Copyright (C) 2006 Benjamin Herrenschmidt, IBM Corporation * * Provide default implementations of the DMA mapping callbacks for * directly mapped busses. */ #include <linux/device.h> #include <linux/dma-mapping.h> #include <linux/dma-debug.h> #include <linux/gfp.h> #include <linux/memblock.h> #include <asm/bug.h> #include <asm/abs_addr.h> #include <asm/machdep.h> /* * Generic direct DMA implementation * * This implementation supports a per-device offset that can be applied if * the address at which memory is visible to devices is not 0. Platform code * can set archdata.dma_data to an unsigned long holding the offset. By * default the offset is PCI_DRAM_OFFSET. */ void *dma_direct_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flag) { void *ret; #ifdef CONFIG_NOT_COHERENT_CACHE ret = __dma_alloc_coherent(dev, size, dma_handle, flag); if (ret == NULL) return NULL; *dma_handle += get_dma_offset(dev); return ret; #else struct page *page; int node = dev_to_node(dev); /* ignore region specifiers */ flag &= ~(__GFP_HIGHMEM); page = alloc_pages_node(node, flag, get_order(size)); if (page == NULL) return NULL; ret = page_address(page); memset(ret, 0, size); *dma_handle = virt_to_abs(ret) + get_dma_offset(dev); return ret; #endif } void dma_direct_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle) { #ifdef CONFIG_NOT_COHERENT_CACHE __dma_free_coherent(size, vaddr); #else free_pages((unsigned long)vaddr, get_order(size)); #endif } static int dma_direct_map_sg(struct device *dev, struct scatterlist *sgl, int nents, enum dma_data_direction direction, struct dma_attrs *attrs) { struct scatterlist *sg; int i; for_each_sg(sgl, sg, nents, i) { sg->dma_address = sg_phys(sg) + get_dma_offset(dev); sg->dma_length = sg->length; __dma_sync_page(sg_page(sg), sg->offset, sg->length, direction); } return nents; } static void dma_direct_unmap_sg(struct device *dev, struct scatterlist *sg, int nents, enum dma_data_direction direction, struct dma_attrs *attrs) { } static int dma_direct_dma_supported(struct device *dev, u64 mask) { #ifdef CONFIG_PPC64 /* Could be improved so platforms can set the limit in case * they have limited DMA windows */ return mask >= get_dma_offset(dev) + (memblock_end_of_DRAM() - 1); #else return 1; #endif } static inline dma_addr_t dma_direct_map_page(struct device *dev, struct page *page, unsigned long offset, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { BUG_ON(dir == DMA_NONE); __dma_sync_page(page, offset, size, dir); return page_to_phys(page) + offset + get_dma_offset(dev); } static inline void dma_direct_unmap_page(struct device *dev, dma_addr_t dma_address, size_t size, enum dma_data_direction direction, struct dma_attrs *attrs) { } #ifdef CONFIG_NOT_COHERENT_CACHE static inline void dma_direct_sync_sg(struct device *dev, struct scatterlist *sgl, int nents, enum dma_data_direction direction) { struct scatterlist *sg; int i; for_each_sg(sgl, sg, nents, i) __dma_sync_page(sg_page(sg), sg->offset, sg->length, direction); } static inline void dma_direct_sync_single(struct device *dev, dma_addr_t dma_handle, size_t size, enum dma_data_direction direction) { __dma_sync(bus_to_virt(dma_handle), size, direction); } #endif struct dma_map_ops dma_direct_ops = { .alloc_coherent = dma_direct_alloc_coherent, .free_coherent = dma_direct_free_coherent, .map_sg = dma_direct_map_sg, .unmap_sg = dma_direct_unmap_sg, .dma_supported = dma_direct_dma_supported, .map_page = dma_direct_map_page, .unmap_page = dma_direct_unmap_page, #ifdef CONFIG_NOT_COHERENT_CACHE .sync_single_for_cpu = dma_direct_sync_single, .sync_single_for_device = dma_direct_sync_single, .sync_sg_for_cpu = dma_direct_sync_sg, .sync_sg_for_device = dma_direct_sync_sg, #endif }; EXPORT_SYMBOL(dma_direct_ops); #define PREALLOC_DMA_DEBUG_ENTRIES (1 << 16) int dma_set_mask(struct device *dev, u64 dma_mask) { struct dma_map_ops *dma_ops = get_dma_ops(dev); if (ppc_md.dma_set_mask) return ppc_md.dma_set_mask(dev, dma_mask); if (unlikely(dma_ops == NULL)) return -EIO; if (dma_ops->set_dma_mask != NULL) return dma_ops->set_dma_mask(dev, dma_mask); if (!dev->dma_mask || !dma_supported(dev, dma_mask)) return -EIO; *dev->dma_mask = dma_mask; return 0; } EXPORT_SYMBOL(dma_set_mask); static int __init dma_init(void) { dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES); return 0; } fs_initcall(dma_init); int dma_mmap_coherent(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t handle, size_t size) { unsigned long pfn; #ifdef CONFIG_NOT_COHERENT_CACHE vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pfn = __dma_get_coherent_pfn((unsigned long)cpu_addr); #else pfn = page_to_pfn(virt_to_page(cpu_addr)); #endif return remap_pfn_range(vma, vma->vm_start, pfn + vma->vm_pgoff, vma->vm_end - vma->vm_start, vma->vm_page_prot); } EXPORT_SYMBOL_GPL(dma_mmap_coherent);
gpl-2.0
zymphad/leanKernel-angler
arch/powerpc/platforms/chrp/smp.c
2327
1190
/* * Smp support for CHRP machines. * * Written by Cort Dougan (cort@cs.nmt.edu) borrowing a great * deal of code from the sparc and intel versions. * * Copyright (C) 1999 Cort Dougan <cort@cs.nmt.edu> * */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/interrupt.h> #include <linux/kernel_stat.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/spinlock.h> #include <asm/ptrace.h> #include <linux/atomic.h> #include <asm/irq.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/sections.h> #include <asm/io.h> #include <asm/prom.h> #include <asm/smp.h> #include <asm/machdep.h> #include <asm/mpic.h> #include <asm/rtas.h> static int smp_chrp_kick_cpu(int nr) { *(unsigned long *)KERNELBASE = nr; asm volatile("dcbf 0,%0"::"r"(KERNELBASE):"memory"); return 0; } static void smp_chrp_setup_cpu(int cpu_nr) { mpic_setup_this_cpu(); } /* CHRP with openpic */ struct smp_ops_t chrp_smp_ops = { .message_pass = smp_mpic_message_pass, .probe = smp_mpic_probe, .kick_cpu = smp_chrp_kick_cpu, .setup_cpu = smp_chrp_setup_cpu, .give_timebase = rtas_give_timebase, .take_timebase = rtas_take_timebase, };
gpl-2.0
adeen-s/android_kernel_cyanogen_msm8916
drivers/net/wireless/brcm80211/brcmsmac/channel.c
2327
21373
/* * Copyright (c) 2010 Broadcom Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <linux/types.h> #include <net/cfg80211.h> #include <net/mac80211.h> #include <net/regulatory.h> #include <defs.h> #include "pub.h" #include "phy/phy_hal.h" #include "main.h" #include "stf.h" #include "channel.h" #include "mac80211_if.h" #include "debug.h" /* QDB() macro takes a dB value and converts to a quarter dB value */ #define QDB(n) ((n) * BRCMS_TXPWR_DB_FACTOR) #define LOCALE_MIMO_IDX_bn 0 #define LOCALE_MIMO_IDX_11n 0 /* max of BAND_5G_PWR_LVLS and 14 for 2.4 GHz */ #define BRCMS_MAXPWR_MIMO_TBL_SIZE 14 /* maxpwr mapping to 5GHz band channels: * maxpwr[0] - channels [34-48] * maxpwr[1] - channels [52-60] * maxpwr[2] - channels [62-64] * maxpwr[3] - channels [100-140] * maxpwr[4] - channels [149-165] */ #define BAND_5G_PWR_LVLS 5 /* 5 power levels for 5G */ #define LC(id) LOCALE_MIMO_IDX_ ## id #define LOCALES(mimo2, mimo5) \ {LC(mimo2), LC(mimo5)} /* macro to get 5 GHz channel group index for tx power */ #define CHANNEL_POWER_IDX_5G(c) (((c) < 52) ? 0 : \ (((c) < 62) ? 1 : \ (((c) < 100) ? 2 : \ (((c) < 149) ? 3 : 4)))) #define BRCM_2GHZ_2412_2462 REG_RULE(2412-10, 2462+10, 40, 0, 19, 0) #define BRCM_2GHZ_2467_2472 REG_RULE(2467-10, 2472+10, 20, 0, 19, \ NL80211_RRF_PASSIVE_SCAN | \ NL80211_RRF_NO_IBSS) #define BRCM_5GHZ_5180_5240 REG_RULE(5180-10, 5240+10, 40, 0, 21, \ NL80211_RRF_PASSIVE_SCAN | \ NL80211_RRF_NO_IBSS) #define BRCM_5GHZ_5260_5320 REG_RULE(5260-10, 5320+10, 40, 0, 21, \ NL80211_RRF_PASSIVE_SCAN | \ NL80211_RRF_DFS | \ NL80211_RRF_NO_IBSS) #define BRCM_5GHZ_5500_5700 REG_RULE(5500-10, 5700+10, 40, 0, 21, \ NL80211_RRF_PASSIVE_SCAN | \ NL80211_RRF_DFS | \ NL80211_RRF_NO_IBSS) #define BRCM_5GHZ_5745_5825 REG_RULE(5745-10, 5825+10, 40, 0, 21, \ NL80211_RRF_PASSIVE_SCAN | \ NL80211_RRF_NO_IBSS) static const struct ieee80211_regdomain brcms_regdom_x2 = { .n_reg_rules = 6, .alpha2 = "X2", .reg_rules = { BRCM_2GHZ_2412_2462, BRCM_2GHZ_2467_2472, BRCM_5GHZ_5180_5240, BRCM_5GHZ_5260_5320, BRCM_5GHZ_5500_5700, BRCM_5GHZ_5745_5825, } }; /* locale per-channel tx power limits for MIMO frames * maxpwr arrays are index by channel for 2.4 GHz limits, and * by sub-band for 5 GHz limits using CHANNEL_POWER_IDX_5G(channel) */ struct locale_mimo_info { /* tx 20 MHz power limits, qdBm units */ s8 maxpwr20[BRCMS_MAXPWR_MIMO_TBL_SIZE]; /* tx 40 MHz power limits, qdBm units */ s8 maxpwr40[BRCMS_MAXPWR_MIMO_TBL_SIZE]; }; /* Country names and abbreviations with locale defined from ISO 3166 */ struct country_info { const u8 locale_mimo_2G; /* 2.4G mimo info */ const u8 locale_mimo_5G; /* 5G mimo info */ }; struct brcms_regd { struct country_info country; const struct ieee80211_regdomain *regdomain; }; struct brcms_cm_info { struct brcms_pub *pub; struct brcms_c_info *wlc; const struct brcms_regd *world_regd; }; /* * MIMO Locale Definitions - 2.4 GHz */ static const struct locale_mimo_info locale_bn = { {QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13)}, {0, 0, QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), QDB(13), 0, 0}, }; static const struct locale_mimo_info *g_mimo_2g_table[] = { &locale_bn }; /* * MIMO Locale Definitions - 5 GHz */ static const struct locale_mimo_info locale_11n = { { /* 12.5 dBm */ 50, 50, 50, QDB(15), QDB(15)}, {QDB(14), QDB(15), QDB(15), QDB(15), QDB(15)}, }; static const struct locale_mimo_info *g_mimo_5g_table[] = { &locale_11n }; static const struct brcms_regd cntry_locales[] = { /* Worldwide RoW 2, must always be at index 0 */ { .country = LOCALES(bn, 11n), .regdomain = &brcms_regdom_x2, }, }; static const struct locale_mimo_info *brcms_c_get_mimo_2g(u8 locale_idx) { if (locale_idx >= ARRAY_SIZE(g_mimo_2g_table)) return NULL; return g_mimo_2g_table[locale_idx]; } static const struct locale_mimo_info *brcms_c_get_mimo_5g(u8 locale_idx) { if (locale_idx >= ARRAY_SIZE(g_mimo_5g_table)) return NULL; return g_mimo_5g_table[locale_idx]; } /* * Indicates whether the country provided is valid to pass * to cfg80211 or not. * * returns true if valid; false if not. */ static bool brcms_c_country_valid(const char *ccode) { /* * only allow ascii alpha uppercase for the first 2 * chars. */ if (!((0x80 & ccode[0]) == 0 && ccode[0] >= 0x41 && ccode[0] <= 0x5A && (0x80 & ccode[1]) == 0 && ccode[1] >= 0x41 && ccode[1] <= 0x5A)) return false; /* * do not match ISO 3166-1 user assigned country codes * that may be in the driver table */ if (!strcmp("AA", ccode) || /* AA */ !strcmp("ZZ", ccode) || /* ZZ */ ccode[0] == 'X' || /* XA - XZ */ (ccode[0] == 'Q' && /* QM - QZ */ (ccode[1] >= 'M' && ccode[1] <= 'Z'))) return false; if (!strcmp("NA", ccode)) return false; return true; } static const struct brcms_regd *brcms_world_regd(const char *regdom, int len) { const struct brcms_regd *regd = NULL; int i; for (i = 0; i < ARRAY_SIZE(cntry_locales); i++) { if (!strncmp(regdom, cntry_locales[i].regdomain->alpha2, len)) { regd = &cntry_locales[i]; break; } } return regd; } static const struct brcms_regd *brcms_default_world_regd(void) { return &cntry_locales[0]; } /* JP, J1 - J10 are Japan ccodes */ static bool brcms_c_japan_ccode(const char *ccode) { return (ccode[0] == 'J' && (ccode[1] == 'P' || (ccode[1] >= '1' && ccode[1] <= '9'))); } static void brcms_c_channel_min_txpower_limits_with_local_constraint( struct brcms_cm_info *wlc_cm, struct txpwr_limits *txpwr, u8 local_constraint_qdbm) { int j; /* CCK Rates */ for (j = 0; j < WL_TX_POWER_CCK_NUM; j++) txpwr->cck[j] = min(txpwr->cck[j], local_constraint_qdbm); /* 20 MHz Legacy OFDM SISO */ for (j = 0; j < WL_TX_POWER_OFDM_NUM; j++) txpwr->ofdm[j] = min(txpwr->ofdm[j], local_constraint_qdbm); /* 20 MHz Legacy OFDM CDD */ for (j = 0; j < BRCMS_NUM_RATES_OFDM; j++) txpwr->ofdm_cdd[j] = min(txpwr->ofdm_cdd[j], local_constraint_qdbm); /* 40 MHz Legacy OFDM SISO */ for (j = 0; j < BRCMS_NUM_RATES_OFDM; j++) txpwr->ofdm_40_siso[j] = min(txpwr->ofdm_40_siso[j], local_constraint_qdbm); /* 40 MHz Legacy OFDM CDD */ for (j = 0; j < BRCMS_NUM_RATES_OFDM; j++) txpwr->ofdm_40_cdd[j] = min(txpwr->ofdm_40_cdd[j], local_constraint_qdbm); /* 20MHz MCS 0-7 SISO */ for (j = 0; j < BRCMS_NUM_RATES_MCS_1_STREAM; j++) txpwr->mcs_20_siso[j] = min(txpwr->mcs_20_siso[j], local_constraint_qdbm); /* 20MHz MCS 0-7 CDD */ for (j = 0; j < BRCMS_NUM_RATES_MCS_1_STREAM; j++) txpwr->mcs_20_cdd[j] = min(txpwr->mcs_20_cdd[j], local_constraint_qdbm); /* 20MHz MCS 0-7 STBC */ for (j = 0; j < BRCMS_NUM_RATES_MCS_1_STREAM; j++) txpwr->mcs_20_stbc[j] = min(txpwr->mcs_20_stbc[j], local_constraint_qdbm); /* 20MHz MCS 8-15 MIMO */ for (j = 0; j < BRCMS_NUM_RATES_MCS_2_STREAM; j++) txpwr->mcs_20_mimo[j] = min(txpwr->mcs_20_mimo[j], local_constraint_qdbm); /* 40MHz MCS 0-7 SISO */ for (j = 0; j < BRCMS_NUM_RATES_MCS_1_STREAM; j++) txpwr->mcs_40_siso[j] = min(txpwr->mcs_40_siso[j], local_constraint_qdbm); /* 40MHz MCS 0-7 CDD */ for (j = 0; j < BRCMS_NUM_RATES_MCS_1_STREAM; j++) txpwr->mcs_40_cdd[j] = min(txpwr->mcs_40_cdd[j], local_constraint_qdbm); /* 40MHz MCS 0-7 STBC */ for (j = 0; j < BRCMS_NUM_RATES_MCS_1_STREAM; j++) txpwr->mcs_40_stbc[j] = min(txpwr->mcs_40_stbc[j], local_constraint_qdbm); /* 40MHz MCS 8-15 MIMO */ for (j = 0; j < BRCMS_NUM_RATES_MCS_2_STREAM; j++) txpwr->mcs_40_mimo[j] = min(txpwr->mcs_40_mimo[j], local_constraint_qdbm); /* 40MHz MCS 32 */ txpwr->mcs32 = min(txpwr->mcs32, local_constraint_qdbm); } /* * set the driver's current country and regulatory information * using a country code as the source. Look up built in country * information found with the country code. */ static void brcms_c_set_country(struct brcms_cm_info *wlc_cm, const struct brcms_regd *regd) { struct brcms_c_info *wlc = wlc_cm->wlc; if ((wlc->pub->_n_enab & SUPPORT_11N) != wlc->protection->nmode_user) brcms_c_set_nmode(wlc); brcms_c_stf_ss_update(wlc, wlc->bandstate[BAND_2G_INDEX]); brcms_c_stf_ss_update(wlc, wlc->bandstate[BAND_5G_INDEX]); brcms_c_set_gmode(wlc, wlc->protection->gmode_user, false); return; } struct brcms_cm_info *brcms_c_channel_mgr_attach(struct brcms_c_info *wlc) { struct brcms_cm_info *wlc_cm; struct brcms_pub *pub = wlc->pub; struct ssb_sprom *sprom = &wlc->hw->d11core->bus->sprom; const char *ccode = sprom->alpha2; int ccode_len = sizeof(sprom->alpha2); wlc_cm = kzalloc(sizeof(struct brcms_cm_info), GFP_ATOMIC); if (wlc_cm == NULL) return NULL; wlc_cm->pub = pub; wlc_cm->wlc = wlc; wlc->cmi = wlc_cm; /* store the country code for passing up as a regulatory hint */ wlc_cm->world_regd = brcms_world_regd(ccode, ccode_len); if (brcms_c_country_valid(ccode)) strncpy(wlc->pub->srom_ccode, ccode, ccode_len); /* * If no custom world domain is found in the SROM, use the * default "X2" domain. */ if (!wlc_cm->world_regd) { wlc_cm->world_regd = brcms_default_world_regd(); ccode = wlc_cm->world_regd->regdomain->alpha2; ccode_len = BRCM_CNTRY_BUF_SZ - 1; } /* save default country for exiting 11d regulatory mode */ strncpy(wlc->country_default, ccode, ccode_len); /* initialize autocountry_default to driver default */ strncpy(wlc->autocountry_default, ccode, ccode_len); brcms_c_set_country(wlc_cm, wlc_cm->world_regd); return wlc_cm; } void brcms_c_channel_mgr_detach(struct brcms_cm_info *wlc_cm) { kfree(wlc_cm); } void brcms_c_channel_set_chanspec(struct brcms_cm_info *wlc_cm, u16 chanspec, u8 local_constraint_qdbm) { struct brcms_c_info *wlc = wlc_cm->wlc; struct ieee80211_channel *ch = wlc->pub->ieee_hw->conf.chandef.chan; struct txpwr_limits txpwr; brcms_c_channel_reg_limits(wlc_cm, chanspec, &txpwr); brcms_c_channel_min_txpower_limits_with_local_constraint( wlc_cm, &txpwr, local_constraint_qdbm ); /* set or restore gmode as required by regulatory */ if (ch->flags & IEEE80211_CHAN_NO_OFDM) brcms_c_set_gmode(wlc, GMODE_LEGACY_B, false); else brcms_c_set_gmode(wlc, wlc->protection->gmode_user, false); brcms_b_set_chanspec(wlc->hw, chanspec, !!(ch->flags & IEEE80211_CHAN_PASSIVE_SCAN), &txpwr); } void brcms_c_channel_reg_limits(struct brcms_cm_info *wlc_cm, u16 chanspec, struct txpwr_limits *txpwr) { struct brcms_c_info *wlc = wlc_cm->wlc; struct ieee80211_channel *ch = wlc->pub->ieee_hw->conf.chandef.chan; uint i; uint chan; int maxpwr; int delta; const struct country_info *country; struct brcms_band *band; int conducted_max = BRCMS_TXPWR_MAX; const struct locale_mimo_info *li_mimo; int maxpwr20, maxpwr40; int maxpwr_idx; uint j; memset(txpwr, 0, sizeof(struct txpwr_limits)); if (WARN_ON(!ch)) return; country = &wlc_cm->world_regd->country; chan = CHSPEC_CHANNEL(chanspec); band = wlc->bandstate[chspec_bandunit(chanspec)]; li_mimo = (band->bandtype == BRCM_BAND_5G) ? brcms_c_get_mimo_5g(country->locale_mimo_5G) : brcms_c_get_mimo_2g(country->locale_mimo_2G); delta = band->antgain; if (band->bandtype == BRCM_BAND_2G) conducted_max = QDB(22); maxpwr = QDB(ch->max_power) - delta; maxpwr = max(maxpwr, 0); maxpwr = min(maxpwr, conducted_max); /* CCK txpwr limits for 2.4G band */ if (band->bandtype == BRCM_BAND_2G) { for (i = 0; i < BRCMS_NUM_RATES_CCK; i++) txpwr->cck[i] = (u8) maxpwr; } for (i = 0; i < BRCMS_NUM_RATES_OFDM; i++) { txpwr->ofdm[i] = (u8) maxpwr; /* * OFDM 40 MHz SISO has the same power as the corresponding * MCS0-7 rate unless overriden by the locale specific code. * We set this value to 0 as a flag (presumably 0 dBm isn't * a possibility) and then copy the MCS0-7 value to the 40 MHz * value if it wasn't explicitly set. */ txpwr->ofdm_40_siso[i] = 0; txpwr->ofdm_cdd[i] = (u8) maxpwr; txpwr->ofdm_40_cdd[i] = 0; } delta = 0; if (band->antgain > QDB(6)) delta = band->antgain - QDB(6); /* Excess over 6 dB */ if (band->bandtype == BRCM_BAND_2G) maxpwr_idx = (chan - 1); else maxpwr_idx = CHANNEL_POWER_IDX_5G(chan); maxpwr20 = li_mimo->maxpwr20[maxpwr_idx]; maxpwr40 = li_mimo->maxpwr40[maxpwr_idx]; maxpwr20 = maxpwr20 - delta; maxpwr20 = max(maxpwr20, 0); maxpwr40 = maxpwr40 - delta; maxpwr40 = max(maxpwr40, 0); /* Fill in the MCS 0-7 (SISO) rates */ for (i = 0; i < BRCMS_NUM_RATES_MCS_1_STREAM; i++) { /* * 20 MHz has the same power as the corresponding OFDM rate * unless overriden by the locale specific code. */ txpwr->mcs_20_siso[i] = txpwr->ofdm[i]; txpwr->mcs_40_siso[i] = 0; } /* Fill in the MCS 0-7 CDD rates */ for (i = 0; i < BRCMS_NUM_RATES_MCS_1_STREAM; i++) { txpwr->mcs_20_cdd[i] = (u8) maxpwr20; txpwr->mcs_40_cdd[i] = (u8) maxpwr40; } /* * These locales have SISO expressed in the * table and override CDD later */ if (li_mimo == &locale_bn) { if (li_mimo == &locale_bn) { maxpwr20 = QDB(16); maxpwr40 = 0; if (chan >= 3 && chan <= 11) maxpwr40 = QDB(16); } for (i = 0; i < BRCMS_NUM_RATES_MCS_1_STREAM; i++) { txpwr->mcs_20_siso[i] = (u8) maxpwr20; txpwr->mcs_40_siso[i] = (u8) maxpwr40; } } /* Fill in the MCS 0-7 STBC rates */ for (i = 0; i < BRCMS_NUM_RATES_MCS_1_STREAM; i++) { txpwr->mcs_20_stbc[i] = 0; txpwr->mcs_40_stbc[i] = 0; } /* Fill in the MCS 8-15 SDM rates */ for (i = 0; i < BRCMS_NUM_RATES_MCS_2_STREAM; i++) { txpwr->mcs_20_mimo[i] = (u8) maxpwr20; txpwr->mcs_40_mimo[i] = (u8) maxpwr40; } /* Fill in MCS32 */ txpwr->mcs32 = (u8) maxpwr40; for (i = 0, j = 0; i < BRCMS_NUM_RATES_OFDM; i++, j++) { if (txpwr->ofdm_40_cdd[i] == 0) txpwr->ofdm_40_cdd[i] = txpwr->mcs_40_cdd[j]; if (i == 0) { i = i + 1; if (txpwr->ofdm_40_cdd[i] == 0) txpwr->ofdm_40_cdd[i] = txpwr->mcs_40_cdd[j]; } } /* * Copy the 40 MHZ MCS 0-7 CDD value to the 40 MHZ MCS 0-7 SISO * value if it wasn't provided explicitly. */ for (i = 0; i < BRCMS_NUM_RATES_MCS_1_STREAM; i++) { if (txpwr->mcs_40_siso[i] == 0) txpwr->mcs_40_siso[i] = txpwr->mcs_40_cdd[i]; } for (i = 0, j = 0; i < BRCMS_NUM_RATES_OFDM; i++, j++) { if (txpwr->ofdm_40_siso[i] == 0) txpwr->ofdm_40_siso[i] = txpwr->mcs_40_siso[j]; if (i == 0) { i = i + 1; if (txpwr->ofdm_40_siso[i] == 0) txpwr->ofdm_40_siso[i] = txpwr->mcs_40_siso[j]; } } /* * Copy the 20 and 40 MHz MCS0-7 CDD values to the corresponding * STBC values if they weren't provided explicitly. */ for (i = 0; i < BRCMS_NUM_RATES_MCS_1_STREAM; i++) { if (txpwr->mcs_20_stbc[i] == 0) txpwr->mcs_20_stbc[i] = txpwr->mcs_20_cdd[i]; if (txpwr->mcs_40_stbc[i] == 0) txpwr->mcs_40_stbc[i] = txpwr->mcs_40_cdd[i]; } return; } /* * Verify the chanspec is using a legal set of parameters, i.e. that the * chanspec specified a band, bw, ctl_sb and channel and that the * combination could be legal given any set of circumstances. * RETURNS: true is the chanspec is malformed, false if it looks good. */ static bool brcms_c_chspec_malformed(u16 chanspec) { /* must be 2G or 5G band */ if (!CHSPEC_IS5G(chanspec) && !CHSPEC_IS2G(chanspec)) return true; /* must be 20 or 40 bandwidth */ if (!CHSPEC_IS40(chanspec) && !CHSPEC_IS20(chanspec)) return true; /* 20MHZ b/w must have no ctl sb, 40 must have a ctl sb */ if (CHSPEC_IS20(chanspec)) { if (!CHSPEC_SB_NONE(chanspec)) return true; } else if (!CHSPEC_SB_UPPER(chanspec) && !CHSPEC_SB_LOWER(chanspec)) { return true; } return false; } /* * Validate the chanspec for this locale, for 40MHZ we need to also * check that the sidebands are valid 20MZH channels in this locale * and they are also a legal HT combination */ static bool brcms_c_valid_chanspec_ext(struct brcms_cm_info *wlc_cm, u16 chspec) { struct brcms_c_info *wlc = wlc_cm->wlc; u8 channel = CHSPEC_CHANNEL(chspec); /* check the chanspec */ if (brcms_c_chspec_malformed(chspec)) { brcms_err(wlc->hw->d11core, "wl%d: malformed chanspec 0x%x\n", wlc->pub->unit, chspec); return false; } if (CHANNEL_BANDUNIT(wlc_cm->wlc, channel) != chspec_bandunit(chspec)) return false; return true; } bool brcms_c_valid_chanspec_db(struct brcms_cm_info *wlc_cm, u16 chspec) { return brcms_c_valid_chanspec_ext(wlc_cm, chspec); } static bool brcms_is_radar_freq(u16 center_freq) { return center_freq >= 5260 && center_freq <= 5700; } static void brcms_reg_apply_radar_flags(struct wiphy *wiphy) { struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; int i; sband = wiphy->bands[IEEE80211_BAND_5GHZ]; if (!sband) return; for (i = 0; i < sband->n_channels; i++) { ch = &sband->channels[i]; if (!brcms_is_radar_freq(ch->center_freq)) continue; /* * All channels in this range should be passive and have * DFS enabled. */ if (!(ch->flags & IEEE80211_CHAN_DISABLED)) ch->flags |= IEEE80211_CHAN_RADAR | IEEE80211_CHAN_NO_IBSS | IEEE80211_CHAN_PASSIVE_SCAN; } } static void brcms_reg_apply_beaconing_flags(struct wiphy *wiphy, enum nl80211_reg_initiator initiator) { struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; const struct ieee80211_reg_rule *rule; int band, i; for (band = 0; band < IEEE80211_NUM_BANDS; band++) { sband = wiphy->bands[band]; if (!sband) continue; for (i = 0; i < sband->n_channels; i++) { ch = &sband->channels[i]; if (ch->flags & (IEEE80211_CHAN_DISABLED | IEEE80211_CHAN_RADAR)) continue; if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) { rule = freq_reg_info(wiphy, ch->center_freq); if (IS_ERR(rule)) continue; if (!(rule->flags & NL80211_RRF_NO_IBSS)) ch->flags &= ~IEEE80211_CHAN_NO_IBSS; if (!(rule->flags & NL80211_RRF_PASSIVE_SCAN)) ch->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN; } else if (ch->beacon_found) { ch->flags &= ~(IEEE80211_CHAN_NO_IBSS | IEEE80211_CHAN_PASSIVE_SCAN); } } } } static void brcms_reg_notifier(struct wiphy *wiphy, struct regulatory_request *request) { struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy); struct brcms_info *wl = hw->priv; struct brcms_c_info *wlc = wl->wlc; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; int band, i; bool ch_found = false; brcms_reg_apply_radar_flags(wiphy); if (request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE) brcms_reg_apply_beaconing_flags(wiphy, request->initiator); /* Disable radio if all channels disallowed by regulatory */ for (band = 0; !ch_found && band < IEEE80211_NUM_BANDS; band++) { sband = wiphy->bands[band]; if (!sband) continue; for (i = 0; !ch_found && i < sband->n_channels; i++) { ch = &sband->channels[i]; if (!(ch->flags & IEEE80211_CHAN_DISABLED)) ch_found = true; } } if (ch_found) { mboolclr(wlc->pub->radio_disabled, WL_RADIO_COUNTRY_DISABLE); } else { mboolset(wlc->pub->radio_disabled, WL_RADIO_COUNTRY_DISABLE); brcms_err(wlc->hw->d11core, "wl%d: %s: no valid channel for \"%s\"\n", wlc->pub->unit, __func__, request->alpha2); } if (wlc->pub->_nbands > 1 || wlc->band->bandtype == BRCM_BAND_2G) wlc_phy_chanspec_ch14_widefilter_set(wlc->band->pi, brcms_c_japan_ccode(request->alpha2)); } void brcms_c_regd_init(struct brcms_c_info *wlc) { struct wiphy *wiphy = wlc->wiphy; const struct brcms_regd *regd = wlc->cmi->world_regd; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; struct brcms_chanvec sup_chan; struct brcms_band *band; int band_idx, i; /* Disable any channels not supported by the phy */ for (band_idx = 0; band_idx < wlc->pub->_nbands; band_idx++) { band = wlc->bandstate[band_idx]; wlc_phy_chanspec_band_validch(band->pi, band->bandtype, &sup_chan); if (band_idx == BAND_2G_INDEX) sband = wiphy->bands[IEEE80211_BAND_2GHZ]; else sband = wiphy->bands[IEEE80211_BAND_5GHZ]; for (i = 0; i < sband->n_channels; i++) { ch = &sband->channels[i]; if (!isset(sup_chan.vec, ch->hw_value)) ch->flags |= IEEE80211_CHAN_DISABLED; } } wlc->wiphy->reg_notifier = brcms_reg_notifier; wlc->wiphy->flags |= WIPHY_FLAG_CUSTOM_REGULATORY | WIPHY_FLAG_STRICT_REGULATORY; wiphy_apply_custom_regulatory(wlc->wiphy, regd->regdomain); brcms_reg_apply_beaconing_flags(wiphy, NL80211_REGDOM_SET_BY_DRIVER); }
gpl-2.0
dimfishr/android_kernel_lge_bullhead
arch/x86/kernel/machine_kexec_64.c
2327
6793
/* * handle transition of Linux booting another kernel * Copyright (C) 2002-2005 Eric Biederman <ebiederm@xmission.com> * * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. */ #include <linux/mm.h> #include <linux/kexec.h> #include <linux/string.h> #include <linux/gfp.h> #include <linux/reboot.h> #include <linux/numa.h> #include <linux/ftrace.h> #include <linux/io.h> #include <linux/suspend.h> #include <asm/init.h> #include <asm/pgtable.h> #include <asm/tlbflush.h> #include <asm/mmu_context.h> #include <asm/debugreg.h> static void free_transition_pgtable(struct kimage *image) { free_page((unsigned long)image->arch.pud); free_page((unsigned long)image->arch.pmd); free_page((unsigned long)image->arch.pte); } static int init_transition_pgtable(struct kimage *image, pgd_t *pgd) { pud_t *pud; pmd_t *pmd; pte_t *pte; unsigned long vaddr, paddr; int result = -ENOMEM; vaddr = (unsigned long)relocate_kernel; paddr = __pa(page_address(image->control_code_page)+PAGE_SIZE); pgd += pgd_index(vaddr); if (!pgd_present(*pgd)) { pud = (pud_t *)get_zeroed_page(GFP_KERNEL); if (!pud) goto err; image->arch.pud = pud; set_pgd(pgd, __pgd(__pa(pud) | _KERNPG_TABLE)); } pud = pud_offset(pgd, vaddr); if (!pud_present(*pud)) { pmd = (pmd_t *)get_zeroed_page(GFP_KERNEL); if (!pmd) goto err; image->arch.pmd = pmd; set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE)); } pmd = pmd_offset(pud, vaddr); if (!pmd_present(*pmd)) { pte = (pte_t *)get_zeroed_page(GFP_KERNEL); if (!pte) goto err; image->arch.pte = pte; set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE)); } pte = pte_offset_kernel(pmd, vaddr); set_pte(pte, pfn_pte(paddr >> PAGE_SHIFT, PAGE_KERNEL_EXEC)); return 0; err: free_transition_pgtable(image); return result; } static void *alloc_pgt_page(void *data) { struct kimage *image = (struct kimage *)data; struct page *page; void *p = NULL; page = kimage_alloc_control_pages(image, 0); if (page) { p = page_address(page); clear_page(p); } return p; } static int init_pgtable(struct kimage *image, unsigned long start_pgtable) { struct x86_mapping_info info = { .alloc_pgt_page = alloc_pgt_page, .context = image, .pmd_flag = __PAGE_KERNEL_LARGE_EXEC, }; unsigned long mstart, mend; pgd_t *level4p; int result; int i; level4p = (pgd_t *)__va(start_pgtable); clear_page(level4p); for (i = 0; i < nr_pfn_mapped; i++) { mstart = pfn_mapped[i].start << PAGE_SHIFT; mend = pfn_mapped[i].end << PAGE_SHIFT; result = kernel_ident_mapping_init(&info, level4p, mstart, mend); if (result) return result; } /* * segments's mem ranges could be outside 0 ~ max_pfn, * for example when jump back to original kernel from kexeced kernel. * or first kernel is booted with user mem map, and second kernel * could be loaded out of that range. */ for (i = 0; i < image->nr_segments; i++) { mstart = image->segment[i].mem; mend = mstart + image->segment[i].memsz; result = kernel_ident_mapping_init(&info, level4p, mstart, mend); if (result) return result; } return init_transition_pgtable(image, level4p); } static void set_idt(void *newidt, u16 limit) { struct desc_ptr curidt; /* x86-64 supports unaliged loads & stores */ curidt.size = limit; curidt.address = (unsigned long)newidt; __asm__ __volatile__ ( "lidtq %0\n" : : "m" (curidt) ); }; static void set_gdt(void *newgdt, u16 limit) { struct desc_ptr curgdt; /* x86-64 supports unaligned loads & stores */ curgdt.size = limit; curgdt.address = (unsigned long)newgdt; __asm__ __volatile__ ( "lgdtq %0\n" : : "m" (curgdt) ); }; static void load_segments(void) { __asm__ __volatile__ ( "\tmovl %0,%%ds\n" "\tmovl %0,%%es\n" "\tmovl %0,%%ss\n" "\tmovl %0,%%fs\n" "\tmovl %0,%%gs\n" : : "a" (__KERNEL_DS) : "memory" ); } int machine_kexec_prepare(struct kimage *image) { unsigned long start_pgtable; int result; /* Calculate the offsets */ start_pgtable = page_to_pfn(image->control_code_page) << PAGE_SHIFT; /* Setup the identity mapped 64bit page table */ result = init_pgtable(image, start_pgtable); if (result) return result; return 0; } void machine_kexec_cleanup(struct kimage *image) { free_transition_pgtable(image); } /* * Do not allocate memory (or fail in any way) in machine_kexec(). * We are past the point of no return, committed to rebooting now. */ void machine_kexec(struct kimage *image) { unsigned long page_list[PAGES_NR]; void *control_page; int save_ftrace_enabled; #ifdef CONFIG_KEXEC_JUMP if (image->preserve_context) save_processor_state(); #endif save_ftrace_enabled = __ftrace_enabled_save(); /* Interrupts aren't acceptable while we reboot */ local_irq_disable(); hw_breakpoint_disable(); if (image->preserve_context) { #ifdef CONFIG_X86_IO_APIC /* * We need to put APICs in legacy mode so that we can * get timer interrupts in second kernel. kexec/kdump * paths already have calls to disable_IO_APIC() in * one form or other. kexec jump path also need * one. */ disable_IO_APIC(); #endif } control_page = page_address(image->control_code_page) + PAGE_SIZE; memcpy(control_page, relocate_kernel, KEXEC_CONTROL_CODE_MAX_SIZE); page_list[PA_CONTROL_PAGE] = virt_to_phys(control_page); page_list[VA_CONTROL_PAGE] = (unsigned long)control_page; page_list[PA_TABLE_PAGE] = (unsigned long)__pa(page_address(image->control_code_page)); if (image->type == KEXEC_TYPE_DEFAULT) page_list[PA_SWAP_PAGE] = (page_to_pfn(image->swap_page) << PAGE_SHIFT); /* * The segment registers are funny things, they have both a * visible and an invisible part. Whenever the visible part is * set to a specific selector, the invisible part is loaded * with from a table in memory. At no other time is the * descriptor table in memory accessed. * * I take advantage of this here by force loading the * segments, before I zap the gdt with an invalid value. */ load_segments(); /* * The gdt & idt are now invalid. * If you want to load them you must set up your own idt & gdt. */ set_gdt(phys_to_virt(0), 0); set_idt(phys_to_virt(0), 0); /* now call it */ image->start = relocate_kernel((unsigned long)image->head, (unsigned long)page_list, image->start, image->preserve_context); #ifdef CONFIG_KEXEC_JUMP if (image->preserve_context) restore_processor_state(); #endif __ftrace_enabled_restore(save_ftrace_enabled); } void arch_crash_save_vmcoreinfo(void) { VMCOREINFO_SYMBOL(phys_base); VMCOREINFO_SYMBOL(init_level4_pgt); #ifdef CONFIG_NUMA VMCOREINFO_SYMBOL(node_data); VMCOREINFO_LENGTH(node_data, MAX_NUMNODES); #endif }
gpl-2.0
evnit/android_kernel_samsung_msm8660-common-10.2
drivers/media/rc/keymaps/rc-proteus-2309.c
3095
1853
/* proteus-2309.h - Keytable for proteus_2309 Remote Controller * * keymap imported from ir-keymaps.c * * Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <media/rc-map.h> /* Michal Majchrowicz <mmajchrowicz@gmail.com> */ static struct rc_map_table proteus_2309[] = { /* numeric */ { 0x00, KEY_0 }, { 0x01, KEY_1 }, { 0x02, KEY_2 }, { 0x03, KEY_3 }, { 0x04, KEY_4 }, { 0x05, KEY_5 }, { 0x06, KEY_6 }, { 0x07, KEY_7 }, { 0x08, KEY_8 }, { 0x09, KEY_9 }, { 0x5c, KEY_POWER }, /* power */ { 0x20, KEY_ZOOM }, /* full screen */ { 0x0f, KEY_BACKSPACE }, /* recall */ { 0x1b, KEY_ENTER }, /* mute */ { 0x41, KEY_RECORD }, /* record */ { 0x43, KEY_STOP }, /* stop */ { 0x16, KEY_S }, { 0x1a, KEY_POWER2 }, /* off */ { 0x2e, KEY_RED }, { 0x1f, KEY_CHANNELDOWN }, /* channel - */ { 0x1c, KEY_CHANNELUP }, /* channel + */ { 0x10, KEY_VOLUMEDOWN }, /* volume - */ { 0x1e, KEY_VOLUMEUP }, /* volume + */ { 0x14, KEY_F1 }, }; static struct rc_map_list proteus_2309_map = { .map = { .scan = proteus_2309, .size = ARRAY_SIZE(proteus_2309), .rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */ .name = RC_MAP_PROTEUS_2309, } }; static int __init init_rc_map_proteus_2309(void) { return rc_map_register(&proteus_2309_map); } static void __exit exit_rc_map_proteus_2309(void) { rc_map_unregister(&proteus_2309_map); } module_init(init_rc_map_proteus_2309) module_exit(exit_rc_map_proteus_2309) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
gpl-2.0
DirtyJerz/omap
drivers/media/rc/keymaps/rc-pinnacle-grey.c
3095
1969
/* pinnacle-grey.h - Keytable for pinnacle_grey Remote Controller * * keymap imported from ir-keymaps.c * * Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <media/rc-map.h> static struct rc_map_table pinnacle_grey[] = { { 0x3a, KEY_0 }, { 0x31, KEY_1 }, { 0x32, KEY_2 }, { 0x33, KEY_3 }, { 0x34, KEY_4 }, { 0x35, KEY_5 }, { 0x36, KEY_6 }, { 0x37, KEY_7 }, { 0x38, KEY_8 }, { 0x39, KEY_9 }, { 0x2f, KEY_POWER }, { 0x2e, KEY_P }, { 0x1f, KEY_L }, { 0x2b, KEY_I }, { 0x2d, KEY_SCREEN }, { 0x1e, KEY_ZOOM }, { 0x1b, KEY_VOLUMEUP }, { 0x0f, KEY_VOLUMEDOWN }, { 0x17, KEY_CHANNELUP }, { 0x1c, KEY_CHANNELDOWN }, { 0x25, KEY_INFO }, { 0x3c, KEY_MUTE }, { 0x3d, KEY_LEFT }, { 0x3b, KEY_RIGHT }, { 0x3f, KEY_UP }, { 0x3e, KEY_DOWN }, { 0x1a, KEY_ENTER }, { 0x1d, KEY_MENU }, { 0x19, KEY_AGAIN }, { 0x16, KEY_PREVIOUSSONG }, { 0x13, KEY_NEXTSONG }, { 0x15, KEY_PAUSE }, { 0x0e, KEY_REWIND }, { 0x0d, KEY_PLAY }, { 0x0b, KEY_STOP }, { 0x07, KEY_FORWARD }, { 0x27, KEY_RECORD }, { 0x26, KEY_TUNER }, { 0x29, KEY_TEXT }, { 0x2a, KEY_MEDIA }, { 0x18, KEY_EPG }, }; static struct rc_map_list pinnacle_grey_map = { .map = { .scan = pinnacle_grey, .size = ARRAY_SIZE(pinnacle_grey), .rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */ .name = RC_MAP_PINNACLE_GREY, } }; static int __init init_rc_map_pinnacle_grey(void) { return rc_map_register(&pinnacle_grey_map); } static void __exit exit_rc_map_pinnacle_grey(void) { rc_map_unregister(&pinnacle_grey_map); } module_init(init_rc_map_pinnacle_grey) module_exit(exit_rc_map_pinnacle_grey) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
gpl-2.0
santod/NuK3rn3l_htc_m7_GPE-5.1
drivers/net/wireless/rt2x00/rt2500usb.c
3351
62388
/* Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com> <http://rt2x00.serialmonkey.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. */ /* Module: rt2500usb Abstract: rt2500usb device specific routines. Supported chipsets: RT2570. */ #include <linux/delay.h> #include <linux/etherdevice.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/usb.h> #include "rt2x00.h" #include "rt2x00usb.h" #include "rt2500usb.h" /* * Allow hardware encryption to be disabled. */ static bool modparam_nohwcrypt; module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO); MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption."); /* * Register access. * All access to the CSR registers will go through the methods * rt2500usb_register_read and rt2500usb_register_write. * BBP and RF register require indirect register access, * and use the CSR registers BBPCSR and RFCSR to achieve this. * These indirect registers work with busy bits, * and we will try maximal REGISTER_BUSY_COUNT times to access * the register while taking a REGISTER_BUSY_DELAY us delay * between each attampt. When the busy bit is still set at that time, * the access attempt is considered to have failed, * and we will print an error. * If the csr_mutex is already held then the _lock variants must * be used instead. */ static inline void rt2500usb_register_read(struct rt2x00_dev *rt2x00dev, const unsigned int offset, u16 *value) { __le16 reg; rt2x00usb_vendor_request_buff(rt2x00dev, USB_MULTI_READ, USB_VENDOR_REQUEST_IN, offset, &reg, sizeof(reg), REGISTER_TIMEOUT); *value = le16_to_cpu(reg); } static inline void rt2500usb_register_read_lock(struct rt2x00_dev *rt2x00dev, const unsigned int offset, u16 *value) { __le16 reg; rt2x00usb_vendor_req_buff_lock(rt2x00dev, USB_MULTI_READ, USB_VENDOR_REQUEST_IN, offset, &reg, sizeof(reg), REGISTER_TIMEOUT); *value = le16_to_cpu(reg); } static inline void rt2500usb_register_multiread(struct rt2x00_dev *rt2x00dev, const unsigned int offset, void *value, const u16 length) { rt2x00usb_vendor_request_buff(rt2x00dev, USB_MULTI_READ, USB_VENDOR_REQUEST_IN, offset, value, length, REGISTER_TIMEOUT16(length)); } static inline void rt2500usb_register_write(struct rt2x00_dev *rt2x00dev, const unsigned int offset, u16 value) { __le16 reg = cpu_to_le16(value); rt2x00usb_vendor_request_buff(rt2x00dev, USB_MULTI_WRITE, USB_VENDOR_REQUEST_OUT, offset, &reg, sizeof(reg), REGISTER_TIMEOUT); } static inline void rt2500usb_register_write_lock(struct rt2x00_dev *rt2x00dev, const unsigned int offset, u16 value) { __le16 reg = cpu_to_le16(value); rt2x00usb_vendor_req_buff_lock(rt2x00dev, USB_MULTI_WRITE, USB_VENDOR_REQUEST_OUT, offset, &reg, sizeof(reg), REGISTER_TIMEOUT); } static inline void rt2500usb_register_multiwrite(struct rt2x00_dev *rt2x00dev, const unsigned int offset, void *value, const u16 length) { rt2x00usb_vendor_request_buff(rt2x00dev, USB_MULTI_WRITE, USB_VENDOR_REQUEST_OUT, offset, value, length, REGISTER_TIMEOUT16(length)); } static int rt2500usb_regbusy_read(struct rt2x00_dev *rt2x00dev, const unsigned int offset, struct rt2x00_field16 field, u16 *reg) { unsigned int i; for (i = 0; i < REGISTER_BUSY_COUNT; i++) { rt2500usb_register_read_lock(rt2x00dev, offset, reg); if (!rt2x00_get_field16(*reg, field)) return 1; udelay(REGISTER_BUSY_DELAY); } ERROR(rt2x00dev, "Indirect register access failed: " "offset=0x%.08x, value=0x%.08x\n", offset, *reg); *reg = ~0; return 0; } #define WAIT_FOR_BBP(__dev, __reg) \ rt2500usb_regbusy_read((__dev), PHY_CSR8, PHY_CSR8_BUSY, (__reg)) #define WAIT_FOR_RF(__dev, __reg) \ rt2500usb_regbusy_read((__dev), PHY_CSR10, PHY_CSR10_RF_BUSY, (__reg)) static void rt2500usb_bbp_write(struct rt2x00_dev *rt2x00dev, const unsigned int word, const u8 value) { u16 reg; mutex_lock(&rt2x00dev->csr_mutex); /* * Wait until the BBP becomes available, afterwards we * can safely write the new data into the register. */ if (WAIT_FOR_BBP(rt2x00dev, &reg)) { reg = 0; rt2x00_set_field16(&reg, PHY_CSR7_DATA, value); rt2x00_set_field16(&reg, PHY_CSR7_REG_ID, word); rt2x00_set_field16(&reg, PHY_CSR7_READ_CONTROL, 0); rt2500usb_register_write_lock(rt2x00dev, PHY_CSR7, reg); } mutex_unlock(&rt2x00dev->csr_mutex); } static void rt2500usb_bbp_read(struct rt2x00_dev *rt2x00dev, const unsigned int word, u8 *value) { u16 reg; mutex_lock(&rt2x00dev->csr_mutex); /* * Wait until the BBP becomes available, afterwards we * can safely write the read request into the register. * After the data has been written, we wait until hardware * returns the correct value, if at any time the register * doesn't become available in time, reg will be 0xffffffff * which means we return 0xff to the caller. */ if (WAIT_FOR_BBP(rt2x00dev, &reg)) { reg = 0; rt2x00_set_field16(&reg, PHY_CSR7_REG_ID, word); rt2x00_set_field16(&reg, PHY_CSR7_READ_CONTROL, 1); rt2500usb_register_write_lock(rt2x00dev, PHY_CSR7, reg); if (WAIT_FOR_BBP(rt2x00dev, &reg)) rt2500usb_register_read_lock(rt2x00dev, PHY_CSR7, &reg); } *value = rt2x00_get_field16(reg, PHY_CSR7_DATA); mutex_unlock(&rt2x00dev->csr_mutex); } static void rt2500usb_rf_write(struct rt2x00_dev *rt2x00dev, const unsigned int word, const u32 value) { u16 reg; mutex_lock(&rt2x00dev->csr_mutex); /* * Wait until the RF becomes available, afterwards we * can safely write the new data into the register. */ if (WAIT_FOR_RF(rt2x00dev, &reg)) { reg = 0; rt2x00_set_field16(&reg, PHY_CSR9_RF_VALUE, value); rt2500usb_register_write_lock(rt2x00dev, PHY_CSR9, reg); reg = 0; rt2x00_set_field16(&reg, PHY_CSR10_RF_VALUE, value >> 16); rt2x00_set_field16(&reg, PHY_CSR10_RF_NUMBER_OF_BITS, 20); rt2x00_set_field16(&reg, PHY_CSR10_RF_IF_SELECT, 0); rt2x00_set_field16(&reg, PHY_CSR10_RF_BUSY, 1); rt2500usb_register_write_lock(rt2x00dev, PHY_CSR10, reg); rt2x00_rf_write(rt2x00dev, word, value); } mutex_unlock(&rt2x00dev->csr_mutex); } #ifdef CONFIG_RT2X00_LIB_DEBUGFS static void _rt2500usb_register_read(struct rt2x00_dev *rt2x00dev, const unsigned int offset, u32 *value) { rt2500usb_register_read(rt2x00dev, offset, (u16 *)value); } static void _rt2500usb_register_write(struct rt2x00_dev *rt2x00dev, const unsigned int offset, u32 value) { rt2500usb_register_write(rt2x00dev, offset, value); } static const struct rt2x00debug rt2500usb_rt2x00debug = { .owner = THIS_MODULE, .csr = { .read = _rt2500usb_register_read, .write = _rt2500usb_register_write, .flags = RT2X00DEBUGFS_OFFSET, .word_base = CSR_REG_BASE, .word_size = sizeof(u16), .word_count = CSR_REG_SIZE / sizeof(u16), }, .eeprom = { .read = rt2x00_eeprom_read, .write = rt2x00_eeprom_write, .word_base = EEPROM_BASE, .word_size = sizeof(u16), .word_count = EEPROM_SIZE / sizeof(u16), }, .bbp = { .read = rt2500usb_bbp_read, .write = rt2500usb_bbp_write, .word_base = BBP_BASE, .word_size = sizeof(u8), .word_count = BBP_SIZE / sizeof(u8), }, .rf = { .read = rt2x00_rf_read, .write = rt2500usb_rf_write, .word_base = RF_BASE, .word_size = sizeof(u32), .word_count = RF_SIZE / sizeof(u32), }, }; #endif /* CONFIG_RT2X00_LIB_DEBUGFS */ static int rt2500usb_rfkill_poll(struct rt2x00_dev *rt2x00dev) { u16 reg; rt2500usb_register_read(rt2x00dev, MAC_CSR19, &reg); return rt2x00_get_field32(reg, MAC_CSR19_BIT7); } #ifdef CONFIG_RT2X00_LIB_LEDS static void rt2500usb_brightness_set(struct led_classdev *led_cdev, enum led_brightness brightness) { struct rt2x00_led *led = container_of(led_cdev, struct rt2x00_led, led_dev); unsigned int enabled = brightness != LED_OFF; u16 reg; rt2500usb_register_read(led->rt2x00dev, MAC_CSR20, &reg); if (led->type == LED_TYPE_RADIO || led->type == LED_TYPE_ASSOC) rt2x00_set_field16(&reg, MAC_CSR20_LINK, enabled); else if (led->type == LED_TYPE_ACTIVITY) rt2x00_set_field16(&reg, MAC_CSR20_ACTIVITY, enabled); rt2500usb_register_write(led->rt2x00dev, MAC_CSR20, reg); } static int rt2500usb_blink_set(struct led_classdev *led_cdev, unsigned long *delay_on, unsigned long *delay_off) { struct rt2x00_led *led = container_of(led_cdev, struct rt2x00_led, led_dev); u16 reg; rt2500usb_register_read(led->rt2x00dev, MAC_CSR21, &reg); rt2x00_set_field16(&reg, MAC_CSR21_ON_PERIOD, *delay_on); rt2x00_set_field16(&reg, MAC_CSR21_OFF_PERIOD, *delay_off); rt2500usb_register_write(led->rt2x00dev, MAC_CSR21, reg); return 0; } static void rt2500usb_init_led(struct rt2x00_dev *rt2x00dev, struct rt2x00_led *led, enum led_type type) { led->rt2x00dev = rt2x00dev; led->type = type; led->led_dev.brightness_set = rt2500usb_brightness_set; led->led_dev.blink_set = rt2500usb_blink_set; led->flags = LED_INITIALIZED; } #endif /* CONFIG_RT2X00_LIB_LEDS */ /* * Configuration handlers. */ /* * rt2500usb does not differentiate between shared and pairwise * keys, so we should use the same function for both key types. */ static int rt2500usb_config_key(struct rt2x00_dev *rt2x00dev, struct rt2x00lib_crypto *crypto, struct ieee80211_key_conf *key) { u32 mask; u16 reg; enum cipher curr_cipher; if (crypto->cmd == SET_KEY) { /* * Disallow to set WEP key other than with index 0, * it is known that not work at least on some hardware. * SW crypto will be used in that case. */ if ((key->cipher == WLAN_CIPHER_SUITE_WEP40 || key->cipher == WLAN_CIPHER_SUITE_WEP104) && key->keyidx != 0) return -EOPNOTSUPP; /* * Pairwise key will always be entry 0, but this * could collide with a shared key on the same * position... */ mask = TXRX_CSR0_KEY_ID.bit_mask; rt2500usb_register_read(rt2x00dev, TXRX_CSR0, &reg); curr_cipher = rt2x00_get_field16(reg, TXRX_CSR0_ALGORITHM); reg &= mask; if (reg && reg == mask) return -ENOSPC; reg = rt2x00_get_field16(reg, TXRX_CSR0_KEY_ID); key->hw_key_idx += reg ? ffz(reg) : 0; /* * Hardware requires that all keys use the same cipher * (e.g. TKIP-only, AES-only, but not TKIP+AES). * If this is not the first key, compare the cipher with the * first one and fall back to SW crypto if not the same. */ if (key->hw_key_idx > 0 && crypto->cipher != curr_cipher) return -EOPNOTSUPP; rt2500usb_register_multiwrite(rt2x00dev, KEY_ENTRY(key->hw_key_idx), crypto->key, sizeof(crypto->key)); /* * The driver does not support the IV/EIV generation * in hardware. However it demands the data to be provided * both separately as well as inside the frame. * We already provided the CONFIG_CRYPTO_COPY_IV to rt2x00lib * to ensure rt2x00lib will not strip the data from the * frame after the copy, now we must tell mac80211 * to generate the IV/EIV data. */ key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV; key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC; } /* * TXRX_CSR0_KEY_ID contains only single-bit fields to indicate * a particular key is valid. */ rt2500usb_register_read(rt2x00dev, TXRX_CSR0, &reg); rt2x00_set_field16(&reg, TXRX_CSR0_ALGORITHM, crypto->cipher); rt2x00_set_field16(&reg, TXRX_CSR0_IV_OFFSET, IEEE80211_HEADER); mask = rt2x00_get_field16(reg, TXRX_CSR0_KEY_ID); if (crypto->cmd == SET_KEY) mask |= 1 << key->hw_key_idx; else if (crypto->cmd == DISABLE_KEY) mask &= ~(1 << key->hw_key_idx); rt2x00_set_field16(&reg, TXRX_CSR0_KEY_ID, mask); rt2500usb_register_write(rt2x00dev, TXRX_CSR0, reg); return 0; } static void rt2500usb_config_filter(struct rt2x00_dev *rt2x00dev, const unsigned int filter_flags) { u16 reg; /* * Start configuration steps. * Note that the version error will always be dropped * and broadcast frames will always be accepted since * there is no filter for it at this time. */ rt2500usb_register_read(rt2x00dev, TXRX_CSR2, &reg); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_CRC, !(filter_flags & FIF_FCSFAIL)); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_PHYSICAL, !(filter_flags & FIF_PLCPFAIL)); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_CONTROL, !(filter_flags & FIF_CONTROL)); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_NOT_TO_ME, !(filter_flags & FIF_PROMISC_IN_BSS)); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_TODS, !(filter_flags & FIF_PROMISC_IN_BSS) && !rt2x00dev->intf_ap_count); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_VERSION_ERROR, 1); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_MULTICAST, !(filter_flags & FIF_ALLMULTI)); rt2x00_set_field16(&reg, TXRX_CSR2_DROP_BROADCAST, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR2, reg); } static void rt2500usb_config_intf(struct rt2x00_dev *rt2x00dev, struct rt2x00_intf *intf, struct rt2x00intf_conf *conf, const unsigned int flags) { unsigned int bcn_preload; u16 reg; if (flags & CONFIG_UPDATE_TYPE) { /* * Enable beacon config */ bcn_preload = PREAMBLE + GET_DURATION(IEEE80211_HEADER, 20); rt2500usb_register_read(rt2x00dev, TXRX_CSR20, &reg); rt2x00_set_field16(&reg, TXRX_CSR20_OFFSET, bcn_preload >> 6); rt2x00_set_field16(&reg, TXRX_CSR20_BCN_EXPECT_WINDOW, 2 * (conf->type != NL80211_IFTYPE_STATION)); rt2500usb_register_write(rt2x00dev, TXRX_CSR20, reg); /* * Enable synchronisation. */ rt2500usb_register_read(rt2x00dev, TXRX_CSR18, &reg); rt2x00_set_field16(&reg, TXRX_CSR18_OFFSET, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR18, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR19, &reg); rt2x00_set_field16(&reg, TXRX_CSR19_TSF_SYNC, conf->sync); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); } if (flags & CONFIG_UPDATE_MAC) rt2500usb_register_multiwrite(rt2x00dev, MAC_CSR2, conf->mac, (3 * sizeof(__le16))); if (flags & CONFIG_UPDATE_BSSID) rt2500usb_register_multiwrite(rt2x00dev, MAC_CSR5, conf->bssid, (3 * sizeof(__le16))); } static void rt2500usb_config_erp(struct rt2x00_dev *rt2x00dev, struct rt2x00lib_erp *erp, u32 changed) { u16 reg; if (changed & BSS_CHANGED_ERP_PREAMBLE) { rt2500usb_register_read(rt2x00dev, TXRX_CSR10, &reg); rt2x00_set_field16(&reg, TXRX_CSR10_AUTORESPOND_PREAMBLE, !!erp->short_preamble); rt2500usb_register_write(rt2x00dev, TXRX_CSR10, reg); } if (changed & BSS_CHANGED_BASIC_RATES) rt2500usb_register_write(rt2x00dev, TXRX_CSR11, erp->basic_rates); if (changed & BSS_CHANGED_BEACON_INT) { rt2500usb_register_read(rt2x00dev, TXRX_CSR18, &reg); rt2x00_set_field16(&reg, TXRX_CSR18_INTERVAL, erp->beacon_int * 4); rt2500usb_register_write(rt2x00dev, TXRX_CSR18, reg); } if (changed & BSS_CHANGED_ERP_SLOT) { rt2500usb_register_write(rt2x00dev, MAC_CSR10, erp->slot_time); rt2500usb_register_write(rt2x00dev, MAC_CSR11, erp->sifs); rt2500usb_register_write(rt2x00dev, MAC_CSR12, erp->eifs); } } static void rt2500usb_config_ant(struct rt2x00_dev *rt2x00dev, struct antenna_setup *ant) { u8 r2; u8 r14; u16 csr5; u16 csr6; /* * We should never come here because rt2x00lib is supposed * to catch this and send us the correct antenna explicitely. */ BUG_ON(ant->rx == ANTENNA_SW_DIVERSITY || ant->tx == ANTENNA_SW_DIVERSITY); rt2500usb_bbp_read(rt2x00dev, 2, &r2); rt2500usb_bbp_read(rt2x00dev, 14, &r14); rt2500usb_register_read(rt2x00dev, PHY_CSR5, &csr5); rt2500usb_register_read(rt2x00dev, PHY_CSR6, &csr6); /* * Configure the TX antenna. */ switch (ant->tx) { case ANTENNA_HW_DIVERSITY: rt2x00_set_field8(&r2, BBP_R2_TX_ANTENNA, 1); rt2x00_set_field16(&csr5, PHY_CSR5_CCK, 1); rt2x00_set_field16(&csr6, PHY_CSR6_OFDM, 1); break; case ANTENNA_A: rt2x00_set_field8(&r2, BBP_R2_TX_ANTENNA, 0); rt2x00_set_field16(&csr5, PHY_CSR5_CCK, 0); rt2x00_set_field16(&csr6, PHY_CSR6_OFDM, 0); break; case ANTENNA_B: default: rt2x00_set_field8(&r2, BBP_R2_TX_ANTENNA, 2); rt2x00_set_field16(&csr5, PHY_CSR5_CCK, 2); rt2x00_set_field16(&csr6, PHY_CSR6_OFDM, 2); break; } /* * Configure the RX antenna. */ switch (ant->rx) { case ANTENNA_HW_DIVERSITY: rt2x00_set_field8(&r14, BBP_R14_RX_ANTENNA, 1); break; case ANTENNA_A: rt2x00_set_field8(&r14, BBP_R14_RX_ANTENNA, 0); break; case ANTENNA_B: default: rt2x00_set_field8(&r14, BBP_R14_RX_ANTENNA, 2); break; } /* * RT2525E and RT5222 need to flip TX I/Q */ if (rt2x00_rf(rt2x00dev, RF2525E) || rt2x00_rf(rt2x00dev, RF5222)) { rt2x00_set_field8(&r2, BBP_R2_TX_IQ_FLIP, 1); rt2x00_set_field16(&csr5, PHY_CSR5_CCK_FLIP, 1); rt2x00_set_field16(&csr6, PHY_CSR6_OFDM_FLIP, 1); /* * RT2525E does not need RX I/Q Flip. */ if (rt2x00_rf(rt2x00dev, RF2525E)) rt2x00_set_field8(&r14, BBP_R14_RX_IQ_FLIP, 0); } else { rt2x00_set_field16(&csr5, PHY_CSR5_CCK_FLIP, 0); rt2x00_set_field16(&csr6, PHY_CSR6_OFDM_FLIP, 0); } rt2500usb_bbp_write(rt2x00dev, 2, r2); rt2500usb_bbp_write(rt2x00dev, 14, r14); rt2500usb_register_write(rt2x00dev, PHY_CSR5, csr5); rt2500usb_register_write(rt2x00dev, PHY_CSR6, csr6); } static void rt2500usb_config_channel(struct rt2x00_dev *rt2x00dev, struct rf_channel *rf, const int txpower) { /* * Set TXpower. */ rt2x00_set_field32(&rf->rf3, RF3_TXPOWER, TXPOWER_TO_DEV(txpower)); /* * For RT2525E we should first set the channel to half band higher. */ if (rt2x00_rf(rt2x00dev, RF2525E)) { static const u32 vals[] = { 0x000008aa, 0x000008ae, 0x000008ae, 0x000008b2, 0x000008b2, 0x000008b6, 0x000008b6, 0x000008ba, 0x000008ba, 0x000008be, 0x000008b7, 0x00000902, 0x00000902, 0x00000906 }; rt2500usb_rf_write(rt2x00dev, 2, vals[rf->channel - 1]); if (rf->rf4) rt2500usb_rf_write(rt2x00dev, 4, rf->rf4); } rt2500usb_rf_write(rt2x00dev, 1, rf->rf1); rt2500usb_rf_write(rt2x00dev, 2, rf->rf2); rt2500usb_rf_write(rt2x00dev, 3, rf->rf3); if (rf->rf4) rt2500usb_rf_write(rt2x00dev, 4, rf->rf4); } static void rt2500usb_config_txpower(struct rt2x00_dev *rt2x00dev, const int txpower) { u32 rf3; rt2x00_rf_read(rt2x00dev, 3, &rf3); rt2x00_set_field32(&rf3, RF3_TXPOWER, TXPOWER_TO_DEV(txpower)); rt2500usb_rf_write(rt2x00dev, 3, rf3); } static void rt2500usb_config_ps(struct rt2x00_dev *rt2x00dev, struct rt2x00lib_conf *libconf) { enum dev_state state = (libconf->conf->flags & IEEE80211_CONF_PS) ? STATE_SLEEP : STATE_AWAKE; u16 reg; if (state == STATE_SLEEP) { rt2500usb_register_read(rt2x00dev, MAC_CSR18, &reg); rt2x00_set_field16(&reg, MAC_CSR18_DELAY_AFTER_BEACON, rt2x00dev->beacon_int - 20); rt2x00_set_field16(&reg, MAC_CSR18_BEACONS_BEFORE_WAKEUP, libconf->conf->listen_interval - 1); /* We must first disable autowake before it can be enabled */ rt2x00_set_field16(&reg, MAC_CSR18_AUTO_WAKE, 0); rt2500usb_register_write(rt2x00dev, MAC_CSR18, reg); rt2x00_set_field16(&reg, MAC_CSR18_AUTO_WAKE, 1); rt2500usb_register_write(rt2x00dev, MAC_CSR18, reg); } else { rt2500usb_register_read(rt2x00dev, MAC_CSR18, &reg); rt2x00_set_field16(&reg, MAC_CSR18_AUTO_WAKE, 0); rt2500usb_register_write(rt2x00dev, MAC_CSR18, reg); } rt2x00dev->ops->lib->set_device_state(rt2x00dev, state); } static void rt2500usb_config(struct rt2x00_dev *rt2x00dev, struct rt2x00lib_conf *libconf, const unsigned int flags) { if (flags & IEEE80211_CONF_CHANGE_CHANNEL) rt2500usb_config_channel(rt2x00dev, &libconf->rf, libconf->conf->power_level); if ((flags & IEEE80211_CONF_CHANGE_POWER) && !(flags & IEEE80211_CONF_CHANGE_CHANNEL)) rt2500usb_config_txpower(rt2x00dev, libconf->conf->power_level); if (flags & IEEE80211_CONF_CHANGE_PS) rt2500usb_config_ps(rt2x00dev, libconf); } /* * Link tuning */ static void rt2500usb_link_stats(struct rt2x00_dev *rt2x00dev, struct link_qual *qual) { u16 reg; /* * Update FCS error count from register. */ rt2500usb_register_read(rt2x00dev, STA_CSR0, &reg); qual->rx_failed = rt2x00_get_field16(reg, STA_CSR0_FCS_ERROR); /* * Update False CCA count from register. */ rt2500usb_register_read(rt2x00dev, STA_CSR3, &reg); qual->false_cca = rt2x00_get_field16(reg, STA_CSR3_FALSE_CCA_ERROR); } static void rt2500usb_reset_tuner(struct rt2x00_dev *rt2x00dev, struct link_qual *qual) { u16 eeprom; u16 value; rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R24, &eeprom); value = rt2x00_get_field16(eeprom, EEPROM_BBPTUNE_R24_LOW); rt2500usb_bbp_write(rt2x00dev, 24, value); rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R25, &eeprom); value = rt2x00_get_field16(eeprom, EEPROM_BBPTUNE_R25_LOW); rt2500usb_bbp_write(rt2x00dev, 25, value); rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R61, &eeprom); value = rt2x00_get_field16(eeprom, EEPROM_BBPTUNE_R61_LOW); rt2500usb_bbp_write(rt2x00dev, 61, value); rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_VGC, &eeprom); value = rt2x00_get_field16(eeprom, EEPROM_BBPTUNE_VGCUPPER); rt2500usb_bbp_write(rt2x00dev, 17, value); qual->vgc_level = value; } /* * Queue handlers. */ static void rt2500usb_start_queue(struct data_queue *queue) { struct rt2x00_dev *rt2x00dev = queue->rt2x00dev; u16 reg; switch (queue->qid) { case QID_RX: rt2500usb_register_read(rt2x00dev, TXRX_CSR2, &reg); rt2x00_set_field16(&reg, TXRX_CSR2_DISABLE_RX, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR2, reg); break; case QID_BEACON: rt2500usb_register_read(rt2x00dev, TXRX_CSR19, &reg); rt2x00_set_field16(&reg, TXRX_CSR19_TSF_COUNT, 1); rt2x00_set_field16(&reg, TXRX_CSR19_TBCN, 1); rt2x00_set_field16(&reg, TXRX_CSR19_BEACON_GEN, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); break; default: break; } } static void rt2500usb_stop_queue(struct data_queue *queue) { struct rt2x00_dev *rt2x00dev = queue->rt2x00dev; u16 reg; switch (queue->qid) { case QID_RX: rt2500usb_register_read(rt2x00dev, TXRX_CSR2, &reg); rt2x00_set_field16(&reg, TXRX_CSR2_DISABLE_RX, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR2, reg); break; case QID_BEACON: rt2500usb_register_read(rt2x00dev, TXRX_CSR19, &reg); rt2x00_set_field16(&reg, TXRX_CSR19_TSF_COUNT, 0); rt2x00_set_field16(&reg, TXRX_CSR19_TBCN, 0); rt2x00_set_field16(&reg, TXRX_CSR19_BEACON_GEN, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); break; default: break; } } /* * Initialization functions. */ static int rt2500usb_init_registers(struct rt2x00_dev *rt2x00dev) { u16 reg; rt2x00usb_vendor_request_sw(rt2x00dev, USB_DEVICE_MODE, 0x0001, USB_MODE_TEST, REGISTER_TIMEOUT); rt2x00usb_vendor_request_sw(rt2x00dev, USB_SINGLE_WRITE, 0x0308, 0x00f0, REGISTER_TIMEOUT); rt2500usb_register_read(rt2x00dev, TXRX_CSR2, &reg); rt2x00_set_field16(&reg, TXRX_CSR2_DISABLE_RX, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR2, reg); rt2500usb_register_write(rt2x00dev, MAC_CSR13, 0x1111); rt2500usb_register_write(rt2x00dev, MAC_CSR14, 0x1e11); rt2500usb_register_read(rt2x00dev, MAC_CSR1, &reg); rt2x00_set_field16(&reg, MAC_CSR1_SOFT_RESET, 1); rt2x00_set_field16(&reg, MAC_CSR1_BBP_RESET, 1); rt2x00_set_field16(&reg, MAC_CSR1_HOST_READY, 0); rt2500usb_register_write(rt2x00dev, MAC_CSR1, reg); rt2500usb_register_read(rt2x00dev, MAC_CSR1, &reg); rt2x00_set_field16(&reg, MAC_CSR1_SOFT_RESET, 0); rt2x00_set_field16(&reg, MAC_CSR1_BBP_RESET, 0); rt2x00_set_field16(&reg, MAC_CSR1_HOST_READY, 0); rt2500usb_register_write(rt2x00dev, MAC_CSR1, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR5, &reg); rt2x00_set_field16(&reg, TXRX_CSR5_BBP_ID0, 13); rt2x00_set_field16(&reg, TXRX_CSR5_BBP_ID0_VALID, 1); rt2x00_set_field16(&reg, TXRX_CSR5_BBP_ID1, 12); rt2x00_set_field16(&reg, TXRX_CSR5_BBP_ID1_VALID, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR5, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR6, &reg); rt2x00_set_field16(&reg, TXRX_CSR6_BBP_ID0, 10); rt2x00_set_field16(&reg, TXRX_CSR6_BBP_ID0_VALID, 1); rt2x00_set_field16(&reg, TXRX_CSR6_BBP_ID1, 11); rt2x00_set_field16(&reg, TXRX_CSR6_BBP_ID1_VALID, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR6, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR7, &reg); rt2x00_set_field16(&reg, TXRX_CSR7_BBP_ID0, 7); rt2x00_set_field16(&reg, TXRX_CSR7_BBP_ID0_VALID, 1); rt2x00_set_field16(&reg, TXRX_CSR7_BBP_ID1, 6); rt2x00_set_field16(&reg, TXRX_CSR7_BBP_ID1_VALID, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR7, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR8, &reg); rt2x00_set_field16(&reg, TXRX_CSR8_BBP_ID0, 5); rt2x00_set_field16(&reg, TXRX_CSR8_BBP_ID0_VALID, 1); rt2x00_set_field16(&reg, TXRX_CSR8_BBP_ID1, 0); rt2x00_set_field16(&reg, TXRX_CSR8_BBP_ID1_VALID, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR8, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR19, &reg); rt2x00_set_field16(&reg, TXRX_CSR19_TSF_COUNT, 0); rt2x00_set_field16(&reg, TXRX_CSR19_TSF_SYNC, 0); rt2x00_set_field16(&reg, TXRX_CSR19_TBCN, 0); rt2x00_set_field16(&reg, TXRX_CSR19_BEACON_GEN, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); rt2500usb_register_write(rt2x00dev, TXRX_CSR21, 0xe78f); rt2500usb_register_write(rt2x00dev, MAC_CSR9, 0xff1d); if (rt2x00dev->ops->lib->set_device_state(rt2x00dev, STATE_AWAKE)) return -EBUSY; rt2500usb_register_read(rt2x00dev, MAC_CSR1, &reg); rt2x00_set_field16(&reg, MAC_CSR1_SOFT_RESET, 0); rt2x00_set_field16(&reg, MAC_CSR1_BBP_RESET, 0); rt2x00_set_field16(&reg, MAC_CSR1_HOST_READY, 1); rt2500usb_register_write(rt2x00dev, MAC_CSR1, reg); if (rt2x00_rev(rt2x00dev) >= RT2570_VERSION_C) { rt2500usb_register_read(rt2x00dev, PHY_CSR2, &reg); rt2x00_set_field16(&reg, PHY_CSR2_LNA, 0); } else { reg = 0; rt2x00_set_field16(&reg, PHY_CSR2_LNA, 1); rt2x00_set_field16(&reg, PHY_CSR2_LNA_MODE, 3); } rt2500usb_register_write(rt2x00dev, PHY_CSR2, reg); rt2500usb_register_write(rt2x00dev, MAC_CSR11, 0x0002); rt2500usb_register_write(rt2x00dev, MAC_CSR22, 0x0053); rt2500usb_register_write(rt2x00dev, MAC_CSR15, 0x01ee); rt2500usb_register_write(rt2x00dev, MAC_CSR16, 0x0000); rt2500usb_register_read(rt2x00dev, MAC_CSR8, &reg); rt2x00_set_field16(&reg, MAC_CSR8_MAX_FRAME_UNIT, rt2x00dev->rx->data_size); rt2500usb_register_write(rt2x00dev, MAC_CSR8, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR0, &reg); rt2x00_set_field16(&reg, TXRX_CSR0_ALGORITHM, CIPHER_NONE); rt2x00_set_field16(&reg, TXRX_CSR0_IV_OFFSET, IEEE80211_HEADER); rt2x00_set_field16(&reg, TXRX_CSR0_KEY_ID, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR0, reg); rt2500usb_register_read(rt2x00dev, MAC_CSR18, &reg); rt2x00_set_field16(&reg, MAC_CSR18_DELAY_AFTER_BEACON, 90); rt2500usb_register_write(rt2x00dev, MAC_CSR18, reg); rt2500usb_register_read(rt2x00dev, PHY_CSR4, &reg); rt2x00_set_field16(&reg, PHY_CSR4_LOW_RF_LE, 1); rt2500usb_register_write(rt2x00dev, PHY_CSR4, reg); rt2500usb_register_read(rt2x00dev, TXRX_CSR1, &reg); rt2x00_set_field16(&reg, TXRX_CSR1_AUTO_SEQUENCE, 1); rt2500usb_register_write(rt2x00dev, TXRX_CSR1, reg); return 0; } static int rt2500usb_wait_bbp_ready(struct rt2x00_dev *rt2x00dev) { unsigned int i; u8 value; for (i = 0; i < REGISTER_BUSY_COUNT; i++) { rt2500usb_bbp_read(rt2x00dev, 0, &value); if ((value != 0xff) && (value != 0x00)) return 0; udelay(REGISTER_BUSY_DELAY); } ERROR(rt2x00dev, "BBP register access failed, aborting.\n"); return -EACCES; } static int rt2500usb_init_bbp(struct rt2x00_dev *rt2x00dev) { unsigned int i; u16 eeprom; u8 value; u8 reg_id; if (unlikely(rt2500usb_wait_bbp_ready(rt2x00dev))) return -EACCES; rt2500usb_bbp_write(rt2x00dev, 3, 0x02); rt2500usb_bbp_write(rt2x00dev, 4, 0x19); rt2500usb_bbp_write(rt2x00dev, 14, 0x1c); rt2500usb_bbp_write(rt2x00dev, 15, 0x30); rt2500usb_bbp_write(rt2x00dev, 16, 0xac); rt2500usb_bbp_write(rt2x00dev, 18, 0x18); rt2500usb_bbp_write(rt2x00dev, 19, 0xff); rt2500usb_bbp_write(rt2x00dev, 20, 0x1e); rt2500usb_bbp_write(rt2x00dev, 21, 0x08); rt2500usb_bbp_write(rt2x00dev, 22, 0x08); rt2500usb_bbp_write(rt2x00dev, 23, 0x08); rt2500usb_bbp_write(rt2x00dev, 24, 0x80); rt2500usb_bbp_write(rt2x00dev, 25, 0x50); rt2500usb_bbp_write(rt2x00dev, 26, 0x08); rt2500usb_bbp_write(rt2x00dev, 27, 0x23); rt2500usb_bbp_write(rt2x00dev, 30, 0x10); rt2500usb_bbp_write(rt2x00dev, 31, 0x2b); rt2500usb_bbp_write(rt2x00dev, 32, 0xb9); rt2500usb_bbp_write(rt2x00dev, 34, 0x12); rt2500usb_bbp_write(rt2x00dev, 35, 0x50); rt2500usb_bbp_write(rt2x00dev, 39, 0xc4); rt2500usb_bbp_write(rt2x00dev, 40, 0x02); rt2500usb_bbp_write(rt2x00dev, 41, 0x60); rt2500usb_bbp_write(rt2x00dev, 53, 0x10); rt2500usb_bbp_write(rt2x00dev, 54, 0x18); rt2500usb_bbp_write(rt2x00dev, 56, 0x08); rt2500usb_bbp_write(rt2x00dev, 57, 0x10); rt2500usb_bbp_write(rt2x00dev, 58, 0x08); rt2500usb_bbp_write(rt2x00dev, 61, 0x60); rt2500usb_bbp_write(rt2x00dev, 62, 0x10); rt2500usb_bbp_write(rt2x00dev, 75, 0xff); for (i = 0; i < EEPROM_BBP_SIZE; i++) { rt2x00_eeprom_read(rt2x00dev, EEPROM_BBP_START + i, &eeprom); if (eeprom != 0xffff && eeprom != 0x0000) { reg_id = rt2x00_get_field16(eeprom, EEPROM_BBP_REG_ID); value = rt2x00_get_field16(eeprom, EEPROM_BBP_VALUE); rt2500usb_bbp_write(rt2x00dev, reg_id, value); } } return 0; } /* * Device state switch handlers. */ static int rt2500usb_enable_radio(struct rt2x00_dev *rt2x00dev) { /* * Initialize all registers. */ if (unlikely(rt2500usb_init_registers(rt2x00dev) || rt2500usb_init_bbp(rt2x00dev))) return -EIO; return 0; } static void rt2500usb_disable_radio(struct rt2x00_dev *rt2x00dev) { rt2500usb_register_write(rt2x00dev, MAC_CSR13, 0x2121); rt2500usb_register_write(rt2x00dev, MAC_CSR14, 0x2121); /* * Disable synchronisation. */ rt2500usb_register_write(rt2x00dev, TXRX_CSR19, 0); rt2x00usb_disable_radio(rt2x00dev); } static int rt2500usb_set_state(struct rt2x00_dev *rt2x00dev, enum dev_state state) { u16 reg; u16 reg2; unsigned int i; char put_to_sleep; char bbp_state; char rf_state; put_to_sleep = (state != STATE_AWAKE); reg = 0; rt2x00_set_field16(&reg, MAC_CSR17_BBP_DESIRE_STATE, state); rt2x00_set_field16(&reg, MAC_CSR17_RF_DESIRE_STATE, state); rt2x00_set_field16(&reg, MAC_CSR17_PUT_TO_SLEEP, put_to_sleep); rt2500usb_register_write(rt2x00dev, MAC_CSR17, reg); rt2x00_set_field16(&reg, MAC_CSR17_SET_STATE, 1); rt2500usb_register_write(rt2x00dev, MAC_CSR17, reg); /* * Device is not guaranteed to be in the requested state yet. * We must wait until the register indicates that the * device has entered the correct state. */ for (i = 0; i < REGISTER_BUSY_COUNT; i++) { rt2500usb_register_read(rt2x00dev, MAC_CSR17, &reg2); bbp_state = rt2x00_get_field16(reg2, MAC_CSR17_BBP_CURR_STATE); rf_state = rt2x00_get_field16(reg2, MAC_CSR17_RF_CURR_STATE); if (bbp_state == state && rf_state == state) return 0; rt2500usb_register_write(rt2x00dev, MAC_CSR17, reg); msleep(30); } return -EBUSY; } static int rt2500usb_set_device_state(struct rt2x00_dev *rt2x00dev, enum dev_state state) { int retval = 0; switch (state) { case STATE_RADIO_ON: retval = rt2500usb_enable_radio(rt2x00dev); break; case STATE_RADIO_OFF: rt2500usb_disable_radio(rt2x00dev); break; case STATE_RADIO_IRQ_ON: case STATE_RADIO_IRQ_OFF: /* No support, but no error either */ break; case STATE_DEEP_SLEEP: case STATE_SLEEP: case STATE_STANDBY: case STATE_AWAKE: retval = rt2500usb_set_state(rt2x00dev, state); break; default: retval = -ENOTSUPP; break; } if (unlikely(retval)) ERROR(rt2x00dev, "Device failed to enter state %d (%d).\n", state, retval); return retval; } /* * TX descriptor initialization */ static void rt2500usb_write_tx_desc(struct queue_entry *entry, struct txentry_desc *txdesc) { struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb); __le32 *txd = (__le32 *) entry->skb->data; u32 word; /* * Start writing the descriptor words. */ rt2x00_desc_read(txd, 0, &word); rt2x00_set_field32(&word, TXD_W0_RETRY_LIMIT, txdesc->retry_limit); rt2x00_set_field32(&word, TXD_W0_MORE_FRAG, test_bit(ENTRY_TXD_MORE_FRAG, &txdesc->flags)); rt2x00_set_field32(&word, TXD_W0_ACK, test_bit(ENTRY_TXD_ACK, &txdesc->flags)); rt2x00_set_field32(&word, TXD_W0_TIMESTAMP, test_bit(ENTRY_TXD_REQ_TIMESTAMP, &txdesc->flags)); rt2x00_set_field32(&word, TXD_W0_OFDM, (txdesc->rate_mode == RATE_MODE_OFDM)); rt2x00_set_field32(&word, TXD_W0_NEW_SEQ, test_bit(ENTRY_TXD_FIRST_FRAGMENT, &txdesc->flags)); rt2x00_set_field32(&word, TXD_W0_IFS, txdesc->u.plcp.ifs); rt2x00_set_field32(&word, TXD_W0_DATABYTE_COUNT, txdesc->length); rt2x00_set_field32(&word, TXD_W0_CIPHER, !!txdesc->cipher); rt2x00_set_field32(&word, TXD_W0_KEY_ID, txdesc->key_idx); rt2x00_desc_write(txd, 0, word); rt2x00_desc_read(txd, 1, &word); rt2x00_set_field32(&word, TXD_W1_IV_OFFSET, txdesc->iv_offset); rt2x00_set_field32(&word, TXD_W1_AIFS, entry->queue->aifs); rt2x00_set_field32(&word, TXD_W1_CWMIN, entry->queue->cw_min); rt2x00_set_field32(&word, TXD_W1_CWMAX, entry->queue->cw_max); rt2x00_desc_write(txd, 1, word); rt2x00_desc_read(txd, 2, &word); rt2x00_set_field32(&word, TXD_W2_PLCP_SIGNAL, txdesc->u.plcp.signal); rt2x00_set_field32(&word, TXD_W2_PLCP_SERVICE, txdesc->u.plcp.service); rt2x00_set_field32(&word, TXD_W2_PLCP_LENGTH_LOW, txdesc->u.plcp.length_low); rt2x00_set_field32(&word, TXD_W2_PLCP_LENGTH_HIGH, txdesc->u.plcp.length_high); rt2x00_desc_write(txd, 2, word); if (test_bit(ENTRY_TXD_ENCRYPT, &txdesc->flags)) { _rt2x00_desc_write(txd, 3, skbdesc->iv[0]); _rt2x00_desc_write(txd, 4, skbdesc->iv[1]); } /* * Register descriptor details in skb frame descriptor. */ skbdesc->flags |= SKBDESC_DESC_IN_SKB; skbdesc->desc = txd; skbdesc->desc_len = TXD_DESC_SIZE; } /* * TX data initialization */ static void rt2500usb_beacondone(struct urb *urb); static void rt2500usb_write_beacon(struct queue_entry *entry, struct txentry_desc *txdesc) { struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev; struct usb_device *usb_dev = to_usb_device_intf(rt2x00dev->dev); struct queue_entry_priv_usb_bcn *bcn_priv = entry->priv_data; int pipe = usb_sndbulkpipe(usb_dev, entry->queue->usb_endpoint); int length; u16 reg, reg0; /* * Disable beaconing while we are reloading the beacon data, * otherwise we might be sending out invalid data. */ rt2500usb_register_read(rt2x00dev, TXRX_CSR19, &reg); rt2x00_set_field16(&reg, TXRX_CSR19_BEACON_GEN, 0); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); /* * Add space for the descriptor in front of the skb. */ skb_push(entry->skb, TXD_DESC_SIZE); memset(entry->skb->data, 0, TXD_DESC_SIZE); /* * Write the TX descriptor for the beacon. */ rt2500usb_write_tx_desc(entry, txdesc); /* * Dump beacon to userspace through debugfs. */ rt2x00debug_dump_frame(rt2x00dev, DUMP_FRAME_BEACON, entry->skb); /* * USB devices cannot blindly pass the skb->len as the * length of the data to usb_fill_bulk_urb. Pass the skb * to the driver to determine what the length should be. */ length = rt2x00dev->ops->lib->get_tx_data_len(entry); usb_fill_bulk_urb(bcn_priv->urb, usb_dev, pipe, entry->skb->data, length, rt2500usb_beacondone, entry); /* * Second we need to create the guardian byte. * We only need a single byte, so lets recycle * the 'flags' field we are not using for beacons. */ bcn_priv->guardian_data = 0; usb_fill_bulk_urb(bcn_priv->guardian_urb, usb_dev, pipe, &bcn_priv->guardian_data, 1, rt2500usb_beacondone, entry); /* * Send out the guardian byte. */ usb_submit_urb(bcn_priv->guardian_urb, GFP_ATOMIC); /* * Enable beaconing again. */ rt2x00_set_field16(&reg, TXRX_CSR19_TSF_COUNT, 1); rt2x00_set_field16(&reg, TXRX_CSR19_TBCN, 1); reg0 = reg; rt2x00_set_field16(&reg, TXRX_CSR19_BEACON_GEN, 1); /* * Beacon generation will fail initially. * To prevent this we need to change the TXRX_CSR19 * register several times (reg0 is the same as reg * except for TXRX_CSR19_BEACON_GEN, which is 0 in reg0 * and 1 in reg). */ rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg0); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg0); rt2500usb_register_write(rt2x00dev, TXRX_CSR19, reg); } static int rt2500usb_get_tx_data_len(struct queue_entry *entry) { int length; /* * The length _must_ be a multiple of 2, * but it must _not_ be a multiple of the USB packet size. */ length = roundup(entry->skb->len, 2); length += (2 * !(length % entry->queue->usb_maxpacket)); return length; } /* * RX control handlers */ static void rt2500usb_fill_rxdone(struct queue_entry *entry, struct rxdone_entry_desc *rxdesc) { struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev; struct queue_entry_priv_usb *entry_priv = entry->priv_data; struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb); __le32 *rxd = (__le32 *)(entry->skb->data + (entry_priv->urb->actual_length - entry->queue->desc_size)); u32 word0; u32 word1; /* * Copy descriptor to the skbdesc->desc buffer, making it safe from moving of * frame data in rt2x00usb. */ memcpy(skbdesc->desc, rxd, skbdesc->desc_len); rxd = (__le32 *)skbdesc->desc; /* * It is now safe to read the descriptor on all architectures. */ rt2x00_desc_read(rxd, 0, &word0); rt2x00_desc_read(rxd, 1, &word1); if (rt2x00_get_field32(word0, RXD_W0_CRC_ERROR)) rxdesc->flags |= RX_FLAG_FAILED_FCS_CRC; if (rt2x00_get_field32(word0, RXD_W0_PHYSICAL_ERROR)) rxdesc->flags |= RX_FLAG_FAILED_PLCP_CRC; rxdesc->cipher = rt2x00_get_field32(word0, RXD_W0_CIPHER); if (rt2x00_get_field32(word0, RXD_W0_CIPHER_ERROR)) rxdesc->cipher_status = RX_CRYPTO_FAIL_KEY; if (rxdesc->cipher != CIPHER_NONE) { _rt2x00_desc_read(rxd, 2, &rxdesc->iv[0]); _rt2x00_desc_read(rxd, 3, &rxdesc->iv[1]); rxdesc->dev_flags |= RXDONE_CRYPTO_IV; /* ICV is located at the end of frame */ rxdesc->flags |= RX_FLAG_MMIC_STRIPPED; if (rxdesc->cipher_status == RX_CRYPTO_SUCCESS) rxdesc->flags |= RX_FLAG_DECRYPTED; else if (rxdesc->cipher_status == RX_CRYPTO_FAIL_MIC) rxdesc->flags |= RX_FLAG_MMIC_ERROR; } /* * Obtain the status about this packet. * When frame was received with an OFDM bitrate, * the signal is the PLCP value. If it was received with * a CCK bitrate the signal is the rate in 100kbit/s. */ rxdesc->signal = rt2x00_get_field32(word1, RXD_W1_SIGNAL); rxdesc->rssi = rt2x00_get_field32(word1, RXD_W1_RSSI) - rt2x00dev->rssi_offset; rxdesc->size = rt2x00_get_field32(word0, RXD_W0_DATABYTE_COUNT); if (rt2x00_get_field32(word0, RXD_W0_OFDM)) rxdesc->dev_flags |= RXDONE_SIGNAL_PLCP; else rxdesc->dev_flags |= RXDONE_SIGNAL_BITRATE; if (rt2x00_get_field32(word0, RXD_W0_MY_BSS)) rxdesc->dev_flags |= RXDONE_MY_BSS; /* * Adjust the skb memory window to the frame boundaries. */ skb_trim(entry->skb, rxdesc->size); } /* * Interrupt functions. */ static void rt2500usb_beacondone(struct urb *urb) { struct queue_entry *entry = (struct queue_entry *)urb->context; struct queue_entry_priv_usb_bcn *bcn_priv = entry->priv_data; if (!test_bit(DEVICE_STATE_ENABLED_RADIO, &entry->queue->rt2x00dev->flags)) return; /* * Check if this was the guardian beacon, * if that was the case we need to send the real beacon now. * Otherwise we should free the sk_buffer, the device * should be doing the rest of the work now. */ if (bcn_priv->guardian_urb == urb) { usb_submit_urb(bcn_priv->urb, GFP_ATOMIC); } else if (bcn_priv->urb == urb) { dev_kfree_skb(entry->skb); entry->skb = NULL; } } /* * Device probe functions. */ static int rt2500usb_validate_eeprom(struct rt2x00_dev *rt2x00dev) { u16 word; u8 *mac; u8 bbp; rt2x00usb_eeprom_read(rt2x00dev, rt2x00dev->eeprom, EEPROM_SIZE); /* * Start validation of the data that has been read. */ mac = rt2x00_eeprom_addr(rt2x00dev, EEPROM_MAC_ADDR_0); if (!is_valid_ether_addr(mac)) { random_ether_addr(mac); EEPROM(rt2x00dev, "MAC: %pM\n", mac); } rt2x00_eeprom_read(rt2x00dev, EEPROM_ANTENNA, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_ANTENNA_NUM, 2); rt2x00_set_field16(&word, EEPROM_ANTENNA_TX_DEFAULT, ANTENNA_SW_DIVERSITY); rt2x00_set_field16(&word, EEPROM_ANTENNA_RX_DEFAULT, ANTENNA_SW_DIVERSITY); rt2x00_set_field16(&word, EEPROM_ANTENNA_LED_MODE, LED_MODE_DEFAULT); rt2x00_set_field16(&word, EEPROM_ANTENNA_DYN_TXAGC, 0); rt2x00_set_field16(&word, EEPROM_ANTENNA_HARDWARE_RADIO, 0); rt2x00_set_field16(&word, EEPROM_ANTENNA_RF_TYPE, RF2522); rt2x00_eeprom_write(rt2x00dev, EEPROM_ANTENNA, word); EEPROM(rt2x00dev, "Antenna: 0x%04x\n", word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_NIC, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_NIC_CARDBUS_ACCEL, 0); rt2x00_set_field16(&word, EEPROM_NIC_DYN_BBP_TUNE, 0); rt2x00_set_field16(&word, EEPROM_NIC_CCK_TX_POWER, 0); rt2x00_eeprom_write(rt2x00dev, EEPROM_NIC, word); EEPROM(rt2x00dev, "NIC: 0x%04x\n", word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_CALIBRATE_OFFSET, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_CALIBRATE_OFFSET_RSSI, DEFAULT_RSSI_OFFSET); rt2x00_eeprom_write(rt2x00dev, EEPROM_CALIBRATE_OFFSET, word); EEPROM(rt2x00dev, "Calibrate offset: 0x%04x\n", word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_BBPTUNE_THRESHOLD, 45); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE, word); EEPROM(rt2x00dev, "BBPtune: 0x%04x\n", word); } /* * Switch lower vgc bound to current BBP R17 value, * lower the value a bit for better quality. */ rt2500usb_bbp_read(rt2x00dev, 17, &bbp); bbp -= 6; rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_VGC, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_BBPTUNE_VGCUPPER, 0x40); rt2x00_set_field16(&word, EEPROM_BBPTUNE_VGCLOWER, bbp); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE_VGC, word); EEPROM(rt2x00dev, "BBPtune vgc: 0x%04x\n", word); } else { rt2x00_set_field16(&word, EEPROM_BBPTUNE_VGCLOWER, bbp); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE_VGC, word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R17, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_BBPTUNE_R17_LOW, 0x48); rt2x00_set_field16(&word, EEPROM_BBPTUNE_R17_HIGH, 0x41); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE_R17, word); EEPROM(rt2x00dev, "BBPtune r17: 0x%04x\n", word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R24, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_BBPTUNE_R24_LOW, 0x40); rt2x00_set_field16(&word, EEPROM_BBPTUNE_R24_HIGH, 0x80); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE_R24, word); EEPROM(rt2x00dev, "BBPtune r24: 0x%04x\n", word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R25, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_BBPTUNE_R25_LOW, 0x40); rt2x00_set_field16(&word, EEPROM_BBPTUNE_R25_HIGH, 0x50); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE_R25, word); EEPROM(rt2x00dev, "BBPtune r25: 0x%04x\n", word); } rt2x00_eeprom_read(rt2x00dev, EEPROM_BBPTUNE_R61, &word); if (word == 0xffff) { rt2x00_set_field16(&word, EEPROM_BBPTUNE_R61_LOW, 0x60); rt2x00_set_field16(&word, EEPROM_BBPTUNE_R61_HIGH, 0x6d); rt2x00_eeprom_write(rt2x00dev, EEPROM_BBPTUNE_R61, word); EEPROM(rt2x00dev, "BBPtune r61: 0x%04x\n", word); } return 0; } static int rt2500usb_init_eeprom(struct rt2x00_dev *rt2x00dev) { u16 reg; u16 value; u16 eeprom; /* * Read EEPROM word for configuration. */ rt2x00_eeprom_read(rt2x00dev, EEPROM_ANTENNA, &eeprom); /* * Identify RF chipset. */ value = rt2x00_get_field16(eeprom, EEPROM_ANTENNA_RF_TYPE); rt2500usb_register_read(rt2x00dev, MAC_CSR0, &reg); rt2x00_set_chip(rt2x00dev, RT2570, value, reg); if (((reg & 0xfff0) != 0) || ((reg & 0x0000000f) == 0)) { ERROR(rt2x00dev, "Invalid RT chipset detected.\n"); return -ENODEV; } if (!rt2x00_rf(rt2x00dev, RF2522) && !rt2x00_rf(rt2x00dev, RF2523) && !rt2x00_rf(rt2x00dev, RF2524) && !rt2x00_rf(rt2x00dev, RF2525) && !rt2x00_rf(rt2x00dev, RF2525E) && !rt2x00_rf(rt2x00dev, RF5222)) { ERROR(rt2x00dev, "Invalid RF chipset detected.\n"); return -ENODEV; } /* * Identify default antenna configuration. */ rt2x00dev->default_ant.tx = rt2x00_get_field16(eeprom, EEPROM_ANTENNA_TX_DEFAULT); rt2x00dev->default_ant.rx = rt2x00_get_field16(eeprom, EEPROM_ANTENNA_RX_DEFAULT); /* * When the eeprom indicates SW_DIVERSITY use HW_DIVERSITY instead. * I am not 100% sure about this, but the legacy drivers do not * indicate antenna swapping in software is required when * diversity is enabled. */ if (rt2x00dev->default_ant.tx == ANTENNA_SW_DIVERSITY) rt2x00dev->default_ant.tx = ANTENNA_HW_DIVERSITY; if (rt2x00dev->default_ant.rx == ANTENNA_SW_DIVERSITY) rt2x00dev->default_ant.rx = ANTENNA_HW_DIVERSITY; /* * Store led mode, for correct led behaviour. */ #ifdef CONFIG_RT2X00_LIB_LEDS value = rt2x00_get_field16(eeprom, EEPROM_ANTENNA_LED_MODE); rt2500usb_init_led(rt2x00dev, &rt2x00dev->led_radio, LED_TYPE_RADIO); if (value == LED_MODE_TXRX_ACTIVITY || value == LED_MODE_DEFAULT || value == LED_MODE_ASUS) rt2500usb_init_led(rt2x00dev, &rt2x00dev->led_qual, LED_TYPE_ACTIVITY); #endif /* CONFIG_RT2X00_LIB_LEDS */ /* * Detect if this device has an hardware controlled radio. */ if (rt2x00_get_field16(eeprom, EEPROM_ANTENNA_HARDWARE_RADIO)) __set_bit(CAPABILITY_HW_BUTTON, &rt2x00dev->cap_flags); /* * Read the RSSI <-> dBm offset information. */ rt2x00_eeprom_read(rt2x00dev, EEPROM_CALIBRATE_OFFSET, &eeprom); rt2x00dev->rssi_offset = rt2x00_get_field16(eeprom, EEPROM_CALIBRATE_OFFSET_RSSI); return 0; } /* * RF value list for RF2522 * Supports: 2.4 GHz */ static const struct rf_channel rf_vals_bg_2522[] = { { 1, 0x00002050, 0x000c1fda, 0x00000101, 0 }, { 2, 0x00002050, 0x000c1fee, 0x00000101, 0 }, { 3, 0x00002050, 0x000c2002, 0x00000101, 0 }, { 4, 0x00002050, 0x000c2016, 0x00000101, 0 }, { 5, 0x00002050, 0x000c202a, 0x00000101, 0 }, { 6, 0x00002050, 0x000c203e, 0x00000101, 0 }, { 7, 0x00002050, 0x000c2052, 0x00000101, 0 }, { 8, 0x00002050, 0x000c2066, 0x00000101, 0 }, { 9, 0x00002050, 0x000c207a, 0x00000101, 0 }, { 10, 0x00002050, 0x000c208e, 0x00000101, 0 }, { 11, 0x00002050, 0x000c20a2, 0x00000101, 0 }, { 12, 0x00002050, 0x000c20b6, 0x00000101, 0 }, { 13, 0x00002050, 0x000c20ca, 0x00000101, 0 }, { 14, 0x00002050, 0x000c20fa, 0x00000101, 0 }, }; /* * RF value list for RF2523 * Supports: 2.4 GHz */ static const struct rf_channel rf_vals_bg_2523[] = { { 1, 0x00022010, 0x00000c9e, 0x000e0111, 0x00000a1b }, { 2, 0x00022010, 0x00000ca2, 0x000e0111, 0x00000a1b }, { 3, 0x00022010, 0x00000ca6, 0x000e0111, 0x00000a1b }, { 4, 0x00022010, 0x00000caa, 0x000e0111, 0x00000a1b }, { 5, 0x00022010, 0x00000cae, 0x000e0111, 0x00000a1b }, { 6, 0x00022010, 0x00000cb2, 0x000e0111, 0x00000a1b }, { 7, 0x00022010, 0x00000cb6, 0x000e0111, 0x00000a1b }, { 8, 0x00022010, 0x00000cba, 0x000e0111, 0x00000a1b }, { 9, 0x00022010, 0x00000cbe, 0x000e0111, 0x00000a1b }, { 10, 0x00022010, 0x00000d02, 0x000e0111, 0x00000a1b }, { 11, 0x00022010, 0x00000d06, 0x000e0111, 0x00000a1b }, { 12, 0x00022010, 0x00000d0a, 0x000e0111, 0x00000a1b }, { 13, 0x00022010, 0x00000d0e, 0x000e0111, 0x00000a1b }, { 14, 0x00022010, 0x00000d1a, 0x000e0111, 0x00000a03 }, }; /* * RF value list for RF2524 * Supports: 2.4 GHz */ static const struct rf_channel rf_vals_bg_2524[] = { { 1, 0x00032020, 0x00000c9e, 0x00000101, 0x00000a1b }, { 2, 0x00032020, 0x00000ca2, 0x00000101, 0x00000a1b }, { 3, 0x00032020, 0x00000ca6, 0x00000101, 0x00000a1b }, { 4, 0x00032020, 0x00000caa, 0x00000101, 0x00000a1b }, { 5, 0x00032020, 0x00000cae, 0x00000101, 0x00000a1b }, { 6, 0x00032020, 0x00000cb2, 0x00000101, 0x00000a1b }, { 7, 0x00032020, 0x00000cb6, 0x00000101, 0x00000a1b }, { 8, 0x00032020, 0x00000cba, 0x00000101, 0x00000a1b }, { 9, 0x00032020, 0x00000cbe, 0x00000101, 0x00000a1b }, { 10, 0x00032020, 0x00000d02, 0x00000101, 0x00000a1b }, { 11, 0x00032020, 0x00000d06, 0x00000101, 0x00000a1b }, { 12, 0x00032020, 0x00000d0a, 0x00000101, 0x00000a1b }, { 13, 0x00032020, 0x00000d0e, 0x00000101, 0x00000a1b }, { 14, 0x00032020, 0x00000d1a, 0x00000101, 0x00000a03 }, }; /* * RF value list for RF2525 * Supports: 2.4 GHz */ static const struct rf_channel rf_vals_bg_2525[] = { { 1, 0x00022020, 0x00080c9e, 0x00060111, 0x00000a1b }, { 2, 0x00022020, 0x00080ca2, 0x00060111, 0x00000a1b }, { 3, 0x00022020, 0x00080ca6, 0x00060111, 0x00000a1b }, { 4, 0x00022020, 0x00080caa, 0x00060111, 0x00000a1b }, { 5, 0x00022020, 0x00080cae, 0x00060111, 0x00000a1b }, { 6, 0x00022020, 0x00080cb2, 0x00060111, 0x00000a1b }, { 7, 0x00022020, 0x00080cb6, 0x00060111, 0x00000a1b }, { 8, 0x00022020, 0x00080cba, 0x00060111, 0x00000a1b }, { 9, 0x00022020, 0x00080cbe, 0x00060111, 0x00000a1b }, { 10, 0x00022020, 0x00080d02, 0x00060111, 0x00000a1b }, { 11, 0x00022020, 0x00080d06, 0x00060111, 0x00000a1b }, { 12, 0x00022020, 0x00080d0a, 0x00060111, 0x00000a1b }, { 13, 0x00022020, 0x00080d0e, 0x00060111, 0x00000a1b }, { 14, 0x00022020, 0x00080d1a, 0x00060111, 0x00000a03 }, }; /* * RF value list for RF2525e * Supports: 2.4 GHz */ static const struct rf_channel rf_vals_bg_2525e[] = { { 1, 0x00022010, 0x0000089a, 0x00060111, 0x00000e1b }, { 2, 0x00022010, 0x0000089e, 0x00060111, 0x00000e07 }, { 3, 0x00022010, 0x0000089e, 0x00060111, 0x00000e1b }, { 4, 0x00022010, 0x000008a2, 0x00060111, 0x00000e07 }, { 5, 0x00022010, 0x000008a2, 0x00060111, 0x00000e1b }, { 6, 0x00022010, 0x000008a6, 0x00060111, 0x00000e07 }, { 7, 0x00022010, 0x000008a6, 0x00060111, 0x00000e1b }, { 8, 0x00022010, 0x000008aa, 0x00060111, 0x00000e07 }, { 9, 0x00022010, 0x000008aa, 0x00060111, 0x00000e1b }, { 10, 0x00022010, 0x000008ae, 0x00060111, 0x00000e07 }, { 11, 0x00022010, 0x000008ae, 0x00060111, 0x00000e1b }, { 12, 0x00022010, 0x000008b2, 0x00060111, 0x00000e07 }, { 13, 0x00022010, 0x000008b2, 0x00060111, 0x00000e1b }, { 14, 0x00022010, 0x000008b6, 0x00060111, 0x00000e23 }, }; /* * RF value list for RF5222 * Supports: 2.4 GHz & 5.2 GHz */ static const struct rf_channel rf_vals_5222[] = { { 1, 0x00022020, 0x00001136, 0x00000101, 0x00000a0b }, { 2, 0x00022020, 0x0000113a, 0x00000101, 0x00000a0b }, { 3, 0x00022020, 0x0000113e, 0x00000101, 0x00000a0b }, { 4, 0x00022020, 0x00001182, 0x00000101, 0x00000a0b }, { 5, 0x00022020, 0x00001186, 0x00000101, 0x00000a0b }, { 6, 0x00022020, 0x0000118a, 0x00000101, 0x00000a0b }, { 7, 0x00022020, 0x0000118e, 0x00000101, 0x00000a0b }, { 8, 0x00022020, 0x00001192, 0x00000101, 0x00000a0b }, { 9, 0x00022020, 0x00001196, 0x00000101, 0x00000a0b }, { 10, 0x00022020, 0x0000119a, 0x00000101, 0x00000a0b }, { 11, 0x00022020, 0x0000119e, 0x00000101, 0x00000a0b }, { 12, 0x00022020, 0x000011a2, 0x00000101, 0x00000a0b }, { 13, 0x00022020, 0x000011a6, 0x00000101, 0x00000a0b }, { 14, 0x00022020, 0x000011ae, 0x00000101, 0x00000a1b }, /* 802.11 UNI / HyperLan 2 */ { 36, 0x00022010, 0x00018896, 0x00000101, 0x00000a1f }, { 40, 0x00022010, 0x0001889a, 0x00000101, 0x00000a1f }, { 44, 0x00022010, 0x0001889e, 0x00000101, 0x00000a1f }, { 48, 0x00022010, 0x000188a2, 0x00000101, 0x00000a1f }, { 52, 0x00022010, 0x000188a6, 0x00000101, 0x00000a1f }, { 66, 0x00022010, 0x000188aa, 0x00000101, 0x00000a1f }, { 60, 0x00022010, 0x000188ae, 0x00000101, 0x00000a1f }, { 64, 0x00022010, 0x000188b2, 0x00000101, 0x00000a1f }, /* 802.11 HyperLan 2 */ { 100, 0x00022010, 0x00008802, 0x00000101, 0x00000a0f }, { 104, 0x00022010, 0x00008806, 0x00000101, 0x00000a0f }, { 108, 0x00022010, 0x0000880a, 0x00000101, 0x00000a0f }, { 112, 0x00022010, 0x0000880e, 0x00000101, 0x00000a0f }, { 116, 0x00022010, 0x00008812, 0x00000101, 0x00000a0f }, { 120, 0x00022010, 0x00008816, 0x00000101, 0x00000a0f }, { 124, 0x00022010, 0x0000881a, 0x00000101, 0x00000a0f }, { 128, 0x00022010, 0x0000881e, 0x00000101, 0x00000a0f }, { 132, 0x00022010, 0x00008822, 0x00000101, 0x00000a0f }, { 136, 0x00022010, 0x00008826, 0x00000101, 0x00000a0f }, /* 802.11 UNII */ { 140, 0x00022010, 0x0000882a, 0x00000101, 0x00000a0f }, { 149, 0x00022020, 0x000090a6, 0x00000101, 0x00000a07 }, { 153, 0x00022020, 0x000090ae, 0x00000101, 0x00000a07 }, { 157, 0x00022020, 0x000090b6, 0x00000101, 0x00000a07 }, { 161, 0x00022020, 0x000090be, 0x00000101, 0x00000a07 }, }; static int rt2500usb_probe_hw_mode(struct rt2x00_dev *rt2x00dev) { struct hw_mode_spec *spec = &rt2x00dev->spec; struct channel_info *info; char *tx_power; unsigned int i; /* * Initialize all hw fields. * * Don't set IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING unless we are * capable of sending the buffered frames out after the DTIM * transmission using rt2x00lib_beacondone. This will send out * multicast and broadcast traffic immediately instead of buffering it * infinitly and thus dropping it after some time. */ rt2x00dev->hw->flags = IEEE80211_HW_RX_INCLUDES_FCS | IEEE80211_HW_SIGNAL_DBM | IEEE80211_HW_SUPPORTS_PS | IEEE80211_HW_PS_NULLFUNC_STACK; SET_IEEE80211_DEV(rt2x00dev->hw, rt2x00dev->dev); SET_IEEE80211_PERM_ADDR(rt2x00dev->hw, rt2x00_eeprom_addr(rt2x00dev, EEPROM_MAC_ADDR_0)); /* * Initialize hw_mode information. */ spec->supported_bands = SUPPORT_BAND_2GHZ; spec->supported_rates = SUPPORT_RATE_CCK | SUPPORT_RATE_OFDM; if (rt2x00_rf(rt2x00dev, RF2522)) { spec->num_channels = ARRAY_SIZE(rf_vals_bg_2522); spec->channels = rf_vals_bg_2522; } else if (rt2x00_rf(rt2x00dev, RF2523)) { spec->num_channels = ARRAY_SIZE(rf_vals_bg_2523); spec->channels = rf_vals_bg_2523; } else if (rt2x00_rf(rt2x00dev, RF2524)) { spec->num_channels = ARRAY_SIZE(rf_vals_bg_2524); spec->channels = rf_vals_bg_2524; } else if (rt2x00_rf(rt2x00dev, RF2525)) { spec->num_channels = ARRAY_SIZE(rf_vals_bg_2525); spec->channels = rf_vals_bg_2525; } else if (rt2x00_rf(rt2x00dev, RF2525E)) { spec->num_channels = ARRAY_SIZE(rf_vals_bg_2525e); spec->channels = rf_vals_bg_2525e; } else if (rt2x00_rf(rt2x00dev, RF5222)) { spec->supported_bands |= SUPPORT_BAND_5GHZ; spec->num_channels = ARRAY_SIZE(rf_vals_5222); spec->channels = rf_vals_5222; } /* * Create channel information array */ info = kcalloc(spec->num_channels, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; spec->channels_info = info; tx_power = rt2x00_eeprom_addr(rt2x00dev, EEPROM_TXPOWER_START); for (i = 0; i < 14; i++) { info[i].max_power = MAX_TXPOWER; info[i].default_power1 = TXPOWER_FROM_DEV(tx_power[i]); } if (spec->num_channels > 14) { for (i = 14; i < spec->num_channels; i++) { info[i].max_power = MAX_TXPOWER; info[i].default_power1 = DEFAULT_TXPOWER; } } return 0; } static int rt2500usb_probe_hw(struct rt2x00_dev *rt2x00dev) { int retval; /* * Allocate eeprom data. */ retval = rt2500usb_validate_eeprom(rt2x00dev); if (retval) return retval; retval = rt2500usb_init_eeprom(rt2x00dev); if (retval) return retval; /* * Initialize hw specifications. */ retval = rt2500usb_probe_hw_mode(rt2x00dev); if (retval) return retval; /* * This device requires the atim queue */ __set_bit(REQUIRE_ATIM_QUEUE, &rt2x00dev->cap_flags); __set_bit(REQUIRE_BEACON_GUARD, &rt2x00dev->cap_flags); if (!modparam_nohwcrypt) { __set_bit(CAPABILITY_HW_CRYPTO, &rt2x00dev->cap_flags); __set_bit(REQUIRE_COPY_IV, &rt2x00dev->cap_flags); } __set_bit(REQUIRE_SW_SEQNO, &rt2x00dev->cap_flags); __set_bit(REQUIRE_PS_AUTOWAKE, &rt2x00dev->cap_flags); /* * Set the rssi offset. */ rt2x00dev->rssi_offset = DEFAULT_RSSI_OFFSET; return 0; } static const struct ieee80211_ops rt2500usb_mac80211_ops = { .tx = rt2x00mac_tx, .start = rt2x00mac_start, .stop = rt2x00mac_stop, .add_interface = rt2x00mac_add_interface, .remove_interface = rt2x00mac_remove_interface, .config = rt2x00mac_config, .configure_filter = rt2x00mac_configure_filter, .set_tim = rt2x00mac_set_tim, .set_key = rt2x00mac_set_key, .sw_scan_start = rt2x00mac_sw_scan_start, .sw_scan_complete = rt2x00mac_sw_scan_complete, .get_stats = rt2x00mac_get_stats, .bss_info_changed = rt2x00mac_bss_info_changed, .conf_tx = rt2x00mac_conf_tx, .rfkill_poll = rt2x00mac_rfkill_poll, .flush = rt2x00mac_flush, .set_antenna = rt2x00mac_set_antenna, .get_antenna = rt2x00mac_get_antenna, .get_ringparam = rt2x00mac_get_ringparam, .tx_frames_pending = rt2x00mac_tx_frames_pending, }; static const struct rt2x00lib_ops rt2500usb_rt2x00_ops = { .probe_hw = rt2500usb_probe_hw, .initialize = rt2x00usb_initialize, .uninitialize = rt2x00usb_uninitialize, .clear_entry = rt2x00usb_clear_entry, .set_device_state = rt2500usb_set_device_state, .rfkill_poll = rt2500usb_rfkill_poll, .link_stats = rt2500usb_link_stats, .reset_tuner = rt2500usb_reset_tuner, .watchdog = rt2x00usb_watchdog, .start_queue = rt2500usb_start_queue, .kick_queue = rt2x00usb_kick_queue, .stop_queue = rt2500usb_stop_queue, .flush_queue = rt2x00usb_flush_queue, .write_tx_desc = rt2500usb_write_tx_desc, .write_beacon = rt2500usb_write_beacon, .get_tx_data_len = rt2500usb_get_tx_data_len, .fill_rxdone = rt2500usb_fill_rxdone, .config_shared_key = rt2500usb_config_key, .config_pairwise_key = rt2500usb_config_key, .config_filter = rt2500usb_config_filter, .config_intf = rt2500usb_config_intf, .config_erp = rt2500usb_config_erp, .config_ant = rt2500usb_config_ant, .config = rt2500usb_config, }; static const struct data_queue_desc rt2500usb_queue_rx = { .entry_num = 32, .data_size = DATA_FRAME_SIZE, .desc_size = RXD_DESC_SIZE, .priv_size = sizeof(struct queue_entry_priv_usb), }; static const struct data_queue_desc rt2500usb_queue_tx = { .entry_num = 32, .data_size = DATA_FRAME_SIZE, .desc_size = TXD_DESC_SIZE, .priv_size = sizeof(struct queue_entry_priv_usb), }; static const struct data_queue_desc rt2500usb_queue_bcn = { .entry_num = 1, .data_size = MGMT_FRAME_SIZE, .desc_size = TXD_DESC_SIZE, .priv_size = sizeof(struct queue_entry_priv_usb_bcn), }; static const struct data_queue_desc rt2500usb_queue_atim = { .entry_num = 8, .data_size = DATA_FRAME_SIZE, .desc_size = TXD_DESC_SIZE, .priv_size = sizeof(struct queue_entry_priv_usb), }; static const struct rt2x00_ops rt2500usb_ops = { .name = KBUILD_MODNAME, .max_sta_intf = 1, .max_ap_intf = 1, .eeprom_size = EEPROM_SIZE, .rf_size = RF_SIZE, .tx_queues = NUM_TX_QUEUES, .extra_tx_headroom = TXD_DESC_SIZE, .rx = &rt2500usb_queue_rx, .tx = &rt2500usb_queue_tx, .bcn = &rt2500usb_queue_bcn, .atim = &rt2500usb_queue_atim, .lib = &rt2500usb_rt2x00_ops, .hw = &rt2500usb_mac80211_ops, #ifdef CONFIG_RT2X00_LIB_DEBUGFS .debugfs = &rt2500usb_rt2x00debug, #endif /* CONFIG_RT2X00_LIB_DEBUGFS */ }; /* * rt2500usb module information. */ static struct usb_device_id rt2500usb_device_table[] = { /* ASUS */ { USB_DEVICE(0x0b05, 0x1706) }, { USB_DEVICE(0x0b05, 0x1707) }, /* Belkin */ { USB_DEVICE(0x050d, 0x7050) }, { USB_DEVICE(0x050d, 0x7051) }, /* Cisco Systems */ { USB_DEVICE(0x13b1, 0x000d) }, { USB_DEVICE(0x13b1, 0x0011) }, { USB_DEVICE(0x13b1, 0x001a) }, /* Conceptronic */ { USB_DEVICE(0x14b2, 0x3c02) }, /* D-LINK */ { USB_DEVICE(0x2001, 0x3c00) }, /* Gigabyte */ { USB_DEVICE(0x1044, 0x8001) }, { USB_DEVICE(0x1044, 0x8007) }, /* Hercules */ { USB_DEVICE(0x06f8, 0xe000) }, /* Melco */ { USB_DEVICE(0x0411, 0x005e) }, { USB_DEVICE(0x0411, 0x0066) }, { USB_DEVICE(0x0411, 0x0067) }, { USB_DEVICE(0x0411, 0x008b) }, { USB_DEVICE(0x0411, 0x0097) }, /* MSI */ { USB_DEVICE(0x0db0, 0x6861) }, { USB_DEVICE(0x0db0, 0x6865) }, { USB_DEVICE(0x0db0, 0x6869) }, /* Ralink */ { USB_DEVICE(0x148f, 0x1706) }, { USB_DEVICE(0x148f, 0x2570) }, { USB_DEVICE(0x148f, 0x9020) }, /* Sagem */ { USB_DEVICE(0x079b, 0x004b) }, /* Siemens */ { USB_DEVICE(0x0681, 0x3c06) }, /* SMC */ { USB_DEVICE(0x0707, 0xee13) }, /* Spairon */ { USB_DEVICE(0x114b, 0x0110) }, /* SURECOM */ { USB_DEVICE(0x0769, 0x11f3) }, /* Trust */ { USB_DEVICE(0x0eb0, 0x9020) }, /* VTech */ { USB_DEVICE(0x0f88, 0x3012) }, /* Zinwell */ { USB_DEVICE(0x5a57, 0x0260) }, { 0, } }; MODULE_AUTHOR(DRV_PROJECT); MODULE_VERSION(DRV_VERSION); MODULE_DESCRIPTION("Ralink RT2500 USB Wireless LAN driver."); MODULE_SUPPORTED_DEVICE("Ralink RT2570 USB chipset based cards"); MODULE_DEVICE_TABLE(usb, rt2500usb_device_table); MODULE_LICENSE("GPL"); static int rt2500usb_probe(struct usb_interface *usb_intf, const struct usb_device_id *id) { return rt2x00usb_probe(usb_intf, &rt2500usb_ops); } static struct usb_driver rt2500usb_driver = { .name = KBUILD_MODNAME, .id_table = rt2500usb_device_table, .probe = rt2500usb_probe, .disconnect = rt2x00usb_disconnect, .suspend = rt2x00usb_suspend, .resume = rt2x00usb_resume, }; module_usb_driver(rt2500usb_driver);
gpl-2.0
tobigun/samsung-kernel-smg800f
drivers/isdn/mISDN/socket.c
4119
18384
/* * * Author Karsten Keil <kkeil@novell.com> * * Copyright 2008 by Karsten Keil <kkeil@novell.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/mISDNif.h> #include <linux/slab.h> #include <linux/export.h> #include "core.h" static u_int *debug; static struct proto mISDN_proto = { .name = "misdn", .owner = THIS_MODULE, .obj_size = sizeof(struct mISDN_sock) }; #define _pms(sk) ((struct mISDN_sock *)sk) static struct mISDN_sock_list data_sockets = { .lock = __RW_LOCK_UNLOCKED(data_sockets.lock) }; static struct mISDN_sock_list base_sockets = { .lock = __RW_LOCK_UNLOCKED(base_sockets.lock) }; #define L2_HEADER_LEN 4 static inline struct sk_buff * _l2_alloc_skb(unsigned int len, gfp_t gfp_mask) { struct sk_buff *skb; skb = alloc_skb(len + L2_HEADER_LEN, gfp_mask); if (likely(skb)) skb_reserve(skb, L2_HEADER_LEN); return skb; } static void mISDN_sock_link(struct mISDN_sock_list *l, struct sock *sk) { write_lock_bh(&l->lock); sk_add_node(sk, &l->head); write_unlock_bh(&l->lock); } static void mISDN_sock_unlink(struct mISDN_sock_list *l, struct sock *sk) { write_lock_bh(&l->lock); sk_del_node_init(sk); write_unlock_bh(&l->lock); } static int mISDN_send(struct mISDNchannel *ch, struct sk_buff *skb) { struct mISDN_sock *msk; int err; msk = container_of(ch, struct mISDN_sock, ch); if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s len %d %p\n", __func__, skb->len, skb); if (msk->sk.sk_state == MISDN_CLOSED) return -EUNATCH; __net_timestamp(skb); err = sock_queue_rcv_skb(&msk->sk, skb); if (err) printk(KERN_WARNING "%s: error %d\n", __func__, err); return err; } static int mISDN_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg) { struct mISDN_sock *msk; msk = container_of(ch, struct mISDN_sock, ch); if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s(%p, %x, %p)\n", __func__, ch, cmd, arg); switch (cmd) { case CLOSE_CHANNEL: msk->sk.sk_state = MISDN_CLOSED; break; } return 0; } static inline void mISDN_sock_cmsg(struct sock *sk, struct msghdr *msg, struct sk_buff *skb) { struct timeval tv; if (_pms(sk)->cmask & MISDN_TIME_STAMP) { skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_MISDN, MISDN_TIME_STAMP, sizeof(tv), &tv); } } static int mISDN_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sk_buff *skb; struct sock *sk = sock->sk; struct sockaddr_mISDN *maddr; int copied, err; if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s: len %d, flags %x ch.nr %d, proto %x\n", __func__, (int)len, flags, _pms(sk)->ch.nr, sk->sk_protocol); if (flags & (MSG_OOB)) return -EOPNOTSUPP; if (sk->sk_state == MISDN_CLOSED) return 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); if (!skb) return err; if (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) { msg->msg_namelen = sizeof(struct sockaddr_mISDN); maddr = (struct sockaddr_mISDN *)msg->msg_name; maddr->family = AF_ISDN; maddr->dev = _pms(sk)->dev->id; if ((sk->sk_protocol == ISDN_P_LAPD_TE) || (sk->sk_protocol == ISDN_P_LAPD_NT)) { maddr->channel = (mISDN_HEAD_ID(skb) >> 16) & 0xff; maddr->tei = (mISDN_HEAD_ID(skb) >> 8) & 0xff; maddr->sapi = mISDN_HEAD_ID(skb) & 0xff; } else { maddr->channel = _pms(sk)->ch.nr; maddr->sapi = _pms(sk)->ch.addr & 0xFF; maddr->tei = (_pms(sk)->ch.addr >> 8) & 0xFF; } } else { if (msg->msg_namelen) printk(KERN_WARNING "%s: too small namelen %d\n", __func__, msg->msg_namelen); msg->msg_namelen = 0; } copied = skb->len + MISDN_HEADER_LEN; if (len < copied) { if (flags & MSG_PEEK) atomic_dec(&skb->users); else skb_queue_head(&sk->sk_receive_queue, skb); return -ENOSPC; } memcpy(skb_push(skb, MISDN_HEADER_LEN), mISDN_HEAD_P(skb), MISDN_HEADER_LEN); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); mISDN_sock_cmsg(sk, msg, skb); skb_free_datagram(sk, skb); return err ? : copied; } static int mISDN_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct sk_buff *skb; int err = -ENOMEM; struct sockaddr_mISDN *maddr; if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s: len %d flags %x ch %d proto %x\n", __func__, (int)len, msg->msg_flags, _pms(sk)->ch.nr, sk->sk_protocol); if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_ERRQUEUE)) return -EINVAL; if (len < MISDN_HEADER_LEN) return -EINVAL; if (sk->sk_state != MISDN_BOUND) return -EBADFD; lock_sock(sk); skb = _l2_alloc_skb(len, GFP_KERNEL); if (!skb) goto done; if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { err = -EFAULT; goto done; } memcpy(mISDN_HEAD_P(skb), skb->data, MISDN_HEADER_LEN); skb_pull(skb, MISDN_HEADER_LEN); if (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) { /* if we have a address, we use it */ maddr = (struct sockaddr_mISDN *)msg->msg_name; mISDN_HEAD_ID(skb) = maddr->channel; } else { /* use default for L2 messages */ if ((sk->sk_protocol == ISDN_P_LAPD_TE) || (sk->sk_protocol == ISDN_P_LAPD_NT)) mISDN_HEAD_ID(skb) = _pms(sk)->ch.nr; } if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s: ID:%x\n", __func__, mISDN_HEAD_ID(skb)); err = -ENODEV; if (!_pms(sk)->ch.peer) goto done; err = _pms(sk)->ch.recv(_pms(sk)->ch.peer, skb); if (err) goto done; else { skb = NULL; err = len; } done: if (skb) kfree_skb(skb); release_sock(sk); return err; } static int data_sock_release(struct socket *sock) { struct sock *sk = sock->sk; if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk); if (!sk) return 0; switch (sk->sk_protocol) { case ISDN_P_TE_S0: case ISDN_P_NT_S0: case ISDN_P_TE_E1: case ISDN_P_NT_E1: if (sk->sk_state == MISDN_BOUND) delete_channel(&_pms(sk)->ch); else mISDN_sock_unlink(&data_sockets, sk); break; case ISDN_P_LAPD_TE: case ISDN_P_LAPD_NT: case ISDN_P_B_RAW: case ISDN_P_B_HDLC: case ISDN_P_B_X75SLP: case ISDN_P_B_L2DTMF: case ISDN_P_B_L2DSP: case ISDN_P_B_L2DSPHDLC: delete_channel(&_pms(sk)->ch); mISDN_sock_unlink(&data_sockets, sk); break; } lock_sock(sk); sock_orphan(sk); skb_queue_purge(&sk->sk_receive_queue); release_sock(sk); sock_put(sk); return 0; } static int data_sock_ioctl_bound(struct sock *sk, unsigned int cmd, void __user *p) { struct mISDN_ctrl_req cq; int err = -EINVAL, val[2]; struct mISDNchannel *bchan, *next; lock_sock(sk); if (!_pms(sk)->dev) { err = -ENODEV; goto done; } switch (cmd) { case IMCTRLREQ: if (copy_from_user(&cq, p, sizeof(cq))) { err = -EFAULT; break; } if ((sk->sk_protocol & ~ISDN_P_B_MASK) == ISDN_P_B_START) { list_for_each_entry_safe(bchan, next, &_pms(sk)->dev->bchannels, list) { if (bchan->nr == cq.channel) { err = bchan->ctrl(bchan, CONTROL_CHANNEL, &cq); break; } } } else err = _pms(sk)->dev->D.ctrl(&_pms(sk)->dev->D, CONTROL_CHANNEL, &cq); if (err) break; if (copy_to_user(p, &cq, sizeof(cq))) err = -EFAULT; break; case IMCLEAR_L2: if (sk->sk_protocol != ISDN_P_LAPD_NT) { err = -EINVAL; break; } val[0] = cmd; if (get_user(val[1], (int __user *)p)) { err = -EFAULT; break; } err = _pms(sk)->dev->teimgr->ctrl(_pms(sk)->dev->teimgr, CONTROL_CHANNEL, val); break; case IMHOLD_L1: if (sk->sk_protocol != ISDN_P_LAPD_NT && sk->sk_protocol != ISDN_P_LAPD_TE) { err = -EINVAL; break; } val[0] = cmd; if (get_user(val[1], (int __user *)p)) { err = -EFAULT; break; } err = _pms(sk)->dev->teimgr->ctrl(_pms(sk)->dev->teimgr, CONTROL_CHANNEL, val); break; default: err = -EINVAL; break; } done: release_sock(sk); return err; } static int data_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { int err = 0, id; struct sock *sk = sock->sk; struct mISDNdevice *dev; struct mISDNversion ver; switch (cmd) { case IMGETVERSION: ver.major = MISDN_MAJOR_VERSION; ver.minor = MISDN_MINOR_VERSION; ver.release = MISDN_RELEASE; if (copy_to_user((void __user *)arg, &ver, sizeof(ver))) err = -EFAULT; break; case IMGETCOUNT: id = get_mdevice_count(); if (put_user(id, (int __user *)arg)) err = -EFAULT; break; case IMGETDEVINFO: if (get_user(id, (int __user *)arg)) { err = -EFAULT; break; } dev = get_mdevice(id); if (dev) { struct mISDN_devinfo di; memset(&di, 0, sizeof(di)); di.id = dev->id; di.Dprotocols = dev->Dprotocols; di.Bprotocols = dev->Bprotocols | get_all_Bprotocols(); di.protocol = dev->D.protocol; memcpy(di.channelmap, dev->channelmap, sizeof(di.channelmap)); di.nrbchan = dev->nrbchan; strcpy(di.name, dev_name(&dev->dev)); if (copy_to_user((void __user *)arg, &di, sizeof(di))) err = -EFAULT; } else err = -ENODEV; break; default: if (sk->sk_state == MISDN_BOUND) err = data_sock_ioctl_bound(sk, cmd, (void __user *)arg); else err = -ENOTCONN; } return err; } static int data_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int len) { struct sock *sk = sock->sk; int err = 0, opt = 0; if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s(%p, %d, %x, %p, %d)\n", __func__, sock, level, optname, optval, len); lock_sock(sk); switch (optname) { case MISDN_TIME_STAMP: if (get_user(opt, (int __user *)optval)) { err = -EFAULT; break; } if (opt) _pms(sk)->cmask |= MISDN_TIME_STAMP; else _pms(sk)->cmask &= ~MISDN_TIME_STAMP; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int data_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int len, opt; if (get_user(len, optlen)) return -EFAULT; if (len != sizeof(char)) return -EINVAL; switch (optname) { case MISDN_TIME_STAMP: if (_pms(sk)->cmask & MISDN_TIME_STAMP) opt = 1; else opt = 0; if (put_user(opt, optval)) return -EFAULT; break; default: return -ENOPROTOOPT; } return 0; } static int data_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr; struct sock *sk = sock->sk; struct hlist_node *node; struct sock *csk; int err = 0; if (*debug & DEBUG_SOCKET) printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk); if (addr_len != sizeof(struct sockaddr_mISDN)) return -EINVAL; if (!maddr || maddr->family != AF_ISDN) return -EINVAL; lock_sock(sk); if (_pms(sk)->dev) { err = -EALREADY; goto done; } _pms(sk)->dev = get_mdevice(maddr->dev); if (!_pms(sk)->dev) { err = -ENODEV; goto done; } if (sk->sk_protocol < ISDN_P_B_START) { read_lock_bh(&data_sockets.lock); sk_for_each(csk, node, &data_sockets.head) { if (sk == csk) continue; if (_pms(csk)->dev != _pms(sk)->dev) continue; if (csk->sk_protocol >= ISDN_P_B_START) continue; if (IS_ISDN_P_TE(csk->sk_protocol) == IS_ISDN_P_TE(sk->sk_protocol)) continue; read_unlock_bh(&data_sockets.lock); err = -EBUSY; goto done; } read_unlock_bh(&data_sockets.lock); } _pms(sk)->ch.send = mISDN_send; _pms(sk)->ch.ctrl = mISDN_ctrl; switch (sk->sk_protocol) { case ISDN_P_TE_S0: case ISDN_P_NT_S0: case ISDN_P_TE_E1: case ISDN_P_NT_E1: mISDN_sock_unlink(&data_sockets, sk); err = connect_layer1(_pms(sk)->dev, &_pms(sk)->ch, sk->sk_protocol, maddr); if (err) mISDN_sock_link(&data_sockets, sk); break; case ISDN_P_LAPD_TE: case ISDN_P_LAPD_NT: err = create_l2entity(_pms(sk)->dev, &_pms(sk)->ch, sk->sk_protocol, maddr); break; case ISDN_P_B_RAW: case ISDN_P_B_HDLC: case ISDN_P_B_X75SLP: case ISDN_P_B_L2DTMF: case ISDN_P_B_L2DSP: case ISDN_P_B_L2DSPHDLC: err = connect_Bstack(_pms(sk)->dev, &_pms(sk)->ch, sk->sk_protocol, maddr); break; default: err = -EPROTONOSUPPORT; } if (err) goto done; sk->sk_state = MISDN_BOUND; _pms(sk)->ch.protocol = sk->sk_protocol; done: release_sock(sk); return err; } static int data_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr; struct sock *sk = sock->sk; if (!_pms(sk)->dev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*maddr); maddr->dev = _pms(sk)->dev->id; maddr->channel = _pms(sk)->ch.nr; maddr->sapi = _pms(sk)->ch.addr & 0xff; maddr->tei = (_pms(sk)->ch.addr >> 8) & 0xff; release_sock(sk); return 0; } static const struct proto_ops data_sock_ops = { .family = PF_ISDN, .owner = THIS_MODULE, .release = data_sock_release, .ioctl = data_sock_ioctl, .bind = data_sock_bind, .getname = data_sock_getname, .sendmsg = mISDN_sock_sendmsg, .recvmsg = mISDN_sock_recvmsg, .poll = datagram_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = data_sock_setsockopt, .getsockopt = data_sock_getsockopt, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .mmap = sock_no_mmap }; static int data_sock_create(struct net *net, struct socket *sock, int protocol) { struct sock *sk; if (sock->type != SOCK_DGRAM) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &data_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = MISDN_OPEN; mISDN_sock_link(&data_sockets, sk); return 0; } static int base_sock_release(struct socket *sock) { struct sock *sk = sock->sk; printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk); if (!sk) return 0; mISDN_sock_unlink(&base_sockets, sk); sock_orphan(sk); sock_put(sk); return 0; } static int base_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { int err = 0, id; struct mISDNdevice *dev; struct mISDNversion ver; switch (cmd) { case IMGETVERSION: ver.major = MISDN_MAJOR_VERSION; ver.minor = MISDN_MINOR_VERSION; ver.release = MISDN_RELEASE; if (copy_to_user((void __user *)arg, &ver, sizeof(ver))) err = -EFAULT; break; case IMGETCOUNT: id = get_mdevice_count(); if (put_user(id, (int __user *)arg)) err = -EFAULT; break; case IMGETDEVINFO: if (get_user(id, (int __user *)arg)) { err = -EFAULT; break; } dev = get_mdevice(id); if (dev) { struct mISDN_devinfo di; memset(&di, 0, sizeof(di)); di.id = dev->id; di.Dprotocols = dev->Dprotocols; di.Bprotocols = dev->Bprotocols | get_all_Bprotocols(); di.protocol = dev->D.protocol; memcpy(di.channelmap, dev->channelmap, sizeof(di.channelmap)); di.nrbchan = dev->nrbchan; strcpy(di.name, dev_name(&dev->dev)); if (copy_to_user((void __user *)arg, &di, sizeof(di))) err = -EFAULT; } else err = -ENODEV; break; case IMSETDEVNAME: { struct mISDN_devrename dn; if (copy_from_user(&dn, (void __user *)arg, sizeof(dn))) { err = -EFAULT; break; } dev = get_mdevice(dn.id); if (dev) err = device_rename(&dev->dev, dn.name); else err = -ENODEV; } break; default: err = -EINVAL; } return err; } static int base_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr; struct sock *sk = sock->sk; int err = 0; if (!maddr || maddr->family != AF_ISDN) return -EINVAL; lock_sock(sk); if (_pms(sk)->dev) { err = -EALREADY; goto done; } _pms(sk)->dev = get_mdevice(maddr->dev); if (!_pms(sk)->dev) { err = -ENODEV; goto done; } sk->sk_state = MISDN_BOUND; done: release_sock(sk); return err; } static const struct proto_ops base_sock_ops = { .family = PF_ISDN, .owner = THIS_MODULE, .release = base_sock_release, .ioctl = base_sock_ioctl, .bind = base_sock_bind, .getname = sock_no_getname, .sendmsg = sock_no_sendmsg, .recvmsg = sock_no_recvmsg, .poll = sock_no_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .mmap = sock_no_mmap }; static int base_sock_create(struct net *net, struct socket *sock, int protocol) { struct sock *sk; if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &base_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = MISDN_OPEN; mISDN_sock_link(&base_sockets, sk); return 0; } static int mISDN_sock_create(struct net *net, struct socket *sock, int proto, int kern) { int err = -EPROTONOSUPPORT; switch (proto) { case ISDN_P_BASE: err = base_sock_create(net, sock, proto); break; case ISDN_P_TE_S0: case ISDN_P_NT_S0: case ISDN_P_TE_E1: case ISDN_P_NT_E1: case ISDN_P_LAPD_TE: case ISDN_P_LAPD_NT: case ISDN_P_B_RAW: case ISDN_P_B_HDLC: case ISDN_P_B_X75SLP: case ISDN_P_B_L2DTMF: case ISDN_P_B_L2DSP: case ISDN_P_B_L2DSPHDLC: err = data_sock_create(net, sock, proto); break; default: return err; } return err; } static const struct net_proto_family mISDN_sock_family_ops = { .owner = THIS_MODULE, .family = PF_ISDN, .create = mISDN_sock_create, }; int misdn_sock_init(u_int *deb) { int err; debug = deb; err = sock_register(&mISDN_sock_family_ops); if (err) printk(KERN_ERR "%s: error(%d)\n", __func__, err); return err; } void misdn_sock_cleanup(void) { sock_unregister(PF_ISDN); }
gpl-2.0
ststeiger/pmfs
drivers/isdn/mISDN/stack.c
4375
16871
/* * * Author Karsten Keil <kkeil@novell.com> * * Copyright 2008 by Karsten Keil <kkeil@novell.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/slab.h> #include <linux/mISDNif.h> #include <linux/kthread.h> #include <linux/sched.h> #include "core.h" static u_int *debug; static inline void _queue_message(struct mISDNstack *st, struct sk_buff *skb) { struct mISDNhead *hh = mISDN_HEAD_P(skb); if (*debug & DEBUG_QUEUE_FUNC) printk(KERN_DEBUG "%s prim(%x) id(%x) %p\n", __func__, hh->prim, hh->id, skb); skb_queue_tail(&st->msgq, skb); if (likely(!test_bit(mISDN_STACK_STOPPED, &st->status))) { test_and_set_bit(mISDN_STACK_WORK, &st->status); wake_up_interruptible(&st->workq); } } static int mISDN_queue_message(struct mISDNchannel *ch, struct sk_buff *skb) { _queue_message(ch->st, skb); return 0; } static struct mISDNchannel * get_channel4id(struct mISDNstack *st, u_int id) { struct mISDNchannel *ch; mutex_lock(&st->lmutex); list_for_each_entry(ch, &st->layer2, list) { if (id == ch->nr) goto unlock; } ch = NULL; unlock: mutex_unlock(&st->lmutex); return ch; } static void send_socklist(struct mISDN_sock_list *sl, struct sk_buff *skb) { struct sock *sk; struct sk_buff *cskb = NULL; read_lock(&sl->lock); sk_for_each(sk, &sl->head) { if (sk->sk_state != MISDN_BOUND) continue; if (!cskb) cskb = skb_copy(skb, GFP_KERNEL); if (!cskb) { printk(KERN_WARNING "%s no skb\n", __func__); break; } if (!sock_queue_rcv_skb(sk, cskb)) cskb = NULL; } read_unlock(&sl->lock); if (cskb) dev_kfree_skb(cskb); } static void send_layer2(struct mISDNstack *st, struct sk_buff *skb) { struct sk_buff *cskb; struct mISDNhead *hh = mISDN_HEAD_P(skb); struct mISDNchannel *ch; int ret; if (!st) return; mutex_lock(&st->lmutex); if ((hh->id & MISDN_ID_ADDR_MASK) == MISDN_ID_ANY) { /* L2 for all */ list_for_each_entry(ch, &st->layer2, list) { if (list_is_last(&ch->list, &st->layer2)) { cskb = skb; skb = NULL; } else { cskb = skb_copy(skb, GFP_KERNEL); } if (cskb) { ret = ch->send(ch, cskb); if (ret) { if (*debug & DEBUG_SEND_ERR) printk(KERN_DEBUG "%s ch%d prim(%x) addr(%x)" " err %d\n", __func__, ch->nr, hh->prim, ch->addr, ret); dev_kfree_skb(cskb); } } else { printk(KERN_WARNING "%s ch%d addr %x no mem\n", __func__, ch->nr, ch->addr); goto out; } } } else { list_for_each_entry(ch, &st->layer2, list) { if ((hh->id & MISDN_ID_ADDR_MASK) == ch->addr) { ret = ch->send(ch, skb); if (!ret) skb = NULL; goto out; } } ret = st->dev->teimgr->ctrl(st->dev->teimgr, CHECK_DATA, skb); if (!ret) skb = NULL; else if (*debug & DEBUG_SEND_ERR) printk(KERN_DEBUG "%s mgr prim(%x) err %d\n", __func__, hh->prim, ret); } out: mutex_unlock(&st->lmutex); if (skb) dev_kfree_skb(skb); } static inline int send_msg_to_layer(struct mISDNstack *st, struct sk_buff *skb) { struct mISDNhead *hh = mISDN_HEAD_P(skb); struct mISDNchannel *ch; int lm; lm = hh->prim & MISDN_LAYERMASK; if (*debug & DEBUG_QUEUE_FUNC) printk(KERN_DEBUG "%s prim(%x) id(%x) %p\n", __func__, hh->prim, hh->id, skb); if (lm == 0x1) { if (!hlist_empty(&st->l1sock.head)) { __net_timestamp(skb); send_socklist(&st->l1sock, skb); } return st->layer1->send(st->layer1, skb); } else if (lm == 0x2) { if (!hlist_empty(&st->l1sock.head)) send_socklist(&st->l1sock, skb); send_layer2(st, skb); return 0; } else if (lm == 0x4) { ch = get_channel4id(st, hh->id); if (ch) return ch->send(ch, skb); else printk(KERN_WARNING "%s: dev(%s) prim(%x) id(%x) no channel\n", __func__, dev_name(&st->dev->dev), hh->prim, hh->id); } else if (lm == 0x8) { WARN_ON(lm == 0x8); ch = get_channel4id(st, hh->id); if (ch) return ch->send(ch, skb); else printk(KERN_WARNING "%s: dev(%s) prim(%x) id(%x) no channel\n", __func__, dev_name(&st->dev->dev), hh->prim, hh->id); } else { /* broadcast not handled yet */ printk(KERN_WARNING "%s: dev(%s) prim %x not delivered\n", __func__, dev_name(&st->dev->dev), hh->prim); } return -ESRCH; } static void do_clear_stack(struct mISDNstack *st) { } static int mISDNStackd(void *data) { struct mISDNstack *st = data; #ifdef MISDN_MSG_STATS cputime_t utime, stime; #endif int err = 0; sigfillset(&current->blocked); if (*debug & DEBUG_MSG_THREAD) printk(KERN_DEBUG "mISDNStackd %s started\n", dev_name(&st->dev->dev)); if (st->notify != NULL) { complete(st->notify); st->notify = NULL; } for (;;) { struct sk_buff *skb; if (unlikely(test_bit(mISDN_STACK_STOPPED, &st->status))) { test_and_clear_bit(mISDN_STACK_WORK, &st->status); test_and_clear_bit(mISDN_STACK_RUNNING, &st->status); } else test_and_set_bit(mISDN_STACK_RUNNING, &st->status); while (test_bit(mISDN_STACK_WORK, &st->status)) { skb = skb_dequeue(&st->msgq); if (!skb) { test_and_clear_bit(mISDN_STACK_WORK, &st->status); /* test if a race happens */ skb = skb_dequeue(&st->msgq); if (!skb) continue; test_and_set_bit(mISDN_STACK_WORK, &st->status); } #ifdef MISDN_MSG_STATS st->msg_cnt++; #endif err = send_msg_to_layer(st, skb); if (unlikely(err)) { if (*debug & DEBUG_SEND_ERR) printk(KERN_DEBUG "%s: %s prim(%x) id(%x) " "send call(%d)\n", __func__, dev_name(&st->dev->dev), mISDN_HEAD_PRIM(skb), mISDN_HEAD_ID(skb), err); dev_kfree_skb(skb); continue; } if (unlikely(test_bit(mISDN_STACK_STOPPED, &st->status))) { test_and_clear_bit(mISDN_STACK_WORK, &st->status); test_and_clear_bit(mISDN_STACK_RUNNING, &st->status); break; } } if (test_bit(mISDN_STACK_CLEARING, &st->status)) { test_and_set_bit(mISDN_STACK_STOPPED, &st->status); test_and_clear_bit(mISDN_STACK_RUNNING, &st->status); do_clear_stack(st); test_and_clear_bit(mISDN_STACK_CLEARING, &st->status); test_and_set_bit(mISDN_STACK_RESTART, &st->status); } if (test_and_clear_bit(mISDN_STACK_RESTART, &st->status)) { test_and_clear_bit(mISDN_STACK_STOPPED, &st->status); test_and_set_bit(mISDN_STACK_RUNNING, &st->status); if (!skb_queue_empty(&st->msgq)) test_and_set_bit(mISDN_STACK_WORK, &st->status); } if (test_bit(mISDN_STACK_ABORT, &st->status)) break; if (st->notify != NULL) { complete(st->notify); st->notify = NULL; } #ifdef MISDN_MSG_STATS st->sleep_cnt++; #endif test_and_clear_bit(mISDN_STACK_ACTIVE, &st->status); wait_event_interruptible(st->workq, (st->status & mISDN_STACK_ACTION_MASK)); if (*debug & DEBUG_MSG_THREAD) printk(KERN_DEBUG "%s: %s wake status %08lx\n", __func__, dev_name(&st->dev->dev), st->status); test_and_set_bit(mISDN_STACK_ACTIVE, &st->status); test_and_clear_bit(mISDN_STACK_WAKEUP, &st->status); if (test_bit(mISDN_STACK_STOPPED, &st->status)) { test_and_clear_bit(mISDN_STACK_RUNNING, &st->status); #ifdef MISDN_MSG_STATS st->stopped_cnt++; #endif } } #ifdef MISDN_MSG_STATS printk(KERN_DEBUG "mISDNStackd daemon for %s proceed %d " "msg %d sleep %d stopped\n", dev_name(&st->dev->dev), st->msg_cnt, st->sleep_cnt, st->stopped_cnt); task_cputime(st->thread, &utime, &stime); printk(KERN_DEBUG "mISDNStackd daemon for %s utime(%ld) stime(%ld)\n", dev_name(&st->dev->dev), utime, stime); printk(KERN_DEBUG "mISDNStackd daemon for %s nvcsw(%ld) nivcsw(%ld)\n", dev_name(&st->dev->dev), st->thread->nvcsw, st->thread->nivcsw); printk(KERN_DEBUG "mISDNStackd daemon for %s killed now\n", dev_name(&st->dev->dev)); #endif test_and_set_bit(mISDN_STACK_KILLED, &st->status); test_and_clear_bit(mISDN_STACK_RUNNING, &st->status); test_and_clear_bit(mISDN_STACK_ACTIVE, &st->status); test_and_clear_bit(mISDN_STACK_ABORT, &st->status); skb_queue_purge(&st->msgq); st->thread = NULL; if (st->notify != NULL) { complete(st->notify); st->notify = NULL; } return 0; } static int l1_receive(struct mISDNchannel *ch, struct sk_buff *skb) { if (!ch->st) return -ENODEV; __net_timestamp(skb); _queue_message(ch->st, skb); return 0; } void set_channel_address(struct mISDNchannel *ch, u_int sapi, u_int tei) { ch->addr = sapi | (tei << 8); } void __add_layer2(struct mISDNchannel *ch, struct mISDNstack *st) { list_add_tail(&ch->list, &st->layer2); } void add_layer2(struct mISDNchannel *ch, struct mISDNstack *st) { mutex_lock(&st->lmutex); __add_layer2(ch, st); mutex_unlock(&st->lmutex); } static int st_own_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg) { if (!ch->st || !ch->st->layer1) return -EINVAL; return ch->st->layer1->ctrl(ch->st->layer1, cmd, arg); } int create_stack(struct mISDNdevice *dev) { struct mISDNstack *newst; int err; DECLARE_COMPLETION_ONSTACK(done); newst = kzalloc(sizeof(struct mISDNstack), GFP_KERNEL); if (!newst) { printk(KERN_ERR "kmalloc mISDN_stack failed\n"); return -ENOMEM; } newst->dev = dev; INIT_LIST_HEAD(&newst->layer2); INIT_HLIST_HEAD(&newst->l1sock.head); rwlock_init(&newst->l1sock.lock); init_waitqueue_head(&newst->workq); skb_queue_head_init(&newst->msgq); mutex_init(&newst->lmutex); dev->D.st = newst; err = create_teimanager(dev); if (err) { printk(KERN_ERR "kmalloc teimanager failed\n"); kfree(newst); return err; } dev->teimgr->peer = &newst->own; dev->teimgr->recv = mISDN_queue_message; dev->teimgr->st = newst; newst->layer1 = &dev->D; dev->D.recv = l1_receive; dev->D.peer = &newst->own; newst->own.st = newst; newst->own.ctrl = st_own_ctrl; newst->own.send = mISDN_queue_message; newst->own.recv = mISDN_queue_message; if (*debug & DEBUG_CORE_FUNC) printk(KERN_DEBUG "%s: st(%s)\n", __func__, dev_name(&newst->dev->dev)); newst->notify = &done; newst->thread = kthread_run(mISDNStackd, (void *)newst, "mISDN_%s", dev_name(&newst->dev->dev)); if (IS_ERR(newst->thread)) { err = PTR_ERR(newst->thread); printk(KERN_ERR "mISDN:cannot create kernel thread for %s (%d)\n", dev_name(&newst->dev->dev), err); delete_teimanager(dev->teimgr); kfree(newst); } else wait_for_completion(&done); return err; } int connect_layer1(struct mISDNdevice *dev, struct mISDNchannel *ch, u_int protocol, struct sockaddr_mISDN *adr) { struct mISDN_sock *msk = container_of(ch, struct mISDN_sock, ch); struct channel_req rq; int err; if (*debug & DEBUG_CORE_FUNC) printk(KERN_DEBUG "%s: %s proto(%x) adr(%d %d %d %d)\n", __func__, dev_name(&dev->dev), protocol, adr->dev, adr->channel, adr->sapi, adr->tei); switch (protocol) { case ISDN_P_NT_S0: case ISDN_P_NT_E1: case ISDN_P_TE_S0: case ISDN_P_TE_E1: ch->recv = mISDN_queue_message; ch->peer = &dev->D.st->own; ch->st = dev->D.st; rq.protocol = protocol; rq.adr.channel = adr->channel; err = dev->D.ctrl(&dev->D, OPEN_CHANNEL, &rq); printk(KERN_DEBUG "%s: ret %d (dev %d)\n", __func__, err, dev->id); if (err) return err; write_lock_bh(&dev->D.st->l1sock.lock); sk_add_node(&msk->sk, &dev->D.st->l1sock.head); write_unlock_bh(&dev->D.st->l1sock.lock); break; default: return -ENOPROTOOPT; } return 0; } int connect_Bstack(struct mISDNdevice *dev, struct mISDNchannel *ch, u_int protocol, struct sockaddr_mISDN *adr) { struct channel_req rq, rq2; int pmask, err; struct Bprotocol *bp; if (*debug & DEBUG_CORE_FUNC) printk(KERN_DEBUG "%s: %s proto(%x) adr(%d %d %d %d)\n", __func__, dev_name(&dev->dev), protocol, adr->dev, adr->channel, adr->sapi, adr->tei); ch->st = dev->D.st; pmask = 1 << (protocol & ISDN_P_B_MASK); if (pmask & dev->Bprotocols) { rq.protocol = protocol; rq.adr = *adr; err = dev->D.ctrl(&dev->D, OPEN_CHANNEL, &rq); if (err) return err; ch->recv = rq.ch->send; ch->peer = rq.ch; rq.ch->recv = ch->send; rq.ch->peer = ch; rq.ch->st = dev->D.st; } else { bp = get_Bprotocol4mask(pmask); if (!bp) return -ENOPROTOOPT; rq2.protocol = protocol; rq2.adr = *adr; rq2.ch = ch; err = bp->create(&rq2); if (err) return err; ch->recv = rq2.ch->send; ch->peer = rq2.ch; rq2.ch->st = dev->D.st; rq.protocol = rq2.protocol; rq.adr = *adr; err = dev->D.ctrl(&dev->D, OPEN_CHANNEL, &rq); if (err) { rq2.ch->ctrl(rq2.ch, CLOSE_CHANNEL, NULL); return err; } rq2.ch->recv = rq.ch->send; rq2.ch->peer = rq.ch; rq.ch->recv = rq2.ch->send; rq.ch->peer = rq2.ch; rq.ch->st = dev->D.st; } ch->protocol = protocol; ch->nr = rq.ch->nr; return 0; } int create_l2entity(struct mISDNdevice *dev, struct mISDNchannel *ch, u_int protocol, struct sockaddr_mISDN *adr) { struct channel_req rq; int err; if (*debug & DEBUG_CORE_FUNC) printk(KERN_DEBUG "%s: %s proto(%x) adr(%d %d %d %d)\n", __func__, dev_name(&dev->dev), protocol, adr->dev, adr->channel, adr->sapi, adr->tei); rq.protocol = ISDN_P_TE_S0; if (dev->Dprotocols & (1 << ISDN_P_TE_E1)) rq.protocol = ISDN_P_TE_E1; switch (protocol) { case ISDN_P_LAPD_NT: rq.protocol = ISDN_P_NT_S0; if (dev->Dprotocols & (1 << ISDN_P_NT_E1)) rq.protocol = ISDN_P_NT_E1; case ISDN_P_LAPD_TE: ch->recv = mISDN_queue_message; ch->peer = &dev->D.st->own; ch->st = dev->D.st; rq.adr.channel = 0; err = dev->D.ctrl(&dev->D, OPEN_CHANNEL, &rq); printk(KERN_DEBUG "%s: ret 1 %d\n", __func__, err); if (err) break; rq.protocol = protocol; rq.adr = *adr; rq.ch = ch; err = dev->teimgr->ctrl(dev->teimgr, OPEN_CHANNEL, &rq); printk(KERN_DEBUG "%s: ret 2 %d\n", __func__, err); if (!err) { if ((protocol == ISDN_P_LAPD_NT) && !rq.ch) break; add_layer2(rq.ch, dev->D.st); rq.ch->recv = mISDN_queue_message; rq.ch->peer = &dev->D.st->own; rq.ch->ctrl(rq.ch, OPEN_CHANNEL, NULL); /* can't fail */ } break; default: err = -EPROTONOSUPPORT; } return err; } void delete_channel(struct mISDNchannel *ch) { struct mISDN_sock *msk = container_of(ch, struct mISDN_sock, ch); struct mISDNchannel *pch; if (!ch->st) { printk(KERN_WARNING "%s: no stack\n", __func__); return; } if (*debug & DEBUG_CORE_FUNC) printk(KERN_DEBUG "%s: st(%s) protocol(%x)\n", __func__, dev_name(&ch->st->dev->dev), ch->protocol); if (ch->protocol >= ISDN_P_B_START) { if (ch->peer) { ch->peer->ctrl(ch->peer, CLOSE_CHANNEL, NULL); ch->peer = NULL; } return; } switch (ch->protocol) { case ISDN_P_NT_S0: case ISDN_P_TE_S0: case ISDN_P_NT_E1: case ISDN_P_TE_E1: write_lock_bh(&ch->st->l1sock.lock); sk_del_node_init(&msk->sk); write_unlock_bh(&ch->st->l1sock.lock); ch->st->dev->D.ctrl(&ch->st->dev->D, CLOSE_CHANNEL, NULL); break; case ISDN_P_LAPD_TE: pch = get_channel4id(ch->st, ch->nr); if (pch) { mutex_lock(&ch->st->lmutex); list_del(&pch->list); mutex_unlock(&ch->st->lmutex); pch->ctrl(pch, CLOSE_CHANNEL, NULL); pch = ch->st->dev->teimgr; pch->ctrl(pch, CLOSE_CHANNEL, NULL); } else printk(KERN_WARNING "%s: no l2 channel\n", __func__); break; case ISDN_P_LAPD_NT: pch = ch->st->dev->teimgr; if (pch) { pch->ctrl(pch, CLOSE_CHANNEL, NULL); } else printk(KERN_WARNING "%s: no l2 channel\n", __func__); break; default: break; } return; } void delete_stack(struct mISDNdevice *dev) { struct mISDNstack *st = dev->D.st; DECLARE_COMPLETION_ONSTACK(done); if (*debug & DEBUG_CORE_FUNC) printk(KERN_DEBUG "%s: st(%s)\n", __func__, dev_name(&st->dev->dev)); if (dev->teimgr) delete_teimanager(dev->teimgr); if (st->thread) { if (st->notify) { printk(KERN_WARNING "%s: notifier in use\n", __func__); complete(st->notify); } st->notify = &done; test_and_set_bit(mISDN_STACK_ABORT, &st->status); test_and_set_bit(mISDN_STACK_WAKEUP, &st->status); wake_up_interruptible(&st->workq); wait_for_completion(&done); } if (!list_empty(&st->layer2)) printk(KERN_WARNING "%s: layer2 list not empty\n", __func__); if (!hlist_empty(&st->l1sock.head)) printk(KERN_WARNING "%s: layer1 list not empty\n", __func__); kfree(st); } void mISDN_initstack(u_int *dp) { debug = dp; }
gpl-2.0
davidmueller13/caf_kernel_msm
drivers/base/regmap/regcache.c
4375
11239
/* * Register cache access API * * Copyright 2011 Wolfson Microelectronics plc * * Author: Dimitris Papastamos <dp@opensource.wolfsonmicro.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/slab.h> #include <linux/export.h> #include <linux/device.h> #include <trace/events/regmap.h> #include <linux/bsearch.h> #include <linux/sort.h> #include "internal.h" static const struct regcache_ops *cache_types[] = { &regcache_rbtree_ops, &regcache_lzo_ops, }; static int regcache_hw_init(struct regmap *map) { int i, j; int ret; int count; unsigned int val; void *tmp_buf; if (!map->num_reg_defaults_raw) return -EINVAL; if (!map->reg_defaults_raw) { u32 cache_bypass = map->cache_bypass; dev_warn(map->dev, "No cache defaults, reading back from HW\n"); /* Bypass the cache access till data read from HW*/ map->cache_bypass = 1; tmp_buf = kmalloc(map->cache_size_raw, GFP_KERNEL); if (!tmp_buf) return -EINVAL; ret = regmap_bulk_read(map, 0, tmp_buf, map->num_reg_defaults_raw); map->cache_bypass = cache_bypass; if (ret < 0) { kfree(tmp_buf); return ret; } map->reg_defaults_raw = tmp_buf; map->cache_free = 1; } /* calculate the size of reg_defaults */ for (count = 0, i = 0; i < map->num_reg_defaults_raw; i++) { val = regcache_get_val(map->reg_defaults_raw, i, map->cache_word_size); if (regmap_volatile(map, i)) continue; count++; } map->reg_defaults = kmalloc(count * sizeof(struct reg_default), GFP_KERNEL); if (!map->reg_defaults) { ret = -ENOMEM; goto err_free; } /* fill the reg_defaults */ map->num_reg_defaults = count; for (i = 0, j = 0; i < map->num_reg_defaults_raw; i++) { val = regcache_get_val(map->reg_defaults_raw, i, map->cache_word_size); if (regmap_volatile(map, i)) continue; map->reg_defaults[j].reg = i; map->reg_defaults[j].def = val; j++; } return 0; err_free: if (map->cache_free) kfree(map->reg_defaults_raw); return ret; } int regcache_init(struct regmap *map, const struct regmap_config *config) { int ret; int i; void *tmp_buf; if (map->cache_type == REGCACHE_NONE) { map->cache_bypass = true; return 0; } for (i = 0; i < ARRAY_SIZE(cache_types); i++) if (cache_types[i]->type == map->cache_type) break; if (i == ARRAY_SIZE(cache_types)) { dev_err(map->dev, "Could not match compress type: %d\n", map->cache_type); return -EINVAL; } map->num_reg_defaults = config->num_reg_defaults; map->num_reg_defaults_raw = config->num_reg_defaults_raw; map->reg_defaults_raw = config->reg_defaults_raw; map->cache_word_size = DIV_ROUND_UP(config->val_bits, 8); map->cache_size_raw = map->cache_word_size * config->num_reg_defaults_raw; map->cache = NULL; map->cache_ops = cache_types[i]; if (!map->cache_ops->read || !map->cache_ops->write || !map->cache_ops->name) return -EINVAL; /* We still need to ensure that the reg_defaults * won't vanish from under us. We'll need to make * a copy of it. */ if (config->reg_defaults) { if (!map->num_reg_defaults) return -EINVAL; tmp_buf = kmemdup(config->reg_defaults, map->num_reg_defaults * sizeof(struct reg_default), GFP_KERNEL); if (!tmp_buf) return -ENOMEM; map->reg_defaults = tmp_buf; } else if (map->num_reg_defaults_raw) { /* Some devices such as PMICs don't have cache defaults, * we cope with this by reading back the HW registers and * crafting the cache defaults by hand. */ ret = regcache_hw_init(map); if (ret < 0) return ret; } if (!map->max_register) map->max_register = map->num_reg_defaults_raw; if (map->cache_ops->init) { dev_dbg(map->dev, "Initializing %s cache\n", map->cache_ops->name); ret = map->cache_ops->init(map); if (ret) goto err_free; } return 0; err_free: kfree(map->reg_defaults); if (map->cache_free) kfree(map->reg_defaults_raw); return ret; } void regcache_exit(struct regmap *map) { if (map->cache_type == REGCACHE_NONE) return; BUG_ON(!map->cache_ops); kfree(map->reg_defaults); if (map->cache_free) kfree(map->reg_defaults_raw); if (map->cache_ops->exit) { dev_dbg(map->dev, "Destroying %s cache\n", map->cache_ops->name); map->cache_ops->exit(map); } } /** * regcache_read: Fetch the value of a given register from the cache. * * @map: map to configure. * @reg: The register index. * @value: The value to be returned. * * Return a negative value on failure, 0 on success. */ int regcache_read(struct regmap *map, unsigned int reg, unsigned int *value) { int ret; if (map->cache_type == REGCACHE_NONE) return -ENOSYS; BUG_ON(!map->cache_ops); if (!regmap_volatile(map, reg)) { ret = map->cache_ops->read(map, reg, value); if (ret == 0) trace_regmap_reg_read_cache(map->dev, reg, *value); return ret; } return -EINVAL; } /** * regcache_write: Set the value of a given register in the cache. * * @map: map to configure. * @reg: The register index. * @value: The new register value. * * Return a negative value on failure, 0 on success. */ int regcache_write(struct regmap *map, unsigned int reg, unsigned int value) { if (map->cache_type == REGCACHE_NONE) return 0; BUG_ON(!map->cache_ops); if (!regmap_writeable(map, reg)) return -EIO; if (!regmap_volatile(map, reg)) return map->cache_ops->write(map, reg, value); return 0; } /** * regcache_sync: Sync the register cache with the hardware. * * @map: map to configure. * * Any registers that should not be synced should be marked as * volatile. In general drivers can choose not to use the provided * syncing functionality if they so require. * * Return a negative value on failure, 0 on success. */ int regcache_sync(struct regmap *map) { int ret = 0; unsigned int i; const char *name; unsigned int bypass; BUG_ON(!map->cache_ops || !map->cache_ops->sync); mutex_lock(&map->lock); /* Remember the initial bypass state */ bypass = map->cache_bypass; dev_dbg(map->dev, "Syncing %s cache\n", map->cache_ops->name); name = map->cache_ops->name; trace_regcache_sync(map->dev, name, "start"); if (!map->cache_dirty) goto out; /* Apply any patch first */ map->cache_bypass = 1; for (i = 0; i < map->patch_regs; i++) { ret = _regmap_write(map, map->patch[i].reg, map->patch[i].def); if (ret != 0) { dev_err(map->dev, "Failed to write %x = %x: %d\n", map->patch[i].reg, map->patch[i].def, ret); goto out; } } map->cache_bypass = 0; ret = map->cache_ops->sync(map, 0, map->max_register); if (ret == 0) map->cache_dirty = false; out: trace_regcache_sync(map->dev, name, "stop"); /* Restore the bypass state */ map->cache_bypass = bypass; mutex_unlock(&map->lock); return ret; } EXPORT_SYMBOL_GPL(regcache_sync); /** * regcache_sync_region: Sync part of the register cache with the hardware. * * @map: map to sync. * @min: first register to sync * @max: last register to sync * * Write all non-default register values in the specified region to * the hardware. * * Return a negative value on failure, 0 on success. */ int regcache_sync_region(struct regmap *map, unsigned int min, unsigned int max) { int ret = 0; const char *name; unsigned int bypass; BUG_ON(!map->cache_ops || !map->cache_ops->sync); mutex_lock(&map->lock); /* Remember the initial bypass state */ bypass = map->cache_bypass; name = map->cache_ops->name; dev_dbg(map->dev, "Syncing %s cache from %d-%d\n", name, min, max); trace_regcache_sync(map->dev, name, "start region"); if (!map->cache_dirty) goto out; ret = map->cache_ops->sync(map, min, max); out: trace_regcache_sync(map->dev, name, "stop region"); /* Restore the bypass state */ map->cache_bypass = bypass; mutex_unlock(&map->lock); return ret; } EXPORT_SYMBOL_GPL(regcache_sync_region); /** * regcache_cache_only: Put a register map into cache only mode * * @map: map to configure * @cache_only: flag if changes should be written to the hardware * * When a register map is marked as cache only writes to the register * map API will only update the register cache, they will not cause * any hardware changes. This is useful for allowing portions of * drivers to act as though the device were functioning as normal when * it is disabled for power saving reasons. */ void regcache_cache_only(struct regmap *map, bool enable) { mutex_lock(&map->lock); WARN_ON(map->cache_bypass && enable); map->cache_only = enable; trace_regmap_cache_only(map->dev, enable); mutex_unlock(&map->lock); } EXPORT_SYMBOL_GPL(regcache_cache_only); /** * regcache_mark_dirty: Mark the register cache as dirty * * @map: map to mark * * Mark the register cache as dirty, for example due to the device * having been powered down for suspend. If the cache is not marked * as dirty then the cache sync will be suppressed. */ void regcache_mark_dirty(struct regmap *map) { mutex_lock(&map->lock); map->cache_dirty = true; mutex_unlock(&map->lock); } EXPORT_SYMBOL_GPL(regcache_mark_dirty); /** * regcache_cache_bypass: Put a register map into cache bypass mode * * @map: map to configure * @cache_bypass: flag if changes should not be written to the hardware * * When a register map is marked with the cache bypass option, writes * to the register map API will only update the hardware and not the * the cache directly. This is useful when syncing the cache back to * the hardware. */ void regcache_cache_bypass(struct regmap *map, bool enable) { mutex_lock(&map->lock); WARN_ON(map->cache_only && enable); map->cache_bypass = enable; trace_regmap_cache_bypass(map->dev, enable); mutex_unlock(&map->lock); } EXPORT_SYMBOL_GPL(regcache_cache_bypass); bool regcache_set_val(void *base, unsigned int idx, unsigned int val, unsigned int word_size) { switch (word_size) { case 1: { u8 *cache = base; if (cache[idx] == val) return true; cache[idx] = val; break; } case 2: { u16 *cache = base; if (cache[idx] == val) return true; cache[idx] = val; break; } case 4: { u32 *cache = base; if (cache[idx] == val) return true; cache[idx] = val; break; } default: BUG(); } return false; } unsigned int regcache_get_val(const void *base, unsigned int idx, unsigned int word_size) { if (!base) return -EINVAL; switch (word_size) { case 1: { const u8 *cache = base; return cache[idx]; } case 2: { const u16 *cache = base; return cache[idx]; } case 4: { const u32 *cache = base; return cache[idx]; } default: BUG(); } /* unreachable */ return -1; } static int regcache_default_cmp(const void *a, const void *b) { const struct reg_default *_a = a; const struct reg_default *_b = b; return _a->reg - _b->reg; } int regcache_lookup_reg(struct regmap *map, unsigned int reg) { struct reg_default key; struct reg_default *r; key.reg = reg; key.def = 0; r = bsearch(&key, map->reg_defaults, map->num_reg_defaults, sizeof(struct reg_default), regcache_default_cmp); if (r) return r - map->reg_defaults; else return -ENOENT; }
gpl-2.0
tianchi-dev/android_kernel_sony_msm8226
drivers/net/ethernet/amd/7990.c
5143
21760
/* * 7990.c -- LANCE ethernet IC generic routines. * This is an attempt to separate out the bits of various ethernet * drivers that are common because they all use the AMD 7990 LANCE * (Local Area Network Controller for Ethernet) chip. * * Copyright (C) 05/1998 Peter Maydell <pmaydell@chiark.greenend.org.uk> * * Most of this stuff was obtained by looking at other LANCE drivers, * in particular a2065.[ch]. The AMD C-LANCE datasheet was also helpful. * NB: this was made easy by the fact that Jes Sorensen had cleaned up * most of a2025 and sunlance with the aim of merging them, so the * common code was pretty obvious. */ #include <linux/crc32.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/in.h> #include <linux/route.h> #include <linux/string.h> #include <linux/skbuff.h> #include <asm/irq.h> /* Used for the temporal inet entries and routing */ #include <linux/socket.h> #include <linux/bitops.h> #include <asm/io.h> #include <asm/dma.h> #include <asm/pgtable.h> #ifdef CONFIG_HP300 #include <asm/blinken.h> #endif #include "7990.h" #define WRITERAP(lp,x) out_be16(lp->base + LANCE_RAP, (x)) #define WRITERDP(lp,x) out_be16(lp->base + LANCE_RDP, (x)) #define READRDP(lp) in_be16(lp->base + LANCE_RDP) #if defined(CONFIG_HPLANCE) || defined(CONFIG_HPLANCE_MODULE) #include "hplance.h" #undef WRITERAP #undef WRITERDP #undef READRDP #if defined(CONFIG_MVME147_NET) || defined(CONFIG_MVME147_NET_MODULE) /* Lossage Factor Nine, Mr Sulu. */ #define WRITERAP(lp,x) (lp->writerap(lp,x)) #define WRITERDP(lp,x) (lp->writerdp(lp,x)) #define READRDP(lp) (lp->readrdp(lp)) #else /* These inlines can be used if only CONFIG_HPLANCE is defined */ static inline void WRITERAP(struct lance_private *lp, __u16 value) { do { out_be16(lp->base + HPLANCE_REGOFF + LANCE_RAP, value); } while ((in_8(lp->base + HPLANCE_STATUS) & LE_ACK) == 0); } static inline void WRITERDP(struct lance_private *lp, __u16 value) { do { out_be16(lp->base + HPLANCE_REGOFF + LANCE_RDP, value); } while ((in_8(lp->base + HPLANCE_STATUS) & LE_ACK) == 0); } static inline __u16 READRDP(struct lance_private *lp) { __u16 value; do { value = in_be16(lp->base + HPLANCE_REGOFF + LANCE_RDP); } while ((in_8(lp->base + HPLANCE_STATUS) & LE_ACK) == 0); return value; } #endif #endif /* CONFIG_HPLANCE || CONFIG_HPLANCE_MODULE */ /* debugging output macros, various flavours */ /* #define TEST_HITS */ #ifdef UNDEF #define PRINT_RINGS() \ do { \ int t; \ for (t=0; t < RX_RING_SIZE; t++) { \ printk("R%d: @(%02X %04X) len %04X, mblen %04X, bits %02X\n",\ t, ib->brx_ring[t].rmd1_hadr, ib->brx_ring[t].rmd0,\ ib->brx_ring[t].length,\ ib->brx_ring[t].mblength, ib->brx_ring[t].rmd1_bits);\ }\ for (t=0; t < TX_RING_SIZE; t++) { \ printk("T%d: @(%02X %04X) len %04X, misc %04X, bits %02X\n",\ t, ib->btx_ring[t].tmd1_hadr, ib->btx_ring[t].tmd0,\ ib->btx_ring[t].length,\ ib->btx_ring[t].misc, ib->btx_ring[t].tmd1_bits);\ }\ } while (0) #else #define PRINT_RINGS() #endif /* Load the CSR registers. The LANCE has to be STOPped when we do this! */ static void load_csrs (struct lance_private *lp) { volatile struct lance_init_block *aib = lp->lance_init_block; int leptr; leptr = LANCE_ADDR (aib); WRITERAP(lp, LE_CSR1); /* load address of init block */ WRITERDP(lp, leptr & 0xFFFF); WRITERAP(lp, LE_CSR2); WRITERDP(lp, leptr >> 16); WRITERAP(lp, LE_CSR3); WRITERDP(lp, lp->busmaster_regval); /* set byteswap/ALEctrl/byte ctrl */ /* Point back to csr0 */ WRITERAP(lp, LE_CSR0); } /* #define to 0 or 1 appropriately */ #define DEBUG_IRING 0 /* Set up the Lance Rx and Tx rings and the init block */ static void lance_init_ring (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); volatile struct lance_init_block *ib = lp->init_block; volatile struct lance_init_block *aib; /* for LANCE_ADDR computations */ int leptr; int i; aib = lp->lance_init_block; lp->rx_new = lp->tx_new = 0; lp->rx_old = lp->tx_old = 0; ib->mode = LE_MO_PROM; /* normal, enable Tx & Rx */ /* Copy the ethernet address to the lance init block * Notice that we do a byteswap if we're big endian. * [I think this is the right criterion; at least, sunlance, * a2065 and atarilance do the byteswap and lance.c (PC) doesn't. * However, the datasheet says that the BSWAP bit doesn't affect * the init block, so surely it should be low byte first for * everybody? Um.] * We could define the ib->physaddr as three 16bit values and * use (addr[1] << 8) | addr[0] & co, but this is more efficient. */ #ifdef __BIG_ENDIAN ib->phys_addr [0] = dev->dev_addr [1]; ib->phys_addr [1] = dev->dev_addr [0]; ib->phys_addr [2] = dev->dev_addr [3]; ib->phys_addr [3] = dev->dev_addr [2]; ib->phys_addr [4] = dev->dev_addr [5]; ib->phys_addr [5] = dev->dev_addr [4]; #else for (i=0; i<6; i++) ib->phys_addr[i] = dev->dev_addr[i]; #endif if (DEBUG_IRING) printk ("TX rings:\n"); lp->tx_full = 0; /* Setup the Tx ring entries */ for (i = 0; i < (1<<lp->lance_log_tx_bufs); i++) { leptr = LANCE_ADDR(&aib->tx_buf[i][0]); ib->btx_ring [i].tmd0 = leptr; ib->btx_ring [i].tmd1_hadr = leptr >> 16; ib->btx_ring [i].tmd1_bits = 0; ib->btx_ring [i].length = 0xf000; /* The ones required by tmd2 */ ib->btx_ring [i].misc = 0; if (DEBUG_IRING) printk ("%d: 0x%8.8x\n", i, leptr); } /* Setup the Rx ring entries */ if (DEBUG_IRING) printk ("RX rings:\n"); for (i = 0; i < (1<<lp->lance_log_rx_bufs); i++) { leptr = LANCE_ADDR(&aib->rx_buf[i][0]); ib->brx_ring [i].rmd0 = leptr; ib->brx_ring [i].rmd1_hadr = leptr >> 16; ib->brx_ring [i].rmd1_bits = LE_R1_OWN; /* 0xf000 == bits that must be one (reserved, presumably) */ ib->brx_ring [i].length = -RX_BUFF_SIZE | 0xf000; ib->brx_ring [i].mblength = 0; if (DEBUG_IRING) printk ("%d: 0x%8.8x\n", i, leptr); } /* Setup the initialization block */ /* Setup rx descriptor pointer */ leptr = LANCE_ADDR(&aib->brx_ring); ib->rx_len = (lp->lance_log_rx_bufs << 13) | (leptr >> 16); ib->rx_ptr = leptr; if (DEBUG_IRING) printk ("RX ptr: %8.8x\n", leptr); /* Setup tx descriptor pointer */ leptr = LANCE_ADDR(&aib->btx_ring); ib->tx_len = (lp->lance_log_tx_bufs << 13) | (leptr >> 16); ib->tx_ptr = leptr; if (DEBUG_IRING) printk ("TX ptr: %8.8x\n", leptr); /* Clear the multicast filter */ ib->filter [0] = 0; ib->filter [1] = 0; PRINT_RINGS(); } /* LANCE must be STOPped before we do this, too... */ static int init_restart_lance (struct lance_private *lp) { int i; WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_INIT); /* Need a hook here for sunlance ledma stuff */ /* Wait for the lance to complete initialization */ for (i = 0; (i < 100) && !(READRDP(lp) & (LE_C0_ERR | LE_C0_IDON)); i++) barrier(); if ((i == 100) || (READRDP(lp) & LE_C0_ERR)) { printk ("LANCE unopened after %d ticks, csr0=%4.4x.\n", i, READRDP(lp)); return -1; } /* Clear IDON by writing a "1", enable interrupts and start lance */ WRITERDP(lp, LE_C0_IDON); WRITERDP(lp, LE_C0_INEA | LE_C0_STRT); return 0; } static int lance_reset (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); int status; /* Stop the lance */ WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_STOP); load_csrs (lp); lance_init_ring (dev); dev->trans_start = jiffies; /* prevent tx timeout */ status = init_restart_lance (lp); #ifdef DEBUG_DRIVER printk ("Lance restart=%d\n", status); #endif return status; } static int lance_rx (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); volatile struct lance_init_block *ib = lp->init_block; volatile struct lance_rx_desc *rd; unsigned char bits; #ifdef TEST_HITS int i; #endif #ifdef TEST_HITS printk ("["); for (i = 0; i < RX_RING_SIZE; i++) { if (i == lp->rx_new) printk ("%s", ib->brx_ring [i].rmd1_bits & LE_R1_OWN ? "_" : "X"); else printk ("%s", ib->brx_ring [i].rmd1_bits & LE_R1_OWN ? "." : "1"); } printk ("]"); #endif #ifdef CONFIG_HP300 blinken_leds(0x40, 0); #endif WRITERDP(lp, LE_C0_RINT | LE_C0_INEA); /* ack Rx int, reenable ints */ for (rd = &ib->brx_ring [lp->rx_new]; /* For each Rx ring we own... */ !((bits = rd->rmd1_bits) & LE_R1_OWN); rd = &ib->brx_ring [lp->rx_new]) { /* We got an incomplete frame? */ if ((bits & LE_R1_POK) != LE_R1_POK) { dev->stats.rx_over_errors++; dev->stats.rx_errors++; continue; } else if (bits & LE_R1_ERR) { /* Count only the end frame as a rx error, * not the beginning */ if (bits & LE_R1_BUF) dev->stats.rx_fifo_errors++; if (bits & LE_R1_CRC) dev->stats.rx_crc_errors++; if (bits & LE_R1_OFL) dev->stats.rx_over_errors++; if (bits & LE_R1_FRA) dev->stats.rx_frame_errors++; if (bits & LE_R1_EOP) dev->stats.rx_errors++; } else { int len = (rd->mblength & 0xfff) - 4; struct sk_buff *skb = netdev_alloc_skb(dev, len + 2); if (!skb) { printk ("%s: Memory squeeze, deferring packet.\n", dev->name); dev->stats.rx_dropped++; rd->mblength = 0; rd->rmd1_bits = LE_R1_OWN; lp->rx_new = (lp->rx_new + 1) & lp->rx_ring_mod_mask; return 0; } skb_reserve (skb, 2); /* 16 byte align */ skb_put (skb, len); /* make room */ skb_copy_to_linear_data(skb, (unsigned char *)&(ib->rx_buf [lp->rx_new][0]), len); skb->protocol = eth_type_trans (skb, dev); netif_rx (skb); dev->stats.rx_packets++; dev->stats.rx_bytes += len; } /* Return the packet to the pool */ rd->mblength = 0; rd->rmd1_bits = LE_R1_OWN; lp->rx_new = (lp->rx_new + 1) & lp->rx_ring_mod_mask; } return 0; } static int lance_tx (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); volatile struct lance_init_block *ib = lp->init_block; volatile struct lance_tx_desc *td; int i, j; int status; #ifdef CONFIG_HP300 blinken_leds(0x80, 0); #endif /* csr0 is 2f3 */ WRITERDP(lp, LE_C0_TINT | LE_C0_INEA); /* csr0 is 73 */ j = lp->tx_old; for (i = j; i != lp->tx_new; i = j) { td = &ib->btx_ring [i]; /* If we hit a packet not owned by us, stop */ if (td->tmd1_bits & LE_T1_OWN) break; if (td->tmd1_bits & LE_T1_ERR) { status = td->misc; dev->stats.tx_errors++; if (status & LE_T3_RTY) dev->stats.tx_aborted_errors++; if (status & LE_T3_LCOL) dev->stats.tx_window_errors++; if (status & LE_T3_CLOS) { dev->stats.tx_carrier_errors++; if (lp->auto_select) { lp->tpe = 1 - lp->tpe; printk("%s: Carrier Lost, trying %s\n", dev->name, lp->tpe?"TPE":"AUI"); /* Stop the lance */ WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_STOP); lance_init_ring (dev); load_csrs (lp); init_restart_lance (lp); return 0; } } /* buffer errors and underflows turn off the transmitter */ /* Restart the adapter */ if (status & (LE_T3_BUF|LE_T3_UFL)) { dev->stats.tx_fifo_errors++; printk ("%s: Tx: ERR_BUF|ERR_UFL, restarting\n", dev->name); /* Stop the lance */ WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_STOP); lance_init_ring (dev); load_csrs (lp); init_restart_lance (lp); return 0; } } else if ((td->tmd1_bits & LE_T1_POK) == LE_T1_POK) { /* * So we don't count the packet more than once. */ td->tmd1_bits &= ~(LE_T1_POK); /* One collision before packet was sent. */ if (td->tmd1_bits & LE_T1_EONE) dev->stats.collisions++; /* More than one collision, be optimistic. */ if (td->tmd1_bits & LE_T1_EMORE) dev->stats.collisions += 2; dev->stats.tx_packets++; } j = (j + 1) & lp->tx_ring_mod_mask; } lp->tx_old = j; WRITERDP(lp, LE_C0_TINT | LE_C0_INEA); return 0; } static irqreturn_t lance_interrupt (int irq, void *dev_id) { struct net_device *dev = (struct net_device *)dev_id; struct lance_private *lp = netdev_priv(dev); int csr0; spin_lock (&lp->devlock); WRITERAP(lp, LE_CSR0); /* LANCE Controller Status */ csr0 = READRDP(lp); PRINT_RINGS(); if (!(csr0 & LE_C0_INTR)) { /* Check if any interrupt has */ spin_unlock (&lp->devlock); return IRQ_NONE; /* been generated by the Lance. */ } /* Acknowledge all the interrupt sources ASAP */ WRITERDP(lp, csr0 & ~(LE_C0_INEA|LE_C0_TDMD|LE_C0_STOP|LE_C0_STRT|LE_C0_INIT)); if ((csr0 & LE_C0_ERR)) { /* Clear the error condition */ WRITERDP(lp, LE_C0_BABL|LE_C0_ERR|LE_C0_MISS|LE_C0_INEA); } if (csr0 & LE_C0_RINT) lance_rx (dev); if (csr0 & LE_C0_TINT) lance_tx (dev); /* Log misc errors. */ if (csr0 & LE_C0_BABL) dev->stats.tx_errors++; /* Tx babble. */ if (csr0 & LE_C0_MISS) dev->stats.rx_errors++; /* Missed a Rx frame. */ if (csr0 & LE_C0_MERR) { printk("%s: Bus master arbitration failure, status %4.4x.\n", dev->name, csr0); /* Restart the chip. */ WRITERDP(lp, LE_C0_STRT); } if (lp->tx_full && netif_queue_stopped(dev) && (TX_BUFFS_AVAIL >= 0)) { lp->tx_full = 0; netif_wake_queue (dev); } WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_BABL|LE_C0_CERR|LE_C0_MISS|LE_C0_MERR|LE_C0_IDON|LE_C0_INEA); spin_unlock (&lp->devlock); return IRQ_HANDLED; } int lance_open (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); int res; /* Install the Interrupt handler. Or we could shunt this out to specific drivers? */ if (request_irq(lp->irq, lance_interrupt, IRQF_SHARED, lp->name, dev)) return -EAGAIN; res = lance_reset(dev); spin_lock_init(&lp->devlock); netif_start_queue (dev); return res; } EXPORT_SYMBOL_GPL(lance_open); int lance_close (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); netif_stop_queue (dev); /* Stop the LANCE */ WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_STOP); free_irq(lp->irq, dev); return 0; } EXPORT_SYMBOL_GPL(lance_close); void lance_tx_timeout(struct net_device *dev) { printk("lance_tx_timeout\n"); lance_reset(dev); dev->trans_start = jiffies; /* prevent tx timeout */ netif_wake_queue (dev); } EXPORT_SYMBOL_GPL(lance_tx_timeout); int lance_start_xmit (struct sk_buff *skb, struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); volatile struct lance_init_block *ib = lp->init_block; int entry, skblen, len; static int outs; unsigned long flags; if (!TX_BUFFS_AVAIL) return NETDEV_TX_LOCKED; netif_stop_queue (dev); skblen = skb->len; #ifdef DEBUG_DRIVER /* dump the packet */ { int i; for (i = 0; i < 64; i++) { if ((i % 16) == 0) printk ("\n"); printk ("%2.2x ", skb->data [i]); } } #endif len = (skblen <= ETH_ZLEN) ? ETH_ZLEN : skblen; entry = lp->tx_new & lp->tx_ring_mod_mask; ib->btx_ring [entry].length = (-len) | 0xf000; ib->btx_ring [entry].misc = 0; if (skb->len < ETH_ZLEN) memset((void *)&ib->tx_buf[entry][0], 0, ETH_ZLEN); skb_copy_from_linear_data(skb, (void *)&ib->tx_buf[entry][0], skblen); /* Now, give the packet to the lance */ ib->btx_ring [entry].tmd1_bits = (LE_T1_POK|LE_T1_OWN); lp->tx_new = (lp->tx_new+1) & lp->tx_ring_mod_mask; outs++; /* Kick the lance: transmit now */ WRITERDP(lp, LE_C0_INEA | LE_C0_TDMD); dev_kfree_skb (skb); spin_lock_irqsave (&lp->devlock, flags); if (TX_BUFFS_AVAIL) netif_start_queue (dev); else lp->tx_full = 1; spin_unlock_irqrestore (&lp->devlock, flags); return NETDEV_TX_OK; } EXPORT_SYMBOL_GPL(lance_start_xmit); /* taken from the depca driver via a2065.c */ static void lance_load_multicast (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); volatile struct lance_init_block *ib = lp->init_block; volatile u16 *mcast_table = (u16 *)&ib->filter; struct netdev_hw_addr *ha; u32 crc; /* set all multicast bits */ if (dev->flags & IFF_ALLMULTI){ ib->filter [0] = 0xffffffff; ib->filter [1] = 0xffffffff; return; } /* clear the multicast filter */ ib->filter [0] = 0; ib->filter [1] = 0; /* Add addresses */ netdev_for_each_mc_addr(ha, dev) { crc = ether_crc_le(6, ha->addr); crc = crc >> 26; mcast_table [crc >> 4] |= 1 << (crc & 0xf); } } void lance_set_multicast (struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); volatile struct lance_init_block *ib = lp->init_block; int stopped; stopped = netif_queue_stopped(dev); if (!stopped) netif_stop_queue (dev); while (lp->tx_old != lp->tx_new) schedule(); WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_STOP); lance_init_ring (dev); if (dev->flags & IFF_PROMISC) { ib->mode |= LE_MO_PROM; } else { ib->mode &= ~LE_MO_PROM; lance_load_multicast (dev); } load_csrs (lp); init_restart_lance (lp); if (!stopped) netif_start_queue (dev); } EXPORT_SYMBOL_GPL(lance_set_multicast); #ifdef CONFIG_NET_POLL_CONTROLLER void lance_poll(struct net_device *dev) { struct lance_private *lp = netdev_priv(dev); spin_lock (&lp->devlock); WRITERAP(lp, LE_CSR0); WRITERDP(lp, LE_C0_STRT); spin_unlock (&lp->devlock); lance_interrupt(dev->irq, dev); } #endif MODULE_LICENSE("GPL");
gpl-2.0
jamison904/kernel_m919
drivers/isdn/hysdn/hycapi.c
5143
22916
/* $Id: hycapi.c,v 1.8.6.4 2001/09/23 22:24:54 kai Exp $ * * Linux driver for HYSDN cards, CAPI2.0-Interface. * * Author Ulrich Albrecht <u.albrecht@hypercope.de> for Hypercope GmbH * Copyright 2000 by Hypercope GmbH * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/signal.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/slab.h> #define VER_DRIVER 0 #define VER_CARDTYPE 1 #define VER_HWID 2 #define VER_SERIAL 3 #define VER_OPTION 4 #define VER_PROTO 5 #define VER_PROFILE 6 #define VER_CAPI 7 #include "hysdn_defs.h" #include <linux/kernelcapi.h> static char hycapi_revision[] = "$Revision: 1.8.6.4 $"; unsigned int hycapi_enable = 0xffffffff; module_param(hycapi_enable, uint, 0); typedef struct _hycapi_appl { unsigned int ctrl_mask; capi_register_params rp; struct sk_buff *listen_req[CAPI_MAXCONTR]; } hycapi_appl; static hycapi_appl hycapi_applications[CAPI_MAXAPPL]; static u16 hycapi_send_message(struct capi_ctr *ctrl, struct sk_buff *skb); static inline int _hycapi_appCheck(int app_id, int ctrl_no) { if ((ctrl_no <= 0) || (ctrl_no > CAPI_MAXCONTR) || (app_id <= 0) || (app_id > CAPI_MAXAPPL)) { printk(KERN_ERR "HYCAPI: Invalid request app_id %d for controller %d", app_id, ctrl_no); return -1; } return ((hycapi_applications[app_id - 1].ctrl_mask & (1 << (ctrl_no-1))) != 0); } /****************************** Kernel-Capi callback reset_ctr ******************************/ static void hycapi_reset_ctr(struct capi_ctr *ctrl) { hycapictrl_info *cinfo = ctrl->driverdata; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "HYCAPI hycapi_reset_ctr\n"); #endif capilib_release(&cinfo->ncci_head); capi_ctr_down(ctrl); } /****************************** Kernel-Capi callback remove_ctr ******************************/ static void hycapi_remove_ctr(struct capi_ctr *ctrl) { int i; hycapictrl_info *cinfo = NULL; hysdn_card *card = NULL; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "HYCAPI hycapi_remove_ctr\n"); #endif cinfo = (hycapictrl_info *)(ctrl->driverdata); if (!cinfo) { printk(KERN_ERR "No hycapictrl_info set!"); return; } card = cinfo->card; capi_ctr_suspend_output(ctrl); for (i = 0; i < CAPI_MAXAPPL; i++) { if (hycapi_applications[i].listen_req[ctrl->cnr - 1]) { kfree_skb(hycapi_applications[i].listen_req[ctrl->cnr - 1]); hycapi_applications[i].listen_req[ctrl->cnr - 1] = NULL; } } detach_capi_ctr(ctrl); ctrl->driverdata = NULL; kfree(card->hyctrlinfo); card->hyctrlinfo = NULL; } /*********************************************************** Queue a CAPI-message to the controller. ***********************************************************/ static void hycapi_sendmsg_internal(struct capi_ctr *ctrl, struct sk_buff *skb) { hycapictrl_info *cinfo = (hycapictrl_info *)(ctrl->driverdata); hysdn_card *card = cinfo->card; spin_lock_irq(&cinfo->lock); #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_send_message\n"); #endif cinfo->skbs[cinfo->in_idx++] = skb; /* add to buffer list */ if (cinfo->in_idx >= HYSDN_MAX_CAPI_SKB) cinfo->in_idx = 0; /* wrap around */ cinfo->sk_count++; /* adjust counter */ if (cinfo->sk_count >= HYSDN_MAX_CAPI_SKB) { /* inform upper layers we're full */ printk(KERN_ERR "HYSDN Card%d: CAPI-buffer overrun!\n", card->myid); capi_ctr_suspend_output(ctrl); } cinfo->tx_skb = skb; spin_unlock_irq(&cinfo->lock); schedule_work(&card->irq_queue); } /*********************************************************** hycapi_register_internal Send down the CAPI_REGISTER-Command to the controller. This functions will also be used if the adapter has been rebooted to re-register any applications in the private list. ************************************************************/ static void hycapi_register_internal(struct capi_ctr *ctrl, __u16 appl, capi_register_params *rp) { char ExtFeatureDefaults[] = "49 /0/0/0/0,*/1,*/2,*/3,*/4,*/5,*/6,*/7,*/8,*/9,*"; hycapictrl_info *cinfo = (hycapictrl_info *)(ctrl->driverdata); hysdn_card *card = cinfo->card; struct sk_buff *skb; __u16 len; __u8 _command = 0xa0, _subcommand = 0x80; __u16 MessageNumber = 0x0000; __u16 MessageBufferSize = 0; int slen = strlen(ExtFeatureDefaults); #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_register_appl\n"); #endif MessageBufferSize = rp->level3cnt * rp->datablkcnt * rp->datablklen; len = CAPI_MSG_BASELEN + 8 + slen + 1; if (!(skb = alloc_skb(len, GFP_ATOMIC))) { printk(KERN_ERR "HYSDN card%d: memory squeeze in hycapi_register_appl\n", card->myid); return; } memcpy(skb_put(skb, sizeof(__u16)), &len, sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u16)), &appl, sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u8)), &_command, sizeof(_command)); memcpy(skb_put(skb, sizeof(__u8)), &_subcommand, sizeof(_subcommand)); memcpy(skb_put(skb, sizeof(__u16)), &MessageNumber, sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u16)), &MessageBufferSize, sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u16)), &(rp->level3cnt), sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u16)), &(rp->datablkcnt), sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u16)), &(rp->datablklen), sizeof(__u16)); memcpy(skb_put(skb, slen), ExtFeatureDefaults, slen); hycapi_applications[appl - 1].ctrl_mask |= (1 << (ctrl->cnr - 1)); hycapi_send_message(ctrl, skb); } /************************************************************ hycapi_restart_internal After an adapter has been rebootet, re-register all applications and send a LISTEN_REQ (if there has been such a thing ) *************************************************************/ static void hycapi_restart_internal(struct capi_ctr *ctrl) { int i; struct sk_buff *skb; #ifdef HYCAPI_PRINTFNAMES printk(KERN_WARNING "HYSDN: hycapi_restart_internal"); #endif for (i = 0; i < CAPI_MAXAPPL; i++) { if (_hycapi_appCheck(i + 1, ctrl->cnr) == 1) { hycapi_register_internal(ctrl, i + 1, &hycapi_applications[i].rp); if (hycapi_applications[i].listen_req[ctrl->cnr - 1]) { skb = skb_copy(hycapi_applications[i].listen_req[ctrl->cnr - 1], GFP_ATOMIC); hycapi_sendmsg_internal(ctrl, skb); } } } } /************************************************************* Register an application. Error-checking is done for CAPI-compliance. The application is recorded in the internal list. *************************************************************/ static void hycapi_register_appl(struct capi_ctr *ctrl, __u16 appl, capi_register_params *rp) { int MaxLogicalConnections = 0, MaxBDataBlocks = 0, MaxBDataLen = 0; hycapictrl_info *cinfo = (hycapictrl_info *)(ctrl->driverdata); hysdn_card *card = cinfo->card; int chk = _hycapi_appCheck(appl, ctrl->cnr); if (chk < 0) { return; } if (chk == 1) { printk(KERN_INFO "HYSDN: apl %d already registered\n", appl); return; } MaxBDataBlocks = rp->datablkcnt > CAPI_MAXDATAWINDOW ? CAPI_MAXDATAWINDOW : rp->datablkcnt; rp->datablkcnt = MaxBDataBlocks; MaxBDataLen = rp->datablklen < 1024 ? 1024 : rp->datablklen; rp->datablklen = MaxBDataLen; MaxLogicalConnections = rp->level3cnt; if (MaxLogicalConnections < 0) { MaxLogicalConnections = card->bchans * -MaxLogicalConnections; } if (MaxLogicalConnections == 0) { MaxLogicalConnections = card->bchans; } rp->level3cnt = MaxLogicalConnections; memcpy(&hycapi_applications[appl - 1].rp, rp, sizeof(capi_register_params)); } /********************************************************************* hycapi_release_internal Send down a CAPI_RELEASE to the controller. *********************************************************************/ static void hycapi_release_internal(struct capi_ctr *ctrl, __u16 appl) { hycapictrl_info *cinfo = (hycapictrl_info *)(ctrl->driverdata); hysdn_card *card = cinfo->card; struct sk_buff *skb; __u16 len; __u8 _command = 0xa1, _subcommand = 0x80; __u16 MessageNumber = 0x0000; capilib_release_appl(&cinfo->ncci_head, appl); #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_release_appl\n"); #endif len = CAPI_MSG_BASELEN; if (!(skb = alloc_skb(len, GFP_ATOMIC))) { printk(KERN_ERR "HYSDN card%d: memory squeeze in hycapi_register_appl\n", card->myid); return; } memcpy(skb_put(skb, sizeof(__u16)), &len, sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u16)), &appl, sizeof(__u16)); memcpy(skb_put(skb, sizeof(__u8)), &_command, sizeof(_command)); memcpy(skb_put(skb, sizeof(__u8)), &_subcommand, sizeof(_subcommand)); memcpy(skb_put(skb, sizeof(__u16)), &MessageNumber, sizeof(__u16)); hycapi_send_message(ctrl, skb); hycapi_applications[appl - 1].ctrl_mask &= ~(1 << (ctrl->cnr - 1)); } /****************************************************************** hycapi_release_appl Release the application from the internal list an remove it's registration at controller-level ******************************************************************/ static void hycapi_release_appl(struct capi_ctr *ctrl, __u16 appl) { int chk; chk = _hycapi_appCheck(appl, ctrl->cnr); if (chk < 0) { printk(KERN_ERR "HYCAPI: Releasing invalid appl %d on controller %d\n", appl, ctrl->cnr); return; } if (hycapi_applications[appl - 1].listen_req[ctrl->cnr - 1]) { kfree_skb(hycapi_applications[appl - 1].listen_req[ctrl->cnr - 1]); hycapi_applications[appl - 1].listen_req[ctrl->cnr - 1] = NULL; } if (chk == 1) { hycapi_release_internal(ctrl, appl); } } /************************************************************** Kill a single controller. **************************************************************/ int hycapi_capi_release(hysdn_card *card) { hycapictrl_info *cinfo = card->hyctrlinfo; struct capi_ctr *ctrl; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_capi_release\n"); #endif if (cinfo) { ctrl = &cinfo->capi_ctrl; hycapi_remove_ctr(ctrl); } return 0; } /************************************************************** hycapi_capi_stop Stop CAPI-Output on a card. (e.g. during reboot) ***************************************************************/ int hycapi_capi_stop(hysdn_card *card) { hycapictrl_info *cinfo = card->hyctrlinfo; struct capi_ctr *ctrl; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_capi_stop\n"); #endif if (cinfo) { ctrl = &cinfo->capi_ctrl; /* ctrl->suspend_output(ctrl); */ capi_ctr_down(ctrl); } return 0; } /*************************************************************** hycapi_send_message Send a message to the controller. Messages are parsed for their Command/Subcommand-type, and appropriate action's are performed. Note that we have to muck around with a 64Bit-DATA_REQ as there are firmware-releases that do not check the MsgLen-Indication! ***************************************************************/ static u16 hycapi_send_message(struct capi_ctr *ctrl, struct sk_buff *skb) { __u16 appl_id; int _len, _len2; __u8 msghead[64]; hycapictrl_info *cinfo = ctrl->driverdata; u16 retval = CAPI_NOERROR; appl_id = CAPIMSG_APPID(skb->data); switch (_hycapi_appCheck(appl_id, ctrl->cnr)) { case 0: /* printk(KERN_INFO "Need to register\n"); */ hycapi_register_internal(ctrl, appl_id, &(hycapi_applications[appl_id - 1].rp)); break; case 1: break; default: printk(KERN_ERR "HYCAPI: Controller mixup!\n"); retval = CAPI_ILLAPPNR; goto out; } switch (CAPIMSG_CMD(skb->data)) { case CAPI_DISCONNECT_B3_RESP: capilib_free_ncci(&cinfo->ncci_head, appl_id, CAPIMSG_NCCI(skb->data)); break; case CAPI_DATA_B3_REQ: _len = CAPIMSG_LEN(skb->data); if (_len > 22) { _len2 = _len - 22; skb_copy_from_linear_data(skb, msghead, 22); skb_copy_to_linear_data_offset(skb, _len2, msghead, 22); skb_pull(skb, _len2); CAPIMSG_SETLEN(skb->data, 22); retval = capilib_data_b3_req(&cinfo->ncci_head, CAPIMSG_APPID(skb->data), CAPIMSG_NCCI(skb->data), CAPIMSG_MSGID(skb->data)); } break; case CAPI_LISTEN_REQ: if (hycapi_applications[appl_id - 1].listen_req[ctrl->cnr - 1]) { kfree_skb(hycapi_applications[appl_id - 1].listen_req[ctrl->cnr - 1]); hycapi_applications[appl_id - 1].listen_req[ctrl->cnr - 1] = NULL; } if (!(hycapi_applications[appl_id -1].listen_req[ctrl->cnr - 1] = skb_copy(skb, GFP_ATOMIC))) { printk(KERN_ERR "HYSDN: memory squeeze in private_listen\n"); } break; default: break; } out: if (retval == CAPI_NOERROR) hycapi_sendmsg_internal(ctrl, skb); else dev_kfree_skb_any(skb); return retval; } static int hycapi_proc_show(struct seq_file *m, void *v) { struct capi_ctr *ctrl = m->private; hycapictrl_info *cinfo = (hycapictrl_info *)(ctrl->driverdata); hysdn_card *card = cinfo->card; char *s; seq_printf(m, "%-16s %s\n", "name", cinfo->cardname); seq_printf(m, "%-16s 0x%x\n", "io", card->iobase); seq_printf(m, "%-16s %d\n", "irq", card->irq); switch (card->brdtype) { case BD_PCCARD: s = "HYSDN Hycard"; break; case BD_ERGO: s = "HYSDN Ergo2"; break; case BD_METRO: s = "HYSDN Metro4"; break; case BD_CHAMP2: s = "HYSDN Champ2"; break; case BD_PLEXUS: s = "HYSDN Plexus30"; break; default: s = "???"; break; } seq_printf(m, "%-16s %s\n", "type", s); if ((s = cinfo->version[VER_DRIVER]) != NULL) seq_printf(m, "%-16s %s\n", "ver_driver", s); if ((s = cinfo->version[VER_CARDTYPE]) != NULL) seq_printf(m, "%-16s %s\n", "ver_cardtype", s); if ((s = cinfo->version[VER_SERIAL]) != NULL) seq_printf(m, "%-16s %s\n", "ver_serial", s); seq_printf(m, "%-16s %s\n", "cardname", cinfo->cardname); return 0; } static int hycapi_proc_open(struct inode *inode, struct file *file) { return single_open(file, hycapi_proc_show, PDE(inode)->data); } static const struct file_operations hycapi_proc_fops = { .owner = THIS_MODULE, .open = hycapi_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; /************************************************************** hycapi_load_firmware This does NOT load any firmware, but the callback somehow is needed on capi-interface registration. **************************************************************/ static int hycapi_load_firmware(struct capi_ctr *ctrl, capiloaddata *data) { #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_load_firmware\n"); #endif return 0; } static char *hycapi_procinfo(struct capi_ctr *ctrl) { hycapictrl_info *cinfo = (hycapictrl_info *)(ctrl->driverdata); #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_proc_info\n"); #endif if (!cinfo) return ""; sprintf(cinfo->infobuf, "%s %s 0x%x %d %s", cinfo->cardname[0] ? cinfo->cardname : "-", cinfo->version[VER_DRIVER] ? cinfo->version[VER_DRIVER] : "-", cinfo->card ? cinfo->card->iobase : 0x0, cinfo->card ? cinfo->card->irq : 0, hycapi_revision ); return cinfo->infobuf; } /****************************************************************** hycapi_rx_capipkt Receive a capi-message. All B3_DATA_IND are converted to 64K-extension compatible format. New nccis are created if necessary. *******************************************************************/ void hycapi_rx_capipkt(hysdn_card *card, unsigned char *buf, unsigned short len) { struct sk_buff *skb; hycapictrl_info *cinfo = card->hyctrlinfo; struct capi_ctr *ctrl; __u16 ApplId; __u16 MsgLen, info; __u16 len2, CapiCmd; __u32 CP64[2] = {0, 0}; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_rx_capipkt\n"); #endif if (!cinfo) { return; } ctrl = &cinfo->capi_ctrl; if (len < CAPI_MSG_BASELEN) { printk(KERN_ERR "HYSDN Card%d: invalid CAPI-message, length %d!\n", card->myid, len); return; } MsgLen = CAPIMSG_LEN(buf); ApplId = CAPIMSG_APPID(buf); CapiCmd = CAPIMSG_CMD(buf); if ((CapiCmd == CAPI_DATA_B3_IND) && (MsgLen < 30)) { len2 = len + (30 - MsgLen); if (!(skb = alloc_skb(len2, GFP_ATOMIC))) { printk(KERN_ERR "HYSDN Card%d: incoming packet dropped\n", card->myid); return; } memcpy(skb_put(skb, MsgLen), buf, MsgLen); memcpy(skb_put(skb, 2 * sizeof(__u32)), CP64, 2 * sizeof(__u32)); memcpy(skb_put(skb, len - MsgLen), buf + MsgLen, len - MsgLen); CAPIMSG_SETLEN(skb->data, 30); } else { if (!(skb = alloc_skb(len, GFP_ATOMIC))) { printk(KERN_ERR "HYSDN Card%d: incoming packet dropped\n", card->myid); return; } memcpy(skb_put(skb, len), buf, len); } switch (CAPIMSG_CMD(skb->data)) { case CAPI_CONNECT_B3_CONF: /* Check info-field for error-indication: */ info = CAPIMSG_U16(skb->data, 12); switch (info) { case 0: capilib_new_ncci(&cinfo->ncci_head, ApplId, CAPIMSG_NCCI(skb->data), hycapi_applications[ApplId - 1].rp.datablkcnt); break; case 0x0001: printk(KERN_ERR "HYSDN Card%d: NCPI not supported by current " "protocol. NCPI ignored.\n", card->myid); break; case 0x2001: printk(KERN_ERR "HYSDN Card%d: Message not supported in" " current state\n", card->myid); break; case 0x2002: printk(KERN_ERR "HYSDN Card%d: invalid PLCI\n", card->myid); break; case 0x2004: printk(KERN_ERR "HYSDN Card%d: out of NCCI\n", card->myid); break; case 0x3008: printk(KERN_ERR "HYSDN Card%d: NCPI not supported\n", card->myid); break; default: printk(KERN_ERR "HYSDN Card%d: Info in CONNECT_B3_CONF: %d\n", card->myid, info); break; } break; case CAPI_CONNECT_B3_IND: capilib_new_ncci(&cinfo->ncci_head, ApplId, CAPIMSG_NCCI(skb->data), hycapi_applications[ApplId - 1].rp.datablkcnt); break; case CAPI_DATA_B3_CONF: capilib_data_b3_conf(&cinfo->ncci_head, ApplId, CAPIMSG_NCCI(skb->data), CAPIMSG_MSGID(skb->data)); break; default: break; } capi_ctr_handle_message(ctrl, ApplId, skb); } /****************************************************************** hycapi_tx_capiack Internally acknowledge a msg sent. This will remove the msg from the internal queue. *******************************************************************/ void hycapi_tx_capiack(hysdn_card *card) { hycapictrl_info *cinfo = card->hyctrlinfo; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_tx_capiack\n"); #endif if (!cinfo) { return; } spin_lock_irq(&cinfo->lock); kfree_skb(cinfo->skbs[cinfo->out_idx]); /* free skb */ cinfo->skbs[cinfo->out_idx++] = NULL; if (cinfo->out_idx >= HYSDN_MAX_CAPI_SKB) cinfo->out_idx = 0; /* wrap around */ if (cinfo->sk_count-- == HYSDN_MAX_CAPI_SKB) /* dec usage count */ capi_ctr_resume_output(&cinfo->capi_ctrl); spin_unlock_irq(&cinfo->lock); } /*************************************************************** hycapi_tx_capiget(hysdn_card *card) This is called when polling for messages to SEND. ****************************************************************/ struct sk_buff * hycapi_tx_capiget(hysdn_card *card) { hycapictrl_info *cinfo = card->hyctrlinfo; if (!cinfo) { return (struct sk_buff *)NULL; } if (!cinfo->sk_count) return (struct sk_buff *)NULL; /* nothing available */ return (cinfo->skbs[cinfo->out_idx]); /* next packet to send */ } /********************************************************** int hycapi_init() attach the capi-driver to the kernel-capi. ***********************************************************/ int hycapi_init(void) { int i; for (i = 0; i < CAPI_MAXAPPL; i++) { memset(&(hycapi_applications[i]), 0, sizeof(hycapi_appl)); } return (0); } /************************************************************** hycapi_cleanup(void) detach the capi-driver to the kernel-capi. Actually this should free some more ressources. Do that later. **************************************************************/ void hycapi_cleanup(void) { } /******************************************************************** hycapi_capi_create(hysdn_card *card) Attach the card with its capi-ctrl. *********************************************************************/ static void hycapi_fill_profile(hysdn_card *card) { hycapictrl_info *cinfo = NULL; struct capi_ctr *ctrl = NULL; cinfo = card->hyctrlinfo; if (!cinfo) return; ctrl = &cinfo->capi_ctrl; strcpy(ctrl->manu, "Hypercope"); ctrl->version.majorversion = 2; ctrl->version.minorversion = 0; ctrl->version.majormanuversion = 3; ctrl->version.minormanuversion = 2; ctrl->profile.ncontroller = card->myid; ctrl->profile.nbchannel = card->bchans; ctrl->profile.goptions = GLOBAL_OPTION_INTERNAL_CONTROLLER | GLOBAL_OPTION_B_CHANNEL_OPERATION; ctrl->profile.support1 = B1_PROT_64KBIT_HDLC | (card->faxchans ? B1_PROT_T30 : 0) | B1_PROT_64KBIT_TRANSPARENT; ctrl->profile.support2 = B2_PROT_ISO7776 | (card->faxchans ? B2_PROT_T30 : 0) | B2_PROT_TRANSPARENT; ctrl->profile.support3 = B3_PROT_TRANSPARENT | B3_PROT_T90NL | (card->faxchans ? B3_PROT_T30 : 0) | (card->faxchans ? B3_PROT_T30EXT : 0) | B3_PROT_ISO8208; } int hycapi_capi_create(hysdn_card *card) { hycapictrl_info *cinfo = NULL; struct capi_ctr *ctrl = NULL; int retval; #ifdef HYCAPI_PRINTFNAMES printk(KERN_NOTICE "hycapi_capi_create\n"); #endif if ((hycapi_enable & (1 << card->myid)) == 0) { return 1; } if (!card->hyctrlinfo) { cinfo = kzalloc(sizeof(hycapictrl_info), GFP_ATOMIC); if (!cinfo) { printk(KERN_WARNING "HYSDN: no memory for capi-ctrl.\n"); return -ENOMEM; } card->hyctrlinfo = cinfo; cinfo->card = card; spin_lock_init(&cinfo->lock); INIT_LIST_HEAD(&cinfo->ncci_head); switch (card->brdtype) { case BD_PCCARD: strcpy(cinfo->cardname, "HYSDN Hycard"); break; case BD_ERGO: strcpy(cinfo->cardname, "HYSDN Ergo2"); break; case BD_METRO: strcpy(cinfo->cardname, "HYSDN Metro4"); break; case BD_CHAMP2: strcpy(cinfo->cardname, "HYSDN Champ2"); break; case BD_PLEXUS: strcpy(cinfo->cardname, "HYSDN Plexus30"); break; default: strcpy(cinfo->cardname, "HYSDN ???"); break; } ctrl = &cinfo->capi_ctrl; ctrl->driver_name = "hycapi"; ctrl->driverdata = cinfo; ctrl->register_appl = hycapi_register_appl; ctrl->release_appl = hycapi_release_appl; ctrl->send_message = hycapi_send_message; ctrl->load_firmware = hycapi_load_firmware; ctrl->reset_ctr = hycapi_reset_ctr; ctrl->procinfo = hycapi_procinfo; ctrl->proc_fops = &hycapi_proc_fops; strcpy(ctrl->name, cinfo->cardname); ctrl->owner = THIS_MODULE; retval = attach_capi_ctr(ctrl); if (retval) { printk(KERN_ERR "hycapi: attach controller failed.\n"); return -EBUSY; } /* fill in the blanks: */ hycapi_fill_profile(card); capi_ctr_ready(ctrl); } else { /* resume output on stopped ctrl */ ctrl = &card->hyctrlinfo->capi_ctrl; hycapi_fill_profile(card); capi_ctr_ready(ctrl); hycapi_restart_internal(ctrl); /* ctrl->resume_output(ctrl); */ } return 0; }
gpl-2.0
ArolWright/android_kernel_motorola_msm8916
arch/powerpc/sysdev/cpm1.c
6679
18997
/* * General Purpose functions for the global management of the * Communication Processor Module. * Copyright (c) 1997 Dan error_act (dmalek@jlc.net) * * In addition to the individual control of the communication * channels, there are a few functions that globally affect the * communication processor. * * Buffer descriptors must be allocated from the dual ported memory * space. The allocator for that is here. When the communication * process is reset, we reclaim the memory available. There is * currently no deallocator for this memory. * The amount of space available is platform dependent. On the * MBX, the EPPC software loads additional microcode into the * communication processor, and uses some of the DP ram for this * purpose. Current, the first 512 bytes and the last 256 bytes of * memory are used. Right now I am conservative and only use the * memory that can never be used for microcode. If there are * applications that require more DP ram, we can expand the boundaries * but then we have to be careful of any downloaded microcode. */ #include <linux/errno.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/dma-mapping.h> #include <linux/param.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/8xx_immap.h> #include <asm/cpm1.h> #include <asm/io.h> #include <asm/tlbflush.h> #include <asm/rheap.h> #include <asm/prom.h> #include <asm/cpm.h> #include <asm/fs_pd.h> #ifdef CONFIG_8xx_GPIO #include <linux/of_gpio.h> #endif #define CPM_MAP_SIZE (0x4000) cpm8xx_t __iomem *cpmp; /* Pointer to comm processor space */ immap_t __iomem *mpc8xx_immr; static cpic8xx_t __iomem *cpic_reg; static struct irq_domain *cpm_pic_host; static void cpm_mask_irq(struct irq_data *d) { unsigned int cpm_vec = (unsigned int)irqd_to_hwirq(d); clrbits32(&cpic_reg->cpic_cimr, (1 << cpm_vec)); } static void cpm_unmask_irq(struct irq_data *d) { unsigned int cpm_vec = (unsigned int)irqd_to_hwirq(d); setbits32(&cpic_reg->cpic_cimr, (1 << cpm_vec)); } static void cpm_end_irq(struct irq_data *d) { unsigned int cpm_vec = (unsigned int)irqd_to_hwirq(d); out_be32(&cpic_reg->cpic_cisr, (1 << cpm_vec)); } static struct irq_chip cpm_pic = { .name = "CPM PIC", .irq_mask = cpm_mask_irq, .irq_unmask = cpm_unmask_irq, .irq_eoi = cpm_end_irq, }; int cpm_get_irq(void) { int cpm_vec; /* Get the vector by setting the ACK bit and then reading * the register. */ out_be16(&cpic_reg->cpic_civr, 1); cpm_vec = in_be16(&cpic_reg->cpic_civr); cpm_vec >>= 11; return irq_linear_revmap(cpm_pic_host, cpm_vec); } static int cpm_pic_host_map(struct irq_domain *h, unsigned int virq, irq_hw_number_t hw) { pr_debug("cpm_pic_host_map(%d, 0x%lx)\n", virq, hw); irq_set_status_flags(virq, IRQ_LEVEL); irq_set_chip_and_handler(virq, &cpm_pic, handle_fasteoi_irq); return 0; } /* The CPM can generate the error interrupt when there is a race condition * between generating and masking interrupts. All we have to do is ACK it * and return. This is a no-op function so we don't need any special * tests in the interrupt handler. */ static irqreturn_t cpm_error_interrupt(int irq, void *dev) { return IRQ_HANDLED; } static struct irqaction cpm_error_irqaction = { .handler = cpm_error_interrupt, .name = "error", }; static const struct irq_domain_ops cpm_pic_host_ops = { .map = cpm_pic_host_map, }; unsigned int cpm_pic_init(void) { struct device_node *np = NULL; struct resource res; unsigned int sirq = NO_IRQ, hwirq, eirq; int ret; pr_debug("cpm_pic_init\n"); np = of_find_compatible_node(NULL, NULL, "fsl,cpm1-pic"); if (np == NULL) np = of_find_compatible_node(NULL, "cpm-pic", "CPM"); if (np == NULL) { printk(KERN_ERR "CPM PIC init: can not find cpm-pic node\n"); return sirq; } ret = of_address_to_resource(np, 0, &res); if (ret) goto end; cpic_reg = ioremap(res.start, resource_size(&res)); if (cpic_reg == NULL) goto end; sirq = irq_of_parse_and_map(np, 0); if (sirq == NO_IRQ) goto end; /* Initialize the CPM interrupt controller. */ hwirq = (unsigned int)virq_to_hw(sirq); out_be32(&cpic_reg->cpic_cicr, (CICR_SCD_SCC4 | CICR_SCC_SCC3 | CICR_SCB_SCC2 | CICR_SCA_SCC1) | ((hwirq/2) << 13) | CICR_HP_MASK); out_be32(&cpic_reg->cpic_cimr, 0); cpm_pic_host = irq_domain_add_linear(np, 64, &cpm_pic_host_ops, NULL); if (cpm_pic_host == NULL) { printk(KERN_ERR "CPM2 PIC: failed to allocate irq host!\n"); sirq = NO_IRQ; goto end; } /* Install our own error handler. */ np = of_find_compatible_node(NULL, NULL, "fsl,cpm1"); if (np == NULL) np = of_find_node_by_type(NULL, "cpm"); if (np == NULL) { printk(KERN_ERR "CPM PIC init: can not find cpm node\n"); goto end; } eirq = irq_of_parse_and_map(np, 0); if (eirq == NO_IRQ) goto end; if (setup_irq(eirq, &cpm_error_irqaction)) printk(KERN_ERR "Could not allocate CPM error IRQ!"); setbits32(&cpic_reg->cpic_cicr, CICR_IEN); end: of_node_put(np); return sirq; } void __init cpm_reset(void) { sysconf8xx_t __iomem *siu_conf; mpc8xx_immr = ioremap(get_immrbase(), 0x4000); if (!mpc8xx_immr) { printk(KERN_CRIT "Could not map IMMR\n"); return; } cpmp = &mpc8xx_immr->im_cpm; #ifndef CONFIG_PPC_EARLY_DEBUG_CPM /* Perform a reset. */ out_be16(&cpmp->cp_cpcr, CPM_CR_RST | CPM_CR_FLG); /* Wait for it. */ while (in_be16(&cpmp->cp_cpcr) & CPM_CR_FLG); #endif #ifdef CONFIG_UCODE_PATCH cpm_load_patch(cpmp); #endif /* Set SDMA Bus Request priority 5. * On 860T, this also enables FEC priority 6. I am not sure * this is what we really want for some applications, but the * manual recommends it. * Bit 25, FAM can also be set to use FEC aggressive mode (860T). */ siu_conf = immr_map(im_siu_conf); out_be32(&siu_conf->sc_sdcr, 1); immr_unmap(siu_conf); cpm_muram_init(); } static DEFINE_SPINLOCK(cmd_lock); #define MAX_CR_CMD_LOOPS 10000 int cpm_command(u32 command, u8 opcode) { int i, ret; unsigned long flags; if (command & 0xffffff0f) return -EINVAL; spin_lock_irqsave(&cmd_lock, flags); ret = 0; out_be16(&cpmp->cp_cpcr, command | CPM_CR_FLG | (opcode << 8)); for (i = 0; i < MAX_CR_CMD_LOOPS; i++) if ((in_be16(&cpmp->cp_cpcr) & CPM_CR_FLG) == 0) goto out; printk(KERN_ERR "%s(): Not able to issue CPM command\n", __func__); ret = -EIO; out: spin_unlock_irqrestore(&cmd_lock, flags); return ret; } EXPORT_SYMBOL(cpm_command); /* Set a baud rate generator. This needs lots of work. There are * four BRGs, any of which can be wired to any channel. * The internal baud rate clock is the system clock divided by 16. * This assumes the baudrate is 16x oversampled by the uart. */ #define BRG_INT_CLK (get_brgfreq()) #define BRG_UART_CLK (BRG_INT_CLK/16) #define BRG_UART_CLK_DIV16 (BRG_UART_CLK/16) void cpm_setbrg(uint brg, uint rate) { u32 __iomem *bp; /* This is good enough to get SMCs running..... */ bp = &cpmp->cp_brgc1; bp += brg; /* The BRG has a 12-bit counter. For really slow baud rates (or * really fast processors), we may have to further divide by 16. */ if (((BRG_UART_CLK / rate) - 1) < 4096) out_be32(bp, (((BRG_UART_CLK / rate) - 1) << 1) | CPM_BRG_EN); else out_be32(bp, (((BRG_UART_CLK_DIV16 / rate) - 1) << 1) | CPM_BRG_EN | CPM_BRG_DIV16); } struct cpm_ioport16 { __be16 dir, par, odr_sor, dat, intr; __be16 res[3]; }; struct cpm_ioport32b { __be32 dir, par, odr, dat; }; struct cpm_ioport32e { __be32 dir, par, sor, odr, dat; }; static void cpm1_set_pin32(int port, int pin, int flags) { struct cpm_ioport32e __iomem *iop; pin = 1 << (31 - pin); if (port == CPM_PORTB) iop = (struct cpm_ioport32e __iomem *) &mpc8xx_immr->im_cpm.cp_pbdir; else iop = (struct cpm_ioport32e __iomem *) &mpc8xx_immr->im_cpm.cp_pedir; if (flags & CPM_PIN_OUTPUT) setbits32(&iop->dir, pin); else clrbits32(&iop->dir, pin); if (!(flags & CPM_PIN_GPIO)) setbits32(&iop->par, pin); else clrbits32(&iop->par, pin); if (port == CPM_PORTB) { if (flags & CPM_PIN_OPENDRAIN) setbits16(&mpc8xx_immr->im_cpm.cp_pbodr, pin); else clrbits16(&mpc8xx_immr->im_cpm.cp_pbodr, pin); } if (port == CPM_PORTE) { if (flags & CPM_PIN_SECONDARY) setbits32(&iop->sor, pin); else clrbits32(&iop->sor, pin); if (flags & CPM_PIN_OPENDRAIN) setbits32(&mpc8xx_immr->im_cpm.cp_peodr, pin); else clrbits32(&mpc8xx_immr->im_cpm.cp_peodr, pin); } } static void cpm1_set_pin16(int port, int pin, int flags) { struct cpm_ioport16 __iomem *iop = (struct cpm_ioport16 __iomem *)&mpc8xx_immr->im_ioport; pin = 1 << (15 - pin); if (port != 0) iop += port - 1; if (flags & CPM_PIN_OUTPUT) setbits16(&iop->dir, pin); else clrbits16(&iop->dir, pin); if (!(flags & CPM_PIN_GPIO)) setbits16(&iop->par, pin); else clrbits16(&iop->par, pin); if (port == CPM_PORTA) { if (flags & CPM_PIN_OPENDRAIN) setbits16(&iop->odr_sor, pin); else clrbits16(&iop->odr_sor, pin); } if (port == CPM_PORTC) { if (flags & CPM_PIN_SECONDARY) setbits16(&iop->odr_sor, pin); else clrbits16(&iop->odr_sor, pin); } } void cpm1_set_pin(enum cpm_port port, int pin, int flags) { if (port == CPM_PORTB || port == CPM_PORTE) cpm1_set_pin32(port, pin, flags); else cpm1_set_pin16(port, pin, flags); } int cpm1_clk_setup(enum cpm_clk_target target, int clock, int mode) { int shift; int i, bits = 0; u32 __iomem *reg; u32 mask = 7; u8 clk_map[][3] = { {CPM_CLK_SCC1, CPM_BRG1, 0}, {CPM_CLK_SCC1, CPM_BRG2, 1}, {CPM_CLK_SCC1, CPM_BRG3, 2}, {CPM_CLK_SCC1, CPM_BRG4, 3}, {CPM_CLK_SCC1, CPM_CLK1, 4}, {CPM_CLK_SCC1, CPM_CLK2, 5}, {CPM_CLK_SCC1, CPM_CLK3, 6}, {CPM_CLK_SCC1, CPM_CLK4, 7}, {CPM_CLK_SCC2, CPM_BRG1, 0}, {CPM_CLK_SCC2, CPM_BRG2, 1}, {CPM_CLK_SCC2, CPM_BRG3, 2}, {CPM_CLK_SCC2, CPM_BRG4, 3}, {CPM_CLK_SCC2, CPM_CLK1, 4}, {CPM_CLK_SCC2, CPM_CLK2, 5}, {CPM_CLK_SCC2, CPM_CLK3, 6}, {CPM_CLK_SCC2, CPM_CLK4, 7}, {CPM_CLK_SCC3, CPM_BRG1, 0}, {CPM_CLK_SCC3, CPM_BRG2, 1}, {CPM_CLK_SCC3, CPM_BRG3, 2}, {CPM_CLK_SCC3, CPM_BRG4, 3}, {CPM_CLK_SCC3, CPM_CLK5, 4}, {CPM_CLK_SCC3, CPM_CLK6, 5}, {CPM_CLK_SCC3, CPM_CLK7, 6}, {CPM_CLK_SCC3, CPM_CLK8, 7}, {CPM_CLK_SCC4, CPM_BRG1, 0}, {CPM_CLK_SCC4, CPM_BRG2, 1}, {CPM_CLK_SCC4, CPM_BRG3, 2}, {CPM_CLK_SCC4, CPM_BRG4, 3}, {CPM_CLK_SCC4, CPM_CLK5, 4}, {CPM_CLK_SCC4, CPM_CLK6, 5}, {CPM_CLK_SCC4, CPM_CLK7, 6}, {CPM_CLK_SCC4, CPM_CLK8, 7}, {CPM_CLK_SMC1, CPM_BRG1, 0}, {CPM_CLK_SMC1, CPM_BRG2, 1}, {CPM_CLK_SMC1, CPM_BRG3, 2}, {CPM_CLK_SMC1, CPM_BRG4, 3}, {CPM_CLK_SMC1, CPM_CLK1, 4}, {CPM_CLK_SMC1, CPM_CLK2, 5}, {CPM_CLK_SMC1, CPM_CLK3, 6}, {CPM_CLK_SMC1, CPM_CLK4, 7}, {CPM_CLK_SMC2, CPM_BRG1, 0}, {CPM_CLK_SMC2, CPM_BRG2, 1}, {CPM_CLK_SMC2, CPM_BRG3, 2}, {CPM_CLK_SMC2, CPM_BRG4, 3}, {CPM_CLK_SMC2, CPM_CLK5, 4}, {CPM_CLK_SMC2, CPM_CLK6, 5}, {CPM_CLK_SMC2, CPM_CLK7, 6}, {CPM_CLK_SMC2, CPM_CLK8, 7}, }; switch (target) { case CPM_CLK_SCC1: reg = &mpc8xx_immr->im_cpm.cp_sicr; shift = 0; break; case CPM_CLK_SCC2: reg = &mpc8xx_immr->im_cpm.cp_sicr; shift = 8; break; case CPM_CLK_SCC3: reg = &mpc8xx_immr->im_cpm.cp_sicr; shift = 16; break; case CPM_CLK_SCC4: reg = &mpc8xx_immr->im_cpm.cp_sicr; shift = 24; break; case CPM_CLK_SMC1: reg = &mpc8xx_immr->im_cpm.cp_simode; shift = 12; break; case CPM_CLK_SMC2: reg = &mpc8xx_immr->im_cpm.cp_simode; shift = 28; break; default: printk(KERN_ERR "cpm1_clock_setup: invalid clock target\n"); return -EINVAL; } for (i = 0; i < ARRAY_SIZE(clk_map); i++) { if (clk_map[i][0] == target && clk_map[i][1] == clock) { bits = clk_map[i][2]; break; } } if (i == ARRAY_SIZE(clk_map)) { printk(KERN_ERR "cpm1_clock_setup: invalid clock combination\n"); return -EINVAL; } bits <<= shift; mask <<= shift; if (reg == &mpc8xx_immr->im_cpm.cp_sicr) { if (mode == CPM_CLK_RTX) { bits |= bits << 3; mask |= mask << 3; } else if (mode == CPM_CLK_RX) { bits <<= 3; mask <<= 3; } } out_be32(reg, (in_be32(reg) & ~mask) | bits); return 0; } /* * GPIO LIB API implementation */ #ifdef CONFIG_8xx_GPIO struct cpm1_gpio16_chip { struct of_mm_gpio_chip mm_gc; spinlock_t lock; /* shadowed data register to clear/set bits safely */ u16 cpdata; }; static inline struct cpm1_gpio16_chip * to_cpm1_gpio16_chip(struct of_mm_gpio_chip *mm_gc) { return container_of(mm_gc, struct cpm1_gpio16_chip, mm_gc); } static void cpm1_gpio16_save_regs(struct of_mm_gpio_chip *mm_gc) { struct cpm1_gpio16_chip *cpm1_gc = to_cpm1_gpio16_chip(mm_gc); struct cpm_ioport16 __iomem *iop = mm_gc->regs; cpm1_gc->cpdata = in_be16(&iop->dat); } static int cpm1_gpio16_get(struct gpio_chip *gc, unsigned int gpio) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm_ioport16 __iomem *iop = mm_gc->regs; u16 pin_mask; pin_mask = 1 << (15 - gpio); return !!(in_be16(&iop->dat) & pin_mask); } static void __cpm1_gpio16_set(struct of_mm_gpio_chip *mm_gc, u16 pin_mask, int value) { struct cpm1_gpio16_chip *cpm1_gc = to_cpm1_gpio16_chip(mm_gc); struct cpm_ioport16 __iomem *iop = mm_gc->regs; if (value) cpm1_gc->cpdata |= pin_mask; else cpm1_gc->cpdata &= ~pin_mask; out_be16(&iop->dat, cpm1_gc->cpdata); } static void cpm1_gpio16_set(struct gpio_chip *gc, unsigned int gpio, int value) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm1_gpio16_chip *cpm1_gc = to_cpm1_gpio16_chip(mm_gc); unsigned long flags; u16 pin_mask = 1 << (15 - gpio); spin_lock_irqsave(&cpm1_gc->lock, flags); __cpm1_gpio16_set(mm_gc, pin_mask, value); spin_unlock_irqrestore(&cpm1_gc->lock, flags); } static int cpm1_gpio16_dir_out(struct gpio_chip *gc, unsigned int gpio, int val) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm1_gpio16_chip *cpm1_gc = to_cpm1_gpio16_chip(mm_gc); struct cpm_ioport16 __iomem *iop = mm_gc->regs; unsigned long flags; u16 pin_mask = 1 << (15 - gpio); spin_lock_irqsave(&cpm1_gc->lock, flags); setbits16(&iop->dir, pin_mask); __cpm1_gpio16_set(mm_gc, pin_mask, val); spin_unlock_irqrestore(&cpm1_gc->lock, flags); return 0; } static int cpm1_gpio16_dir_in(struct gpio_chip *gc, unsigned int gpio) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm1_gpio16_chip *cpm1_gc = to_cpm1_gpio16_chip(mm_gc); struct cpm_ioport16 __iomem *iop = mm_gc->regs; unsigned long flags; u16 pin_mask = 1 << (15 - gpio); spin_lock_irqsave(&cpm1_gc->lock, flags); clrbits16(&iop->dir, pin_mask); spin_unlock_irqrestore(&cpm1_gc->lock, flags); return 0; } int cpm1_gpiochip_add16(struct device_node *np) { struct cpm1_gpio16_chip *cpm1_gc; struct of_mm_gpio_chip *mm_gc; struct gpio_chip *gc; cpm1_gc = kzalloc(sizeof(*cpm1_gc), GFP_KERNEL); if (!cpm1_gc) return -ENOMEM; spin_lock_init(&cpm1_gc->lock); mm_gc = &cpm1_gc->mm_gc; gc = &mm_gc->gc; mm_gc->save_regs = cpm1_gpio16_save_regs; gc->ngpio = 16; gc->direction_input = cpm1_gpio16_dir_in; gc->direction_output = cpm1_gpio16_dir_out; gc->get = cpm1_gpio16_get; gc->set = cpm1_gpio16_set; return of_mm_gpiochip_add(np, mm_gc); } struct cpm1_gpio32_chip { struct of_mm_gpio_chip mm_gc; spinlock_t lock; /* shadowed data register to clear/set bits safely */ u32 cpdata; }; static inline struct cpm1_gpio32_chip * to_cpm1_gpio32_chip(struct of_mm_gpio_chip *mm_gc) { return container_of(mm_gc, struct cpm1_gpio32_chip, mm_gc); } static void cpm1_gpio32_save_regs(struct of_mm_gpio_chip *mm_gc) { struct cpm1_gpio32_chip *cpm1_gc = to_cpm1_gpio32_chip(mm_gc); struct cpm_ioport32b __iomem *iop = mm_gc->regs; cpm1_gc->cpdata = in_be32(&iop->dat); } static int cpm1_gpio32_get(struct gpio_chip *gc, unsigned int gpio) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm_ioport32b __iomem *iop = mm_gc->regs; u32 pin_mask; pin_mask = 1 << (31 - gpio); return !!(in_be32(&iop->dat) & pin_mask); } static void __cpm1_gpio32_set(struct of_mm_gpio_chip *mm_gc, u32 pin_mask, int value) { struct cpm1_gpio32_chip *cpm1_gc = to_cpm1_gpio32_chip(mm_gc); struct cpm_ioport32b __iomem *iop = mm_gc->regs; if (value) cpm1_gc->cpdata |= pin_mask; else cpm1_gc->cpdata &= ~pin_mask; out_be32(&iop->dat, cpm1_gc->cpdata); } static void cpm1_gpio32_set(struct gpio_chip *gc, unsigned int gpio, int value) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm1_gpio32_chip *cpm1_gc = to_cpm1_gpio32_chip(mm_gc); unsigned long flags; u32 pin_mask = 1 << (31 - gpio); spin_lock_irqsave(&cpm1_gc->lock, flags); __cpm1_gpio32_set(mm_gc, pin_mask, value); spin_unlock_irqrestore(&cpm1_gc->lock, flags); } static int cpm1_gpio32_dir_out(struct gpio_chip *gc, unsigned int gpio, int val) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm1_gpio32_chip *cpm1_gc = to_cpm1_gpio32_chip(mm_gc); struct cpm_ioport32b __iomem *iop = mm_gc->regs; unsigned long flags; u32 pin_mask = 1 << (31 - gpio); spin_lock_irqsave(&cpm1_gc->lock, flags); setbits32(&iop->dir, pin_mask); __cpm1_gpio32_set(mm_gc, pin_mask, val); spin_unlock_irqrestore(&cpm1_gc->lock, flags); return 0; } static int cpm1_gpio32_dir_in(struct gpio_chip *gc, unsigned int gpio) { struct of_mm_gpio_chip *mm_gc = to_of_mm_gpio_chip(gc); struct cpm1_gpio32_chip *cpm1_gc = to_cpm1_gpio32_chip(mm_gc); struct cpm_ioport32b __iomem *iop = mm_gc->regs; unsigned long flags; u32 pin_mask = 1 << (31 - gpio); spin_lock_irqsave(&cpm1_gc->lock, flags); clrbits32(&iop->dir, pin_mask); spin_unlock_irqrestore(&cpm1_gc->lock, flags); return 0; } int cpm1_gpiochip_add32(struct device_node *np) { struct cpm1_gpio32_chip *cpm1_gc; struct of_mm_gpio_chip *mm_gc; struct gpio_chip *gc; cpm1_gc = kzalloc(sizeof(*cpm1_gc), GFP_KERNEL); if (!cpm1_gc) return -ENOMEM; spin_lock_init(&cpm1_gc->lock); mm_gc = &cpm1_gc->mm_gc; gc = &mm_gc->gc; mm_gc->save_regs = cpm1_gpio32_save_regs; gc->ngpio = 32; gc->direction_input = cpm1_gpio32_dir_in; gc->direction_output = cpm1_gpio32_dir_out; gc->get = cpm1_gpio32_get; gc->set = cpm1_gpio32_set; return of_mm_gpiochip_add(np, mm_gc); } static int cpm_init_par_io(void) { struct device_node *np; for_each_compatible_node(np, NULL, "fsl,cpm1-pario-bank-a") cpm1_gpiochip_add16(np); for_each_compatible_node(np, NULL, "fsl,cpm1-pario-bank-b") cpm1_gpiochip_add32(np); for_each_compatible_node(np, NULL, "fsl,cpm1-pario-bank-c") cpm1_gpiochip_add16(np); for_each_compatible_node(np, NULL, "fsl,cpm1-pario-bank-d") cpm1_gpiochip_add16(np); /* Port E uses CPM2 layout */ for_each_compatible_node(np, NULL, "fsl,cpm1-pario-bank-e") cpm2_gpiochip_add32(np); return 0; } arch_initcall(cpm_init_par_io); #endif /* CONFIG_8xx_GPIO */
gpl-2.0
pio-masaki/android_kernel_a100
arch/sh/boards/mach-dreamcast/irq.c
7447
4568
/* * arch/sh/boards/dreamcast/irq.c * * Holly IRQ support for the Sega Dreamcast. * * Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org> * * This file is part of the LinuxDC project (www.linuxdc.org) * Released under the terms of the GNU GPL v2.0 */ #include <linux/irq.h> #include <linux/io.h> #include <asm/irq.h> #include <mach/sysasic.h> /* * Dreamcast System ASIC Hardware Events - * * The Dreamcast's System ASIC (a.k.a. Holly) is responsible for receiving * hardware events from system peripherals and triggering an SH7750 IRQ. * Hardware events can trigger IRQs 13, 11, or 9 depending on which bits are * set in the Event Mask Registers (EMRs). When a hardware event is * triggered, its corresponding bit in the Event Status Registers (ESRs) * is set, and that bit should be rewritten to the ESR to acknowledge that * event. * * There are three 32-bit ESRs located at 0xa05f6900 - 0xa05f6908. Event * types can be found in arch/sh/include/mach-dreamcast/mach/sysasic.h. * There are three groups of EMRs that parallel the ESRs. Each EMR group * corresponds to an IRQ, so 0xa05f6910 - 0xa05f6918 triggers IRQ 13, * 0xa05f6920 - 0xa05f6928 triggers IRQ 11, and 0xa05f6930 - 0xa05f6938 * triggers IRQ 9. * * In the kernel, these events are mapped to virtual IRQs so that drivers can * respond to them as they would a normal interrupt. In order to keep this * mapping simple, the events are mapped as: * * 6900/6910 - Events 0-31, IRQ 13 * 6904/6924 - Events 32-63, IRQ 11 * 6908/6938 - Events 64-95, IRQ 9 * */ #define ESR_BASE 0x005f6900 /* Base event status register */ #define EMR_BASE 0x005f6910 /* Base event mask register */ /* * Helps us determine the EMR group that this event belongs to: 0 = 0x6910, * 1 = 0x6920, 2 = 0x6930; also determine the event offset. */ #define LEVEL(event) (((event) - HW_EVENT_IRQ_BASE) / 32) /* Return the hardware event's bit position within the EMR/ESR */ #define EVENT_BIT(event) (((event) - HW_EVENT_IRQ_BASE) & 31) /* * For each of these *_irq routines, the IRQ passed in is the virtual IRQ * (logically mapped to the corresponding bit for the hardware event). */ /* Disable the hardware event by masking its bit in its EMR */ static inline void disable_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2); __u32 mask; mask = inl(emr); mask &= ~(1 << EVENT_BIT(irq)); outl(mask, emr); } /* Enable the hardware event by setting its bit in its EMR */ static inline void enable_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2); __u32 mask; mask = inl(emr); mask |= (1 << EVENT_BIT(irq)); outl(mask, emr); } /* Acknowledge a hardware event by writing its bit back to its ESR */ static void mask_ack_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 esr = ESR_BASE + (LEVEL(irq) << 2); disable_systemasic_irq(data); outl((1 << EVENT_BIT(irq)), esr); } struct irq_chip systemasic_int = { .name = "System ASIC", .irq_mask = disable_systemasic_irq, .irq_mask_ack = mask_ack_systemasic_irq, .irq_unmask = enable_systemasic_irq, }; /* * Map the hardware event indicated by the processor IRQ to a virtual IRQ. */ int systemasic_irq_demux(int irq) { __u32 emr, esr, status, level; __u32 j, bit; switch (irq) { case 13: level = 0; break; case 11: level = 1; break; case 9: level = 2; break; default: return irq; } emr = EMR_BASE + (level << 4) + (level << 2); esr = ESR_BASE + (level << 2); /* Mask the ESR to filter any spurious, unwanted interrupts */ status = inl(esr); status &= inl(emr); /* Now scan and find the first set bit as the event to map */ for (bit = 1, j = 0; j < 32; bit <<= 1, j++) { if (status & bit) { irq = HW_EVENT_IRQ_BASE + j + (level << 5); return irq; } } /* Not reached */ return irq; } void systemasic_irq_init(void) { int i, nid = cpu_to_node(boot_cpu_data); /* Assign all virtual IRQs to the System ASIC int. handler */ for (i = HW_EVENT_IRQ_BASE; i < HW_EVENT_IRQ_MAX; i++) { unsigned int irq; irq = create_irq_nr(i, nid); if (unlikely(irq == 0)) { pr_err("%s: failed hooking irq %d for systemasic\n", __func__, i); return; } if (unlikely(irq != i)) { pr_err("%s: got irq %d but wanted %d, bailing.\n", __func__, irq, i); destroy_irq(irq); return; } irq_set_chip_and_handler(i, &systemasic_int, handle_level_irq); } }
gpl-2.0
puskyer/android_kernel_motorola_olympus
arch/sh/boards/mach-dreamcast/irq.c
7447
4568
/* * arch/sh/boards/dreamcast/irq.c * * Holly IRQ support for the Sega Dreamcast. * * Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org> * * This file is part of the LinuxDC project (www.linuxdc.org) * Released under the terms of the GNU GPL v2.0 */ #include <linux/irq.h> #include <linux/io.h> #include <asm/irq.h> #include <mach/sysasic.h> /* * Dreamcast System ASIC Hardware Events - * * The Dreamcast's System ASIC (a.k.a. Holly) is responsible for receiving * hardware events from system peripherals and triggering an SH7750 IRQ. * Hardware events can trigger IRQs 13, 11, or 9 depending on which bits are * set in the Event Mask Registers (EMRs). When a hardware event is * triggered, its corresponding bit in the Event Status Registers (ESRs) * is set, and that bit should be rewritten to the ESR to acknowledge that * event. * * There are three 32-bit ESRs located at 0xa05f6900 - 0xa05f6908. Event * types can be found in arch/sh/include/mach-dreamcast/mach/sysasic.h. * There are three groups of EMRs that parallel the ESRs. Each EMR group * corresponds to an IRQ, so 0xa05f6910 - 0xa05f6918 triggers IRQ 13, * 0xa05f6920 - 0xa05f6928 triggers IRQ 11, and 0xa05f6930 - 0xa05f6938 * triggers IRQ 9. * * In the kernel, these events are mapped to virtual IRQs so that drivers can * respond to them as they would a normal interrupt. In order to keep this * mapping simple, the events are mapped as: * * 6900/6910 - Events 0-31, IRQ 13 * 6904/6924 - Events 32-63, IRQ 11 * 6908/6938 - Events 64-95, IRQ 9 * */ #define ESR_BASE 0x005f6900 /* Base event status register */ #define EMR_BASE 0x005f6910 /* Base event mask register */ /* * Helps us determine the EMR group that this event belongs to: 0 = 0x6910, * 1 = 0x6920, 2 = 0x6930; also determine the event offset. */ #define LEVEL(event) (((event) - HW_EVENT_IRQ_BASE) / 32) /* Return the hardware event's bit position within the EMR/ESR */ #define EVENT_BIT(event) (((event) - HW_EVENT_IRQ_BASE) & 31) /* * For each of these *_irq routines, the IRQ passed in is the virtual IRQ * (logically mapped to the corresponding bit for the hardware event). */ /* Disable the hardware event by masking its bit in its EMR */ static inline void disable_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2); __u32 mask; mask = inl(emr); mask &= ~(1 << EVENT_BIT(irq)); outl(mask, emr); } /* Enable the hardware event by setting its bit in its EMR */ static inline void enable_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2); __u32 mask; mask = inl(emr); mask |= (1 << EVENT_BIT(irq)); outl(mask, emr); } /* Acknowledge a hardware event by writing its bit back to its ESR */ static void mask_ack_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 esr = ESR_BASE + (LEVEL(irq) << 2); disable_systemasic_irq(data); outl((1 << EVENT_BIT(irq)), esr); } struct irq_chip systemasic_int = { .name = "System ASIC", .irq_mask = disable_systemasic_irq, .irq_mask_ack = mask_ack_systemasic_irq, .irq_unmask = enable_systemasic_irq, }; /* * Map the hardware event indicated by the processor IRQ to a virtual IRQ. */ int systemasic_irq_demux(int irq) { __u32 emr, esr, status, level; __u32 j, bit; switch (irq) { case 13: level = 0; break; case 11: level = 1; break; case 9: level = 2; break; default: return irq; } emr = EMR_BASE + (level << 4) + (level << 2); esr = ESR_BASE + (level << 2); /* Mask the ESR to filter any spurious, unwanted interrupts */ status = inl(esr); status &= inl(emr); /* Now scan and find the first set bit as the event to map */ for (bit = 1, j = 0; j < 32; bit <<= 1, j++) { if (status & bit) { irq = HW_EVENT_IRQ_BASE + j + (level << 5); return irq; } } /* Not reached */ return irq; } void systemasic_irq_init(void) { int i, nid = cpu_to_node(boot_cpu_data); /* Assign all virtual IRQs to the System ASIC int. handler */ for (i = HW_EVENT_IRQ_BASE; i < HW_EVENT_IRQ_MAX; i++) { unsigned int irq; irq = create_irq_nr(i, nid); if (unlikely(irq == 0)) { pr_err("%s: failed hooking irq %d for systemasic\n", __func__, i); return; } if (unlikely(irq != i)) { pr_err("%s: got irq %d but wanted %d, bailing.\n", __func__, irq, i); destroy_irq(irq); return; } irq_set_chip_and_handler(i, &systemasic_int, handle_level_irq); } }
gpl-2.0
Shamestick/android_kernel_htc_msm8974
arch/sh/boards/mach-dreamcast/irq.c
7447
4568
/* * arch/sh/boards/dreamcast/irq.c * * Holly IRQ support for the Sega Dreamcast. * * Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org> * * This file is part of the LinuxDC project (www.linuxdc.org) * Released under the terms of the GNU GPL v2.0 */ #include <linux/irq.h> #include <linux/io.h> #include <asm/irq.h> #include <mach/sysasic.h> /* * Dreamcast System ASIC Hardware Events - * * The Dreamcast's System ASIC (a.k.a. Holly) is responsible for receiving * hardware events from system peripherals and triggering an SH7750 IRQ. * Hardware events can trigger IRQs 13, 11, or 9 depending on which bits are * set in the Event Mask Registers (EMRs). When a hardware event is * triggered, its corresponding bit in the Event Status Registers (ESRs) * is set, and that bit should be rewritten to the ESR to acknowledge that * event. * * There are three 32-bit ESRs located at 0xa05f6900 - 0xa05f6908. Event * types can be found in arch/sh/include/mach-dreamcast/mach/sysasic.h. * There are three groups of EMRs that parallel the ESRs. Each EMR group * corresponds to an IRQ, so 0xa05f6910 - 0xa05f6918 triggers IRQ 13, * 0xa05f6920 - 0xa05f6928 triggers IRQ 11, and 0xa05f6930 - 0xa05f6938 * triggers IRQ 9. * * In the kernel, these events are mapped to virtual IRQs so that drivers can * respond to them as they would a normal interrupt. In order to keep this * mapping simple, the events are mapped as: * * 6900/6910 - Events 0-31, IRQ 13 * 6904/6924 - Events 32-63, IRQ 11 * 6908/6938 - Events 64-95, IRQ 9 * */ #define ESR_BASE 0x005f6900 /* Base event status register */ #define EMR_BASE 0x005f6910 /* Base event mask register */ /* * Helps us determine the EMR group that this event belongs to: 0 = 0x6910, * 1 = 0x6920, 2 = 0x6930; also determine the event offset. */ #define LEVEL(event) (((event) - HW_EVENT_IRQ_BASE) / 32) /* Return the hardware event's bit position within the EMR/ESR */ #define EVENT_BIT(event) (((event) - HW_EVENT_IRQ_BASE) & 31) /* * For each of these *_irq routines, the IRQ passed in is the virtual IRQ * (logically mapped to the corresponding bit for the hardware event). */ /* Disable the hardware event by masking its bit in its EMR */ static inline void disable_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2); __u32 mask; mask = inl(emr); mask &= ~(1 << EVENT_BIT(irq)); outl(mask, emr); } /* Enable the hardware event by setting its bit in its EMR */ static inline void enable_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2); __u32 mask; mask = inl(emr); mask |= (1 << EVENT_BIT(irq)); outl(mask, emr); } /* Acknowledge a hardware event by writing its bit back to its ESR */ static void mask_ack_systemasic_irq(struct irq_data *data) { unsigned int irq = data->irq; __u32 esr = ESR_BASE + (LEVEL(irq) << 2); disable_systemasic_irq(data); outl((1 << EVENT_BIT(irq)), esr); } struct irq_chip systemasic_int = { .name = "System ASIC", .irq_mask = disable_systemasic_irq, .irq_mask_ack = mask_ack_systemasic_irq, .irq_unmask = enable_systemasic_irq, }; /* * Map the hardware event indicated by the processor IRQ to a virtual IRQ. */ int systemasic_irq_demux(int irq) { __u32 emr, esr, status, level; __u32 j, bit; switch (irq) { case 13: level = 0; break; case 11: level = 1; break; case 9: level = 2; break; default: return irq; } emr = EMR_BASE + (level << 4) + (level << 2); esr = ESR_BASE + (level << 2); /* Mask the ESR to filter any spurious, unwanted interrupts */ status = inl(esr); status &= inl(emr); /* Now scan and find the first set bit as the event to map */ for (bit = 1, j = 0; j < 32; bit <<= 1, j++) { if (status & bit) { irq = HW_EVENT_IRQ_BASE + j + (level << 5); return irq; } } /* Not reached */ return irq; } void systemasic_irq_init(void) { int i, nid = cpu_to_node(boot_cpu_data); /* Assign all virtual IRQs to the System ASIC int. handler */ for (i = HW_EVENT_IRQ_BASE; i < HW_EVENT_IRQ_MAX; i++) { unsigned int irq; irq = create_irq_nr(i, nid); if (unlikely(irq == 0)) { pr_err("%s: failed hooking irq %d for systemasic\n", __func__, i); return; } if (unlikely(irq != i)) { pr_err("%s: got irq %d but wanted %d, bailing.\n", __func__, irq, i); destroy_irq(irq); return; } irq_set_chip_and_handler(i, &systemasic_int, handle_level_irq); } }
gpl-2.0
syphyr/android_kernel_lge_awifi
arch/arm/mach-ixp4xx/ixp4xx_npe.c
8983
21541
/* * Intel IXP4xx Network Processor Engine driver for Linux * * Copyright (C) 2007 Krzysztof Halasa <khc@pm.waw.pl> * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. * * The code is based on publicly available information: * - Intel IXP4xx Developer's Manual and other e-papers * - Intel IXP400 Access Library Software (BSD license) * - previous works by Christian Hohnstaedt <chohnstaedt@innominate.com> * Thanks, Christian. */ #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/firmware.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/module.h> #include <mach/npe.h> #define DEBUG_MSG 0 #define DEBUG_FW 0 #define NPE_COUNT 3 #define MAX_RETRIES 1000 /* microseconds */ #define NPE_42X_DATA_SIZE 0x800 /* in dwords */ #define NPE_46X_DATA_SIZE 0x1000 #define NPE_A_42X_INSTR_SIZE 0x1000 #define NPE_B_AND_C_42X_INSTR_SIZE 0x800 #define NPE_46X_INSTR_SIZE 0x1000 #define REGS_SIZE 0x1000 #define NPE_PHYS_REG 32 #define FW_MAGIC 0xFEEDF00D #define FW_BLOCK_TYPE_INSTR 0x0 #define FW_BLOCK_TYPE_DATA 0x1 #define FW_BLOCK_TYPE_EOF 0xF /* NPE exec status (read) and command (write) */ #define CMD_NPE_STEP 0x01 #define CMD_NPE_START 0x02 #define CMD_NPE_STOP 0x03 #define CMD_NPE_CLR_PIPE 0x04 #define CMD_CLR_PROFILE_CNT 0x0C #define CMD_RD_INS_MEM 0x10 /* instruction memory */ #define CMD_WR_INS_MEM 0x11 #define CMD_RD_DATA_MEM 0x12 /* data memory */ #define CMD_WR_DATA_MEM 0x13 #define CMD_RD_ECS_REG 0x14 /* exec access register */ #define CMD_WR_ECS_REG 0x15 #define STAT_RUN 0x80000000 #define STAT_STOP 0x40000000 #define STAT_CLEAR 0x20000000 #define STAT_ECS_K 0x00800000 /* pipeline clean */ #define NPE_STEVT 0x1B #define NPE_STARTPC 0x1C #define NPE_REGMAP 0x1E #define NPE_CINDEX 0x1F #define INSTR_WR_REG_SHORT 0x0000C000 #define INSTR_WR_REG_BYTE 0x00004000 #define INSTR_RD_FIFO 0x0F888220 #define INSTR_RESET_MBOX 0x0FAC8210 #define ECS_BG_CTXT_REG_0 0x00 /* Background Executing Context */ #define ECS_BG_CTXT_REG_1 0x01 /* Stack level */ #define ECS_BG_CTXT_REG_2 0x02 #define ECS_PRI_1_CTXT_REG_0 0x04 /* Priority 1 Executing Context */ #define ECS_PRI_1_CTXT_REG_1 0x05 /* Stack level */ #define ECS_PRI_1_CTXT_REG_2 0x06 #define ECS_PRI_2_CTXT_REG_0 0x08 /* Priority 2 Executing Context */ #define ECS_PRI_2_CTXT_REG_1 0x09 /* Stack level */ #define ECS_PRI_2_CTXT_REG_2 0x0A #define ECS_DBG_CTXT_REG_0 0x0C /* Debug Executing Context */ #define ECS_DBG_CTXT_REG_1 0x0D /* Stack level */ #define ECS_DBG_CTXT_REG_2 0x0E #define ECS_INSTRUCT_REG 0x11 /* NPE Instruction Register */ #define ECS_REG_0_ACTIVE 0x80000000 /* all levels */ #define ECS_REG_0_NEXTPC_MASK 0x1FFF0000 /* BG/PRI1/PRI2 levels */ #define ECS_REG_0_LDUR_BITS 8 #define ECS_REG_0_LDUR_MASK 0x00000700 /* all levels */ #define ECS_REG_1_CCTXT_BITS 16 #define ECS_REG_1_CCTXT_MASK 0x000F0000 /* all levels */ #define ECS_REG_1_SELCTXT_BITS 0 #define ECS_REG_1_SELCTXT_MASK 0x0000000F /* all levels */ #define ECS_DBG_REG_2_IF 0x00100000 /* debug level */ #define ECS_DBG_REG_2_IE 0x00080000 /* debug level */ /* NPE watchpoint_fifo register bit */ #define WFIFO_VALID 0x80000000 /* NPE messaging_status register bit definitions */ #define MSGSTAT_OFNE 0x00010000 /* OutFifoNotEmpty */ #define MSGSTAT_IFNF 0x00020000 /* InFifoNotFull */ #define MSGSTAT_OFNF 0x00040000 /* OutFifoNotFull */ #define MSGSTAT_IFNE 0x00080000 /* InFifoNotEmpty */ #define MSGSTAT_MBINT 0x00100000 /* Mailbox interrupt */ #define MSGSTAT_IFINT 0x00200000 /* InFifo interrupt */ #define MSGSTAT_OFINT 0x00400000 /* OutFifo interrupt */ #define MSGSTAT_WFINT 0x00800000 /* WatchFifo interrupt */ /* NPE messaging_control register bit definitions */ #define MSGCTL_OUT_FIFO 0x00010000 /* enable output FIFO */ #define MSGCTL_IN_FIFO 0x00020000 /* enable input FIFO */ #define MSGCTL_OUT_FIFO_WRITE 0x01000000 /* enable FIFO + WRITE */ #define MSGCTL_IN_FIFO_WRITE 0x02000000 /* NPE mailbox_status value for reset */ #define RESET_MBOX_STAT 0x0000F0F0 const char *npe_names[] = { "NPE-A", "NPE-B", "NPE-C" }; #define print_npe(pri, npe, fmt, ...) \ printk(pri "%s: " fmt, npe_name(npe), ## __VA_ARGS__) #if DEBUG_MSG #define debug_msg(npe, fmt, ...) \ print_npe(KERN_DEBUG, npe, fmt, ## __VA_ARGS__) #else #define debug_msg(npe, fmt, ...) #endif static struct { u32 reg, val; } ecs_reset[] = { { ECS_BG_CTXT_REG_0, 0xA0000000 }, { ECS_BG_CTXT_REG_1, 0x01000000 }, { ECS_BG_CTXT_REG_2, 0x00008000 }, { ECS_PRI_1_CTXT_REG_0, 0x20000080 }, { ECS_PRI_1_CTXT_REG_1, 0x01000000 }, { ECS_PRI_1_CTXT_REG_2, 0x00008000 }, { ECS_PRI_2_CTXT_REG_0, 0x20000080 }, { ECS_PRI_2_CTXT_REG_1, 0x01000000 }, { ECS_PRI_2_CTXT_REG_2, 0x00008000 }, { ECS_DBG_CTXT_REG_0, 0x20000000 }, { ECS_DBG_CTXT_REG_1, 0x00000000 }, { ECS_DBG_CTXT_REG_2, 0x001E0000 }, { ECS_INSTRUCT_REG, 0x1003C00F }, }; static struct npe npe_tab[NPE_COUNT] = { { .id = 0, .regs = (struct npe_regs __iomem *)IXP4XX_NPEA_BASE_VIRT, .regs_phys = IXP4XX_NPEA_BASE_PHYS, }, { .id = 1, .regs = (struct npe_regs __iomem *)IXP4XX_NPEB_BASE_VIRT, .regs_phys = IXP4XX_NPEB_BASE_PHYS, }, { .id = 2, .regs = (struct npe_regs __iomem *)IXP4XX_NPEC_BASE_VIRT, .regs_phys = IXP4XX_NPEC_BASE_PHYS, } }; int npe_running(struct npe *npe) { return (__raw_readl(&npe->regs->exec_status_cmd) & STAT_RUN) != 0; } static void npe_cmd_write(struct npe *npe, u32 addr, int cmd, u32 data) { __raw_writel(data, &npe->regs->exec_data); __raw_writel(addr, &npe->regs->exec_addr); __raw_writel(cmd, &npe->regs->exec_status_cmd); } static u32 npe_cmd_read(struct npe *npe, u32 addr, int cmd) { __raw_writel(addr, &npe->regs->exec_addr); __raw_writel(cmd, &npe->regs->exec_status_cmd); /* Iintroduce extra read cycles after issuing read command to NPE so that we read the register after the NPE has updated it. This is to overcome race condition between XScale and NPE */ __raw_readl(&npe->regs->exec_data); __raw_readl(&npe->regs->exec_data); return __raw_readl(&npe->regs->exec_data); } static void npe_clear_active(struct npe *npe, u32 reg) { u32 val = npe_cmd_read(npe, reg, CMD_RD_ECS_REG); npe_cmd_write(npe, reg, CMD_WR_ECS_REG, val & ~ECS_REG_0_ACTIVE); } static void npe_start(struct npe *npe) { /* ensure only Background Context Stack Level is active */ npe_clear_active(npe, ECS_PRI_1_CTXT_REG_0); npe_clear_active(npe, ECS_PRI_2_CTXT_REG_0); npe_clear_active(npe, ECS_DBG_CTXT_REG_0); __raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd); __raw_writel(CMD_NPE_START, &npe->regs->exec_status_cmd); } static void npe_stop(struct npe *npe) { __raw_writel(CMD_NPE_STOP, &npe->regs->exec_status_cmd); __raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd); /*FIXME?*/ } static int __must_check npe_debug_instr(struct npe *npe, u32 instr, u32 ctx, u32 ldur) { u32 wc; int i; /* set the Active bit, and the LDUR, in the debug level */ npe_cmd_write(npe, ECS_DBG_CTXT_REG_0, CMD_WR_ECS_REG, ECS_REG_0_ACTIVE | (ldur << ECS_REG_0_LDUR_BITS)); /* set CCTXT at ECS DEBUG L3 to specify in which context to execute the instruction, and set SELCTXT at ECS DEBUG Level to specify which context store to access. Debug ECS Level Reg 1 has form 0x000n000n, where n = context number */ npe_cmd_write(npe, ECS_DBG_CTXT_REG_1, CMD_WR_ECS_REG, (ctx << ECS_REG_1_CCTXT_BITS) | (ctx << ECS_REG_1_SELCTXT_BITS)); /* clear the pipeline */ __raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd); /* load NPE instruction into the instruction register */ npe_cmd_write(npe, ECS_INSTRUCT_REG, CMD_WR_ECS_REG, instr); /* we need this value later to wait for completion of NPE execution step */ wc = __raw_readl(&npe->regs->watch_count); /* issue a Step One command via the Execution Control register */ __raw_writel(CMD_NPE_STEP, &npe->regs->exec_status_cmd); /* Watch Count register increments when NPE completes an instruction */ for (i = 0; i < MAX_RETRIES; i++) { if (wc != __raw_readl(&npe->regs->watch_count)) return 0; udelay(1); } print_npe(KERN_ERR, npe, "reset: npe_debug_instr(): timeout\n"); return -ETIMEDOUT; } static int __must_check npe_logical_reg_write8(struct npe *npe, u32 addr, u8 val, u32 ctx) { /* here we build the NPE assembler instruction: mov8 d0, #0 */ u32 instr = INSTR_WR_REG_BYTE | /* OpCode */ addr << 9 | /* base Operand */ (val & 0x1F) << 4 | /* lower 5 bits to immediate data */ (val & ~0x1F) << (18 - 5);/* higher 3 bits to CoProc instr. */ return npe_debug_instr(npe, instr, ctx, 1); /* execute it */ } static int __must_check npe_logical_reg_write16(struct npe *npe, u32 addr, u16 val, u32 ctx) { /* here we build the NPE assembler instruction: mov16 d0, #0 */ u32 instr = INSTR_WR_REG_SHORT | /* OpCode */ addr << 9 | /* base Operand */ (val & 0x1F) << 4 | /* lower 5 bits to immediate data */ (val & ~0x1F) << (18 - 5);/* higher 11 bits to CoProc instr. */ return npe_debug_instr(npe, instr, ctx, 1); /* execute it */ } static int __must_check npe_logical_reg_write32(struct npe *npe, u32 addr, u32 val, u32 ctx) { /* write in 16 bit steps first the high and then the low value */ if (npe_logical_reg_write16(npe, addr, val >> 16, ctx)) return -ETIMEDOUT; return npe_logical_reg_write16(npe, addr + 2, val & 0xFFFF, ctx); } static int npe_reset(struct npe *npe) { u32 val, ctl, exec_count, ctx_reg2; int i; ctl = (__raw_readl(&npe->regs->messaging_control) | 0x3F000000) & 0x3F3FFFFF; /* disable parity interrupt */ __raw_writel(ctl & 0x3F00FFFF, &npe->regs->messaging_control); /* pre exec - debug instruction */ /* turn off the halt bit by clearing Execution Count register. */ exec_count = __raw_readl(&npe->regs->exec_count); __raw_writel(0, &npe->regs->exec_count); /* ensure that IF and IE are on (temporarily), so that we don't end up stepping forever */ ctx_reg2 = npe_cmd_read(npe, ECS_DBG_CTXT_REG_2, CMD_RD_ECS_REG); npe_cmd_write(npe, ECS_DBG_CTXT_REG_2, CMD_WR_ECS_REG, ctx_reg2 | ECS_DBG_REG_2_IF | ECS_DBG_REG_2_IE); /* clear the FIFOs */ while (__raw_readl(&npe->regs->watchpoint_fifo) & WFIFO_VALID) ; while (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_OFNE) /* read from the outFIFO until empty */ print_npe(KERN_DEBUG, npe, "npe_reset: read FIFO = 0x%X\n", __raw_readl(&npe->regs->in_out_fifo)); while (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE) /* step execution of the NPE intruction to read inFIFO using the Debug Executing Context stack */ if (npe_debug_instr(npe, INSTR_RD_FIFO, 0, 0)) return -ETIMEDOUT; /* reset the mailbox reg from the XScale side */ __raw_writel(RESET_MBOX_STAT, &npe->regs->mailbox_status); /* from NPE side */ if (npe_debug_instr(npe, INSTR_RESET_MBOX, 0, 0)) return -ETIMEDOUT; /* Reset the physical registers in the NPE register file */ for (val = 0; val < NPE_PHYS_REG; val++) { if (npe_logical_reg_write16(npe, NPE_REGMAP, val >> 1, 0)) return -ETIMEDOUT; /* address is either 0 or 4 */ if (npe_logical_reg_write32(npe, (val & 1) * 4, 0, 0)) return -ETIMEDOUT; } /* Reset the context store = each context's Context Store registers */ /* Context 0 has no STARTPC. Instead, this value is used to set NextPC for Background ECS, to set where NPE starts executing code */ val = npe_cmd_read(npe, ECS_BG_CTXT_REG_0, CMD_RD_ECS_REG); val &= ~ECS_REG_0_NEXTPC_MASK; val |= (0 /* NextPC */ << 16) & ECS_REG_0_NEXTPC_MASK; npe_cmd_write(npe, ECS_BG_CTXT_REG_0, CMD_WR_ECS_REG, val); for (i = 0; i < 16; i++) { if (i) { /* Context 0 has no STEVT nor STARTPC */ /* STEVT = off, 0x80 */ if (npe_logical_reg_write8(npe, NPE_STEVT, 0x80, i)) return -ETIMEDOUT; if (npe_logical_reg_write16(npe, NPE_STARTPC, 0, i)) return -ETIMEDOUT; } /* REGMAP = d0->p0, d8->p2, d16->p4 */ if (npe_logical_reg_write16(npe, NPE_REGMAP, 0x820, i)) return -ETIMEDOUT; if (npe_logical_reg_write8(npe, NPE_CINDEX, 0, i)) return -ETIMEDOUT; } /* post exec */ /* clear active bit in debug level */ npe_cmd_write(npe, ECS_DBG_CTXT_REG_0, CMD_WR_ECS_REG, 0); /* clear the pipeline */ __raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd); /* restore previous values */ __raw_writel(exec_count, &npe->regs->exec_count); npe_cmd_write(npe, ECS_DBG_CTXT_REG_2, CMD_WR_ECS_REG, ctx_reg2); /* write reset values to Execution Context Stack registers */ for (val = 0; val < ARRAY_SIZE(ecs_reset); val++) npe_cmd_write(npe, ecs_reset[val].reg, CMD_WR_ECS_REG, ecs_reset[val].val); /* clear the profile counter */ __raw_writel(CMD_CLR_PROFILE_CNT, &npe->regs->exec_status_cmd); __raw_writel(0, &npe->regs->exec_count); __raw_writel(0, &npe->regs->action_points[0]); __raw_writel(0, &npe->regs->action_points[1]); __raw_writel(0, &npe->regs->action_points[2]); __raw_writel(0, &npe->regs->action_points[3]); __raw_writel(0, &npe->regs->watch_count); val = ixp4xx_read_feature_bits(); /* reset the NPE */ ixp4xx_write_feature_bits(val & ~(IXP4XX_FEATURE_RESET_NPEA << npe->id)); /* deassert reset */ ixp4xx_write_feature_bits(val | (IXP4XX_FEATURE_RESET_NPEA << npe->id)); for (i = 0; i < MAX_RETRIES; i++) { if (ixp4xx_read_feature_bits() & (IXP4XX_FEATURE_RESET_NPEA << npe->id)) break; /* NPE is back alive */ udelay(1); } if (i == MAX_RETRIES) return -ETIMEDOUT; npe_stop(npe); /* restore NPE configuration bus Control Register - parity settings */ __raw_writel(ctl, &npe->regs->messaging_control); return 0; } int npe_send_message(struct npe *npe, const void *msg, const char *what) { const u32 *send = msg; int cycles = 0; debug_msg(npe, "Trying to send message %s [%08X:%08X]\n", what, send[0], send[1]); if (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE) { debug_msg(npe, "NPE input FIFO not empty\n"); return -EIO; } __raw_writel(send[0], &npe->regs->in_out_fifo); if (!(__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNF)) { debug_msg(npe, "NPE input FIFO full\n"); return -EIO; } __raw_writel(send[1], &npe->regs->in_out_fifo); while ((cycles < MAX_RETRIES) && (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE)) { udelay(1); cycles++; } if (cycles == MAX_RETRIES) { debug_msg(npe, "Timeout sending message\n"); return -ETIMEDOUT; } #if DEBUG_MSG > 1 debug_msg(npe, "Sending a message took %i cycles\n", cycles); #endif return 0; } int npe_recv_message(struct npe *npe, void *msg, const char *what) { u32 *recv = msg; int cycles = 0, cnt = 0; debug_msg(npe, "Trying to receive message %s\n", what); while (cycles < MAX_RETRIES) { if (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_OFNE) { recv[cnt++] = __raw_readl(&npe->regs->in_out_fifo); if (cnt == 2) break; } else { udelay(1); cycles++; } } switch(cnt) { case 1: debug_msg(npe, "Received [%08X]\n", recv[0]); break; case 2: debug_msg(npe, "Received [%08X:%08X]\n", recv[0], recv[1]); break; } if (cycles == MAX_RETRIES) { debug_msg(npe, "Timeout waiting for message\n"); return -ETIMEDOUT; } #if DEBUG_MSG > 1 debug_msg(npe, "Receiving a message took %i cycles\n", cycles); #endif return 0; } int npe_send_recv_message(struct npe *npe, void *msg, const char *what) { int result; u32 *send = msg, recv[2]; if ((result = npe_send_message(npe, msg, what)) != 0) return result; if ((result = npe_recv_message(npe, recv, what)) != 0) return result; if ((recv[0] != send[0]) || (recv[1] != send[1])) { debug_msg(npe, "Message %s: unexpected message received\n", what); return -EIO; } return 0; } int npe_load_firmware(struct npe *npe, const char *name, struct device *dev) { const struct firmware *fw_entry; struct dl_block { u32 type; u32 offset; } *blk; struct dl_image { u32 magic; u32 id; u32 size; union { u32 data[0]; struct dl_block blocks[0]; }; } *image; struct dl_codeblock { u32 npe_addr; u32 size; u32 data[0]; } *cb; int i, j, err, data_size, instr_size, blocks, table_end; u32 cmd; if ((err = request_firmware(&fw_entry, name, dev)) != 0) return err; err = -EINVAL; if (fw_entry->size < sizeof(struct dl_image)) { print_npe(KERN_ERR, npe, "incomplete firmware file\n"); goto err; } image = (struct dl_image*)fw_entry->data; #if DEBUG_FW print_npe(KERN_DEBUG, npe, "firmware: %08X %08X %08X (0x%X bytes)\n", image->magic, image->id, image->size, image->size * 4); #endif if (image->magic == swab32(FW_MAGIC)) { /* swapped file */ image->id = swab32(image->id); image->size = swab32(image->size); } else if (image->magic != FW_MAGIC) { print_npe(KERN_ERR, npe, "bad firmware file magic: 0x%X\n", image->magic); goto err; } if ((image->size * 4 + sizeof(struct dl_image)) != fw_entry->size) { print_npe(KERN_ERR, npe, "inconsistent size of firmware file\n"); goto err; } if (((image->id >> 24) & 0xF /* NPE ID */) != npe->id) { print_npe(KERN_ERR, npe, "firmware file NPE ID mismatch\n"); goto err; } if (image->magic == swab32(FW_MAGIC)) for (i = 0; i < image->size; i++) image->data[i] = swab32(image->data[i]); if (cpu_is_ixp42x() && ((image->id >> 28) & 0xF /* device ID */)) { print_npe(KERN_INFO, npe, "IXP43x/IXP46x firmware ignored on " "IXP42x\n"); goto err; } if (npe_running(npe)) { print_npe(KERN_INFO, npe, "unable to load firmware, NPE is " "already running\n"); err = -EBUSY; goto err; } #if 0 npe_stop(npe); npe_reset(npe); #endif print_npe(KERN_INFO, npe, "firmware functionality 0x%X, " "revision 0x%X:%X\n", (image->id >> 16) & 0xFF, (image->id >> 8) & 0xFF, image->id & 0xFF); if (cpu_is_ixp42x()) { if (!npe->id) instr_size = NPE_A_42X_INSTR_SIZE; else instr_size = NPE_B_AND_C_42X_INSTR_SIZE; data_size = NPE_42X_DATA_SIZE; } else { instr_size = NPE_46X_INSTR_SIZE; data_size = NPE_46X_DATA_SIZE; } for (blocks = 0; blocks * sizeof(struct dl_block) / 4 < image->size; blocks++) if (image->blocks[blocks].type == FW_BLOCK_TYPE_EOF) break; if (blocks * sizeof(struct dl_block) / 4 >= image->size) { print_npe(KERN_INFO, npe, "firmware EOF block marker not " "found\n"); goto err; } #if DEBUG_FW print_npe(KERN_DEBUG, npe, "%i firmware blocks found\n", blocks); #endif table_end = blocks * sizeof(struct dl_block) / 4 + 1 /* EOF marker */; for (i = 0, blk = image->blocks; i < blocks; i++, blk++) { if (blk->offset > image->size - sizeof(struct dl_codeblock) / 4 || blk->offset < table_end) { print_npe(KERN_INFO, npe, "invalid offset 0x%X of " "firmware block #%i\n", blk->offset, i); goto err; } cb = (struct dl_codeblock*)&image->data[blk->offset]; if (blk->type == FW_BLOCK_TYPE_INSTR) { if (cb->npe_addr + cb->size > instr_size) goto too_big; cmd = CMD_WR_INS_MEM; } else if (blk->type == FW_BLOCK_TYPE_DATA) { if (cb->npe_addr + cb->size > data_size) goto too_big; cmd = CMD_WR_DATA_MEM; } else { print_npe(KERN_INFO, npe, "invalid firmware block #%i " "type 0x%X\n", i, blk->type); goto err; } if (blk->offset + sizeof(*cb) / 4 + cb->size > image->size) { print_npe(KERN_INFO, npe, "firmware block #%i doesn't " "fit in firmware image: type %c, start 0x%X," " length 0x%X\n", i, blk->type == FW_BLOCK_TYPE_INSTR ? 'I' : 'D', cb->npe_addr, cb->size); goto err; } for (j = 0; j < cb->size; j++) npe_cmd_write(npe, cb->npe_addr + j, cmd, cb->data[j]); } npe_start(npe); if (!npe_running(npe)) print_npe(KERN_ERR, npe, "unable to start\n"); release_firmware(fw_entry); return 0; too_big: print_npe(KERN_INFO, npe, "firmware block #%i doesn't fit in NPE " "memory: type %c, start 0x%X, length 0x%X\n", i, blk->type == FW_BLOCK_TYPE_INSTR ? 'I' : 'D', cb->npe_addr, cb->size); err: release_firmware(fw_entry); return err; } struct npe *npe_request(unsigned id) { if (id < NPE_COUNT) if (npe_tab[id].valid) if (try_module_get(THIS_MODULE)) return &npe_tab[id]; return NULL; } void npe_release(struct npe *npe) { module_put(THIS_MODULE); } static int __init npe_init_module(void) { int i, found = 0; for (i = 0; i < NPE_COUNT; i++) { struct npe *npe = &npe_tab[i]; if (!(ixp4xx_read_feature_bits() & (IXP4XX_FEATURE_RESET_NPEA << i))) continue; /* NPE already disabled or not present */ if (!(npe->mem_res = request_mem_region(npe->regs_phys, REGS_SIZE, npe_name(npe)))) { print_npe(KERN_ERR, npe, "failed to request memory region\n"); continue; } if (npe_reset(npe)) continue; npe->valid = 1; found++; } if (!found) return -ENODEV; return 0; } static void __exit npe_cleanup_module(void) { int i; for (i = 0; i < NPE_COUNT; i++) if (npe_tab[i].mem_res) { npe_reset(&npe_tab[i]); release_resource(npe_tab[i].mem_res); } } module_init(npe_init_module); module_exit(npe_cleanup_module); MODULE_AUTHOR("Krzysztof Halasa"); MODULE_LICENSE("GPL v2"); EXPORT_SYMBOL(npe_names); EXPORT_SYMBOL(npe_running); EXPORT_SYMBOL(npe_request); EXPORT_SYMBOL(npe_release); EXPORT_SYMBOL(npe_load_firmware); EXPORT_SYMBOL(npe_send_message); EXPORT_SYMBOL(npe_recv_message); EXPORT_SYMBOL(npe_send_recv_message);
gpl-2.0
chrisch1974/htc8960-3.4
drivers/tty/serial/8250/8250_gsc.c
9239
3596
/* * Serial Device Initialisation for Lasi/Asp/Wax/Dino * * (c) Copyright Matthew Wilcox <willy@debian.org> 2001-2002 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/errno.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/module.h> #include <linux/serial_core.h> #include <linux/signal.h> #include <linux/types.h> #include <asm/hardware.h> #include <asm/parisc-device.h> #include <asm/io.h> #include "8250.h" static int __init serial_init_chip(struct parisc_device *dev) { struct uart_port port; unsigned long address; int err; if (!dev->irq) { /* We find some unattached serial ports by walking native * busses. These should be silently ignored. Otherwise, * what we have here is a missing parent device, so tell * the user what they're missing. */ if (parisc_parent(dev)->id.hw_type != HPHW_IOA) printk(KERN_INFO "Serial: device 0x%llx not configured.\n" "Enable support for Wax, Lasi, Asp or Dino.\n", (unsigned long long)dev->hpa.start); return -ENODEV; } address = dev->hpa.start; if (dev->id.sversion != 0x8d) address += 0x800; memset(&port, 0, sizeof(port)); port.iotype = UPIO_MEM; /* 7.272727MHz on Lasi. Assumed the same for Dino, Wax and Timi. */ port.uartclk = 7272727; port.mapbase = address; port.membase = ioremap_nocache(address, 16); port.irq = dev->irq; port.flags = UPF_BOOT_AUTOCONF; port.dev = &dev->dev; err = serial8250_register_port(&port); if (err < 0) { printk(KERN_WARNING "serial8250_register_port returned error %d\n", err); iounmap(port.membase); return err; } return 0; } static struct parisc_device_id serial_tbl[] = { { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00075 }, { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0008c }, { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0008d }, { 0 } }; /* Hack. Some machines have SERIAL_0 attached to Lasi and SERIAL_1 * attached to Dino. Unfortunately, Dino appears before Lasi in the device * tree. To ensure that ttyS0 == SERIAL_0, we register two drivers; one * which only knows about Lasi and then a second which will find all the * other serial ports. HPUX ignores this problem. */ static struct parisc_device_id lasi_tbl[] = { { HPHW_FIO, HVERSION_REV_ANY_ID, 0x03B, 0x0008C }, /* C1xx/C1xxL */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x03C, 0x0008C }, /* B132L */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x03D, 0x0008C }, /* B160L */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x03E, 0x0008C }, /* B132L+ */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x03F, 0x0008C }, /* B180L+ */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x046, 0x0008C }, /* Rocky2 120 */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x047, 0x0008C }, /* Rocky2 150 */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x04E, 0x0008C }, /* Kiji L2 132 */ { HPHW_FIO, HVERSION_REV_ANY_ID, 0x056, 0x0008C }, /* Raven+ */ { 0 } }; MODULE_DEVICE_TABLE(parisc, serial_tbl); static struct parisc_driver lasi_driver = { .name = "serial_1", .id_table = lasi_tbl, .probe = serial_init_chip, }; static struct parisc_driver serial_driver = { .name = "serial", .id_table = serial_tbl, .probe = serial_init_chip, }; static int __init probe_serial_gsc(void) { register_parisc_driver(&lasi_driver); register_parisc_driver(&serial_driver); return 0; } module_init(probe_serial_gsc); MODULE_LICENSE("GPL");
gpl-2.0
derekcentrico/m6.kernel.3.x
arch/ia64/kvm/asm-offsets.c
11799
9551
/* * asm-offsets.c Generate definitions needed by assembly language modules. * This code generates raw asm output which is post-processed * to extract and format the required data. * * Anthony Xu <anthony.xu@intel.com> * Xiantao Zhang <xiantao.zhang@intel.com> * Copyright (c) 2007 Intel Corporation KVM support. * * 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., 59 Temple * Place - Suite 330, Boston, MA 02111-1307 USA. * */ #include <linux/kvm_host.h> #include <linux/kbuild.h> #include "vcpu.h" void foo(void) { DEFINE(VMM_TASK_SIZE, sizeof(struct kvm_vcpu)); DEFINE(VMM_PT_REGS_SIZE, sizeof(struct kvm_pt_regs)); BLANK(); DEFINE(VMM_VCPU_META_RR0_OFFSET, offsetof(struct kvm_vcpu, arch.metaphysical_rr0)); DEFINE(VMM_VCPU_META_SAVED_RR0_OFFSET, offsetof(struct kvm_vcpu, arch.metaphysical_saved_rr0)); DEFINE(VMM_VCPU_VRR0_OFFSET, offsetof(struct kvm_vcpu, arch.vrr[0])); DEFINE(VMM_VPD_IRR0_OFFSET, offsetof(struct vpd, irr[0])); DEFINE(VMM_VCPU_ITC_CHECK_OFFSET, offsetof(struct kvm_vcpu, arch.itc_check)); DEFINE(VMM_VCPU_IRQ_CHECK_OFFSET, offsetof(struct kvm_vcpu, arch.irq_check)); DEFINE(VMM_VPD_VHPI_OFFSET, offsetof(struct vpd, vhpi)); DEFINE(VMM_VCPU_VSA_BASE_OFFSET, offsetof(struct kvm_vcpu, arch.vsa_base)); DEFINE(VMM_VCPU_VPD_OFFSET, offsetof(struct kvm_vcpu, arch.vpd)); DEFINE(VMM_VCPU_IRQ_CHECK, offsetof(struct kvm_vcpu, arch.irq_check)); DEFINE(VMM_VCPU_TIMER_PENDING, offsetof(struct kvm_vcpu, arch.timer_pending)); DEFINE(VMM_VCPU_META_SAVED_RR0_OFFSET, offsetof(struct kvm_vcpu, arch.metaphysical_saved_rr0)); DEFINE(VMM_VCPU_MODE_FLAGS_OFFSET, offsetof(struct kvm_vcpu, arch.mode_flags)); DEFINE(VMM_VCPU_ITC_OFS_OFFSET, offsetof(struct kvm_vcpu, arch.itc_offset)); DEFINE(VMM_VCPU_LAST_ITC_OFFSET, offsetof(struct kvm_vcpu, arch.last_itc)); DEFINE(VMM_VCPU_SAVED_GP_OFFSET, offsetof(struct kvm_vcpu, arch.saved_gp)); BLANK(); DEFINE(VMM_PT_REGS_B6_OFFSET, offsetof(struct kvm_pt_regs, b6)); DEFINE(VMM_PT_REGS_B7_OFFSET, offsetof(struct kvm_pt_regs, b7)); DEFINE(VMM_PT_REGS_AR_CSD_OFFSET, offsetof(struct kvm_pt_regs, ar_csd)); DEFINE(VMM_PT_REGS_AR_SSD_OFFSET, offsetof(struct kvm_pt_regs, ar_ssd)); DEFINE(VMM_PT_REGS_R8_OFFSET, offsetof(struct kvm_pt_regs, r8)); DEFINE(VMM_PT_REGS_R9_OFFSET, offsetof(struct kvm_pt_regs, r9)); DEFINE(VMM_PT_REGS_R10_OFFSET, offsetof(struct kvm_pt_regs, r10)); DEFINE(VMM_PT_REGS_R11_OFFSET, offsetof(struct kvm_pt_regs, r11)); DEFINE(VMM_PT_REGS_CR_IPSR_OFFSET, offsetof(struct kvm_pt_regs, cr_ipsr)); DEFINE(VMM_PT_REGS_CR_IIP_OFFSET, offsetof(struct kvm_pt_regs, cr_iip)); DEFINE(VMM_PT_REGS_CR_IFS_OFFSET, offsetof(struct kvm_pt_regs, cr_ifs)); DEFINE(VMM_PT_REGS_AR_UNAT_OFFSET, offsetof(struct kvm_pt_regs, ar_unat)); DEFINE(VMM_PT_REGS_AR_PFS_OFFSET, offsetof(struct kvm_pt_regs, ar_pfs)); DEFINE(VMM_PT_REGS_AR_RSC_OFFSET, offsetof(struct kvm_pt_regs, ar_rsc)); DEFINE(VMM_PT_REGS_AR_RNAT_OFFSET, offsetof(struct kvm_pt_regs, ar_rnat)); DEFINE(VMM_PT_REGS_AR_BSPSTORE_OFFSET, offsetof(struct kvm_pt_regs, ar_bspstore)); DEFINE(VMM_PT_REGS_PR_OFFSET, offsetof(struct kvm_pt_regs, pr)); DEFINE(VMM_PT_REGS_B0_OFFSET, offsetof(struct kvm_pt_regs, b0)); DEFINE(VMM_PT_REGS_LOADRS_OFFSET, offsetof(struct kvm_pt_regs, loadrs)); DEFINE(VMM_PT_REGS_R1_OFFSET, offsetof(struct kvm_pt_regs, r1)); DEFINE(VMM_PT_REGS_R12_OFFSET, offsetof(struct kvm_pt_regs, r12)); DEFINE(VMM_PT_REGS_R13_OFFSET, offsetof(struct kvm_pt_regs, r13)); DEFINE(VMM_PT_REGS_AR_FPSR_OFFSET, offsetof(struct kvm_pt_regs, ar_fpsr)); DEFINE(VMM_PT_REGS_R15_OFFSET, offsetof(struct kvm_pt_regs, r15)); DEFINE(VMM_PT_REGS_R14_OFFSET, offsetof(struct kvm_pt_regs, r14)); DEFINE(VMM_PT_REGS_R2_OFFSET, offsetof(struct kvm_pt_regs, r2)); DEFINE(VMM_PT_REGS_R3_OFFSET, offsetof(struct kvm_pt_regs, r3)); DEFINE(VMM_PT_REGS_R16_OFFSET, offsetof(struct kvm_pt_regs, r16)); DEFINE(VMM_PT_REGS_R17_OFFSET, offsetof(struct kvm_pt_regs, r17)); DEFINE(VMM_PT_REGS_R18_OFFSET, offsetof(struct kvm_pt_regs, r18)); DEFINE(VMM_PT_REGS_R19_OFFSET, offsetof(struct kvm_pt_regs, r19)); DEFINE(VMM_PT_REGS_R20_OFFSET, offsetof(struct kvm_pt_regs, r20)); DEFINE(VMM_PT_REGS_R21_OFFSET, offsetof(struct kvm_pt_regs, r21)); DEFINE(VMM_PT_REGS_R22_OFFSET, offsetof(struct kvm_pt_regs, r22)); DEFINE(VMM_PT_REGS_R23_OFFSET, offsetof(struct kvm_pt_regs, r23)); DEFINE(VMM_PT_REGS_R24_OFFSET, offsetof(struct kvm_pt_regs, r24)); DEFINE(VMM_PT_REGS_R25_OFFSET, offsetof(struct kvm_pt_regs, r25)); DEFINE(VMM_PT_REGS_R26_OFFSET, offsetof(struct kvm_pt_regs, r26)); DEFINE(VMM_PT_REGS_R27_OFFSET, offsetof(struct kvm_pt_regs, r27)); DEFINE(VMM_PT_REGS_R28_OFFSET, offsetof(struct kvm_pt_regs, r28)); DEFINE(VMM_PT_REGS_R29_OFFSET, offsetof(struct kvm_pt_regs, r29)); DEFINE(VMM_PT_REGS_R30_OFFSET, offsetof(struct kvm_pt_regs, r30)); DEFINE(VMM_PT_REGS_R31_OFFSET, offsetof(struct kvm_pt_regs, r31)); DEFINE(VMM_PT_REGS_AR_CCV_OFFSET, offsetof(struct kvm_pt_regs, ar_ccv)); DEFINE(VMM_PT_REGS_F6_OFFSET, offsetof(struct kvm_pt_regs, f6)); DEFINE(VMM_PT_REGS_F7_OFFSET, offsetof(struct kvm_pt_regs, f7)); DEFINE(VMM_PT_REGS_F8_OFFSET, offsetof(struct kvm_pt_regs, f8)); DEFINE(VMM_PT_REGS_F9_OFFSET, offsetof(struct kvm_pt_regs, f9)); DEFINE(VMM_PT_REGS_F10_OFFSET, offsetof(struct kvm_pt_regs, f10)); DEFINE(VMM_PT_REGS_F11_OFFSET, offsetof(struct kvm_pt_regs, f11)); DEFINE(VMM_PT_REGS_R4_OFFSET, offsetof(struct kvm_pt_regs, r4)); DEFINE(VMM_PT_REGS_R5_OFFSET, offsetof(struct kvm_pt_regs, r5)); DEFINE(VMM_PT_REGS_R6_OFFSET, offsetof(struct kvm_pt_regs, r6)); DEFINE(VMM_PT_REGS_R7_OFFSET, offsetof(struct kvm_pt_regs, r7)); DEFINE(VMM_PT_REGS_EML_UNAT_OFFSET, offsetof(struct kvm_pt_regs, eml_unat)); DEFINE(VMM_VCPU_IIPA_OFFSET, offsetof(struct kvm_vcpu, arch.cr_iipa)); DEFINE(VMM_VCPU_OPCODE_OFFSET, offsetof(struct kvm_vcpu, arch.opcode)); DEFINE(VMM_VCPU_CAUSE_OFFSET, offsetof(struct kvm_vcpu, arch.cause)); DEFINE(VMM_VCPU_ISR_OFFSET, offsetof(struct kvm_vcpu, arch.cr_isr)); DEFINE(VMM_PT_REGS_R16_SLOT, (((offsetof(struct kvm_pt_regs, r16) - sizeof(struct kvm_pt_regs)) >> 3) & 0x3f)); DEFINE(VMM_VCPU_MODE_FLAGS_OFFSET, offsetof(struct kvm_vcpu, arch.mode_flags)); DEFINE(VMM_VCPU_GP_OFFSET, offsetof(struct kvm_vcpu, arch.__gp)); BLANK(); DEFINE(VMM_VPD_BASE_OFFSET, offsetof(struct kvm_vcpu, arch.vpd)); DEFINE(VMM_VPD_VIFS_OFFSET, offsetof(struct vpd, ifs)); DEFINE(VMM_VLSAPIC_INSVC_BASE_OFFSET, offsetof(struct kvm_vcpu, arch.insvc[0])); DEFINE(VMM_VPD_VPTA_OFFSET, offsetof(struct vpd, pta)); DEFINE(VMM_VPD_VPSR_OFFSET, offsetof(struct vpd, vpsr)); DEFINE(VMM_CTX_R4_OFFSET, offsetof(union context, gr[4])); DEFINE(VMM_CTX_R5_OFFSET, offsetof(union context, gr[5])); DEFINE(VMM_CTX_R12_OFFSET, offsetof(union context, gr[12])); DEFINE(VMM_CTX_R13_OFFSET, offsetof(union context, gr[13])); DEFINE(VMM_CTX_KR0_OFFSET, offsetof(union context, ar[0])); DEFINE(VMM_CTX_KR1_OFFSET, offsetof(union context, ar[1])); DEFINE(VMM_CTX_B0_OFFSET, offsetof(union context, br[0])); DEFINE(VMM_CTX_B1_OFFSET, offsetof(union context, br[1])); DEFINE(VMM_CTX_B2_OFFSET, offsetof(union context, br[2])); DEFINE(VMM_CTX_RR0_OFFSET, offsetof(union context, rr[0])); DEFINE(VMM_CTX_RSC_OFFSET, offsetof(union context, ar[16])); DEFINE(VMM_CTX_BSPSTORE_OFFSET, offsetof(union context, ar[18])); DEFINE(VMM_CTX_RNAT_OFFSET, offsetof(union context, ar[19])); DEFINE(VMM_CTX_FCR_OFFSET, offsetof(union context, ar[21])); DEFINE(VMM_CTX_EFLAG_OFFSET, offsetof(union context, ar[24])); DEFINE(VMM_CTX_CFLG_OFFSET, offsetof(union context, ar[27])); DEFINE(VMM_CTX_FSR_OFFSET, offsetof(union context, ar[28])); DEFINE(VMM_CTX_FIR_OFFSET, offsetof(union context, ar[29])); DEFINE(VMM_CTX_FDR_OFFSET, offsetof(union context, ar[30])); DEFINE(VMM_CTX_UNAT_OFFSET, offsetof(union context, ar[36])); DEFINE(VMM_CTX_FPSR_OFFSET, offsetof(union context, ar[40])); DEFINE(VMM_CTX_PFS_OFFSET, offsetof(union context, ar[64])); DEFINE(VMM_CTX_LC_OFFSET, offsetof(union context, ar[65])); DEFINE(VMM_CTX_DCR_OFFSET, offsetof(union context, cr[0])); DEFINE(VMM_CTX_IVA_OFFSET, offsetof(union context, cr[2])); DEFINE(VMM_CTX_PTA_OFFSET, offsetof(union context, cr[8])); DEFINE(VMM_CTX_IBR0_OFFSET, offsetof(union context, ibr[0])); DEFINE(VMM_CTX_DBR0_OFFSET, offsetof(union context, dbr[0])); DEFINE(VMM_CTX_F2_OFFSET, offsetof(union context, fr[2])); DEFINE(VMM_CTX_F3_OFFSET, offsetof(union context, fr[3])); DEFINE(VMM_CTX_F32_OFFSET, offsetof(union context, fr[32])); DEFINE(VMM_CTX_F33_OFFSET, offsetof(union context, fr[33])); DEFINE(VMM_CTX_PKR0_OFFSET, offsetof(union context, pkr[0])); DEFINE(VMM_CTX_PSR_OFFSET, offsetof(union context, psr)); BLANK(); }
gpl-2.0
OnePlusOSS/android_kernel_oneplus_msm8994
fs/nls/nls_iso8859-9.c
12567
11053
/* * linux/fs/nls/nls_iso8859-9.c * * Charset iso8859-9 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, /* 0x90*/ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, /* 0xa0*/ 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, /* 0xb0*/ 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, /* 0xc0*/ 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, /* 0xd0*/ 0x011e, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x0130, 0x015e, 0x00df, /* 0xe0*/ 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, /* 0xf0*/ 0x011f, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x0131, 0x015f, 0x00ff, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0x00, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0x00, 0x00, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0x00, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0x00, 0x00, 0xff, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xf0, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0xdd, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xde, 0xfe, /* 0x58-0x5f */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, NULL, NULL, NULL, NULL, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xc0-0xc7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xc8-0xcf */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xd7, /* 0xd0-0xd7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0x69, 0xfe, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0x00, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xe0-0xe7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xe8-0xef */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xf7, /* 0xf0-0xf7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0x49, 0xde, 0x00, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "iso8859-9", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, .owner = THIS_MODULE, }; static int __init init_nls_iso8859_9(void) { return register_nls(&table); } static void __exit exit_nls_iso8859_9(void) { unregister_nls(&table); } module_init(init_nls_iso8859_9) module_exit(exit_nls_iso8859_9) MODULE_LICENSE("Dual BSD/GPL");
gpl-2.0
Compunctus/android_kernel_lge_g3
drivers/media/platform/msm/camera_v2/msm_buf_mgr/msm_generic_buf_mgr.c
24
7766
/* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include "msm_generic_buf_mgr.h" static struct msm_buf_mngr_device *msm_buf_mngr_dev; struct v4l2_subdev *msm_buf_mngr_get_subdev(void) { return &msm_buf_mngr_dev->subdev.sd; } static int msm_buf_mngr_get_buf(struct msm_buf_mngr_device *buf_mngr_dev, void __user *argp) { unsigned long flags; struct msm_buf_mngr_info *buf_info = (struct msm_buf_mngr_info *)argp; struct msm_get_bufs *new_entry = kzalloc(sizeof(struct msm_get_bufs), GFP_KERNEL); if (!new_entry) { pr_err("%s:No mem\n", __func__); return -ENOMEM; } INIT_LIST_HEAD(&new_entry->entry); new_entry->vb2_buf = buf_mngr_dev->vb2_ops.get_buf(buf_info->session_id, buf_info->stream_id); if (!new_entry->vb2_buf) { pr_debug("%s:Get buf is null\n", __func__); kfree(new_entry); return -EINVAL; } new_entry->session_id = buf_info->session_id; new_entry->stream_id = buf_info->stream_id; spin_lock_irqsave(&buf_mngr_dev->buf_q_spinlock, flags); list_add_tail(&new_entry->entry, &buf_mngr_dev->buf_qhead); spin_unlock_irqrestore(&buf_mngr_dev->buf_q_spinlock, flags); buf_info->index = new_entry->vb2_buf->v4l2_buf.index; return 0; } static int msm_buf_mngr_buf_done(struct msm_buf_mngr_device *buf_mngr_dev, struct msm_buf_mngr_info *buf_info) { unsigned long flags; struct msm_get_bufs *bufs, *save; int ret = -EINVAL; spin_lock_irqsave(&buf_mngr_dev->buf_q_spinlock, flags); list_for_each_entry_safe(bufs, save, &buf_mngr_dev->buf_qhead, entry) { if ((bufs->session_id == buf_info->session_id) && (bufs->stream_id == buf_info->stream_id) && (bufs->vb2_buf->v4l2_buf.index == buf_info->index)) { #ifndef CONFIG_MACH_LGE bufs->vb2_buf->v4l2_buf.sequence = buf_info->frame_id; bufs->vb2_buf->v4l2_buf.timestamp = buf_info->timestamp; bufs->vb2_buf->v4l2_buf.reserved = 0; #endif ret = buf_mngr_dev->vb2_ops.buf_done (bufs->vb2_buf, buf_info->session_id, buf_info->stream_id); #ifdef CONFIG_MACH_LGE if (!ret) { bufs->vb2_buf->v4l2_buf.sequence = buf_info->frame_id; bufs->vb2_buf->v4l2_buf.timestamp = buf_info->timestamp; bufs->vb2_buf->v4l2_buf.reserved = 0; } else { pr_err("%s:vb2_ops failed %d type= %d\n", __func__, ret,bufs->vb2_buf->v4l2_buf.type); } #endif list_del_init(&bufs->entry); kfree(bufs); break; } } spin_unlock_irqrestore(&buf_mngr_dev->buf_q_spinlock, flags); return ret; } static int msm_buf_mngr_put_buf(struct msm_buf_mngr_device *buf_mngr_dev, struct msm_buf_mngr_info *buf_info) { unsigned long flags; struct msm_get_bufs *bufs, *save; int ret = -EINVAL; spin_lock_irqsave(&buf_mngr_dev->buf_q_spinlock, flags); list_for_each_entry_safe(bufs, save, &buf_mngr_dev->buf_qhead, entry) { if ((bufs->session_id == buf_info->session_id) && (bufs->stream_id == buf_info->stream_id) && (bufs->vb2_buf->v4l2_buf.index == buf_info->index)) { ret = buf_mngr_dev->vb2_ops.put_buf(bufs->vb2_buf, buf_info->session_id, buf_info->stream_id); list_del_init(&bufs->entry); kfree(bufs); break; } } spin_unlock_irqrestore(&buf_mngr_dev->buf_q_spinlock, flags); return ret; } static void msm_buf_mngr_sd_shutdown(struct msm_buf_mngr_device *buf_mngr_dev) { unsigned long flags; struct msm_get_bufs *bufs, *save; spin_lock_irqsave(&buf_mngr_dev->buf_q_spinlock, flags); if (!list_empty(&buf_mngr_dev->buf_qhead)) { list_for_each_entry_safe(bufs, save, &buf_mngr_dev->buf_qhead, entry) { pr_err("%s: Error delete invalid bufs =%x, ses_id=%d, str_id=%d, idx=%d\n", __func__, (unsigned int)bufs, bufs->session_id, bufs->stream_id, bufs->vb2_buf->v4l2_buf.index); list_del_init(&bufs->entry); kfree(bufs); } } spin_unlock_irqrestore(&buf_mngr_dev->buf_q_spinlock, flags); } static int msm_generic_buf_mngr_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { int rc = 0; struct msm_buf_mngr_device *buf_mngr_dev = v4l2_get_subdevdata(sd); if (!buf_mngr_dev) { pr_err("%s buf manager device NULL\n", __func__); rc = -ENODEV; return rc; } return rc; } static int msm_generic_buf_mngr_close(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { int rc = 0; struct msm_buf_mngr_device *buf_mngr_dev = v4l2_get_subdevdata(sd); if (!buf_mngr_dev) { pr_err("%s buf manager device NULL\n", __func__); rc = -ENODEV; return rc; } return rc; } static long msm_buf_mngr_subdev_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg) { int rc = 0; struct msm_buf_mngr_device *buf_mngr_dev = v4l2_get_subdevdata(sd); void __user *argp = (void __user *)arg; if (!buf_mngr_dev) { pr_err("%s buf manager device NULL\n", __func__); rc = -ENOMEM; return rc; } switch (cmd) { case VIDIOC_MSM_BUF_MNGR_GET_BUF: rc = msm_buf_mngr_get_buf(buf_mngr_dev, argp); break; case VIDIOC_MSM_BUF_MNGR_BUF_DONE: rc = msm_buf_mngr_buf_done(buf_mngr_dev, argp); break; case VIDIOC_MSM_BUF_MNGR_PUT_BUF: rc = msm_buf_mngr_put_buf(buf_mngr_dev, argp); break; case VIDIOC_MSM_BUF_MNGR_INIT: rc = msm_generic_buf_mngr_open(sd, NULL); break; case VIDIOC_MSM_BUF_MNGR_DEINIT: rc = msm_generic_buf_mngr_close(sd, NULL); break; case MSM_SD_SHUTDOWN: msm_buf_mngr_sd_shutdown(buf_mngr_dev); break; default: return -ENOIOCTLCMD; } return rc; } static struct v4l2_subdev_core_ops msm_buf_mngr_subdev_core_ops = { .ioctl = msm_buf_mngr_subdev_ioctl, }; static const struct v4l2_subdev_internal_ops msm_generic_buf_mngr_subdev_internal_ops = { .open = msm_generic_buf_mngr_open, .close = msm_generic_buf_mngr_close, }; static const struct v4l2_subdev_ops msm_buf_mngr_subdev_ops = { .core = &msm_buf_mngr_subdev_core_ops, }; static const struct of_device_id msm_buf_mngr_dt_match[] = { {.compatible = "qcom,msm_buf_mngr"}, {} }; static int __init msm_buf_mngr_init(void) { int rc = 0; msm_buf_mngr_dev = kzalloc(sizeof(*msm_buf_mngr_dev), GFP_KERNEL); if (WARN_ON(!msm_buf_mngr_dev)) { pr_err("%s: not enough memory", __func__); return -ENOMEM; } /* Sub-dev */ v4l2_subdev_init(&msm_buf_mngr_dev->subdev.sd, &msm_buf_mngr_subdev_ops); snprintf(msm_buf_mngr_dev->subdev.sd.name, ARRAY_SIZE(msm_buf_mngr_dev->subdev.sd.name), "msm_buf_mngr"); msm_buf_mngr_dev->subdev.sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; v4l2_set_subdevdata(&msm_buf_mngr_dev->subdev.sd, msm_buf_mngr_dev); media_entity_init(&msm_buf_mngr_dev->subdev.sd.entity, 0, NULL, 0); msm_buf_mngr_dev->subdev.sd.entity.type = MEDIA_ENT_T_V4L2_SUBDEV; msm_buf_mngr_dev->subdev.sd.entity.group_id = MSM_CAMERA_SUBDEV_BUF_MNGR; msm_buf_mngr_dev->subdev.sd.internal_ops = &msm_generic_buf_mngr_subdev_internal_ops; msm_buf_mngr_dev->subdev.close_seq = MSM_SD_CLOSE_4TH_CATEGORY; rc = msm_sd_register(&msm_buf_mngr_dev->subdev); if (rc != 0) { pr_err("%s: msm_sd_register error = %d\n", __func__, rc); goto end; } v4l2_subdev_notify(&msm_buf_mngr_dev->subdev.sd, MSM_SD_NOTIFY_REQ_CB, &msm_buf_mngr_dev->vb2_ops); INIT_LIST_HEAD(&msm_buf_mngr_dev->buf_qhead); spin_lock_init(&msm_buf_mngr_dev->buf_q_spinlock); end: return rc; } static void __exit msm_buf_mngr_exit(void) { kfree(msm_buf_mngr_dev); } module_init(msm_buf_mngr_init); module_exit(msm_buf_mngr_exit); MODULE_DESCRIPTION("MSM Buffer Manager"); MODULE_LICENSE("GPL v2");
gpl-2.0
xsacha/SymbianGCC
gcc/testsuite/gcc.target/sh/pr54089-8.c
24
3185
/* Check that the rotcl instruction is generated. */ /* { dg-do compile { target "sh*-*-*" } } */ /* { dg-options "-O1" } */ /* { dg-skip-if "" { "sh*-*-*" } { "-m5*"} { "" } } */ /* { dg-final { scan-assembler-times "rotcl" 28 } } */ typedef char bool; long long test_00 (long long a) { return a << 1; } unsigned int test_01 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 1) | r); } unsigned int test_02 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 2) | r); } unsigned int test_03 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 3) | r); } unsigned int test_04 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 4) | r); } unsigned int test_05 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 5) | r); } unsigned int test_06 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 6) | r); } unsigned int test_07 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 7) | r); } unsigned int test_08 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 8) | r); } unsigned int test_09 (unsigned int a, int b, int c) { bool r = b == c; return ((a << 31) | r); } unsigned int test_10 (unsigned int a, int b) { /* 1x shlr, 1x rotcl */ return (a << 1) | (b & 1); } unsigned int test_11 (unsigned int a, int b) { /* 1x shlr, 1x rotcl (+1x add as shll) */ return (a << 2) | (b & 1); } unsigned int test_12 (unsigned int a, int b) { /* 1x shlr, 1x shll2, 1x rotcl */ return (a << 3) | (b & 1); } unsigned int test_13 (unsigned int a, int b) { /* 1x shll, 1x rotcl */ bool r = b < 0; return (a << 1) | r; } unsigned int test_14 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 1) | r); } unsigned int test_15 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 11) | r); } unsigned int test_16 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 3) | r); } unsigned int test_17 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 4) | r); } unsigned int test_18 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 5) | r); } unsigned int test_19 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 6) | r); } unsigned int test_20 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 7) | r); } unsigned int test_21 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 8) | r); } unsigned int test_22 (unsigned int a, int b, int c) { bool r = b != c; return ((a << 31) | r); } unsigned int test_23 (unsigned int a, int b, int c) { /* 1x shll, 1x rotcl */ return (a >> 31) | (b << 13); } unsigned int test_24 (unsigned int a, unsigned int b) { /* 1x shll, 1x rotcl */ return (a >> 31) | (b << 1); } unsigned int test_25 (unsigned int a, unsigned int b) { /* 1x shll, 1x rotcl */ return (a >> 31) | (b << 3); } unsigned int test_26 (unsigned int a, unsigned int b) { /* 1x shll, 1x rotcl */ return (b << 3) | (a >> 31); } unsigned int test_27 (unsigned int a, unsigned int b) { /* 1x shlr, 1x rotcl */ return (a << 1) | ((b >> 4) & 1); }
gpl-2.0
llubu/Glibc_Linker
nptl/pthread_atfork.c
24
2671
/* Copyright (C) 2002, 2006 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. In addition to the permissions in the GNU Lesser General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file with other programs, and to distribute those programs without any restriction coming from the use of this file. (The GNU Lesser General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into another program.) Note that people who make modified versions of this file are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include "pthreadP.h" #include <fork.h> /* This is defined by newer gcc version unique for each module. */ extern void *__dso_handle __attribute__ ((__weak__, __visibility__ ("hidden"))); /* Hide the symbol so that no definition but the one locally in the executable or DSO is used. */ int #ifndef __pthread_atfork /* Don't mark the compatibility function as hidden. */ attribute_hidden #endif __pthread_atfork (prepare, parent, child) void (*prepare) (void); void (*parent) (void); void (*child) (void); { return __register_atfork (prepare, parent, child, &__dso_handle == NULL ? NULL : __dso_handle); } #ifndef __pthread_atfork extern int pthread_atfork (void (*prepare) (void), void (*parent) (void), void (*child) (void)) attribute_hidden; strong_alias (__pthread_atfork, pthread_atfork) #endif
gpl-2.0
rduivenvoorde/QGIS
src/server/qgsservercachemanager.cpp
24
7017
/*************************************************************************** qgsservercachemanager.cpp ------------------------- begin : 2018-07-05 copyright : (C) 2018 by René-Luc D'Hont email : rldhont at 3liz dot 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 "qgsservercachemanager.h" #include "qgsserverprojectutils.h" #include "qgsmessagelog.h" #include "qgis.h" QgsServerCacheManager::QgsServerCacheManager( const QgsServerSettings &settings ): mSettings( settings ) { mPluginsServerCaches.reset( new QgsServerCacheFilterMap() ); } QgsServerCacheManager::QgsServerCacheManager( const QgsServerCacheManager &copy ): mSettings( copy.mSettings ) { if ( copy.mPluginsServerCaches ) { mPluginsServerCaches.reset( new QgsServerCacheFilterMap( *copy.mPluginsServerCaches ) ); } else { mPluginsServerCaches.reset( nullptr ); } } QgsServerCacheManager &QgsServerCacheManager::operator=( const QgsServerCacheManager &copy ) { if ( copy.mPluginsServerCaches ) { mPluginsServerCaches.reset( new QgsServerCacheFilterMap( *copy.mPluginsServerCaches ) ); } else { mPluginsServerCaches.reset( nullptr ); } return *this; } QgsServerCacheManager::~QgsServerCacheManager() { mPluginsServerCaches.reset(); } bool QgsServerCacheManager::getCachedDocument( QDomDocument *doc, const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl ) const { bool cache = true; const QString key = getCacheKey( cache, accessControl, request ); if ( !cache ) { return false; } QByteArray content; QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { content = scIterator.value()->getCachedDocument( project, request, key ); if ( !content.isEmpty() ) { break; } } if ( content.isEmpty() ) { return false; } if ( !doc->setContent( content ) ) { return false; } return true; } bool QgsServerCacheManager::setCachedDocument( const QDomDocument *doc, const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl ) const { bool cache = true; const QString key = getCacheKey( cache, accessControl, request ); if ( !cache ) { return false; } QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { if ( scIterator.value()->setCachedDocument( doc, project, request, key ) ) { return true; } } return false; } bool QgsServerCacheManager::deleteCachedDocument( const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl ) const { bool cache = true; const QString key = getCacheKey( cache, accessControl, request ); QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { if ( scIterator.value()->deleteCachedDocument( project, request, key ) ) { return true; } } return false; } bool QgsServerCacheManager::deleteCachedDocuments( const QgsProject *project ) const { QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { if ( scIterator.value()->deleteCachedDocuments( project ) ) { return true; } } return false; } QByteArray QgsServerCacheManager::getCachedImage( const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl ) const { bool cache = true; const QString key = getCacheKey( cache, accessControl, request ); QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { QByteArray content = scIterator.value()->getCachedImage( project, request, key ); if ( !content.isEmpty() ) { return content; } } return QByteArray(); } bool QgsServerCacheManager::setCachedImage( const QByteArray *img, const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl ) const { bool cache = true; const QString key = getCacheKey( cache, accessControl, request ); QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { if ( scIterator.value()->setCachedImage( img, project, request, key ) ) { return true; } } return false; } bool QgsServerCacheManager::deleteCachedImage( const QgsProject *project, const QgsServerRequest &request, QgsAccessControl *accessControl ) const { bool cache = true; const QString key = getCacheKey( cache, accessControl, request ); QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { if ( scIterator.value()->deleteCachedImage( project, request, key ) ) { return true; } } return false; } bool QgsServerCacheManager::deleteCachedImages( const QgsProject *project ) const { QgsServerCacheFilterMap::const_iterator scIterator; for ( scIterator = mPluginsServerCaches->constBegin(); scIterator != mPluginsServerCaches->constEnd(); ++scIterator ) { if ( scIterator.value()->deleteCachedImages( project ) ) { return true; } } return false; } void QgsServerCacheManager::registerServerCache( QgsServerCacheFilter *serverCache, int priority ) { mPluginsServerCaches->insert( priority, serverCache ); } QString QgsServerCacheManager::getCacheKey( bool &cache, QgsAccessControl *accessControl, const QgsServerRequest &request ) const { QStringList cacheKeyList; cacheKeyList << QgsServerProjectUtils::serviceUrl( request.serverParameters().service(), request, mSettings ); if ( accessControl ) { cache = accessControl->fillCacheKey( cacheKeyList ); } else { cache = true; } return cacheKeyList.join( '-' ); }
gpl-2.0
rho-devel/rho
src/nmath/gamma.c
24
6376
/* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000-2013 The R Core Team * Copyright (C) 2002-2004 The R Foundation * * 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, a copy is available at * https://www.R-project.org/Licenses/ * * SYNOPSIS * * #include <Rmath.h> * double gammafn(double x); * * DESCRIPTION * * This function computes the value of the gamma function. * * NOTES * * This function is a translation into C of a Fortran subroutine * by W. Fullerton of Los Alamos Scientific Laboratory. * (e.g. http://www.netlib.org/slatec/fnlib/gamma.f) * * The accuracy of this routine compares (very) favourably * with those of the Sun Microsystems portable mathematical * library. * * MM specialized the case of n! for n < 50 - for even better precision */ #include "nmath.h" double gammafn(double x) { const static double gamcs[42] = { +.8571195590989331421920062399942e-2, +.4415381324841006757191315771652e-2, +.5685043681599363378632664588789e-1, -.4219835396418560501012500186624e-2, +.1326808181212460220584006796352e-2, -.1893024529798880432523947023886e-3, +.3606925327441245256578082217225e-4, -.6056761904460864218485548290365e-5, +.1055829546302283344731823509093e-5, -.1811967365542384048291855891166e-6, +.3117724964715322277790254593169e-7, -.5354219639019687140874081024347e-8, +.9193275519859588946887786825940e-9, -.1577941280288339761767423273953e-9, +.2707980622934954543266540433089e-10, -.4646818653825730144081661058933e-11, +.7973350192007419656460767175359e-12, -.1368078209830916025799499172309e-12, +.2347319486563800657233471771688e-13, -.4027432614949066932766570534699e-14, +.6910051747372100912138336975257e-15, -.1185584500221992907052387126192e-15, +.2034148542496373955201026051932e-16, -.3490054341717405849274012949108e-17, +.5987993856485305567135051066026e-18, -.1027378057872228074490069778431e-18, +.1762702816060529824942759660748e-19, -.3024320653735306260958772112042e-20, +.5188914660218397839717833550506e-21, -.8902770842456576692449251601066e-22, +.1527474068493342602274596891306e-22, -.2620731256187362900257328332799e-23, +.4496464047830538670331046570666e-24, -.7714712731336877911703901525333e-25, +.1323635453126044036486572714666e-25, -.2270999412942928816702313813333e-26, +.3896418998003991449320816639999e-27, -.6685198115125953327792127999999e-28, +.1146998663140024384347613866666e-28, -.1967938586345134677295103999999e-29, +.3376448816585338090334890666666e-30, -.5793070335782135784625493333333e-31 }; int i, n; double y; double sinpiy, value; #ifdef NOMORE_FOR_THREADS static int ngam = 0; static double xmin = 0, xmax = 0., xsml = 0., dxrel = 0.; /* Initialize machine dependent constants, the first time gamma() is called. FIXME for threads ! */ if (ngam == 0) { ngam = chebyshev_init(gamcs, 42, DBL_EPSILON/20);/*was .1*d1mach(3)*/ gammalims(&xmin, &xmax);/*-> ./gammalims.c */ xsml = exp(fmax2(log(DBL_MIN), -log(DBL_MAX)) + 0.01); /* = exp(.01)*DBL_MIN = 2.247e-308 for IEEE */ dxrel = sqrt(DBL_EPSILON);/*was sqrt(d1mach(4)) */ } #else /* For IEEE double precision DBL_EPSILON = 2^-52 = 2.220446049250313e-16 : * (xmin, xmax) are non-trivial, see ./gammalims.c * xsml = exp(.01)*DBL_MIN * dxrel = sqrt(DBL_EPSILON) = 2 ^ -26 */ # define ngam 22 # define xmin -170.5674972726612 # define xmax 171.61447887182298 # define xsml 2.2474362225598545e-308 # define dxrel 1.490116119384765696e-8 #endif if(ISNAN(x)) return x; /* If the argument is exactly zero or a negative integer * then return NaN. */ if (x == 0 || (x < 0 && x == round(x))) { ML_ERROR(ME_DOMAIN, "gammafn"); return ML_NAN; } y = fabs(x); if (y <= 10) { /* Compute gamma(x) for -10 <= x <= 10 * Reduce the interval and find gamma(1 + y) for 0 <= y < 1 * first of all. */ n = (int) x; if(x < 0) --n; y = x - n;/* n = floor(x) ==> y in [ 0, 1 ) */ --n; value = chebyshev_eval(y * 2 - 1, gamcs, ngam) + .9375; if (n == 0) return value;/* x = 1.dddd = 1+y */ if (n < 0) { /* compute gamma(x) for -10 <= x < 1 */ /* exact 0 or "-n" checked already above */ /* The answer is less than half precision */ /* because x too near a negative integer. */ if (x < -0.5 && fabs(x - (int)(x - 0.5) / x) < dxrel) { ML_ERROR(ME_PRECISION, "gammafn"); } /* The argument is so close to 0 that the result would overflow. */ if (y < xsml) { ML_ERROR(ME_RANGE, "gammafn"); if(x > 0) return ML_POSINF; else return ML_NEGINF; } n = -n; for (i = 0; i < n; i++) { value /= (x + i); } return value; } else { /* gamma(x) for 2 <= x <= 10 */ for (i = 1; i <= n; i++) { value *= (y + i); } return value; } } else { /* gamma(x) for y = |x| > 10. */ if (x > xmax) { /* Overflow */ ML_ERROR(ME_RANGE, "gammafn"); return ML_POSINF; } if (x < xmin) { /* Underflow */ ML_ERROR(ME_UNDERFLOW, "gammafn"); return 0.; } if(y <= 50 && y == (int)y) { /* compute (n - 1)! */ value = 1.; for (i = 2; i < y; i++) value *= i; } else { /* normal case */ value = exp((y - 0.5) * log(y) - y + M_LN_SQRT_2PI + ((2*y == (int)2*y)? stirlerr(y) : lgammacor(y))); } if (x > 0) return value; if (fabs((x - (int)(x - 0.5))/x) < dxrel){ /* The answer is less than half precision because */ /* the argument is too near a negative integer. */ ML_ERROR(ME_PRECISION, "gammafn"); } sinpiy = sinpi(y); if (sinpiy == 0) { /* Negative integer arg - overflow */ ML_ERROR(ME_RANGE, "gammafn"); return ML_POSINF; } return -M_PI / (y * sinpiy * value); } }
gpl-2.0
hugh712/my_driver_study
Jollen/jk2410/kernel-jk2410/drivers/sound/emu10k1/midi.c
24
14076
/* ********************************************************************** * midi.c - /dev/midi interface for emu10k1 driver * Copyright 1999, 2000 Creative Labs, Inc. * ********************************************************************** * * Date Author Summary of changes * ---- ------ ------------------ * October 20, 1999 Bertrand Lee base code release * ********************************************************************** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, * USA. * ********************************************************************** */ #define __NO_VERSION__ #include <linux/module.h> #include <linux/poll.h> #include <linux/slab.h> #include <linux/version.h> #include <linux/sched.h> #include <linux/smp_lock.h> #include <asm/uaccess.h> #include "hwaccess.h" #include "cardmo.h" #include "cardmi.h" #include "midi.h" #ifdef EMU10K1_SEQUENCER #include "../sound_config.h" #endif static spinlock_t midi_spinlock __attribute((unused)) = SPIN_LOCK_UNLOCKED; static void init_midi_hdr(struct midi_hdr *midihdr) { midihdr->bufferlength = MIDIIN_BUFLEN; midihdr->bytesrecorded = 0; midihdr->flags = 0; } static int midiin_add_buffer(struct emu10k1_mididevice *midi_dev, struct midi_hdr **midihdrptr) { struct midi_hdr *midihdr; if ((midihdr = (struct midi_hdr *) kmalloc(sizeof(struct midi_hdr), GFP_KERNEL)) == NULL) { ERROR(); return -EINVAL; } init_midi_hdr(midihdr); if ((midihdr->data = (u8 *) kmalloc(MIDIIN_BUFLEN, GFP_KERNEL)) == NULL) { ERROR(); kfree(midihdr); return -1; } if (emu10k1_mpuin_add_buffer(midi_dev->card->mpuin, midihdr) < 0) { ERROR(); kfree(midihdr->data); kfree(midihdr); return -1; } *midihdrptr = midihdr; list_add_tail(&midihdr->list, &midi_dev->mid_hdrs); return 0; } static int emu10k1_midi_open(struct inode *inode, struct file *file) { int minor = MINOR(inode->i_rdev); struct emu10k1_card *card = NULL; struct emu10k1_mididevice *midi_dev; struct list_head *entry; DPF(2, "emu10k1_midi_open()\n"); /* Check for correct device to open */ list_for_each(entry, &emu10k1_devs) { card = list_entry(entry, struct emu10k1_card, list); if (card->midi_dev == minor) goto match; } return -ENODEV; match: #ifdef EMU10K1_SEQUENCER if (card->seq_mididev) /* card is opened by sequencer */ return -EBUSY; #endif /* Wait for device to become free */ down(&card->open_sem); while (card->open_mode & (file->f_mode << FMODE_MIDI_SHIFT)) { if (file->f_flags & O_NONBLOCK) { up(&card->open_sem); return -EBUSY; } up(&card->open_sem); interruptible_sleep_on(&card->open_wait); if (signal_pending(current)) { return -ERESTARTSYS; } down(&card->open_sem); } if ((midi_dev = (struct emu10k1_mididevice *) kmalloc(sizeof(*midi_dev), GFP_KERNEL)) == NULL) return -EINVAL; midi_dev->card = card; midi_dev->mistate = MIDIIN_STATE_STOPPED; init_waitqueue_head(&midi_dev->oWait); init_waitqueue_head(&midi_dev->iWait); midi_dev->ird = 0; midi_dev->iwr = 0; midi_dev->icnt = 0; INIT_LIST_HEAD(&midi_dev->mid_hdrs); if (file->f_mode & FMODE_READ) { struct midi_openinfo dsCardMidiOpenInfo; struct midi_hdr *midihdr1; struct midi_hdr *midihdr2; dsCardMidiOpenInfo.refdata = (unsigned long) midi_dev; if (emu10k1_mpuin_open(card, &dsCardMidiOpenInfo) < 0) { ERROR(); kfree(midi_dev); return -ENODEV; } /* Add two buffers to receive sysex buffer */ if (midiin_add_buffer(midi_dev, &midihdr1) < 0) { kfree(midi_dev); return -ENODEV; } if (midiin_add_buffer(midi_dev, &midihdr2) < 0) { list_del(&midihdr1->list); kfree(midihdr1->data); kfree(midihdr1); kfree(midi_dev); return -ENODEV; } } if (file->f_mode & FMODE_WRITE) { struct midi_openinfo dsCardMidiOpenInfo; dsCardMidiOpenInfo.refdata = (unsigned long) midi_dev; if (emu10k1_mpuout_open(card, &dsCardMidiOpenInfo) < 0) { ERROR(); kfree(midi_dev); return -ENODEV; } } file->private_data = (void *) midi_dev; card->open_mode |= (file->f_mode << FMODE_MIDI_SHIFT) & (FMODE_MIDI_READ | FMODE_MIDI_WRITE); up(&card->open_sem); return 0; } static int emu10k1_midi_release(struct inode *inode, struct file *file) { struct emu10k1_mididevice *midi_dev = (struct emu10k1_mididevice *) file->private_data; struct emu10k1_card *card; lock_kernel(); card = midi_dev->card; DPF(2, "emu10k1_midi_release()\n"); if (file->f_mode & FMODE_WRITE) { if (!(file->f_flags & O_NONBLOCK)) { while (!signal_pending(current) && (card->mpuout->firstmidiq != NULL)) { DPF(4, "Cannot close - buffers not empty\n"); interruptible_sleep_on(&midi_dev->oWait); } } emu10k1_mpuout_close(card); } if (file->f_mode & FMODE_READ) { struct midi_hdr *midihdr; if (midi_dev->mistate == MIDIIN_STATE_STARTED) { emu10k1_mpuin_stop(card); midi_dev->mistate = MIDIIN_STATE_STOPPED; } emu10k1_mpuin_reset(card); emu10k1_mpuin_close(card); while (!list_empty(&midi_dev->mid_hdrs)) { midihdr = list_entry(midi_dev->mid_hdrs.next, struct midi_hdr, list); list_del(midi_dev->mid_hdrs.next); kfree(midihdr->data); kfree(midihdr); } } kfree(midi_dev); down(&card->open_sem); card->open_mode &= ~((file->f_mode << FMODE_MIDI_SHIFT) & (FMODE_MIDI_READ | FMODE_MIDI_WRITE)); up(&card->open_sem); wake_up_interruptible(&card->open_wait); unlock_kernel(); return 0; } static ssize_t emu10k1_midi_read(struct file *file, char *buffer, size_t count, loff_t * pos) { struct emu10k1_mididevice *midi_dev = (struct emu10k1_mididevice *) file->private_data; ssize_t ret = 0; u16 cnt; unsigned long flags; DPD(4, "emu10k1_midi_read(), count %#x\n", (u32) count); if (pos != &file->f_pos) return -ESPIPE; if (!access_ok(VERIFY_WRITE, buffer, count)) return -EFAULT; if (midi_dev->mistate == MIDIIN_STATE_STOPPED) { if (emu10k1_mpuin_start(midi_dev->card) < 0) { ERROR(); return -EINVAL; } midi_dev->mistate = MIDIIN_STATE_STARTED; } while (count > 0) { cnt = MIDIIN_BUFLEN - midi_dev->ird; spin_lock_irqsave(&midi_spinlock, flags); if (midi_dev->icnt < cnt) cnt = midi_dev->icnt; spin_unlock_irqrestore(&midi_spinlock, flags); if (cnt > count) cnt = count; if (cnt <= 0) { if (file->f_flags & O_NONBLOCK) return ret ? ret : -EAGAIN; DPF(2, " Go to sleep...\n"); interruptible_sleep_on(&midi_dev->iWait); if (signal_pending(current)) return ret ? ret : -ERESTARTSYS; continue; } if (copy_to_user(buffer, midi_dev->iBuf + midi_dev->ird, cnt)) { ERROR(); return ret ? ret : -EFAULT; } midi_dev->ird += cnt; midi_dev->ird %= MIDIIN_BUFLEN; spin_lock_irqsave(&midi_spinlock, flags); midi_dev->icnt -= cnt; spin_unlock_irqrestore(&midi_spinlock, flags); count -= cnt; buffer += cnt; ret += cnt; if (midi_dev->icnt == 0) break; } return ret; } static ssize_t emu10k1_midi_write(struct file *file, const char *buffer, size_t count, loff_t * pos) { struct emu10k1_mididevice *midi_dev = (struct emu10k1_mididevice *) file->private_data; struct midi_hdr *midihdr; ssize_t ret = 0; unsigned long flags; DPD(4, "emu10k1_midi_write(), count=%#x\n", (u32) count); if (pos != &file->f_pos) return -ESPIPE; if (!access_ok(VERIFY_READ, buffer, count)) return -EFAULT; if ((midihdr = (struct midi_hdr *) kmalloc(sizeof(struct midi_hdr), GFP_KERNEL)) == NULL) return -EINVAL; midihdr->bufferlength = count; midihdr->bytesrecorded = 0; midihdr->flags = 0; if ((midihdr->data = (u8 *) kmalloc(count, GFP_KERNEL)) == NULL) { ERROR(); kfree(midihdr); return -EINVAL; } if (copy_from_user(midihdr->data, buffer, count)) { kfree(midihdr->data); kfree(midihdr); return ret ? ret : -EFAULT; } spin_lock_irqsave(&midi_spinlock, flags); if (emu10k1_mpuout_add_buffer(midi_dev->card, midihdr) < 0) { ERROR(); kfree(midihdr->data); kfree(midihdr); spin_unlock_irqrestore(&midi_spinlock, flags); return -EINVAL; } spin_unlock_irqrestore(&midi_spinlock, flags); return count; } static unsigned int emu10k1_midi_poll(struct file *file, struct poll_table_struct *wait) { struct emu10k1_mididevice *midi_dev = (struct emu10k1_mididevice *) file->private_data; unsigned long flags; unsigned int mask = 0; DPF(4, "emu10k1_midi_poll() called\n"); if (file->f_mode & FMODE_WRITE) poll_wait(file, &midi_dev->oWait, wait); if (file->f_mode & FMODE_READ) poll_wait(file, &midi_dev->iWait, wait); spin_lock_irqsave(&midi_spinlock, flags); if (file->f_mode & FMODE_WRITE) mask |= POLLOUT | POLLWRNORM; if (file->f_mode & FMODE_READ) { if (midi_dev->mistate == MIDIIN_STATE_STARTED) if (midi_dev->icnt > 0) mask |= POLLIN | POLLRDNORM; } spin_unlock_irqrestore(&midi_spinlock, flags); return mask; } int emu10k1_midi_callback(unsigned long msg, unsigned long refdata, unsigned long *pmsg) { struct emu10k1_mididevice *midi_dev = (struct emu10k1_mididevice *) refdata; struct midi_hdr *midihdr = NULL; unsigned long flags; int i; DPF(4, "emu10k1_midi_callback()\n"); spin_lock_irqsave(&midi_spinlock, flags); switch (msg) { case ICARDMIDI_OUTLONGDATA: midihdr = (struct midi_hdr *) pmsg[2]; kfree(midihdr->data); kfree(midihdr); wake_up_interruptible(&midi_dev->oWait); break; case ICARDMIDI_INLONGDATA: midihdr = (struct midi_hdr *) pmsg[2]; for (i = 0; i < midihdr->bytesrecorded; i++) { midi_dev->iBuf[midi_dev->iwr++] = midihdr->data[i]; midi_dev->iwr %= MIDIIN_BUFLEN; } midi_dev->icnt += midihdr->bytesrecorded; if (midi_dev->mistate == MIDIIN_STATE_STARTED) { init_midi_hdr(midihdr); emu10k1_mpuin_add_buffer(midi_dev->card->mpuin, midihdr); wake_up_interruptible(&midi_dev->iWait); } break; case ICARDMIDI_INDATA: { u8 *pBuf = (u8 *) & pmsg[1]; u16 bytesvalid = pmsg[2]; for (i = 0; i < bytesvalid; i++) { midi_dev->iBuf[midi_dev->iwr++] = pBuf[i]; midi_dev->iwr %= MIDIIN_BUFLEN; } midi_dev->icnt += bytesvalid; } wake_up_interruptible(&midi_dev->iWait); break; default: /* Unknown message */ spin_unlock_irqrestore(&midi_spinlock, flags); return -1; } spin_unlock_irqrestore(&midi_spinlock, flags); return 0; } /* MIDI file operations */ struct file_operations emu10k1_midi_fops = { owner: THIS_MODULE, read: emu10k1_midi_read, write: emu10k1_midi_write, poll: emu10k1_midi_poll, open: emu10k1_midi_open, release: emu10k1_midi_release, }; #ifdef EMU10K1_SEQUENCER /* functions used for sequencer access */ int emu10k1_seq_midi_open(int dev, int mode, void (*input) (int dev, unsigned char data), void (*output) (int dev)) { struct emu10k1_card *card; struct midi_openinfo dsCardMidiOpenInfo; struct emu10k1_mididevice *midi_dev; if (midi_devs[dev] == NULL || midi_devs[dev]->devc == NULL) return -EINVAL; card = midi_devs[dev]->devc; if (card->open_mode) /* card is opened native */ return -EBUSY; DPF(2, "emu10k1_seq_midi_open()\n"); if ((midi_dev = (struct emu10k1_mididevice *) kmalloc(sizeof(*midi_dev), GFP_KERNEL)) == NULL) return -EINVAL; midi_dev->card = card; midi_dev->mistate = MIDIIN_STATE_STOPPED; init_waitqueue_head(&midi_dev->oWait); init_waitqueue_head(&midi_dev->iWait); midi_dev->ird = 0; midi_dev->iwr = 0; midi_dev->icnt = 0; INIT_LIST_HEAD(&midi_dev->mid_hdrs); dsCardMidiOpenInfo.refdata = (unsigned long) midi_dev; if (emu10k1_mpuout_open(card, &dsCardMidiOpenInfo) < 0) { ERROR(); return -ENODEV; } card->seq_mididev = midi_dev; return 0; } void emu10k1_seq_midi_close(int dev) { struct emu10k1_card *card; DPF(2, "emu10k1_seq_midi_close()\n"); if (midi_devs[dev] == NULL || midi_devs[dev]->devc == NULL) return; card = midi_devs[dev]->devc; emu10k1_mpuout_close(card); if (card->seq_mididev) { kfree(card->seq_mididev); card->seq_mididev = 0; } } int emu10k1_seq_midi_out(int dev, unsigned char midi_byte) { struct emu10k1_card *card; struct midi_hdr *midihdr; unsigned long flags; if (midi_devs[dev] == NULL || midi_devs[dev]->devc == NULL) return -EINVAL; card = midi_devs[dev]->devc; if ((midihdr = (struct midi_hdr *) kmalloc(sizeof(struct midi_hdr), GFP_KERNEL)) == NULL) return -EINVAL; midihdr->bufferlength = 1; midihdr->bytesrecorded = 0; midihdr->flags = 0; if ((midihdr->data = (u8 *) kmalloc(1, GFP_KERNEL)) == NULL) { ERROR(); kfree(midihdr); return -EINVAL; } *(midihdr->data) = midi_byte; spin_lock_irqsave(&midi_spinlock, flags); if (emu10k1_mpuout_add_buffer(card, midihdr) < 0) { ERROR(); kfree(midihdr->data); kfree(midihdr); spin_unlock_irqrestore(&midi_spinlock, flags); return -EINVAL; } spin_unlock_irqrestore(&midi_spinlock, flags); return 1; } int emu10k1_seq_midi_start_read(int dev) { return 0; } int emu10k1_seq_midi_end_read(int dev) { return 0; } void emu10k1_seq_midi_kick(int dev) { } int emu10k1_seq_midi_buffer_status(int dev) { int count; struct midi_queue *queue; struct emu10k1_card *card; if (midi_devs[dev] == NULL || midi_devs[dev]->devc == NULL) return -EINVAL; count = 0; card = midi_devs[dev]->devc; queue = card->mpuout->firstmidiq; while (queue != NULL) { count++; if (queue == card->mpuout->lastmidiq) break; queue = queue->next; } return count; } #endif
gpl-2.0
william-wfei/linux
arch/x86/kernel/kvm.c
24
14931
/* * KVM paravirt_ops implementation * * 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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (C) 2007, Red Hat, Inc., Ingo Molnar <mingo@redhat.com> * Copyright IBM Corporation, 2007 * Authors: Anthony Liguori <aliguori@us.ibm.com> */ #include <linux/context_tracking.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/kvm_para.h> #include <linux/cpu.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/hardirq.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/hash.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/kprobes.h> #include <linux/debugfs.h> #include <linux/nmi.h> #include <linux/swait.h> #include <asm/timer.h> #include <asm/cpu.h> #include <asm/traps.h> #include <asm/desc.h> #include <asm/tlbflush.h> #include <asm/apic.h> #include <asm/apicdef.h> #include <asm/hypervisor.h> #include <asm/kvm_guest.h> static int kvmapf = 1; static int parse_no_kvmapf(char *arg) { kvmapf = 0; return 0; } early_param("no-kvmapf", parse_no_kvmapf); static int steal_acc = 1; static int parse_no_stealacc(char *arg) { steal_acc = 0; return 0; } early_param("no-steal-acc", parse_no_stealacc); static int kvmclock_vsyscall = 1; static int parse_no_kvmclock_vsyscall(char *arg) { kvmclock_vsyscall = 0; return 0; } early_param("no-kvmclock-vsyscall", parse_no_kvmclock_vsyscall); static DEFINE_PER_CPU(struct kvm_vcpu_pv_apf_data, apf_reason) __aligned(64); static DEFINE_PER_CPU(struct kvm_steal_time, steal_time) __aligned(64); static int has_steal_clock = 0; /* * No need for any "IO delay" on KVM */ static void kvm_io_delay(void) { } #define KVM_TASK_SLEEP_HASHBITS 8 #define KVM_TASK_SLEEP_HASHSIZE (1<<KVM_TASK_SLEEP_HASHBITS) struct kvm_task_sleep_node { struct hlist_node link; struct swait_queue_head wq; u32 token; int cpu; bool halted; }; static struct kvm_task_sleep_head { raw_spinlock_t lock; struct hlist_head list; } async_pf_sleepers[KVM_TASK_SLEEP_HASHSIZE]; static struct kvm_task_sleep_node *_find_apf_task(struct kvm_task_sleep_head *b, u32 token) { struct hlist_node *p; hlist_for_each(p, &b->list) { struct kvm_task_sleep_node *n = hlist_entry(p, typeof(*n), link); if (n->token == token) return n; } return NULL; } void kvm_async_pf_task_wait(u32 token) { u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS); struct kvm_task_sleep_head *b = &async_pf_sleepers[key]; struct kvm_task_sleep_node n, *e; DECLARE_SWAITQUEUE(wait); rcu_irq_enter(); raw_spin_lock(&b->lock); e = _find_apf_task(b, token); if (e) { /* dummy entry exist -> wake up was delivered ahead of PF */ hlist_del(&e->link); kfree(e); raw_spin_unlock(&b->lock); rcu_irq_exit(); return; } n.token = token; n.cpu = smp_processor_id(); n.halted = is_idle_task(current) || preempt_count() > 1; init_swait_queue_head(&n.wq); hlist_add_head(&n.link, &b->list); raw_spin_unlock(&b->lock); for (;;) { if (!n.halted) prepare_to_swait(&n.wq, &wait, TASK_UNINTERRUPTIBLE); if (hlist_unhashed(&n.link)) break; if (!n.halted) { local_irq_enable(); schedule(); local_irq_disable(); } else { /* * We cannot reschedule. So halt. */ rcu_irq_exit(); native_safe_halt(); rcu_irq_enter(); local_irq_disable(); } } if (!n.halted) finish_swait(&n.wq, &wait); rcu_irq_exit(); return; } EXPORT_SYMBOL_GPL(kvm_async_pf_task_wait); static void apf_task_wake_one(struct kvm_task_sleep_node *n) { hlist_del_init(&n->link); if (n->halted) smp_send_reschedule(n->cpu); else if (swait_active(&n->wq)) swake_up(&n->wq); } static void apf_task_wake_all(void) { int i; for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) { struct hlist_node *p, *next; struct kvm_task_sleep_head *b = &async_pf_sleepers[i]; raw_spin_lock(&b->lock); hlist_for_each_safe(p, next, &b->list) { struct kvm_task_sleep_node *n = hlist_entry(p, typeof(*n), link); if (n->cpu == smp_processor_id()) apf_task_wake_one(n); } raw_spin_unlock(&b->lock); } } void kvm_async_pf_task_wake(u32 token) { u32 key = hash_32(token, KVM_TASK_SLEEP_HASHBITS); struct kvm_task_sleep_head *b = &async_pf_sleepers[key]; struct kvm_task_sleep_node *n; if (token == ~0) { apf_task_wake_all(); return; } again: raw_spin_lock(&b->lock); n = _find_apf_task(b, token); if (!n) { /* * async PF was not yet handled. * Add dummy entry for the token. */ n = kzalloc(sizeof(*n), GFP_ATOMIC); if (!n) { /* * Allocation failed! Busy wait while other cpu * handles async PF. */ raw_spin_unlock(&b->lock); cpu_relax(); goto again; } n->token = token; n->cpu = smp_processor_id(); init_swait_queue_head(&n->wq); hlist_add_head(&n->link, &b->list); } else apf_task_wake_one(n); raw_spin_unlock(&b->lock); return; } EXPORT_SYMBOL_GPL(kvm_async_pf_task_wake); u32 kvm_read_and_reset_pf_reason(void) { u32 reason = 0; if (__this_cpu_read(apf_reason.enabled)) { reason = __this_cpu_read(apf_reason.reason); __this_cpu_write(apf_reason.reason, 0); } return reason; } EXPORT_SYMBOL_GPL(kvm_read_and_reset_pf_reason); NOKPROBE_SYMBOL(kvm_read_and_reset_pf_reason); dotraplinkage void do_async_page_fault(struct pt_regs *regs, unsigned long error_code) { enum ctx_state prev_state; switch (kvm_read_and_reset_pf_reason()) { default: trace_do_page_fault(regs, error_code); break; case KVM_PV_REASON_PAGE_NOT_PRESENT: /* page is swapped out by the host. */ prev_state = exception_enter(); kvm_async_pf_task_wait((u32)read_cr2()); exception_exit(prev_state); break; case KVM_PV_REASON_PAGE_READY: rcu_irq_enter(); kvm_async_pf_task_wake((u32)read_cr2()); rcu_irq_exit(); break; } } NOKPROBE_SYMBOL(do_async_page_fault); static void __init paravirt_ops_setup(void) { pv_info.name = "KVM"; if (kvm_para_has_feature(KVM_FEATURE_NOP_IO_DELAY)) pv_cpu_ops.io_delay = kvm_io_delay; #ifdef CONFIG_X86_IO_APIC no_timer_check = 1; #endif } static void kvm_register_steal_time(void) { int cpu = smp_processor_id(); struct kvm_steal_time *st = &per_cpu(steal_time, cpu); if (!has_steal_clock) return; wrmsrl(MSR_KVM_STEAL_TIME, (slow_virt_to_phys(st) | KVM_MSR_ENABLED)); pr_info("kvm-stealtime: cpu %d, msr %llx\n", cpu, (unsigned long long) slow_virt_to_phys(st)); } static DEFINE_PER_CPU(unsigned long, kvm_apic_eoi) = KVM_PV_EOI_DISABLED; static notrace void kvm_guest_apic_eoi_write(u32 reg, u32 val) { /** * This relies on __test_and_clear_bit to modify the memory * in a way that is atomic with respect to the local CPU. * The hypervisor only accesses this memory from the local CPU so * there's no need for lock or memory barriers. * An optimization barrier is implied in apic write. */ if (__test_and_clear_bit(KVM_PV_EOI_BIT, this_cpu_ptr(&kvm_apic_eoi))) return; apic->native_eoi_write(APIC_EOI, APIC_EOI_ACK); } static void kvm_guest_cpu_init(void) { if (!kvm_para_available()) return; if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF) && kvmapf) { u64 pa = slow_virt_to_phys(this_cpu_ptr(&apf_reason)); #ifdef CONFIG_PREEMPT pa |= KVM_ASYNC_PF_SEND_ALWAYS; #endif wrmsrl(MSR_KVM_ASYNC_PF_EN, pa | KVM_ASYNC_PF_ENABLED); __this_cpu_write(apf_reason.enabled, 1); printk(KERN_INFO"KVM setup async PF for cpu %d\n", smp_processor_id()); } if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) { unsigned long pa; /* Size alignment is implied but just to make it explicit. */ BUILD_BUG_ON(__alignof__(kvm_apic_eoi) < 4); __this_cpu_write(kvm_apic_eoi, 0); pa = slow_virt_to_phys(this_cpu_ptr(&kvm_apic_eoi)) | KVM_MSR_ENABLED; wrmsrl(MSR_KVM_PV_EOI_EN, pa); } if (has_steal_clock) kvm_register_steal_time(); } static void kvm_pv_disable_apf(void) { if (!__this_cpu_read(apf_reason.enabled)) return; wrmsrl(MSR_KVM_ASYNC_PF_EN, 0); __this_cpu_write(apf_reason.enabled, 0); printk(KERN_INFO"Unregister pv shared memory for cpu %d\n", smp_processor_id()); } static void kvm_pv_guest_cpu_reboot(void *unused) { /* * We disable PV EOI before we load a new kernel by kexec, * since MSR_KVM_PV_EOI_EN stores a pointer into old kernel's memory. * New kernel can re-enable when it boots. */ if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) wrmsrl(MSR_KVM_PV_EOI_EN, 0); kvm_pv_disable_apf(); kvm_disable_steal_time(); } static int kvm_pv_reboot_notify(struct notifier_block *nb, unsigned long code, void *unused) { if (code == SYS_RESTART) on_each_cpu(kvm_pv_guest_cpu_reboot, NULL, 1); return NOTIFY_DONE; } static struct notifier_block kvm_pv_reboot_nb = { .notifier_call = kvm_pv_reboot_notify, }; static u64 kvm_steal_clock(int cpu) { u64 steal; struct kvm_steal_time *src; int version; src = &per_cpu(steal_time, cpu); do { version = src->version; rmb(); steal = src->steal; rmb(); } while ((version & 1) || (version != src->version)); return steal; } void kvm_disable_steal_time(void) { if (!has_steal_clock) return; wrmsr(MSR_KVM_STEAL_TIME, 0, 0); } #ifdef CONFIG_SMP static void __init kvm_smp_prepare_boot_cpu(void) { kvm_guest_cpu_init(); native_smp_prepare_boot_cpu(); kvm_spinlock_init(); } static void kvm_guest_cpu_offline(void) { kvm_disable_steal_time(); if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) wrmsrl(MSR_KVM_PV_EOI_EN, 0); kvm_pv_disable_apf(); apf_task_wake_all(); } static int kvm_cpu_online(unsigned int cpu) { local_irq_disable(); kvm_guest_cpu_init(); local_irq_enable(); return 0; } static int kvm_cpu_down_prepare(unsigned int cpu) { local_irq_disable(); kvm_guest_cpu_offline(); local_irq_enable(); return 0; } #endif static void __init kvm_apf_trap_init(void) { set_intr_gate(14, async_page_fault); } void __init kvm_guest_init(void) { int i; if (!kvm_para_available()) return; paravirt_ops_setup(); register_reboot_notifier(&kvm_pv_reboot_nb); for (i = 0; i < KVM_TASK_SLEEP_HASHSIZE; i++) raw_spin_lock_init(&async_pf_sleepers[i].lock); if (kvm_para_has_feature(KVM_FEATURE_ASYNC_PF)) x86_init.irqs.trap_init = kvm_apf_trap_init; if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) { has_steal_clock = 1; pv_time_ops.steal_clock = kvm_steal_clock; } if (kvm_para_has_feature(KVM_FEATURE_PV_EOI)) apic_set_eoi_write(kvm_guest_apic_eoi_write); if (kvmclock_vsyscall) kvm_setup_vsyscall_timeinfo(); #ifdef CONFIG_SMP smp_ops.smp_prepare_boot_cpu = kvm_smp_prepare_boot_cpu; if (cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "x86/kvm:online", kvm_cpu_online, kvm_cpu_down_prepare) < 0) pr_err("kvm_guest: Failed to install cpu hotplug callbacks\n"); #else kvm_guest_cpu_init(); #endif /* * Hard lockup detection is enabled by default. Disable it, as guests * can get false positives too easily, for example if the host is * overcommitted. */ hardlockup_detector_disable(); } static noinline uint32_t __kvm_cpuid_base(void) { if (boot_cpu_data.cpuid_level < 0) return 0; /* So we don't blow up on old processors */ if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) return hypervisor_cpuid_base("KVMKVMKVM\0\0\0", 0); return 0; } static inline uint32_t kvm_cpuid_base(void) { static int kvm_cpuid_base = -1; if (kvm_cpuid_base == -1) kvm_cpuid_base = __kvm_cpuid_base(); return kvm_cpuid_base; } bool kvm_para_available(void) { return kvm_cpuid_base() != 0; } EXPORT_SYMBOL_GPL(kvm_para_available); unsigned int kvm_arch_para_features(void) { return cpuid_eax(kvm_cpuid_base() | KVM_CPUID_FEATURES); } static uint32_t __init kvm_detect(void) { return kvm_cpuid_base(); } const struct hypervisor_x86 x86_hyper_kvm __refconst = { .name = "KVM", .detect = kvm_detect, .x2apic_available = kvm_para_available, }; EXPORT_SYMBOL_GPL(x86_hyper_kvm); static __init int activate_jump_labels(void) { if (has_steal_clock) { static_key_slow_inc(&paravirt_steal_enabled); if (steal_acc) static_key_slow_inc(&paravirt_steal_rq_enabled); } return 0; } arch_initcall(activate_jump_labels); #ifdef CONFIG_PARAVIRT_SPINLOCKS /* Kick a cpu by its apicid. Used to wake up a halted vcpu */ static void kvm_kick_cpu(int cpu) { int apicid; unsigned long flags = 0; apicid = per_cpu(x86_cpu_to_apicid, cpu); kvm_hypercall2(KVM_HC_KICK_CPU, flags, apicid); } #include <asm/qspinlock.h> static void kvm_wait(u8 *ptr, u8 val) { unsigned long flags; if (in_nmi()) return; local_irq_save(flags); if (READ_ONCE(*ptr) != val) goto out; /* * halt until it's our turn and kicked. Note that we do safe halt * for irq enabled case to avoid hang when lock info is overwritten * in irq spinlock slowpath and no spurious interrupt occur to save us. */ if (arch_irqs_disabled_flags(flags)) halt(); else safe_halt(); out: local_irq_restore(flags); } #ifdef CONFIG_X86_32 __visible bool __kvm_vcpu_is_preempted(long cpu) { struct kvm_steal_time *src = &per_cpu(steal_time, cpu); return !!src->preempted; } PV_CALLEE_SAVE_REGS_THUNK(__kvm_vcpu_is_preempted); #else #include <asm/asm-offsets.h> extern bool __raw_callee_save___kvm_vcpu_is_preempted(long); /* * Hand-optimize version for x86-64 to avoid 8 64-bit register saving and * restoring to/from the stack. */ asm( ".pushsection .text;" ".global __raw_callee_save___kvm_vcpu_is_preempted;" ".type __raw_callee_save___kvm_vcpu_is_preempted, @function;" "__raw_callee_save___kvm_vcpu_is_preempted:" "movq __per_cpu_offset(,%rdi,8), %rax;" "cmpb $0, " __stringify(KVM_STEAL_TIME_preempted) "+steal_time(%rax);" "setne %al;" "ret;" ".popsection"); #endif /* * Setup pv_lock_ops to exploit KVM_FEATURE_PV_UNHALT if present. */ void __init kvm_spinlock_init(void) { if (!kvm_para_available()) return; /* Does host kernel support KVM_FEATURE_PV_UNHALT? */ if (!kvm_para_has_feature(KVM_FEATURE_PV_UNHALT)) return; __pv_init_lock_hash(); pv_lock_ops.queued_spin_lock_slowpath = __pv_queued_spin_lock_slowpath; pv_lock_ops.queued_spin_unlock = PV_CALLEE_SAVE(__pv_queued_spin_unlock); pv_lock_ops.wait = kvm_wait; pv_lock_ops.kick = kvm_kick_cpu; if (kvm_para_has_feature(KVM_FEATURE_STEAL_TIME)) { pv_lock_ops.vcpu_is_preempted = PV_CALLEE_SAVE(__kvm_vcpu_is_preempted); } } #endif /* CONFIG_PARAVIRT_SPINLOCKS */
gpl-2.0
Fighter1/OpenRP
codeJK2/game/AI_Mark2.cpp
24
9791
/* =========================================================================== Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "g_headers.h" #include "b_local.h" #include "g_nav.h" //#define AMMO_POD_HEALTH 40 #define AMMO_POD_HEALTH 1 #define TURN_OFF 0x00000100 #define VELOCITY_DECAY 0.25 #define MAX_DISTANCE 256 #define MAX_DISTANCE_SQR ( MAX_DISTANCE * MAX_DISTANCE ) #define MIN_DISTANCE 24 #define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) extern gitem_t *FindItemForAmmo( ammo_t ammo ); //Local state enums enum { LSTATE_NONE = 0, LSTATE_DROPPINGDOWN, LSTATE_DOWN, LSTATE_RISINGUP, }; gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); void NPC_Mark2_Precache( void ) { G_SoundIndex( "sound/chars/mark2/misc/mark2_explo" );// blows up on death G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" ); G_SoundIndex( "sound/chars/mark2/misc/mark2_fire" ); G_SoundIndex( "sound/chars/mark2/misc/mark2_move_lp" ); G_EffectIndex( "droidexplosion1" ); G_EffectIndex( "env/med_explode2" ); G_EffectIndex( "blaster/smoke_bolton" ); G_EffectIndex( "bryar/muzzle_flash" ); RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL )); RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS)); RegisterItem( FindItemForAmmo( AMMO_POWERCELL )); RegisterItem( FindItemForAmmo( AMMO_BLASTER )); } /* ------------------------- NPC_Mark2_Part_Explode ------------------------- */ void NPC_Mark2_Part_Explode( gentity_t *self, int bolt ) { if ( bolt >=0 ) { mdxaBone_t boltMatrix; vec3_t org, dir; gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, bolt, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), NULL, self->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); G_PlayEffect( "env/med_explode2", org, dir ); } G_PlayEffect( "blaster/smoke_bolton", self->playerModel, bolt, self->s.number); self->count++; // Count of pods blown off } /* ------------------------- NPC_Mark2_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ void NPC_Mark2_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) { int newBolt,i; NPC_Pain( self, inflictor, other, point, damage, mod ); for (i=0;i<3;i++) { if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? { if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("torso_canister%d",(i+1)) ); if ( newBolt != -1 ) { NPC_Mark2_Part_Explode(self,newBolt); } gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_canister%d",(i+1)), TURN_OFF ); break; } } } G_Sound( self, G_SoundIndex( "sound/chars/mark2/misc/mark2_pain" )); // If any pods were blown off, kill him if (self->count > 0) { G_Damage( self, NULL, NULL, NULL, NULL, self->health, DAMAGE_NO_PROTECTION, MOD_UNKNOWN ); } } /* ------------------------- Mark2_Hunt ------------------------- */ void Mark2_Hunt(void) { if ( NPCInfo->goalEntity == NULL ) { NPCInfo->goalEntity = NPC->enemy; } // Turn toward him before moving towards him. NPC_FaceEnemy( qtrue ); NPCInfo->combatMove = qtrue; NPC_MoveToGoal( qtrue ); } /* ------------------------- Mark2_FireBlaster ------------------------- */ void Mark2_FireBlaster(qboolean advance) { vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; static vec3_t forward, vright, up; gentity_t *missile; mdxaBone_t boltMatrix; gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, NPC->genericBolt1, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), NULL, NPC->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); if (NPC->health) { CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); VectorSubtract (enemy_org1, muzzle1, delta1); vectoangles ( delta1, angleToEnemy1 ); AngleVectors (angleToEnemy1, forward, vright, up); } else { AngleVectors (NPC->currentAngles, forward, vright, up); } G_PlayEffect( "bryar/muzzle_flash", muzzle1, forward ); G_Sound( NPC, G_SoundIndex("sound/chars/mark2/misc/mark2_fire")); missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; missile->damage = 1; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; } /* ------------------------- Mark2_BlasterAttack ------------------------- */ void Mark2_BlasterAttack(qboolean advance) { if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? { if (NPCInfo->localState == LSTATE_NONE) // He's up so shoot less often. { TIMER_Set( NPC, "attackDelay", Q_irand( 500, 2000) ); } else { TIMER_Set( NPC, "attackDelay", Q_irand( 100, 500) ); } Mark2_FireBlaster(advance); return; } else if (advance) { Mark2_Hunt(); } } /* ------------------------- Mark2_AttackDecision ------------------------- */ void Mark2_AttackDecision( void ) { NPC_FaceEnemy( qtrue ); float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); qboolean visible = NPC_ClearLOS( NPC->enemy ); qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // He's been ordered to get up if (NPCInfo->localState == LSTATE_RISINGUP) { NPC->flags &= ~FL_SHIELDED; NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1START, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); if ((NPC->client->ps.legsAnimTimer==0) && NPC->client->ps.torsoAnim == BOTH_RUN1START ) { NPCInfo->localState = LSTATE_NONE; // He's up again. } return; } // If we cannot see our target, move to see it if ((!visible) || (!NPC_FaceEnemy(qtrue))) { // If he's going down or is down, make him get up if ((NPCInfo->localState == LSTATE_DOWN) || (NPCInfo->localState == LSTATE_DROPPINGDOWN)) { if ( TIMER_Done( NPC, "downTime" ) ) // Down being down?? (The delay is so he doesn't pop up and down when the player goes in and out of range) { NPCInfo->localState = LSTATE_RISINGUP; NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); TIMER_Set( NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. } } else { Mark2_Hunt(); } return; } // He's down but he could advance if he wants to. if ((advance) && (TIMER_Done( NPC, "downTime" )) && (NPCInfo->localState == LSTATE_DOWN)) { NPCInfo->localState = LSTATE_RISINGUP; NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); TIMER_Set( NPC, "runTime", Q_irand( 3000, 8000) ); // So he runs for a while before testing to see if he should drop down. } NPC_FaceEnemy( qtrue ); // Dropping down to shoot if (NPCInfo->localState == LSTATE_DROPPINGDOWN) { NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_RUN1STOP, SETANIM_FLAG_HOLD|SETANIM_FLAG_OVERRIDE ); TIMER_Set( NPC, "downTime", Q_irand( 3000, 9000) ); if ((NPC->client->ps.legsAnimTimer==0) && NPC->client->ps.torsoAnim == BOTH_RUN1STOP ) { NPC->flags |= FL_SHIELDED; NPCInfo->localState = LSTATE_DOWN; } } // He's down and shooting else if (NPCInfo->localState == LSTATE_DOWN) { // NPC->flags |= FL_SHIELDED;//only damagable by lightsabers and missiles Mark2_BlasterAttack(qfalse); } else if (TIMER_Done( NPC, "runTime" )) // Lowering down to attack. But only if he's done running at you. { NPCInfo->localState = LSTATE_DROPPINGDOWN; } else if (advance) { // We can see enemy so shoot him if timer lets you. Mark2_BlasterAttack(advance); } } /* ------------------------- Mark2_Patrol ------------------------- */ void Mark2_Patrol( void ) { if ( NPC_CheckPlayerTeamStealth() ) { // G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/anger.wav")); NPC_UpdateAngles( qtrue, qtrue ); return; } //If we have somewhere to go, then do that if (!NPC->enemy) { if ( UpdateGoal() ) { ucmd.buttons |= BUTTON_WALKING; NPC_MoveToGoal( qtrue ); NPC_UpdateAngles( qtrue, qtrue ); } //randomly talk if (TIMER_Done(NPC,"patrolNoise")) { // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); } } } /* ------------------------- Mark2_Idle ------------------------- */ void Mark2_Idle( void ) { NPC_BSIdle(); } /* ------------------------- NPC_BSMark2_Default ------------------------- */ void NPC_BSMark2_Default( void ) { if ( NPC->enemy ) { NPCInfo->goalEntity = NPC->enemy; Mark2_AttackDecision(); } else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) { Mark2_Patrol(); } else { Mark2_Idle(); } }
gpl-2.0
caibo2014/mptcp
drivers/spi/spi-bfin-sport.c
280
23378
/* * SPI bus via the Blackfin SPORT peripheral * * Enter bugs at http://blackfin.uclinux.org/ * * Copyright 2009-2011 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #include <linux/init.h> #include <linux/module.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/gpio.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/irq.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/spi/spi.h> #include <linux/workqueue.h> #include <asm/portmux.h> #include <asm/bfin5xx_spi.h> #include <asm/blackfin.h> #include <asm/bfin_sport.h> #include <asm/cacheflush.h> #define DRV_NAME "bfin-sport-spi" #define DRV_DESC "SPI bus via the Blackfin SPORT" MODULE_AUTHOR("Cliff Cai"); MODULE_DESCRIPTION(DRV_DESC); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:bfin-sport-spi"); enum bfin_sport_spi_state { START_STATE, RUNNING_STATE, DONE_STATE, ERROR_STATE, }; struct bfin_sport_spi_master_data; struct bfin_sport_transfer_ops { void (*write) (struct bfin_sport_spi_master_data *); void (*read) (struct bfin_sport_spi_master_data *); void (*duplex) (struct bfin_sport_spi_master_data *); }; struct bfin_sport_spi_master_data { /* Driver model hookup */ struct device *dev; /* SPI framework hookup */ struct spi_master *master; /* Regs base of SPI controller */ struct sport_register __iomem *regs; int err_irq; /* Pin request list */ u16 *pin_req; /* Driver message queue */ struct workqueue_struct *workqueue; struct work_struct pump_messages; spinlock_t lock; struct list_head queue; int busy; bool run; /* Message Transfer pump */ struct tasklet_struct pump_transfers; /* Current message transfer state info */ enum bfin_sport_spi_state state; struct spi_message *cur_msg; struct spi_transfer *cur_transfer; struct bfin_sport_spi_slave_data *cur_chip; union { void *tx; u8 *tx8; u16 *tx16; }; void *tx_end; union { void *rx; u8 *rx8; u16 *rx16; }; void *rx_end; int cs_change; struct bfin_sport_transfer_ops *ops; }; struct bfin_sport_spi_slave_data { u16 ctl_reg; u16 baud; u16 cs_chg_udelay; /* Some devices require > 255usec delay */ u32 cs_gpio; u16 idle_tx_val; struct bfin_sport_transfer_ops *ops; }; static void bfin_sport_spi_enable(struct bfin_sport_spi_master_data *drv_data) { bfin_write_or(&drv_data->regs->tcr1, TSPEN); bfin_write_or(&drv_data->regs->rcr1, TSPEN); SSYNC(); } static void bfin_sport_spi_disable(struct bfin_sport_spi_master_data *drv_data) { bfin_write_and(&drv_data->regs->tcr1, ~TSPEN); bfin_write_and(&drv_data->regs->rcr1, ~TSPEN); SSYNC(); } /* Caculate the SPI_BAUD register value based on input HZ */ static u16 bfin_sport_hz_to_spi_baud(u32 speed_hz) { u_long clk, sclk = get_sclk(); int div = (sclk / (2 * speed_hz)) - 1; if (div < 0) div = 0; clk = sclk / (2 * (div + 1)); if (clk > speed_hz) div++; return div; } /* Chip select operation functions for cs_change flag */ static void bfin_sport_spi_cs_active(struct bfin_sport_spi_slave_data *chip) { gpio_direction_output(chip->cs_gpio, 0); } static void bfin_sport_spi_cs_deactive(struct bfin_sport_spi_slave_data *chip) { gpio_direction_output(chip->cs_gpio, 1); /* Move delay here for consistency */ if (chip->cs_chg_udelay) udelay(chip->cs_chg_udelay); } static void bfin_sport_spi_stat_poll_complete(struct bfin_sport_spi_master_data *drv_data) { unsigned long timeout = jiffies + HZ; while (!(bfin_read(&drv_data->regs->stat) & RXNE)) { if (!time_before(jiffies, timeout)) break; } } static void bfin_sport_spi_u8_writer(struct bfin_sport_spi_master_data *drv_data) { u16 dummy; while (drv_data->tx < drv_data->tx_end) { bfin_write(&drv_data->regs->tx16, *drv_data->tx8++); bfin_sport_spi_stat_poll_complete(drv_data); dummy = bfin_read(&drv_data->regs->rx16); } } static void bfin_sport_spi_u8_reader(struct bfin_sport_spi_master_data *drv_data) { u16 tx_val = drv_data->cur_chip->idle_tx_val; while (drv_data->rx < drv_data->rx_end) { bfin_write(&drv_data->regs->tx16, tx_val); bfin_sport_spi_stat_poll_complete(drv_data); *drv_data->rx8++ = bfin_read(&drv_data->regs->rx16); } } static void bfin_sport_spi_u8_duplex(struct bfin_sport_spi_master_data *drv_data) { while (drv_data->rx < drv_data->rx_end) { bfin_write(&drv_data->regs->tx16, *drv_data->tx8++); bfin_sport_spi_stat_poll_complete(drv_data); *drv_data->rx8++ = bfin_read(&drv_data->regs->rx16); } } static struct bfin_sport_transfer_ops bfin_sport_transfer_ops_u8 = { .write = bfin_sport_spi_u8_writer, .read = bfin_sport_spi_u8_reader, .duplex = bfin_sport_spi_u8_duplex, }; static void bfin_sport_spi_u16_writer(struct bfin_sport_spi_master_data *drv_data) { u16 dummy; while (drv_data->tx < drv_data->tx_end) { bfin_write(&drv_data->regs->tx16, *drv_data->tx16++); bfin_sport_spi_stat_poll_complete(drv_data); dummy = bfin_read(&drv_data->regs->rx16); } } static void bfin_sport_spi_u16_reader(struct bfin_sport_spi_master_data *drv_data) { u16 tx_val = drv_data->cur_chip->idle_tx_val; while (drv_data->rx < drv_data->rx_end) { bfin_write(&drv_data->regs->tx16, tx_val); bfin_sport_spi_stat_poll_complete(drv_data); *drv_data->rx16++ = bfin_read(&drv_data->regs->rx16); } } static void bfin_sport_spi_u16_duplex(struct bfin_sport_spi_master_data *drv_data) { while (drv_data->rx < drv_data->rx_end) { bfin_write(&drv_data->regs->tx16, *drv_data->tx16++); bfin_sport_spi_stat_poll_complete(drv_data); *drv_data->rx16++ = bfin_read(&drv_data->regs->rx16); } } static struct bfin_sport_transfer_ops bfin_sport_transfer_ops_u16 = { .write = bfin_sport_spi_u16_writer, .read = bfin_sport_spi_u16_reader, .duplex = bfin_sport_spi_u16_duplex, }; /* stop controller and re-config current chip */ static void bfin_sport_spi_restore_state(struct bfin_sport_spi_master_data *drv_data) { struct bfin_sport_spi_slave_data *chip = drv_data->cur_chip; bfin_sport_spi_disable(drv_data); dev_dbg(drv_data->dev, "restoring spi ctl state\n"); bfin_write(&drv_data->regs->tcr1, chip->ctl_reg); bfin_write(&drv_data->regs->tclkdiv, chip->baud); SSYNC(); bfin_write(&drv_data->regs->rcr1, chip->ctl_reg & ~(ITCLK | ITFS)); SSYNC(); bfin_sport_spi_cs_active(chip); } /* test if there is more transfer to be done */ static enum bfin_sport_spi_state bfin_sport_spi_next_transfer(struct bfin_sport_spi_master_data *drv_data) { struct spi_message *msg = drv_data->cur_msg; struct spi_transfer *trans = drv_data->cur_transfer; /* Move to next transfer */ if (trans->transfer_list.next != &msg->transfers) { drv_data->cur_transfer = list_entry(trans->transfer_list.next, struct spi_transfer, transfer_list); return RUNNING_STATE; } return DONE_STATE; } /* * caller already set message->status; * dma and pio irqs are blocked give finished message back */ static void bfin_sport_spi_giveback(struct bfin_sport_spi_master_data *drv_data) { struct bfin_sport_spi_slave_data *chip = drv_data->cur_chip; unsigned long flags; struct spi_message *msg; spin_lock_irqsave(&drv_data->lock, flags); msg = drv_data->cur_msg; drv_data->state = START_STATE; drv_data->cur_msg = NULL; drv_data->cur_transfer = NULL; drv_data->cur_chip = NULL; queue_work(drv_data->workqueue, &drv_data->pump_messages); spin_unlock_irqrestore(&drv_data->lock, flags); if (!drv_data->cs_change) bfin_sport_spi_cs_deactive(chip); if (msg->complete) msg->complete(msg->context); } static irqreturn_t sport_err_handler(int irq, void *dev_id) { struct bfin_sport_spi_master_data *drv_data = dev_id; u16 status; dev_dbg(drv_data->dev, "%s enter\n", __func__); status = bfin_read(&drv_data->regs->stat) & (TOVF | TUVF | ROVF | RUVF); if (status) { bfin_write(&drv_data->regs->stat, status); SSYNC(); bfin_sport_spi_disable(drv_data); dev_err(drv_data->dev, "status error:%s%s%s%s\n", status & TOVF ? " TOVF" : "", status & TUVF ? " TUVF" : "", status & ROVF ? " ROVF" : "", status & RUVF ? " RUVF" : ""); } return IRQ_HANDLED; } static void bfin_sport_spi_pump_transfers(unsigned long data) { struct bfin_sport_spi_master_data *drv_data = (void *)data; struct spi_message *message = NULL; struct spi_transfer *transfer = NULL; struct spi_transfer *previous = NULL; struct bfin_sport_spi_slave_data *chip = NULL; unsigned int bits_per_word; u32 tranf_success = 1; u32 transfer_speed; u8 full_duplex = 0; /* Get current state information */ message = drv_data->cur_msg; transfer = drv_data->cur_transfer; chip = drv_data->cur_chip; if (transfer->speed_hz) transfer_speed = bfin_sport_hz_to_spi_baud(transfer->speed_hz); else transfer_speed = chip->baud; bfin_write(&drv_data->regs->tclkdiv, transfer_speed); SSYNC(); /* * if msg is error or done, report it back using complete() callback */ /* Handle for abort */ if (drv_data->state == ERROR_STATE) { dev_dbg(drv_data->dev, "transfer: we've hit an error\n"); message->status = -EIO; bfin_sport_spi_giveback(drv_data); return; } /* Handle end of message */ if (drv_data->state == DONE_STATE) { dev_dbg(drv_data->dev, "transfer: all done!\n"); message->status = 0; bfin_sport_spi_giveback(drv_data); return; } /* Delay if requested at end of transfer */ if (drv_data->state == RUNNING_STATE) { dev_dbg(drv_data->dev, "transfer: still running ...\n"); previous = list_entry(transfer->transfer_list.prev, struct spi_transfer, transfer_list); if (previous->delay_usecs) udelay(previous->delay_usecs); } if (transfer->len == 0) { /* Move to next transfer of this msg */ drv_data->state = bfin_sport_spi_next_transfer(drv_data); /* Schedule next transfer tasklet */ tasklet_schedule(&drv_data->pump_transfers); } if (transfer->tx_buf != NULL) { drv_data->tx = (void *)transfer->tx_buf; drv_data->tx_end = drv_data->tx + transfer->len; dev_dbg(drv_data->dev, "tx_buf is %p, tx_end is %p\n", transfer->tx_buf, drv_data->tx_end); } else drv_data->tx = NULL; if (transfer->rx_buf != NULL) { full_duplex = transfer->tx_buf != NULL; drv_data->rx = transfer->rx_buf; drv_data->rx_end = drv_data->rx + transfer->len; dev_dbg(drv_data->dev, "rx_buf is %p, rx_end is %p\n", transfer->rx_buf, drv_data->rx_end); } else drv_data->rx = NULL; drv_data->cs_change = transfer->cs_change; /* Bits per word setup */ bits_per_word = transfer->bits_per_word; if (bits_per_word == 16) drv_data->ops = &bfin_sport_transfer_ops_u16; else drv_data->ops = &bfin_sport_transfer_ops_u8; bfin_write(&drv_data->regs->tcr2, bits_per_word - 1); bfin_write(&drv_data->regs->tfsdiv, bits_per_word - 1); bfin_write(&drv_data->regs->rcr2, bits_per_word - 1); drv_data->state = RUNNING_STATE; if (drv_data->cs_change) bfin_sport_spi_cs_active(chip); dev_dbg(drv_data->dev, "now pumping a transfer: width is %d, len is %d\n", bits_per_word, transfer->len); /* PIO mode write then read */ dev_dbg(drv_data->dev, "doing IO transfer\n"); bfin_sport_spi_enable(drv_data); if (full_duplex) { /* full duplex mode */ BUG_ON((drv_data->tx_end - drv_data->tx) != (drv_data->rx_end - drv_data->rx)); drv_data->ops->duplex(drv_data); if (drv_data->tx != drv_data->tx_end) tranf_success = 0; } else if (drv_data->tx != NULL) { /* write only half duplex */ drv_data->ops->write(drv_data); if (drv_data->tx != drv_data->tx_end) tranf_success = 0; } else if (drv_data->rx != NULL) { /* read only half duplex */ drv_data->ops->read(drv_data); if (drv_data->rx != drv_data->rx_end) tranf_success = 0; } bfin_sport_spi_disable(drv_data); if (!tranf_success) { dev_dbg(drv_data->dev, "IO write error!\n"); drv_data->state = ERROR_STATE; } else { /* Update total byte transferred */ message->actual_length += transfer->len; /* Move to next transfer of this msg */ drv_data->state = bfin_sport_spi_next_transfer(drv_data); if (drv_data->cs_change) bfin_sport_spi_cs_deactive(chip); } /* Schedule next transfer tasklet */ tasklet_schedule(&drv_data->pump_transfers); } /* pop a msg from queue and kick off real transfer */ static void bfin_sport_spi_pump_messages(struct work_struct *work) { struct bfin_sport_spi_master_data *drv_data; unsigned long flags; struct spi_message *next_msg; drv_data = container_of(work, struct bfin_sport_spi_master_data, pump_messages); /* Lock queue and check for queue work */ spin_lock_irqsave(&drv_data->lock, flags); if (list_empty(&drv_data->queue) || !drv_data->run) { /* pumper kicked off but no work to do */ drv_data->busy = 0; spin_unlock_irqrestore(&drv_data->lock, flags); return; } /* Make sure we are not already running a message */ if (drv_data->cur_msg) { spin_unlock_irqrestore(&drv_data->lock, flags); return; } /* Extract head of queue */ next_msg = list_entry(drv_data->queue.next, struct spi_message, queue); drv_data->cur_msg = next_msg; /* Setup the SSP using the per chip configuration */ drv_data->cur_chip = spi_get_ctldata(drv_data->cur_msg->spi); list_del_init(&drv_data->cur_msg->queue); /* Initialize message state */ drv_data->cur_msg->state = START_STATE; drv_data->cur_transfer = list_entry(drv_data->cur_msg->transfers.next, struct spi_transfer, transfer_list); bfin_sport_spi_restore_state(drv_data); dev_dbg(drv_data->dev, "got a message to pump, " "state is set to: baud %d, cs_gpio %i, ctl 0x%x\n", drv_data->cur_chip->baud, drv_data->cur_chip->cs_gpio, drv_data->cur_chip->ctl_reg); dev_dbg(drv_data->dev, "the first transfer len is %d\n", drv_data->cur_transfer->len); /* Mark as busy and launch transfers */ tasklet_schedule(&drv_data->pump_transfers); drv_data->busy = 1; spin_unlock_irqrestore(&drv_data->lock, flags); } /* * got a msg to transfer, queue it in drv_data->queue. * And kick off message pumper */ static int bfin_sport_spi_transfer(struct spi_device *spi, struct spi_message *msg) { struct bfin_sport_spi_master_data *drv_data = spi_master_get_devdata(spi->master); unsigned long flags; spin_lock_irqsave(&drv_data->lock, flags); if (!drv_data->run) { spin_unlock_irqrestore(&drv_data->lock, flags); return -ESHUTDOWN; } msg->actual_length = 0; msg->status = -EINPROGRESS; msg->state = START_STATE; dev_dbg(&spi->dev, "adding an msg in transfer()\n"); list_add_tail(&msg->queue, &drv_data->queue); if (drv_data->run && !drv_data->busy) queue_work(drv_data->workqueue, &drv_data->pump_messages); spin_unlock_irqrestore(&drv_data->lock, flags); return 0; } /* Called every time common spi devices change state */ static int bfin_sport_spi_setup(struct spi_device *spi) { struct bfin_sport_spi_slave_data *chip, *first = NULL; int ret; /* Only alloc (or use chip_info) on first setup */ chip = spi_get_ctldata(spi); if (chip == NULL) { struct bfin5xx_spi_chip *chip_info; chip = first = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; /* platform chip_info isn't required */ chip_info = spi->controller_data; if (chip_info) { /* * DITFS and TDTYPE are only thing we don't set, but * they probably shouldn't be changed by people. */ if (chip_info->ctl_reg || chip_info->enable_dma) { ret = -EINVAL; dev_err(&spi->dev, "don't set ctl_reg/enable_dma fields\n"); goto error; } chip->cs_chg_udelay = chip_info->cs_chg_udelay; chip->idle_tx_val = chip_info->idle_tx_val; } } /* translate common spi framework into our register * following configure contents are same for tx and rx. */ if (spi->mode & SPI_CPHA) chip->ctl_reg &= ~TCKFE; else chip->ctl_reg |= TCKFE; if (spi->mode & SPI_LSB_FIRST) chip->ctl_reg |= TLSBIT; else chip->ctl_reg &= ~TLSBIT; /* Sport in master mode */ chip->ctl_reg |= ITCLK | ITFS | TFSR | LATFS | LTFS; chip->baud = bfin_sport_hz_to_spi_baud(spi->max_speed_hz); chip->cs_gpio = spi->chip_select; ret = gpio_request(chip->cs_gpio, spi->modalias); if (ret) goto error; dev_dbg(&spi->dev, "setup spi chip %s, width is %d\n", spi->modalias, spi->bits_per_word); dev_dbg(&spi->dev, "ctl_reg is 0x%x, GPIO is %i\n", chip->ctl_reg, spi->chip_select); spi_set_ctldata(spi, chip); bfin_sport_spi_cs_deactive(chip); return ret; error: kfree(first); return ret; } /* * callback for spi framework. * clean driver specific data */ static void bfin_sport_spi_cleanup(struct spi_device *spi) { struct bfin_sport_spi_slave_data *chip = spi_get_ctldata(spi); if (!chip) return; gpio_free(chip->cs_gpio); kfree(chip); } static int bfin_sport_spi_init_queue(struct bfin_sport_spi_master_data *drv_data) { INIT_LIST_HEAD(&drv_data->queue); spin_lock_init(&drv_data->lock); drv_data->run = false; drv_data->busy = 0; /* init transfer tasklet */ tasklet_init(&drv_data->pump_transfers, bfin_sport_spi_pump_transfers, (unsigned long)drv_data); /* init messages workqueue */ INIT_WORK(&drv_data->pump_messages, bfin_sport_spi_pump_messages); drv_data->workqueue = create_singlethread_workqueue(dev_name(drv_data->master->dev.parent)); if (drv_data->workqueue == NULL) return -EBUSY; return 0; } static int bfin_sport_spi_start_queue(struct bfin_sport_spi_master_data *drv_data) { unsigned long flags; spin_lock_irqsave(&drv_data->lock, flags); if (drv_data->run || drv_data->busy) { spin_unlock_irqrestore(&drv_data->lock, flags); return -EBUSY; } drv_data->run = true; drv_data->cur_msg = NULL; drv_data->cur_transfer = NULL; drv_data->cur_chip = NULL; spin_unlock_irqrestore(&drv_data->lock, flags); queue_work(drv_data->workqueue, &drv_data->pump_messages); return 0; } static inline int bfin_sport_spi_stop_queue(struct bfin_sport_spi_master_data *drv_data) { unsigned long flags; unsigned limit = 500; int status = 0; spin_lock_irqsave(&drv_data->lock, flags); /* * This is a bit lame, but is optimized for the common execution path. * A wait_queue on the drv_data->busy could be used, but then the common * execution path (pump_messages) would be required to call wake_up or * friends on every SPI message. Do this instead */ drv_data->run = false; while (!list_empty(&drv_data->queue) && drv_data->busy && limit--) { spin_unlock_irqrestore(&drv_data->lock, flags); msleep(10); spin_lock_irqsave(&drv_data->lock, flags); } if (!list_empty(&drv_data->queue) || drv_data->busy) status = -EBUSY; spin_unlock_irqrestore(&drv_data->lock, flags); return status; } static inline int bfin_sport_spi_destroy_queue(struct bfin_sport_spi_master_data *drv_data) { int status; status = bfin_sport_spi_stop_queue(drv_data); if (status) return status; destroy_workqueue(drv_data->workqueue); return 0; } static int bfin_sport_spi_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct bfin5xx_spi_master *platform_info; struct spi_master *master; struct resource *res, *ires; struct bfin_sport_spi_master_data *drv_data; int status; platform_info = dev_get_platdata(dev); /* Allocate master with space for drv_data */ master = spi_alloc_master(dev, sizeof(*master) + 16); if (!master) { dev_err(dev, "cannot alloc spi_master\n"); return -ENOMEM; } drv_data = spi_master_get_devdata(master); drv_data->master = master; drv_data->dev = dev; drv_data->pin_req = platform_info->pin_req; master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST; master->bits_per_word_mask = SPI_BPW_MASK(8) | SPI_BPW_MASK(16); master->bus_num = pdev->id; master->num_chipselect = platform_info->num_chipselect; master->cleanup = bfin_sport_spi_cleanup; master->setup = bfin_sport_spi_setup; master->transfer = bfin_sport_spi_transfer; /* Find and map our resources */ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (res == NULL) { dev_err(dev, "cannot get IORESOURCE_MEM\n"); status = -ENOENT; goto out_error_get_res; } drv_data->regs = ioremap(res->start, resource_size(res)); if (drv_data->regs == NULL) { dev_err(dev, "cannot map registers\n"); status = -ENXIO; goto out_error_ioremap; } ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!ires) { dev_err(dev, "cannot get IORESOURCE_IRQ\n"); status = -ENODEV; goto out_error_get_ires; } drv_data->err_irq = ires->start; /* Initial and start queue */ status = bfin_sport_spi_init_queue(drv_data); if (status) { dev_err(dev, "problem initializing queue\n"); goto out_error_queue_alloc; } status = bfin_sport_spi_start_queue(drv_data); if (status) { dev_err(dev, "problem starting queue\n"); goto out_error_queue_alloc; } status = request_irq(drv_data->err_irq, sport_err_handler, 0, "sport_spi_err", drv_data); if (status) { dev_err(dev, "unable to request sport err irq\n"); goto out_error_irq; } status = peripheral_request_list(drv_data->pin_req, DRV_NAME); if (status) { dev_err(dev, "requesting peripherals failed\n"); goto out_error_peripheral; } /* Register with the SPI framework */ platform_set_drvdata(pdev, drv_data); status = spi_register_master(master); if (status) { dev_err(dev, "problem registering spi master\n"); goto out_error_master; } dev_info(dev, "%s, regs_base@%p\n", DRV_DESC, drv_data->regs); return 0; out_error_master: peripheral_free_list(drv_data->pin_req); out_error_peripheral: free_irq(drv_data->err_irq, drv_data); out_error_irq: out_error_queue_alloc: bfin_sport_spi_destroy_queue(drv_data); out_error_get_ires: iounmap(drv_data->regs); out_error_ioremap: out_error_get_res: spi_master_put(master); return status; } /* stop hardware and remove the driver */ static int bfin_sport_spi_remove(struct platform_device *pdev) { struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev); int status = 0; if (!drv_data) return 0; /* Remove the queue */ status = bfin_sport_spi_destroy_queue(drv_data); if (status) return status; /* Disable the SSP at the peripheral and SOC level */ bfin_sport_spi_disable(drv_data); /* Disconnect from the SPI framework */ spi_unregister_master(drv_data->master); peripheral_free_list(drv_data->pin_req); return 0; } #ifdef CONFIG_PM_SLEEP static int bfin_sport_spi_suspend(struct device *dev) { struct bfin_sport_spi_master_data *drv_data = dev_get_drvdata(dev); int status; status = bfin_sport_spi_stop_queue(drv_data); if (status) return status; /* stop hardware */ bfin_sport_spi_disable(drv_data); return status; } static int bfin_sport_spi_resume(struct device *dev) { struct bfin_sport_spi_master_data *drv_data = dev_get_drvdata(dev); int status; /* Enable the SPI interface */ bfin_sport_spi_enable(drv_data); /* Start the queue running */ status = bfin_sport_spi_start_queue(drv_data); if (status) dev_err(drv_data->dev, "problem resuming queue\n"); return status; } static SIMPLE_DEV_PM_OPS(bfin_sport_spi_pm_ops, bfin_sport_spi_suspend, bfin_sport_spi_resume); #define BFIN_SPORT_SPI_PM_OPS (&bfin_sport_spi_pm_ops) #else #define BFIN_SPORT_SPI_PM_OPS NULL #endif static struct platform_driver bfin_sport_spi_driver = { .driver = { .name = DRV_NAME, .owner = THIS_MODULE, .pm = BFIN_SPORT_SPI_PM_OPS, }, .probe = bfin_sport_spi_probe, .remove = bfin_sport_spi_remove, }; module_platform_driver(bfin_sport_spi_driver);
gpl-2.0
y10g/elini_kernel
drivers/usb/core/devio.c
280
48518
/*****************************************************************************/ /* * devio.c -- User space communication with USB devices. * * Copyright (C) 1999-2000 Thomas Sailer (sailer@ife.ee.ethz.ch) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * This file implements the usbfs/x/y files, where * x is the bus number and y the device number. * * It allows user space programs/"drivers" to communicate directly * with USB devices without intervening kernel driver. * * Revision history * 22.12.1999 0.1 Initial release (split from proc_usb.c) * 04.01.2000 0.2 Turned into its own filesystem * 30.09.2005 0.3 Fix user-triggerable oops in async URB delivery * (CAN-2005-3055) */ /*****************************************************************************/ #include <linux/fs.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/smp_lock.h> #include <linux/signal.h> #include <linux/poll.h> #include <linux/module.h> #include <linux/usb.h> #include <linux/usbdevice_fs.h> #include <linux/cdev.h> #include <linux/notifier.h> #include <linux/security.h> #include <asm/uaccess.h> #include <asm/byteorder.h> #include <linux/moduleparam.h> #include "hcd.h" /* for usbcore internals */ #include "usb.h" #include "hub.h" #define USB_MAXBUS 64 #define USB_DEVICE_MAX USB_MAXBUS * 128 /* Mutual exclusion for removal, open, and release */ DEFINE_MUTEX(usbfs_mutex); struct dev_state { struct list_head list; /* state list */ struct usb_device *dev; struct file *file; spinlock_t lock; /* protects the async urb lists */ struct list_head async_pending; struct list_head async_completed; wait_queue_head_t wait; /* wake up if a request completed */ unsigned int discsignr; struct pid *disc_pid; uid_t disc_uid, disc_euid; void __user *disccontext; unsigned long ifclaimed; u32 secid; u32 disabled_bulk_eps; }; struct async { struct list_head asynclist; struct dev_state *ps; struct pid *pid; uid_t uid, euid; unsigned int signr; unsigned int ifnum; void __user *userbuffer; void __user *userurb; struct urb *urb; int status; u32 secid; u8 bulk_addr; u8 bulk_status; }; static int usbfs_snoop; module_param(usbfs_snoop, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(usbfs_snoop, "true to log all usbfs traffic"); #define snoop(dev, format, arg...) \ do { \ if (usbfs_snoop) \ dev_info(dev , format , ## arg); \ } while (0) enum snoop_when { SUBMIT, COMPLETE }; #define USB_DEVICE_DEV MKDEV(USB_DEVICE_MAJOR, 0) #define MAX_USBFS_BUFFER_SIZE 16384 static int connected(struct dev_state *ps) { return (!list_empty(&ps->list) && ps->dev->state != USB_STATE_NOTATTACHED); } static loff_t usbdev_lseek(struct file *file, loff_t offset, int orig) { loff_t ret; lock_kernel(); switch (orig) { case 0: file->f_pos = offset; ret = file->f_pos; break; case 1: file->f_pos += offset; ret = file->f_pos; break; case 2: default: ret = -EINVAL; } unlock_kernel(); return ret; } static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; ssize_t ret = 0; unsigned len; loff_t pos; int i; pos = *ppos; usb_lock_device(dev); if (!connected(ps)) { ret = -ENODEV; goto err; } else if (pos < 0) { ret = -EINVAL; goto err; } if (pos < sizeof(struct usb_device_descriptor)) { /* 18 bytes - fits on the stack */ struct usb_device_descriptor temp_desc; memcpy(&temp_desc, &dev->descriptor, sizeof(dev->descriptor)); le16_to_cpus(&temp_desc.bcdUSB); le16_to_cpus(&temp_desc.idVendor); le16_to_cpus(&temp_desc.idProduct); le16_to_cpus(&temp_desc.bcdDevice); len = sizeof(struct usb_device_descriptor) - pos; if (len > nbytes) len = nbytes; if (copy_to_user(buf, ((char *)&temp_desc) + pos, len)) { ret = -EFAULT; goto err; } *ppos += len; buf += len; nbytes -= len; ret += len; } pos = sizeof(struct usb_device_descriptor); for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) { struct usb_config_descriptor *config = (struct usb_config_descriptor *)dev->rawdescriptors[i]; unsigned int length = le16_to_cpu(config->wTotalLength); if (*ppos < pos + length) { /* The descriptor may claim to be longer than it * really is. Here is the actual allocated length. */ unsigned alloclen = le16_to_cpu(dev->config[i].desc.wTotalLength); len = length - (*ppos - pos); if (len > nbytes) len = nbytes; /* Simply don't write (skip over) unallocated parts */ if (alloclen > (*ppos - pos)) { alloclen -= (*ppos - pos); if (copy_to_user(buf, dev->rawdescriptors[i] + (*ppos - pos), min(len, alloclen))) { ret = -EFAULT; goto err; } } *ppos += len; buf += len; nbytes -= len; ret += len; } pos += length; } err: usb_unlock_device(dev); return ret; } /* * async list handling */ static struct async *alloc_async(unsigned int numisoframes) { struct async *as; as = kzalloc(sizeof(struct async), GFP_KERNEL); if (!as) return NULL; as->urb = usb_alloc_urb(numisoframes, GFP_KERNEL); if (!as->urb) { kfree(as); return NULL; } return as; } static void free_async(struct async *as) { put_pid(as->pid); kfree(as->urb->transfer_buffer); kfree(as->urb->setup_packet); usb_free_urb(as->urb); kfree(as); } static void async_newpending(struct async *as) { struct dev_state *ps = as->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); list_add_tail(&as->asynclist, &ps->async_pending); spin_unlock_irqrestore(&ps->lock, flags); } static void async_removepending(struct async *as) { struct dev_state *ps = as->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); list_del_init(&as->asynclist); spin_unlock_irqrestore(&ps->lock, flags); } static struct async *async_getcompleted(struct dev_state *ps) { unsigned long flags; struct async *as = NULL; spin_lock_irqsave(&ps->lock, flags); if (!list_empty(&ps->async_completed)) { as = list_entry(ps->async_completed.next, struct async, asynclist); list_del_init(&as->asynclist); } spin_unlock_irqrestore(&ps->lock, flags); return as; } static struct async *async_getpending(struct dev_state *ps, void __user *userurb) { unsigned long flags; struct async *as; spin_lock_irqsave(&ps->lock, flags); list_for_each_entry(as, &ps->async_pending, asynclist) if (as->userurb == userurb) { list_del_init(&as->asynclist); spin_unlock_irqrestore(&ps->lock, flags); return as; } spin_unlock_irqrestore(&ps->lock, flags); return NULL; } static void snoop_urb(struct usb_device *udev, void __user *userurb, int pipe, unsigned length, int timeout_or_status, enum snoop_when when) { static const char *types[] = {"isoc", "int", "ctrl", "bulk"}; static const char *dirs[] = {"out", "in"}; int ep; const char *t, *d; if (!usbfs_snoop) return; ep = usb_pipeendpoint(pipe); t = types[usb_pipetype(pipe)]; d = dirs[!!usb_pipein(pipe)]; if (userurb) { /* Async */ if (when == SUBMIT) dev_info(&udev->dev, "userurb %p, ep%d %s-%s, " "length %u\n", userurb, ep, t, d, length); else dev_info(&udev->dev, "userurb %p, ep%d %s-%s, " "actual_length %u status %d\n", userurb, ep, t, d, length, timeout_or_status); } else { if (when == SUBMIT) dev_info(&udev->dev, "ep%d %s-%s, length %u, " "timeout %d\n", ep, t, d, length, timeout_or_status); else dev_info(&udev->dev, "ep%d %s-%s, actual_length %u, " "status %d\n", ep, t, d, length, timeout_or_status); } } #define AS_CONTINUATION 1 #define AS_UNLINK 2 static void cancel_bulk_urbs(struct dev_state *ps, unsigned bulk_addr) __releases(ps->lock) __acquires(ps->lock) { struct async *as; /* Mark all the pending URBs that match bulk_addr, up to but not * including the first one without AS_CONTINUATION. If such an * URB is encountered then a new transfer has already started so * the endpoint doesn't need to be disabled; otherwise it does. */ list_for_each_entry(as, &ps->async_pending, asynclist) { if (as->bulk_addr == bulk_addr) { if (as->bulk_status != AS_CONTINUATION) goto rescan; as->bulk_status = AS_UNLINK; as->bulk_addr = 0; } } ps->disabled_bulk_eps |= (1 << bulk_addr); /* Now carefully unlink all the marked pending URBs */ rescan: list_for_each_entry(as, &ps->async_pending, asynclist) { if (as->bulk_status == AS_UNLINK) { as->bulk_status = 0; /* Only once */ spin_unlock(&ps->lock); /* Allow completions */ usb_unlink_urb(as->urb); spin_lock(&ps->lock); goto rescan; } } } static void async_completed(struct urb *urb) { struct async *as = urb->context; struct dev_state *ps = as->ps; struct siginfo sinfo; struct pid *pid = NULL; uid_t uid = 0; uid_t euid = 0; u32 secid = 0; int signr; spin_lock(&ps->lock); list_move_tail(&as->asynclist, &ps->async_completed); as->status = urb->status; signr = as->signr; if (signr) { sinfo.si_signo = as->signr; sinfo.si_errno = as->status; sinfo.si_code = SI_ASYNCIO; sinfo.si_addr = as->userurb; pid = as->pid; uid = as->uid; euid = as->euid; secid = as->secid; } snoop(&urb->dev->dev, "urb complete\n"); snoop_urb(urb->dev, as->userurb, urb->pipe, urb->actual_length, as->status, COMPLETE); if (as->status < 0 && as->bulk_addr && as->status != -ECONNRESET && as->status != -ENOENT) cancel_bulk_urbs(ps, as->bulk_addr); spin_unlock(&ps->lock); if (signr) kill_pid_info_as_uid(sinfo.si_signo, &sinfo, pid, uid, euid, secid); wake_up(&ps->wait); } static void destroy_async(struct dev_state *ps, struct list_head *list) { struct async *as; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); while (!list_empty(list)) { as = list_entry(list->next, struct async, asynclist); list_del_init(&as->asynclist); /* drop the spinlock so the completion handler can run */ spin_unlock_irqrestore(&ps->lock, flags); usb_kill_urb(as->urb); spin_lock_irqsave(&ps->lock, flags); } spin_unlock_irqrestore(&ps->lock, flags); } static void destroy_async_on_interface(struct dev_state *ps, unsigned int ifnum) { struct list_head *p, *q, hitlist; unsigned long flags; INIT_LIST_HEAD(&hitlist); spin_lock_irqsave(&ps->lock, flags); list_for_each_safe(p, q, &ps->async_pending) if (ifnum == list_entry(p, struct async, asynclist)->ifnum) list_move_tail(p, &hitlist); spin_unlock_irqrestore(&ps->lock, flags); destroy_async(ps, &hitlist); } static void destroy_all_async(struct dev_state *ps) { destroy_async(ps, &ps->async_pending); } /* * interface claims are made only at the request of user level code, * which can also release them (explicitly or by closing files). * they're also undone when devices disconnect. */ static int driver_probe(struct usb_interface *intf, const struct usb_device_id *id) { return -ENODEV; } static void driver_disconnect(struct usb_interface *intf) { struct dev_state *ps = usb_get_intfdata(intf); unsigned int ifnum = intf->altsetting->desc.bInterfaceNumber; if (!ps) return; /* NOTE: this relies on usbcore having canceled and completed * all pending I/O requests; 2.6 does that. */ if (likely(ifnum < 8*sizeof(ps->ifclaimed))) clear_bit(ifnum, &ps->ifclaimed); else dev_warn(&intf->dev, "interface number %u out of range\n", ifnum); usb_set_intfdata(intf, NULL); /* force async requests to complete */ destroy_async_on_interface(ps, ifnum); } /* The following routines are merely placeholders. There is no way * to inform a user task about suspend or resumes. */ static int driver_suspend(struct usb_interface *intf, pm_message_t msg) { return 0; } static int driver_resume(struct usb_interface *intf) { return 0; } struct usb_driver usbfs_driver = { .name = "usbfs", .probe = driver_probe, .disconnect = driver_disconnect, .suspend = driver_suspend, .resume = driver_resume, }; static int claimintf(struct dev_state *ps, unsigned int ifnum) { struct usb_device *dev = ps->dev; struct usb_interface *intf; int err; if (ifnum >= 8*sizeof(ps->ifclaimed)) return -EINVAL; /* already claimed */ if (test_bit(ifnum, &ps->ifclaimed)) return 0; intf = usb_ifnum_to_if(dev, ifnum); if (!intf) err = -ENOENT; else err = usb_driver_claim_interface(&usbfs_driver, intf, ps); if (err == 0) set_bit(ifnum, &ps->ifclaimed); return err; } static int releaseintf(struct dev_state *ps, unsigned int ifnum) { struct usb_device *dev; struct usb_interface *intf; int err; err = -EINVAL; if (ifnum >= 8*sizeof(ps->ifclaimed)) return err; dev = ps->dev; intf = usb_ifnum_to_if(dev, ifnum); if (!intf) err = -ENOENT; else if (test_and_clear_bit(ifnum, &ps->ifclaimed)) { usb_driver_release_interface(&usbfs_driver, intf); err = 0; } return err; } static int checkintf(struct dev_state *ps, unsigned int ifnum) { if (ps->dev->state != USB_STATE_CONFIGURED) return -EHOSTUNREACH; if (ifnum >= 8*sizeof(ps->ifclaimed)) return -EINVAL; if (test_bit(ifnum, &ps->ifclaimed)) return 0; /* if not yet claimed, claim it for the driver */ dev_warn(&ps->dev->dev, "usbfs: process %d (%s) did not claim " "interface %u before use\n", task_pid_nr(current), current->comm, ifnum); return claimintf(ps, ifnum); } static int findintfep(struct usb_device *dev, unsigned int ep) { unsigned int i, j, e; struct usb_interface *intf; struct usb_host_interface *alts; struct usb_endpoint_descriptor *endpt; if (ep & ~(USB_DIR_IN|0xf)) return -EINVAL; if (!dev->actconfig) return -ESRCH; for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { intf = dev->actconfig->interface[i]; for (j = 0; j < intf->num_altsetting; j++) { alts = &intf->altsetting[j]; for (e = 0; e < alts->desc.bNumEndpoints; e++) { endpt = &alts->endpoint[e].desc; if (endpt->bEndpointAddress == ep) return alts->desc.bInterfaceNumber; } } } return -ENOENT; } static int check_ctrlrecip(struct dev_state *ps, unsigned int requesttype, unsigned int index) { int ret = 0; if (ps->dev->state != USB_STATE_UNAUTHENTICATED && ps->dev->state != USB_STATE_ADDRESS && ps->dev->state != USB_STATE_CONFIGURED) return -EHOSTUNREACH; if (USB_TYPE_VENDOR == (USB_TYPE_MASK & requesttype)) return 0; index &= 0xff; switch (requesttype & USB_RECIP_MASK) { case USB_RECIP_ENDPOINT: ret = findintfep(ps->dev, index); if (ret >= 0) ret = checkintf(ps, ret); break; case USB_RECIP_INTERFACE: ret = checkintf(ps, index); break; } return ret; } static int match_devt(struct device *dev, void *data) { return dev->devt == (dev_t) (unsigned long) data; } static struct usb_device *usbdev_lookup_by_devt(dev_t devt) { struct device *dev; dev = bus_find_device(&usb_bus_type, NULL, (void *) (unsigned long) devt, match_devt); if (!dev) return NULL; return container_of(dev, struct usb_device, dev); } /* * file operations */ static int usbdev_open(struct inode *inode, struct file *file) { struct usb_device *dev = NULL; struct dev_state *ps; const struct cred *cred = current_cred(); int ret; lock_kernel(); /* Protect against simultaneous removal or release */ mutex_lock(&usbfs_mutex); ret = -ENOMEM; ps = kmalloc(sizeof(struct dev_state), GFP_KERNEL); if (!ps) goto out; ret = -ENODEV; /* usbdev device-node */ if (imajor(inode) == USB_DEVICE_MAJOR) dev = usbdev_lookup_by_devt(inode->i_rdev); #ifdef CONFIG_USB_DEVICEFS /* procfs file */ if (!dev) { dev = inode->i_private; if (dev && dev->usbfs_dentry && dev->usbfs_dentry->d_inode == inode) usb_get_dev(dev); else dev = NULL; } #endif if (!dev || dev->state == USB_STATE_NOTATTACHED) goto out; ret = usb_autoresume_device(dev); if (ret) goto out; ret = 0; ps->dev = dev; ps->file = file; spin_lock_init(&ps->lock); INIT_LIST_HEAD(&ps->list); INIT_LIST_HEAD(&ps->async_pending); INIT_LIST_HEAD(&ps->async_completed); init_waitqueue_head(&ps->wait); ps->discsignr = 0; ps->disc_pid = get_pid(task_pid(current)); ps->disc_uid = cred->uid; ps->disc_euid = cred->euid; ps->disccontext = NULL; ps->ifclaimed = 0; security_task_getsecid(current, &ps->secid); smp_wmb(); list_add_tail(&ps->list, &dev->filelist); file->private_data = ps; snoop(&dev->dev, "opened by process %d: %s\n", task_pid_nr(current), current->comm); out: if (ret) { kfree(ps); usb_put_dev(dev); } mutex_unlock(&usbfs_mutex); unlock_kernel(); return ret; } static int usbdev_release(struct inode *inode, struct file *file) { struct dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; unsigned int ifnum; struct async *as; usb_lock_device(dev); usb_hub_release_all_ports(dev, ps); /* Protect against simultaneous open */ mutex_lock(&usbfs_mutex); list_del_init(&ps->list); mutex_unlock(&usbfs_mutex); for (ifnum = 0; ps->ifclaimed && ifnum < 8*sizeof(ps->ifclaimed); ifnum++) { if (test_bit(ifnum, &ps->ifclaimed)) releaseintf(ps, ifnum); } destroy_all_async(ps); usb_autosuspend_device(dev); usb_unlock_device(dev); usb_put_dev(dev); put_pid(ps->disc_pid); as = async_getcompleted(ps); while (as) { free_async(as); as = async_getcompleted(ps); } kfree(ps); return 0; } static int proc_control(struct dev_state *ps, void __user *arg) { struct usb_device *dev = ps->dev; struct usbdevfs_ctrltransfer ctrl; unsigned int tmo; unsigned char *tbuf; unsigned wLength; int i, pipe, ret; if (copy_from_user(&ctrl, arg, sizeof(ctrl))) return -EFAULT; ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.wIndex); if (ret) return ret; wLength = ctrl.wLength; /* To suppress 64k PAGE_SIZE warning */ if (wLength > PAGE_SIZE) return -EINVAL; tbuf = (unsigned char *)__get_free_page(GFP_KERNEL); if (!tbuf) return -ENOMEM; tmo = ctrl.timeout; if (ctrl.bRequestType & 0x80) { if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data, ctrl.wLength)) { free_page((unsigned long)tbuf); return -EINVAL; } pipe = usb_rcvctrlpipe(dev, 0); snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT); usb_unlock_device(dev); i = usb_control_msg(dev, pipe, ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE); if ((i > 0) && ctrl.wLength) { if (copy_to_user(ctrl.data, tbuf, i)) { free_page((unsigned long)tbuf); return -EFAULT; } } } else { if (ctrl.wLength) { if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) { free_page((unsigned long)tbuf); return -EFAULT; } } pipe = usb_sndctrlpipe(dev, 0); snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT); usb_unlock_device(dev); i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE); } free_page((unsigned long)tbuf); if (i < 0 && i != -EPIPE) { dev_printk(KERN_DEBUG, &dev->dev, "usbfs: USBDEVFS_CONTROL " "failed cmd %s rqt %u rq %u len %u ret %d\n", current->comm, ctrl.bRequestType, ctrl.bRequest, ctrl.wLength, i); } return i; } static int proc_bulk(struct dev_state *ps, void __user *arg) { struct usb_device *dev = ps->dev; struct usbdevfs_bulktransfer bulk; unsigned int tmo, len1, pipe; int len2; unsigned char *tbuf; int i, ret; if (copy_from_user(&bulk, arg, sizeof(bulk))) return -EFAULT; ret = findintfep(ps->dev, bulk.ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; if (bulk.ep & USB_DIR_IN) pipe = usb_rcvbulkpipe(dev, bulk.ep & 0x7f); else pipe = usb_sndbulkpipe(dev, bulk.ep & 0x7f); if (!usb_maxpacket(dev, pipe, !(bulk.ep & USB_DIR_IN))) return -EINVAL; len1 = bulk.len; if (len1 > MAX_USBFS_BUFFER_SIZE) return -EINVAL; if (!(tbuf = kmalloc(len1, GFP_KERNEL))) return -ENOMEM; tmo = bulk.timeout; if (bulk.ep & 0x80) { if (len1 && !access_ok(VERIFY_WRITE, bulk.data, len1)) { kfree(tbuf); return -EINVAL; } snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT); usb_unlock_device(dev); i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, len2, i, COMPLETE); if (!i && len2) { if (copy_to_user(bulk.data, tbuf, len2)) { kfree(tbuf); return -EFAULT; } } } else { if (len1) { if (copy_from_user(tbuf, bulk.data, len1)) { kfree(tbuf); return -EFAULT; } } snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT); usb_unlock_device(dev); i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, len2, i, COMPLETE); } kfree(tbuf); if (i < 0) return i; return len2; } static int proc_resetep(struct dev_state *ps, void __user *arg) { unsigned int ep; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; usb_reset_endpoint(ps->dev, ep); return 0; } static int proc_clearhalt(struct dev_state *ps, void __user *arg) { unsigned int ep; int pipe; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; if (ep & USB_DIR_IN) pipe = usb_rcvbulkpipe(ps->dev, ep & 0x7f); else pipe = usb_sndbulkpipe(ps->dev, ep & 0x7f); return usb_clear_halt(ps->dev, pipe); } static int proc_getdriver(struct dev_state *ps, void __user *arg) { struct usbdevfs_getdriver gd; struct usb_interface *intf; int ret; if (copy_from_user(&gd, arg, sizeof(gd))) return -EFAULT; intf = usb_ifnum_to_if(ps->dev, gd.interface); if (!intf || !intf->dev.driver) ret = -ENODATA; else { strncpy(gd.driver, intf->dev.driver->name, sizeof(gd.driver)); ret = (copy_to_user(arg, &gd, sizeof(gd)) ? -EFAULT : 0); } return ret; } static int proc_connectinfo(struct dev_state *ps, void __user *arg) { struct usbdevfs_connectinfo ci; ci.devnum = ps->dev->devnum; ci.slow = ps->dev->speed == USB_SPEED_LOW; if (copy_to_user(arg, &ci, sizeof(ci))) return -EFAULT; return 0; } static int proc_resetdevice(struct dev_state *ps) { return usb_reset_device(ps->dev); } static int proc_setintf(struct dev_state *ps, void __user *arg) { struct usbdevfs_setinterface setintf; int ret; if (copy_from_user(&setintf, arg, sizeof(setintf))) return -EFAULT; if ((ret = checkintf(ps, setintf.interface))) return ret; return usb_set_interface(ps->dev, setintf.interface, setintf.altsetting); } static int proc_setconfig(struct dev_state *ps, void __user *arg) { int u; int status = 0; struct usb_host_config *actconfig; if (get_user(u, (int __user *)arg)) return -EFAULT; actconfig = ps->dev->actconfig; /* Don't touch the device if any interfaces are claimed. * It could interfere with other drivers' operations, and if * an interface is claimed by usbfs it could easily deadlock. */ if (actconfig) { int i; for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) { if (usb_interface_claimed(actconfig->interface[i])) { dev_warn(&ps->dev->dev, "usbfs: interface %d claimed by %s " "while '%s' sets config #%d\n", actconfig->interface[i] ->cur_altsetting ->desc.bInterfaceNumber, actconfig->interface[i] ->dev.driver->name, current->comm, u); status = -EBUSY; break; } } } /* SET_CONFIGURATION is often abused as a "cheap" driver reset, * so avoid usb_set_configuration()'s kick to sysfs */ if (status == 0) { if (actconfig && actconfig->desc.bConfigurationValue == u) status = usb_reset_configuration(ps->dev); else status = usb_set_configuration(ps->dev, u); } return status; } static int proc_do_submiturb(struct dev_state *ps, struct usbdevfs_urb *uurb, struct usbdevfs_iso_packet_desc __user *iso_frame_desc, void __user *arg) { struct usbdevfs_iso_packet_desc *isopkt = NULL; struct usb_host_endpoint *ep; struct async *as; struct usb_ctrlrequest *dr = NULL; const struct cred *cred = current_cred(); unsigned int u, totlen, isofrmlen; int ret, ifnum = -1; int is_in; if (uurb->flags & ~(USBDEVFS_URB_ISO_ASAP | USBDEVFS_URB_SHORT_NOT_OK | USBDEVFS_URB_BULK_CONTINUATION | USBDEVFS_URB_NO_FSBR | USBDEVFS_URB_ZERO_PACKET | USBDEVFS_URB_NO_INTERRUPT)) return -EINVAL; if (uurb->buffer_length > 0 && !uurb->buffer) return -EINVAL; if (!(uurb->type == USBDEVFS_URB_TYPE_CONTROL && (uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) == 0)) { ifnum = findintfep(ps->dev, uurb->endpoint); if (ifnum < 0) return ifnum; ret = checkintf(ps, ifnum); if (ret) return ret; } if ((uurb->endpoint & USB_ENDPOINT_DIR_MASK) != 0) { is_in = 1; ep = ps->dev->ep_in[uurb->endpoint & USB_ENDPOINT_NUMBER_MASK]; } else { is_in = 0; ep = ps->dev->ep_out[uurb->endpoint & USB_ENDPOINT_NUMBER_MASK]; } if (!ep) return -ENOENT; switch(uurb->type) { case USBDEVFS_URB_TYPE_CONTROL: if (!usb_endpoint_xfer_control(&ep->desc)) return -EINVAL; /* min 8 byte setup packet, * max 8 byte setup plus an arbitrary data stage */ if (uurb->buffer_length < 8 || uurb->buffer_length > (8 + MAX_USBFS_BUFFER_SIZE)) return -EINVAL; dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL); if (!dr) return -ENOMEM; if (copy_from_user(dr, uurb->buffer, 8)) { kfree(dr); return -EFAULT; } if (uurb->buffer_length < (le16_to_cpup(&dr->wLength) + 8)) { kfree(dr); return -EINVAL; } ret = check_ctrlrecip(ps, dr->bRequestType, le16_to_cpup(&dr->wIndex)); if (ret) { kfree(dr); return ret; } uurb->number_of_packets = 0; uurb->buffer_length = le16_to_cpup(&dr->wLength); uurb->buffer += 8; if ((dr->bRequestType & USB_DIR_IN) && uurb->buffer_length) { is_in = 1; uurb->endpoint |= USB_DIR_IN; } else { is_in = 0; uurb->endpoint &= ~USB_DIR_IN; } break; case USBDEVFS_URB_TYPE_BULK: switch (usb_endpoint_type(&ep->desc)) { case USB_ENDPOINT_XFER_CONTROL: case USB_ENDPOINT_XFER_ISOC: return -EINVAL; /* allow single-shot interrupt transfers, at bogus rates */ } uurb->number_of_packets = 0; if (uurb->buffer_length > MAX_USBFS_BUFFER_SIZE) return -EINVAL; break; case USBDEVFS_URB_TYPE_ISO: /* arbitrary limit */ if (uurb->number_of_packets < 1 || uurb->number_of_packets > 128) return -EINVAL; if (!usb_endpoint_xfer_isoc(&ep->desc)) return -EINVAL; isofrmlen = sizeof(struct usbdevfs_iso_packet_desc) * uurb->number_of_packets; if (!(isopkt = kmalloc(isofrmlen, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(isopkt, iso_frame_desc, isofrmlen)) { kfree(isopkt); return -EFAULT; } for (totlen = u = 0; u < uurb->number_of_packets; u++) { /* arbitrary limit, * sufficient for USB 2.0 high-bandwidth iso */ if (isopkt[u].length > 8192) { kfree(isopkt); return -EINVAL; } totlen += isopkt[u].length; } /* 3072 * 64 microframes */ if (totlen > 196608) { kfree(isopkt); return -EINVAL; } uurb->buffer_length = totlen; break; case USBDEVFS_URB_TYPE_INTERRUPT: uurb->number_of_packets = 0; if (!usb_endpoint_xfer_int(&ep->desc)) return -EINVAL; if (uurb->buffer_length > MAX_USBFS_BUFFER_SIZE) return -EINVAL; break; default: return -EINVAL; } if (uurb->buffer_length > 0 && !access_ok(is_in ? VERIFY_WRITE : VERIFY_READ, uurb->buffer, uurb->buffer_length)) { kfree(isopkt); kfree(dr); return -EFAULT; } as = alloc_async(uurb->number_of_packets); if (!as) { kfree(isopkt); kfree(dr); return -ENOMEM; } if (uurb->buffer_length > 0) { as->urb->transfer_buffer = kmalloc(uurb->buffer_length, GFP_KERNEL); if (!as->urb->transfer_buffer) { kfree(isopkt); kfree(dr); free_async(as); return -ENOMEM; } } as->urb->dev = ps->dev; as->urb->pipe = (uurb->type << 30) | __create_pipe(ps->dev, uurb->endpoint & 0xf) | (uurb->endpoint & USB_DIR_IN); /* This tedious sequence is necessary because the URB_* flags * are internal to the kernel and subject to change, whereas * the USBDEVFS_URB_* flags are a user API and must not be changed. */ u = (is_in ? URB_DIR_IN : URB_DIR_OUT); if (uurb->flags & USBDEVFS_URB_ISO_ASAP) u |= URB_ISO_ASAP; if (uurb->flags & USBDEVFS_URB_SHORT_NOT_OK) u |= URB_SHORT_NOT_OK; if (uurb->flags & USBDEVFS_URB_NO_FSBR) u |= URB_NO_FSBR; if (uurb->flags & USBDEVFS_URB_ZERO_PACKET) u |= URB_ZERO_PACKET; if (uurb->flags & USBDEVFS_URB_NO_INTERRUPT) u |= URB_NO_INTERRUPT; as->urb->transfer_flags = u; as->urb->transfer_buffer_length = uurb->buffer_length; as->urb->setup_packet = (unsigned char *)dr; as->urb->start_frame = uurb->start_frame; as->urb->number_of_packets = uurb->number_of_packets; if (uurb->type == USBDEVFS_URB_TYPE_ISO || ps->dev->speed == USB_SPEED_HIGH) as->urb->interval = 1 << min(15, ep->desc.bInterval - 1); else as->urb->interval = ep->desc.bInterval; as->urb->context = as; as->urb->complete = async_completed; for (totlen = u = 0; u < uurb->number_of_packets; u++) { as->urb->iso_frame_desc[u].offset = totlen; as->urb->iso_frame_desc[u].length = isopkt[u].length; totlen += isopkt[u].length; } kfree(isopkt); as->ps = ps; as->userurb = arg; if (is_in && uurb->buffer_length > 0) as->userbuffer = uurb->buffer; else as->userbuffer = NULL; as->signr = uurb->signr; as->ifnum = ifnum; as->pid = get_pid(task_pid(current)); as->uid = cred->uid; as->euid = cred->euid; security_task_getsecid(current, &as->secid); if (!is_in && uurb->buffer_length > 0) { if (copy_from_user(as->urb->transfer_buffer, uurb->buffer, uurb->buffer_length)) { free_async(as); return -EFAULT; } } snoop_urb(ps->dev, as->userurb, as->urb->pipe, as->urb->transfer_buffer_length, 0, SUBMIT); async_newpending(as); if (usb_endpoint_xfer_bulk(&ep->desc)) { spin_lock_irq(&ps->lock); /* Not exactly the endpoint address; the direction bit is * shifted to the 0x10 position so that the value will be * between 0 and 31. */ as->bulk_addr = usb_endpoint_num(&ep->desc) | ((ep->desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK) >> 3); /* If this bulk URB is the start of a new transfer, re-enable * the endpoint. Otherwise mark it as a continuation URB. */ if (uurb->flags & USBDEVFS_URB_BULK_CONTINUATION) as->bulk_status = AS_CONTINUATION; else ps->disabled_bulk_eps &= ~(1 << as->bulk_addr); /* Don't accept continuation URBs if the endpoint is * disabled because of an earlier error. */ if (ps->disabled_bulk_eps & (1 << as->bulk_addr)) ret = -EREMOTEIO; else ret = usb_submit_urb(as->urb, GFP_ATOMIC); spin_unlock_irq(&ps->lock); } else { ret = usb_submit_urb(as->urb, GFP_KERNEL); } if (ret) { dev_printk(KERN_DEBUG, &ps->dev->dev, "usbfs: usb_submit_urb returned %d\n", ret); snoop_urb(ps->dev, as->userurb, as->urb->pipe, 0, ret, COMPLETE); async_removepending(as); free_async(as); return ret; } return 0; } static int proc_submiturb(struct dev_state *ps, void __user *arg) { struct usbdevfs_urb uurb; if (copy_from_user(&uurb, arg, sizeof(uurb))) return -EFAULT; return proc_do_submiturb(ps, &uurb, (((struct usbdevfs_urb __user *)arg)->iso_frame_desc), arg); } static int proc_unlinkurb(struct dev_state *ps, void __user *arg) { struct async *as; as = async_getpending(ps, arg); if (!as) return -EINVAL; usb_kill_urb(as->urb); return 0; } static int processcompl(struct async *as, void __user * __user *arg) { struct urb *urb = as->urb; struct usbdevfs_urb __user *userurb = as->userurb; void __user *addr = as->userurb; unsigned int i; if (as->userbuffer && urb->actual_length) if (copy_to_user(as->userbuffer, urb->transfer_buffer, urb->actual_length)) goto err_out; if (put_user(as->status, &userurb->status)) goto err_out; if (put_user(urb->actual_length, &userurb->actual_length)) goto err_out; if (put_user(urb->error_count, &userurb->error_count)) goto err_out; if (usb_endpoint_xfer_isoc(&urb->ep->desc)) { for (i = 0; i < urb->number_of_packets; i++) { if (put_user(urb->iso_frame_desc[i].actual_length, &userurb->iso_frame_desc[i].actual_length)) goto err_out; if (put_user(urb->iso_frame_desc[i].status, &userurb->iso_frame_desc[i].status)) goto err_out; } } if (put_user(addr, (void __user * __user *)arg)) return -EFAULT; return 0; err_out: return -EFAULT; } static struct async *reap_as(struct dev_state *ps) { DECLARE_WAITQUEUE(wait, current); struct async *as = NULL; struct usb_device *dev = ps->dev; add_wait_queue(&ps->wait, &wait); for (;;) { __set_current_state(TASK_INTERRUPTIBLE); as = async_getcompleted(ps); if (as) break; if (signal_pending(current)) break; usb_unlock_device(dev); schedule(); usb_lock_device(dev); } remove_wait_queue(&ps->wait, &wait); set_current_state(TASK_RUNNING); return as; } static int proc_reapurb(struct dev_state *ps, void __user *arg) { struct async *as = reap_as(ps); if (as) { int retval = processcompl(as, (void __user * __user *)arg); free_async(as); return retval; } if (signal_pending(current)) return -EINTR; return -EIO; } static int proc_reapurbnonblock(struct dev_state *ps, void __user *arg) { int retval; struct async *as; as = async_getcompleted(ps); retval = -EAGAIN; if (as) { retval = processcompl(as, (void __user * __user *)arg); free_async(as); } return retval; } #ifdef CONFIG_COMPAT static int get_urb32(struct usbdevfs_urb *kurb, struct usbdevfs_urb32 __user *uurb) { __u32 uptr; if (!access_ok(VERIFY_READ, uurb, sizeof(*uurb)) || __get_user(kurb->type, &uurb->type) || __get_user(kurb->endpoint, &uurb->endpoint) || __get_user(kurb->status, &uurb->status) || __get_user(kurb->flags, &uurb->flags) || __get_user(kurb->buffer_length, &uurb->buffer_length) || __get_user(kurb->actual_length, &uurb->actual_length) || __get_user(kurb->start_frame, &uurb->start_frame) || __get_user(kurb->number_of_packets, &uurb->number_of_packets) || __get_user(kurb->error_count, &uurb->error_count) || __get_user(kurb->signr, &uurb->signr)) return -EFAULT; if (__get_user(uptr, &uurb->buffer)) return -EFAULT; kurb->buffer = compat_ptr(uptr); if (__get_user(uptr, &uurb->usercontext)) return -EFAULT; kurb->usercontext = compat_ptr(uptr); return 0; } static int proc_submiturb_compat(struct dev_state *ps, void __user *arg) { struct usbdevfs_urb uurb; if (get_urb32(&uurb, (struct usbdevfs_urb32 __user *)arg)) return -EFAULT; return proc_do_submiturb(ps, &uurb, ((struct usbdevfs_urb32 __user *)arg)->iso_frame_desc, arg); } static int processcompl_compat(struct async *as, void __user * __user *arg) { struct urb *urb = as->urb; struct usbdevfs_urb32 __user *userurb = as->userurb; void __user *addr = as->userurb; unsigned int i; if (as->userbuffer && urb->actual_length) if (copy_to_user(as->userbuffer, urb->transfer_buffer, urb->actual_length)) return -EFAULT; if (put_user(as->status, &userurb->status)) return -EFAULT; if (put_user(urb->actual_length, &userurb->actual_length)) return -EFAULT; if (put_user(urb->error_count, &userurb->error_count)) return -EFAULT; if (usb_endpoint_xfer_isoc(&urb->ep->desc)) { for (i = 0; i < urb->number_of_packets; i++) { if (put_user(urb->iso_frame_desc[i].actual_length, &userurb->iso_frame_desc[i].actual_length)) return -EFAULT; if (put_user(urb->iso_frame_desc[i].status, &userurb->iso_frame_desc[i].status)) return -EFAULT; } } if (put_user(ptr_to_compat(addr), (u32 __user *)arg)) return -EFAULT; return 0; } static int proc_reapurb_compat(struct dev_state *ps, void __user *arg) { struct async *as = reap_as(ps); if (as) { int retval = processcompl_compat(as, (void __user * __user *)arg); free_async(as); return retval; } if (signal_pending(current)) return -EINTR; return -EIO; } static int proc_reapurbnonblock_compat(struct dev_state *ps, void __user *arg) { int retval; struct async *as; retval = -EAGAIN; as = async_getcompleted(ps); if (as) { retval = processcompl_compat(as, (void __user * __user *)arg); free_async(as); } return retval; } #endif static int proc_disconnectsignal(struct dev_state *ps, void __user *arg) { struct usbdevfs_disconnectsignal ds; if (copy_from_user(&ds, arg, sizeof(ds))) return -EFAULT; ps->discsignr = ds.signr; ps->disccontext = ds.context; return 0; } static int proc_claiminterface(struct dev_state *ps, void __user *arg) { unsigned int ifnum; if (get_user(ifnum, (unsigned int __user *)arg)) return -EFAULT; return claimintf(ps, ifnum); } static int proc_releaseinterface(struct dev_state *ps, void __user *arg) { unsigned int ifnum; int ret; if (get_user(ifnum, (unsigned int __user *)arg)) return -EFAULT; if ((ret = releaseintf(ps, ifnum)) < 0) return ret; destroy_async_on_interface (ps, ifnum); return 0; } static int proc_ioctl(struct dev_state *ps, struct usbdevfs_ioctl *ctl) { int size; void *buf = NULL; int retval = 0; struct usb_interface *intf = NULL; struct usb_driver *driver = NULL; /* alloc buffer */ if ((size = _IOC_SIZE(ctl->ioctl_code)) > 0) { if ((buf = kmalloc(size, GFP_KERNEL)) == NULL) return -ENOMEM; if ((_IOC_DIR(ctl->ioctl_code) & _IOC_WRITE)) { if (copy_from_user(buf, ctl->data, size)) { kfree(buf); return -EFAULT; } } else { memset(buf, 0, size); } } if (!connected(ps)) { kfree(buf); return -ENODEV; } if (ps->dev->state != USB_STATE_CONFIGURED) retval = -EHOSTUNREACH; else if (!(intf = usb_ifnum_to_if(ps->dev, ctl->ifno))) retval = -EINVAL; else switch (ctl->ioctl_code) { /* disconnect kernel driver from interface */ case USBDEVFS_DISCONNECT: if (intf->dev.driver) { driver = to_usb_driver(intf->dev.driver); dev_dbg(&intf->dev, "disconnect by usbfs\n"); usb_driver_release_interface(driver, intf); } else retval = -ENODATA; break; /* let kernel drivers try to (re)bind to the interface */ case USBDEVFS_CONNECT: if (!intf->dev.driver) retval = device_attach(&intf->dev); else retval = -EBUSY; break; /* talk directly to the interface's driver */ default: if (intf->dev.driver) driver = to_usb_driver(intf->dev.driver); if (driver == NULL || driver->ioctl == NULL) { retval = -ENOTTY; } else { retval = driver->ioctl(intf, ctl->ioctl_code, buf); if (retval == -ENOIOCTLCMD) retval = -ENOTTY; } } /* cleanup and return */ if (retval >= 0 && (_IOC_DIR(ctl->ioctl_code) & _IOC_READ) != 0 && size > 0 && copy_to_user(ctl->data, buf, size) != 0) retval = -EFAULT; kfree(buf); return retval; } static int proc_ioctl_default(struct dev_state *ps, void __user *arg) { struct usbdevfs_ioctl ctrl; if (copy_from_user(&ctrl, arg, sizeof(ctrl))) return -EFAULT; return proc_ioctl(ps, &ctrl); } #ifdef CONFIG_COMPAT static int proc_ioctl_compat(struct dev_state *ps, compat_uptr_t arg) { struct usbdevfs_ioctl32 __user *uioc; struct usbdevfs_ioctl ctrl; u32 udata; uioc = compat_ptr((long)arg); if (!access_ok(VERIFY_READ, uioc, sizeof(*uioc)) || __get_user(ctrl.ifno, &uioc->ifno) || __get_user(ctrl.ioctl_code, &uioc->ioctl_code) || __get_user(udata, &uioc->data)) return -EFAULT; ctrl.data = compat_ptr(udata); return proc_ioctl(ps, &ctrl); } #endif static int proc_claim_port(struct dev_state *ps, void __user *arg) { unsigned portnum; int rc; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; rc = usb_hub_claim_port(ps->dev, portnum, ps); if (rc == 0) snoop(&ps->dev->dev, "port %d claimed by process %d: %s\n", portnum, task_pid_nr(current), current->comm); return rc; } static int proc_release_port(struct dev_state *ps, void __user *arg) { unsigned portnum; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; return usb_hub_release_port(ps->dev, portnum, ps); } /* * NOTE: All requests here that have interface numbers as parameters * are assuming that somehow the configuration has been prevented from * changing. But there's no mechanism to ensure that... */ static int usbdev_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) { struct dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; void __user *p = (void __user *)arg; int ret = -ENOTTY; if (!(file->f_mode & FMODE_WRITE)) return -EPERM; usb_lock_device(dev); if (!connected(ps)) { usb_unlock_device(dev); return -ENODEV; } switch (cmd) { case USBDEVFS_CONTROL: snoop(&dev->dev, "%s: CONTROL\n", __func__); ret = proc_control(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_BULK: snoop(&dev->dev, "%s: BULK\n", __func__); ret = proc_bulk(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_RESETEP: snoop(&dev->dev, "%s: RESETEP\n", __func__); ret = proc_resetep(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_RESET: snoop(&dev->dev, "%s: RESET\n", __func__); ret = proc_resetdevice(ps); break; case USBDEVFS_CLEAR_HALT: snoop(&dev->dev, "%s: CLEAR_HALT\n", __func__); ret = proc_clearhalt(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_GETDRIVER: snoop(&dev->dev, "%s: GETDRIVER\n", __func__); ret = proc_getdriver(ps, p); break; case USBDEVFS_CONNECTINFO: snoop(&dev->dev, "%s: CONNECTINFO\n", __func__); ret = proc_connectinfo(ps, p); break; case USBDEVFS_SETINTERFACE: snoop(&dev->dev, "%s: SETINTERFACE\n", __func__); ret = proc_setintf(ps, p); break; case USBDEVFS_SETCONFIGURATION: snoop(&dev->dev, "%s: SETCONFIGURATION\n", __func__); ret = proc_setconfig(ps, p); break; case USBDEVFS_SUBMITURB: snoop(&dev->dev, "%s: SUBMITURB\n", __func__); ret = proc_submiturb(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; #ifdef CONFIG_COMPAT case USBDEVFS_SUBMITURB32: snoop(&dev->dev, "%s: SUBMITURB32\n", __func__); ret = proc_submiturb_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_REAPURB32: snoop(&dev->dev, "%s: REAPURB32\n", __func__); ret = proc_reapurb_compat(ps, p); break; case USBDEVFS_REAPURBNDELAY32: snoop(&dev->dev, "%s: REAPURBNDELAY32\n", __func__); ret = proc_reapurbnonblock_compat(ps, p); break; case USBDEVFS_IOCTL32: snoop(&dev->dev, "%s: IOCTL\n", __func__); ret = proc_ioctl_compat(ps, ptr_to_compat(p)); break; #endif case USBDEVFS_DISCARDURB: snoop(&dev->dev, "%s: DISCARDURB\n", __func__); ret = proc_unlinkurb(ps, p); break; case USBDEVFS_REAPURB: snoop(&dev->dev, "%s: REAPURB\n", __func__); ret = proc_reapurb(ps, p); break; case USBDEVFS_REAPURBNDELAY: snoop(&dev->dev, "%s: REAPURBNDELAY\n", __func__); ret = proc_reapurbnonblock(ps, p); break; case USBDEVFS_DISCSIGNAL: snoop(&dev->dev, "%s: DISCSIGNAL\n", __func__); ret = proc_disconnectsignal(ps, p); break; case USBDEVFS_CLAIMINTERFACE: snoop(&dev->dev, "%s: CLAIMINTERFACE\n", __func__); ret = proc_claiminterface(ps, p); break; case USBDEVFS_RELEASEINTERFACE: snoop(&dev->dev, "%s: RELEASEINTERFACE\n", __func__); ret = proc_releaseinterface(ps, p); break; case USBDEVFS_IOCTL: snoop(&dev->dev, "%s: IOCTL\n", __func__); ret = proc_ioctl_default(ps, p); break; case USBDEVFS_CLAIM_PORT: snoop(&dev->dev, "%s: CLAIM_PORT\n", __func__); ret = proc_claim_port(ps, p); break; case USBDEVFS_RELEASE_PORT: snoop(&dev->dev, "%s: RELEASE_PORT\n", __func__); ret = proc_release_port(ps, p); break; } usb_unlock_device(dev); if (ret >= 0) inode->i_atime = CURRENT_TIME; return ret; } /* No kernel lock - fine */ static unsigned int usbdev_poll(struct file *file, struct poll_table_struct *wait) { struct dev_state *ps = file->private_data; unsigned int mask = 0; poll_wait(file, &ps->wait, wait); if (file->f_mode & FMODE_WRITE && !list_empty(&ps->async_completed)) mask |= POLLOUT | POLLWRNORM; if (!connected(ps)) mask |= POLLERR | POLLHUP; return mask; } const struct file_operations usbdev_file_operations = { .owner = THIS_MODULE, .llseek = usbdev_lseek, .read = usbdev_read, .poll = usbdev_poll, .ioctl = usbdev_ioctl, .open = usbdev_open, .release = usbdev_release, }; static void usbdev_remove(struct usb_device *udev) { struct dev_state *ps; struct siginfo sinfo; while (!list_empty(&udev->filelist)) { ps = list_entry(udev->filelist.next, struct dev_state, list); destroy_all_async(ps); wake_up_all(&ps->wait); list_del_init(&ps->list); if (ps->discsignr) { sinfo.si_signo = ps->discsignr; sinfo.si_errno = EPIPE; sinfo.si_code = SI_ASYNCIO; sinfo.si_addr = ps->disccontext; kill_pid_info_as_uid(ps->discsignr, &sinfo, ps->disc_pid, ps->disc_uid, ps->disc_euid, ps->secid); } } } #ifdef CONFIG_USB_DEVICE_CLASS static struct class *usb_classdev_class; static int usb_classdev_add(struct usb_device *dev) { struct device *cldev; cldev = device_create(usb_classdev_class, &dev->dev, dev->dev.devt, NULL, "usbdev%d.%d", dev->bus->busnum, dev->devnum); if (IS_ERR(cldev)) return PTR_ERR(cldev); dev->usb_classdev = cldev; return 0; } static void usb_classdev_remove(struct usb_device *dev) { if (dev->usb_classdev) device_unregister(dev->usb_classdev); } #else #define usb_classdev_add(dev) 0 #define usb_classdev_remove(dev) do {} while (0) #endif static int usbdev_notify(struct notifier_block *self, unsigned long action, void *dev) { switch (action) { case USB_DEVICE_ADD: if (usb_classdev_add(dev)) return NOTIFY_BAD; break; case USB_DEVICE_REMOVE: usb_classdev_remove(dev); usbdev_remove(dev); break; } return NOTIFY_OK; } static struct notifier_block usbdev_nb = { .notifier_call = usbdev_notify, }; static struct cdev usb_device_cdev; int __init usb_devio_init(void) { int retval; retval = register_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX, "usb_device"); if (retval) { printk(KERN_ERR "Unable to register minors for usb_device\n"); goto out; } cdev_init(&usb_device_cdev, &usbdev_file_operations); retval = cdev_add(&usb_device_cdev, USB_DEVICE_DEV, USB_DEVICE_MAX); if (retval) { printk(KERN_ERR "Unable to get usb_device major %d\n", USB_DEVICE_MAJOR); goto error_cdev; } #ifdef CONFIG_USB_DEVICE_CLASS usb_classdev_class = class_create(THIS_MODULE, "usb_device"); if (IS_ERR(usb_classdev_class)) { printk(KERN_ERR "Unable to register usb_device class\n"); retval = PTR_ERR(usb_classdev_class); cdev_del(&usb_device_cdev); usb_classdev_class = NULL; goto out; } /* devices of this class shadow the major:minor of their parent * device, so clear ->dev_kobj to prevent adding duplicate entries * to /sys/dev */ usb_classdev_class->dev_kobj = NULL; #endif usb_register_notify(&usbdev_nb); out: return retval; error_cdev: unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX); goto out; } void usb_devio_cleanup(void) { usb_unregister_notify(&usbdev_nb); #ifdef CONFIG_USB_DEVICE_CLASS class_destroy(usb_classdev_class); #endif cdev_del(&usb_device_cdev); unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX); }
gpl-2.0
Saylance/PandariaCore
dep/g3dlite/source/CoordinateFrame.cpp
536
12216
/** @file CoordinateFrame.cpp Coordinate frame class @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2001-06-02 @edited 2010-03-13 Copyright 2000-2010, Morgan McGuire. All rights reserved. */ #include "G3D/platform.h" #include "G3D/CoordinateFrame.h" #include "G3D/Quat.h" #include "G3D/Matrix4.h" #include "G3D/Box.h" #include "G3D/AABox.h" #include "G3D/Sphere.h" #include "G3D/Triangle.h" #include "G3D/Ray.h" #include "G3D/Capsule.h" #include "G3D/Cylinder.h" #include "G3D/UprightFrame.h" #include "G3D/Any.h" #include "G3D/stringutils.h" #include "G3D/PhysicsFrame.h" #include "G3D/UprightFrame.h" namespace G3D { std::string CoordinateFrame::toXYZYPRDegreesString() const { UprightFrame uframe(*this); return format("CFrame::fromXYZYPRDegrees(% 5.1ff, % 5.1ff, % 5.1ff, % 5.1ff, % 5.1ff, % 5.1ff)", uframe.translation.x, uframe.translation.y, uframe.translation.z, toDegrees(uframe.yaw), toDegrees(uframe.pitch), 0.0f); } CoordinateFrame::CoordinateFrame(const Any& any) { *this = CFrame(); const std::string& n = toUpper(any.name()); if (beginsWith(n, "VECTOR3")) { translation = any; } else if (beginsWith(n, "MATRIX3")) { rotation = any; } else if ((n == "CFRAME") || (n == "COORDINATEFRAME")) { any.verifyType(Any::TABLE, Any::ARRAY); if (any.type() == Any::ARRAY) { any.verifySize(2); rotation = any[0]; translation = any[1]; } else { for (Any::AnyTable::Iterator it = any.table().begin(); it.hasMore(); ++it) { const std::string& n = toLower(it->key); if (n == "translation") { translation = Vector3(it->value); } else if (n == "rotation") { rotation = Matrix3(it->value); } else { any.verify(false, "Illegal table key: " + it->key); } } } } else if (beginsWith(n, "PHYSICSFRAME") || beginsWith(n, "PFRAME")) { *this = PhysicsFrame(any); } else { any.verifyName("CFrame::fromXYZYPRDegrees", "CoordinateFrame::fromXYZYPRDegrees"); any.verifyType(Any::ARRAY); any.verifySize(3, 6); int s = any.size(); *this = fromXYZYPRDegrees(any[0], any[1], any[2], (s > 3) ? any[3].number() : 0.0f, (s > 4) ? any[4].number() : 0.0f, (s > 5) ? any[5].number() : 0.0f); } } CoordinateFrame::operator Any() const { float x, y, z, yaw, pitch, roll; getXYZYPRDegrees(x, y, z, yaw, pitch, roll); Any a(Any::ARRAY, "CFrame::fromXYZYPRDegrees"); a.append(x, y, z, yaw); if ( ! G3D::fuzzyEq(yaw, 0.0f) || ! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { a.append(yaw); if (! G3D::fuzzyEq(pitch, 0.0f) || ! G3D::fuzzyEq(roll, 0.0f)) { a.append(pitch); if (! G3D::fuzzyEq(roll, 0.0f)) { a.append(roll); } } } return a; } CoordinateFrame::CoordinateFrame(const class UprightFrame& f) { *this = f.toCoordinateFrame(); } CoordinateFrame::CoordinateFrame() : rotation(Matrix3::identity()), translation(Vector3::zero()) { } CoordinateFrame CoordinateFrame::fromXYZYPRRadians(float x, float y, float z, float yaw, float pitch, float roll) { Matrix3 rotation = Matrix3::fromAxisAngle(Vector3::unitY(), yaw); rotation = Matrix3::fromAxisAngle(rotation.column(0), pitch) * rotation; rotation = Matrix3::fromAxisAngle(rotation.column(2), roll) * rotation; const Vector3 translation(x, y, z); return CoordinateFrame(rotation, translation); } void CoordinateFrame::getXYZYPRRadians(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const { x = translation.x; y = translation.y; z = translation.z; const Vector3& look = lookVector(); if (abs(look.y) > 0.99f) { // Looking nearly straight up or down yaw = G3D::pi() + atan2(look.x, look.z); pitch = asin(look.y); roll = 0.0f; } else { // Yaw cannot be affected by others, so pull it first yaw = G3D::pi() + atan2(look.x, look.z); // Pitch is the elevation of the yaw vector pitch = asin(look.y); Vector3 actualRight = rightVector(); Vector3 expectedRight = look.cross(Vector3::unitY()); roll = 0;//acos(actualRight.dot(expectedRight)); TODO } } void CoordinateFrame::getXYZYPRDegrees(float& x, float& y, float& z, float& yaw, float& pitch, float& roll) const { getXYZYPRRadians(x, y, z, yaw, pitch, roll); yaw = toDegrees(yaw); pitch = toDegrees(pitch); roll = toDegrees(roll); } CoordinateFrame CoordinateFrame::fromXYZYPRDegrees(float x, float y, float z, float yaw, float pitch, float roll) { return fromXYZYPRRadians(x, y, z, toRadians(yaw), toRadians(pitch), toRadians(roll)); } Ray CoordinateFrame::lookRay() const { return Ray::fromOriginAndDirection(translation, lookVector()); } bool CoordinateFrame::fuzzyEq(const CoordinateFrame& other) const { for (int c = 0; c < 3; ++c) { for (int r = 0; r < 3; ++r) { if (! G3D::fuzzyEq(other.rotation[r][c], rotation[r][c])) { return false; } } if (! G3D::fuzzyEq(translation[c], other.translation[c])) { return false; } } return true; } bool CoordinateFrame::fuzzyIsIdentity() const { const Matrix3& I = Matrix3::identity(); for (int c = 0; c < 3; ++c) { for (int r = 0; r < 3; ++r) { if (fuzzyNe(I[r][c], rotation[r][c])) { return false; } } if (fuzzyNe(translation[c], 0)) { return false; } } return true; } bool CoordinateFrame::isIdentity() const { return (translation == Vector3::zero()) && (rotation == Matrix3::identity()); } Matrix4 CoordinateFrame::toMatrix4() const { return Matrix4(*this); } std::string CoordinateFrame::toXML() const { return G3D::format( "<COORDINATEFRAME>\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf,\n %lf,%lf,%lf,%lf\n</COORDINATEFRAME>\n", rotation[0][0], rotation[0][1], rotation[0][2], translation.x, rotation[1][0], rotation[1][1], rotation[1][2], translation.y, rotation[2][0], rotation[2][1], rotation[2][2], translation.z, 0.0, 0.0, 0.0, 1.0); } Plane CoordinateFrame::toObjectSpace(const Plane& p) const { Vector3 N, P; double d; p.getEquation(N, d); P = N * (float)d; P = pointToObjectSpace(P); N = normalToObjectSpace(N); return Plane(N, P); } Plane CoordinateFrame::toWorldSpace(const Plane& p) const { Vector3 N, P; double d; p.getEquation(N, d); P = N * (float)d; P = pointToWorldSpace(P); N = normalToWorldSpace(N); return Plane(N, P); } Triangle CoordinateFrame::toObjectSpace(const Triangle& t) const { return Triangle(pointToObjectSpace(t.vertex(0)), pointToObjectSpace(t.vertex(1)), pointToObjectSpace(t.vertex(2))); } Triangle CoordinateFrame::toWorldSpace(const Triangle& t) const { return Triangle(pointToWorldSpace(t.vertex(0)), pointToWorldSpace(t.vertex(1)), pointToWorldSpace(t.vertex(2))); } Cylinder CoordinateFrame::toWorldSpace(const Cylinder& c) const { return Cylinder( pointToWorldSpace(c.point(0)), pointToWorldSpace(c.point(1)), c.radius()); } Capsule CoordinateFrame::toWorldSpace(const Capsule& c) const { return Capsule( pointToWorldSpace(c.point(0)), pointToWorldSpace(c.point(1)), c.radius()); } Box CoordinateFrame::toWorldSpace(const AABox& b) const { Box b2(b); return toWorldSpace(b2); } Box CoordinateFrame::toWorldSpace(const Box& b) const { Box out(b); for (int i = 0; i < 8; ++i) { out._corner[i] = pointToWorldSpace(b._corner[i]); debugAssert(! isNaN(out._corner[i].x)); } for (int i = 0; i < 3; ++i) { out._axis[i] = vectorToWorldSpace(b._axis[i]); } out._center = pointToWorldSpace(b._center); return out; } Box CoordinateFrame::toObjectSpace(const Box &b) const { return inverse().toWorldSpace(b); } Box CoordinateFrame::toObjectSpace(const AABox& b) const { return toObjectSpace(Box(b)); } CoordinateFrame::CoordinateFrame(class BinaryInput& b) : rotation(Matrix3::zero()) { deserialize(b); } void CoordinateFrame::deserialize(class BinaryInput& b) { rotation.deserialize(b); translation.deserialize(b); } void CoordinateFrame::serialize(class BinaryOutput& b) const { rotation.serialize(b); translation.serialize(b); } Sphere CoordinateFrame::toWorldSpace(const Sphere &b) const { return Sphere(pointToWorldSpace(b.center), b.radius); } Sphere CoordinateFrame::toObjectSpace(const Sphere &b) const { return Sphere(pointToObjectSpace(b.center), b.radius); } Ray CoordinateFrame::toWorldSpace(const Ray& r) const { return Ray::fromOriginAndDirection(pointToWorldSpace(r.origin()), vectorToWorldSpace(r.direction())); } Ray CoordinateFrame::toObjectSpace(const Ray& r) const { return Ray::fromOriginAndDirection(pointToObjectSpace(r.origin()), vectorToObjectSpace(r.direction())); } void CoordinateFrame::lookAt(const Vector3 &target) { lookAt(target, Vector3::unitY()); } void CoordinateFrame::lookAt( const Vector3& target, Vector3 up) { up = up.direction(); Vector3 look = (target - translation).direction(); if (fabs(look.dot(up)) > .99f) { up = Vector3::unitX(); if (fabs(look.dot(up)) > .99f) { up = Vector3::unitY(); } } up -= look * look.dot(up); up.unitize(); Vector3 z = -look; Vector3 x = -z.cross(up); x.unitize(); Vector3 y = z.cross(x); rotation.setColumn(0, x); rotation.setColumn(1, y); rotation.setColumn(2, z); } CoordinateFrame CoordinateFrame::lerp( const CoordinateFrame& other, float alpha) const { if (alpha == 1.0f) { return other; } else if (alpha == 0.0f) { return *this; } else { const Quat q1(this->rotation); const Quat q2(other.rotation); return CoordinateFrame( q1.slerp(q2, alpha).toRotationMatrix(), translation * (1 - alpha) + other.translation * alpha); } } void CoordinateFrame::pointToWorldSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = 0; i < v.size(); ++i) { vout[i] = pointToWorldSpace(v[i]); } } void CoordinateFrame::normalToWorldSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = 0; i < v.size(); ++i) { vout[i] = normalToWorldSpace(v[i]); } } void CoordinateFrame::vectorToWorldSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = vectorToWorldSpace(v[i]); } } void CoordinateFrame::pointToObjectSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = pointToObjectSpace(v[i]); } } void CoordinateFrame::normalToObjectSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = normalToObjectSpace(v[i]); } } void CoordinateFrame::vectorToObjectSpace(const Array<Vector3>& v, Array<Vector3>& vout) const { vout.resize(v.size()); for (int i = v.size() - 1; i >= 0; --i) { vout[i] = vectorToObjectSpace(v[i]); } } } // namespace
gpl-2.0
tiny4579/tiny-gingersense
drivers/media/video/pvrusb2/pvrusb2-i2c-core.c
1048
18990
/* * * * Copyright (C) 2005 Mike Isely <isely@pobox.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 * * 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/i2c.h> #include "pvrusb2-i2c-core.h" #include "pvrusb2-hdw-internal.h" #include "pvrusb2-debug.h" #include "pvrusb2-fx2-cmd.h" #include "pvrusb2.h" #define trace_i2c(...) pvr2_trace(PVR2_TRACE_I2C,__VA_ARGS__) /* This module attempts to implement a compliant I2C adapter for the pvrusb2 device. */ static unsigned int i2c_scan; module_param(i2c_scan, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(i2c_scan,"scan i2c bus at insmod time"); static int ir_mode[PVR_NUM] = { [0 ... PVR_NUM-1] = 1 }; module_param_array(ir_mode, int, NULL, 0444); MODULE_PARM_DESC(ir_mode,"specify: 0=disable IR reception, 1=normal IR"); static int pvr2_disable_ir_video; module_param_named(disable_autoload_ir_video, pvr2_disable_ir_video, int, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(disable_autoload_ir_video, "1=do not try to autoload ir_video IR receiver"); /* Mapping of IR schemes to known I2C addresses - if any */ static const unsigned char ir_video_addresses[] = { [PVR2_IR_SCHEME_ZILOG] = 0x71, [PVR2_IR_SCHEME_29XXX] = 0x18, [PVR2_IR_SCHEME_24XXX] = 0x18, }; static int pvr2_i2c_write(struct pvr2_hdw *hdw, /* Context */ u8 i2c_addr, /* I2C address we're talking to */ u8 *data, /* Data to write */ u16 length) /* Size of data to write */ { /* Return value - default 0 means success */ int ret; if (!data) length = 0; if (length > (sizeof(hdw->cmd_buffer) - 3)) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Killing an I2C write to %u that is too large" " (desired=%u limit=%u)", i2c_addr, length,(unsigned int)(sizeof(hdw->cmd_buffer) - 3)); return -ENOTSUPP; } LOCK_TAKE(hdw->ctl_lock); /* Clear the command buffer (likely to be paranoia) */ memset(hdw->cmd_buffer, 0, sizeof(hdw->cmd_buffer)); /* Set up command buffer for an I2C write */ hdw->cmd_buffer[0] = FX2CMD_I2C_WRITE; /* write prefix */ hdw->cmd_buffer[1] = i2c_addr; /* i2c addr of chip */ hdw->cmd_buffer[2] = length; /* length of what follows */ if (length) memcpy(hdw->cmd_buffer + 3, data, length); /* Do the operation */ ret = pvr2_send_request(hdw, hdw->cmd_buffer, length + 3, hdw->cmd_buffer, 1); if (!ret) { if (hdw->cmd_buffer[0] != 8) { ret = -EIO; if (hdw->cmd_buffer[0] != 7) { trace_i2c("unexpected status" " from i2_write[%d]: %d", i2c_addr,hdw->cmd_buffer[0]); } } } LOCK_GIVE(hdw->ctl_lock); return ret; } static int pvr2_i2c_read(struct pvr2_hdw *hdw, /* Context */ u8 i2c_addr, /* I2C address we're talking to */ u8 *data, /* Data to write */ u16 dlen, /* Size of data to write */ u8 *res, /* Where to put data we read */ u16 rlen) /* Amount of data to read */ { /* Return value - default 0 means success */ int ret; if (!data) dlen = 0; if (dlen > (sizeof(hdw->cmd_buffer) - 4)) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Killing an I2C read to %u that has wlen too large" " (desired=%u limit=%u)", i2c_addr, dlen,(unsigned int)(sizeof(hdw->cmd_buffer) - 4)); return -ENOTSUPP; } if (res && (rlen > (sizeof(hdw->cmd_buffer) - 1))) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "Killing an I2C read to %u that has rlen too large" " (desired=%u limit=%u)", i2c_addr, rlen,(unsigned int)(sizeof(hdw->cmd_buffer) - 1)); return -ENOTSUPP; } LOCK_TAKE(hdw->ctl_lock); /* Clear the command buffer (likely to be paranoia) */ memset(hdw->cmd_buffer, 0, sizeof(hdw->cmd_buffer)); /* Set up command buffer for an I2C write followed by a read */ hdw->cmd_buffer[0] = FX2CMD_I2C_READ; /* read prefix */ hdw->cmd_buffer[1] = dlen; /* arg length */ hdw->cmd_buffer[2] = rlen; /* answer length. Device will send one more byte (status). */ hdw->cmd_buffer[3] = i2c_addr; /* i2c addr of chip */ if (dlen) memcpy(hdw->cmd_buffer + 4, data, dlen); /* Do the operation */ ret = pvr2_send_request(hdw, hdw->cmd_buffer, 4 + dlen, hdw->cmd_buffer, rlen + 1); if (!ret) { if (hdw->cmd_buffer[0] != 8) { ret = -EIO; if (hdw->cmd_buffer[0] != 7) { trace_i2c("unexpected status" " from i2_read[%d]: %d", i2c_addr,hdw->cmd_buffer[0]); } } } /* Copy back the result */ if (res && rlen) { if (ret) { /* Error, just blank out the return buffer */ memset(res, 0, rlen); } else { memcpy(res, hdw->cmd_buffer + 1, rlen); } } LOCK_GIVE(hdw->ctl_lock); return ret; } /* This is the common low level entry point for doing I2C operations to the hardware. */ static int pvr2_i2c_basic_op(struct pvr2_hdw *hdw, u8 i2c_addr, u8 *wdata, u16 wlen, u8 *rdata, u16 rlen) { if (!rdata) rlen = 0; if (!wdata) wlen = 0; if (rlen || !wlen) { return pvr2_i2c_read(hdw,i2c_addr,wdata,wlen,rdata,rlen); } else { return pvr2_i2c_write(hdw,i2c_addr,wdata,wlen); } } /* This is a special entry point for cases of I2C transaction attempts to the IR receiver. The implementation here simulates the IR receiver by issuing a command to the FX2 firmware and using that response to return what the real I2C receiver would have returned. We use this for 24xxx devices, where the IR receiver chip has been removed and replaced with FX2 related logic. */ static int i2c_24xxx_ir(struct pvr2_hdw *hdw, u8 i2c_addr,u8 *wdata,u16 wlen,u8 *rdata,u16 rlen) { u8 dat[4]; unsigned int stat; if (!(rlen || wlen)) { /* This is a probe attempt. Just let it succeed. */ return 0; } /* We don't understand this kind of transaction */ if ((wlen != 0) || (rlen == 0)) return -EIO; if (rlen < 3) { /* Mike Isely <isely@pobox.com> Appears to be a probe attempt from lirc. Just fill in zeroes and return. If we try instead to do the full transaction here, then bad things seem to happen within the lirc driver module (version 0.8.0-7 sources from Debian, when run under vanilla 2.6.17.6 kernel) - and I don't have the patience to chase it down. */ if (rlen > 0) rdata[0] = 0; if (rlen > 1) rdata[1] = 0; return 0; } /* Issue a command to the FX2 to read the IR receiver. */ LOCK_TAKE(hdw->ctl_lock); do { hdw->cmd_buffer[0] = FX2CMD_GET_IR_CODE; stat = pvr2_send_request(hdw, hdw->cmd_buffer,1, hdw->cmd_buffer,4); dat[0] = hdw->cmd_buffer[0]; dat[1] = hdw->cmd_buffer[1]; dat[2] = hdw->cmd_buffer[2]; dat[3] = hdw->cmd_buffer[3]; } while (0); LOCK_GIVE(hdw->ctl_lock); /* Give up if that operation failed. */ if (stat != 0) return stat; /* Mangle the results into something that looks like the real IR receiver. */ rdata[2] = 0xc1; if (dat[0] != 1) { /* No code received. */ rdata[0] = 0; rdata[1] = 0; } else { u16 val; /* Mash the FX2 firmware-provided IR code into something that the normal i2c chip-level driver expects. */ val = dat[1]; val <<= 8; val |= dat[2]; val >>= 1; val &= ~0x0003; val |= 0x8000; rdata[0] = (val >> 8) & 0xffu; rdata[1] = val & 0xffu; } return 0; } /* This is a special entry point that is entered if an I2C operation is attempted to a wm8775 chip on model 24xxx hardware. Autodetect of this part doesn't work, but we know it is really there. So let's look for the autodetect attempt and just return success if we see that. */ static int i2c_hack_wm8775(struct pvr2_hdw *hdw, u8 i2c_addr,u8 *wdata,u16 wlen,u8 *rdata,u16 rlen) { if (!(rlen || wlen)) { // This is a probe attempt. Just let it succeed. return 0; } return pvr2_i2c_basic_op(hdw,i2c_addr,wdata,wlen,rdata,rlen); } /* This is an entry point designed to always fail any attempt to perform a transfer. We use this to cause certain I2C addresses to not be probed. */ static int i2c_black_hole(struct pvr2_hdw *hdw, u8 i2c_addr,u8 *wdata,u16 wlen,u8 *rdata,u16 rlen) { return -EIO; } /* This is a special entry point that is entered if an I2C operation is attempted to a cx25840 chip on model 24xxx hardware. This chip can sometimes wedge itself. Worse still, when this happens msp3400 can falsely detect this part and then the system gets hosed up after msp3400 gets confused and dies. What we want to do here is try to keep msp3400 away and also try to notice if the chip is wedged and send a warning to the system log. */ static int i2c_hack_cx25840(struct pvr2_hdw *hdw, u8 i2c_addr,u8 *wdata,u16 wlen,u8 *rdata,u16 rlen) { int ret; unsigned int subaddr; u8 wbuf[2]; int state = hdw->i2c_cx25840_hack_state; if (!(rlen || wlen)) { // Probe attempt - always just succeed and don't bother the // hardware (this helps to make the state machine further // down somewhat easier). return 0; } if (state == 3) { return pvr2_i2c_basic_op(hdw,i2c_addr,wdata,wlen,rdata,rlen); } /* We're looking for the exact pattern where the revision register is being read. The cx25840 module will always look at the revision register first. Any other pattern of access therefore has to be a probe attempt from somebody else so we'll reject it. Normally we could just let each client just probe the part anyway, but when the cx25840 is wedged, msp3400 will get a false positive and that just screws things up... */ if (wlen == 0) { switch (state) { case 1: subaddr = 0x0100; break; case 2: subaddr = 0x0101; break; default: goto fail; } } else if (wlen == 2) { subaddr = (wdata[0] << 8) | wdata[1]; switch (subaddr) { case 0x0100: state = 1; break; case 0x0101: state = 2; break; default: goto fail; } } else { goto fail; } if (!rlen) goto success; state = 0; if (rlen != 1) goto fail; /* If we get to here then we have a legitimate read for one of the two revision bytes, so pass it through. */ wbuf[0] = subaddr >> 8; wbuf[1] = subaddr; ret = pvr2_i2c_basic_op(hdw,i2c_addr,wbuf,2,rdata,rlen); if ((ret != 0) || (*rdata == 0x04) || (*rdata == 0x0a)) { pvr2_trace(PVR2_TRACE_ERROR_LEGS, "WARNING: Detected a wedged cx25840 chip;" " the device will not work."); pvr2_trace(PVR2_TRACE_ERROR_LEGS, "WARNING: Try power cycling the pvrusb2 device."); pvr2_trace(PVR2_TRACE_ERROR_LEGS, "WARNING: Disabling further access to the device" " to prevent other foul-ups."); // This blocks all further communication with the part. hdw->i2c_func[0x44] = NULL; pvr2_hdw_render_useless(hdw); goto fail; } /* Success! */ pvr2_trace(PVR2_TRACE_CHIPS,"cx25840 appears to be OK."); state = 3; success: hdw->i2c_cx25840_hack_state = state; return 0; fail: hdw->i2c_cx25840_hack_state = state; return -EIO; } /* This is a very, very limited I2C adapter implementation. We can only support what we actually know will work on the device... */ static int pvr2_i2c_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg msgs[], int num) { int ret = -ENOTSUPP; pvr2_i2c_func funcp = NULL; struct pvr2_hdw *hdw = (struct pvr2_hdw *)(i2c_adap->algo_data); if (!num) { ret = -EINVAL; goto done; } if (msgs[0].addr < PVR2_I2C_FUNC_CNT) { funcp = hdw->i2c_func[msgs[0].addr]; } if (!funcp) { ret = -EIO; goto done; } if (num == 1) { if (msgs[0].flags & I2C_M_RD) { /* Simple read */ u16 tcnt,bcnt,offs; if (!msgs[0].len) { /* Length == 0 read. This is a probe. */ if (funcp(hdw,msgs[0].addr,NULL,0,NULL,0)) { ret = -EIO; goto done; } ret = 1; goto done; } /* If the read is short enough we'll do the whole thing atomically. Otherwise we have no choice but to break apart the reads. */ tcnt = msgs[0].len; offs = 0; while (tcnt) { bcnt = tcnt; if (bcnt > sizeof(hdw->cmd_buffer)-1) { bcnt = sizeof(hdw->cmd_buffer)-1; } if (funcp(hdw,msgs[0].addr,NULL,0, msgs[0].buf+offs,bcnt)) { ret = -EIO; goto done; } offs += bcnt; tcnt -= bcnt; } ret = 1; goto done; } else { /* Simple write */ ret = 1; if (funcp(hdw,msgs[0].addr, msgs[0].buf,msgs[0].len,NULL,0)) { ret = -EIO; } goto done; } } else if (num == 2) { if (msgs[0].addr != msgs[1].addr) { trace_i2c("i2c refusing 2 phase transfer with" " conflicting target addresses"); ret = -ENOTSUPP; goto done; } if ((!((msgs[0].flags & I2C_M_RD))) && (msgs[1].flags & I2C_M_RD)) { u16 tcnt,bcnt,wcnt,offs; /* Write followed by atomic read. If the read portion is short enough we'll do the whole thing atomically. Otherwise we have no choice but to break apart the reads. */ tcnt = msgs[1].len; wcnt = msgs[0].len; offs = 0; while (tcnt || wcnt) { bcnt = tcnt; if (bcnt > sizeof(hdw->cmd_buffer)-1) { bcnt = sizeof(hdw->cmd_buffer)-1; } if (funcp(hdw,msgs[0].addr, msgs[0].buf,wcnt, msgs[1].buf+offs,bcnt)) { ret = -EIO; goto done; } offs += bcnt; tcnt -= bcnt; wcnt = 0; } ret = 2; goto done; } else { trace_i2c("i2c refusing complex transfer" " read0=%d read1=%d", (msgs[0].flags & I2C_M_RD), (msgs[1].flags & I2C_M_RD)); } } else { trace_i2c("i2c refusing %d phase transfer",num); } done: if (pvrusb2_debug & PVR2_TRACE_I2C_TRAF) { unsigned int idx,offs,cnt; for (idx = 0; idx < num; idx++) { cnt = msgs[idx].len; printk(KERN_INFO "pvrusb2 i2c xfer %u/%u:" " addr=0x%x len=%d %s", idx+1,num, msgs[idx].addr, cnt, (msgs[idx].flags & I2C_M_RD ? "read" : "write")); if ((ret > 0) || !(msgs[idx].flags & I2C_M_RD)) { if (cnt > 8) cnt = 8; printk(" ["); for (offs = 0; offs < (cnt>8?8:cnt); offs++) { if (offs) printk(" "); printk("%02x",msgs[idx].buf[offs]); } if (offs < cnt) printk(" ..."); printk("]"); } if (idx+1 == num) { printk(" result=%d",ret); } printk("\n"); } if (!num) { printk(KERN_INFO "pvrusb2 i2c xfer null transfer result=%d\n", ret); } } return ret; } static u32 pvr2_i2c_functionality(struct i2c_adapter *adap) { return I2C_FUNC_SMBUS_EMUL | I2C_FUNC_I2C; } static struct i2c_algorithm pvr2_i2c_algo_template = { .master_xfer = pvr2_i2c_xfer, .functionality = pvr2_i2c_functionality, }; static struct i2c_adapter pvr2_i2c_adap_template = { .owner = THIS_MODULE, .class = 0, }; /* Return true if device exists at given address */ static int do_i2c_probe(struct pvr2_hdw *hdw, int addr) { struct i2c_msg msg[1]; int rc; msg[0].addr = 0; msg[0].flags = I2C_M_RD; msg[0].len = 0; msg[0].buf = NULL; msg[0].addr = addr; rc = i2c_transfer(&hdw->i2c_adap, msg, ARRAY_SIZE(msg)); return rc == 1; } static void do_i2c_scan(struct pvr2_hdw *hdw) { int i; printk(KERN_INFO "%s: i2c scan beginning\n", hdw->name); for (i = 0; i < 128; i++) { if (do_i2c_probe(hdw, i)) { printk(KERN_INFO "%s: i2c scan: found device @ 0x%x\n", hdw->name, i); } } printk(KERN_INFO "%s: i2c scan done.\n", hdw->name); } static void pvr2_i2c_register_ir(struct pvr2_hdw *hdw) { struct i2c_board_info info; unsigned char addr = 0; if (pvr2_disable_ir_video) { pvr2_trace(PVR2_TRACE_INFO, "Automatic binding of ir_video has been disabled."); return; } if (hdw->ir_scheme_active < ARRAY_SIZE(ir_video_addresses)) { addr = ir_video_addresses[hdw->ir_scheme_active]; } if (!addr) { /* The device either doesn't support I2C-based IR or we don't know (yet) how to operate IR on the device. */ return; } pvr2_trace(PVR2_TRACE_INFO, "Binding ir_video to i2c address 0x%02x.", addr); memset(&info, 0, sizeof(struct i2c_board_info)); strlcpy(info.type, "ir_video", I2C_NAME_SIZE); info.addr = addr; i2c_new_device(&hdw->i2c_adap, &info); } void pvr2_i2c_core_init(struct pvr2_hdw *hdw) { unsigned int idx; /* The default action for all possible I2C addresses is just to do the transfer normally. */ for (idx = 0; idx < PVR2_I2C_FUNC_CNT; idx++) { hdw->i2c_func[idx] = pvr2_i2c_basic_op; } /* However, deal with various special cases for 24xxx hardware. */ if (ir_mode[hdw->unit_number] == 0) { printk(KERN_INFO "%s: IR disabled\n",hdw->name); hdw->i2c_func[0x18] = i2c_black_hole; } else if (ir_mode[hdw->unit_number] == 1) { if (hdw->ir_scheme_active == PVR2_IR_SCHEME_24XXX) { /* Set up translation so that our IR looks like a 29xxx device */ hdw->i2c_func[0x18] = i2c_24xxx_ir; } } if (hdw->hdw_desc->flag_has_cx25840) { hdw->i2c_func[0x44] = i2c_hack_cx25840; } if (hdw->hdw_desc->flag_has_wm8775) { hdw->i2c_func[0x1b] = i2c_hack_wm8775; } // Configure the adapter and set up everything else related to it. memcpy(&hdw->i2c_adap,&pvr2_i2c_adap_template,sizeof(hdw->i2c_adap)); memcpy(&hdw->i2c_algo,&pvr2_i2c_algo_template,sizeof(hdw->i2c_algo)); strlcpy(hdw->i2c_adap.name,hdw->name,sizeof(hdw->i2c_adap.name)); hdw->i2c_adap.dev.parent = &hdw->usb_dev->dev; hdw->i2c_adap.algo = &hdw->i2c_algo; hdw->i2c_adap.algo_data = hdw; hdw->i2c_linked = !0; i2c_set_adapdata(&hdw->i2c_adap, &hdw->v4l2_dev); i2c_add_adapter(&hdw->i2c_adap); if (hdw->i2c_func[0x18] == i2c_24xxx_ir) { /* Probe for a different type of IR receiver on this device. This is really the only way to differentiate older 24xxx devices from 24xxx variants that include an IR blaster. If the IR blaster is present, the IR receiver is part of that chip and thus we must disable the emulated IR receiver. */ if (do_i2c_probe(hdw, 0x71)) { pvr2_trace(PVR2_TRACE_INFO, "Device has newer IR hardware;" " disabling unneeded virtual IR device"); hdw->i2c_func[0x18] = NULL; /* Remember that this is a different device... */ hdw->ir_scheme_active = PVR2_IR_SCHEME_24XXX_MCE; } } if (i2c_scan) do_i2c_scan(hdw); pvr2_i2c_register_ir(hdw); } void pvr2_i2c_core_done(struct pvr2_hdw *hdw) { if (hdw->i2c_linked) { i2c_del_adapter(&hdw->i2c_adap); hdw->i2c_linked = 0; } } /* Stuff for Emacs to see, in order to encourage consistent editing style: *** Local Variables: *** *** mode: c *** *** fill-column: 75 *** *** tab-width: 8 *** *** c-basic-offset: 8 *** *** End: *** */
gpl-2.0
Snuzzo/PLUS_kernel
drivers/video/omap2/dss/core.c
2072
13199
/* * linux/drivers/video/omap2/dss/core.c * * Copyright (C) 2009 Nokia Corporation * Author: Tomi Valkeinen <tomi.valkeinen@nokia.com> * * Some code and ideas taken from drivers/video/omap/ driver * by Imre Deak. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #define DSS_SUBSYS_NAME "CORE" #include <linux/kernel.h> #include <linux/module.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/seq_file.h> #include <linux/debugfs.h> #include <linux/io.h> #include <linux/device.h> #include <linux/regulator/consumer.h> #include <video/omapdss.h> #include "dss.h" #include "dss_features.h" static struct { struct platform_device *pdev; struct regulator *vdds_dsi_reg; struct regulator *vdds_sdi_reg; } core; static char *def_disp_name; module_param_named(def_disp, def_disp_name, charp, 0); MODULE_PARM_DESC(def_disp, "default display name"); #ifdef DEBUG unsigned int dss_debug; module_param_named(debug, dss_debug, bool, 0644); #endif static int omap_dss_register_device(struct omap_dss_device *); static void omap_dss_unregister_device(struct omap_dss_device *); /* REGULATORS */ struct regulator *dss_get_vdds_dsi(void) { struct regulator *reg; if (core.vdds_dsi_reg != NULL) return core.vdds_dsi_reg; reg = regulator_get(&core.pdev->dev, "vdds_dsi"); if (!IS_ERR(reg)) core.vdds_dsi_reg = reg; return reg; } struct regulator *dss_get_vdds_sdi(void) { struct regulator *reg; if (core.vdds_sdi_reg != NULL) return core.vdds_sdi_reg; reg = regulator_get(&core.pdev->dev, "vdds_sdi"); if (!IS_ERR(reg)) core.vdds_sdi_reg = reg; return reg; } #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_OMAP2_DSS_DEBUG_SUPPORT) static int dss_debug_show(struct seq_file *s, void *unused) { void (*func)(struct seq_file *) = s->private; func(s); return 0; } static int dss_debug_open(struct inode *inode, struct file *file) { return single_open(file, dss_debug_show, inode->i_private); } static const struct file_operations dss_debug_fops = { .open = dss_debug_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *dss_debugfs_dir; static int dss_initialize_debugfs(void) { dss_debugfs_dir = debugfs_create_dir("omapdss", NULL); if (IS_ERR(dss_debugfs_dir)) { int err = PTR_ERR(dss_debugfs_dir); dss_debugfs_dir = NULL; return err; } debugfs_create_file("clk", S_IRUGO, dss_debugfs_dir, &dss_debug_dump_clocks, &dss_debug_fops); #ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS debugfs_create_file("dispc_irq", S_IRUGO, dss_debugfs_dir, &dispc_dump_irqs, &dss_debug_fops); #endif #if defined(CONFIG_OMAP2_DSS_DSI) && defined(CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS) dsi_create_debugfs_files_irq(dss_debugfs_dir, &dss_debug_fops); #endif debugfs_create_file("dss", S_IRUGO, dss_debugfs_dir, &dss_dump_regs, &dss_debug_fops); debugfs_create_file("dispc", S_IRUGO, dss_debugfs_dir, &dispc_dump_regs, &dss_debug_fops); #ifdef CONFIG_OMAP2_DSS_RFBI debugfs_create_file("rfbi", S_IRUGO, dss_debugfs_dir, &rfbi_dump_regs, &dss_debug_fops); #endif #ifdef CONFIG_OMAP2_DSS_DSI dsi_create_debugfs_files_reg(dss_debugfs_dir, &dss_debug_fops); #endif #ifdef CONFIG_OMAP2_DSS_VENC debugfs_create_file("venc", S_IRUGO, dss_debugfs_dir, &venc_dump_regs, &dss_debug_fops); #endif return 0; } static void dss_uninitialize_debugfs(void) { if (dss_debugfs_dir) debugfs_remove_recursive(dss_debugfs_dir); } #else /* CONFIG_DEBUG_FS && CONFIG_OMAP2_DSS_DEBUG_SUPPORT */ static inline int dss_initialize_debugfs(void) { return 0; } static inline void dss_uninitialize_debugfs(void) { } #endif /* CONFIG_DEBUG_FS && CONFIG_OMAP2_DSS_DEBUG_SUPPORT */ /* PLATFORM DEVICE */ static int omap_dss_probe(struct platform_device *pdev) { struct omap_dss_board_info *pdata = pdev->dev.platform_data; int r; int i; core.pdev = pdev; dss_features_init(); dss_init_overlay_managers(pdev); dss_init_overlays(pdev); r = dss_init_platform_driver(); if (r) { DSSERR("Failed to initialize DSS platform driver\n"); goto err_dss; } /* keep clocks enabled to prevent context saves/restores during init */ dss_clk_enable(DSS_CLK_ICK | DSS_CLK_FCK); r = rfbi_init_platform_driver(); if (r) { DSSERR("Failed to initialize rfbi platform driver\n"); goto err_rfbi; } r = dispc_init_platform_driver(); if (r) { DSSERR("Failed to initialize dispc platform driver\n"); goto err_dispc; } r = venc_init_platform_driver(); if (r) { DSSERR("Failed to initialize venc platform driver\n"); goto err_venc; } r = dsi_init_platform_driver(); if (r) { DSSERR("Failed to initialize DSI platform driver\n"); goto err_dsi; } r = hdmi_init_platform_driver(); if (r) { DSSERR("Failed to initialize hdmi\n"); goto err_hdmi; } r = dss_initialize_debugfs(); if (r) goto err_debugfs; for (i = 0; i < pdata->num_devices; ++i) { struct omap_dss_device *dssdev = pdata->devices[i]; r = omap_dss_register_device(dssdev); if (r) { DSSERR("device %d %s register failed %d\n", i, dssdev->name ?: "unnamed", r); while (--i >= 0) omap_dss_unregister_device(pdata->devices[i]); goto err_register; } if (def_disp_name && strcmp(def_disp_name, dssdev->name) == 0) pdata->default_device = dssdev; } dss_clk_disable(DSS_CLK_ICK | DSS_CLK_FCK); return 0; err_register: dss_uninitialize_debugfs(); err_debugfs: hdmi_uninit_platform_driver(); err_hdmi: dsi_uninit_platform_driver(); err_dsi: venc_uninit_platform_driver(); err_venc: dispc_uninit_platform_driver(); err_dispc: rfbi_uninit_platform_driver(); err_rfbi: dss_uninit_platform_driver(); err_dss: return r; } static int omap_dss_remove(struct platform_device *pdev) { struct omap_dss_board_info *pdata = pdev->dev.platform_data; int i; dss_uninitialize_debugfs(); venc_uninit_platform_driver(); dispc_uninit_platform_driver(); rfbi_uninit_platform_driver(); dsi_uninit_platform_driver(); hdmi_uninit_platform_driver(); dss_uninit_platform_driver(); dss_uninit_overlays(pdev); dss_uninit_overlay_managers(pdev); for (i = 0; i < pdata->num_devices; ++i) omap_dss_unregister_device(pdata->devices[i]); return 0; } static void omap_dss_shutdown(struct platform_device *pdev) { DSSDBG("shutdown\n"); dss_disable_all_devices(); } static int omap_dss_suspend(struct platform_device *pdev, pm_message_t state) { DSSDBG("suspend %d\n", state.event); return dss_suspend_all_devices(); } static int omap_dss_resume(struct platform_device *pdev) { DSSDBG("resume\n"); return dss_resume_all_devices(); } static struct platform_driver omap_dss_driver = { .probe = omap_dss_probe, .remove = omap_dss_remove, .shutdown = omap_dss_shutdown, .suspend = omap_dss_suspend, .resume = omap_dss_resume, .driver = { .name = "omapdss", .owner = THIS_MODULE, }, }; /* BUS */ static int dss_bus_match(struct device *dev, struct device_driver *driver) { struct omap_dss_device *dssdev = to_dss_device(dev); DSSDBG("bus_match. dev %s/%s, drv %s\n", dev_name(dev), dssdev->driver_name, driver->name); return strcmp(dssdev->driver_name, driver->name) == 0; } static ssize_t device_name_show(struct device *dev, struct device_attribute *attr, char *buf) { struct omap_dss_device *dssdev = to_dss_device(dev); return snprintf(buf, PAGE_SIZE, "%s\n", dssdev->name ? dssdev->name : ""); } static struct device_attribute default_dev_attrs[] = { __ATTR(name, S_IRUGO, device_name_show, NULL), __ATTR_NULL, }; static ssize_t driver_name_show(struct device_driver *drv, char *buf) { struct omap_dss_driver *dssdrv = to_dss_driver(drv); return snprintf(buf, PAGE_SIZE, "%s\n", dssdrv->driver.name ? dssdrv->driver.name : ""); } static struct driver_attribute default_drv_attrs[] = { __ATTR(name, S_IRUGO, driver_name_show, NULL), __ATTR_NULL, }; static struct bus_type dss_bus_type = { .name = "omapdss", .match = dss_bus_match, .dev_attrs = default_dev_attrs, .drv_attrs = default_drv_attrs, }; static void dss_bus_release(struct device *dev) { DSSDBG("bus_release\n"); } static struct device dss_bus = { .release = dss_bus_release, }; struct bus_type *dss_get_bus(void) { return &dss_bus_type; } /* DRIVER */ static int dss_driver_probe(struct device *dev) { int r; struct omap_dss_driver *dssdrv = to_dss_driver(dev->driver); struct omap_dss_device *dssdev = to_dss_device(dev); struct omap_dss_board_info *pdata = core.pdev->dev.platform_data; bool force; DSSDBG("driver_probe: dev %s/%s, drv %s\n", dev_name(dev), dssdev->driver_name, dssdrv->driver.name); dss_init_device(core.pdev, dssdev); force = pdata->default_device == dssdev; dss_recheck_connections(dssdev, force); r = dssdrv->probe(dssdev); if (r) { DSSERR("driver probe failed: %d\n", r); dss_uninit_device(core.pdev, dssdev); return r; } DSSDBG("probe done for device %s\n", dev_name(dev)); dssdev->driver = dssdrv; return 0; } static int dss_driver_remove(struct device *dev) { struct omap_dss_driver *dssdrv = to_dss_driver(dev->driver); struct omap_dss_device *dssdev = to_dss_device(dev); DSSDBG("driver_remove: dev %s/%s\n", dev_name(dev), dssdev->driver_name); dssdrv->remove(dssdev); dss_uninit_device(core.pdev, dssdev); dssdev->driver = NULL; return 0; } int omap_dss_register_driver(struct omap_dss_driver *dssdriver) { dssdriver->driver.bus = &dss_bus_type; dssdriver->driver.probe = dss_driver_probe; dssdriver->driver.remove = dss_driver_remove; if (dssdriver->get_resolution == NULL) dssdriver->get_resolution = omapdss_default_get_resolution; if (dssdriver->get_recommended_bpp == NULL) dssdriver->get_recommended_bpp = omapdss_default_get_recommended_bpp; return driver_register(&dssdriver->driver); } EXPORT_SYMBOL(omap_dss_register_driver); void omap_dss_unregister_driver(struct omap_dss_driver *dssdriver) { driver_unregister(&dssdriver->driver); } EXPORT_SYMBOL(omap_dss_unregister_driver); /* DEVICE */ static void reset_device(struct device *dev, int check) { u8 *dev_p = (u8 *)dev; u8 *dev_end = dev_p + sizeof(*dev); void *saved_pdata; saved_pdata = dev->platform_data; if (check) { /* * Check if there is any other setting than platform_data * in struct device; warn that these will be reset by our * init. */ dev->platform_data = NULL; while (dev_p < dev_end) { if (*dev_p) { WARN("%s: struct device fields will be " "discarded\n", __func__); break; } dev_p++; } } memset(dev, 0, sizeof(*dev)); dev->platform_data = saved_pdata; } static void omap_dss_dev_release(struct device *dev) { reset_device(dev, 0); } static int omap_dss_register_device(struct omap_dss_device *dssdev) { static int dev_num; WARN_ON(!dssdev->driver_name); reset_device(&dssdev->dev, 1); dssdev->dev.bus = &dss_bus_type; dssdev->dev.parent = &dss_bus; dssdev->dev.release = omap_dss_dev_release; dev_set_name(&dssdev->dev, "display%d", dev_num++); return device_register(&dssdev->dev); } static void omap_dss_unregister_device(struct omap_dss_device *dssdev) { device_unregister(&dssdev->dev); } /* BUS */ static int omap_dss_bus_register(void) { int r; r = bus_register(&dss_bus_type); if (r) { DSSERR("bus register failed\n"); return r; } dev_set_name(&dss_bus, "omapdss"); r = device_register(&dss_bus); if (r) { DSSERR("bus driver register failed\n"); bus_unregister(&dss_bus_type); return r; } return 0; } /* INIT */ #ifdef CONFIG_OMAP2_DSS_MODULE static void omap_dss_bus_unregister(void) { device_unregister(&dss_bus); bus_unregister(&dss_bus_type); } static int __init omap_dss_init(void) { int r; r = omap_dss_bus_register(); if (r) return r; r = platform_driver_register(&omap_dss_driver); if (r) { omap_dss_bus_unregister(); return r; } return 0; } static void __exit omap_dss_exit(void) { if (core.vdds_dsi_reg != NULL) { regulator_put(core.vdds_dsi_reg); core.vdds_dsi_reg = NULL; } if (core.vdds_sdi_reg != NULL) { regulator_put(core.vdds_sdi_reg); core.vdds_sdi_reg = NULL; } platform_driver_unregister(&omap_dss_driver); omap_dss_bus_unregister(); } module_init(omap_dss_init); module_exit(omap_dss_exit); #else static int __init omap_dss_init(void) { return omap_dss_bus_register(); } static int __init omap_dss_init2(void) { return platform_driver_register(&omap_dss_driver); } core_initcall(omap_dss_init); device_initcall(omap_dss_init2); #endif MODULE_AUTHOR("Tomi Valkeinen <tomi.valkeinen@nokia.com>"); MODULE_DESCRIPTION("OMAP2/3 Display Subsystem"); MODULE_LICENSE("GPL v2");
gpl-2.0
knone1/android_kernel_asus_moorefield-backup
drivers/pwm/core.c
2072
19372
/* * Generic pwmlib implementation * * Copyright (C) 2011 Sascha Hauer <s.hauer@pengutronix.de> * Copyright (C) 2011-2012 Avionic Design GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/module.h> #include <linux/pwm.h> #include <linux/radix-tree.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/device.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #define MAX_PWMS 1024 /* flags in the third cell of the DT PWM specifier */ #define PWM_SPEC_POLARITY (1 << 0) static DEFINE_MUTEX(pwm_lookup_lock); static LIST_HEAD(pwm_lookup_list); static DEFINE_MUTEX(pwm_lock); static LIST_HEAD(pwm_chips); static DECLARE_BITMAP(allocated_pwms, MAX_PWMS); static RADIX_TREE(pwm_tree, GFP_KERNEL); static struct pwm_device *pwm_to_device(unsigned int pwm) { return radix_tree_lookup(&pwm_tree, pwm); } static int alloc_pwms(int pwm, unsigned int count) { unsigned int from = 0; unsigned int start; if (pwm >= MAX_PWMS) return -EINVAL; if (pwm >= 0) from = pwm; start = bitmap_find_next_zero_area(allocated_pwms, MAX_PWMS, from, count, 0); if (pwm >= 0 && start != pwm) return -EEXIST; if (start + count > MAX_PWMS) return -ENOSPC; return start; } static void free_pwms(struct pwm_chip *chip) { unsigned int i; for (i = 0; i < chip->npwm; i++) { struct pwm_device *pwm = &chip->pwms[i]; radix_tree_delete(&pwm_tree, pwm->pwm); } bitmap_clear(allocated_pwms, chip->base, chip->npwm); kfree(chip->pwms); chip->pwms = NULL; } static struct pwm_chip *pwmchip_find_by_name(const char *name) { struct pwm_chip *chip; if (!name) return NULL; mutex_lock(&pwm_lock); list_for_each_entry(chip, &pwm_chips, list) { const char *chip_name = dev_name(chip->dev); if (chip_name && strcmp(chip_name, name) == 0) { mutex_unlock(&pwm_lock); return chip; } } mutex_unlock(&pwm_lock); return NULL; } static int pwm_device_request(struct pwm_device *pwm, const char *label) { int err; if (test_bit(PWMF_REQUESTED, &pwm->flags)) return -EBUSY; if (!try_module_get(pwm->chip->ops->owner)) return -ENODEV; if (pwm->chip->ops->request) { err = pwm->chip->ops->request(pwm->chip, pwm); if (err) { module_put(pwm->chip->ops->owner); return err; } } set_bit(PWMF_REQUESTED, &pwm->flags); pwm->label = label; return 0; } struct pwm_device * of_pwm_xlate_with_flags(struct pwm_chip *pc, const struct of_phandle_args *args) { struct pwm_device *pwm; if (pc->of_pwm_n_cells < 3) return ERR_PTR(-EINVAL); if (args->args[0] >= pc->npwm) return ERR_PTR(-EINVAL); pwm = pwm_request_from_chip(pc, args->args[0], NULL); if (IS_ERR(pwm)) return pwm; pwm_set_period(pwm, args->args[1]); if (args->args[2] & PWM_SPEC_POLARITY) pwm_set_polarity(pwm, PWM_POLARITY_INVERSED); else pwm_set_polarity(pwm, PWM_POLARITY_NORMAL); return pwm; } EXPORT_SYMBOL_GPL(of_pwm_xlate_with_flags); static struct pwm_device * of_pwm_simple_xlate(struct pwm_chip *pc, const struct of_phandle_args *args) { struct pwm_device *pwm; if (pc->of_pwm_n_cells < 2) return ERR_PTR(-EINVAL); if (args->args[0] >= pc->npwm) return ERR_PTR(-EINVAL); pwm = pwm_request_from_chip(pc, args->args[0], NULL); if (IS_ERR(pwm)) return pwm; pwm_set_period(pwm, args->args[1]); return pwm; } static void of_pwmchip_add(struct pwm_chip *chip) { if (!chip->dev || !chip->dev->of_node) return; if (!chip->of_xlate) { chip->of_xlate = of_pwm_simple_xlate; chip->of_pwm_n_cells = 2; } of_node_get(chip->dev->of_node); } static void of_pwmchip_remove(struct pwm_chip *chip) { if (chip->dev && chip->dev->of_node) of_node_put(chip->dev->of_node); } /** * pwm_set_chip_data() - set private chip data for a PWM * @pwm: PWM device * @data: pointer to chip-specific data */ int pwm_set_chip_data(struct pwm_device *pwm, void *data) { if (!pwm) return -EINVAL; pwm->chip_data = data; return 0; } EXPORT_SYMBOL_GPL(pwm_set_chip_data); /** * pwm_get_chip_data() - get private chip data for a PWM * @pwm: PWM device */ void *pwm_get_chip_data(struct pwm_device *pwm) { return pwm ? pwm->chip_data : NULL; } EXPORT_SYMBOL_GPL(pwm_get_chip_data); /** * pwmchip_add() - register a new PWM chip * @chip: the PWM chip to add * * Register a new PWM chip. If chip->base < 0 then a dynamically assigned base * will be used. */ int pwmchip_add(struct pwm_chip *chip) { struct pwm_device *pwm; unsigned int i; int ret; if (!chip || !chip->dev || !chip->ops || !chip->ops->config || !chip->ops->enable || !chip->ops->disable) return -EINVAL; mutex_lock(&pwm_lock); ret = alloc_pwms(chip->base, chip->npwm); if (ret < 0) goto out; chip->pwms = kzalloc(chip->npwm * sizeof(*pwm), GFP_KERNEL); if (!chip->pwms) { ret = -ENOMEM; goto out; } chip->base = ret; for (i = 0; i < chip->npwm; i++) { pwm = &chip->pwms[i]; pwm->chip = chip; pwm->pwm = chip->base + i; pwm->hwpwm = i; radix_tree_insert(&pwm_tree, pwm->pwm, pwm); } bitmap_set(allocated_pwms, chip->base, chip->npwm); INIT_LIST_HEAD(&chip->list); list_add(&chip->list, &pwm_chips); ret = 0; if (IS_ENABLED(CONFIG_OF)) of_pwmchip_add(chip); out: mutex_unlock(&pwm_lock); return ret; } EXPORT_SYMBOL_GPL(pwmchip_add); /** * pwmchip_remove() - remove a PWM chip * @chip: the PWM chip to remove * * Removes a PWM chip. This function may return busy if the PWM chip provides * a PWM device that is still requested. */ int pwmchip_remove(struct pwm_chip *chip) { unsigned int i; int ret = 0; mutex_lock(&pwm_lock); for (i = 0; i < chip->npwm; i++) { struct pwm_device *pwm = &chip->pwms[i]; if (test_bit(PWMF_REQUESTED, &pwm->flags)) { ret = -EBUSY; goto out; } } list_del_init(&chip->list); if (IS_ENABLED(CONFIG_OF)) of_pwmchip_remove(chip); free_pwms(chip); out: mutex_unlock(&pwm_lock); return ret; } EXPORT_SYMBOL_GPL(pwmchip_remove); /** * pwm_request() - request a PWM device * @pwm_id: global PWM device index * @label: PWM device label * * This function is deprecated, use pwm_get() instead. */ struct pwm_device *pwm_request(int pwm, const char *label) { struct pwm_device *dev; int err; if (pwm < 0 || pwm >= MAX_PWMS) return ERR_PTR(-EINVAL); mutex_lock(&pwm_lock); dev = pwm_to_device(pwm); if (!dev) { dev = ERR_PTR(-EPROBE_DEFER); goto out; } err = pwm_device_request(dev, label); if (err < 0) dev = ERR_PTR(err); out: mutex_unlock(&pwm_lock); return dev; } EXPORT_SYMBOL_GPL(pwm_request); /** * pwm_request_from_chip() - request a PWM device relative to a PWM chip * @chip: PWM chip * @index: per-chip index of the PWM to request * @label: a literal description string of this PWM * * Returns the PWM at the given index of the given PWM chip. A negative error * code is returned if the index is not valid for the specified PWM chip or * if the PWM device cannot be requested. */ struct pwm_device *pwm_request_from_chip(struct pwm_chip *chip, unsigned int index, const char *label) { struct pwm_device *pwm; int err; if (!chip || index >= chip->npwm) return ERR_PTR(-EINVAL); mutex_lock(&pwm_lock); pwm = &chip->pwms[index]; err = pwm_device_request(pwm, label); if (err < 0) pwm = ERR_PTR(err); mutex_unlock(&pwm_lock); return pwm; } EXPORT_SYMBOL_GPL(pwm_request_from_chip); /** * pwm_free() - free a PWM device * @pwm: PWM device * * This function is deprecated, use pwm_put() instead. */ void pwm_free(struct pwm_device *pwm) { pwm_put(pwm); } EXPORT_SYMBOL_GPL(pwm_free); /** * pwm_config() - change a PWM device configuration * @pwm: PWM device * @duty_ns: "on" time (in nanoseconds) * @period_ns: duration (in nanoseconds) of one cycle */ int pwm_config(struct pwm_device *pwm, int duty_ns, int period_ns) { if (!pwm || duty_ns < 0 || period_ns <= 0 || duty_ns > period_ns) return -EINVAL; return pwm->chip->ops->config(pwm->chip, pwm, duty_ns, period_ns); } EXPORT_SYMBOL_GPL(pwm_config); /** * pwm_set_polarity() - configure the polarity of a PWM signal * @pwm: PWM device * @polarity: new polarity of the PWM signal * * Note that the polarity cannot be configured while the PWM device is enabled */ int pwm_set_polarity(struct pwm_device *pwm, enum pwm_polarity polarity) { if (!pwm || !pwm->chip->ops) return -EINVAL; if (!pwm->chip->ops->set_polarity) return -ENOSYS; if (test_bit(PWMF_ENABLED, &pwm->flags)) return -EBUSY; return pwm->chip->ops->set_polarity(pwm->chip, pwm, polarity); } EXPORT_SYMBOL_GPL(pwm_set_polarity); /** * pwm_enable() - start a PWM output toggling * @pwm: PWM device */ int pwm_enable(struct pwm_device *pwm) { if (pwm && !test_and_set_bit(PWMF_ENABLED, &pwm->flags)) return pwm->chip->ops->enable(pwm->chip, pwm); return pwm ? 0 : -EINVAL; } EXPORT_SYMBOL_GPL(pwm_enable); /** * pwm_disable() - stop a PWM output toggling * @pwm: PWM device */ void pwm_disable(struct pwm_device *pwm) { if (pwm && test_and_clear_bit(PWMF_ENABLED, &pwm->flags)) pwm->chip->ops->disable(pwm->chip, pwm); } EXPORT_SYMBOL_GPL(pwm_disable); static struct pwm_chip *of_node_to_pwmchip(struct device_node *np) { struct pwm_chip *chip; mutex_lock(&pwm_lock); list_for_each_entry(chip, &pwm_chips, list) if (chip->dev && chip->dev->of_node == np) { mutex_unlock(&pwm_lock); return chip; } mutex_unlock(&pwm_lock); return ERR_PTR(-EPROBE_DEFER); } /** * of_pwm_get() - request a PWM via the PWM framework * @np: device node to get the PWM from * @con_id: consumer name * * Returns the PWM device parsed from the phandle and index specified in the * "pwms" property of a device tree node or a negative error-code on failure. * Values parsed from the device tree are stored in the returned PWM device * object. * * If con_id is NULL, the first PWM device listed in the "pwms" property will * be requested. Otherwise the "pwm-names" property is used to do a reverse * lookup of the PWM index. This also means that the "pwm-names" property * becomes mandatory for devices that look up the PWM device via the con_id * parameter. */ struct pwm_device *of_pwm_get(struct device_node *np, const char *con_id) { struct pwm_device *pwm = NULL; struct of_phandle_args args; struct pwm_chip *pc; int index = 0; int err; if (con_id) { index = of_property_match_string(np, "pwm-names", con_id); if (index < 0) return ERR_PTR(index); } err = of_parse_phandle_with_args(np, "pwms", "#pwm-cells", index, &args); if (err) { pr_debug("%s(): can't parse \"pwms\" property\n", __func__); return ERR_PTR(err); } pc = of_node_to_pwmchip(args.np); if (IS_ERR(pc)) { pr_debug("%s(): PWM chip not found\n", __func__); pwm = ERR_CAST(pc); goto put; } if (args.args_count != pc->of_pwm_n_cells) { pr_debug("%s: wrong #pwm-cells for %s\n", np->full_name, args.np->full_name); pwm = ERR_PTR(-EINVAL); goto put; } pwm = pc->of_xlate(pc, &args); if (IS_ERR(pwm)) goto put; /* * If a consumer name was not given, try to look it up from the * "pwm-names" property if it exists. Otherwise use the name of * the user device node. */ if (!con_id) { err = of_property_read_string_index(np, "pwm-names", index, &con_id); if (err < 0) con_id = np->name; } pwm->label = con_id; put: of_node_put(args.np); return pwm; } EXPORT_SYMBOL_GPL(of_pwm_get); /** * pwm_add_table() - register PWM device consumers * @table: array of consumers to register * @num: number of consumers in table */ void __init pwm_add_table(struct pwm_lookup *table, size_t num) { mutex_lock(&pwm_lookup_lock); while (num--) { list_add_tail(&table->list, &pwm_lookup_list); table++; } mutex_unlock(&pwm_lookup_lock); } /** * pwm_get() - look up and request a PWM device * @dev: device for PWM consumer * @con_id: consumer name * * Lookup is first attempted using DT. If the device was not instantiated from * a device tree, a PWM chip and a relative index is looked up via a table * supplied by board setup code (see pwm_add_table()). * * Once a PWM chip has been found the specified PWM device will be requested * and is ready to be used. */ struct pwm_device *pwm_get(struct device *dev, const char *con_id) { struct pwm_device *pwm = ERR_PTR(-EPROBE_DEFER); const char *dev_id = dev ? dev_name(dev) : NULL; struct pwm_chip *chip = NULL; unsigned int index = 0; unsigned int best = 0; struct pwm_lookup *p; unsigned int match; /* look up via DT first */ if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node) return of_pwm_get(dev->of_node, con_id); /* * We look up the provider in the static table typically provided by * board setup code. We first try to lookup the consumer device by * name. If the consumer device was passed in as NULL or if no match * was found, we try to find the consumer by directly looking it up * by name. * * If a match is found, the provider PWM chip is looked up by name * and a PWM device is requested using the PWM device per-chip index. * * The lookup algorithm was shamelessly taken from the clock * framework: * * We do slightly fuzzy matching here: * An entry with a NULL ID is assumed to be a wildcard. * If an entry has a device ID, it must match * If an entry has a connection ID, it must match * Then we take the most specific entry - with the following order * of precedence: dev+con > dev only > con only. */ mutex_lock(&pwm_lookup_lock); list_for_each_entry(p, &pwm_lookup_list, list) { match = 0; if (p->dev_id) { if (!dev_id || strcmp(p->dev_id, dev_id)) continue; match += 2; } if (p->con_id) { if (!con_id || strcmp(p->con_id, con_id)) continue; match += 1; } if (match > best) { chip = pwmchip_find_by_name(p->provider); index = p->index; if (match != 3) best = match; else break; } } if (chip) pwm = pwm_request_from_chip(chip, index, con_id ?: dev_id); mutex_unlock(&pwm_lookup_lock); return pwm; } EXPORT_SYMBOL_GPL(pwm_get); /** * pwm_put() - release a PWM device * @pwm: PWM device */ void pwm_put(struct pwm_device *pwm) { if (!pwm) return; mutex_lock(&pwm_lock); if (!test_and_clear_bit(PWMF_REQUESTED, &pwm->flags)) { pr_warn("PWM device already freed\n"); goto out; } if (pwm->chip->ops->free) pwm->chip->ops->free(pwm->chip, pwm); pwm->label = NULL; module_put(pwm->chip->ops->owner); out: mutex_unlock(&pwm_lock); } EXPORT_SYMBOL_GPL(pwm_put); static void devm_pwm_release(struct device *dev, void *res) { pwm_put(*(struct pwm_device **)res); } /** * devm_pwm_get() - resource managed pwm_get() * @dev: device for PWM consumer * @con_id: consumer name * * This function performs like pwm_get() but the acquired PWM device will * automatically be released on driver detach. */ struct pwm_device *devm_pwm_get(struct device *dev, const char *con_id) { struct pwm_device **ptr, *pwm; ptr = devres_alloc(devm_pwm_release, sizeof(**ptr), GFP_KERNEL); if (!ptr) return ERR_PTR(-ENOMEM); pwm = pwm_get(dev, con_id); if (!IS_ERR(pwm)) { *ptr = pwm; devres_add(dev, ptr); } else { devres_free(ptr); } return pwm; } EXPORT_SYMBOL_GPL(devm_pwm_get); /** * devm_of_pwm_get() - resource managed of_pwm_get() * @dev: device for PWM consumer * @np: device node to get the PWM from * @con_id: consumer name * * This function performs like of_pwm_get() but the acquired PWM device will * automatically be released on driver detach. */ struct pwm_device *devm_of_pwm_get(struct device *dev, struct device_node *np, const char *con_id) { struct pwm_device **ptr, *pwm; ptr = devres_alloc(devm_pwm_release, sizeof(**ptr), GFP_KERNEL); if (!ptr) return ERR_PTR(-ENOMEM); pwm = of_pwm_get(np, con_id); if (!IS_ERR(pwm)) { *ptr = pwm; devres_add(dev, ptr); } else { devres_free(ptr); } return pwm; } EXPORT_SYMBOL_GPL(devm_of_pwm_get); static int devm_pwm_match(struct device *dev, void *res, void *data) { struct pwm_device **p = res; if (WARN_ON(!p || !*p)) return 0; return *p == data; } /** * devm_pwm_put() - resource managed pwm_put() * @dev: device for PWM consumer * @pwm: PWM device * * Release a PWM previously allocated using devm_pwm_get(). Calling this * function is usually not needed because devm-allocated resources are * automatically released on driver detach. */ void devm_pwm_put(struct device *dev, struct pwm_device *pwm) { WARN_ON(devres_release(dev, devm_pwm_release, devm_pwm_match, pwm)); } EXPORT_SYMBOL_GPL(devm_pwm_put); /** * pwm_can_sleep() - report whether PWM access will sleep * @pwm: PWM device * * It returns true if accessing the PWM can sleep, false otherwise. */ bool pwm_can_sleep(struct pwm_device *pwm) { return pwm->chip->can_sleep; } EXPORT_SYMBOL_GPL(pwm_can_sleep); #ifdef CONFIG_DEBUG_FS static void pwm_dbg_show(struct pwm_chip *chip, struct seq_file *s) { unsigned int i; for (i = 0; i < chip->npwm; i++) { struct pwm_device *pwm = &chip->pwms[i]; seq_printf(s, " pwm-%-3d (%-20.20s):", i, pwm->label); if (test_bit(PWMF_REQUESTED, &pwm->flags)) seq_printf(s, " requested"); if (test_bit(PWMF_ENABLED, &pwm->flags)) seq_printf(s, " enabled"); seq_printf(s, "\n"); } } static void *pwm_seq_start(struct seq_file *s, loff_t *pos) { mutex_lock(&pwm_lock); s->private = ""; return seq_list_start(&pwm_chips, *pos); } static void *pwm_seq_next(struct seq_file *s, void *v, loff_t *pos) { s->private = "\n"; return seq_list_next(v, &pwm_chips, pos); } static void pwm_seq_stop(struct seq_file *s, void *v) { mutex_unlock(&pwm_lock); } static int pwm_seq_show(struct seq_file *s, void *v) { struct pwm_chip *chip = list_entry(v, struct pwm_chip, list); seq_printf(s, "%s%s/%s, %d PWM device%s\n", (char *)s->private, chip->dev->bus ? chip->dev->bus->name : "no-bus", dev_name(chip->dev), chip->npwm, (chip->npwm != 1) ? "s" : ""); if (chip->ops->dbg_show) chip->ops->dbg_show(chip, s); else pwm_dbg_show(chip, s); return 0; } static const struct seq_operations pwm_seq_ops = { .start = pwm_seq_start, .next = pwm_seq_next, .stop = pwm_seq_stop, .show = pwm_seq_show, }; static int pwm_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &pwm_seq_ops); } static const struct file_operations pwm_debugfs_ops = { .owner = THIS_MODULE, .open = pwm_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static int __init pwm_debugfs_init(void) { debugfs_create_file("pwm", S_IFREG | S_IRUGO, NULL, NULL, &pwm_debugfs_ops); return 0; } subsys_initcall(pwm_debugfs_init); #endif /* CONFIG_DEBUG_FS */
gpl-2.0
metacloud/linux
arch/powerpc/kvm/44x_tlb.c
2072
14247
/* * 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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright IBM Corp. 2007 * * Authors: Hollis Blanchard <hollisb@us.ibm.com> */ #include <linux/types.h> #include <linux/string.h> #include <linux/kvm.h> #include <linux/kvm_host.h> #include <linux/highmem.h> #include <asm/tlbflush.h> #include <asm/mmu-44x.h> #include <asm/kvm_ppc.h> #include <asm/kvm_44x.h> #include "timing.h" #include "44x_tlb.h" #include "trace.h" #ifndef PPC44x_TLBE_SIZE #define PPC44x_TLBE_SIZE PPC44x_TLB_4K #endif #define PAGE_SIZE_4K (1<<12) #define PAGE_MASK_4K (~(PAGE_SIZE_4K - 1)) #define PPC44x_TLB_UATTR_MASK \ (PPC44x_TLB_U0|PPC44x_TLB_U1|PPC44x_TLB_U2|PPC44x_TLB_U3) #define PPC44x_TLB_USER_PERM_MASK (PPC44x_TLB_UX|PPC44x_TLB_UR|PPC44x_TLB_UW) #define PPC44x_TLB_SUPER_PERM_MASK (PPC44x_TLB_SX|PPC44x_TLB_SR|PPC44x_TLB_SW) #ifdef DEBUG void kvmppc_dump_tlbs(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); struct kvmppc_44x_tlbe *tlbe; int i; printk("vcpu %d TLB dump:\n", vcpu->vcpu_id); printk("| %2s | %3s | %8s | %8s | %8s |\n", "nr", "tid", "word0", "word1", "word2"); for (i = 0; i < ARRAY_SIZE(vcpu_44x->guest_tlb); i++) { tlbe = &vcpu_44x->guest_tlb[i]; if (tlbe->word0 & PPC44x_TLB_VALID) printk(" G%2d | %02X | %08X | %08X | %08X |\n", i, tlbe->tid, tlbe->word0, tlbe->word1, tlbe->word2); } } #endif static inline void kvmppc_44x_tlbie(unsigned int index) { /* 0 <= index < 64, so the V bit is clear and we can use the index as * word0. */ asm volatile( "tlbwe %[index], %[index], 0\n" : : [index] "r"(index) ); } static inline void kvmppc_44x_tlbre(unsigned int index, struct kvmppc_44x_tlbe *tlbe) { asm volatile( "tlbre %[word0], %[index], 0\n" "mfspr %[tid], %[sprn_mmucr]\n" "andi. %[tid], %[tid], 0xff\n" "tlbre %[word1], %[index], 1\n" "tlbre %[word2], %[index], 2\n" : [word0] "=r"(tlbe->word0), [word1] "=r"(tlbe->word1), [word2] "=r"(tlbe->word2), [tid] "=r"(tlbe->tid) : [index] "r"(index), [sprn_mmucr] "i"(SPRN_MMUCR) : "cc" ); } static inline void kvmppc_44x_tlbwe(unsigned int index, struct kvmppc_44x_tlbe *stlbe) { unsigned long tmp; asm volatile( "mfspr %[tmp], %[sprn_mmucr]\n" "rlwimi %[tmp], %[tid], 0, 0xff\n" "mtspr %[sprn_mmucr], %[tmp]\n" "tlbwe %[word0], %[index], 0\n" "tlbwe %[word1], %[index], 1\n" "tlbwe %[word2], %[index], 2\n" : [tmp] "=&r"(tmp) : [word0] "r"(stlbe->word0), [word1] "r"(stlbe->word1), [word2] "r"(stlbe->word2), [tid] "r"(stlbe->tid), [index] "r"(index), [sprn_mmucr] "i"(SPRN_MMUCR) ); } static u32 kvmppc_44x_tlb_shadow_attrib(u32 attrib, int usermode) { /* We only care about the guest's permission and user bits. */ attrib &= PPC44x_TLB_PERM_MASK|PPC44x_TLB_UATTR_MASK; if (!usermode) { /* Guest is in supervisor mode, so we need to translate guest * supervisor permissions into user permissions. */ attrib &= ~PPC44x_TLB_USER_PERM_MASK; attrib |= (attrib & PPC44x_TLB_SUPER_PERM_MASK) << 3; } /* Make sure host can always access this memory. */ attrib |= PPC44x_TLB_SX|PPC44x_TLB_SR|PPC44x_TLB_SW; /* WIMGE = 0b00100 */ attrib |= PPC44x_TLB_M; return attrib; } /* Load shadow TLB back into hardware. */ void kvmppc_44x_tlb_load(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); int i; for (i = 0; i <= tlb_44x_hwater; i++) { struct kvmppc_44x_tlbe *stlbe = &vcpu_44x->shadow_tlb[i]; if (get_tlb_v(stlbe) && get_tlb_ts(stlbe)) kvmppc_44x_tlbwe(i, stlbe); } } static void kvmppc_44x_tlbe_set_modified(struct kvmppc_vcpu_44x *vcpu_44x, unsigned int i) { vcpu_44x->shadow_tlb_mod[i] = 1; } /* Save hardware TLB to the vcpu, and invalidate all guest mappings. */ void kvmppc_44x_tlb_put(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); int i; for (i = 0; i <= tlb_44x_hwater; i++) { struct kvmppc_44x_tlbe *stlbe = &vcpu_44x->shadow_tlb[i]; if (vcpu_44x->shadow_tlb_mod[i]) kvmppc_44x_tlbre(i, stlbe); if (get_tlb_v(stlbe) && get_tlb_ts(stlbe)) kvmppc_44x_tlbie(i); } } /* Search the guest TLB for a matching entry. */ int kvmppc_44x_tlb_index(struct kvm_vcpu *vcpu, gva_t eaddr, unsigned int pid, unsigned int as) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); int i; /* XXX Replace loop with fancy data structures. */ for (i = 0; i < ARRAY_SIZE(vcpu_44x->guest_tlb); i++) { struct kvmppc_44x_tlbe *tlbe = &vcpu_44x->guest_tlb[i]; unsigned int tid; if (eaddr < get_tlb_eaddr(tlbe)) continue; if (eaddr > get_tlb_end(tlbe)) continue; tid = get_tlb_tid(tlbe); if (tid && (tid != pid)) continue; if (!get_tlb_v(tlbe)) continue; if (get_tlb_ts(tlbe) != as) continue; return i; } return -1; } gpa_t kvmppc_mmu_xlate(struct kvm_vcpu *vcpu, unsigned int gtlb_index, gva_t eaddr) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); struct kvmppc_44x_tlbe *gtlbe = &vcpu_44x->guest_tlb[gtlb_index]; unsigned int pgmask = get_tlb_bytes(gtlbe) - 1; return get_tlb_raddr(gtlbe) | (eaddr & pgmask); } int kvmppc_mmu_itlb_index(struct kvm_vcpu *vcpu, gva_t eaddr) { unsigned int as = !!(vcpu->arch.shared->msr & MSR_IS); return kvmppc_44x_tlb_index(vcpu, eaddr, vcpu->arch.pid, as); } int kvmppc_mmu_dtlb_index(struct kvm_vcpu *vcpu, gva_t eaddr) { unsigned int as = !!(vcpu->arch.shared->msr & MSR_DS); return kvmppc_44x_tlb_index(vcpu, eaddr, vcpu->arch.pid, as); } void kvmppc_mmu_itlb_miss(struct kvm_vcpu *vcpu) { } void kvmppc_mmu_dtlb_miss(struct kvm_vcpu *vcpu) { } static void kvmppc_44x_shadow_release(struct kvmppc_vcpu_44x *vcpu_44x, unsigned int stlb_index) { struct kvmppc_44x_shadow_ref *ref = &vcpu_44x->shadow_refs[stlb_index]; if (!ref->page) return; /* Discard from the TLB. */ /* Note: we could actually invalidate a host mapping, if the host overwrote * this TLB entry since we inserted a guest mapping. */ kvmppc_44x_tlbie(stlb_index); /* Now release the page. */ if (ref->writeable) kvm_release_page_dirty(ref->page); else kvm_release_page_clean(ref->page); ref->page = NULL; /* XXX set tlb_44x_index to stlb_index? */ trace_kvm_stlb_inval(stlb_index); } void kvmppc_mmu_destroy(struct kvm_vcpu *vcpu) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); int i; for (i = 0; i <= tlb_44x_hwater; i++) kvmppc_44x_shadow_release(vcpu_44x, i); } /** * kvmppc_mmu_map -- create a host mapping for guest memory * * If the guest wanted a larger page than the host supports, only the first * host page is mapped here and the rest are demand faulted. * * If the guest wanted a smaller page than the host page size, we map only the * guest-size page (i.e. not a full host page mapping). * * Caller must ensure that the specified guest TLB entry is safe to insert into * the shadow TLB. */ void kvmppc_mmu_map(struct kvm_vcpu *vcpu, u64 gvaddr, gpa_t gpaddr, unsigned int gtlb_index) { struct kvmppc_44x_tlbe stlbe; struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); struct kvmppc_44x_tlbe *gtlbe = &vcpu_44x->guest_tlb[gtlb_index]; struct kvmppc_44x_shadow_ref *ref; struct page *new_page; hpa_t hpaddr; gfn_t gfn; u32 asid = gtlbe->tid; u32 flags = gtlbe->word2; u32 max_bytes = get_tlb_bytes(gtlbe); unsigned int victim; /* Select TLB entry to clobber. Indirectly guard against races with the TLB * miss handler by disabling interrupts. */ local_irq_disable(); victim = ++tlb_44x_index; if (victim > tlb_44x_hwater) victim = 0; tlb_44x_index = victim; local_irq_enable(); /* Get reference to new page. */ gfn = gpaddr >> PAGE_SHIFT; new_page = gfn_to_page(vcpu->kvm, gfn); if (is_error_page(new_page)) { printk(KERN_ERR "Couldn't get guest page for gfn %llx!\n", (unsigned long long)gfn); return; } hpaddr = page_to_phys(new_page); /* Invalidate any previous shadow mappings. */ kvmppc_44x_shadow_release(vcpu_44x, victim); /* XXX Make sure (va, size) doesn't overlap any other * entries. 440x6 user manual says the result would be * "undefined." */ /* XXX what about AS? */ /* Force TS=1 for all guest mappings. */ stlbe.word0 = PPC44x_TLB_VALID | PPC44x_TLB_TS; if (max_bytes >= PAGE_SIZE) { /* Guest mapping is larger than or equal to host page size. We can use * a "native" host mapping. */ stlbe.word0 |= (gvaddr & PAGE_MASK) | PPC44x_TLBE_SIZE; } else { /* Guest mapping is smaller than host page size. We must restrict the * size of the mapping to be at most the smaller of the two, but for * simplicity we fall back to a 4K mapping (this is probably what the * guest is using anyways). */ stlbe.word0 |= (gvaddr & PAGE_MASK_4K) | PPC44x_TLB_4K; /* 'hpaddr' is a host page, which is larger than the mapping we're * inserting here. To compensate, we must add the in-page offset to the * sub-page. */ hpaddr |= gpaddr & (PAGE_MASK ^ PAGE_MASK_4K); } stlbe.word1 = (hpaddr & 0xfffffc00) | ((hpaddr >> 32) & 0xf); stlbe.word2 = kvmppc_44x_tlb_shadow_attrib(flags, vcpu->arch.shared->msr & MSR_PR); stlbe.tid = !(asid & 0xff); /* Keep track of the reference so we can properly release it later. */ ref = &vcpu_44x->shadow_refs[victim]; ref->page = new_page; ref->gtlb_index = gtlb_index; ref->writeable = !!(stlbe.word2 & PPC44x_TLB_UW); ref->tid = stlbe.tid; /* Insert shadow mapping into hardware TLB. */ kvmppc_44x_tlbe_set_modified(vcpu_44x, victim); kvmppc_44x_tlbwe(victim, &stlbe); trace_kvm_stlb_write(victim, stlbe.tid, stlbe.word0, stlbe.word1, stlbe.word2); } /* For a particular guest TLB entry, invalidate the corresponding host TLB * mappings and release the host pages. */ static void kvmppc_44x_invalidate(struct kvm_vcpu *vcpu, unsigned int gtlb_index) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); int i; for (i = 0; i < ARRAY_SIZE(vcpu_44x->shadow_refs); i++) { struct kvmppc_44x_shadow_ref *ref = &vcpu_44x->shadow_refs[i]; if (ref->gtlb_index == gtlb_index) kvmppc_44x_shadow_release(vcpu_44x, i); } } void kvmppc_mmu_msr_notify(struct kvm_vcpu *vcpu, u32 old_msr) { int usermode = vcpu->arch.shared->msr & MSR_PR; vcpu->arch.shadow_pid = !usermode; } void kvmppc_set_pid(struct kvm_vcpu *vcpu, u32 new_pid) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); int i; if (unlikely(vcpu->arch.pid == new_pid)) return; vcpu->arch.pid = new_pid; /* Guest userspace runs with TID=0 mappings and PID=0, to make sure it * can't access guest kernel mappings (TID=1). When we switch to a new * guest PID, which will also use host PID=0, we must discard the old guest * userspace mappings. */ for (i = 0; i < ARRAY_SIZE(vcpu_44x->shadow_refs); i++) { struct kvmppc_44x_shadow_ref *ref = &vcpu_44x->shadow_refs[i]; if (ref->tid == 0) kvmppc_44x_shadow_release(vcpu_44x, i); } } static int tlbe_is_host_safe(const struct kvm_vcpu *vcpu, const struct kvmppc_44x_tlbe *tlbe) { gpa_t gpa; if (!get_tlb_v(tlbe)) return 0; /* Does it match current guest AS? */ /* XXX what about IS != DS? */ if (get_tlb_ts(tlbe) != !!(vcpu->arch.shared->msr & MSR_IS)) return 0; gpa = get_tlb_raddr(tlbe); if (!gfn_to_memslot(vcpu->kvm, gpa >> PAGE_SHIFT)) /* Mapping is not for RAM. */ return 0; return 1; } int kvmppc_44x_emul_tlbwe(struct kvm_vcpu *vcpu, u8 ra, u8 rs, u8 ws) { struct kvmppc_vcpu_44x *vcpu_44x = to_44x(vcpu); struct kvmppc_44x_tlbe *tlbe; unsigned int gtlb_index; int idx; gtlb_index = kvmppc_get_gpr(vcpu, ra); if (gtlb_index >= KVM44x_GUEST_TLB_SIZE) { printk("%s: index %d\n", __func__, gtlb_index); kvmppc_dump_vcpu(vcpu); return EMULATE_FAIL; } tlbe = &vcpu_44x->guest_tlb[gtlb_index]; /* Invalidate shadow mappings for the about-to-be-clobbered TLB entry. */ if (tlbe->word0 & PPC44x_TLB_VALID) kvmppc_44x_invalidate(vcpu, gtlb_index); switch (ws) { case PPC44x_TLB_PAGEID: tlbe->tid = get_mmucr_stid(vcpu); tlbe->word0 = kvmppc_get_gpr(vcpu, rs); break; case PPC44x_TLB_XLAT: tlbe->word1 = kvmppc_get_gpr(vcpu, rs); break; case PPC44x_TLB_ATTRIB: tlbe->word2 = kvmppc_get_gpr(vcpu, rs); break; default: return EMULATE_FAIL; } idx = srcu_read_lock(&vcpu->kvm->srcu); if (tlbe_is_host_safe(vcpu, tlbe)) { gva_t eaddr; gpa_t gpaddr; u32 bytes; eaddr = get_tlb_eaddr(tlbe); gpaddr = get_tlb_raddr(tlbe); /* Use the advertised page size to mask effective and real addrs. */ bytes = get_tlb_bytes(tlbe); eaddr &= ~(bytes - 1); gpaddr &= ~(bytes - 1); kvmppc_mmu_map(vcpu, eaddr, gpaddr, gtlb_index); } srcu_read_unlock(&vcpu->kvm->srcu, idx); trace_kvm_gtlb_write(gtlb_index, tlbe->tid, tlbe->word0, tlbe->word1, tlbe->word2); kvmppc_set_exit_type(vcpu, EMULATED_TLBWE_EXITS); return EMULATE_DONE; } int kvmppc_44x_emul_tlbsx(struct kvm_vcpu *vcpu, u8 rt, u8 ra, u8 rb, u8 rc) { u32 ea; int gtlb_index; unsigned int as = get_mmucr_sts(vcpu); unsigned int pid = get_mmucr_stid(vcpu); ea = kvmppc_get_gpr(vcpu, rb); if (ra) ea += kvmppc_get_gpr(vcpu, ra); gtlb_index = kvmppc_44x_tlb_index(vcpu, ea, pid, as); if (rc) { u32 cr = kvmppc_get_cr(vcpu); if (gtlb_index < 0) kvmppc_set_cr(vcpu, cr & ~0x20000000); else kvmppc_set_cr(vcpu, cr | 0x20000000); } kvmppc_set_gpr(vcpu, rt, gtlb_index); kvmppc_set_exit_type(vcpu, EMULATED_TLBSX_EXITS); return EMULATE_DONE; }
gpl-2.0
mialwe/mnics2
arch/arm/mach-ux500/usb.c
2328
4050
/* * Copyright (C) ST-Ericsson SA 2011 * * Author: Mian Yousaf Kaukab <mian.yousaf.kaukab@stericsson.com> * License terms: GNU General Public License (GPL) version 2 */ #include <linux/platform_device.h> #include <linux/usb/musb.h> #include <plat/ste_dma40.h> #include <mach/hardware.h> #include <mach/usb.h> #define MUSB_DMA40_RX_CH { \ .mode = STEDMA40_MODE_LOGICAL, \ .dir = STEDMA40_PERIPH_TO_MEM, \ .dst_dev_type = STEDMA40_DEV_DST_MEMORY, \ .src_info.data_width = STEDMA40_WORD_WIDTH, \ .dst_info.data_width = STEDMA40_WORD_WIDTH, \ .src_info.psize = STEDMA40_PSIZE_LOG_16, \ .dst_info.psize = STEDMA40_PSIZE_LOG_16, \ } #define MUSB_DMA40_TX_CH { \ .mode = STEDMA40_MODE_LOGICAL, \ .dir = STEDMA40_MEM_TO_PERIPH, \ .src_dev_type = STEDMA40_DEV_SRC_MEMORY, \ .src_info.data_width = STEDMA40_WORD_WIDTH, \ .dst_info.data_width = STEDMA40_WORD_WIDTH, \ .src_info.psize = STEDMA40_PSIZE_LOG_16, \ .dst_info.psize = STEDMA40_PSIZE_LOG_16, \ } static struct stedma40_chan_cfg musb_dma_rx_ch[UX500_MUSB_DMA_NUM_RX_CHANNELS] = { MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH }; static struct stedma40_chan_cfg musb_dma_tx_ch[UX500_MUSB_DMA_NUM_TX_CHANNELS] = { MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, }; static void *ux500_dma_rx_param_array[UX500_MUSB_DMA_NUM_RX_CHANNELS] = { &musb_dma_rx_ch[0], &musb_dma_rx_ch[1], &musb_dma_rx_ch[2], &musb_dma_rx_ch[3], &musb_dma_rx_ch[4], &musb_dma_rx_ch[5], &musb_dma_rx_ch[6], &musb_dma_rx_ch[7] }; static void *ux500_dma_tx_param_array[UX500_MUSB_DMA_NUM_TX_CHANNELS] = { &musb_dma_tx_ch[0], &musb_dma_tx_ch[1], &musb_dma_tx_ch[2], &musb_dma_tx_ch[3], &musb_dma_tx_ch[4], &musb_dma_tx_ch[5], &musb_dma_tx_ch[6], &musb_dma_tx_ch[7] }; static struct ux500_musb_board_data musb_board_data = { .dma_rx_param_array = ux500_dma_rx_param_array, .dma_tx_param_array = ux500_dma_tx_param_array, .num_rx_channels = UX500_MUSB_DMA_NUM_RX_CHANNELS, .num_tx_channels = UX500_MUSB_DMA_NUM_TX_CHANNELS, .dma_filter = stedma40_filter, }; static u64 ux500_musb_dmamask = DMA_BIT_MASK(32); static struct musb_hdrc_config musb_hdrc_config = { .multipoint = true, .dyn_fifo = true, .num_eps = 16, .ram_bits = 16, }; static struct musb_hdrc_platform_data musb_platform_data = { #if defined(CONFIG_USB_MUSB_OTG) .mode = MUSB_OTG, #elif defined(CONFIG_USB_MUSB_PERIPHERAL) .mode = MUSB_PERIPHERAL, #else /* defined(CONFIG_USB_MUSB_HOST) */ .mode = MUSB_HOST, #endif .config = &musb_hdrc_config, .board_data = &musb_board_data, }; static struct resource usb_resources[] = { [0] = { .name = "usb-mem", .flags = IORESOURCE_MEM, }, [1] = { .name = "mc", /* hard-coded in musb */ .flags = IORESOURCE_IRQ, }, }; struct platform_device ux500_musb_device = { .name = "musb-ux500", .id = 0, .dev = { .platform_data = &musb_platform_data, .dma_mask = &ux500_musb_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), }, .num_resources = ARRAY_SIZE(usb_resources), .resource = usb_resources, }; static inline void ux500_usb_dma_update_rx_ch_config(int *src_dev_type) { u32 idx; for (idx = 0; idx < UX500_MUSB_DMA_NUM_RX_CHANNELS; idx++) musb_dma_rx_ch[idx].src_dev_type = src_dev_type[idx]; } static inline void ux500_usb_dma_update_tx_ch_config(int *dst_dev_type) { u32 idx; for (idx = 0; idx < UX500_MUSB_DMA_NUM_TX_CHANNELS; idx++) musb_dma_tx_ch[idx].dst_dev_type = dst_dev_type[idx]; } void ux500_add_usb(resource_size_t base, int irq, int *dma_rx_cfg, int *dma_tx_cfg) { ux500_musb_device.resource[0].start = base; ux500_musb_device.resource[0].end = base + SZ_64K - 1; ux500_musb_device.resource[1].start = irq; ux500_musb_device.resource[1].end = irq; ux500_usb_dma_update_rx_ch_config(dma_rx_cfg); ux500_usb_dma_update_tx_ch_config(dma_tx_cfg); platform_device_register(&ux500_musb_device); }
gpl-2.0
0xD34D/kernel_omap_bowser-common
arch/arm/mach-ux500/usb.c
2328
4050
/* * Copyright (C) ST-Ericsson SA 2011 * * Author: Mian Yousaf Kaukab <mian.yousaf.kaukab@stericsson.com> * License terms: GNU General Public License (GPL) version 2 */ #include <linux/platform_device.h> #include <linux/usb/musb.h> #include <plat/ste_dma40.h> #include <mach/hardware.h> #include <mach/usb.h> #define MUSB_DMA40_RX_CH { \ .mode = STEDMA40_MODE_LOGICAL, \ .dir = STEDMA40_PERIPH_TO_MEM, \ .dst_dev_type = STEDMA40_DEV_DST_MEMORY, \ .src_info.data_width = STEDMA40_WORD_WIDTH, \ .dst_info.data_width = STEDMA40_WORD_WIDTH, \ .src_info.psize = STEDMA40_PSIZE_LOG_16, \ .dst_info.psize = STEDMA40_PSIZE_LOG_16, \ } #define MUSB_DMA40_TX_CH { \ .mode = STEDMA40_MODE_LOGICAL, \ .dir = STEDMA40_MEM_TO_PERIPH, \ .src_dev_type = STEDMA40_DEV_SRC_MEMORY, \ .src_info.data_width = STEDMA40_WORD_WIDTH, \ .dst_info.data_width = STEDMA40_WORD_WIDTH, \ .src_info.psize = STEDMA40_PSIZE_LOG_16, \ .dst_info.psize = STEDMA40_PSIZE_LOG_16, \ } static struct stedma40_chan_cfg musb_dma_rx_ch[UX500_MUSB_DMA_NUM_RX_CHANNELS] = { MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH, MUSB_DMA40_RX_CH }; static struct stedma40_chan_cfg musb_dma_tx_ch[UX500_MUSB_DMA_NUM_TX_CHANNELS] = { MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, MUSB_DMA40_TX_CH, }; static void *ux500_dma_rx_param_array[UX500_MUSB_DMA_NUM_RX_CHANNELS] = { &musb_dma_rx_ch[0], &musb_dma_rx_ch[1], &musb_dma_rx_ch[2], &musb_dma_rx_ch[3], &musb_dma_rx_ch[4], &musb_dma_rx_ch[5], &musb_dma_rx_ch[6], &musb_dma_rx_ch[7] }; static void *ux500_dma_tx_param_array[UX500_MUSB_DMA_NUM_TX_CHANNELS] = { &musb_dma_tx_ch[0], &musb_dma_tx_ch[1], &musb_dma_tx_ch[2], &musb_dma_tx_ch[3], &musb_dma_tx_ch[4], &musb_dma_tx_ch[5], &musb_dma_tx_ch[6], &musb_dma_tx_ch[7] }; static struct ux500_musb_board_data musb_board_data = { .dma_rx_param_array = ux500_dma_rx_param_array, .dma_tx_param_array = ux500_dma_tx_param_array, .num_rx_channels = UX500_MUSB_DMA_NUM_RX_CHANNELS, .num_tx_channels = UX500_MUSB_DMA_NUM_TX_CHANNELS, .dma_filter = stedma40_filter, }; static u64 ux500_musb_dmamask = DMA_BIT_MASK(32); static struct musb_hdrc_config musb_hdrc_config = { .multipoint = true, .dyn_fifo = true, .num_eps = 16, .ram_bits = 16, }; static struct musb_hdrc_platform_data musb_platform_data = { #if defined(CONFIG_USB_MUSB_OTG) .mode = MUSB_OTG, #elif defined(CONFIG_USB_MUSB_PERIPHERAL) .mode = MUSB_PERIPHERAL, #else /* defined(CONFIG_USB_MUSB_HOST) */ .mode = MUSB_HOST, #endif .config = &musb_hdrc_config, .board_data = &musb_board_data, }; static struct resource usb_resources[] = { [0] = { .name = "usb-mem", .flags = IORESOURCE_MEM, }, [1] = { .name = "mc", /* hard-coded in musb */ .flags = IORESOURCE_IRQ, }, }; struct platform_device ux500_musb_device = { .name = "musb-ux500", .id = 0, .dev = { .platform_data = &musb_platform_data, .dma_mask = &ux500_musb_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), }, .num_resources = ARRAY_SIZE(usb_resources), .resource = usb_resources, }; static inline void ux500_usb_dma_update_rx_ch_config(int *src_dev_type) { u32 idx; for (idx = 0; idx < UX500_MUSB_DMA_NUM_RX_CHANNELS; idx++) musb_dma_rx_ch[idx].src_dev_type = src_dev_type[idx]; } static inline void ux500_usb_dma_update_tx_ch_config(int *dst_dev_type) { u32 idx; for (idx = 0; idx < UX500_MUSB_DMA_NUM_TX_CHANNELS; idx++) musb_dma_tx_ch[idx].dst_dev_type = dst_dev_type[idx]; } void ux500_add_usb(resource_size_t base, int irq, int *dma_rx_cfg, int *dma_tx_cfg) { ux500_musb_device.resource[0].start = base; ux500_musb_device.resource[0].end = base + SZ_64K - 1; ux500_musb_device.resource[1].start = irq; ux500_musb_device.resource[1].end = irq; ux500_usb_dma_update_rx_ch_config(dma_rx_cfg); ux500_usb_dma_update_tx_ch_config(dma_tx_cfg); platform_device_register(&ux500_musb_device); }
gpl-2.0
schmatzler/zte-kernel-smartchat
arch/arm/mach-omap1/board-generic.c
2584
2471
/* * linux/arch/arm/mach-omap1/board-generic.c * * Modified from board-innovator1510.c * * Code for generic OMAP board. Should work on many OMAP systems where * the device drivers take care of all the necessary hardware initialization. * Do not put any board specific code to this file; create a new machine * type if you need custom low-level initializations. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <mach/hardware.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/gpio.h> #include <plat/mux.h> #include <plat/usb.h> #include <plat/board.h> #include <plat/common.h> static void __init omap_generic_init_irq(void) { omap1_init_common_hw(); omap_init_irq(); } /* assume no Mini-AB port */ #ifdef CONFIG_ARCH_OMAP15XX static struct omap_usb_config generic1510_usb_config __initdata = { .register_host = 1, .register_dev = 1, .hmc_mode = 16, .pins[0] = 3, }; #endif #if defined(CONFIG_ARCH_OMAP16XX) static struct omap_usb_config generic1610_usb_config __initdata = { #ifdef CONFIG_USB_OTG .otg = 1, #endif .register_host = 1, .register_dev = 1, .hmc_mode = 16, .pins[0] = 6, }; #endif static struct omap_board_config_kernel generic_config[] __initdata = { }; static void __init omap_generic_init(void) { #ifdef CONFIG_ARCH_OMAP15XX if (cpu_is_omap15xx()) { /* mux pins for uarts */ omap_cfg_reg(UART1_TX); omap_cfg_reg(UART1_RTS); omap_cfg_reg(UART2_TX); omap_cfg_reg(UART2_RTS); omap_cfg_reg(UART3_TX); omap_cfg_reg(UART3_RX); omap1_usb_init(&generic1510_usb_config); } #endif #if defined(CONFIG_ARCH_OMAP16XX) if (!cpu_is_omap1510()) { omap1_usb_init(&generic1610_usb_config); } #endif omap_board_config = generic_config; omap_board_config_size = ARRAY_SIZE(generic_config); omap_serial_init(); omap_register_i2c_bus(1, 100, NULL, 0); } static void __init omap_generic_map_io(void) { omap1_map_common_io(); } MACHINE_START(OMAP_GENERIC, "Generic OMAP1510/1610/1710") /* Maintainer: Tony Lindgren <tony@atomide.com> */ .boot_params = 0x10000100, .map_io = omap_generic_map_io, .reserve = omap_reserve, .init_irq = omap_generic_init_irq, .init_machine = omap_generic_init, .timer = &omap_timer, MACHINE_END
gpl-2.0
isnehalkiran/kernel-msm
net/wimax/stack.c
2584
18240
/* * Linux WiMAX * Initialization, addition and removal of wimax devices * * * Copyright (C) 2005-2006 Intel Corporation <linux-wimax@intel.com> * Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * This implements: * * - basic life cycle of 'struct wimax_dev' [wimax_dev_*()]; on * addition/registration initialize all subfields and allocate * generic netlink resources for user space communication. On * removal/unregistration, undo all that. * * - device state machine [wimax_state_change()] and support to send * reports to user space when the state changes * [wimax_gnl_re_state_change*()]. * * See include/net/wimax.h for rationales and design. * * ROADMAP * * [__]wimax_state_change() Called by drivers to update device's state * wimax_gnl_re_state_change_alloc() * wimax_gnl_re_state_change_send() * * wimax_dev_init() Init a device * wimax_dev_add() Register * wimax_rfkill_add() * wimax_gnl_add() Register all the generic netlink resources. * wimax_id_table_add() * wimax_dev_rm() Unregister * wimax_id_table_rm() * wimax_gnl_rm() * wimax_rfkill_rm() */ #include <linux/device.h> #include <linux/gfp.h> #include <net/genetlink.h> #include <linux/netdevice.h> #include <linux/wimax.h> #include <linux/module.h> #include "wimax-internal.h" #define D_SUBMODULE stack #include "debug-levels.h" static char wimax_debug_params[128]; module_param_string(debug, wimax_debug_params, sizeof(wimax_debug_params), 0644); MODULE_PARM_DESC(debug, "String of space-separated NAME:VALUE pairs, where NAMEs " "are the different debug submodules and VALUE are the " "initial debug value to set."); /* * Authoritative source for the RE_STATE_CHANGE attribute policy * * We don't really use it here, but /me likes to keep the definition * close to where the data is generated. */ /* static const struct nla_policy wimax_gnl_re_status_change[WIMAX_GNL_ATTR_MAX + 1] = { [WIMAX_GNL_STCH_STATE_OLD] = { .type = NLA_U8 }, [WIMAX_GNL_STCH_STATE_NEW] = { .type = NLA_U8 }, }; */ /* * Allocate a Report State Change message * * @header: save it, you need it for _send() * * Creates and fills a basic state change message; different code * paths can then add more attributes to the message as needed. * * Use wimax_gnl_re_state_change_send() to send the returned skb. * * Returns: skb with the genl message if ok, IS_ERR() ptr on error * with an errno code. */ static struct sk_buff *wimax_gnl_re_state_change_alloc( struct wimax_dev *wimax_dev, enum wimax_st new_state, enum wimax_st old_state, void **header) { int result; struct device *dev = wimax_dev_to_dev(wimax_dev); void *data; struct sk_buff *report_skb; d_fnstart(3, dev, "(wimax_dev %p new_state %u old_state %u)\n", wimax_dev, new_state, old_state); result = -ENOMEM; report_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (report_skb == NULL) { dev_err(dev, "RE_STCH: can't create message\n"); goto error_new; } data = genlmsg_put(report_skb, 0, wimax_gnl_mcg.id, &wimax_gnl_family, 0, WIMAX_GNL_RE_STATE_CHANGE); if (data == NULL) { dev_err(dev, "RE_STCH: can't put data into message\n"); goto error_put; } *header = data; result = nla_put_u8(report_skb, WIMAX_GNL_STCH_STATE_OLD, old_state); if (result < 0) { dev_err(dev, "RE_STCH: Error adding OLD attr: %d\n", result); goto error_put; } result = nla_put_u8(report_skb, WIMAX_GNL_STCH_STATE_NEW, new_state); if (result < 0) { dev_err(dev, "RE_STCH: Error adding NEW attr: %d\n", result); goto error_put; } result = nla_put_u32(report_skb, WIMAX_GNL_STCH_IFIDX, wimax_dev->net_dev->ifindex); if (result < 0) { dev_err(dev, "RE_STCH: Error adding IFINDEX attribute\n"); goto error_put; } d_fnend(3, dev, "(wimax_dev %p new_state %u old_state %u) = %p\n", wimax_dev, new_state, old_state, report_skb); return report_skb; error_put: nlmsg_free(report_skb); error_new: d_fnend(3, dev, "(wimax_dev %p new_state %u old_state %u) = %d\n", wimax_dev, new_state, old_state, result); return ERR_PTR(result); } /* * Send a Report State Change message (as created with _alloc). * * @report_skb: as returned by wimax_gnl_re_state_change_alloc() * @header: as returned by wimax_gnl_re_state_change_alloc() * * Returns: 0 if ok, < 0 errno code on error. * * If the message is NULL, pretend it didn't happen. */ static int wimax_gnl_re_state_change_send( struct wimax_dev *wimax_dev, struct sk_buff *report_skb, void *header) { int result = 0; struct device *dev = wimax_dev_to_dev(wimax_dev); d_fnstart(3, dev, "(wimax_dev %p report_skb %p)\n", wimax_dev, report_skb); if (report_skb == NULL) { result = -ENOMEM; goto out; } genlmsg_end(report_skb, header); genlmsg_multicast(report_skb, 0, wimax_gnl_mcg.id, GFP_KERNEL); out: d_fnend(3, dev, "(wimax_dev %p report_skb %p) = %d\n", wimax_dev, report_skb, result); return result; } static void __check_new_state(enum wimax_st old_state, enum wimax_st new_state, unsigned int allowed_states_bm) { if (WARN_ON(((1 << new_state) & allowed_states_bm) == 0)) { printk(KERN_ERR "SW BUG! Forbidden state change %u -> %u\n", old_state, new_state); } } /* * Set the current state of a WiMAX device [unlocking version of * wimax_state_change(). */ void __wimax_state_change(struct wimax_dev *wimax_dev, enum wimax_st new_state) { struct device *dev = wimax_dev_to_dev(wimax_dev); enum wimax_st old_state = wimax_dev->state; struct sk_buff *stch_skb; void *header; d_fnstart(3, dev, "(wimax_dev %p new_state %u [old %u])\n", wimax_dev, new_state, old_state); if (WARN_ON(new_state >= __WIMAX_ST_INVALID)) { dev_err(dev, "SW BUG: requesting invalid state %u\n", new_state); goto out; } if (old_state == new_state) goto out; header = NULL; /* gcc complains? can't grok why */ stch_skb = wimax_gnl_re_state_change_alloc( wimax_dev, new_state, old_state, &header); /* Verify the state transition and do exit-from-state actions */ switch (old_state) { case __WIMAX_ST_NULL: __check_new_state(old_state, new_state, 1 << WIMAX_ST_DOWN); break; case WIMAX_ST_DOWN: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_UNINITIALIZED | 1 << WIMAX_ST_RADIO_OFF); break; case __WIMAX_ST_QUIESCING: __check_new_state(old_state, new_state, 1 << WIMAX_ST_DOWN); break; case WIMAX_ST_UNINITIALIZED: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF); break; case WIMAX_ST_RADIO_OFF: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_READY); break; case WIMAX_ST_READY: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_SCANNING | 1 << WIMAX_ST_CONNECTING | 1 << WIMAX_ST_CONNECTED); break; case WIMAX_ST_SCANNING: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_READY | 1 << WIMAX_ST_CONNECTING | 1 << WIMAX_ST_CONNECTED); break; case WIMAX_ST_CONNECTING: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_READY | 1 << WIMAX_ST_SCANNING | 1 << WIMAX_ST_CONNECTED); break; case WIMAX_ST_CONNECTED: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_READY); netif_tx_disable(wimax_dev->net_dev); netif_carrier_off(wimax_dev->net_dev); break; case __WIMAX_ST_INVALID: default: dev_err(dev, "SW BUG: wimax_dev %p is in unknown state %u\n", wimax_dev, wimax_dev->state); WARN_ON(1); goto out; } /* Execute the actions of entry to the new state */ switch (new_state) { case __WIMAX_ST_NULL: dev_err(dev, "SW BUG: wimax_dev %p entering NULL state " "from %u\n", wimax_dev, wimax_dev->state); WARN_ON(1); /* Nobody can enter this state */ break; case WIMAX_ST_DOWN: break; case __WIMAX_ST_QUIESCING: break; case WIMAX_ST_UNINITIALIZED: break; case WIMAX_ST_RADIO_OFF: break; case WIMAX_ST_READY: break; case WIMAX_ST_SCANNING: break; case WIMAX_ST_CONNECTING: break; case WIMAX_ST_CONNECTED: netif_carrier_on(wimax_dev->net_dev); netif_wake_queue(wimax_dev->net_dev); break; case __WIMAX_ST_INVALID: default: BUG(); } __wimax_state_set(wimax_dev, new_state); if (!IS_ERR(stch_skb)) wimax_gnl_re_state_change_send(wimax_dev, stch_skb, header); out: d_fnend(3, dev, "(wimax_dev %p new_state %u [old %u]) = void\n", wimax_dev, new_state, old_state); } /** * wimax_state_change - Set the current state of a WiMAX device * * @wimax_dev: WiMAX device descriptor (properly referenced) * @new_state: New state to switch to * * This implements the state changes for the wimax devices. It will * * - verify that the state transition is legal (for now it'll just * print a warning if not) according to the table in * linux/wimax.h's documentation for 'enum wimax_st'. * * - perform the actions needed for leaving the current state and * whichever are needed for entering the new state. * * - issue a report to user space indicating the new state (and an * optional payload with information about the new state). * * NOTE: @wimax_dev must be locked */ void wimax_state_change(struct wimax_dev *wimax_dev, enum wimax_st new_state) { /* * A driver cannot take the wimax_dev out of the * __WIMAX_ST_NULL state unless by calling wimax_dev_add(). If * the wimax_dev's state is still NULL, we ignore any request * to change its state because it means it hasn't been yet * registered. * * There is no need to complain about it, as routines that * call this might be shared from different code paths that * are called before or after wimax_dev_add() has done its * job. */ mutex_lock(&wimax_dev->mutex); if (wimax_dev->state > __WIMAX_ST_NULL) __wimax_state_change(wimax_dev, new_state); mutex_unlock(&wimax_dev->mutex); } EXPORT_SYMBOL_GPL(wimax_state_change); /** * wimax_state_get() - Return the current state of a WiMAX device * * @wimax_dev: WiMAX device descriptor * * Returns: Current state of the device according to its driver. */ enum wimax_st wimax_state_get(struct wimax_dev *wimax_dev) { enum wimax_st state; mutex_lock(&wimax_dev->mutex); state = wimax_dev->state; mutex_unlock(&wimax_dev->mutex); return state; } EXPORT_SYMBOL_GPL(wimax_state_get); /** * wimax_dev_init - initialize a newly allocated instance * * @wimax_dev: WiMAX device descriptor to initialize. * * Initializes fields of a freshly allocated @wimax_dev instance. This * function assumes that after allocation, the memory occupied by * @wimax_dev was zeroed. */ void wimax_dev_init(struct wimax_dev *wimax_dev) { INIT_LIST_HEAD(&wimax_dev->id_table_node); __wimax_state_set(wimax_dev, __WIMAX_ST_NULL); mutex_init(&wimax_dev->mutex); mutex_init(&wimax_dev->mutex_reset); } EXPORT_SYMBOL_GPL(wimax_dev_init); /* * This extern is declared here because it's easier to keep track -- * both declarations are a list of the same */ extern struct genl_ops wimax_gnl_msg_from_user, wimax_gnl_reset, wimax_gnl_rfkill, wimax_gnl_state_get; static struct genl_ops *wimax_gnl_ops[] = { &wimax_gnl_msg_from_user, &wimax_gnl_reset, &wimax_gnl_rfkill, &wimax_gnl_state_get, }; static size_t wimax_addr_scnprint(char *addr_str, size_t addr_str_size, unsigned char *addr, size_t addr_len) { unsigned int cnt, total; for (total = cnt = 0; cnt < addr_len; cnt++) total += scnprintf(addr_str + total, addr_str_size - total, "%02x%c", addr[cnt], cnt == addr_len - 1 ? '\0' : ':'); return total; } /** * wimax_dev_add - Register a new WiMAX device * * @wimax_dev: WiMAX device descriptor (as embedded in your @net_dev's * priv data). You must have called wimax_dev_init() on it before. * * @net_dev: net device the @wimax_dev is associated with. The * function expects SET_NETDEV_DEV() and register_netdev() were * already called on it. * * Registers the new WiMAX device, sets up the user-kernel control * interface (generic netlink) and common WiMAX infrastructure. * * Note that the parts that will allow interaction with user space are * setup at the very end, when the rest is in place, as once that * happens, the driver might get user space control requests via * netlink or from debugfs that might translate into calls into * wimax_dev->op_*(). */ int wimax_dev_add(struct wimax_dev *wimax_dev, struct net_device *net_dev) { int result; struct device *dev = net_dev->dev.parent; char addr_str[32]; d_fnstart(3, dev, "(wimax_dev %p net_dev %p)\n", wimax_dev, net_dev); /* Do the RFKILL setup before locking, as RFKILL will call * into our functions. */ wimax_dev->net_dev = net_dev; result = wimax_rfkill_add(wimax_dev); if (result < 0) goto error_rfkill_add; /* Set up user-space interaction */ mutex_lock(&wimax_dev->mutex); wimax_id_table_add(wimax_dev); result = wimax_debugfs_add(wimax_dev); if (result < 0) { dev_err(dev, "cannot initialize debugfs: %d\n", result); goto error_debugfs_add; } __wimax_state_set(wimax_dev, WIMAX_ST_DOWN); mutex_unlock(&wimax_dev->mutex); wimax_addr_scnprint(addr_str, sizeof(addr_str), net_dev->dev_addr, net_dev->addr_len); dev_err(dev, "WiMAX interface %s (%s) ready\n", net_dev->name, addr_str); d_fnend(3, dev, "(wimax_dev %p net_dev %p) = 0\n", wimax_dev, net_dev); return 0; error_debugfs_add: wimax_id_table_rm(wimax_dev); mutex_unlock(&wimax_dev->mutex); wimax_rfkill_rm(wimax_dev); error_rfkill_add: d_fnend(3, dev, "(wimax_dev %p net_dev %p) = %d\n", wimax_dev, net_dev, result); return result; } EXPORT_SYMBOL_GPL(wimax_dev_add); /** * wimax_dev_rm - Unregister an existing WiMAX device * * @wimax_dev: WiMAX device descriptor * * Unregisters a WiMAX device previously registered for use with * wimax_add_rm(). * * IMPORTANT! Must call before calling unregister_netdev(). * * After this function returns, you will not get any more user space * control requests (via netlink or debugfs) and thus to wimax_dev->ops. * * Reentrancy control is ensured by setting the state to * %__WIMAX_ST_QUIESCING. rfkill operations coming through * wimax_*rfkill*() will be stopped by the quiescing state; ops coming * from the rfkill subsystem will be stopped by the support being * removed by wimax_rfkill_rm(). */ void wimax_dev_rm(struct wimax_dev *wimax_dev) { d_fnstart(3, NULL, "(wimax_dev %p)\n", wimax_dev); mutex_lock(&wimax_dev->mutex); __wimax_state_change(wimax_dev, __WIMAX_ST_QUIESCING); wimax_debugfs_rm(wimax_dev); wimax_id_table_rm(wimax_dev); __wimax_state_change(wimax_dev, WIMAX_ST_DOWN); mutex_unlock(&wimax_dev->mutex); wimax_rfkill_rm(wimax_dev); d_fnend(3, NULL, "(wimax_dev %p) = void\n", wimax_dev); } EXPORT_SYMBOL_GPL(wimax_dev_rm); /* Debug framework control of debug levels */ struct d_level D_LEVEL[] = { D_SUBMODULE_DEFINE(debugfs), D_SUBMODULE_DEFINE(id_table), D_SUBMODULE_DEFINE(op_msg), D_SUBMODULE_DEFINE(op_reset), D_SUBMODULE_DEFINE(op_rfkill), D_SUBMODULE_DEFINE(op_state_get), D_SUBMODULE_DEFINE(stack), }; size_t D_LEVEL_SIZE = ARRAY_SIZE(D_LEVEL); struct genl_family wimax_gnl_family = { .id = GENL_ID_GENERATE, .name = "WiMAX", .version = WIMAX_GNL_VERSION, .hdrsize = 0, .maxattr = WIMAX_GNL_ATTR_MAX, }; struct genl_multicast_group wimax_gnl_mcg = { .name = "msg", }; /* Shutdown the wimax stack */ static int __init wimax_subsys_init(void) { int result, cnt; d_fnstart(4, NULL, "()\n"); d_parse_params(D_LEVEL, D_LEVEL_SIZE, wimax_debug_params, "wimax.debug"); snprintf(wimax_gnl_family.name, sizeof(wimax_gnl_family.name), "WiMAX"); result = genl_register_family(&wimax_gnl_family); if (unlikely(result < 0)) { printk(KERN_ERR "cannot register generic netlink family: %d\n", result); goto error_register_family; } for (cnt = 0; cnt < ARRAY_SIZE(wimax_gnl_ops); cnt++) { result = genl_register_ops(&wimax_gnl_family, wimax_gnl_ops[cnt]); d_printf(4, NULL, "registering generic netlink op code " "%u: %d\n", wimax_gnl_ops[cnt]->cmd, result); if (unlikely(result < 0)) { printk(KERN_ERR "cannot register generic netlink op " "code %u: %d\n", wimax_gnl_ops[cnt]->cmd, result); goto error_register_ops; } } result = genl_register_mc_group(&wimax_gnl_family, &wimax_gnl_mcg); if (result < 0) goto error_mc_group; d_fnend(4, NULL, "() = 0\n"); return 0; error_mc_group: error_register_ops: for (cnt--; cnt >= 0; cnt--) genl_unregister_ops(&wimax_gnl_family, wimax_gnl_ops[cnt]); genl_unregister_family(&wimax_gnl_family); error_register_family: d_fnend(4, NULL, "() = %d\n", result); return result; } module_init(wimax_subsys_init); /* Shutdown the wimax stack */ static void __exit wimax_subsys_exit(void) { int cnt; wimax_id_table_release(); genl_unregister_mc_group(&wimax_gnl_family, &wimax_gnl_mcg); for (cnt = ARRAY_SIZE(wimax_gnl_ops) - 1; cnt >= 0; cnt--) genl_unregister_ops(&wimax_gnl_family, wimax_gnl_ops[cnt]); genl_unregister_family(&wimax_gnl_family); } module_exit(wimax_subsys_exit); MODULE_AUTHOR("Intel Corporation <linux-wimax@intel.com>"); MODULE_DESCRIPTION("Linux WiMAX stack"); MODULE_LICENSE("GPL");
gpl-2.0
mythos234/NamelessN910F-LL
net/wimax/stack.c
2584
18240
/* * Linux WiMAX * Initialization, addition and removal of wimax devices * * * Copyright (C) 2005-2006 Intel Corporation <linux-wimax@intel.com> * Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * * This implements: * * - basic life cycle of 'struct wimax_dev' [wimax_dev_*()]; on * addition/registration initialize all subfields and allocate * generic netlink resources for user space communication. On * removal/unregistration, undo all that. * * - device state machine [wimax_state_change()] and support to send * reports to user space when the state changes * [wimax_gnl_re_state_change*()]. * * See include/net/wimax.h for rationales and design. * * ROADMAP * * [__]wimax_state_change() Called by drivers to update device's state * wimax_gnl_re_state_change_alloc() * wimax_gnl_re_state_change_send() * * wimax_dev_init() Init a device * wimax_dev_add() Register * wimax_rfkill_add() * wimax_gnl_add() Register all the generic netlink resources. * wimax_id_table_add() * wimax_dev_rm() Unregister * wimax_id_table_rm() * wimax_gnl_rm() * wimax_rfkill_rm() */ #include <linux/device.h> #include <linux/gfp.h> #include <net/genetlink.h> #include <linux/netdevice.h> #include <linux/wimax.h> #include <linux/module.h> #include "wimax-internal.h" #define D_SUBMODULE stack #include "debug-levels.h" static char wimax_debug_params[128]; module_param_string(debug, wimax_debug_params, sizeof(wimax_debug_params), 0644); MODULE_PARM_DESC(debug, "String of space-separated NAME:VALUE pairs, where NAMEs " "are the different debug submodules and VALUE are the " "initial debug value to set."); /* * Authoritative source for the RE_STATE_CHANGE attribute policy * * We don't really use it here, but /me likes to keep the definition * close to where the data is generated. */ /* static const struct nla_policy wimax_gnl_re_status_change[WIMAX_GNL_ATTR_MAX + 1] = { [WIMAX_GNL_STCH_STATE_OLD] = { .type = NLA_U8 }, [WIMAX_GNL_STCH_STATE_NEW] = { .type = NLA_U8 }, }; */ /* * Allocate a Report State Change message * * @header: save it, you need it for _send() * * Creates and fills a basic state change message; different code * paths can then add more attributes to the message as needed. * * Use wimax_gnl_re_state_change_send() to send the returned skb. * * Returns: skb with the genl message if ok, IS_ERR() ptr on error * with an errno code. */ static struct sk_buff *wimax_gnl_re_state_change_alloc( struct wimax_dev *wimax_dev, enum wimax_st new_state, enum wimax_st old_state, void **header) { int result; struct device *dev = wimax_dev_to_dev(wimax_dev); void *data; struct sk_buff *report_skb; d_fnstart(3, dev, "(wimax_dev %p new_state %u old_state %u)\n", wimax_dev, new_state, old_state); result = -ENOMEM; report_skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (report_skb == NULL) { dev_err(dev, "RE_STCH: can't create message\n"); goto error_new; } data = genlmsg_put(report_skb, 0, wimax_gnl_mcg.id, &wimax_gnl_family, 0, WIMAX_GNL_RE_STATE_CHANGE); if (data == NULL) { dev_err(dev, "RE_STCH: can't put data into message\n"); goto error_put; } *header = data; result = nla_put_u8(report_skb, WIMAX_GNL_STCH_STATE_OLD, old_state); if (result < 0) { dev_err(dev, "RE_STCH: Error adding OLD attr: %d\n", result); goto error_put; } result = nla_put_u8(report_skb, WIMAX_GNL_STCH_STATE_NEW, new_state); if (result < 0) { dev_err(dev, "RE_STCH: Error adding NEW attr: %d\n", result); goto error_put; } result = nla_put_u32(report_skb, WIMAX_GNL_STCH_IFIDX, wimax_dev->net_dev->ifindex); if (result < 0) { dev_err(dev, "RE_STCH: Error adding IFINDEX attribute\n"); goto error_put; } d_fnend(3, dev, "(wimax_dev %p new_state %u old_state %u) = %p\n", wimax_dev, new_state, old_state, report_skb); return report_skb; error_put: nlmsg_free(report_skb); error_new: d_fnend(3, dev, "(wimax_dev %p new_state %u old_state %u) = %d\n", wimax_dev, new_state, old_state, result); return ERR_PTR(result); } /* * Send a Report State Change message (as created with _alloc). * * @report_skb: as returned by wimax_gnl_re_state_change_alloc() * @header: as returned by wimax_gnl_re_state_change_alloc() * * Returns: 0 if ok, < 0 errno code on error. * * If the message is NULL, pretend it didn't happen. */ static int wimax_gnl_re_state_change_send( struct wimax_dev *wimax_dev, struct sk_buff *report_skb, void *header) { int result = 0; struct device *dev = wimax_dev_to_dev(wimax_dev); d_fnstart(3, dev, "(wimax_dev %p report_skb %p)\n", wimax_dev, report_skb); if (report_skb == NULL) { result = -ENOMEM; goto out; } genlmsg_end(report_skb, header); genlmsg_multicast(report_skb, 0, wimax_gnl_mcg.id, GFP_KERNEL); out: d_fnend(3, dev, "(wimax_dev %p report_skb %p) = %d\n", wimax_dev, report_skb, result); return result; } static void __check_new_state(enum wimax_st old_state, enum wimax_st new_state, unsigned int allowed_states_bm) { if (WARN_ON(((1 << new_state) & allowed_states_bm) == 0)) { printk(KERN_ERR "SW BUG! Forbidden state change %u -> %u\n", old_state, new_state); } } /* * Set the current state of a WiMAX device [unlocking version of * wimax_state_change(). */ void __wimax_state_change(struct wimax_dev *wimax_dev, enum wimax_st new_state) { struct device *dev = wimax_dev_to_dev(wimax_dev); enum wimax_st old_state = wimax_dev->state; struct sk_buff *stch_skb; void *header; d_fnstart(3, dev, "(wimax_dev %p new_state %u [old %u])\n", wimax_dev, new_state, old_state); if (WARN_ON(new_state >= __WIMAX_ST_INVALID)) { dev_err(dev, "SW BUG: requesting invalid state %u\n", new_state); goto out; } if (old_state == new_state) goto out; header = NULL; /* gcc complains? can't grok why */ stch_skb = wimax_gnl_re_state_change_alloc( wimax_dev, new_state, old_state, &header); /* Verify the state transition and do exit-from-state actions */ switch (old_state) { case __WIMAX_ST_NULL: __check_new_state(old_state, new_state, 1 << WIMAX_ST_DOWN); break; case WIMAX_ST_DOWN: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_UNINITIALIZED | 1 << WIMAX_ST_RADIO_OFF); break; case __WIMAX_ST_QUIESCING: __check_new_state(old_state, new_state, 1 << WIMAX_ST_DOWN); break; case WIMAX_ST_UNINITIALIZED: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF); break; case WIMAX_ST_RADIO_OFF: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_READY); break; case WIMAX_ST_READY: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_SCANNING | 1 << WIMAX_ST_CONNECTING | 1 << WIMAX_ST_CONNECTED); break; case WIMAX_ST_SCANNING: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_READY | 1 << WIMAX_ST_CONNECTING | 1 << WIMAX_ST_CONNECTED); break; case WIMAX_ST_CONNECTING: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_READY | 1 << WIMAX_ST_SCANNING | 1 << WIMAX_ST_CONNECTED); break; case WIMAX_ST_CONNECTED: __check_new_state(old_state, new_state, 1 << __WIMAX_ST_QUIESCING | 1 << WIMAX_ST_RADIO_OFF | 1 << WIMAX_ST_READY); netif_tx_disable(wimax_dev->net_dev); netif_carrier_off(wimax_dev->net_dev); break; case __WIMAX_ST_INVALID: default: dev_err(dev, "SW BUG: wimax_dev %p is in unknown state %u\n", wimax_dev, wimax_dev->state); WARN_ON(1); goto out; } /* Execute the actions of entry to the new state */ switch (new_state) { case __WIMAX_ST_NULL: dev_err(dev, "SW BUG: wimax_dev %p entering NULL state " "from %u\n", wimax_dev, wimax_dev->state); WARN_ON(1); /* Nobody can enter this state */ break; case WIMAX_ST_DOWN: break; case __WIMAX_ST_QUIESCING: break; case WIMAX_ST_UNINITIALIZED: break; case WIMAX_ST_RADIO_OFF: break; case WIMAX_ST_READY: break; case WIMAX_ST_SCANNING: break; case WIMAX_ST_CONNECTING: break; case WIMAX_ST_CONNECTED: netif_carrier_on(wimax_dev->net_dev); netif_wake_queue(wimax_dev->net_dev); break; case __WIMAX_ST_INVALID: default: BUG(); } __wimax_state_set(wimax_dev, new_state); if (!IS_ERR(stch_skb)) wimax_gnl_re_state_change_send(wimax_dev, stch_skb, header); out: d_fnend(3, dev, "(wimax_dev %p new_state %u [old %u]) = void\n", wimax_dev, new_state, old_state); } /** * wimax_state_change - Set the current state of a WiMAX device * * @wimax_dev: WiMAX device descriptor (properly referenced) * @new_state: New state to switch to * * This implements the state changes for the wimax devices. It will * * - verify that the state transition is legal (for now it'll just * print a warning if not) according to the table in * linux/wimax.h's documentation for 'enum wimax_st'. * * - perform the actions needed for leaving the current state and * whichever are needed for entering the new state. * * - issue a report to user space indicating the new state (and an * optional payload with information about the new state). * * NOTE: @wimax_dev must be locked */ void wimax_state_change(struct wimax_dev *wimax_dev, enum wimax_st new_state) { /* * A driver cannot take the wimax_dev out of the * __WIMAX_ST_NULL state unless by calling wimax_dev_add(). If * the wimax_dev's state is still NULL, we ignore any request * to change its state because it means it hasn't been yet * registered. * * There is no need to complain about it, as routines that * call this might be shared from different code paths that * are called before or after wimax_dev_add() has done its * job. */ mutex_lock(&wimax_dev->mutex); if (wimax_dev->state > __WIMAX_ST_NULL) __wimax_state_change(wimax_dev, new_state); mutex_unlock(&wimax_dev->mutex); } EXPORT_SYMBOL_GPL(wimax_state_change); /** * wimax_state_get() - Return the current state of a WiMAX device * * @wimax_dev: WiMAX device descriptor * * Returns: Current state of the device according to its driver. */ enum wimax_st wimax_state_get(struct wimax_dev *wimax_dev) { enum wimax_st state; mutex_lock(&wimax_dev->mutex); state = wimax_dev->state; mutex_unlock(&wimax_dev->mutex); return state; } EXPORT_SYMBOL_GPL(wimax_state_get); /** * wimax_dev_init - initialize a newly allocated instance * * @wimax_dev: WiMAX device descriptor to initialize. * * Initializes fields of a freshly allocated @wimax_dev instance. This * function assumes that after allocation, the memory occupied by * @wimax_dev was zeroed. */ void wimax_dev_init(struct wimax_dev *wimax_dev) { INIT_LIST_HEAD(&wimax_dev->id_table_node); __wimax_state_set(wimax_dev, __WIMAX_ST_NULL); mutex_init(&wimax_dev->mutex); mutex_init(&wimax_dev->mutex_reset); } EXPORT_SYMBOL_GPL(wimax_dev_init); /* * This extern is declared here because it's easier to keep track -- * both declarations are a list of the same */ extern struct genl_ops wimax_gnl_msg_from_user, wimax_gnl_reset, wimax_gnl_rfkill, wimax_gnl_state_get; static struct genl_ops *wimax_gnl_ops[] = { &wimax_gnl_msg_from_user, &wimax_gnl_reset, &wimax_gnl_rfkill, &wimax_gnl_state_get, }; static size_t wimax_addr_scnprint(char *addr_str, size_t addr_str_size, unsigned char *addr, size_t addr_len) { unsigned int cnt, total; for (total = cnt = 0; cnt < addr_len; cnt++) total += scnprintf(addr_str + total, addr_str_size - total, "%02x%c", addr[cnt], cnt == addr_len - 1 ? '\0' : ':'); return total; } /** * wimax_dev_add - Register a new WiMAX device * * @wimax_dev: WiMAX device descriptor (as embedded in your @net_dev's * priv data). You must have called wimax_dev_init() on it before. * * @net_dev: net device the @wimax_dev is associated with. The * function expects SET_NETDEV_DEV() and register_netdev() were * already called on it. * * Registers the new WiMAX device, sets up the user-kernel control * interface (generic netlink) and common WiMAX infrastructure. * * Note that the parts that will allow interaction with user space are * setup at the very end, when the rest is in place, as once that * happens, the driver might get user space control requests via * netlink or from debugfs that might translate into calls into * wimax_dev->op_*(). */ int wimax_dev_add(struct wimax_dev *wimax_dev, struct net_device *net_dev) { int result; struct device *dev = net_dev->dev.parent; char addr_str[32]; d_fnstart(3, dev, "(wimax_dev %p net_dev %p)\n", wimax_dev, net_dev); /* Do the RFKILL setup before locking, as RFKILL will call * into our functions. */ wimax_dev->net_dev = net_dev; result = wimax_rfkill_add(wimax_dev); if (result < 0) goto error_rfkill_add; /* Set up user-space interaction */ mutex_lock(&wimax_dev->mutex); wimax_id_table_add(wimax_dev); result = wimax_debugfs_add(wimax_dev); if (result < 0) { dev_err(dev, "cannot initialize debugfs: %d\n", result); goto error_debugfs_add; } __wimax_state_set(wimax_dev, WIMAX_ST_DOWN); mutex_unlock(&wimax_dev->mutex); wimax_addr_scnprint(addr_str, sizeof(addr_str), net_dev->dev_addr, net_dev->addr_len); dev_err(dev, "WiMAX interface %s (%s) ready\n", net_dev->name, addr_str); d_fnend(3, dev, "(wimax_dev %p net_dev %p) = 0\n", wimax_dev, net_dev); return 0; error_debugfs_add: wimax_id_table_rm(wimax_dev); mutex_unlock(&wimax_dev->mutex); wimax_rfkill_rm(wimax_dev); error_rfkill_add: d_fnend(3, dev, "(wimax_dev %p net_dev %p) = %d\n", wimax_dev, net_dev, result); return result; } EXPORT_SYMBOL_GPL(wimax_dev_add); /** * wimax_dev_rm - Unregister an existing WiMAX device * * @wimax_dev: WiMAX device descriptor * * Unregisters a WiMAX device previously registered for use with * wimax_add_rm(). * * IMPORTANT! Must call before calling unregister_netdev(). * * After this function returns, you will not get any more user space * control requests (via netlink or debugfs) and thus to wimax_dev->ops. * * Reentrancy control is ensured by setting the state to * %__WIMAX_ST_QUIESCING. rfkill operations coming through * wimax_*rfkill*() will be stopped by the quiescing state; ops coming * from the rfkill subsystem will be stopped by the support being * removed by wimax_rfkill_rm(). */ void wimax_dev_rm(struct wimax_dev *wimax_dev) { d_fnstart(3, NULL, "(wimax_dev %p)\n", wimax_dev); mutex_lock(&wimax_dev->mutex); __wimax_state_change(wimax_dev, __WIMAX_ST_QUIESCING); wimax_debugfs_rm(wimax_dev); wimax_id_table_rm(wimax_dev); __wimax_state_change(wimax_dev, WIMAX_ST_DOWN); mutex_unlock(&wimax_dev->mutex); wimax_rfkill_rm(wimax_dev); d_fnend(3, NULL, "(wimax_dev %p) = void\n", wimax_dev); } EXPORT_SYMBOL_GPL(wimax_dev_rm); /* Debug framework control of debug levels */ struct d_level D_LEVEL[] = { D_SUBMODULE_DEFINE(debugfs), D_SUBMODULE_DEFINE(id_table), D_SUBMODULE_DEFINE(op_msg), D_SUBMODULE_DEFINE(op_reset), D_SUBMODULE_DEFINE(op_rfkill), D_SUBMODULE_DEFINE(op_state_get), D_SUBMODULE_DEFINE(stack), }; size_t D_LEVEL_SIZE = ARRAY_SIZE(D_LEVEL); struct genl_family wimax_gnl_family = { .id = GENL_ID_GENERATE, .name = "WiMAX", .version = WIMAX_GNL_VERSION, .hdrsize = 0, .maxattr = WIMAX_GNL_ATTR_MAX, }; struct genl_multicast_group wimax_gnl_mcg = { .name = "msg", }; /* Shutdown the wimax stack */ static int __init wimax_subsys_init(void) { int result, cnt; d_fnstart(4, NULL, "()\n"); d_parse_params(D_LEVEL, D_LEVEL_SIZE, wimax_debug_params, "wimax.debug"); snprintf(wimax_gnl_family.name, sizeof(wimax_gnl_family.name), "WiMAX"); result = genl_register_family(&wimax_gnl_family); if (unlikely(result < 0)) { printk(KERN_ERR "cannot register generic netlink family: %d\n", result); goto error_register_family; } for (cnt = 0; cnt < ARRAY_SIZE(wimax_gnl_ops); cnt++) { result = genl_register_ops(&wimax_gnl_family, wimax_gnl_ops[cnt]); d_printf(4, NULL, "registering generic netlink op code " "%u: %d\n", wimax_gnl_ops[cnt]->cmd, result); if (unlikely(result < 0)) { printk(KERN_ERR "cannot register generic netlink op " "code %u: %d\n", wimax_gnl_ops[cnt]->cmd, result); goto error_register_ops; } } result = genl_register_mc_group(&wimax_gnl_family, &wimax_gnl_mcg); if (result < 0) goto error_mc_group; d_fnend(4, NULL, "() = 0\n"); return 0; error_mc_group: error_register_ops: for (cnt--; cnt >= 0; cnt--) genl_unregister_ops(&wimax_gnl_family, wimax_gnl_ops[cnt]); genl_unregister_family(&wimax_gnl_family); error_register_family: d_fnend(4, NULL, "() = %d\n", result); return result; } module_init(wimax_subsys_init); /* Shutdown the wimax stack */ static void __exit wimax_subsys_exit(void) { int cnt; wimax_id_table_release(); genl_unregister_mc_group(&wimax_gnl_family, &wimax_gnl_mcg); for (cnt = ARRAY_SIZE(wimax_gnl_ops) - 1; cnt >= 0; cnt--) genl_unregister_ops(&wimax_gnl_family, wimax_gnl_ops[cnt]); genl_unregister_family(&wimax_gnl_family); } module_exit(wimax_subsys_exit); MODULE_AUTHOR("Intel Corporation <linux-wimax@intel.com>"); MODULE_DESCRIPTION("Linux WiMAX stack"); MODULE_LICENSE("GPL");
gpl-2.0
sakuramilk/linux-3.0.y
sound/pci/au88x0/au88x0_core.c
3096
79116
/* * 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 Library 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. */ /* Vortex core low level functions. Author: Manuel Jander (mjander@users.sourceforge.cl) These functions are mainly the result of translations made from the original disassembly of the au88x0 binary drivers, written by Aureal before they went down. Many thanks to the Jeff Muizelaar, Kester Maddock, and whoever contributed to the OpenVortex project. The author of this file, put the few available pieces together and translated the rest of the riddle (Mix, Src and connection stuff). Some things are still to be discovered, and their meanings are unclear. Some of these functions aren't intended to be really used, rather to help to understand how does the AU88X0 chips work. Keep them in, because they could be used somewhere in the future. This code hasn't been tested or proof read thoroughly. If you wanna help, take a look at the AU88X0 assembly and check if this matches. Functions tested ok so far are (they show the desired effect at least): vortex_routes(); (1 bug fixed). vortex_adb_addroute(); vortex_adb_addroutes(); vortex_connect_codecplay(); vortex_src_flushbuffers(); vortex_adbdma_setmode(); note: still some unknown arguments! vortex_adbdma_startfifo(); vortex_adbdma_stopfifo(); vortex_fifo_setadbctrl(); note: still some unknown arguments! vortex_mix_setinputvolumebyte(); vortex_mix_enableinput(); vortex_mixer_addWTD(); (fixed) vortex_connection_adbdma_src_src(); vortex_connection_adbdma_src(); vortex_src_change_convratio(); vortex_src_addWTD(); (fixed) History: 01-03-2003 First revision. 01-21-2003 Some bug fixes. 17-02-2003 many bugfixes after a big versioning mess. 18-02-2003 JAAAAAHHHUUUUUU!!!! The mixer works !! I'm just so happy ! (2 hours later...) I cant believe it! Im really lucky today. Now the SRC is working too! Yeah! XMMS works ! 20-02-2003 First steps into the ALSA world. 28-02-2003 As my birthday present, i discovered how the DMA buffer pages really work :-). It was all wrong. 12-03-2003 ALSA driver starts working (2 channels). 16-03-2003 More srcblock_setupchannel discoveries. 12-04-2003 AU8830 playback support. Recording in the works. 17-04-2003 vortex_route() and vortex_routes() bug fixes. AU8830 recording works now, but chipn' dale effect is still there. 16-05-2003 SrcSetupChannel cleanup. Moved the Src setup stuff entirely into au88x0_pcm.c . 06-06-2003 Buffer shifter bugfix. Mixer volume fix. 07-12-2003 A3D routing finally fixed. Believed to be OK. 25-03-2004 Many thanks to Claudia, for such valuable bug reports. */ #include "au88x0.h" #include "au88x0_a3d.h" #include <linux/delay.h> /* MIXER (CAsp4Mix.s and CAsp4Mixer.s) */ // FIXME: get rid of this. static int mchannels[NR_MIXIN]; static int rampchs[NR_MIXIN]; static void vortex_mixer_en_sr(vortex_t * vortex, int channel) { hwwrite(vortex->mmio, VORTEX_MIXER_SR, hwread(vortex->mmio, VORTEX_MIXER_SR) | (0x1 << channel)); } static void vortex_mixer_dis_sr(vortex_t * vortex, int channel) { hwwrite(vortex->mmio, VORTEX_MIXER_SR, hwread(vortex->mmio, VORTEX_MIXER_SR) & ~(0x1 << channel)); } #if 0 static void vortex_mix_muteinputgain(vortex_t * vortex, unsigned char mix, unsigned char channel) { hwwrite(vortex->mmio, VORTEX_MIX_INVOL_A + ((mix << 5) + channel), 0x80); hwwrite(vortex->mmio, VORTEX_MIX_INVOL_B + ((mix << 5) + channel), 0x80); } static int vortex_mix_getvolume(vortex_t * vortex, unsigned char mix) { int a; a = hwread(vortex->mmio, VORTEX_MIX_VOL_A + (mix << 2)) & 0xff; //FP2LinearFrac(a); return (a); } static int vortex_mix_getinputvolume(vortex_t * vortex, unsigned char mix, int channel, int *vol) { int a; if (!(mchannels[mix] & (1 << channel))) return 0; a = hwread(vortex->mmio, VORTEX_MIX_INVOL_A + (((mix << 5) + channel) << 2)); /* if (rampchs[mix] == 0) a = FP2LinearFrac(a); else a = FP2LinearFracWT(a); */ *vol = a; return (0); } static unsigned int vortex_mix_boost6db(unsigned char vol) { return (vol + 8); /* WOW! what a complex function! */ } static void vortex_mix_rampvolume(vortex_t * vortex, int mix) { int ch; char a; // This function is intended for ramping down only (see vortex_disableinput()). for (ch = 0; ch < 0x20; ch++) { if (((1 << ch) & rampchs[mix]) == 0) continue; a = hwread(vortex->mmio, VORTEX_MIX_INVOL_B + (((mix << 5) + ch) << 2)); if (a > -126) { a -= 2; hwwrite(vortex->mmio, VORTEX_MIX_INVOL_A + (((mix << 5) + ch) << 2), a); hwwrite(vortex->mmio, VORTEX_MIX_INVOL_B + (((mix << 5) + ch) << 2), a); } else vortex_mix_killinput(vortex, mix, ch); } } static int vortex_mix_getenablebit(vortex_t * vortex, unsigned char mix, int mixin) { int addr, temp; if (mixin >= 0) addr = mixin; else addr = mixin + 3; addr = ((mix << 3) + (addr >> 2)) << 2; temp = hwread(vortex->mmio, VORTEX_MIX_ENIN + addr); return ((temp >> (mixin & 3)) & 1); } #endif static void vortex_mix_setvolumebyte(vortex_t * vortex, unsigned char mix, unsigned char vol) { int temp; hwwrite(vortex->mmio, VORTEX_MIX_VOL_A + (mix << 2), vol); if (1) { /*if (this_10) */ temp = hwread(vortex->mmio, VORTEX_MIX_VOL_B + (mix << 2)); if ((temp != 0x80) || (vol == 0x80)) return; } hwwrite(vortex->mmio, VORTEX_MIX_VOL_B + (mix << 2), vol); } static void vortex_mix_setinputvolumebyte(vortex_t * vortex, unsigned char mix, int mixin, unsigned char vol) { int temp; hwwrite(vortex->mmio, VORTEX_MIX_INVOL_A + (((mix << 5) + mixin) << 2), vol); if (1) { /* this_10, initialized to 1. */ temp = hwread(vortex->mmio, VORTEX_MIX_INVOL_B + (((mix << 5) + mixin) << 2)); if ((temp != 0x80) || (vol == 0x80)) return; } hwwrite(vortex->mmio, VORTEX_MIX_INVOL_B + (((mix << 5) + mixin) << 2), vol); } static void vortex_mix_setenablebit(vortex_t * vortex, unsigned char mix, int mixin, int en) { int temp, addr; if (mixin < 0) addr = (mixin + 3); else addr = mixin; addr = ((mix << 3) + (addr >> 2)) << 2; temp = hwread(vortex->mmio, VORTEX_MIX_ENIN + addr); if (en) temp |= (1 << (mixin & 3)); else temp &= ~(1 << (mixin & 3)); /* Mute input. Astatic void crackling? */ hwwrite(vortex->mmio, VORTEX_MIX_INVOL_B + (((mix << 5) + mixin) << 2), 0x80); /* Looks like clear buffer. */ hwwrite(vortex->mmio, VORTEX_MIX_SMP + (mixin << 2), 0x0); hwwrite(vortex->mmio, VORTEX_MIX_SMP + 4 + (mixin << 2), 0x0); /* Write enable bit. */ hwwrite(vortex->mmio, VORTEX_MIX_ENIN + addr, temp); } static void vortex_mix_killinput(vortex_t * vortex, unsigned char mix, int mixin) { rampchs[mix] &= ~(1 << mixin); vortex_mix_setinputvolumebyte(vortex, mix, mixin, 0x80); mchannels[mix] &= ~(1 << mixin); vortex_mix_setenablebit(vortex, mix, mixin, 0); } static void vortex_mix_enableinput(vortex_t * vortex, unsigned char mix, int mixin) { vortex_mix_killinput(vortex, mix, mixin); if ((mchannels[mix] & (1 << mixin)) == 0) { vortex_mix_setinputvolumebyte(vortex, mix, mixin, 0x80); /*0x80 : mute */ mchannels[mix] |= (1 << mixin); } vortex_mix_setenablebit(vortex, mix, mixin, 1); } static void vortex_mix_disableinput(vortex_t * vortex, unsigned char mix, int channel, int ramp) { if (ramp) { rampchs[mix] |= (1 << channel); // Register callback. //vortex_mix_startrampvolume(vortex); vortex_mix_killinput(vortex, mix, channel); } else vortex_mix_killinput(vortex, mix, channel); } static int vortex_mixer_addWTD(vortex_t * vortex, unsigned char mix, unsigned char ch) { int temp, lifeboat = 0, prev; temp = hwread(vortex->mmio, VORTEX_MIXER_SR); if ((temp & (1 << ch)) == 0) { hwwrite(vortex->mmio, VORTEX_MIXER_CHNBASE + (ch << 2), mix); vortex_mixer_en_sr(vortex, ch); return 1; } prev = VORTEX_MIXER_CHNBASE + (ch << 2); temp = hwread(vortex->mmio, prev); while (temp & 0x10) { prev = VORTEX_MIXER_RTBASE + ((temp & 0xf) << 2); temp = hwread(vortex->mmio, prev); //printk(KERN_INFO "vortex: mixAddWTD: while addr=%x, val=%x\n", prev, temp); if ((++lifeboat) > 0xf) { printk(KERN_ERR "vortex_mixer_addWTD: lifeboat overflow\n"); return 0; } } hwwrite(vortex->mmio, VORTEX_MIXER_RTBASE + ((temp & 0xf) << 2), mix); hwwrite(vortex->mmio, prev, (temp & 0xf) | 0x10); return 1; } static int vortex_mixer_delWTD(vortex_t * vortex, unsigned char mix, unsigned char ch) { int esp14 = -1, esp18, eax, ebx, edx, ebp, esi = 0; //int esp1f=edi(while)=src, esp10=ch; eax = hwread(vortex->mmio, VORTEX_MIXER_SR); if (((1 << ch) & eax) == 0) { printk(KERN_ERR "mix ALARM %x\n", eax); return 0; } ebp = VORTEX_MIXER_CHNBASE + (ch << 2); esp18 = hwread(vortex->mmio, ebp); if (esp18 & 0x10) { ebx = (esp18 & 0xf); if (mix == ebx) { ebx = VORTEX_MIXER_RTBASE + (mix << 2); edx = hwread(vortex->mmio, ebx); //7b60 hwwrite(vortex->mmio, ebp, edx); hwwrite(vortex->mmio, ebx, 0); } else { //7ad3 edx = hwread(vortex->mmio, VORTEX_MIXER_RTBASE + (ebx << 2)); //printk(KERN_INFO "vortex: mixdelWTD: 1 addr=%x, val=%x, src=%x\n", ebx, edx, src); while ((edx & 0xf) != mix) { if ((esi) > 0xf) { printk(KERN_ERR "vortex: mixdelWTD: error lifeboat overflow\n"); return 0; } esp14 = ebx; ebx = edx & 0xf; ebp = ebx << 2; edx = hwread(vortex->mmio, VORTEX_MIXER_RTBASE + ebp); //printk(KERN_INFO "vortex: mixdelWTD: while addr=%x, val=%x\n", ebp, edx); esi++; } //7b30 ebp = ebx << 2; if (edx & 0x10) { /* Delete entry in between others */ ebx = VORTEX_MIXER_RTBASE + ((edx & 0xf) << 2); edx = hwread(vortex->mmio, ebx); //7b60 hwwrite(vortex->mmio, VORTEX_MIXER_RTBASE + ebp, edx); hwwrite(vortex->mmio, ebx, 0); //printk(KERN_INFO "vortex mixdelWTD between addr= 0x%x, val= 0x%x\n", ebp, edx); } else { /* Delete last entry */ //7b83 if (esp14 == -1) hwwrite(vortex->mmio, VORTEX_MIXER_CHNBASE + (ch << 2), esp18 & 0xef); else { ebx = (0xffffffe0 & edx) | (0xf & ebx); hwwrite(vortex->mmio, VORTEX_MIXER_RTBASE + (esp14 << 2), ebx); //printk(KERN_INFO "vortex mixdelWTD last addr= 0x%x, val= 0x%x\n", esp14, ebx); } hwwrite(vortex->mmio, VORTEX_MIXER_RTBASE + ebp, 0); return 1; } } } else { //printk(KERN_INFO "removed last mix\n"); //7be0 vortex_mixer_dis_sr(vortex, ch); hwwrite(vortex->mmio, ebp, 0); } return 1; } static void vortex_mixer_init(vortex_t * vortex) { u32 addr; int x; // FIXME: get rid of this crap. memset(mchannels, 0, NR_MIXOUT * sizeof(int)); memset(rampchs, 0, NR_MIXOUT * sizeof(int)); addr = VORTEX_MIX_SMP + 0x17c; for (x = 0x5f; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0); addr -= 4; } addr = VORTEX_MIX_ENIN + 0x1fc; for (x = 0x7f; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0); addr -= 4; } addr = VORTEX_MIX_SMP + 0x17c; for (x = 0x5f; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0); addr -= 4; } addr = VORTEX_MIX_INVOL_A + 0x7fc; for (x = 0x1ff; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0x80); addr -= 4; } addr = VORTEX_MIX_VOL_A + 0x3c; for (x = 0xf; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0x80); addr -= 4; } addr = VORTEX_MIX_INVOL_B + 0x7fc; for (x = 0x1ff; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0x80); addr -= 4; } addr = VORTEX_MIX_VOL_B + 0x3c; for (x = 0xf; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0x80); addr -= 4; } addr = VORTEX_MIXER_RTBASE + (MIXER_RTBASE_SIZE - 1) * 4; for (x = (MIXER_RTBASE_SIZE - 1); x >= 0; x--) { hwwrite(vortex->mmio, addr, 0x0); addr -= 4; } hwwrite(vortex->mmio, VORTEX_MIXER_SR, 0); /* Set clipping ceiling (this may be all wrong). */ /* for (x = 0; x < 0x80; x++) { hwwrite(vortex->mmio, VORTEX_MIXER_CLIP + (x << 2), 0x3ffff); } */ /* call CAsp4Mix__Initialize_CAsp4HwIO____CAsp4Mixer____ Register ISR callback for volume smooth fade out. Maybe this avoids clicks when press "stop" ? */ } /* SRC (CAsp4Src.s and CAsp4SrcBlock) */ static void vortex_src_en_sr(vortex_t * vortex, int channel) { hwwrite(vortex->mmio, VORTEX_SRCBLOCK_SR, hwread(vortex->mmio, VORTEX_SRCBLOCK_SR) | (0x1 << channel)); } static void vortex_src_dis_sr(vortex_t * vortex, int channel) { hwwrite(vortex->mmio, VORTEX_SRCBLOCK_SR, hwread(vortex->mmio, VORTEX_SRCBLOCK_SR) & ~(0x1 << channel)); } static void vortex_src_flushbuffers(vortex_t * vortex, unsigned char src) { int i; for (i = 0x1f; i >= 0; i--) hwwrite(vortex->mmio, VORTEX_SRC_DATA0 + (src << 7) + (i << 2), 0); hwwrite(vortex->mmio, VORTEX_SRC_DATA + (src << 3), 0); hwwrite(vortex->mmio, VORTEX_SRC_DATA + (src << 3) + 4, 0); } static void vortex_src_cleardrift(vortex_t * vortex, unsigned char src) { hwwrite(vortex->mmio, VORTEX_SRC_DRIFT0 + (src << 2), 0); hwwrite(vortex->mmio, VORTEX_SRC_DRIFT1 + (src << 2), 0); hwwrite(vortex->mmio, VORTEX_SRC_DRIFT2 + (src << 2), 1); } static void vortex_src_set_throttlesource(vortex_t * vortex, unsigned char src, int en) { int temp; temp = hwread(vortex->mmio, VORTEX_SRC_SOURCE); if (en) temp |= 1 << src; else temp &= ~(1 << src); hwwrite(vortex->mmio, VORTEX_SRC_SOURCE, temp); } static int vortex_src_persist_convratio(vortex_t * vortex, unsigned char src, int ratio) { int temp, lifeboat = 0; do { hwwrite(vortex->mmio, VORTEX_SRC_CONVRATIO + (src << 2), ratio); temp = hwread(vortex->mmio, VORTEX_SRC_CONVRATIO + (src << 2)); if ((++lifeboat) > 0x9) { printk(KERN_ERR "Vortex: Src cvr fail\n"); break; } } while (temp != ratio); return temp; } #if 0 static void vortex_src_slowlock(vortex_t * vortex, unsigned char src) { int temp; hwwrite(vortex->mmio, VORTEX_SRC_DRIFT2 + (src << 2), 1); hwwrite(vortex->mmio, VORTEX_SRC_DRIFT0 + (src << 2), 0); temp = hwread(vortex->mmio, VORTEX_SRC_U0 + (src << 2)); if (temp & 0x200) hwwrite(vortex->mmio, VORTEX_SRC_U0 + (src << 2), temp & ~0x200L); } static void vortex_src_change_convratio(vortex_t * vortex, unsigned char src, int ratio) { int temp, a; if ((ratio & 0x10000) && (ratio != 0x10000)) { if (ratio & 0x3fff) a = (0x11 - ((ratio >> 0xe) & 0x3)) - 1; else a = (0x11 - ((ratio >> 0xe) & 0x3)) - 2; } else a = 0xc; temp = hwread(vortex->mmio, VORTEX_SRC_U0 + (src << 2)); if (((temp >> 4) & 0xf) != a) hwwrite(vortex->mmio, VORTEX_SRC_U0 + (src << 2), (temp & 0xf) | ((a & 0xf) << 4)); vortex_src_persist_convratio(vortex, src, ratio); } static int vortex_src_checkratio(vortex_t * vortex, unsigned char src, unsigned int desired_ratio) { int hw_ratio, lifeboat = 0; hw_ratio = hwread(vortex->mmio, VORTEX_SRC_CONVRATIO + (src << 2)); while (hw_ratio != desired_ratio) { hwwrite(vortex->mmio, VORTEX_SRC_CONVRATIO + (src << 2), desired_ratio); if ((lifeboat++) > 15) { printk(KERN_ERR "Vortex: could not set src-%d from %d to %d\n", src, hw_ratio, desired_ratio); break; } } return hw_ratio; } #endif /* Objective: Set samplerate for given SRC module. Arguments: card: pointer to vortex_t strcut. src: Integer index of the SRC module. cr: Current sample rate conversion factor. b: unknown 16 bit value. sweep: Enable Samplerate fade from cr toward tr flag. dirplay: 1: playback, 0: recording. sl: Slow Lock flag. tr: Target samplerate conversion. thsource: Throttle source flag (no idea what that means). */ static void vortex_src_setupchannel(vortex_t * card, unsigned char src, unsigned int cr, unsigned int b, int sweep, int d, int dirplay, int sl, unsigned int tr, int thsource) { // noplayback: d=2,4,7,0xa,0xb when using first 2 src's. // c: enables pitch sweep. // looks like g is c related. Maybe g is a sweep parameter ? // g = cvr // dirplay: 0 = recording, 1 = playback // d = src hw index. int esi, ebp = 0, esp10; vortex_src_flushbuffers(card, src); if (sweep) { if ((tr & 0x10000) && (tr != 0x10000)) { tr = 0; esi = 0x7; } else { if ((((short)tr) < 0) && (tr != 0x8000)) { tr = 0; esi = 0x8; } else { tr = 1; esi = 0xc; } } } else { if ((cr & 0x10000) && (cr != 0x10000)) { tr = 0; /*ebx = 0 */ esi = 0x11 - ((cr >> 0xe) & 7); if (cr & 0x3fff) esi -= 1; else esi -= 2; } else { tr = 1; esi = 0xc; } } vortex_src_cleardrift(card, src); vortex_src_set_throttlesource(card, src, thsource); if ((dirplay == 0) && (sweep == 0)) { if (tr) esp10 = 0xf; else esp10 = 0xc; ebp = 0; } else { if (tr) ebp = 0xf; else ebp = 0xc; esp10 = 0; } hwwrite(card->mmio, VORTEX_SRC_U0 + (src << 2), (sl << 0x9) | (sweep << 0x8) | ((esi & 0xf) << 4) | d); /* 0xc0 esi=0xc c=f=0 d=0 */ vortex_src_persist_convratio(card, src, cr); hwwrite(card->mmio, VORTEX_SRC_U1 + (src << 2), b & 0xffff); /* 0 b=0 */ hwwrite(card->mmio, VORTEX_SRC_U2 + (src << 2), (tr << 0x11) | (dirplay << 0x10) | (ebp << 0x8) | esp10); /* 0x30f00 e=g=1 esp10=0 ebp=f */ //printk(KERN_INFO "vortex: SRC %d, d=0x%x, esi=0x%x, esp10=0x%x, ebp=0x%x\n", src, d, esi, esp10, ebp); } static void vortex_srcblock_init(vortex_t * vortex) { u32 addr; int x; hwwrite(vortex->mmio, VORTEX_SRC_SOURCESIZE, 0x1ff); /* for (x=0; x<0x10; x++) { vortex_src_init(&vortex_src[x], x); } */ //addr = 0xcc3c; //addr = 0x26c3c; addr = VORTEX_SRC_RTBASE + 0x3c; for (x = 0xf; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0); addr -= 4; } //addr = 0xcc94; //addr = 0x26c94; addr = VORTEX_SRC_CHNBASE + 0x54; for (x = 0x15; x >= 0; x--) { hwwrite(vortex->mmio, addr, 0); addr -= 4; } } static int vortex_src_addWTD(vortex_t * vortex, unsigned char src, unsigned char ch) { int temp, lifeboat = 0, prev; // esp13 = src temp = hwread(vortex->mmio, VORTEX_SRCBLOCK_SR); if ((temp & (1 << ch)) == 0) { hwwrite(vortex->mmio, VORTEX_SRC_CHNBASE + (ch << 2), src); vortex_src_en_sr(vortex, ch); return 1; } prev = VORTEX_SRC_CHNBASE + (ch << 2); /*ebp */ temp = hwread(vortex->mmio, prev); //while (temp & NR_SRC) { while (temp & 0x10) { prev = VORTEX_SRC_RTBASE + ((temp & 0xf) << 2); /*esp12 */ //prev = VORTEX_SRC_RTBASE + ((temp & (NR_SRC-1)) << 2); /*esp12*/ temp = hwread(vortex->mmio, prev); //printk(KERN_INFO "vortex: srcAddWTD: while addr=%x, val=%x\n", prev, temp); if ((++lifeboat) > 0xf) { printk(KERN_ERR "vortex_src_addWTD: lifeboat overflow\n"); return 0; } } hwwrite(vortex->mmio, VORTEX_SRC_RTBASE + ((temp & 0xf) << 2), src); //hwwrite(vortex->mmio, prev, (temp & (NR_SRC-1)) | NR_SRC); hwwrite(vortex->mmio, prev, (temp & 0xf) | 0x10); return 1; } static int vortex_src_delWTD(vortex_t * vortex, unsigned char src, unsigned char ch) { int esp14 = -1, esp18, eax, ebx, edx, ebp, esi = 0; //int esp1f=edi(while)=src, esp10=ch; eax = hwread(vortex->mmio, VORTEX_SRCBLOCK_SR); if (((1 << ch) & eax) == 0) { printk(KERN_ERR "src alarm\n"); return 0; } ebp = VORTEX_SRC_CHNBASE + (ch << 2); esp18 = hwread(vortex->mmio, ebp); if (esp18 & 0x10) { ebx = (esp18 & 0xf); if (src == ebx) { ebx = VORTEX_SRC_RTBASE + (src << 2); edx = hwread(vortex->mmio, ebx); //7b60 hwwrite(vortex->mmio, ebp, edx); hwwrite(vortex->mmio, ebx, 0); } else { //7ad3 edx = hwread(vortex->mmio, VORTEX_SRC_RTBASE + (ebx << 2)); //printk(KERN_INFO "vortex: srcdelWTD: 1 addr=%x, val=%x, src=%x\n", ebx, edx, src); while ((edx & 0xf) != src) { if ((esi) > 0xf) { printk ("vortex: srcdelWTD: error, lifeboat overflow\n"); return 0; } esp14 = ebx; ebx = edx & 0xf; ebp = ebx << 2; edx = hwread(vortex->mmio, VORTEX_SRC_RTBASE + ebp); //printk(KERN_INFO "vortex: srcdelWTD: while addr=%x, val=%x\n", ebp, edx); esi++; } //7b30 ebp = ebx << 2; if (edx & 0x10) { /* Delete entry in between others */ ebx = VORTEX_SRC_RTBASE + ((edx & 0xf) << 2); edx = hwread(vortex->mmio, ebx); //7b60 hwwrite(vortex->mmio, VORTEX_SRC_RTBASE + ebp, edx); hwwrite(vortex->mmio, ebx, 0); //printk(KERN_INFO "vortex srcdelWTD between addr= 0x%x, val= 0x%x\n", ebp, edx); } else { /* Delete last entry */ //7b83 if (esp14 == -1) hwwrite(vortex->mmio, VORTEX_SRC_CHNBASE + (ch << 2), esp18 & 0xef); else { ebx = (0xffffffe0 & edx) | (0xf & ebx); hwwrite(vortex->mmio, VORTEX_SRC_RTBASE + (esp14 << 2), ebx); //printk(KERN_INFO"vortex srcdelWTD last addr= 0x%x, val= 0x%x\n", esp14, ebx); } hwwrite(vortex->mmio, VORTEX_SRC_RTBASE + ebp, 0); return 1; } } } else { //7be0 vortex_src_dis_sr(vortex, ch); hwwrite(vortex->mmio, ebp, 0); } return 1; } /*FIFO*/ static void vortex_fifo_clearadbdata(vortex_t * vortex, int fifo, int x) { for (x--; x >= 0; x--) hwwrite(vortex->mmio, VORTEX_FIFO_ADBDATA + (((fifo << FIFO_SIZE_BITS) + x) << 2), 0); } #if 0 static void vortex_fifo_adbinitialize(vortex_t * vortex, int fifo, int j) { vortex_fifo_clearadbdata(vortex, fifo, FIFO_SIZE); #ifdef CHIP_AU8820 hwwrite(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2), (FIFO_U1 | ((j & FIFO_MASK) << 0xb))); #else hwwrite(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2), (FIFO_U1 | ((j & FIFO_MASK) << 0xc))); #endif } #endif static void vortex_fifo_setadbvalid(vortex_t * vortex, int fifo, int en) { hwwrite(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2), (hwread(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2)) & 0xffffffef) | ((1 & en) << 4) | FIFO_U1); } static void vortex_fifo_setadbctrl(vortex_t * vortex, int fifo, int b, int priority, int empty, int valid, int f) { int temp, lifeboat = 0; //int this_8[NR_ADB] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* position */ int this_4 = 0x2; /* f seems priority related. * CAsp4AdbDma::SetPriority is the only place that calls SetAdbCtrl with f set to 1 * every where else it is set to 0. It seems, however, that CAsp4AdbDma::SetPriority * is never called, thus the f related bits remain a mystery for now. */ do { temp = hwread(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2)); if (lifeboat++ > 0xbb8) { printk(KERN_ERR "Vortex: vortex_fifo_setadbctrl fail\n"); break; } } while (temp & FIFO_RDONLY); // AU8830 semes to take some special care about fifo content (data). // But i'm just to lazy to translate that :) if (valid) { if ((temp & FIFO_VALID) == 0) { //this_8[fifo] = 0; vortex_fifo_clearadbdata(vortex, fifo, FIFO_SIZE); // this_4 #ifdef CHIP_AU8820 temp = (this_4 & 0x1f) << 0xb; #else temp = (this_4 & 0x3f) << 0xc; #endif temp = (temp & 0xfffffffd) | ((b & 1) << 1); temp = (temp & 0xfffffff3) | ((priority & 3) << 2); temp = (temp & 0xffffffef) | ((valid & 1) << 4); temp |= FIFO_U1; temp = (temp & 0xffffffdf) | ((empty & 1) << 5); #ifdef CHIP_AU8820 temp = (temp & 0xfffbffff) | ((f & 1) << 0x12); #endif #ifdef CHIP_AU8830 temp = (temp & 0xf7ffffff) | ((f & 1) << 0x1b); temp = (temp & 0xefffffff) | ((f & 1) << 0x1c); #endif #ifdef CHIP_AU8810 temp = (temp & 0xfeffffff) | ((f & 1) << 0x18); temp = (temp & 0xfdffffff) | ((f & 1) << 0x19); #endif } } else { if (temp & FIFO_VALID) { #ifdef CHIP_AU8820 temp = ((f & 1) << 0x12) | (temp & 0xfffbffef); #endif #ifdef CHIP_AU8830 temp = ((f & 1) << 0x1b) | (temp & 0xe7ffffef) | FIFO_BITS; #endif #ifdef CHIP_AU8810 temp = ((f & 1) << 0x18) | (temp & 0xfcffffef) | FIFO_BITS; #endif } else /*if (this_8[fifo]) */ vortex_fifo_clearadbdata(vortex, fifo, FIFO_SIZE); } hwwrite(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2), temp); hwread(vortex->mmio, VORTEX_FIFO_ADBCTRL + (fifo << 2)); } #ifndef CHIP_AU8810 static void vortex_fifo_clearwtdata(vortex_t * vortex, int fifo, int x) { if (x < 1) return; for (x--; x >= 0; x--) hwwrite(vortex->mmio, VORTEX_FIFO_WTDATA + (((fifo << FIFO_SIZE_BITS) + x) << 2), 0); } static void vortex_fifo_wtinitialize(vortex_t * vortex, int fifo, int j) { vortex_fifo_clearwtdata(vortex, fifo, FIFO_SIZE); #ifdef CHIP_AU8820 hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), (FIFO_U1 | ((j & FIFO_MASK) << 0xb))); #else hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), (FIFO_U1 | ((j & FIFO_MASK) << 0xc))); #endif } static void vortex_fifo_setwtvalid(vortex_t * vortex, int fifo, int en) { hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), (hwread(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2)) & 0xffffffef) | ((en & 1) << 4) | FIFO_U1); } static void vortex_fifo_setwtctrl(vortex_t * vortex, int fifo, int ctrl, int priority, int empty, int valid, int f) { int temp = 0, lifeboat = 0; int this_4 = 2; do { temp = hwread(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2)); if (lifeboat++ > 0xbb8) { printk(KERN_ERR "Vortex: vortex_fifo_setwtctrl fail\n"); break; } } while (temp & FIFO_RDONLY); if (valid) { if ((temp & FIFO_VALID) == 0) { vortex_fifo_clearwtdata(vortex, fifo, FIFO_SIZE); // this_4 #ifdef CHIP_AU8820 temp = (this_4 & 0x1f) << 0xb; #else temp = (this_4 & 0x3f) << 0xc; #endif temp = (temp & 0xfffffffd) | ((ctrl & 1) << 1); temp = (temp & 0xfffffff3) | ((priority & 3) << 2); temp = (temp & 0xffffffef) | ((valid & 1) << 4); temp |= FIFO_U1; temp = (temp & 0xffffffdf) | ((empty & 1) << 5); #ifdef CHIP_AU8820 temp = (temp & 0xfffbffff) | ((f & 1) << 0x12); #endif #ifdef CHIP_AU8830 temp = (temp & 0xf7ffffff) | ((f & 1) << 0x1b); temp = (temp & 0xefffffff) | ((f & 1) << 0x1c); #endif #ifdef CHIP_AU8810 temp = (temp & 0xfeffffff) | ((f & 1) << 0x18); temp = (temp & 0xfdffffff) | ((f & 1) << 0x19); #endif } } else { if (temp & FIFO_VALID) { #ifdef CHIP_AU8820 temp = ((f & 1) << 0x12) | (temp & 0xfffbffef); #endif #ifdef CHIP_AU8830 temp = ((f & 1) << 0x1b) | (temp & 0xe7ffffef) | FIFO_BITS; #endif #ifdef CHIP_AU8810 temp = ((f & 1) << 0x18) | (temp & 0xfcffffef) | FIFO_BITS; #endif } else /*if (this_8[fifo]) */ vortex_fifo_clearwtdata(vortex, fifo, FIFO_SIZE); } hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), temp); hwread(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2)); /* do { temp = hwread(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2)); if (lifeboat++ > 0xbb8) { printk(KERN_ERR "Vortex: vortex_fifo_setwtctrl fail (hanging)\n"); break; } } while ((temp & FIFO_RDONLY)&&(temp & FIFO_VALID)&&(temp != 0xFFFFFFFF)); if (valid) { if (temp & FIFO_VALID) { temp = 0x40000; //temp |= 0x08000000; //temp |= 0x10000000; //temp |= 0x04000000; //temp |= 0x00400000; temp |= 0x1c400000; temp &= 0xFFFFFFF3; temp &= 0xFFFFFFEF; temp |= (valid & 1) << 4; hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), temp); return; } else { vortex_fifo_clearwtdata(vortex, fifo, FIFO_SIZE); return; } } else { temp &= 0xffffffef; temp |= 0x08000000; temp |= 0x10000000; temp |= 0x04000000; temp |= 0x00400000; hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), temp); temp = hwread(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2)); //((temp >> 6) & 0x3f) priority = 0; if (((temp & 0x0fc0) ^ ((temp >> 6) & 0x0fc0)) & 0FFFFFFC0) vortex_fifo_clearwtdata(vortex, fifo, FIFO_SIZE); valid = 0xfb; temp = (temp & 0xfffffffd) | ((ctrl & 1) << 1); temp = (temp & 0xfffdffff) | ((f & 1) << 0x11); temp = (temp & 0xfffffff3) | ((priority & 3) << 2); temp = (temp & 0xffffffef) | ((valid & 1) << 4); temp = (temp & 0xffffffdf) | ((empty & 1) << 5); hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), temp); } */ /* temp = (temp & 0xfffffffd) | ((ctrl & 1) << 1); temp = (temp & 0xfffdffff) | ((f & 1) << 0x11); temp = (temp & 0xfffffff3) | ((priority & 3) << 2); temp = (temp & 0xffffffef) | ((valid & 1) << 4); temp = (temp & 0xffffffdf) | ((empty & 1) << 5); #ifdef FIFO_BITS temp = temp | FIFO_BITS | 40000; #endif // 0x1c440010, 0x1c400000 hwwrite(vortex->mmio, VORTEX_FIFO_WTCTRL + (fifo << 2), temp); */ } #endif static void vortex_fifo_init(vortex_t * vortex) { int x; u32 addr; /* ADB DMA channels fifos. */ addr = VORTEX_FIFO_ADBCTRL + ((NR_ADB - 1) * 4); for (x = NR_ADB - 1; x >= 0; x--) { hwwrite(vortex->mmio, addr, (FIFO_U0 | FIFO_U1)); if (hwread(vortex->mmio, addr) != (FIFO_U0 | FIFO_U1)) printk(KERN_ERR "bad adb fifo reset!"); vortex_fifo_clearadbdata(vortex, x, FIFO_SIZE); addr -= 4; } #ifndef CHIP_AU8810 /* WT DMA channels fifos. */ addr = VORTEX_FIFO_WTCTRL + ((NR_WT - 1) * 4); for (x = NR_WT - 1; x >= 0; x--) { hwwrite(vortex->mmio, addr, FIFO_U0); if (hwread(vortex->mmio, addr) != FIFO_U0) printk(KERN_ERR "bad wt fifo reset (0x%08x, 0x%08x)!\n", addr, hwread(vortex->mmio, addr)); vortex_fifo_clearwtdata(vortex, x, FIFO_SIZE); addr -= 4; } #endif /* trigger... */ #ifdef CHIP_AU8820 hwwrite(vortex->mmio, 0xf8c0, 0xd03); //0x0843 0xd6b #else #ifdef CHIP_AU8830 hwwrite(vortex->mmio, 0x17000, 0x61); /* wt a */ hwwrite(vortex->mmio, 0x17004, 0x61); /* wt b */ #endif hwwrite(vortex->mmio, 0x17008, 0x61); /* adb */ #endif } /* ADBDMA */ static void vortex_adbdma_init(vortex_t * vortex) { } static void vortex_adbdma_setfirstbuffer(vortex_t * vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; hwwrite(vortex->mmio, VORTEX_ADBDMA_CTRL + (adbdma << 2), dma->dma_ctrl); } static void vortex_adbdma_setstartbuffer(vortex_t * vortex, int adbdma, int sb) { stream_t *dma = &vortex->dma_adb[adbdma]; //hwwrite(vortex->mmio, VORTEX_ADBDMA_START + (adbdma << 2), sb << (((NR_ADB-1)-((adbdma&0xf)*2)))); hwwrite(vortex->mmio, VORTEX_ADBDMA_START + (adbdma << 2), sb << ((0xf - (adbdma & 0xf)) * 2)); dma->period_real = dma->period_virt = sb; } static void vortex_adbdma_setbuffers(vortex_t * vortex, int adbdma, int psize, int count) { stream_t *dma = &vortex->dma_adb[adbdma]; dma->period_bytes = psize; dma->nr_periods = count; dma->cfg0 = 0; dma->cfg1 = 0; switch (count) { /* Four or more pages */ default: case 4: dma->cfg1 |= 0x88000000 | 0x44000000 | 0x30000000 | (psize - 1); hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (adbdma << 4) + 0xc, snd_pcm_sgbuf_get_addr(dma->substream, psize * 3)); /* 3 pages */ case 3: dma->cfg0 |= 0x12000000; dma->cfg1 |= 0x80000000 | 0x40000000 | ((psize - 1) << 0xc); hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (adbdma << 4) + 0x8, snd_pcm_sgbuf_get_addr(dma->substream, psize * 2)); /* 2 pages */ case 2: dma->cfg0 |= 0x88000000 | 0x44000000 | 0x10000000 | (psize - 1); hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (adbdma << 4) + 0x4, snd_pcm_sgbuf_get_addr(dma->substream, psize)); /* 1 page */ case 1: dma->cfg0 |= 0x80000000 | 0x40000000 | ((psize - 1) << 0xc); hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (adbdma << 4), snd_pcm_sgbuf_get_addr(dma->substream, 0)); break; } /* printk(KERN_DEBUG "vortex: cfg0 = 0x%x\nvortex: cfg1=0x%x\n", dma->cfg0, dma->cfg1); */ hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFCFG0 + (adbdma << 3), dma->cfg0); hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFCFG1 + (adbdma << 3), dma->cfg1); vortex_adbdma_setfirstbuffer(vortex, adbdma); vortex_adbdma_setstartbuffer(vortex, adbdma, 0); } static void vortex_adbdma_setmode(vortex_t * vortex, int adbdma, int ie, int dir, int fmt, int d, u32 offset) { stream_t *dma = &vortex->dma_adb[adbdma]; dma->dma_unknown = d; dma->dma_ctrl = ((offset & OFFSET_MASK) | (dma->dma_ctrl & ~OFFSET_MASK)); /* Enable PCMOUT interrupts. */ dma->dma_ctrl = (dma->dma_ctrl & ~IE_MASK) | ((ie << IE_SHIFT) & IE_MASK); dma->dma_ctrl = (dma->dma_ctrl & ~DIR_MASK) | ((dir << DIR_SHIFT) & DIR_MASK); dma->dma_ctrl = (dma->dma_ctrl & ~FMT_MASK) | ((fmt << FMT_SHIFT) & FMT_MASK); hwwrite(vortex->mmio, VORTEX_ADBDMA_CTRL + (adbdma << 2), dma->dma_ctrl); hwread(vortex->mmio, VORTEX_ADBDMA_CTRL + (adbdma << 2)); } static int vortex_adbdma_bufshift(vortex_t * vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; int page, p, pp, delta, i; page = (hwread(vortex->mmio, VORTEX_ADBDMA_STAT + (adbdma << 2)) & ADB_SUBBUF_MASK) >> ADB_SUBBUF_SHIFT; if (dma->nr_periods >= 4) delta = (page - dma->period_real) & 3; else { delta = (page - dma->period_real); if (delta < 0) delta += dma->nr_periods; } if (delta == 0) return 0; /* refresh hw page table */ if (dma->nr_periods > 4) { for (i = 0; i < delta; i++) { /* p: audio buffer page index */ p = dma->period_virt + i + 4; if (p >= dma->nr_periods) p -= dma->nr_periods; /* pp: hardware DMA page index. */ pp = dma->period_real + i; if (pp >= 4) pp -= 4; //hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE+(((adbdma << 2)+pp) << 2), dma->table[p].addr); hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (((adbdma << 2) + pp) << 2), snd_pcm_sgbuf_get_addr(dma->substream, dma->period_bytes * p)); /* Force write thru cache. */ hwread(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (((adbdma << 2) + pp) << 2)); } } dma->period_virt += delta; dma->period_real = page; if (dma->period_virt >= dma->nr_periods) dma->period_virt -= dma->nr_periods; if (delta != 1) printk(KERN_INFO "vortex: %d virt=%d, real=%d, delta=%d\n", adbdma, dma->period_virt, dma->period_real, delta); return delta; } static void vortex_adbdma_resetup(vortex_t *vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; int p, pp, i; /* refresh hw page table */ for (i=0 ; i < 4 && i < dma->nr_periods; i++) { /* p: audio buffer page index */ p = dma->period_virt + i; if (p >= dma->nr_periods) p -= dma->nr_periods; /* pp: hardware DMA page index. */ pp = dma->period_real + i; if (dma->nr_periods < 4) { if (pp >= dma->nr_periods) pp -= dma->nr_periods; } else { if (pp >= 4) pp -= 4; } hwwrite(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (((adbdma << 2) + pp) << 2), snd_pcm_sgbuf_get_addr(dma->substream, dma->period_bytes * p)); /* Force write thru cache. */ hwread(vortex->mmio, VORTEX_ADBDMA_BUFBASE + (((adbdma << 2)+pp) << 2)); } } static inline int vortex_adbdma_getlinearpos(vortex_t * vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; int temp, page, delta; temp = hwread(vortex->mmio, VORTEX_ADBDMA_STAT + (adbdma << 2)); page = (temp & ADB_SUBBUF_MASK) >> ADB_SUBBUF_SHIFT; if (dma->nr_periods >= 4) delta = (page - dma->period_real) & 3; else { delta = (page - dma->period_real); if (delta < 0) delta += dma->nr_periods; } return (dma->period_virt + delta) * dma->period_bytes + (temp & (dma->period_bytes - 1)); } static void vortex_adbdma_startfifo(vortex_t * vortex, int adbdma) { int this_8 = 0 /*empty */ , this_4 = 0 /*priority */ ; stream_t *dma = &vortex->dma_adb[adbdma]; switch (dma->fifo_status) { case FIFO_START: vortex_fifo_setadbvalid(vortex, adbdma, dma->fifo_enabled ? 1 : 0); break; case FIFO_STOP: this_8 = 1; hwwrite(vortex->mmio, VORTEX_ADBDMA_CTRL + (adbdma << 2), dma->dma_ctrl); vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; case FIFO_PAUSE: vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; } dma->fifo_status = FIFO_START; } static void vortex_adbdma_resumefifo(vortex_t * vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; int this_8 = 1, this_4 = 0; switch (dma->fifo_status) { case FIFO_STOP: hwwrite(vortex->mmio, VORTEX_ADBDMA_CTRL + (adbdma << 2), dma->dma_ctrl); vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; case FIFO_PAUSE: vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; } dma->fifo_status = FIFO_START; } static void vortex_adbdma_pausefifo(vortex_t * vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; int this_8 = 0, this_4 = 0; switch (dma->fifo_status) { case FIFO_START: vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, 0, 0); break; case FIFO_STOP: hwwrite(vortex->mmio, VORTEX_ADBDMA_CTRL + (adbdma << 2), dma->dma_ctrl); vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, 0, 0); break; } dma->fifo_status = FIFO_PAUSE; } #if 0 // Using pause instead static void vortex_adbdma_stopfifo(vortex_t * vortex, int adbdma) { stream_t *dma = &vortex->dma_adb[adbdma]; int this_4 = 0, this_8 = 0; if (dma->fifo_status == FIFO_START) vortex_fifo_setadbctrl(vortex, adbdma, dma->dma_unknown, this_4, this_8, 0, 0); else if (dma->fifo_status == FIFO_STOP) return; dma->fifo_status = FIFO_STOP; dma->fifo_enabled = 0; } #endif /* WTDMA */ #ifndef CHIP_AU8810 static void vortex_wtdma_setfirstbuffer(vortex_t * vortex, int wtdma) { //int this_7c=dma_ctrl; stream_t *dma = &vortex->dma_wt[wtdma]; hwwrite(vortex->mmio, VORTEX_WTDMA_CTRL + (wtdma << 2), dma->dma_ctrl); } static void vortex_wtdma_setstartbuffer(vortex_t * vortex, int wtdma, int sb) { stream_t *dma = &vortex->dma_wt[wtdma]; //hwwrite(vortex->mmio, VORTEX_WTDMA_START + (wtdma << 2), sb << ((0x1f-(wtdma&0xf)*2))); hwwrite(vortex->mmio, VORTEX_WTDMA_START + (wtdma << 2), sb << ((0xf - (wtdma & 0xf)) * 2)); dma->period_real = dma->period_virt = sb; } static void vortex_wtdma_setbuffers(vortex_t * vortex, int wtdma, int psize, int count) { stream_t *dma = &vortex->dma_wt[wtdma]; dma->period_bytes = psize; dma->nr_periods = count; dma->cfg0 = 0; dma->cfg1 = 0; switch (count) { /* Four or more pages */ default: case 4: dma->cfg1 |= 0x88000000 | 0x44000000 | 0x30000000 | (psize-1); hwwrite(vortex->mmio, VORTEX_WTDMA_BUFBASE + (wtdma << 4) + 0xc, snd_pcm_sgbuf_get_addr(dma->substream, psize * 3)); /* 3 pages */ case 3: dma->cfg0 |= 0x12000000; dma->cfg1 |= 0x80000000 | 0x40000000 | ((psize-1) << 0xc); hwwrite(vortex->mmio, VORTEX_WTDMA_BUFBASE + (wtdma << 4) + 0x8, snd_pcm_sgbuf_get_addr(dma->substream, psize * 2)); /* 2 pages */ case 2: dma->cfg0 |= 0x88000000 | 0x44000000 | 0x10000000 | (psize-1); hwwrite(vortex->mmio, VORTEX_WTDMA_BUFBASE + (wtdma << 4) + 0x4, snd_pcm_sgbuf_get_addr(dma->substream, psize)); /* 1 page */ case 1: dma->cfg0 |= 0x80000000 | 0x40000000 | ((psize-1) << 0xc); hwwrite(vortex->mmio, VORTEX_WTDMA_BUFBASE + (wtdma << 4), snd_pcm_sgbuf_get_addr(dma->substream, 0)); break; } hwwrite(vortex->mmio, VORTEX_WTDMA_BUFCFG0 + (wtdma << 3), dma->cfg0); hwwrite(vortex->mmio, VORTEX_WTDMA_BUFCFG1 + (wtdma << 3), dma->cfg1); vortex_wtdma_setfirstbuffer(vortex, wtdma); vortex_wtdma_setstartbuffer(vortex, wtdma, 0); } static void vortex_wtdma_setmode(vortex_t * vortex, int wtdma, int ie, int fmt, int d, /*int e, */ u32 offset) { stream_t *dma = &vortex->dma_wt[wtdma]; //dma->this_08 = e; dma->dma_unknown = d; dma->dma_ctrl = 0; dma->dma_ctrl = ((offset & OFFSET_MASK) | (dma->dma_ctrl & ~OFFSET_MASK)); /* PCMOUT interrupt */ dma->dma_ctrl = (dma->dma_ctrl & ~IE_MASK) | ((ie << IE_SHIFT) & IE_MASK); /* Always playback. */ dma->dma_ctrl |= (1 << DIR_SHIFT); /* Audio Format */ dma->dma_ctrl = (dma->dma_ctrl & FMT_MASK) | ((fmt << FMT_SHIFT) & FMT_MASK); /* Write into hardware */ hwwrite(vortex->mmio, VORTEX_WTDMA_CTRL + (wtdma << 2), dma->dma_ctrl); } static int vortex_wtdma_bufshift(vortex_t * vortex, int wtdma) { stream_t *dma = &vortex->dma_wt[wtdma]; int page, p, pp, delta, i; page = (hwread(vortex->mmio, VORTEX_WTDMA_STAT + (wtdma << 2)) & WT_SUBBUF_MASK) >> WT_SUBBUF_SHIFT; if (dma->nr_periods >= 4) delta = (page - dma->period_real) & 3; else { delta = (page - dma->period_real); if (delta < 0) delta += dma->nr_periods; } if (delta == 0) return 0; /* refresh hw page table */ if (dma->nr_periods > 4) { for (i = 0; i < delta; i++) { /* p: audio buffer page index */ p = dma->period_virt + i + 4; if (p >= dma->nr_periods) p -= dma->nr_periods; /* pp: hardware DMA page index. */ pp = dma->period_real + i; if (pp >= 4) pp -= 4; hwwrite(vortex->mmio, VORTEX_WTDMA_BUFBASE + (((wtdma << 2) + pp) << 2), snd_pcm_sgbuf_get_addr(dma->substream, dma->period_bytes * p)); /* Force write thru cache. */ hwread(vortex->mmio, VORTEX_WTDMA_BUFBASE + (((wtdma << 2) + pp) << 2)); } } dma->period_virt += delta; if (dma->period_virt >= dma->nr_periods) dma->period_virt -= dma->nr_periods; dma->period_real = page; if (delta != 1) printk(KERN_WARNING "vortex: wt virt = %d, delta = %d\n", dma->period_virt, delta); return delta; } #if 0 static void vortex_wtdma_getposition(vortex_t * vortex, int wtdma, int *subbuf, int *pos) { int temp; temp = hwread(vortex->mmio, VORTEX_WTDMA_STAT + (wtdma << 2)); *subbuf = (temp >> WT_SUBBUF_SHIFT) & WT_SUBBUF_MASK; *pos = temp & POS_MASK; } static int vortex_wtdma_getcursubuffer(vortex_t * vortex, int wtdma) { return ((hwread(vortex->mmio, VORTEX_WTDMA_STAT + (wtdma << 2)) >> POS_SHIFT) & POS_MASK); } #endif static inline int vortex_wtdma_getlinearpos(vortex_t * vortex, int wtdma) { stream_t *dma = &vortex->dma_wt[wtdma]; int temp; temp = hwread(vortex->mmio, VORTEX_WTDMA_STAT + (wtdma << 2)); temp = (dma->period_virt * dma->period_bytes) + (temp & (dma->period_bytes - 1)); return temp; } static void vortex_wtdma_startfifo(vortex_t * vortex, int wtdma) { stream_t *dma = &vortex->dma_wt[wtdma]; int this_8 = 0, this_4 = 0; switch (dma->fifo_status) { case FIFO_START: vortex_fifo_setwtvalid(vortex, wtdma, dma->fifo_enabled ? 1 : 0); break; case FIFO_STOP: this_8 = 1; hwwrite(vortex->mmio, VORTEX_WTDMA_CTRL + (wtdma << 2), dma->dma_ctrl); vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; case FIFO_PAUSE: vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; } dma->fifo_status = FIFO_START; } static void vortex_wtdma_resumefifo(vortex_t * vortex, int wtdma) { stream_t *dma = &vortex->dma_wt[wtdma]; int this_8 = 0, this_4 = 0; switch (dma->fifo_status) { case FIFO_STOP: hwwrite(vortex->mmio, VORTEX_WTDMA_CTRL + (wtdma << 2), dma->dma_ctrl); vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; case FIFO_PAUSE: vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, dma->fifo_enabled ? 1 : 0, 0); break; } dma->fifo_status = FIFO_START; } static void vortex_wtdma_pausefifo(vortex_t * vortex, int wtdma) { stream_t *dma = &vortex->dma_wt[wtdma]; int this_8 = 0, this_4 = 0; switch (dma->fifo_status) { case FIFO_START: vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, 0, 0); break; case FIFO_STOP: hwwrite(vortex->mmio, VORTEX_WTDMA_CTRL + (wtdma << 2), dma->dma_ctrl); vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, 0, 0); break; } dma->fifo_status = FIFO_PAUSE; } static void vortex_wtdma_stopfifo(vortex_t * vortex, int wtdma) { stream_t *dma = &vortex->dma_wt[wtdma]; int this_4 = 0, this_8 = 0; if (dma->fifo_status == FIFO_START) vortex_fifo_setwtctrl(vortex, wtdma, dma->dma_unknown, this_4, this_8, 0, 0); else if (dma->fifo_status == FIFO_STOP) return; dma->fifo_status = FIFO_STOP; dma->fifo_enabled = 0; } #endif /* ADB Routes */ typedef int ADBRamLink; static void vortex_adb_init(vortex_t * vortex) { int i; /* it looks like we are writing more than we need to... * if we write what we are supposed to it breaks things... */ hwwrite(vortex->mmio, VORTEX_ADB_SR, 0); for (i = 0; i < VORTEX_ADB_RTBASE_COUNT; i++) hwwrite(vortex->mmio, VORTEX_ADB_RTBASE + (i << 2), hwread(vortex->mmio, VORTEX_ADB_RTBASE + (i << 2)) | ROUTE_MASK); for (i = 0; i < VORTEX_ADB_CHNBASE_COUNT; i++) { hwwrite(vortex->mmio, VORTEX_ADB_CHNBASE + (i << 2), hwread(vortex->mmio, VORTEX_ADB_CHNBASE + (i << 2)) | ROUTE_MASK); } } static void vortex_adb_en_sr(vortex_t * vortex, int channel) { hwwrite(vortex->mmio, VORTEX_ADB_SR, hwread(vortex->mmio, VORTEX_ADB_SR) | (0x1 << channel)); } static void vortex_adb_dis_sr(vortex_t * vortex, int channel) { hwwrite(vortex->mmio, VORTEX_ADB_SR, hwread(vortex->mmio, VORTEX_ADB_SR) & ~(0x1 << channel)); } static void vortex_adb_addroutes(vortex_t * vortex, unsigned char channel, ADBRamLink * route, int rnum) { int temp, prev, lifeboat = 0; if ((rnum <= 0) || (route == NULL)) return; /* Write last routes. */ rnum--; hwwrite(vortex->mmio, VORTEX_ADB_RTBASE + ((route[rnum] & ADB_MASK) << 2), ROUTE_MASK); while (rnum > 0) { hwwrite(vortex->mmio, VORTEX_ADB_RTBASE + ((route[rnum - 1] & ADB_MASK) << 2), route[rnum]); rnum--; } /* Write first route. */ temp = hwread(vortex->mmio, VORTEX_ADB_CHNBASE + (channel << 2)) & ADB_MASK; if (temp == ADB_MASK) { /* First entry on this channel. */ hwwrite(vortex->mmio, VORTEX_ADB_CHNBASE + (channel << 2), route[0]); vortex_adb_en_sr(vortex, channel); return; } /* Not first entry on this channel. Need to link. */ do { prev = temp; temp = hwread(vortex->mmio, VORTEX_ADB_RTBASE + (temp << 2)) & ADB_MASK; if ((lifeboat++) > ADB_MASK) { printk(KERN_ERR "vortex_adb_addroutes: unending route! 0x%x\n", *route); return; } } while (temp != ADB_MASK); hwwrite(vortex->mmio, VORTEX_ADB_RTBASE + (prev << 2), route[0]); } static void vortex_adb_delroutes(vortex_t * vortex, unsigned char channel, ADBRamLink route0, ADBRamLink route1) { int temp, lifeboat = 0, prev; /* Find route. */ temp = hwread(vortex->mmio, VORTEX_ADB_CHNBASE + (channel << 2)) & ADB_MASK; if (temp == (route0 & ADB_MASK)) { temp = hwread(vortex->mmio, VORTEX_ADB_RTBASE + ((route1 & ADB_MASK) << 2)); if ((temp & ADB_MASK) == ADB_MASK) vortex_adb_dis_sr(vortex, channel); hwwrite(vortex->mmio, VORTEX_ADB_CHNBASE + (channel << 2), temp); return; } do { prev = temp; temp = hwread(vortex->mmio, VORTEX_ADB_RTBASE + (prev << 2)) & ADB_MASK; if (((lifeboat++) > ADB_MASK) || (temp == ADB_MASK)) { printk(KERN_ERR "vortex_adb_delroutes: route not found! 0x%x\n", route0); return; } } while (temp != (route0 & ADB_MASK)); temp = hwread(vortex->mmio, VORTEX_ADB_RTBASE + (temp << 2)); if ((temp & ADB_MASK) == route1) temp = hwread(vortex->mmio, VORTEX_ADB_RTBASE + (temp << 2)); /* Make bridge over deleted route. */ hwwrite(vortex->mmio, VORTEX_ADB_RTBASE + (prev << 2), temp); } static void vortex_route(vortex_t * vortex, int en, unsigned char channel, unsigned char source, unsigned char dest) { ADBRamLink route; route = ((source & ADB_MASK) << ADB_SHIFT) | (dest & ADB_MASK); if (en) { vortex_adb_addroutes(vortex, channel, &route, 1); if ((source < (OFFSET_SRCOUT + NR_SRC)) && (source >= OFFSET_SRCOUT)) vortex_src_addWTD(vortex, (source - OFFSET_SRCOUT), channel); else if ((source < (OFFSET_MIXOUT + NR_MIXOUT)) && (source >= OFFSET_MIXOUT)) vortex_mixer_addWTD(vortex, (source - OFFSET_MIXOUT), channel); } else { vortex_adb_delroutes(vortex, channel, route, route); if ((source < (OFFSET_SRCOUT + NR_SRC)) && (source >= OFFSET_SRCOUT)) vortex_src_delWTD(vortex, (source - OFFSET_SRCOUT), channel); else if ((source < (OFFSET_MIXOUT + NR_MIXOUT)) && (source >= OFFSET_MIXOUT)) vortex_mixer_delWTD(vortex, (source - OFFSET_MIXOUT), channel); } } #if 0 static void vortex_routes(vortex_t * vortex, int en, unsigned char channel, unsigned char source, unsigned char dest0, unsigned char dest1) { ADBRamLink route[2]; route[0] = ((source & ADB_MASK) << ADB_SHIFT) | (dest0 & ADB_MASK); route[1] = ((source & ADB_MASK) << ADB_SHIFT) | (dest1 & ADB_MASK); if (en) { vortex_adb_addroutes(vortex, channel, route, 2); if ((source < (OFFSET_SRCOUT + NR_SRC)) && (source >= (OFFSET_SRCOUT))) vortex_src_addWTD(vortex, (source - OFFSET_SRCOUT), channel); else if ((source < (OFFSET_MIXOUT + NR_MIXOUT)) && (source >= (OFFSET_MIXOUT))) vortex_mixer_addWTD(vortex, (source - OFFSET_MIXOUT), channel); } else { vortex_adb_delroutes(vortex, channel, route[0], route[1]); if ((source < (OFFSET_SRCOUT + NR_SRC)) && (source >= (OFFSET_SRCOUT))) vortex_src_delWTD(vortex, (source - OFFSET_SRCOUT), channel); else if ((source < (OFFSET_MIXOUT + NR_MIXOUT)) && (source >= (OFFSET_MIXOUT))) vortex_mixer_delWTD(vortex, (source - OFFSET_MIXOUT), channel); } } #endif /* Route two sources to same target. Sources must be of same class !!! */ static void vortex_routeLRT(vortex_t * vortex, int en, unsigned char ch, unsigned char source0, unsigned char source1, unsigned char dest) { ADBRamLink route[2]; route[0] = ((source0 & ADB_MASK) << ADB_SHIFT) | (dest & ADB_MASK); route[1] = ((source1 & ADB_MASK) << ADB_SHIFT) | (dest & ADB_MASK); if (dest < 0x10) route[1] = (route[1] & ~ADB_MASK) | (dest + 0x20); /* fifo A */ if (en) { vortex_adb_addroutes(vortex, ch, route, 2); if ((source0 < (OFFSET_SRCOUT + NR_SRC)) && (source0 >= OFFSET_SRCOUT)) { vortex_src_addWTD(vortex, (source0 - OFFSET_SRCOUT), ch); vortex_src_addWTD(vortex, (source1 - OFFSET_SRCOUT), ch); } else if ((source0 < (OFFSET_MIXOUT + NR_MIXOUT)) && (source0 >= OFFSET_MIXOUT)) { vortex_mixer_addWTD(vortex, (source0 - OFFSET_MIXOUT), ch); vortex_mixer_addWTD(vortex, (source1 - OFFSET_MIXOUT), ch); } } else { vortex_adb_delroutes(vortex, ch, route[0], route[1]); if ((source0 < (OFFSET_SRCOUT + NR_SRC)) && (source0 >= OFFSET_SRCOUT)) { vortex_src_delWTD(vortex, (source0 - OFFSET_SRCOUT), ch); vortex_src_delWTD(vortex, (source1 - OFFSET_SRCOUT), ch); } else if ((source0 < (OFFSET_MIXOUT + NR_MIXOUT)) && (source0 >= OFFSET_MIXOUT)) { vortex_mixer_delWTD(vortex, (source0 - OFFSET_MIXOUT), ch); vortex_mixer_delWTD(vortex, (source1 - OFFSET_MIXOUT), ch); } } } /* Connection stuff */ // Connect adbdma to src('s). static void vortex_connection_adbdma_src(vortex_t * vortex, int en, unsigned char ch, unsigned char adbdma, unsigned char src) { vortex_route(vortex, en, ch, ADB_DMA(adbdma), ADB_SRCIN(src)); } // Connect SRC to mixin. static void vortex_connection_src_mixin(vortex_t * vortex, int en, unsigned char channel, unsigned char src, unsigned char mixin) { vortex_route(vortex, en, channel, ADB_SRCOUT(src), ADB_MIXIN(mixin)); } // Connect mixin with mix output. static void vortex_connection_mixin_mix(vortex_t * vortex, int en, unsigned char mixin, unsigned char mix, int a) { if (en) { vortex_mix_enableinput(vortex, mix, mixin); vortex_mix_setinputvolumebyte(vortex, mix, mixin, MIX_DEFIGAIN); // added to original code. } else vortex_mix_disableinput(vortex, mix, mixin, a); } // Connect absolut address to mixin. static void vortex_connection_adb_mixin(vortex_t * vortex, int en, unsigned char channel, unsigned char source, unsigned char mixin) { vortex_route(vortex, en, channel, source, ADB_MIXIN(mixin)); } static void vortex_connection_src_adbdma(vortex_t * vortex, int en, unsigned char ch, unsigned char src, unsigned char adbdma) { vortex_route(vortex, en, ch, ADB_SRCOUT(src), ADB_DMA(adbdma)); } static void vortex_connection_src_src_adbdma(vortex_t * vortex, int en, unsigned char ch, unsigned char src0, unsigned char src1, unsigned char adbdma) { vortex_routeLRT(vortex, en, ch, ADB_SRCOUT(src0), ADB_SRCOUT(src1), ADB_DMA(adbdma)); } // mix to absolut address. static void vortex_connection_mix_adb(vortex_t * vortex, int en, unsigned char ch, unsigned char mix, unsigned char dest) { vortex_route(vortex, en, ch, ADB_MIXOUT(mix), dest); vortex_mix_setvolumebyte(vortex, mix, MIX_DEFOGAIN); // added to original code. } // mixer to src. static void vortex_connection_mix_src(vortex_t * vortex, int en, unsigned char ch, unsigned char mix, unsigned char src) { vortex_route(vortex, en, ch, ADB_MIXOUT(mix), ADB_SRCIN(src)); vortex_mix_setvolumebyte(vortex, mix, MIX_DEFOGAIN); // added to original code. } #if 0 static void vortex_connection_adbdma_src_src(vortex_t * vortex, int en, unsigned char channel, unsigned char adbdma, unsigned char src0, unsigned char src1) { vortex_routes(vortex, en, channel, ADB_DMA(adbdma), ADB_SRCIN(src0), ADB_SRCIN(src1)); } // Connect two mix to AdbDma. static void vortex_connection_mix_mix_adbdma(vortex_t * vortex, int en, unsigned char ch, unsigned char mix0, unsigned char mix1, unsigned char adbdma) { ADBRamLink routes[2]; routes[0] = (((mix0 + OFFSET_MIXOUT) & ADB_MASK) << ADB_SHIFT) | (adbdma & ADB_MASK); routes[1] = (((mix1 + OFFSET_MIXOUT) & ADB_MASK) << ADB_SHIFT) | ((adbdma + 0x20) & ADB_MASK); if (en) { vortex_adb_addroutes(vortex, ch, routes, 0x2); vortex_mixer_addWTD(vortex, mix0, ch); vortex_mixer_addWTD(vortex, mix1, ch); } else { vortex_adb_delroutes(vortex, ch, routes[0], routes[1]); vortex_mixer_delWTD(vortex, mix0, ch); vortex_mixer_delWTD(vortex, mix1, ch); } } #endif /* CODEC connect. */ static void vortex_connect_codecplay(vortex_t * vortex, int en, unsigned char mixers[]) { #ifdef CHIP_AU8820 vortex_connection_mix_adb(vortex, en, 0x11, mixers[0], ADB_CODECOUT(0)); vortex_connection_mix_adb(vortex, en, 0x11, mixers[1], ADB_CODECOUT(1)); #else #if 1 // Connect front channels through EQ. vortex_connection_mix_adb(vortex, en, 0x11, mixers[0], ADB_EQIN(0)); vortex_connection_mix_adb(vortex, en, 0x11, mixers[1], ADB_EQIN(1)); /* Lower volume, since EQ has some gain. */ vortex_mix_setvolumebyte(vortex, mixers[0], 0); vortex_mix_setvolumebyte(vortex, mixers[1], 0); vortex_route(vortex, en, 0x11, ADB_EQOUT(0), ADB_CODECOUT(0)); vortex_route(vortex, en, 0x11, ADB_EQOUT(1), ADB_CODECOUT(1)); /* Check if reg 0x28 has SDAC bit set. */ if (VORTEX_IS_QUAD(vortex)) { /* Rear channel. Note: ADB_CODECOUT(0+2) and (1+2) is for AC97 modem */ vortex_connection_mix_adb(vortex, en, 0x11, mixers[2], ADB_CODECOUT(0 + 4)); vortex_connection_mix_adb(vortex, en, 0x11, mixers[3], ADB_CODECOUT(1 + 4)); /* printk(KERN_DEBUG "SDAC detected "); */ } #else // Use plain direct output to codec. vortex_connection_mix_adb(vortex, en, 0x11, mixers[0], ADB_CODECOUT(0)); vortex_connection_mix_adb(vortex, en, 0x11, mixers[1], ADB_CODECOUT(1)); #endif #endif } static void vortex_connect_codecrec(vortex_t * vortex, int en, unsigned char mixin0, unsigned char mixin1) { /* Enable: 0x1, 0x1 Channel: 0x11, 0x11 ADB Source address: 0x48, 0x49 Destination Asp4Topology_0x9c,0x98 */ vortex_connection_adb_mixin(vortex, en, 0x11, ADB_CODECIN(0), mixin0); vortex_connection_adb_mixin(vortex, en, 0x11, ADB_CODECIN(1), mixin1); } // Higher level ADB audio path (de)allocator. /* Resource manager */ static int resnum[VORTEX_RESOURCE_LAST] = { NR_ADB, NR_SRC, NR_MIXIN, NR_MIXOUT, NR_A3D }; /* Checkout/Checkin resource of given type. resmap: resource map to be used. If NULL means that we want to allocate a DMA resource (root of all other resources of a dma channel). out: Mean checkout if != 0. Else mean Checkin resource. restype: Indicates type of resource to be checked in or out. */ static char vortex_adb_checkinout(vortex_t * vortex, int resmap[], int out, int restype) { int i, qty = resnum[restype], resinuse = 0; if (out) { /* Gather used resources by all streams. */ for (i = 0; i < NR_ADB; i++) { resinuse |= vortex->dma_adb[i].resources[restype]; } resinuse |= vortex->fixed_res[restype]; /* Find and take free resource. */ for (i = 0; i < qty; i++) { if ((resinuse & (1 << i)) == 0) { if (resmap != NULL) resmap[restype] |= (1 << i); else vortex->dma_adb[i].resources[restype] |= (1 << i); /* printk(KERN_DEBUG "vortex: ResManager: type %d out %d\n", restype, i); */ return i; } } } else { if (resmap == NULL) return -EINVAL; /* Checkin first resource of type restype. */ for (i = 0; i < qty; i++) { if (resmap[restype] & (1 << i)) { resmap[restype] &= ~(1 << i); /* printk(KERN_DEBUG "vortex: ResManager: type %d in %d\n", restype, i); */ return i; } } } printk(KERN_ERR "vortex: FATAL: ResManager: resource type %d exhausted.\n", restype); return -ENOMEM; } /* Default Connections */ static int vortex_adb_allocroute(vortex_t * vortex, int dma, int nr_ch, int dir, int type); static void vortex_connect_default(vortex_t * vortex, int en) { // Connect AC97 codec. vortex->mixplayb[0] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXOUT); vortex->mixplayb[1] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXOUT); if (VORTEX_IS_QUAD(vortex)) { vortex->mixplayb[2] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXOUT); vortex->mixplayb[3] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXOUT); } vortex_connect_codecplay(vortex, en, vortex->mixplayb); vortex->mixcapt[0] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXIN); vortex->mixcapt[1] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXIN); vortex_connect_codecrec(vortex, en, MIX_CAPT(0), MIX_CAPT(1)); // Connect SPDIF #ifndef CHIP_AU8820 vortex->mixspdif[0] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXOUT); vortex->mixspdif[1] = vortex_adb_checkinout(vortex, vortex->fixed_res, en, VORTEX_RESOURCE_MIXOUT); vortex_connection_mix_adb(vortex, en, 0x14, vortex->mixspdif[0], ADB_SPDIFOUT(0)); vortex_connection_mix_adb(vortex, en, 0x14, vortex->mixspdif[1], ADB_SPDIFOUT(1)); #endif // Connect WT #ifndef CHIP_AU8810 vortex_wt_connect(vortex, en); #endif // A3D (crosstalk canceler and A3D slices). AU8810 disabled for now. #ifndef CHIP_AU8820 vortex_Vort3D_connect(vortex, en); #endif // Connect I2S // Connect DSP interface for SQ3500 turbo (not here i think...) // Connect AC98 modem codec } /* Allocate nr_ch pcm audio routes if dma < 0. If dma >= 0, existing routes are deallocated. dma: DMA engine routes to be deallocated when dma >= 0. nr_ch: Number of channels to be de/allocated. dir: direction of stream. Uses same values as substream->stream. type: Type of audio output/source (codec, spdif, i2s, dsp, etc) Return: Return allocated DMA or same DMA passed as "dma" when dma >= 0. */ static int vortex_adb_allocroute(vortex_t * vortex, int dma, int nr_ch, int dir, int type) { stream_t *stream; int i, en; if ((nr_ch == 3) || ((dir == SNDRV_PCM_STREAM_CAPTURE) && (nr_ch > 2))) return -EBUSY; if (dma >= 0) { en = 0; vortex_adb_checkinout(vortex, vortex->dma_adb[dma].resources, en, VORTEX_RESOURCE_DMA); } else { en = 1; if ((dma = vortex_adb_checkinout(vortex, NULL, en, VORTEX_RESOURCE_DMA)) < 0) return -EBUSY; } stream = &vortex->dma_adb[dma]; stream->dma = dma; stream->dir = dir; stream->type = type; /* PLAYBACK ROUTES. */ if (dir == SNDRV_PCM_STREAM_PLAYBACK) { int src[4], mix[4], ch_top; #ifndef CHIP_AU8820 int a3d = 0; #endif /* Get SRC and MIXER hardware resources. */ if (stream->type != VORTEX_PCM_SPDIF) { for (i = 0; i < nr_ch; i++) { if ((src[i] = vortex_adb_checkinout(vortex, stream->resources, en, VORTEX_RESOURCE_SRC)) < 0) { memset(stream->resources, 0, sizeof(unsigned char) * VORTEX_RESOURCE_LAST); return -EBUSY; } if (stream->type != VORTEX_PCM_A3D) { if ((mix[i] = vortex_adb_checkinout(vortex, stream->resources, en, VORTEX_RESOURCE_MIXIN)) < 0) { memset(stream->resources, 0, sizeof(unsigned char) * VORTEX_RESOURCE_LAST); return -EBUSY; } } } } #ifndef CHIP_AU8820 if (stream->type == VORTEX_PCM_A3D) { if ((a3d = vortex_adb_checkinout(vortex, stream->resources, en, VORTEX_RESOURCE_A3D)) < 0) { memset(stream->resources, 0, sizeof(unsigned char) * VORTEX_RESOURCE_LAST); printk(KERN_ERR "vortex: out of A3D sources. Sorry\n"); return -EBUSY; } /* (De)Initialize A3D hardware source. */ vortex_Vort3D_InitializeSource(&(vortex->a3d[a3d]), en); } /* Make SPDIF out exclusive to "spdif" device when in use. */ if ((stream->type == VORTEX_PCM_SPDIF) && (en)) { vortex_route(vortex, 0, 0x14, ADB_MIXOUT(vortex->mixspdif[0]), ADB_SPDIFOUT(0)); vortex_route(vortex, 0, 0x14, ADB_MIXOUT(vortex->mixspdif[1]), ADB_SPDIFOUT(1)); } #endif /* Make playback routes. */ for (i = 0; i < nr_ch; i++) { if (stream->type == VORTEX_PCM_ADB) { vortex_connection_adbdma_src(vortex, en, src[nr_ch - 1], dma, src[i]); vortex_connection_src_mixin(vortex, en, 0x11, src[i], mix[i]); vortex_connection_mixin_mix(vortex, en, mix[i], MIX_PLAYB(i), 0); #ifndef CHIP_AU8820 vortex_connection_mixin_mix(vortex, en, mix[i], MIX_SPDIF(i % 2), 0); vortex_mix_setinputvolumebyte(vortex, MIX_SPDIF(i % 2), mix[i], MIX_DEFIGAIN); #endif } #ifndef CHIP_AU8820 if (stream->type == VORTEX_PCM_A3D) { vortex_connection_adbdma_src(vortex, en, src[nr_ch - 1], dma, src[i]); vortex_route(vortex, en, 0x11, ADB_SRCOUT(src[i]), ADB_A3DIN(a3d)); /* XTalk test. */ //vortex_route(vortex, en, 0x11, dma, ADB_XTALKIN(i?9:4)); //vortex_route(vortex, en, 0x11, ADB_SRCOUT(src[i]), ADB_XTALKIN(i?4:9)); } if (stream->type == VORTEX_PCM_SPDIF) vortex_route(vortex, en, 0x14, ADB_DMA(stream->dma), ADB_SPDIFOUT(i)); #endif } if (stream->type != VORTEX_PCM_SPDIF && stream->type != VORTEX_PCM_A3D) { ch_top = (VORTEX_IS_QUAD(vortex) ? 4 : 2); for (i = nr_ch; i < ch_top; i++) { vortex_connection_mixin_mix(vortex, en, mix[i % nr_ch], MIX_PLAYB(i), 0); #ifndef CHIP_AU8820 vortex_connection_mixin_mix(vortex, en, mix[i % nr_ch], MIX_SPDIF(i % 2), 0); vortex_mix_setinputvolumebyte(vortex, MIX_SPDIF(i % 2), mix[i % nr_ch], MIX_DEFIGAIN); #endif } } #ifndef CHIP_AU8820 else { if (nr_ch == 1 && stream->type == VORTEX_PCM_SPDIF) vortex_route(vortex, en, 0x14, ADB_DMA(stream->dma), ADB_SPDIFOUT(1)); } /* Reconnect SPDIF out when "spdif" device is down. */ if ((stream->type == VORTEX_PCM_SPDIF) && (!en)) { vortex_route(vortex, 1, 0x14, ADB_MIXOUT(vortex->mixspdif[0]), ADB_SPDIFOUT(0)); vortex_route(vortex, 1, 0x14, ADB_MIXOUT(vortex->mixspdif[1]), ADB_SPDIFOUT(1)); } #endif /* CAPTURE ROUTES. */ } else { int src[2], mix[2]; /* Get SRC and MIXER hardware resources. */ for (i = 0; i < nr_ch; i++) { if ((mix[i] = vortex_adb_checkinout(vortex, stream->resources, en, VORTEX_RESOURCE_MIXOUT)) < 0) { memset(stream->resources, 0, sizeof(unsigned char) * VORTEX_RESOURCE_LAST); return -EBUSY; } if ((src[i] = vortex_adb_checkinout(vortex, stream->resources, en, VORTEX_RESOURCE_SRC)) < 0) { memset(stream->resources, 0, sizeof(unsigned char) * VORTEX_RESOURCE_LAST); return -EBUSY; } } /* Make capture routes. */ vortex_connection_mixin_mix(vortex, en, MIX_CAPT(0), mix[0], 0); vortex_connection_mix_src(vortex, en, 0x11, mix[0], src[0]); if (nr_ch == 1) { vortex_connection_mixin_mix(vortex, en, MIX_CAPT(1), mix[0], 0); vortex_connection_src_adbdma(vortex, en, src[0], src[0], dma); } else { vortex_connection_mixin_mix(vortex, en, MIX_CAPT(1), mix[1], 0); vortex_connection_mix_src(vortex, en, 0x11, mix[1], src[1]); vortex_connection_src_src_adbdma(vortex, en, src[1], src[0], src[1], dma); } } vortex->dma_adb[dma].nr_ch = nr_ch; #if 0 /* AC97 Codec channel setup. FIXME: this has no effect on some cards !! */ if (nr_ch < 4) { /* Copy stereo to rear channel (surround) */ snd_ac97_write_cache(vortex->codec, AC97_SIGMATEL_DAC2INVERT, snd_ac97_read(vortex->codec, AC97_SIGMATEL_DAC2INVERT) | 4); } else { /* Allow separate front and rear channels. */ snd_ac97_write_cache(vortex->codec, AC97_SIGMATEL_DAC2INVERT, snd_ac97_read(vortex->codec, AC97_SIGMATEL_DAC2INVERT) & ~((u32) 4)); } #endif return dma; } /* Set the SampleRate of the SRC's attached to the given DMA engine. */ static void vortex_adb_setsrc(vortex_t * vortex, int adbdma, unsigned int rate, int dir) { stream_t *stream = &(vortex->dma_adb[adbdma]); int i, cvrt; /* dir=1:play ; dir=0:rec */ if (dir) cvrt = SRC_RATIO(rate, 48000); else cvrt = SRC_RATIO(48000, rate); /* Setup SRC's */ for (i = 0; i < NR_SRC; i++) { if (stream->resources[VORTEX_RESOURCE_SRC] & (1 << i)) vortex_src_setupchannel(vortex, i, cvrt, 0, 0, i, dir, 1, cvrt, dir); } } // Timer and ISR functions. static void vortex_settimer(vortex_t * vortex, int period) { //set the timer period to <period> 48000ths of a second. hwwrite(vortex->mmio, VORTEX_IRQ_STAT, period); } #if 0 static void vortex_enable_timer_int(vortex_t * card) { hwwrite(card->mmio, VORTEX_IRQ_CTRL, hwread(card->mmio, VORTEX_IRQ_CTRL) | IRQ_TIMER | 0x60); } static void vortex_disable_timer_int(vortex_t * card) { hwwrite(card->mmio, VORTEX_IRQ_CTRL, hwread(card->mmio, VORTEX_IRQ_CTRL) & ~IRQ_TIMER); } #endif static void vortex_enable_int(vortex_t * card) { // CAsp4ISR__EnableVortexInt_void_ hwwrite(card->mmio, VORTEX_CTRL, hwread(card->mmio, VORTEX_CTRL) | CTRL_IRQ_ENABLE); hwwrite(card->mmio, VORTEX_IRQ_CTRL, (hwread(card->mmio, VORTEX_IRQ_CTRL) & 0xffffefc0) | 0x24); } static void vortex_disable_int(vortex_t * card) { hwwrite(card->mmio, VORTEX_CTRL, hwread(card->mmio, VORTEX_CTRL) & ~CTRL_IRQ_ENABLE); } static irqreturn_t vortex_interrupt(int irq, void *dev_id) { vortex_t *vortex = dev_id; int i, handled; u32 source; //check if the interrupt is ours. if (!(hwread(vortex->mmio, VORTEX_STAT) & 0x1)) return IRQ_NONE; // This is the Interrupt Enable flag we set before (consistency check). if (!(hwread(vortex->mmio, VORTEX_CTRL) & CTRL_IRQ_ENABLE)) return IRQ_NONE; source = hwread(vortex->mmio, VORTEX_IRQ_SOURCE); // Reset IRQ flags. hwwrite(vortex->mmio, VORTEX_IRQ_SOURCE, source); hwread(vortex->mmio, VORTEX_IRQ_SOURCE); // Is at least one IRQ flag set? if (source == 0) { printk(KERN_ERR "vortex: missing irq source\n"); return IRQ_NONE; } handled = 0; // Attend every interrupt source. if (unlikely(source & IRQ_ERR_MASK)) { if (source & IRQ_FATAL) { printk(KERN_ERR "vortex: IRQ fatal error\n"); } if (source & IRQ_PARITY) { printk(KERN_ERR "vortex: IRQ parity error\n"); } if (source & IRQ_REG) { printk(KERN_ERR "vortex: IRQ reg error\n"); } if (source & IRQ_FIFO) { printk(KERN_ERR "vortex: IRQ fifo error\n"); } if (source & IRQ_DMA) { printk(KERN_ERR "vortex: IRQ dma error\n"); } handled = 1; } if (source & IRQ_PCMOUT) { /* ALSA period acknowledge. */ spin_lock(&vortex->lock); for (i = 0; i < NR_ADB; i++) { if (vortex->dma_adb[i].fifo_status == FIFO_START) { if (!vortex_adbdma_bufshift(vortex, i)) continue; spin_unlock(&vortex->lock); snd_pcm_period_elapsed(vortex->dma_adb[i]. substream); spin_lock(&vortex->lock); } } #ifndef CHIP_AU8810 for (i = 0; i < NR_WT; i++) { if (vortex->dma_wt[i].fifo_status == FIFO_START) { if (vortex_wtdma_bufshift(vortex, i)) ; spin_unlock(&vortex->lock); snd_pcm_period_elapsed(vortex->dma_wt[i]. substream); spin_lock(&vortex->lock); } } #endif spin_unlock(&vortex->lock); handled = 1; } //Acknowledge the Timer interrupt if (source & IRQ_TIMER) { hwread(vortex->mmio, VORTEX_IRQ_STAT); handled = 1; } if (source & IRQ_MIDI) { snd_mpu401_uart_interrupt(vortex->irq, vortex->rmidi->private_data); handled = 1; } if (!handled) { printk(KERN_ERR "vortex: unknown irq source %x\n", source); } return IRQ_RETVAL(handled); } /* Codec */ #define POLL_COUNT 1000 static void vortex_codec_init(vortex_t * vortex) { int i; for (i = 0; i < 32; i++) { /* the windows driver writes -i, so we write -i */ hwwrite(vortex->mmio, (VORTEX_CODEC_CHN + (i << 2)), -i); msleep(2); } if (0) { hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x8068); msleep(1); hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x00e8); msleep(1); } else { hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x00a8); msleep(2); hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x80a8); msleep(2); hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x80e8); msleep(2); hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x80a8); msleep(2); hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x00a8); msleep(2); hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0x00e8); } for (i = 0; i < 32; i++) { hwwrite(vortex->mmio, (VORTEX_CODEC_CHN + (i << 2)), -i); msleep(5); } hwwrite(vortex->mmio, VORTEX_CODEC_CTRL, 0xe8); msleep(1); /* Enable codec channels 0 and 1. */ hwwrite(vortex->mmio, VORTEX_CODEC_EN, hwread(vortex->mmio, VORTEX_CODEC_EN) | EN_CODEC); } static void vortex_codec_write(struct snd_ac97 * codec, unsigned short addr, unsigned short data) { vortex_t *card = (vortex_t *) codec->private_data; unsigned int lifeboat = 0; /* wait for transactions to clear */ while (!(hwread(card->mmio, VORTEX_CODEC_CTRL) & 0x100)) { udelay(100); if (lifeboat++ > POLL_COUNT) { printk(KERN_ERR "vortex: ac97 codec stuck busy\n"); return; } } /* write register */ hwwrite(card->mmio, VORTEX_CODEC_IO, ((addr << VORTEX_CODEC_ADDSHIFT) & VORTEX_CODEC_ADDMASK) | ((data << VORTEX_CODEC_DATSHIFT) & VORTEX_CODEC_DATMASK) | VORTEX_CODEC_WRITE | (codec->num << VORTEX_CODEC_ID_SHIFT) ); /* Flush Caches. */ hwread(card->mmio, VORTEX_CODEC_IO); } static unsigned short vortex_codec_read(struct snd_ac97 * codec, unsigned short addr) { vortex_t *card = (vortex_t *) codec->private_data; u32 read_addr, data; unsigned lifeboat = 0; /* wait for transactions to clear */ while (!(hwread(card->mmio, VORTEX_CODEC_CTRL) & 0x100)) { udelay(100); if (lifeboat++ > POLL_COUNT) { printk(KERN_ERR "vortex: ac97 codec stuck busy\n"); return 0xffff; } } /* set up read address */ read_addr = ((addr << VORTEX_CODEC_ADDSHIFT) & VORTEX_CODEC_ADDMASK) | (codec->num << VORTEX_CODEC_ID_SHIFT) ; hwwrite(card->mmio, VORTEX_CODEC_IO, read_addr); /* wait for address */ do { udelay(100); data = hwread(card->mmio, VORTEX_CODEC_IO); if (lifeboat++ > POLL_COUNT) { printk(KERN_ERR "vortex: ac97 address never arrived\n"); return 0xffff; } } while ((data & VORTEX_CODEC_ADDMASK) != (addr << VORTEX_CODEC_ADDSHIFT)); /* return data. */ return (u16) (data & VORTEX_CODEC_DATMASK); } /* SPDIF support */ static void vortex_spdif_init(vortex_t * vortex, int spdif_sr, int spdif_mode) { int i, this_38 = 0, this_04 = 0, this_08 = 0, this_0c = 0; /* CAsp4Spdif::InitializeSpdifHardware(void) */ hwwrite(vortex->mmio, VORTEX_SPDIF_FLAGS, hwread(vortex->mmio, VORTEX_SPDIF_FLAGS) & 0xfff3fffd); //for (i=0x291D4; i<0x29200; i+=4) for (i = 0; i < 11; i++) hwwrite(vortex->mmio, VORTEX_SPDIF_CFG1 + (i << 2), 0); //hwwrite(vortex->mmio, 0x29190, hwread(vortex->mmio, 0x29190) | 0xc0000); hwwrite(vortex->mmio, VORTEX_CODEC_EN, hwread(vortex->mmio, VORTEX_CODEC_EN) | EN_SPDIF); /* CAsp4Spdif::ProgramSRCInHardware(enum SPDIF_SR,enum SPDIFMODE) */ if (this_04 && this_08) { int edi; i = (((0x5DC00000 / spdif_sr) + 1) >> 1); if (i > 0x800) { if (i < 0x1ffff) edi = (i >> 1); else edi = 0x1ffff; } else { i = edi = 0x800; } /* this_04 and this_08 are the CASp4Src's (samplerate converters) */ vortex_src_setupchannel(vortex, this_04, edi, 0, 1, this_0c, 1, 0, edi, 1); vortex_src_setupchannel(vortex, this_08, edi, 0, 1, this_0c, 1, 0, edi, 1); } i = spdif_sr; spdif_sr |= 0x8c; switch (i) { case 32000: this_38 &= 0xFFFFFFFE; this_38 &= 0xFFFFFFFD; this_38 &= 0xF3FFFFFF; this_38 |= 0x03000000; /* set 32khz samplerate */ this_38 &= 0xFFFFFF3F; spdif_sr &= 0xFFFFFFFD; spdif_sr |= 1; break; case 44100: this_38 &= 0xFFFFFFFE; this_38 &= 0xFFFFFFFD; this_38 &= 0xF0FFFFFF; this_38 |= 0x03000000; this_38 &= 0xFFFFFF3F; spdif_sr &= 0xFFFFFFFC; break; case 48000: if (spdif_mode == 1) { this_38 &= 0xFFFFFFFE; this_38 &= 0xFFFFFFFD; this_38 &= 0xF2FFFFFF; this_38 |= 0x02000000; /* set 48khz samplerate */ this_38 &= 0xFFFFFF3F; } else { /* J. Gordon Wolfe: I think this stuff is for AC3 */ this_38 |= 0x00000003; this_38 &= 0xFFFFFFBF; this_38 |= 0x80; } spdif_sr |= 2; spdif_sr &= 0xFFFFFFFE; break; } /* looks like the next 2 lines transfer a 16-bit value into 2 8-bit registers. seems to be for the standard IEC/SPDIF initialization stuff */ hwwrite(vortex->mmio, VORTEX_SPDIF_CFG0, this_38 & 0xffff); hwwrite(vortex->mmio, VORTEX_SPDIF_CFG1, this_38 >> 0x10); hwwrite(vortex->mmio, VORTEX_SPDIF_SMPRATE, spdif_sr); } /* Initialization */ static int __devinit vortex_core_init(vortex_t * vortex) { printk(KERN_INFO "Vortex: init.... "); /* Hardware Init. */ hwwrite(vortex->mmio, VORTEX_CTRL, 0xffffffff); msleep(5); hwwrite(vortex->mmio, VORTEX_CTRL, hwread(vortex->mmio, VORTEX_CTRL) & 0xffdfffff); msleep(5); /* Reset IRQ flags */ hwwrite(vortex->mmio, VORTEX_IRQ_SOURCE, 0xffffffff); hwread(vortex->mmio, VORTEX_IRQ_STAT); vortex_codec_init(vortex); #ifdef CHIP_AU8830 hwwrite(vortex->mmio, VORTEX_CTRL, hwread(vortex->mmio, VORTEX_CTRL) | 0x1000000); #endif /* Init audio engine. */ vortex_adbdma_init(vortex); hwwrite(vortex->mmio, VORTEX_ENGINE_CTRL, 0x0); //, 0xc83c7e58, 0xc5f93e58 vortex_adb_init(vortex); /* Init processing blocks. */ vortex_fifo_init(vortex); vortex_mixer_init(vortex); vortex_srcblock_init(vortex); #ifndef CHIP_AU8820 vortex_eq_init(vortex); vortex_spdif_init(vortex, 48000, 1); vortex_Vort3D_enable(vortex); #endif #ifndef CHIP_AU8810 vortex_wt_init(vortex); #endif // Moved to au88x0.c //vortex_connect_default(vortex, 1); vortex_settimer(vortex, 0x90); // Enable Interrupts. // vortex_enable_int() must be first !! // hwwrite(vortex->mmio, VORTEX_IRQ_CTRL, 0); // vortex_enable_int(vortex); //vortex_enable_timer_int(vortex); //vortex_disable_timer_int(vortex); printk(KERN_INFO "done.\n"); spin_lock_init(&vortex->lock); return 0; } static int vortex_core_shutdown(vortex_t * vortex) { printk(KERN_INFO "Vortex: shutdown..."); #ifndef CHIP_AU8820 vortex_eq_free(vortex); vortex_Vort3D_disable(vortex); #endif //vortex_disable_timer_int(vortex); vortex_disable_int(vortex); vortex_connect_default(vortex, 0); /* Reset all DMA fifos. */ vortex_fifo_init(vortex); /* Erase all audio routes. */ vortex_adb_init(vortex); /* Disable MPU401 */ //hwwrite(vortex->mmio, VORTEX_IRQ_CTRL, hwread(vortex->mmio, VORTEX_IRQ_CTRL) & ~IRQ_MIDI); //hwwrite(vortex->mmio, VORTEX_CTRL, hwread(vortex->mmio, VORTEX_CTRL) & ~CTRL_MIDI_EN); hwwrite(vortex->mmio, VORTEX_IRQ_CTRL, 0); hwwrite(vortex->mmio, VORTEX_CTRL, 0); msleep(5); hwwrite(vortex->mmio, VORTEX_IRQ_SOURCE, 0xffff); printk(KERN_INFO "done.\n"); return 0; } /* Alsa support. */ static int vortex_alsafmt_aspfmt(int alsafmt) { int fmt; switch (alsafmt) { case SNDRV_PCM_FORMAT_U8: fmt = 0x1; break; case SNDRV_PCM_FORMAT_MU_LAW: fmt = 0x2; break; case SNDRV_PCM_FORMAT_A_LAW: fmt = 0x3; break; case SNDRV_PCM_FORMAT_SPECIAL: fmt = 0x4; /* guess. */ break; case SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE: fmt = 0x5; /* guess. */ break; case SNDRV_PCM_FORMAT_S16_LE: fmt = 0x8; break; case SNDRV_PCM_FORMAT_S16_BE: fmt = 0x9; /* check this... */ break; default: fmt = 0x8; printk(KERN_ERR "vortex: format unsupported %d\n", alsafmt); break; } return fmt; } /* Some not yet useful translations. */ #if 0 typedef enum { ASPFMTLINEAR16 = 0, /* 0x8 */ ASPFMTLINEAR8, /* 0x1 */ ASPFMTULAW, /* 0x2 */ ASPFMTALAW, /* 0x3 */ ASPFMTSPORT, /* ? */ ASPFMTSPDIF, /* ? */ } ASPENCODING; static int vortex_translateformat(vortex_t * vortex, char bits, char nch, int encod) { int a, this_194; if ((bits != 8) && (bits != 16)) return -1; switch (encod) { case 0: if (bits == 0x10) a = 8; // 16 bit break; case 1: if (bits == 8) a = 1; // 8 bit break; case 2: a = 2; // U_LAW break; case 3: a = 3; // A_LAW break; } switch (nch) { case 1: this_194 = 0; break; case 2: this_194 = 1; break; case 4: this_194 = 1; break; case 6: this_194 = 1; break; } return (a); } static void vortex_cdmacore_setformat(vortex_t * vortex, int bits, int nch) { short int d, this_148; d = ((bits >> 3) * nch); this_148 = 0xbb80 / d; } #endif
gpl-2.0
TeamJB/kernel_samsung_smdk4412
mm/bounce.c
3864
6639
/* bounce buffer handling for block devices * * - Split from highmem.c */ #include <linux/mm.h> #include <linux/module.h> #include <linux/swap.h> #include <linux/gfp.h> #include <linux/bio.h> #include <linux/pagemap.h> #include <linux/mempool.h> #include <linux/blkdev.h> #include <linux/init.h> #include <linux/hash.h> #include <linux/highmem.h> #include <asm/tlbflush.h> #include <trace/events/block.h> #define POOL_SIZE 64 #define ISA_POOL_SIZE 16 static mempool_t *page_pool, *isa_page_pool; #ifdef CONFIG_HIGHMEM static __init int init_emergency_pool(void) { struct sysinfo i; si_meminfo(&i); si_swapinfo(&i); if (!i.totalhigh) return 0; page_pool = mempool_create_page_pool(POOL_SIZE, 0); BUG_ON(!page_pool); printk("highmem bounce pool size: %d pages\n", POOL_SIZE); return 0; } __initcall(init_emergency_pool); /* * highmem version, map in to vec */ static void bounce_copy_vec(struct bio_vec *to, unsigned char *vfrom) { unsigned long flags; unsigned char *vto; local_irq_save(flags); vto = kmap_atomic(to->bv_page, KM_BOUNCE_READ); memcpy(vto + to->bv_offset, vfrom, to->bv_len); kunmap_atomic(vto, KM_BOUNCE_READ); local_irq_restore(flags); } #else /* CONFIG_HIGHMEM */ #define bounce_copy_vec(to, vfrom) \ memcpy(page_address((to)->bv_page) + (to)->bv_offset, vfrom, (to)->bv_len) #endif /* CONFIG_HIGHMEM */ /* * allocate pages in the DMA region for the ISA pool */ static void *mempool_alloc_pages_isa(gfp_t gfp_mask, void *data) { return mempool_alloc_pages(gfp_mask | GFP_DMA, data); } /* * gets called "every" time someone init's a queue with BLK_BOUNCE_ISA * as the max address, so check if the pool has already been created. */ int init_emergency_isa_pool(void) { if (isa_page_pool) return 0; isa_page_pool = mempool_create(ISA_POOL_SIZE, mempool_alloc_pages_isa, mempool_free_pages, (void *) 0); BUG_ON(!isa_page_pool); printk("isa bounce pool size: %d pages\n", ISA_POOL_SIZE); return 0; } /* * Simple bounce buffer support for highmem pages. Depending on the * queue gfp mask set, *to may or may not be a highmem page. kmap it * always, it will do the Right Thing */ static void copy_to_high_bio_irq(struct bio *to, struct bio *from) { unsigned char *vfrom; struct bio_vec *tovec, *fromvec; int i; __bio_for_each_segment(tovec, to, i, 0) { fromvec = from->bi_io_vec + i; /* * not bounced */ if (tovec->bv_page == fromvec->bv_page) continue; /* * fromvec->bv_offset and fromvec->bv_len might have been * modified by the block layer, so use the original copy, * bounce_copy_vec already uses tovec->bv_len */ vfrom = page_address(fromvec->bv_page) + tovec->bv_offset; bounce_copy_vec(tovec, vfrom); flush_dcache_page(tovec->bv_page); } } static void bounce_end_io(struct bio *bio, mempool_t *pool, int err) { struct bio *bio_orig = bio->bi_private; struct bio_vec *bvec, *org_vec; int i; if (test_bit(BIO_EOPNOTSUPP, &bio->bi_flags)) set_bit(BIO_EOPNOTSUPP, &bio_orig->bi_flags); /* * free up bounce indirect pages used */ __bio_for_each_segment(bvec, bio, i, 0) { org_vec = bio_orig->bi_io_vec + i; if (bvec->bv_page == org_vec->bv_page) continue; dec_zone_page_state(bvec->bv_page, NR_BOUNCE); mempool_free(bvec->bv_page, pool); } bio_endio(bio_orig, err); bio_put(bio); } static void bounce_end_io_write(struct bio *bio, int err) { bounce_end_io(bio, page_pool, err); } static void bounce_end_io_write_isa(struct bio *bio, int err) { bounce_end_io(bio, isa_page_pool, err); } static void __bounce_end_io_read(struct bio *bio, mempool_t *pool, int err) { struct bio *bio_orig = bio->bi_private; if (test_bit(BIO_UPTODATE, &bio->bi_flags)) copy_to_high_bio_irq(bio_orig, bio); bounce_end_io(bio, pool, err); } static void bounce_end_io_read(struct bio *bio, int err) { __bounce_end_io_read(bio, page_pool, err); } static void bounce_end_io_read_isa(struct bio *bio, int err) { __bounce_end_io_read(bio, isa_page_pool, err); } static void __blk_queue_bounce(struct request_queue *q, struct bio **bio_orig, mempool_t *pool) { struct page *page; struct bio *bio = NULL; int i, rw = bio_data_dir(*bio_orig); struct bio_vec *to, *from; bio_for_each_segment(from, *bio_orig, i) { page = from->bv_page; /* * is destination page below bounce pfn? */ if (page_to_pfn(page) <= queue_bounce_pfn(q)) continue; /* * irk, bounce it */ if (!bio) { unsigned int cnt = (*bio_orig)->bi_vcnt; bio = bio_alloc(GFP_NOIO, cnt); memset(bio->bi_io_vec, 0, cnt * sizeof(struct bio_vec)); } to = bio->bi_io_vec + i; to->bv_page = mempool_alloc(pool, q->bounce_gfp); to->bv_len = from->bv_len; to->bv_offset = from->bv_offset; inc_zone_page_state(to->bv_page, NR_BOUNCE); if (rw == WRITE) { char *vto, *vfrom; flush_dcache_page(from->bv_page); vto = page_address(to->bv_page) + to->bv_offset; vfrom = kmap(from->bv_page) + from->bv_offset; memcpy(vto, vfrom, to->bv_len); kunmap(from->bv_page); } } /* * no pages bounced */ if (!bio) return; trace_block_bio_bounce(q, *bio_orig); /* * at least one page was bounced, fill in possible non-highmem * pages */ __bio_for_each_segment(from, *bio_orig, i, 0) { to = bio_iovec_idx(bio, i); if (!to->bv_page) { to->bv_page = from->bv_page; to->bv_len = from->bv_len; to->bv_offset = from->bv_offset; } } bio->bi_bdev = (*bio_orig)->bi_bdev; bio->bi_flags |= (1 << BIO_BOUNCED); bio->bi_sector = (*bio_orig)->bi_sector; bio->bi_rw = (*bio_orig)->bi_rw; bio->bi_vcnt = (*bio_orig)->bi_vcnt; bio->bi_idx = (*bio_orig)->bi_idx; bio->bi_size = (*bio_orig)->bi_size; if (pool == page_pool) { bio->bi_end_io = bounce_end_io_write; if (rw == READ) bio->bi_end_io = bounce_end_io_read; } else { bio->bi_end_io = bounce_end_io_write_isa; if (rw == READ) bio->bi_end_io = bounce_end_io_read_isa; } bio->bi_private = *bio_orig; *bio_orig = bio; } void blk_queue_bounce(struct request_queue *q, struct bio **bio_orig) { mempool_t *pool; /* * Data-less bio, nothing to bounce */ if (!bio_has_data(*bio_orig)) return; /* * for non-isa bounce case, just check if the bounce pfn is equal * to or bigger than the highest pfn in the system -- in that case, * don't waste time iterating over bio segments */ if (!(q->bounce_gfp & GFP_DMA)) { if (queue_bounce_pfn(q) >= blk_max_pfn) return; pool = page_pool; } else { BUG_ON(!isa_page_pool); pool = isa_page_pool; } /* * slow path */ __blk_queue_bounce(q, bio_orig, pool); } EXPORT_SYMBOL(blk_queue_bounce);
gpl-2.0
ghsr/android_kernel_samsung_i9152
arch/arm/mach-msm/clock-debug.c
4120
3039
/* * Copyright (C) 2007 Google, Inc. * Copyright (c) 2007-2010, Code Aurora Forum. All rights reserved. * * 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/module.h> #include <linux/ctype.h> #include <linux/debugfs.h> #include <linux/clk.h> #include "clock.h" static int clock_debug_rate_set(void *data, u64 val) { struct clk *clock = data; int ret; /* Only increases to max rate will succeed, but that's actually good * for debugging purposes so we don't check for error. */ if (clock->flags & CLK_MAX) clk_set_max_rate(clock, val); if (clock->flags & CLK_MIN) ret = clk_set_min_rate(clock, val); else ret = clk_set_rate(clock, val); if (ret != 0) printk(KERN_ERR "clk_set%s_rate failed (%d)\n", (clock->flags & CLK_MIN) ? "_min" : "", ret); return ret; } static int clock_debug_rate_get(void *data, u64 *val) { struct clk *clock = data; *val = clk_get_rate(clock); return 0; } DEFINE_SIMPLE_ATTRIBUTE(clock_rate_fops, clock_debug_rate_get, clock_debug_rate_set, "%llu\n"); static int clock_debug_enable_set(void *data, u64 val) { struct clk *clock = data; int rc = 0; if (val) rc = clock->ops->enable(clock->id); else clock->ops->disable(clock->id); return rc; } static int clock_debug_enable_get(void *data, u64 *val) { struct clk *clock = data; *val = clock->ops->is_enabled(clock->id); return 0; } DEFINE_SIMPLE_ATTRIBUTE(clock_enable_fops, clock_debug_enable_get, clock_debug_enable_set, "%llu\n"); static int clock_debug_local_get(void *data, u64 *val) { struct clk *clock = data; *val = clock->ops->is_local(clock->id); return 0; } DEFINE_SIMPLE_ATTRIBUTE(clock_local_fops, clock_debug_local_get, NULL, "%llu\n"); static struct dentry *debugfs_base; int __init clock_debug_init(void) { debugfs_base = debugfs_create_dir("clk", NULL); if (!debugfs_base) return -ENOMEM; return 0; } int __init clock_debug_add(struct clk *clock) { char temp[50], *ptr; struct dentry *clk_dir; if (!debugfs_base) return -ENOMEM; strncpy(temp, clock->dbg_name, ARRAY_SIZE(temp)-1); for (ptr = temp; *ptr; ptr++) *ptr = tolower(*ptr); clk_dir = debugfs_create_dir(temp, debugfs_base); if (!clk_dir) return -ENOMEM; if (!debugfs_create_file("rate", S_IRUGO | S_IWUSR, clk_dir, clock, &clock_rate_fops)) goto error; if (!debugfs_create_file("enable", S_IRUGO | S_IWUSR, clk_dir, clock, &clock_enable_fops)) goto error; if (!debugfs_create_file("is_local", S_IRUGO, clk_dir, clock, &clock_local_fops)) goto error; return 0; error: debugfs_remove_recursive(clk_dir); return -ENOMEM; }
gpl-2.0
NoelMacwan/kernel_sony_msm8x27
drivers/mtd/chips/jedec_probe.c
7448
57819
/* Common Flash Interface probe code. (C) 2000 Red Hat. GPL'd. See JEDEC (http://www.jedec.org/) standard JESD21C (section 3.5) for the standard this probe goes back to. Occasionally maintained by Thayne Harbaugh tharbaugh at lnxi dot com */ #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/kernel.h> #include <asm/io.h> #include <asm/byteorder.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/mtd/mtd.h> #include <linux/mtd/map.h> #include <linux/mtd/cfi.h> #include <linux/mtd/gen_probe.h> /* AMD */ #define AM29DL800BB 0x22CB #define AM29DL800BT 0x224A #define AM29F800BB 0x2258 #define AM29F800BT 0x22D6 #define AM29LV400BB 0x22BA #define AM29LV400BT 0x22B9 #define AM29LV800BB 0x225B #define AM29LV800BT 0x22DA #define AM29LV160DT 0x22C4 #define AM29LV160DB 0x2249 #define AM29F017D 0x003D #define AM29F016D 0x00AD #define AM29F080 0x00D5 #define AM29F040 0x00A4 #define AM29LV040B 0x004F #define AM29F032B 0x0041 #define AM29F002T 0x00B0 #define AM29SL800DB 0x226B #define AM29SL800DT 0x22EA /* Atmel */ #define AT49BV512 0x0003 #define AT29LV512 0x003d #define AT49BV16X 0x00C0 #define AT49BV16XT 0x00C2 #define AT49BV32X 0x00C8 #define AT49BV32XT 0x00C9 /* Eon */ #define EN29SL800BB 0x226B #define EN29SL800BT 0x22EA /* Fujitsu */ #define MBM29F040C 0x00A4 #define MBM29F800BA 0x2258 #define MBM29LV650UE 0x22D7 #define MBM29LV320TE 0x22F6 #define MBM29LV320BE 0x22F9 #define MBM29LV160TE 0x22C4 #define MBM29LV160BE 0x2249 #define MBM29LV800BA 0x225B #define MBM29LV800TA 0x22DA #define MBM29LV400TC 0x22B9 #define MBM29LV400BC 0x22BA /* Hyundai */ #define HY29F002T 0x00B0 /* Intel */ #define I28F004B3T 0x00d4 #define I28F004B3B 0x00d5 #define I28F400B3T 0x8894 #define I28F400B3B 0x8895 #define I28F008S5 0x00a6 #define I28F016S5 0x00a0 #define I28F008SA 0x00a2 #define I28F008B3T 0x00d2 #define I28F008B3B 0x00d3 #define I28F800B3T 0x8892 #define I28F800B3B 0x8893 #define I28F016S3 0x00aa #define I28F016B3T 0x00d0 #define I28F016B3B 0x00d1 #define I28F160B3T 0x8890 #define I28F160B3B 0x8891 #define I28F320B3T 0x8896 #define I28F320B3B 0x8897 #define I28F640B3T 0x8898 #define I28F640B3B 0x8899 #define I28F640C3B 0x88CD #define I28F160F3T 0x88F3 #define I28F160F3B 0x88F4 #define I28F160C3T 0x88C2 #define I28F160C3B 0x88C3 #define I82802AB 0x00ad #define I82802AC 0x00ac /* Macronix */ #define MX29LV040C 0x004F #define MX29LV160T 0x22C4 #define MX29LV160B 0x2249 #define MX29F040 0x00A4 #define MX29F016 0x00AD #define MX29F002T 0x00B0 #define MX29F004T 0x0045 #define MX29F004B 0x0046 /* NEC */ #define UPD29F064115 0x221C /* PMC */ #define PM49FL002 0x006D #define PM49FL004 0x006E #define PM49FL008 0x006A /* Sharp */ #define LH28F640BF 0x00b0 /* ST - www.st.com */ #define M29F800AB 0x0058 #define M29W800DT 0x22D7 #define M29W800DB 0x225B #define M29W400DT 0x00EE #define M29W400DB 0x00EF #define M29W160DT 0x22C4 #define M29W160DB 0x2249 #define M29W040B 0x00E3 #define M50FW040 0x002C #define M50FW080 0x002D #define M50FW016 0x002E #define M50LPW080 0x002F #define M50FLW080A 0x0080 #define M50FLW080B 0x0081 #define PSD4256G6V 0x00e9 /* SST */ #define SST29EE020 0x0010 #define SST29LE020 0x0012 #define SST29EE512 0x005d #define SST29LE512 0x003d #define SST39LF800 0x2781 #define SST39LF160 0x2782 #define SST39VF1601 0x234b #define SST39VF3201 0x235b #define SST39WF1601 0x274b #define SST39WF1602 0x274a #define SST39LF512 0x00D4 #define SST39LF010 0x00D5 #define SST39LF020 0x00D6 #define SST39LF040 0x00D7 #define SST39SF010A 0x00B5 #define SST39SF020A 0x00B6 #define SST39SF040 0x00B7 #define SST49LF004B 0x0060 #define SST49LF040B 0x0050 #define SST49LF008A 0x005a #define SST49LF030A 0x001C #define SST49LF040A 0x0051 #define SST49LF080A 0x005B #define SST36VF3203 0x7354 /* Toshiba */ #define TC58FVT160 0x00C2 #define TC58FVB160 0x0043 #define TC58FVT321 0x009A #define TC58FVB321 0x009C #define TC58FVT641 0x0093 #define TC58FVB641 0x0095 /* Winbond */ #define W49V002A 0x00b0 /* * Unlock address sets for AMD command sets. * Intel command sets use the MTD_UADDR_UNNECESSARY. * Each identifier, except MTD_UADDR_UNNECESSARY, and * MTD_UADDR_NO_SUPPORT must be defined below in unlock_addrs[]. * MTD_UADDR_NOT_SUPPORTED must be 0 so that structure * initialization need not require initializing all of the * unlock addresses for all bit widths. */ enum uaddr { MTD_UADDR_NOT_SUPPORTED = 0, /* data width not supported */ MTD_UADDR_0x0555_0x02AA, MTD_UADDR_0x0555_0x0AAA, MTD_UADDR_0x5555_0x2AAA, MTD_UADDR_0x0AAA_0x0554, MTD_UADDR_0x0AAA_0x0555, MTD_UADDR_0xAAAA_0x5555, MTD_UADDR_DONT_CARE, /* Requires an arbitrary address */ MTD_UADDR_UNNECESSARY, /* Does not require any address */ }; struct unlock_addr { uint32_t addr1; uint32_t addr2; }; /* * I don't like the fact that the first entry in unlock_addrs[] * exists, but is for MTD_UADDR_NOT_SUPPORTED - and, therefore, * should not be used. The problem is that structures with * initializers have extra fields initialized to 0. It is _very_ * desirable to have the unlock address entries for unsupported * data widths automatically initialized - that means that * MTD_UADDR_NOT_SUPPORTED must be 0 and the first entry here * must go unused. */ static const struct unlock_addr unlock_addrs[] = { [MTD_UADDR_NOT_SUPPORTED] = { .addr1 = 0xffff, .addr2 = 0xffff }, [MTD_UADDR_0x0555_0x02AA] = { .addr1 = 0x0555, .addr2 = 0x02aa }, [MTD_UADDR_0x0555_0x0AAA] = { .addr1 = 0x0555, .addr2 = 0x0aaa }, [MTD_UADDR_0x5555_0x2AAA] = { .addr1 = 0x5555, .addr2 = 0x2aaa }, [MTD_UADDR_0x0AAA_0x0554] = { .addr1 = 0x0AAA, .addr2 = 0x0554 }, [MTD_UADDR_0x0AAA_0x0555] = { .addr1 = 0x0AAA, .addr2 = 0x0555 }, [MTD_UADDR_0xAAAA_0x5555] = { .addr1 = 0xaaaa, .addr2 = 0x5555 }, [MTD_UADDR_DONT_CARE] = { .addr1 = 0x0000, /* Doesn't matter which address */ .addr2 = 0x0000 /* is used - must be last entry */ }, [MTD_UADDR_UNNECESSARY] = { .addr1 = 0x0000, .addr2 = 0x0000 } }; struct amd_flash_info { const char *name; const uint16_t mfr_id; const uint16_t dev_id; const uint8_t dev_size; const uint8_t nr_regions; const uint16_t cmd_set; const uint32_t regions[6]; const uint8_t devtypes; /* Bitmask for x8, x16 etc. */ const uint8_t uaddr; /* unlock addrs for 8, 16, 32, 64 */ }; #define ERASEINFO(size,blocks) (size<<8)|(blocks-1) #define SIZE_64KiB 16 #define SIZE_128KiB 17 #define SIZE_256KiB 18 #define SIZE_512KiB 19 #define SIZE_1MiB 20 #define SIZE_2MiB 21 #define SIZE_4MiB 22 #define SIZE_8MiB 23 /* * Please keep this list ordered by manufacturer! * Fortunately, the list isn't searched often and so a * slow, linear search isn't so bad. */ static const struct amd_flash_info jedec_table[] = { { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F032B, .name = "AMD AM29F032B", .uaddr = MTD_UADDR_0x0555_0x02AA, .devtypes = CFI_DEVICETYPE_X8, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,64) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV160DT, .name = "AMD AM29LV160DT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,31), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV160DB, .name = "AMD AM29LV160DB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,31) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV400BB, .name = "AMD AM29LV400BB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,7) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV400BT, .name = "AMD AM29LV400BT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,7), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV800BB, .name = "AMD AM29LV800BB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15), } }, { /* add DL */ .mfr_id = CFI_MFR_AMD, .dev_id = AM29DL800BB, .name = "AMD AM29DL800BB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 6, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x08000,1), ERASEINFO(0x02000,4), ERASEINFO(0x08000,1), ERASEINFO(0x04000,1), ERASEINFO(0x10000,14) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29DL800BT, .name = "AMD AM29DL800BT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 6, .regions = { ERASEINFO(0x10000,14), ERASEINFO(0x04000,1), ERASEINFO(0x08000,1), ERASEINFO(0x02000,4), ERASEINFO(0x08000,1), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F800BB, .name = "AMD AM29F800BB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV800BT, .name = "AMD AM29LV800BT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,15), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F800BT, .name = "AMD AM29F800BT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,15), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F017D, .name = "AMD AM29F017D", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_DONT_CARE, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,32), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F016D, .name = "AMD AM29F016D", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,32), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F080, .name = "AMD AM29F080", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,16), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F040, .name = "AMD AM29F040", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29LV040B, .name = "AMD AM29LV040B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29F002T, .name = "AMD AM29F002T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,3), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29SL800DT, .name = "AMD AM29SL800DT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,15), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1), } }, { .mfr_id = CFI_MFR_AMD, .dev_id = AM29SL800DB, .name = "AMD AM29SL800DB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15), } }, { .mfr_id = CFI_MFR_ATMEL, .dev_id = AT49BV512, .name = "Atmel AT49BV512", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_64KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,1) } }, { .mfr_id = CFI_MFR_ATMEL, .dev_id = AT29LV512, .name = "Atmel AT29LV512", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_64KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x80,256), ERASEINFO(0x80,256) } }, { .mfr_id = CFI_MFR_ATMEL, .dev_id = AT49BV16X, .name = "Atmel AT49BV16X", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x0AAA, /* ???? */ .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000,8), ERASEINFO(0x10000,31) } }, { .mfr_id = CFI_MFR_ATMEL, .dev_id = AT49BV16XT, .name = "Atmel AT49BV16XT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x0AAA, /* ???? */ .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000,31), ERASEINFO(0x02000,8) } }, { .mfr_id = CFI_MFR_ATMEL, .dev_id = AT49BV32X, .name = "Atmel AT49BV32X", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x0AAA, /* ???? */ .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000,8), ERASEINFO(0x10000,63) } }, { .mfr_id = CFI_MFR_ATMEL, .dev_id = AT49BV32XT, .name = "Atmel AT49BV32XT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x0AAA, /* ???? */ .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000,63), ERASEINFO(0x02000,8) } }, { .mfr_id = CFI_MFR_EON, .dev_id = EN29SL800BT, .name = "Eon EN29SL800BT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,15), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1), } }, { .mfr_id = CFI_MFR_EON, .dev_id = EN29SL800BB, .name = "Eon EN29SL800BB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15), } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29F040C, .name = "Fujitsu MBM29F040C", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29F800BA, .name = "Fujitsu MBM29F800BA", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15), } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV650UE, .name = "Fujitsu MBM29LV650UE", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_DONT_CARE, .dev_size = SIZE_8MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,128) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV320TE, .name = "Fujitsu MBM29LV320TE", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000,63), ERASEINFO(0x02000,8) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV320BE, .name = "Fujitsu MBM29LV320BE", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000,8), ERASEINFO(0x10000,63) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV160TE, .name = "Fujitsu MBM29LV160TE", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,31), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV160BE, .name = "Fujitsu MBM29LV160BE", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,31) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV800BA, .name = "Fujitsu MBM29LV800BA", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV800TA, .name = "Fujitsu MBM29LV800TA", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,15), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV400BC, .name = "Fujitsu MBM29LV400BC", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,7) } }, { .mfr_id = CFI_MFR_FUJITSU, .dev_id = MBM29LV400TC, .name = "Fujitsu MBM29LV400TC", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,7), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_HYUNDAI, .dev_id = HY29F002T, .name = "Hyundai HY29F002T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,3), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F004B3B, .name = "Intel 28F004B3B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_512KiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 7), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F004B3T, .name = "Intel 28F004B3T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_512KiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 7), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F400B3B, .name = "Intel 28F400B3B", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_512KiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 7), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F400B3T, .name = "Intel 28F400B3T", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_512KiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 7), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F008B3B, .name = "Intel 28F008B3B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 15), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F008B3T, .name = "Intel 28F008B3T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 15), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F008S5, .name = "Intel 28F008S5", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,16), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F016S5, .name = "Intel 28F016S5", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,32), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F008SA, .name = "Intel 28F008SA", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000, 16), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F800B3B, .name = "Intel 28F800B3B", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 15), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F800B3T, .name = "Intel 28F800B3T", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 15), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F016B3B, .name = "Intel 28F016B3B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 31), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F016S3, .name = "Intel I28F016S3", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000, 32), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F016B3T, .name = "Intel 28F016B3T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 31), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F160B3B, .name = "Intel 28F160B3B", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 31), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F160B3T, .name = "Intel 28F160B3T", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 31), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F320B3B, .name = "Intel 28F320B3B", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_4MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 63), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F320B3T, .name = "Intel 28F320B3T", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_4MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 63), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F640B3B, .name = "Intel 28F640B3B", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_8MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 127), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F640B3T, .name = "Intel 28F640B3T", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_8MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000, 127), ERASEINFO(0x02000, 8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I28F640C3B, .name = "Intel 28F640C3B", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_8MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000, 8), ERASEINFO(0x10000, 127), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I82802AB, .name = "Intel 82802AB", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_512KiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_INTEL, .dev_id = I82802AC, .name = "Intel 82802AC", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,16), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29LV040C, .name = "Macronix MX29LV040C", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29LV160T, .name = "MXIC MX29LV160T", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,31), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_NEC, .dev_id = UPD29F064115, .name = "NEC uPD29F064115", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0xAAAA_0x5555, .dev_size = SIZE_8MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 3, .regions = { ERASEINFO(0x2000,8), ERASEINFO(0x10000,126), ERASEINFO(0x2000,8), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29LV160B, .name = "MXIC MX29LV160B", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,31) } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29F040, .name = "Macronix MX29F040", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29F016, .name = "Macronix MX29F016", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,32), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29F004T, .name = "Macronix MX29F004T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,7), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29F004B, .name = "Macronix MX29F004B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,7), } }, { .mfr_id = CFI_MFR_MACRONIX, .dev_id = MX29F002T, .name = "Macronix MX29F002T", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,3), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1), } }, { .mfr_id = CFI_MFR_PMC, .dev_id = PM49FL002, .name = "PMC Pm49FL002", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO( 0x01000, 64 ) } }, { .mfr_id = CFI_MFR_PMC, .dev_id = PM49FL004, .name = "PMC Pm49FL004", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO( 0x01000, 128 ) } }, { .mfr_id = CFI_MFR_PMC, .dev_id = PM49FL008, .name = "PMC Pm49FL008", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO( 0x01000, 256 ) } }, { .mfr_id = CFI_MFR_SHARP, .dev_id = LH28F640BF, .name = "LH28F640BF", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_4MiB, .cmd_set = P_ID_INTEL_STD, .nr_regions = 1, .regions = { ERASEINFO(0x40000,16), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39LF512, .name = "SST 39LF512", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_64KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,16), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39LF010, .name = "SST 39LF010", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_128KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,32), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST29EE020, .name = "SST 29EE020", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_SST_PAGE, .nr_regions = 1, .regions = {ERASEINFO(0x01000,64), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST29LE020, .name = "SST 29LE020", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_SST_PAGE, .nr_regions = 1, .regions = {ERASEINFO(0x01000,64), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39LF020, .name = "SST 39LF020", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,64), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39LF040, .name = "SST 39LF040", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,128), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39SF010A, .name = "SST 39SF010A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_128KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,32), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39SF020A, .name = "SST 39SF020A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,64), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST39SF040, .name = "SST 39SF040", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,128), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST49LF040B, .name = "SST 49LF040B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,128), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST49LF004B, .name = "SST 49LF004B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,128), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST49LF008A, .name = "SST 49LF008A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,256), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST49LF030A, .name = "SST 49LF030A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,96), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST49LF040A, .name = "SST 49LF040A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,128), } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST49LF080A, .name = "SST 49LF080A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x01000,256), } }, { .mfr_id = CFI_MFR_SST, /* should be CFI */ .dev_id = SST39LF160, .name = "SST 39LF160", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0xAAAA_0x5555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x1000,256), ERASEINFO(0x1000,256) } }, { .mfr_id = CFI_MFR_SST, /* should be CFI */ .dev_id = SST39VF1601, .name = "SST 39VF1601", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0xAAAA_0x5555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x1000,256), ERASEINFO(0x1000,256) } }, { /* CFI is broken: reports AMD_STD, but needs custom uaddr */ .mfr_id = CFI_MFR_SST, .dev_id = SST39WF1601, .name = "SST 39WF1601", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0xAAAA_0x5555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x1000,256), ERASEINFO(0x1000,256) } }, { /* CFI is broken: reports AMD_STD, but needs custom uaddr */ .mfr_id = CFI_MFR_SST, .dev_id = SST39WF1602, .name = "SST 39WF1602", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0xAAAA_0x5555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x1000,256), ERASEINFO(0x1000,256) } }, { .mfr_id = CFI_MFR_SST, /* should be CFI */ .dev_id = SST39VF3201, .name = "SST 39VF3201", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0xAAAA_0x5555, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x1000,256), ERASEINFO(0x1000,256), ERASEINFO(0x1000,256), ERASEINFO(0x1000,256) } }, { .mfr_id = CFI_MFR_SST, .dev_id = SST36VF3203, .name = "SST 36VF3203", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,64), } }, { .mfr_id = CFI_MFR_ST, .dev_id = M29F800AB, .name = "ST M29F800AB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15), } }, { .mfr_id = CFI_MFR_ST, /* FIXME - CFI device? */ .dev_id = M29W800DT, .name = "ST M29W800DT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,15), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_ST, /* FIXME - CFI device? */ .dev_id = M29W800DB, .name = "ST M29W800DB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,15) } }, { .mfr_id = CFI_MFR_ST, .dev_id = M29W400DT, .name = "ST M29W400DT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,7), ERASEINFO(0x02000,1), ERASEINFO(0x08000,2), ERASEINFO(0x10000,1) } }, { .mfr_id = CFI_MFR_ST, .dev_id = M29W400DB, .name = "ST M29W400DB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,7) } }, { .mfr_id = CFI_MFR_ST, /* FIXME - CFI device? */ .dev_id = M29W160DT, .name = "ST M29W160DT", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, /* ???? */ .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,31), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_ST, /* FIXME - CFI device? */ .dev_id = M29W160DB, .name = "ST M29W160DB", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, /* ???? */ .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,31) } }, { .mfr_id = CFI_MFR_ST, .dev_id = M29W040B, .name = "ST M29W040B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0555_0x02AA, .dev_size = SIZE_512KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_ST, .dev_id = M50FW040, .name = "ST M50FW040", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_512KiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,8), } }, { .mfr_id = CFI_MFR_ST, .dev_id = M50FW080, .name = "ST M50FW080", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,16), } }, { .mfr_id = CFI_MFR_ST, .dev_id = M50FW016, .name = "ST M50FW016", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_2MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,32), } }, { .mfr_id = CFI_MFR_ST, .dev_id = M50LPW080, .name = "ST M50LPW080", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 1, .regions = { ERASEINFO(0x10000,16), }, }, { .mfr_id = CFI_MFR_ST, .dev_id = M50FLW080A, .name = "ST M50FLW080A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 4, .regions = { ERASEINFO(0x1000,16), ERASEINFO(0x10000,13), ERASEINFO(0x1000,16), ERASEINFO(0x1000,16), } }, { .mfr_id = CFI_MFR_ST, .dev_id = M50FLW080B, .name = "ST M50FLW080B", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_UNNECESSARY, .dev_size = SIZE_1MiB, .cmd_set = P_ID_INTEL_EXT, .nr_regions = 4, .regions = { ERASEINFO(0x1000,16), ERASEINFO(0x1000,16), ERASEINFO(0x10000,13), ERASEINFO(0x1000,16), } }, { .mfr_id = 0xff00 | CFI_MFR_ST, .dev_id = 0xff00 | PSD4256G6V, .name = "ST PSD4256G6V", .devtypes = CFI_DEVICETYPE_X16, .uaddr = MTD_UADDR_0x0AAA_0x0554, .dev_size = SIZE_1MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 1, .regions = { ERASEINFO(0x10000,16), } }, { .mfr_id = CFI_MFR_TOSHIBA, .dev_id = TC58FVT160, .name = "Toshiba TC58FVT160", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000,31), ERASEINFO(0x08000,1), ERASEINFO(0x02000,2), ERASEINFO(0x04000,1) } }, { .mfr_id = CFI_MFR_TOSHIBA, .dev_id = TC58FVB160, .name = "Toshiba TC58FVB160", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_2MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x04000,1), ERASEINFO(0x02000,2), ERASEINFO(0x08000,1), ERASEINFO(0x10000,31) } }, { .mfr_id = CFI_MFR_TOSHIBA, .dev_id = TC58FVB321, .name = "Toshiba TC58FVB321", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000,8), ERASEINFO(0x10000,63) } }, { .mfr_id = CFI_MFR_TOSHIBA, .dev_id = TC58FVT321, .name = "Toshiba TC58FVT321", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_4MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000,63), ERASEINFO(0x02000,8) } }, { .mfr_id = CFI_MFR_TOSHIBA, .dev_id = TC58FVB641, .name = "Toshiba TC58FVB641", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_8MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x02000,8), ERASEINFO(0x10000,127) } }, { .mfr_id = CFI_MFR_TOSHIBA, .dev_id = TC58FVT641, .name = "Toshiba TC58FVT641", .devtypes = CFI_DEVICETYPE_X16|CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x0AAA_0x0555, .dev_size = SIZE_8MiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 2, .regions = { ERASEINFO(0x10000,127), ERASEINFO(0x02000,8) } }, { .mfr_id = CFI_MFR_WINBOND, .dev_id = W49V002A, .name = "Winbond W49V002A", .devtypes = CFI_DEVICETYPE_X8, .uaddr = MTD_UADDR_0x5555_0x2AAA, .dev_size = SIZE_256KiB, .cmd_set = P_ID_AMD_STD, .nr_regions = 4, .regions = { ERASEINFO(0x10000, 3), ERASEINFO(0x08000, 1), ERASEINFO(0x02000, 2), ERASEINFO(0x04000, 1), } } }; static inline u32 jedec_read_mfr(struct map_info *map, uint32_t base, struct cfi_private *cfi) { map_word result; unsigned long mask; int bank = 0; /* According to JEDEC "Standard Manufacturer's Identification Code" * (http://www.jedec.org/download/search/jep106W.pdf) * several first banks can contain 0x7f instead of actual ID */ do { uint32_t ofs = cfi_build_cmd_addr(0 + (bank << 8), map, cfi); mask = (1 << (cfi->device_type * 8)) - 1; result = map_read(map, base + ofs); bank++; } while ((result.x[0] & mask) == CFI_MFR_CONTINUATION); return result.x[0] & mask; } static inline u32 jedec_read_id(struct map_info *map, uint32_t base, struct cfi_private *cfi) { map_word result; unsigned long mask; u32 ofs = cfi_build_cmd_addr(1, map, cfi); mask = (1 << (cfi->device_type * 8)) -1; result = map_read(map, base + ofs); return result.x[0] & mask; } static void jedec_reset(u32 base, struct map_info *map, struct cfi_private *cfi) { /* Reset */ /* after checking the datasheets for SST, MACRONIX and ATMEL * (oh and incidentaly the jedec spec - 3.5.3.3) the reset * sequence is *supposed* to be 0xaa at 0x5555, 0x55 at * 0x2aaa, 0xF0 at 0x5555 this will not affect the AMD chips * as they will ignore the writes and don't care what address * the F0 is written to */ if (cfi->addr_unlock1) { pr_debug( "reset unlock called %x %x \n", cfi->addr_unlock1,cfi->addr_unlock2); cfi_send_gen_cmd(0xaa, cfi->addr_unlock1, base, map, cfi, cfi->device_type, NULL); cfi_send_gen_cmd(0x55, cfi->addr_unlock2, base, map, cfi, cfi->device_type, NULL); } cfi_send_gen_cmd(0xF0, cfi->addr_unlock1, base, map, cfi, cfi->device_type, NULL); /* Some misdesigned Intel chips do not respond for 0xF0 for a reset, * so ensure we're in read mode. Send both the Intel and the AMD command * for this. Intel uses 0xff for this, AMD uses 0xff for NOP, so * this should be safe. */ cfi_send_gen_cmd(0xFF, 0, base, map, cfi, cfi->device_type, NULL); /* FIXME - should have reset delay before continuing */ } static int cfi_jedec_setup(struct map_info *map, struct cfi_private *cfi, int index) { int i,num_erase_regions; uint8_t uaddr; if (!(jedec_table[index].devtypes & cfi->device_type)) { pr_debug("Rejecting potential %s with incompatible %d-bit device type\n", jedec_table[index].name, 4 * (1<<cfi->device_type)); return 0; } printk(KERN_INFO "Found: %s\n",jedec_table[index].name); num_erase_regions = jedec_table[index].nr_regions; cfi->cfiq = kmalloc(sizeof(struct cfi_ident) + num_erase_regions * 4, GFP_KERNEL); if (!cfi->cfiq) { //xx printk(KERN_WARNING "%s: kmalloc failed for CFI ident structure\n", map->name); return 0; } memset(cfi->cfiq, 0, sizeof(struct cfi_ident)); cfi->cfiq->P_ID = jedec_table[index].cmd_set; cfi->cfiq->NumEraseRegions = jedec_table[index].nr_regions; cfi->cfiq->DevSize = jedec_table[index].dev_size; cfi->cfi_mode = CFI_MODE_JEDEC; cfi->sector_erase_cmd = CMD(0x30); for (i=0; i<num_erase_regions; i++){ cfi->cfiq->EraseRegionInfo[i] = jedec_table[index].regions[i]; } cfi->cmdset_priv = NULL; /* This may be redundant for some cases, but it doesn't hurt */ cfi->mfr = jedec_table[index].mfr_id; cfi->id = jedec_table[index].dev_id; uaddr = jedec_table[index].uaddr; /* The table has unlock addresses in _bytes_, and we try not to let our brains explode when we see the datasheets talking about address lines numbered from A-1 to A18. The CFI table has unlock addresses in device-words according to the mode the device is connected in */ cfi->addr_unlock1 = unlock_addrs[uaddr].addr1 / cfi->device_type; cfi->addr_unlock2 = unlock_addrs[uaddr].addr2 / cfi->device_type; return 1; /* ok */ } /* * There is a BIG problem properly ID'ing the JEDEC device and guaranteeing * the mapped address, unlock addresses, and proper chip ID. This function * attempts to minimize errors. It is doubtfull that this probe will ever * be perfect - consequently there should be some module parameters that * could be manually specified to force the chip info. */ static inline int jedec_match( uint32_t base, struct map_info *map, struct cfi_private *cfi, const struct amd_flash_info *finfo ) { int rc = 0; /* failure until all tests pass */ u32 mfr, id; uint8_t uaddr; /* * The IDs must match. For X16 and X32 devices operating in * a lower width ( X8 or X16 ), the device ID's are usually just * the lower byte(s) of the larger device ID for wider mode. If * a part is found that doesn't fit this assumption (device id for * smaller width mode is completely unrealated to full-width mode) * then the jedec_table[] will have to be augmented with the IDs * for different widths. */ switch (cfi->device_type) { case CFI_DEVICETYPE_X8: mfr = (uint8_t)finfo->mfr_id; id = (uint8_t)finfo->dev_id; /* bjd: it seems that if we do this, we can end up * detecting 16bit flashes as an 8bit device, even though * there aren't. */ if (finfo->dev_id > 0xff) { pr_debug("%s(): ID is not 8bit\n", __func__); goto match_done; } break; case CFI_DEVICETYPE_X16: mfr = (uint16_t)finfo->mfr_id; id = (uint16_t)finfo->dev_id; break; case CFI_DEVICETYPE_X32: mfr = (uint16_t)finfo->mfr_id; id = (uint32_t)finfo->dev_id; break; default: printk(KERN_WARNING "MTD %s(): Unsupported device type %d\n", __func__, cfi->device_type); goto match_done; } if ( cfi->mfr != mfr || cfi->id != id ) { goto match_done; } /* the part size must fit in the memory window */ pr_debug("MTD %s(): Check fit 0x%.8x + 0x%.8x = 0x%.8x\n", __func__, base, 1 << finfo->dev_size, base + (1 << finfo->dev_size) ); if ( base + cfi_interleave(cfi) * ( 1 << finfo->dev_size ) > map->size ) { pr_debug("MTD %s(): 0x%.4x 0x%.4x %dKiB doesn't fit\n", __func__, finfo->mfr_id, finfo->dev_id, 1 << finfo->dev_size ); goto match_done; } if (! (finfo->devtypes & cfi->device_type)) goto match_done; uaddr = finfo->uaddr; pr_debug("MTD %s(): check unlock addrs 0x%.4x 0x%.4x\n", __func__, cfi->addr_unlock1, cfi->addr_unlock2 ); if ( MTD_UADDR_UNNECESSARY != uaddr && MTD_UADDR_DONT_CARE != uaddr && ( unlock_addrs[uaddr].addr1 / cfi->device_type != cfi->addr_unlock1 || unlock_addrs[uaddr].addr2 / cfi->device_type != cfi->addr_unlock2 ) ) { pr_debug("MTD %s(): 0x%.4x 0x%.4x did not match\n", __func__, unlock_addrs[uaddr].addr1, unlock_addrs[uaddr].addr2); goto match_done; } /* * Make sure the ID's disappear when the device is taken out of * ID mode. The only time this should fail when it should succeed * is when the ID's are written as data to the same * addresses. For this rare and unfortunate case the chip * cannot be probed correctly. * FIXME - write a driver that takes all of the chip info as * module parameters, doesn't probe but forces a load. */ pr_debug("MTD %s(): check ID's disappear when not in ID mode\n", __func__ ); jedec_reset( base, map, cfi ); mfr = jedec_read_mfr( map, base, cfi ); id = jedec_read_id( map, base, cfi ); if ( mfr == cfi->mfr && id == cfi->id ) { pr_debug("MTD %s(): ID 0x%.2x:0x%.2x did not change after reset:\n" "You might need to manually specify JEDEC parameters.\n", __func__, cfi->mfr, cfi->id ); goto match_done; } /* all tests passed - mark as success */ rc = 1; /* * Put the device back in ID mode - only need to do this if we * were truly frobbing a real device. */ pr_debug("MTD %s(): return to ID mode\n", __func__ ); if (cfi->addr_unlock1) { cfi_send_gen_cmd(0xaa, cfi->addr_unlock1, base, map, cfi, cfi->device_type, NULL); cfi_send_gen_cmd(0x55, cfi->addr_unlock2, base, map, cfi, cfi->device_type, NULL); } cfi_send_gen_cmd(0x90, cfi->addr_unlock1, base, map, cfi, cfi->device_type, NULL); /* FIXME - should have a delay before continuing */ match_done: return rc; } static int jedec_probe_chip(struct map_info *map, __u32 base, unsigned long *chip_map, struct cfi_private *cfi) { int i; enum uaddr uaddr_idx = MTD_UADDR_NOT_SUPPORTED; u32 probe_offset1, probe_offset2; retry: if (!cfi->numchips) { uaddr_idx++; if (MTD_UADDR_UNNECESSARY == uaddr_idx) return 0; cfi->addr_unlock1 = unlock_addrs[uaddr_idx].addr1 / cfi->device_type; cfi->addr_unlock2 = unlock_addrs[uaddr_idx].addr2 / cfi->device_type; } /* Make certain we aren't probing past the end of map */ if (base >= map->size) { printk(KERN_NOTICE "Probe at base(0x%08x) past the end of the map(0x%08lx)\n", base, map->size -1); return 0; } /* Ensure the unlock addresses we try stay inside the map */ probe_offset1 = cfi_build_cmd_addr(cfi->addr_unlock1, map, cfi); probe_offset2 = cfi_build_cmd_addr(cfi->addr_unlock2, map, cfi); if ( ((base + probe_offset1 + map_bankwidth(map)) >= map->size) || ((base + probe_offset2 + map_bankwidth(map)) >= map->size)) goto retry; /* Reset */ jedec_reset(base, map, cfi); /* Autoselect Mode */ if(cfi->addr_unlock1) { cfi_send_gen_cmd(0xaa, cfi->addr_unlock1, base, map, cfi, cfi->device_type, NULL); cfi_send_gen_cmd(0x55, cfi->addr_unlock2, base, map, cfi, cfi->device_type, NULL); } cfi_send_gen_cmd(0x90, cfi->addr_unlock1, base, map, cfi, cfi->device_type, NULL); /* FIXME - should have a delay before continuing */ if (!cfi->numchips) { /* This is the first time we're called. Set up the CFI stuff accordingly and return */ cfi->mfr = jedec_read_mfr(map, base, cfi); cfi->id = jedec_read_id(map, base, cfi); pr_debug("Search for id:(%02x %02x) interleave(%d) type(%d)\n", cfi->mfr, cfi->id, cfi_interleave(cfi), cfi->device_type); for (i = 0; i < ARRAY_SIZE(jedec_table); i++) { if ( jedec_match( base, map, cfi, &jedec_table[i] ) ) { pr_debug("MTD %s(): matched device 0x%x,0x%x unlock_addrs: 0x%.4x 0x%.4x\n", __func__, cfi->mfr, cfi->id, cfi->addr_unlock1, cfi->addr_unlock2 ); if (!cfi_jedec_setup(map, cfi, i)) return 0; goto ok_out; } } goto retry; } else { uint16_t mfr; uint16_t id; /* Make sure it is a chip of the same manufacturer and id */ mfr = jedec_read_mfr(map, base, cfi); id = jedec_read_id(map, base, cfi); if ((mfr != cfi->mfr) || (id != cfi->id)) { printk(KERN_DEBUG "%s: Found different chip or no chip at all (mfr 0x%x, id 0x%x) at 0x%x\n", map->name, mfr, id, base); jedec_reset(base, map, cfi); return 0; } } /* Check each previous chip locations to see if it's an alias */ for (i=0; i < (base >> cfi->chipshift); i++) { unsigned long start; if(!test_bit(i, chip_map)) { continue; /* Skip location; no valid chip at this address */ } start = i << cfi->chipshift; if (jedec_read_mfr(map, start, cfi) == cfi->mfr && jedec_read_id(map, start, cfi) == cfi->id) { /* Eep. This chip also looks like it's in autoselect mode. Is it an alias for the new one? */ jedec_reset(start, map, cfi); /* If the device IDs go away, it's an alias */ if (jedec_read_mfr(map, base, cfi) != cfi->mfr || jedec_read_id(map, base, cfi) != cfi->id) { printk(KERN_DEBUG "%s: Found an alias at 0x%x for the chip at 0x%lx\n", map->name, base, start); return 0; } /* Yes, it's actually got the device IDs as data. Most * unfortunate. Stick the new chip in read mode * too and if it's the same, assume it's an alias. */ /* FIXME: Use other modes to do a proper check */ jedec_reset(base, map, cfi); if (jedec_read_mfr(map, base, cfi) == cfi->mfr && jedec_read_id(map, base, cfi) == cfi->id) { printk(KERN_DEBUG "%s: Found an alias at 0x%x for the chip at 0x%lx\n", map->name, base, start); return 0; } } } /* OK, if we got to here, then none of the previous chips appear to be aliases for the current one. */ set_bit((base >> cfi->chipshift), chip_map); /* Update chip map */ cfi->numchips++; ok_out: /* Put it back into Read Mode */ jedec_reset(base, map, cfi); printk(KERN_INFO "%s: Found %d x%d devices at 0x%x in %d-bit bank\n", map->name, cfi_interleave(cfi), cfi->device_type*8, base, map->bankwidth*8); return 1; } static struct chip_probe jedec_chip_probe = { .name = "JEDEC", .probe_chip = jedec_probe_chip }; static struct mtd_info *jedec_probe(struct map_info *map) { /* * Just use the generic probe stuff to call our CFI-specific * chip_probe routine in all the possible permutations, etc. */ return mtd_do_chip_probe(map, &jedec_chip_probe); } static struct mtd_chip_driver jedec_chipdrv = { .probe = jedec_probe, .name = "jedec_probe", .module = THIS_MODULE }; static int __init jedec_probe_init(void) { register_mtd_chip_driver(&jedec_chipdrv); return 0; } static void __exit jedec_probe_exit(void) { unregister_mtd_chip_driver(&jedec_chipdrv); } module_init(jedec_probe_init); module_exit(jedec_probe_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Erwin Authried <eauth@softsys.co.at> et al."); MODULE_DESCRIPTION("Probe code for JEDEC-compliant flash chips");
gpl-2.0
percy-g2/android_kernel_msm8625
drivers/mtd/tests/mtd_nandecctest.c
9240
1822
#include <linux/kernel.h> #include <linux/module.h> #include <linux/list.h> #include <linux/random.h> #include <linux/string.h> #include <linux/bitops.h> #include <linux/jiffies.h> #include <linux/mtd/nand_ecc.h> #if defined(CONFIG_MTD_NAND) || defined(CONFIG_MTD_NAND_MODULE) static void inject_single_bit_error(void *data, size_t size) { unsigned long offset = random32() % (size * BITS_PER_BYTE); __change_bit(offset, data); } static unsigned char data[512]; static unsigned char error_data[512]; static int nand_ecc_test(const size_t size) { unsigned char code[3]; unsigned char error_code[3]; char testname[30]; BUG_ON(sizeof(data) < size); sprintf(testname, "nand-ecc-%zu", size); get_random_bytes(data, size); memcpy(error_data, data, size); inject_single_bit_error(error_data, size); __nand_calculate_ecc(data, size, code); __nand_calculate_ecc(error_data, size, error_code); __nand_correct_data(error_data, code, error_code, size); if (!memcmp(data, error_data, size)) { printk(KERN_INFO "mtd_nandecctest: ok - %s\n", testname); return 0; } printk(KERN_ERR "mtd_nandecctest: not ok - %s\n", testname); printk(KERN_DEBUG "hexdump of data:\n"); print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 16, 4, data, size, false); printk(KERN_DEBUG "hexdump of error data:\n"); print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 16, 4, error_data, size, false); return -1; } #else static int nand_ecc_test(const size_t size) { return 0; } #endif static int __init ecc_test_init(void) { srandom32(jiffies); nand_ecc_test(256); nand_ecc_test(512); return 0; } static void __exit ecc_test_exit(void) { } module_init(ecc_test_init); module_exit(ecc_test_exit); MODULE_DESCRIPTION("NAND ECC function test module"); MODULE_AUTHOR("Akinobu Mita"); MODULE_LICENSE("GPL");
gpl-2.0
Albinoman887/Linux-3.4.x
arch/mips/wrppmc/time.c
11544
1084
/* * time.c: MIPS CPU Count/Compare timer hookup * * Author: Mark.Zhan, <rongkai.zhan@windriver.com> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 1996, 1997, 2004 by Ralf Baechle (ralf@linux-mips.org) * Copyright (C) 2006, Wind River System Inc. */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <asm/gt64120.h> #include <asm/time.h> #define WRPPMC_CPU_CLK_FREQ 40000000 /* 40MHZ */ /* * Estimate CPU frequency. Sets mips_hpt_frequency as a side-effect * * NOTE: We disable all GT64120 timers, and use MIPS processor internal * timer as the source of kernel clock tick. */ void __init plat_time_init(void) { /* Disable GT64120 timers */ GT_WRITE(GT_TC_CONTROL_OFS, 0x00); GT_WRITE(GT_TC0_OFS, 0x00); GT_WRITE(GT_TC1_OFS, 0x00); GT_WRITE(GT_TC2_OFS, 0x00); GT_WRITE(GT_TC3_OFS, 0x00); /* Use MIPS compare/count internal timer */ mips_hpt_frequency = WRPPMC_CPU_CLK_FREQ; }
gpl-2.0
zcop/android_kernel_htc_m7c
arch/parisc/kernel/asm-offsets.c
11800
16486
/* * Generate definitions needed by assembly language modules. * This code generates raw asm output which is post-processed to extract * and format the required data. * * Copyright (C) 2000-2001 John Marvin <jsm at parisc-linux.org> * Copyright (C) 2000 David Huggins-Daines <dhd with pobox.org> * Copyright (C) 2000 Sam Creasey <sammy@sammy.net> * Copyright (C) 2000 Grant Grundler <grundler with parisc-linux.org> * Copyright (C) 2001 Paul Bame <bame at parisc-linux.org> * Copyright (C) 2001 Richard Hirst <rhirst at parisc-linux.org> * Copyright (C) 2002 Randolph Chung <tausq with parisc-linux.org> * Copyright (C) 2003 James Bottomley <jejb at parisc-linux.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/types.h> #include <linux/sched.h> #include <linux/thread_info.h> #include <linux/ptrace.h> #include <linux/hardirq.h> #include <linux/kbuild.h> #include <asm/pgtable.h> #include <asm/ptrace.h> #include <asm/processor.h> #include <asm/pdc.h> #include <asm/uaccess.h> #ifdef CONFIG_64BIT #define FRAME_SIZE 128 #else #define FRAME_SIZE 64 #endif #define FRAME_ALIGN 64 /* Add FRAME_SIZE to the size x and align it to y. All definitions * that use align_frame will include space for a frame. */ #define align_frame(x,y) (((x)+FRAME_SIZE+(y)-1) - (((x)+(y)-1)%(y))) int main(void) { DEFINE(TASK_THREAD_INFO, offsetof(struct task_struct, stack)); DEFINE(TASK_STATE, offsetof(struct task_struct, state)); DEFINE(TASK_FLAGS, offsetof(struct task_struct, flags)); DEFINE(TASK_SIGPENDING, offsetof(struct task_struct, pending)); DEFINE(TASK_PTRACE, offsetof(struct task_struct, ptrace)); DEFINE(TASK_MM, offsetof(struct task_struct, mm)); DEFINE(TASK_PERSONALITY, offsetof(struct task_struct, personality)); DEFINE(TASK_PID, offsetof(struct task_struct, pid)); BLANK(); DEFINE(TASK_REGS, offsetof(struct task_struct, thread.regs)); DEFINE(TASK_PT_PSW, offsetof(struct task_struct, thread.regs.gr[ 0])); DEFINE(TASK_PT_GR1, offsetof(struct task_struct, thread.regs.gr[ 1])); DEFINE(TASK_PT_GR2, offsetof(struct task_struct, thread.regs.gr[ 2])); DEFINE(TASK_PT_GR3, offsetof(struct task_struct, thread.regs.gr[ 3])); DEFINE(TASK_PT_GR4, offsetof(struct task_struct, thread.regs.gr[ 4])); DEFINE(TASK_PT_GR5, offsetof(struct task_struct, thread.regs.gr[ 5])); DEFINE(TASK_PT_GR6, offsetof(struct task_struct, thread.regs.gr[ 6])); DEFINE(TASK_PT_GR7, offsetof(struct task_struct, thread.regs.gr[ 7])); DEFINE(TASK_PT_GR8, offsetof(struct task_struct, thread.regs.gr[ 8])); DEFINE(TASK_PT_GR9, offsetof(struct task_struct, thread.regs.gr[ 9])); DEFINE(TASK_PT_GR10, offsetof(struct task_struct, thread.regs.gr[10])); DEFINE(TASK_PT_GR11, offsetof(struct task_struct, thread.regs.gr[11])); DEFINE(TASK_PT_GR12, offsetof(struct task_struct, thread.regs.gr[12])); DEFINE(TASK_PT_GR13, offsetof(struct task_struct, thread.regs.gr[13])); DEFINE(TASK_PT_GR14, offsetof(struct task_struct, thread.regs.gr[14])); DEFINE(TASK_PT_GR15, offsetof(struct task_struct, thread.regs.gr[15])); DEFINE(TASK_PT_GR16, offsetof(struct task_struct, thread.regs.gr[16])); DEFINE(TASK_PT_GR17, offsetof(struct task_struct, thread.regs.gr[17])); DEFINE(TASK_PT_GR18, offsetof(struct task_struct, thread.regs.gr[18])); DEFINE(TASK_PT_GR19, offsetof(struct task_struct, thread.regs.gr[19])); DEFINE(TASK_PT_GR20, offsetof(struct task_struct, thread.regs.gr[20])); DEFINE(TASK_PT_GR21, offsetof(struct task_struct, thread.regs.gr[21])); DEFINE(TASK_PT_GR22, offsetof(struct task_struct, thread.regs.gr[22])); DEFINE(TASK_PT_GR23, offsetof(struct task_struct, thread.regs.gr[23])); DEFINE(TASK_PT_GR24, offsetof(struct task_struct, thread.regs.gr[24])); DEFINE(TASK_PT_GR25, offsetof(struct task_struct, thread.regs.gr[25])); DEFINE(TASK_PT_GR26, offsetof(struct task_struct, thread.regs.gr[26])); DEFINE(TASK_PT_GR27, offsetof(struct task_struct, thread.regs.gr[27])); DEFINE(TASK_PT_GR28, offsetof(struct task_struct, thread.regs.gr[28])); DEFINE(TASK_PT_GR29, offsetof(struct task_struct, thread.regs.gr[29])); DEFINE(TASK_PT_GR30, offsetof(struct task_struct, thread.regs.gr[30])); DEFINE(TASK_PT_GR31, offsetof(struct task_struct, thread.regs.gr[31])); DEFINE(TASK_PT_FR0, offsetof(struct task_struct, thread.regs.fr[ 0])); DEFINE(TASK_PT_FR1, offsetof(struct task_struct, thread.regs.fr[ 1])); DEFINE(TASK_PT_FR2, offsetof(struct task_struct, thread.regs.fr[ 2])); DEFINE(TASK_PT_FR3, offsetof(struct task_struct, thread.regs.fr[ 3])); DEFINE(TASK_PT_FR4, offsetof(struct task_struct, thread.regs.fr[ 4])); DEFINE(TASK_PT_FR5, offsetof(struct task_struct, thread.regs.fr[ 5])); DEFINE(TASK_PT_FR6, offsetof(struct task_struct, thread.regs.fr[ 6])); DEFINE(TASK_PT_FR7, offsetof(struct task_struct, thread.regs.fr[ 7])); DEFINE(TASK_PT_FR8, offsetof(struct task_struct, thread.regs.fr[ 8])); DEFINE(TASK_PT_FR9, offsetof(struct task_struct, thread.regs.fr[ 9])); DEFINE(TASK_PT_FR10, offsetof(struct task_struct, thread.regs.fr[10])); DEFINE(TASK_PT_FR11, offsetof(struct task_struct, thread.regs.fr[11])); DEFINE(TASK_PT_FR12, offsetof(struct task_struct, thread.regs.fr[12])); DEFINE(TASK_PT_FR13, offsetof(struct task_struct, thread.regs.fr[13])); DEFINE(TASK_PT_FR14, offsetof(struct task_struct, thread.regs.fr[14])); DEFINE(TASK_PT_FR15, offsetof(struct task_struct, thread.regs.fr[15])); DEFINE(TASK_PT_FR16, offsetof(struct task_struct, thread.regs.fr[16])); DEFINE(TASK_PT_FR17, offsetof(struct task_struct, thread.regs.fr[17])); DEFINE(TASK_PT_FR18, offsetof(struct task_struct, thread.regs.fr[18])); DEFINE(TASK_PT_FR19, offsetof(struct task_struct, thread.regs.fr[19])); DEFINE(TASK_PT_FR20, offsetof(struct task_struct, thread.regs.fr[20])); DEFINE(TASK_PT_FR21, offsetof(struct task_struct, thread.regs.fr[21])); DEFINE(TASK_PT_FR22, offsetof(struct task_struct, thread.regs.fr[22])); DEFINE(TASK_PT_FR23, offsetof(struct task_struct, thread.regs.fr[23])); DEFINE(TASK_PT_FR24, offsetof(struct task_struct, thread.regs.fr[24])); DEFINE(TASK_PT_FR25, offsetof(struct task_struct, thread.regs.fr[25])); DEFINE(TASK_PT_FR26, offsetof(struct task_struct, thread.regs.fr[26])); DEFINE(TASK_PT_FR27, offsetof(struct task_struct, thread.regs.fr[27])); DEFINE(TASK_PT_FR28, offsetof(struct task_struct, thread.regs.fr[28])); DEFINE(TASK_PT_FR29, offsetof(struct task_struct, thread.regs.fr[29])); DEFINE(TASK_PT_FR30, offsetof(struct task_struct, thread.regs.fr[30])); DEFINE(TASK_PT_FR31, offsetof(struct task_struct, thread.regs.fr[31])); DEFINE(TASK_PT_SR0, offsetof(struct task_struct, thread.regs.sr[ 0])); DEFINE(TASK_PT_SR1, offsetof(struct task_struct, thread.regs.sr[ 1])); DEFINE(TASK_PT_SR2, offsetof(struct task_struct, thread.regs.sr[ 2])); DEFINE(TASK_PT_SR3, offsetof(struct task_struct, thread.regs.sr[ 3])); DEFINE(TASK_PT_SR4, offsetof(struct task_struct, thread.regs.sr[ 4])); DEFINE(TASK_PT_SR5, offsetof(struct task_struct, thread.regs.sr[ 5])); DEFINE(TASK_PT_SR6, offsetof(struct task_struct, thread.regs.sr[ 6])); DEFINE(TASK_PT_SR7, offsetof(struct task_struct, thread.regs.sr[ 7])); DEFINE(TASK_PT_IASQ0, offsetof(struct task_struct, thread.regs.iasq[0])); DEFINE(TASK_PT_IASQ1, offsetof(struct task_struct, thread.regs.iasq[1])); DEFINE(TASK_PT_IAOQ0, offsetof(struct task_struct, thread.regs.iaoq[0])); DEFINE(TASK_PT_IAOQ1, offsetof(struct task_struct, thread.regs.iaoq[1])); DEFINE(TASK_PT_CR27, offsetof(struct task_struct, thread.regs.cr27)); DEFINE(TASK_PT_ORIG_R28, offsetof(struct task_struct, thread.regs.orig_r28)); DEFINE(TASK_PT_KSP, offsetof(struct task_struct, thread.regs.ksp)); DEFINE(TASK_PT_KPC, offsetof(struct task_struct, thread.regs.kpc)); DEFINE(TASK_PT_SAR, offsetof(struct task_struct, thread.regs.sar)); DEFINE(TASK_PT_IIR, offsetof(struct task_struct, thread.regs.iir)); DEFINE(TASK_PT_ISR, offsetof(struct task_struct, thread.regs.isr)); DEFINE(TASK_PT_IOR, offsetof(struct task_struct, thread.regs.ior)); BLANK(); DEFINE(TASK_SZ, sizeof(struct task_struct)); /* TASK_SZ_ALGN includes space for a stack frame. */ DEFINE(TASK_SZ_ALGN, align_frame(sizeof(struct task_struct), FRAME_ALIGN)); BLANK(); DEFINE(PT_PSW, offsetof(struct pt_regs, gr[ 0])); DEFINE(PT_GR1, offsetof(struct pt_regs, gr[ 1])); DEFINE(PT_GR2, offsetof(struct pt_regs, gr[ 2])); DEFINE(PT_GR3, offsetof(struct pt_regs, gr[ 3])); DEFINE(PT_GR4, offsetof(struct pt_regs, gr[ 4])); DEFINE(PT_GR5, offsetof(struct pt_regs, gr[ 5])); DEFINE(PT_GR6, offsetof(struct pt_regs, gr[ 6])); DEFINE(PT_GR7, offsetof(struct pt_regs, gr[ 7])); DEFINE(PT_GR8, offsetof(struct pt_regs, gr[ 8])); DEFINE(PT_GR9, offsetof(struct pt_regs, gr[ 9])); DEFINE(PT_GR10, offsetof(struct pt_regs, gr[10])); DEFINE(PT_GR11, offsetof(struct pt_regs, gr[11])); DEFINE(PT_GR12, offsetof(struct pt_regs, gr[12])); DEFINE(PT_GR13, offsetof(struct pt_regs, gr[13])); DEFINE(PT_GR14, offsetof(struct pt_regs, gr[14])); DEFINE(PT_GR15, offsetof(struct pt_regs, gr[15])); DEFINE(PT_GR16, offsetof(struct pt_regs, gr[16])); DEFINE(PT_GR17, offsetof(struct pt_regs, gr[17])); DEFINE(PT_GR18, offsetof(struct pt_regs, gr[18])); DEFINE(PT_GR19, offsetof(struct pt_regs, gr[19])); DEFINE(PT_GR20, offsetof(struct pt_regs, gr[20])); DEFINE(PT_GR21, offsetof(struct pt_regs, gr[21])); DEFINE(PT_GR22, offsetof(struct pt_regs, gr[22])); DEFINE(PT_GR23, offsetof(struct pt_regs, gr[23])); DEFINE(PT_GR24, offsetof(struct pt_regs, gr[24])); DEFINE(PT_GR25, offsetof(struct pt_regs, gr[25])); DEFINE(PT_GR26, offsetof(struct pt_regs, gr[26])); DEFINE(PT_GR27, offsetof(struct pt_regs, gr[27])); DEFINE(PT_GR28, offsetof(struct pt_regs, gr[28])); DEFINE(PT_GR29, offsetof(struct pt_regs, gr[29])); DEFINE(PT_GR30, offsetof(struct pt_regs, gr[30])); DEFINE(PT_GR31, offsetof(struct pt_regs, gr[31])); DEFINE(PT_FR0, offsetof(struct pt_regs, fr[ 0])); DEFINE(PT_FR1, offsetof(struct pt_regs, fr[ 1])); DEFINE(PT_FR2, offsetof(struct pt_regs, fr[ 2])); DEFINE(PT_FR3, offsetof(struct pt_regs, fr[ 3])); DEFINE(PT_FR4, offsetof(struct pt_regs, fr[ 4])); DEFINE(PT_FR5, offsetof(struct pt_regs, fr[ 5])); DEFINE(PT_FR6, offsetof(struct pt_regs, fr[ 6])); DEFINE(PT_FR7, offsetof(struct pt_regs, fr[ 7])); DEFINE(PT_FR8, offsetof(struct pt_regs, fr[ 8])); DEFINE(PT_FR9, offsetof(struct pt_regs, fr[ 9])); DEFINE(PT_FR10, offsetof(struct pt_regs, fr[10])); DEFINE(PT_FR11, offsetof(struct pt_regs, fr[11])); DEFINE(PT_FR12, offsetof(struct pt_regs, fr[12])); DEFINE(PT_FR13, offsetof(struct pt_regs, fr[13])); DEFINE(PT_FR14, offsetof(struct pt_regs, fr[14])); DEFINE(PT_FR15, offsetof(struct pt_regs, fr[15])); DEFINE(PT_FR16, offsetof(struct pt_regs, fr[16])); DEFINE(PT_FR17, offsetof(struct pt_regs, fr[17])); DEFINE(PT_FR18, offsetof(struct pt_regs, fr[18])); DEFINE(PT_FR19, offsetof(struct pt_regs, fr[19])); DEFINE(PT_FR20, offsetof(struct pt_regs, fr[20])); DEFINE(PT_FR21, offsetof(struct pt_regs, fr[21])); DEFINE(PT_FR22, offsetof(struct pt_regs, fr[22])); DEFINE(PT_FR23, offsetof(struct pt_regs, fr[23])); DEFINE(PT_FR24, offsetof(struct pt_regs, fr[24])); DEFINE(PT_FR25, offsetof(struct pt_regs, fr[25])); DEFINE(PT_FR26, offsetof(struct pt_regs, fr[26])); DEFINE(PT_FR27, offsetof(struct pt_regs, fr[27])); DEFINE(PT_FR28, offsetof(struct pt_regs, fr[28])); DEFINE(PT_FR29, offsetof(struct pt_regs, fr[29])); DEFINE(PT_FR30, offsetof(struct pt_regs, fr[30])); DEFINE(PT_FR31, offsetof(struct pt_regs, fr[31])); DEFINE(PT_SR0, offsetof(struct pt_regs, sr[ 0])); DEFINE(PT_SR1, offsetof(struct pt_regs, sr[ 1])); DEFINE(PT_SR2, offsetof(struct pt_regs, sr[ 2])); DEFINE(PT_SR3, offsetof(struct pt_regs, sr[ 3])); DEFINE(PT_SR4, offsetof(struct pt_regs, sr[ 4])); DEFINE(PT_SR5, offsetof(struct pt_regs, sr[ 5])); DEFINE(PT_SR6, offsetof(struct pt_regs, sr[ 6])); DEFINE(PT_SR7, offsetof(struct pt_regs, sr[ 7])); DEFINE(PT_IASQ0, offsetof(struct pt_regs, iasq[0])); DEFINE(PT_IASQ1, offsetof(struct pt_regs, iasq[1])); DEFINE(PT_IAOQ0, offsetof(struct pt_regs, iaoq[0])); DEFINE(PT_IAOQ1, offsetof(struct pt_regs, iaoq[1])); DEFINE(PT_CR27, offsetof(struct pt_regs, cr27)); DEFINE(PT_ORIG_R28, offsetof(struct pt_regs, orig_r28)); DEFINE(PT_KSP, offsetof(struct pt_regs, ksp)); DEFINE(PT_KPC, offsetof(struct pt_regs, kpc)); DEFINE(PT_SAR, offsetof(struct pt_regs, sar)); DEFINE(PT_IIR, offsetof(struct pt_regs, iir)); DEFINE(PT_ISR, offsetof(struct pt_regs, isr)); DEFINE(PT_IOR, offsetof(struct pt_regs, ior)); DEFINE(PT_SIZE, sizeof(struct pt_regs)); /* PT_SZ_ALGN includes space for a stack frame. */ DEFINE(PT_SZ_ALGN, align_frame(sizeof(struct pt_regs), FRAME_ALIGN)); BLANK(); DEFINE(TI_TASK, offsetof(struct thread_info, task)); DEFINE(TI_EXEC_DOMAIN, offsetof(struct thread_info, exec_domain)); DEFINE(TI_FLAGS, offsetof(struct thread_info, flags)); DEFINE(TI_CPU, offsetof(struct thread_info, cpu)); DEFINE(TI_SEGMENT, offsetof(struct thread_info, addr_limit)); DEFINE(TI_PRE_COUNT, offsetof(struct thread_info, preempt_count)); DEFINE(THREAD_SZ, sizeof(struct thread_info)); /* THREAD_SZ_ALGN includes space for a stack frame. */ DEFINE(THREAD_SZ_ALGN, align_frame(sizeof(struct thread_info), FRAME_ALIGN)); BLANK(); DEFINE(ICACHE_BASE, offsetof(struct pdc_cache_info, ic_base)); DEFINE(ICACHE_STRIDE, offsetof(struct pdc_cache_info, ic_stride)); DEFINE(ICACHE_COUNT, offsetof(struct pdc_cache_info, ic_count)); DEFINE(ICACHE_LOOP, offsetof(struct pdc_cache_info, ic_loop)); DEFINE(DCACHE_BASE, offsetof(struct pdc_cache_info, dc_base)); DEFINE(DCACHE_STRIDE, offsetof(struct pdc_cache_info, dc_stride)); DEFINE(DCACHE_COUNT, offsetof(struct pdc_cache_info, dc_count)); DEFINE(DCACHE_LOOP, offsetof(struct pdc_cache_info, dc_loop)); DEFINE(ITLB_SID_BASE, offsetof(struct pdc_cache_info, it_sp_base)); DEFINE(ITLB_SID_STRIDE, offsetof(struct pdc_cache_info, it_sp_stride)); DEFINE(ITLB_SID_COUNT, offsetof(struct pdc_cache_info, it_sp_count)); DEFINE(ITLB_OFF_BASE, offsetof(struct pdc_cache_info, it_off_base)); DEFINE(ITLB_OFF_STRIDE, offsetof(struct pdc_cache_info, it_off_stride)); DEFINE(ITLB_OFF_COUNT, offsetof(struct pdc_cache_info, it_off_count)); DEFINE(ITLB_LOOP, offsetof(struct pdc_cache_info, it_loop)); DEFINE(DTLB_SID_BASE, offsetof(struct pdc_cache_info, dt_sp_base)); DEFINE(DTLB_SID_STRIDE, offsetof(struct pdc_cache_info, dt_sp_stride)); DEFINE(DTLB_SID_COUNT, offsetof(struct pdc_cache_info, dt_sp_count)); DEFINE(DTLB_OFF_BASE, offsetof(struct pdc_cache_info, dt_off_base)); DEFINE(DTLB_OFF_STRIDE, offsetof(struct pdc_cache_info, dt_off_stride)); DEFINE(DTLB_OFF_COUNT, offsetof(struct pdc_cache_info, dt_off_count)); DEFINE(DTLB_LOOP, offsetof(struct pdc_cache_info, dt_loop)); BLANK(); DEFINE(TIF_BLOCKSTEP_PA_BIT, 31-TIF_BLOCKSTEP); DEFINE(TIF_SINGLESTEP_PA_BIT, 31-TIF_SINGLESTEP); BLANK(); DEFINE(ASM_PMD_SHIFT, PMD_SHIFT); DEFINE(ASM_PGDIR_SHIFT, PGDIR_SHIFT); DEFINE(ASM_BITS_PER_PGD, BITS_PER_PGD); DEFINE(ASM_BITS_PER_PMD, BITS_PER_PMD); DEFINE(ASM_BITS_PER_PTE, BITS_PER_PTE); DEFINE(ASM_PGD_PMD_OFFSET, -(PAGE_SIZE << PGD_ORDER)); DEFINE(ASM_PMD_ENTRY, ((PAGE_OFFSET & PMD_MASK) >> PMD_SHIFT)); DEFINE(ASM_PGD_ENTRY, PAGE_OFFSET >> PGDIR_SHIFT); DEFINE(ASM_PGD_ENTRY_SIZE, PGD_ENTRY_SIZE); DEFINE(ASM_PMD_ENTRY_SIZE, PMD_ENTRY_SIZE); DEFINE(ASM_PTE_ENTRY_SIZE, PTE_ENTRY_SIZE); DEFINE(ASM_PFN_PTE_SHIFT, PFN_PTE_SHIFT); DEFINE(ASM_PT_INITIAL, PT_INITIAL); BLANK(); DEFINE(EXCDATA_IP, offsetof(struct exception_data, fault_ip)); DEFINE(EXCDATA_SPACE, offsetof(struct exception_data, fault_space)); DEFINE(EXCDATA_ADDR, offsetof(struct exception_data, fault_addr)); BLANK(); DEFINE(ASM_PDC_RESULT_SIZE, NUM_PDC_RESULT * sizeof(unsigned long)); BLANK(); return 0; }
gpl-2.0
robacklin/uclinux-linux
fs/xfs/quota/xfs_dquot.c
25
43850
/* * Copyright (c) 2000-2003 Silicon Graphics, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU General Public License along * with this program; if not, write the Free Software Foundation, Inc., 59 * Temple Place - Suite 330, Boston MA 02111-1307, USA. * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/SGIGPLNoticeExplan/ */ #include "xfs.h" #include "xfs_fs.h" #include "xfs_inum.h" #include "xfs_log.h" #include "xfs_trans.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_dir.h" #include "xfs_dir2.h" #include "xfs_alloc.h" #include "xfs_dmapi.h" #include "xfs_quota.h" #include "xfs_mount.h" #include "xfs_alloc_btree.h" #include "xfs_bmap_btree.h" #include "xfs_ialloc_btree.h" #include "xfs_btree.h" #include "xfs_ialloc.h" #include "xfs_attr_sf.h" #include "xfs_dir_sf.h" #include "xfs_dir2_sf.h" #include "xfs_dinode.h" #include "xfs_inode.h" #include "xfs_bmap.h" #include "xfs_bit.h" #include "xfs_rtalloc.h" #include "xfs_error.h" #include "xfs_itable.h" #include "xfs_rw.h" #include "xfs_acl.h" #include "xfs_cap.h" #include "xfs_mac.h" #include "xfs_attr.h" #include "xfs_buf_item.h" #include "xfs_trans_space.h" #include "xfs_trans_priv.h" #include "xfs_qm.h" /* LOCK ORDER inode lock (ilock) dquot hash-chain lock (hashlock) xqm dquot freelist lock (freelistlock mount's dquot list lock (mplistlock) user dquot lock - lock ordering among dquots is based on the uid or gid group dquot lock - similar to udquots. Between the two dquots, the udquot has to be locked first. pin lock - the dquot lock must be held to take this lock. flush lock - ditto. */ STATIC void xfs_qm_dqflush_done(xfs_buf_t *, xfs_dq_logitem_t *); #ifdef DEBUG xfs_buftarg_t *xfs_dqerror_target; int xfs_do_dqerror; int xfs_dqreq_num; int xfs_dqerror_mod = 33; #endif /* * Allocate and initialize a dquot. We don't always allocate fresh memory; * we try to reclaim a free dquot if the number of incore dquots are above * a threshold. * The only field inside the core that gets initialized at this point * is the d_id field. The idea is to fill in the entire q_core * when we read in the on disk dquot. */ xfs_dquot_t * xfs_qm_dqinit( xfs_mount_t *mp, xfs_dqid_t id, uint type) { xfs_dquot_t *dqp; boolean_t brandnewdquot; brandnewdquot = xfs_qm_dqalloc_incore(&dqp); dqp->dq_flags = type; INT_SET(dqp->q_core.d_id, ARCH_CONVERT, id); dqp->q_mount = mp; /* * No need to re-initialize these if this is a reclaimed dquot. */ if (brandnewdquot) { dqp->dq_flnext = dqp->dq_flprev = dqp; mutex_init(&dqp->q_qlock, MUTEX_DEFAULT, "xdq"); initnsema(&dqp->q_flock, 1, "fdq"); sv_init(&dqp->q_pinwait, SV_DEFAULT, "pdq"); #ifdef XFS_DQUOT_TRACE dqp->q_trace = ktrace_alloc(DQUOT_TRACE_SIZE, KM_SLEEP); xfs_dqtrace_entry(dqp, "DQINIT"); #endif } else { /* * Only the q_core portion was zeroed in dqreclaim_one(). * So, we need to reset others. */ dqp->q_nrefs = 0; dqp->q_blkno = 0; dqp->MPL_NEXT = dqp->HL_NEXT = NULL; dqp->HL_PREVP = dqp->MPL_PREVP = NULL; dqp->q_bufoffset = 0; dqp->q_fileoffset = 0; dqp->q_transp = NULL; dqp->q_gdquot = NULL; dqp->q_res_bcount = 0; dqp->q_res_icount = 0; dqp->q_res_rtbcount = 0; dqp->q_pincount = 0; dqp->q_hash = NULL; ASSERT(dqp->dq_flnext == dqp->dq_flprev); #ifdef XFS_DQUOT_TRACE ASSERT(dqp->q_trace); xfs_dqtrace_entry(dqp, "DQRECLAIMED_INIT"); #endif } /* * log item gets initialized later */ return (dqp); } /* * This is called to free all the memory associated with a dquot */ void xfs_qm_dqdestroy( xfs_dquot_t *dqp) { ASSERT(! XFS_DQ_IS_ON_FREELIST(dqp)); mutex_destroy(&dqp->q_qlock); freesema(&dqp->q_flock); sv_destroy(&dqp->q_pinwait); #ifdef XFS_DQUOT_TRACE if (dqp->q_trace) ktrace_free(dqp->q_trace); dqp->q_trace = NULL; #endif kmem_zone_free(xfs_Gqm->qm_dqzone, dqp); atomic_dec(&xfs_Gqm->qm_totaldquots); } /* * This is what a 'fresh' dquot inside a dquot chunk looks like on disk. */ STATIC void xfs_qm_dqinit_core( xfs_dqid_t id, uint type, xfs_dqblk_t *d) { /* * Caller has zero'd the entire dquot 'chunk' already. */ INT_SET(d->dd_diskdq.d_magic, ARCH_CONVERT, XFS_DQUOT_MAGIC); INT_SET(d->dd_diskdq.d_version, ARCH_CONVERT, XFS_DQUOT_VERSION); INT_SET(d->dd_diskdq.d_id, ARCH_CONVERT, id); INT_SET(d->dd_diskdq.d_flags, ARCH_CONVERT, type); } #ifdef XFS_DQUOT_TRACE /* * Dquot tracing for debugging. */ /* ARGSUSED */ void __xfs_dqtrace_entry( xfs_dquot_t *dqp, char *func, void *retaddr, xfs_inode_t *ip) { xfs_dquot_t *udqp = NULL; xfs_ino_t ino = 0; ASSERT(dqp->q_trace); if (ip) { ino = ip->i_ino; udqp = ip->i_udquot; } ktrace_enter(dqp->q_trace, (void *)(__psint_t)DQUOT_KTRACE_ENTRY, (void *)func, (void *)(__psint_t)dqp->q_nrefs, (void *)(__psint_t)dqp->dq_flags, (void *)(__psint_t)dqp->q_res_bcount, (void *)(__psint_t)INT_GET(dqp->q_core.d_bcount, ARCH_CONVERT), (void *)(__psint_t)INT_GET(dqp->q_core.d_icount, ARCH_CONVERT), (void *)(__psint_t)INT_GET(dqp->q_core.d_blk_hardlimit, ARCH_CONVERT), (void *)(__psint_t)INT_GET(dqp->q_core.d_blk_softlimit, ARCH_CONVERT), (void *)(__psint_t)INT_GET(dqp->q_core.d_ino_hardlimit, ARCH_CONVERT), (void *)(__psint_t)INT_GET(dqp->q_core.d_ino_softlimit, ARCH_CONVERT), (void *)(__psint_t)INT_GET(dqp->q_core.d_id, ARCH_CONVERT), (void *)(__psint_t)current_pid(), (void *)(__psint_t)ino, (void *)(__psint_t)retaddr, (void *)(__psint_t)udqp); return; } #endif /* * If default limits are in force, push them into the dquot now. * We overwrite the dquot limits only if they are zero and this * is not the root dquot. */ void xfs_qm_adjust_dqlimits( xfs_mount_t *mp, xfs_disk_dquot_t *d) { xfs_quotainfo_t *q = mp->m_quotainfo; ASSERT(!INT_ISZERO(d->d_id, ARCH_CONVERT)); if (q->qi_bsoftlimit && INT_ISZERO(d->d_blk_softlimit, ARCH_CONVERT)) INT_SET(d->d_blk_softlimit, ARCH_CONVERT, q->qi_bsoftlimit); if (q->qi_bhardlimit && INT_ISZERO(d->d_blk_hardlimit, ARCH_CONVERT)) INT_SET(d->d_blk_hardlimit, ARCH_CONVERT, q->qi_bhardlimit); if (q->qi_isoftlimit && INT_ISZERO(d->d_ino_softlimit, ARCH_CONVERT)) INT_SET(d->d_ino_softlimit, ARCH_CONVERT, q->qi_isoftlimit); if (q->qi_ihardlimit && INT_ISZERO(d->d_ino_hardlimit, ARCH_CONVERT)) INT_SET(d->d_ino_hardlimit, ARCH_CONVERT, q->qi_ihardlimit); if (q->qi_rtbsoftlimit && INT_ISZERO(d->d_rtb_softlimit, ARCH_CONVERT)) INT_SET(d->d_rtb_softlimit, ARCH_CONVERT, q->qi_rtbsoftlimit); if (q->qi_rtbhardlimit && INT_ISZERO(d->d_rtb_hardlimit, ARCH_CONVERT)) INT_SET(d->d_rtb_hardlimit, ARCH_CONVERT, q->qi_rtbhardlimit); } /* * Check the limits and timers of a dquot and start or reset timers * if necessary. * This gets called even when quota enforcement is OFF, which makes our * life a little less complicated. (We just don't reject any quota * reservations in that case, when enforcement is off). * We also return 0 as the values of the timers in Q_GETQUOTA calls, when * enforcement's off. * In contrast, warnings are a little different in that they don't * 'automatically' get started when limits get exceeded. */ void xfs_qm_adjust_dqtimers( xfs_mount_t *mp, xfs_disk_dquot_t *d) { ASSERT(!INT_ISZERO(d->d_id, ARCH_CONVERT)); #ifdef QUOTADEBUG if (INT_GET(d->d_blk_hardlimit, ARCH_CONVERT)) ASSERT(INT_GET(d->d_blk_softlimit, ARCH_CONVERT) <= INT_GET(d->d_blk_hardlimit, ARCH_CONVERT)); if (INT_GET(d->d_ino_hardlimit, ARCH_CONVERT)) ASSERT(INT_GET(d->d_ino_softlimit, ARCH_CONVERT) <= INT_GET(d->d_ino_hardlimit, ARCH_CONVERT)); if (INT_GET(d->d_rtb_hardlimit, ARCH_CONVERT)) ASSERT(INT_GET(d->d_rtb_softlimit, ARCH_CONVERT) <= INT_GET(d->d_rtb_hardlimit, ARCH_CONVERT)); #endif if (INT_ISZERO(d->d_btimer, ARCH_CONVERT)) { if ((INT_GET(d->d_blk_softlimit, ARCH_CONVERT) && (INT_GET(d->d_bcount, ARCH_CONVERT) >= INT_GET(d->d_blk_softlimit, ARCH_CONVERT))) || (INT_GET(d->d_blk_hardlimit, ARCH_CONVERT) && (INT_GET(d->d_bcount, ARCH_CONVERT) >= INT_GET(d->d_blk_hardlimit, ARCH_CONVERT)))) { INT_SET(d->d_btimer, ARCH_CONVERT, get_seconds() + XFS_QI_BTIMELIMIT(mp)); } } else { if ((INT_ISZERO(d->d_blk_softlimit, ARCH_CONVERT) || (INT_GET(d->d_bcount, ARCH_CONVERT) < INT_GET(d->d_blk_softlimit, ARCH_CONVERT))) && (INT_ISZERO(d->d_blk_hardlimit, ARCH_CONVERT) || (INT_GET(d->d_bcount, ARCH_CONVERT) < INT_GET(d->d_blk_hardlimit, ARCH_CONVERT)))) { INT_ZERO(d->d_btimer, ARCH_CONVERT); } } if (INT_ISZERO(d->d_itimer, ARCH_CONVERT)) { if ((INT_GET(d->d_ino_softlimit, ARCH_CONVERT) && (INT_GET(d->d_icount, ARCH_CONVERT) >= INT_GET(d->d_ino_softlimit, ARCH_CONVERT))) || (INT_GET(d->d_ino_hardlimit, ARCH_CONVERT) && (INT_GET(d->d_icount, ARCH_CONVERT) >= INT_GET(d->d_ino_hardlimit, ARCH_CONVERT)))) { INT_SET(d->d_itimer, ARCH_CONVERT, get_seconds() + XFS_QI_ITIMELIMIT(mp)); } } else { if ((INT_ISZERO(d->d_ino_softlimit, ARCH_CONVERT) || (INT_GET(d->d_icount, ARCH_CONVERT) < INT_GET(d->d_ino_softlimit, ARCH_CONVERT))) && (INT_ISZERO(d->d_ino_hardlimit, ARCH_CONVERT) || (INT_GET(d->d_icount, ARCH_CONVERT) < INT_GET(d->d_ino_hardlimit, ARCH_CONVERT)))) { INT_ZERO(d->d_itimer, ARCH_CONVERT); } } if (INT_ISZERO(d->d_rtbtimer, ARCH_CONVERT)) { if ((INT_GET(d->d_rtb_softlimit, ARCH_CONVERT) && (INT_GET(d->d_rtbcount, ARCH_CONVERT) >= INT_GET(d->d_rtb_softlimit, ARCH_CONVERT))) || (INT_GET(d->d_rtb_hardlimit, ARCH_CONVERT) && (INT_GET(d->d_rtbcount, ARCH_CONVERT) >= INT_GET(d->d_rtb_hardlimit, ARCH_CONVERT)))) { INT_SET(d->d_rtbtimer, ARCH_CONVERT, get_seconds() + XFS_QI_RTBTIMELIMIT(mp)); } } else { if ((INT_ISZERO(d->d_rtb_softlimit, ARCH_CONVERT) || (INT_GET(d->d_rtbcount, ARCH_CONVERT) < INT_GET(d->d_rtb_softlimit, ARCH_CONVERT))) && (INT_ISZERO(d->d_rtb_hardlimit, ARCH_CONVERT) || (INT_GET(d->d_rtbcount, ARCH_CONVERT) < INT_GET(d->d_rtb_hardlimit, ARCH_CONVERT)))) { INT_ZERO(d->d_rtbtimer, ARCH_CONVERT); } } } /* * Increment or reset warnings of a given dquot. */ int xfs_qm_dqwarn( xfs_disk_dquot_t *d, uint flags) { int warned; /* * root's limits are not real limits. */ if (INT_ISZERO(d->d_id, ARCH_CONVERT)) return (0); warned = 0; if (INT_GET(d->d_blk_softlimit, ARCH_CONVERT) && (INT_GET(d->d_bcount, ARCH_CONVERT) >= INT_GET(d->d_blk_softlimit, ARCH_CONVERT))) { if (flags & XFS_QMOPT_DOWARN) { INT_MOD(d->d_bwarns, ARCH_CONVERT, +1); warned++; } } else { if (INT_ISZERO(d->d_blk_softlimit, ARCH_CONVERT) || (INT_GET(d->d_bcount, ARCH_CONVERT) < INT_GET(d->d_blk_softlimit, ARCH_CONVERT))) { INT_ZERO(d->d_bwarns, ARCH_CONVERT); } } if (INT_GET(d->d_ino_softlimit, ARCH_CONVERT) > 0 && (INT_GET(d->d_icount, ARCH_CONVERT) >= INT_GET(d->d_ino_softlimit, ARCH_CONVERT))) { if (flags & XFS_QMOPT_DOWARN) { INT_MOD(d->d_iwarns, ARCH_CONVERT, +1); warned++; } } else { if ((INT_ISZERO(d->d_ino_softlimit, ARCH_CONVERT)) || (INT_GET(d->d_icount, ARCH_CONVERT) < INT_GET(d->d_ino_softlimit, ARCH_CONVERT))) { INT_ZERO(d->d_iwarns, ARCH_CONVERT); } } #ifdef QUOTADEBUG if (INT_GET(d->d_iwarns, ARCH_CONVERT)) cmn_err(CE_DEBUG, "--------@@Inode warnings running : %Lu >= %Lu", INT_GET(d->d_icount, ARCH_CONVERT), INT_GET(d->d_ino_softlimit, ARCH_CONVERT)); if (INT_GET(d->d_bwarns, ARCH_CONVERT)) cmn_err(CE_DEBUG, "--------@@Blks warnings running : %Lu >= %Lu", INT_GET(d->d_bcount, ARCH_CONVERT), INT_GET(d->d_blk_softlimit, ARCH_CONVERT)); #endif return (warned); } /* * initialize a buffer full of dquots and log the whole thing */ STATIC void xfs_qm_init_dquot_blk( xfs_trans_t *tp, xfs_mount_t *mp, xfs_dqid_t id, uint type, xfs_buf_t *bp) { xfs_dqblk_t *d; int curid, i; ASSERT(tp); ASSERT(XFS_BUF_ISBUSY(bp)); ASSERT(XFS_BUF_VALUSEMA(bp) <= 0); d = (xfs_dqblk_t *)XFS_BUF_PTR(bp); /* * ID of the first dquot in the block - id's are zero based. */ curid = id - (id % XFS_QM_DQPERBLK(mp)); ASSERT(curid >= 0); memset(d, 0, BBTOB(XFS_QI_DQCHUNKLEN(mp))); for (i = 0; i < XFS_QM_DQPERBLK(mp); i++, d++, curid++) xfs_qm_dqinit_core(curid, type, d); xfs_trans_dquot_buf(tp, bp, type & XFS_DQ_USER ? XFS_BLI_UDQUOT_BUF : XFS_BLI_GDQUOT_BUF); xfs_trans_log_buf(tp, bp, 0, BBTOB(XFS_QI_DQCHUNKLEN(mp)) - 1); } /* * Allocate a block and fill it with dquots. * This is called when the bmapi finds a hole. */ STATIC int xfs_qm_dqalloc( xfs_trans_t *tp, xfs_mount_t *mp, xfs_dquot_t *dqp, xfs_inode_t *quotip, xfs_fileoff_t offset_fsb, xfs_buf_t **O_bpp) { xfs_fsblock_t firstblock; xfs_bmap_free_t flist; xfs_bmbt_irec_t map; int nmaps, error, committed; xfs_buf_t *bp; ASSERT(tp != NULL); xfs_dqtrace_entry(dqp, "DQALLOC"); /* * Initialize the bmap freelist prior to calling bmapi code. */ XFS_BMAP_INIT(&flist, &firstblock); xfs_ilock(quotip, XFS_ILOCK_EXCL); /* * Return if this type of quotas is turned off while we didn't * have an inode lock */ if (XFS_IS_THIS_QUOTA_OFF(dqp)) { xfs_iunlock(quotip, XFS_ILOCK_EXCL); return (ESRCH); } /* * xfs_trans_commit normally decrements the vnode ref count * when it unlocks the inode. Since we want to keep the quota * inode around, we bump the vnode ref count now. */ VN_HOLD(XFS_ITOV(quotip)); xfs_trans_ijoin(tp, quotip, XFS_ILOCK_EXCL); nmaps = 1; if ((error = xfs_bmapi(tp, quotip, offset_fsb, XFS_DQUOT_CLUSTER_SIZE_FSB, XFS_BMAPI_METADATA | XFS_BMAPI_WRITE, &firstblock, XFS_QM_DQALLOC_SPACE_RES(mp), &map, &nmaps, &flist))) { goto error0; } ASSERT(map.br_blockcount == XFS_DQUOT_CLUSTER_SIZE_FSB); ASSERT(nmaps == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); /* * Keep track of the blkno to save a lookup later */ dqp->q_blkno = XFS_FSB_TO_DADDR(mp, map.br_startblock); /* now we can just get the buffer (there's nothing to read yet) */ bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, dqp->q_blkno, XFS_QI_DQCHUNKLEN(mp), 0); if (!bp || (error = XFS_BUF_GETERROR(bp))) goto error1; /* * Make a chunk of dquots out of this buffer and log * the entire thing. */ xfs_qm_init_dquot_blk(tp, mp, INT_GET(dqp->q_core.d_id, ARCH_CONVERT), dqp->dq_flags & (XFS_DQ_USER|XFS_DQ_GROUP), bp); if ((error = xfs_bmap_finish(&tp, &flist, firstblock, &committed))) { goto error1; } *O_bpp = bp; return 0; error1: xfs_bmap_cancel(&flist); error0: xfs_iunlock(quotip, XFS_ILOCK_EXCL); return (error); } /* * Maps a dquot to the buffer containing its on-disk version. * This returns a ptr to the buffer containing the on-disk dquot * in the bpp param, and a ptr to the on-disk dquot within that buffer */ STATIC int xfs_qm_dqtobp( xfs_trans_t *tp, xfs_dquot_t *dqp, xfs_disk_dquot_t **O_ddpp, xfs_buf_t **O_bpp, uint flags) { xfs_bmbt_irec_t map; int nmaps, error; xfs_buf_t *bp; xfs_inode_t *quotip; xfs_mount_t *mp; xfs_disk_dquot_t *ddq; xfs_dqid_t id; boolean_t newdquot; mp = dqp->q_mount; id = INT_GET(dqp->q_core.d_id, ARCH_CONVERT); nmaps = 1; newdquot = B_FALSE; /* * If we don't know where the dquot lives, find out. */ if (dqp->q_blkno == (xfs_daddr_t) 0) { /* We use the id as an index */ dqp->q_fileoffset = (xfs_fileoff_t) ((uint)id / XFS_QM_DQPERBLK(mp)); nmaps = 1; quotip = XFS_DQ_TO_QIP(dqp); xfs_ilock(quotip, XFS_ILOCK_SHARED); /* * Return if this type of quotas is turned off while we didn't * have an inode lock */ if (XFS_IS_THIS_QUOTA_OFF(dqp)) { xfs_iunlock(quotip, XFS_ILOCK_SHARED); return (ESRCH); } /* * Find the block map; no allocations yet */ error = xfs_bmapi(NULL, quotip, dqp->q_fileoffset, XFS_DQUOT_CLUSTER_SIZE_FSB, XFS_BMAPI_METADATA, NULL, 0, &map, &nmaps, NULL); xfs_iunlock(quotip, XFS_ILOCK_SHARED); if (error) return (error); ASSERT(nmaps == 1); ASSERT(map.br_blockcount == 1); /* * offset of dquot in the (fixed sized) dquot chunk. */ dqp->q_bufoffset = (id % XFS_QM_DQPERBLK(mp)) * sizeof(xfs_dqblk_t); if (map.br_startblock == HOLESTARTBLOCK) { /* * We don't allocate unless we're asked to */ if (!(flags & XFS_QMOPT_DQALLOC)) return (ENOENT); ASSERT(tp); if ((error = xfs_qm_dqalloc(tp, mp, dqp, quotip, dqp->q_fileoffset, &bp))) return (error); newdquot = B_TRUE; } else { /* * store the blkno etc so that we don't have to do the * mapping all the time */ dqp->q_blkno = XFS_FSB_TO_DADDR(mp, map.br_startblock); } } ASSERT(dqp->q_blkno != DELAYSTARTBLOCK); ASSERT(dqp->q_blkno != HOLESTARTBLOCK); /* * Read in the buffer, unless we've just done the allocation * (in which case we already have the buf). */ if (! newdquot) { xfs_dqtrace_entry(dqp, "DQTOBP READBUF"); if ((error = xfs_trans_read_buf(mp, tp, mp->m_ddev_targp, dqp->q_blkno, XFS_QI_DQCHUNKLEN(mp), 0, &bp))) { return (error); } if (error || !bp) return XFS_ERROR(error); } ASSERT(XFS_BUF_ISBUSY(bp)); ASSERT(XFS_BUF_VALUSEMA(bp) <= 0); /* * calculate the location of the dquot inside the buffer. */ ddq = (xfs_disk_dquot_t *)((char *)XFS_BUF_PTR(bp) + dqp->q_bufoffset); /* * A simple sanity check in case we got a corrupted dquot... */ if (xfs_qm_dqcheck(ddq, id, dqp->dq_flags & (XFS_DQ_USER|XFS_DQ_GROUP), flags & (XFS_QMOPT_DQREPAIR|XFS_QMOPT_DOWARN), "dqtobp")) { if (!(flags & XFS_QMOPT_DQREPAIR)) { xfs_trans_brelse(tp, bp); return XFS_ERROR(EIO); } XFS_BUF_BUSY(bp); /* We dirtied this */ } *O_bpp = bp; *O_ddpp = ddq; return (0); } /* * Read in the ondisk dquot using dqtobp() then copy it to an incore version, * and release the buffer immediately. * */ /* ARGSUSED */ STATIC int xfs_qm_dqread( xfs_trans_t *tp, xfs_dqid_t id, xfs_dquot_t *dqp, /* dquot to get filled in */ uint flags) { xfs_disk_dquot_t *ddqp; xfs_buf_t *bp; int error; /* * get a pointer to the on-disk dquot and the buffer containing it * dqp already knows its own type (GROUP/USER). */ xfs_dqtrace_entry(dqp, "DQREAD"); if ((error = xfs_qm_dqtobp(tp, dqp, &ddqp, &bp, flags))) { return (error); } /* copy everything from disk dquot to the incore dquot */ memcpy(&dqp->q_core, ddqp, sizeof(xfs_disk_dquot_t)); ASSERT(INT_GET(dqp->q_core.d_id, ARCH_CONVERT) == id); xfs_qm_dquot_logitem_init(dqp); /* * Reservation counters are defined as reservation plus current usage * to avoid having to add everytime. */ dqp->q_res_bcount = INT_GET(ddqp->d_bcount, ARCH_CONVERT); dqp->q_res_icount = INT_GET(ddqp->d_icount, ARCH_CONVERT); dqp->q_res_rtbcount = INT_GET(ddqp->d_rtbcount, ARCH_CONVERT); /* Mark the buf so that this will stay incore a little longer */ XFS_BUF_SET_VTYPE_REF(bp, B_FS_DQUOT, XFS_DQUOT_REF); /* * We got the buffer with a xfs_trans_read_buf() (in dqtobp()) * So we need to release with xfs_trans_brelse(). * The strategy here is identical to that of inodes; we lock * the dquot in xfs_qm_dqget() before making it accessible to * others. This is because dquots, like inodes, need a good level of * concurrency, and we don't want to take locks on the entire buffers * for dquot accesses. * Note also that the dquot buffer may even be dirty at this point, if * this particular dquot was repaired. We still aren't afraid to * brelse it because we have the changes incore. */ ASSERT(XFS_BUF_ISBUSY(bp)); ASSERT(XFS_BUF_VALUSEMA(bp) <= 0); xfs_trans_brelse(tp, bp); return (error); } /* * allocate an incore dquot from the kernel heap, * and fill its core with quota information kept on disk. * If XFS_QMOPT_DQALLOC is set, it'll allocate a dquot on disk * if it wasn't already allocated. */ STATIC int xfs_qm_idtodq( xfs_mount_t *mp, xfs_dqid_t id, /* gid or uid, depending on type */ uint type, /* UDQUOT or GDQUOT */ uint flags, /* DQALLOC, DQREPAIR */ xfs_dquot_t **O_dqpp)/* OUT : incore dquot, not locked */ { xfs_dquot_t *dqp; int error; xfs_trans_t *tp; int cancelflags=0; dqp = xfs_qm_dqinit(mp, id, type); tp = NULL; if (flags & XFS_QMOPT_DQALLOC) { tp = xfs_trans_alloc(mp, XFS_TRANS_QM_DQALLOC); if ((error = xfs_trans_reserve(tp, XFS_QM_DQALLOC_SPACE_RES(mp), XFS_WRITE_LOG_RES(mp) + BBTOB(XFS_QI_DQCHUNKLEN(mp)) - 1 + 128, 0, XFS_TRANS_PERM_LOG_RES, XFS_WRITE_LOG_COUNT))) { cancelflags = 0; goto error0; } cancelflags = XFS_TRANS_RELEASE_LOG_RES; } /* * Read it from disk; xfs_dqread() takes care of * all the necessary initialization of dquot's fields (locks, etc) */ if ((error = xfs_qm_dqread(tp, id, dqp, flags))) { /* * This can happen if quotas got turned off (ESRCH), * or if the dquot didn't exist on disk and we ask to * allocate (ENOENT). */ xfs_dqtrace_entry(dqp, "DQREAD FAIL"); cancelflags |= XFS_TRANS_ABORT; goto error0; } if (tp) { if ((error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES, NULL))) goto error1; } *O_dqpp = dqp; return (0); error0: ASSERT(error); if (tp) xfs_trans_cancel(tp, cancelflags); error1: xfs_qm_dqdestroy(dqp); *O_dqpp = NULL; return (error); } /* * Lookup a dquot in the incore dquot hashtable. We keep two separate * hashtables for user and group dquots; and, these are global tables * inside the XQM, not per-filesystem tables. * The hash chain must be locked by caller, and it is left locked * on return. Returning dquot is locked. */ STATIC int xfs_qm_dqlookup( xfs_mount_t *mp, xfs_dqid_t id, xfs_dqhash_t *qh, xfs_dquot_t **O_dqpp) { xfs_dquot_t *dqp; uint flist_locked; xfs_dquot_t *d; ASSERT(XFS_DQ_IS_HASH_LOCKED(qh)); flist_locked = B_FALSE; /* * Traverse the hashchain looking for a match */ for (dqp = qh->qh_next; dqp != NULL; dqp = dqp->HL_NEXT) { /* * We already have the hashlock. We don't need the * dqlock to look at the id field of the dquot, since the * id can't be modified without the hashlock anyway. */ if (INT_GET(dqp->q_core.d_id, ARCH_CONVERT) == id && dqp->q_mount == mp) { xfs_dqtrace_entry(dqp, "DQFOUND BY LOOKUP"); /* * All in core dquots must be on the dqlist of mp */ ASSERT(dqp->MPL_PREVP != NULL); xfs_dqlock(dqp); if (dqp->q_nrefs == 0) { ASSERT (XFS_DQ_IS_ON_FREELIST(dqp)); if (! xfs_qm_freelist_lock_nowait(xfs_Gqm)) { xfs_dqtrace_entry(dqp, "DQLOOKUP: WANT"); /* * We may have raced with dqreclaim_one() * (and lost). So, flag that we don't * want the dquot to be reclaimed. */ dqp->dq_flags |= XFS_DQ_WANT; xfs_dqunlock(dqp); xfs_qm_freelist_lock(xfs_Gqm); xfs_dqlock(dqp); dqp->dq_flags &= ~(XFS_DQ_WANT); } flist_locked = B_TRUE; } /* * id couldn't have changed; we had the hashlock all * along */ ASSERT(INT_GET(dqp->q_core.d_id, ARCH_CONVERT) == id); if (flist_locked) { if (dqp->q_nrefs != 0) { xfs_qm_freelist_unlock(xfs_Gqm); flist_locked = B_FALSE; } else { /* * take it off the freelist */ xfs_dqtrace_entry(dqp, "DQLOOKUP: TAKEOFF FL"); XQM_FREELIST_REMOVE(dqp); /* xfs_qm_freelist_print(&(xfs_Gqm-> qm_dqfreelist), "after removal"); */ } } /* * grab a reference */ XFS_DQHOLD(dqp); if (flist_locked) xfs_qm_freelist_unlock(xfs_Gqm); /* * move the dquot to the front of the hashchain */ ASSERT(XFS_DQ_IS_HASH_LOCKED(qh)); if (dqp->HL_PREVP != &qh->qh_next) { xfs_dqtrace_entry(dqp, "DQLOOKUP: HASH MOVETOFRONT"); if ((d = dqp->HL_NEXT)) d->HL_PREVP = dqp->HL_PREVP; *(dqp->HL_PREVP) = d; d = qh->qh_next; d->HL_PREVP = &dqp->HL_NEXT; dqp->HL_NEXT = d; dqp->HL_PREVP = &qh->qh_next; qh->qh_next = dqp; } xfs_dqtrace_entry(dqp, "LOOKUP END"); *O_dqpp = dqp; ASSERT(XFS_DQ_IS_HASH_LOCKED(qh)); return (0); } } *O_dqpp = NULL; ASSERT(XFS_DQ_IS_HASH_LOCKED(qh)); return (1); } /* * Given the file system, inode OR id, and type (UDQUOT/GDQUOT), return a * a locked dquot, doing an allocation (if requested) as needed. * When both an inode and an id are given, the inode's id takes precedence. * That is, if the id changes while we don't hold the ilock inside this * function, the new dquot is returned, not necessarily the one requested * in the id argument. */ int xfs_qm_dqget( xfs_mount_t *mp, xfs_inode_t *ip, /* locked inode (optional) */ xfs_dqid_t id, /* gid or uid, depending on type */ uint type, /* UDQUOT or GDQUOT */ uint flags, /* DQALLOC, DQSUSER, DQREPAIR, DOWARN */ xfs_dquot_t **O_dqpp) /* OUT : locked incore dquot */ { xfs_dquot_t *dqp; xfs_dqhash_t *h; uint version; int error; ASSERT(XFS_IS_QUOTA_RUNNING(mp)); if ((! XFS_IS_UQUOTA_ON(mp) && type == XFS_DQ_USER) || (! XFS_IS_GQUOTA_ON(mp) && type == XFS_DQ_GROUP)) { return (ESRCH); } h = XFS_DQ_HASH(mp, id, type); #ifdef DEBUG if (xfs_do_dqerror) { if ((xfs_dqerror_target == mp->m_ddev_targp) && (xfs_dqreq_num++ % xfs_dqerror_mod) == 0) { cmn_err(CE_DEBUG, "Returning error in dqget"); return (EIO); } } #endif again: #ifdef DEBUG ASSERT(type == XFS_DQ_USER || type == XFS_DQ_GROUP); if (ip) { ASSERT(XFS_ISLOCKED_INODE_EXCL(ip)); if (type == XFS_DQ_USER) ASSERT(ip->i_udquot == NULL); else ASSERT(ip->i_gdquot == NULL); } #endif XFS_DQ_HASH_LOCK(h); /* * Look in the cache (hashtable). * The chain is kept locked during lookup. */ if (xfs_qm_dqlookup(mp, id, h, O_dqpp) == 0) { XQM_STATS_INC(xqmstats.xs_qm_dqcachehits); /* * The dquot was found, moved to the front of the chain, * taken off the freelist if it was on it, and locked * at this point. Just unlock the hashchain and return. */ ASSERT(*O_dqpp); ASSERT(XFS_DQ_IS_LOCKED(*O_dqpp)); XFS_DQ_HASH_UNLOCK(h); xfs_dqtrace_entry(*O_dqpp, "DQGET DONE (FROM CACHE)"); return (0); /* success */ } XQM_STATS_INC(xqmstats.xs_qm_dqcachemisses); /* * Dquot cache miss. We don't want to keep the inode lock across * a (potential) disk read. Also we don't want to deal with the lock * ordering between quotainode and this inode. OTOH, dropping the inode * lock here means dealing with a chown that can happen before * we re-acquire the lock. */ if (ip) xfs_iunlock(ip, XFS_ILOCK_EXCL); /* * Save the hashchain version stamp, and unlock the chain, so that * we don't keep the lock across a disk read */ version = h->qh_version; XFS_DQ_HASH_UNLOCK(h); /* * Allocate the dquot on the kernel heap, and read the ondisk * portion off the disk. Also, do all the necessary initialization * This can return ENOENT if dquot didn't exist on disk and we didn't * ask it to allocate; ESRCH if quotas got turned off suddenly. */ if ((error = xfs_qm_idtodq(mp, id, type, flags & (XFS_QMOPT_DQALLOC|XFS_QMOPT_DQREPAIR| XFS_QMOPT_DOWARN), &dqp))) { if (ip) xfs_ilock(ip, XFS_ILOCK_EXCL); return (error); } /* * See if this is mount code calling to look at the overall quota limits * which are stored in the id == 0 user or group's dquot. * Since we may not have done a quotacheck by this point, just return * the dquot without attaching it to any hashtables, lists, etc, or even * taking a reference. * The caller must dqdestroy this once done. */ if (flags & XFS_QMOPT_DQSUSER) { ASSERT(id == 0); ASSERT(! ip); goto dqret; } /* * Dquot lock comes after hashlock in the lock ordering */ if (ip) { xfs_ilock(ip, XFS_ILOCK_EXCL); if (! XFS_IS_DQTYPE_ON(mp, type)) { /* inode stays locked on return */ xfs_qm_dqdestroy(dqp); return XFS_ERROR(ESRCH); } /* * A dquot could be attached to this inode by now, since * we had dropped the ilock. */ if (type == XFS_DQ_USER) { if (ip->i_udquot) { xfs_qm_dqdestroy(dqp); dqp = ip->i_udquot; xfs_dqlock(dqp); goto dqret; } } else { if (ip->i_gdquot) { xfs_qm_dqdestroy(dqp); dqp = ip->i_gdquot; xfs_dqlock(dqp); goto dqret; } } } /* * Hashlock comes after ilock in lock order */ XFS_DQ_HASH_LOCK(h); if (version != h->qh_version) { xfs_dquot_t *tmpdqp; /* * Now, see if somebody else put the dquot in the * hashtable before us. This can happen because we didn't * keep the hashchain lock. We don't have to worry about * lock order between the two dquots here since dqp isn't * on any findable lists yet. */ if (xfs_qm_dqlookup(mp, id, h, &tmpdqp) == 0) { /* * Duplicate found. Just throw away the new dquot * and start over. */ xfs_qm_dqput(tmpdqp); XFS_DQ_HASH_UNLOCK(h); xfs_qm_dqdestroy(dqp); XQM_STATS_INC(xqmstats.xs_qm_dquot_dups); goto again; } } /* * Put the dquot at the beginning of the hash-chain and mp's list * LOCK ORDER: hashlock, freelistlock, mplistlock, udqlock, gdqlock .. */ ASSERT(XFS_DQ_IS_HASH_LOCKED(h)); dqp->q_hash = h; XQM_HASHLIST_INSERT(h, dqp); /* * Attach this dquot to this filesystem's list of all dquots, * kept inside the mount structure in m_quotainfo field */ xfs_qm_mplist_lock(mp); /* * We return a locked dquot to the caller, with a reference taken */ xfs_dqlock(dqp); dqp->q_nrefs = 1; XQM_MPLIST_INSERT(&(XFS_QI_MPL_LIST(mp)), dqp); xfs_qm_mplist_unlock(mp); XFS_DQ_HASH_UNLOCK(h); dqret: ASSERT((ip == NULL) || XFS_ISLOCKED_INODE_EXCL(ip)); xfs_dqtrace_entry(dqp, "DQGET DONE"); *O_dqpp = dqp; return (0); } /* * Release a reference to the dquot (decrement ref-count) * and unlock it. If there is a group quota attached to this * dquot, carefully release that too without tripping over * deadlocks'n'stuff. */ void xfs_qm_dqput( xfs_dquot_t *dqp) { xfs_dquot_t *gdqp; ASSERT(dqp->q_nrefs > 0); ASSERT(XFS_DQ_IS_LOCKED(dqp)); xfs_dqtrace_entry(dqp, "DQPUT"); if (dqp->q_nrefs != 1) { dqp->q_nrefs--; xfs_dqunlock(dqp); return; } /* * drop the dqlock and acquire the freelist and dqlock * in the right order; but try to get it out-of-order first */ if (! xfs_qm_freelist_lock_nowait(xfs_Gqm)) { xfs_dqtrace_entry(dqp, "DQPUT: FLLOCK-WAIT"); xfs_dqunlock(dqp); xfs_qm_freelist_lock(xfs_Gqm); xfs_dqlock(dqp); } while (1) { gdqp = NULL; /* We can't depend on nrefs being == 1 here */ if (--dqp->q_nrefs == 0) { xfs_dqtrace_entry(dqp, "DQPUT: ON FREELIST"); /* * insert at end of the freelist. */ XQM_FREELIST_INSERT(&(xfs_Gqm->qm_dqfreelist), dqp); /* * If we just added a udquot to the freelist, then * we want to release the gdquot reference that * it (probably) has. Otherwise it'll keep the * gdquot from getting reclaimed. */ if ((gdqp = dqp->q_gdquot)) { /* * Avoid a recursive dqput call */ xfs_dqlock(gdqp); dqp->q_gdquot = NULL; } /* xfs_qm_freelist_print(&(xfs_Gqm->qm_dqfreelist), "@@@@@++ Free list (after append) @@@@@+"); */ } xfs_dqunlock(dqp); /* * If we had a group quota inside the user quota as a hint, * release it now. */ if (! gdqp) break; dqp = gdqp; } xfs_qm_freelist_unlock(xfs_Gqm); } /* * Release a dquot. Flush it if dirty, then dqput() it. * dquot must not be locked. */ void xfs_qm_dqrele( xfs_dquot_t *dqp) { ASSERT(dqp); xfs_dqtrace_entry(dqp, "DQRELE"); xfs_dqlock(dqp); /* * We don't care to flush it if the dquot is dirty here. * That will create stutters that we want to avoid. * Instead we do a delayed write when we try to reclaim * a dirty dquot. Also xfs_sync will take part of the burden... */ xfs_qm_dqput(dqp); } /* * Write a modified dquot to disk. * The dquot must be locked and the flush lock too taken by caller. * The flush lock will not be unlocked until the dquot reaches the disk, * but the dquot is free to be unlocked and modified by the caller * in the interim. Dquot is still locked on return. This behavior is * identical to that of inodes. */ int xfs_qm_dqflush( xfs_dquot_t *dqp, uint flags) { xfs_mount_t *mp; xfs_buf_t *bp; xfs_disk_dquot_t *ddqp; int error; SPLDECL(s); ASSERT(XFS_DQ_IS_LOCKED(dqp)); ASSERT(XFS_DQ_IS_FLUSH_LOCKED(dqp)); xfs_dqtrace_entry(dqp, "DQFLUSH"); /* * If not dirty, nada. */ if (!XFS_DQ_IS_DIRTY(dqp)) { xfs_dqfunlock(dqp); return (0); } /* * Cant flush a pinned dquot. Wait for it. */ xfs_qm_dqunpin_wait(dqp); /* * This may have been unpinned because the filesystem is shutting * down forcibly. If that's the case we must not write this dquot * to disk, because the log record didn't make it to disk! */ if (XFS_FORCED_SHUTDOWN(dqp->q_mount)) { dqp->dq_flags &= ~(XFS_DQ_DIRTY); xfs_dqfunlock(dqp); return XFS_ERROR(EIO); } /* * Get the buffer containing the on-disk dquot * We don't need a transaction envelope because we know that the * the ondisk-dquot has already been allocated for. */ if ((error = xfs_qm_dqtobp(NULL, dqp, &ddqp, &bp, XFS_QMOPT_DOWARN))) { xfs_dqtrace_entry(dqp, "DQTOBP FAIL"); ASSERT(error != ENOENT); /* * Quotas could have gotten turned off (ESRCH) */ xfs_dqfunlock(dqp); return (error); } if (xfs_qm_dqcheck(&dqp->q_core, INT_GET(ddqp->d_id, ARCH_CONVERT), 0, XFS_QMOPT_DOWARN, "dqflush (incore copy)")) { xfs_force_shutdown(dqp->q_mount, XFS_CORRUPT_INCORE); return XFS_ERROR(EIO); } /* This is the only portion of data that needs to persist */ memcpy(ddqp, &(dqp->q_core), sizeof(xfs_disk_dquot_t)); /* * Clear the dirty field and remember the flush lsn for later use. */ dqp->dq_flags &= ~(XFS_DQ_DIRTY); mp = dqp->q_mount; /* lsn is 64 bits */ AIL_LOCK(mp, s); dqp->q_logitem.qli_flush_lsn = dqp->q_logitem.qli_item.li_lsn; AIL_UNLOCK(mp, s); /* * Attach an iodone routine so that we can remove this dquot from the * AIL and release the flush lock once the dquot is synced to disk. */ xfs_buf_attach_iodone(bp, (void(*)(xfs_buf_t *, xfs_log_item_t *)) xfs_qm_dqflush_done, &(dqp->q_logitem.qli_item)); /* * If the buffer is pinned then push on the log so we won't * get stuck waiting in the write for too long. */ if (XFS_BUF_ISPINNED(bp)) { xfs_dqtrace_entry(dqp, "DQFLUSH LOG FORCE"); xfs_log_force(mp, (xfs_lsn_t)0, XFS_LOG_FORCE); } if (flags & XFS_QMOPT_DELWRI) { xfs_bdwrite(mp, bp); } else if (flags & XFS_QMOPT_ASYNC) { xfs_bawrite(mp, bp); } else { error = xfs_bwrite(mp, bp); } xfs_dqtrace_entry(dqp, "DQFLUSH END"); /* * dqp is still locked, but caller is free to unlock it now. */ return (error); } /* * This is the dquot flushing I/O completion routine. It is called * from interrupt level when the buffer containing the dquot is * flushed to disk. It is responsible for removing the dquot logitem * from the AIL if it has not been re-logged, and unlocking the dquot's * flush lock. This behavior is very similar to that of inodes.. */ /*ARGSUSED*/ STATIC void xfs_qm_dqflush_done( xfs_buf_t *bp, xfs_dq_logitem_t *qip) { xfs_dquot_t *dqp; SPLDECL(s); dqp = qip->qli_dquot; /* * We only want to pull the item from the AIL if its * location in the log has not changed since we started the flush. * Thus, we only bother if the dquot's lsn has * not changed. First we check the lsn outside the lock * since it's cheaper, and then we recheck while * holding the lock before removing the dquot from the AIL. */ if ((qip->qli_item.li_flags & XFS_LI_IN_AIL) && qip->qli_item.li_lsn == qip->qli_flush_lsn) { AIL_LOCK(dqp->q_mount, s); /* * xfs_trans_delete_ail() drops the AIL lock. */ if (qip->qli_item.li_lsn == qip->qli_flush_lsn) xfs_trans_delete_ail(dqp->q_mount, (xfs_log_item_t*)qip, s); else AIL_UNLOCK(dqp->q_mount, s); } /* * Release the dq's flush lock since we're done with it. */ xfs_dqfunlock(dqp); } int xfs_qm_dqflock_nowait( xfs_dquot_t *dqp) { int locked; locked = cpsema(&((dqp)->q_flock)); /* XXX ifdef these out */ if (locked) (dqp)->dq_flags |= XFS_DQ_FLOCKED; return (locked); } int xfs_qm_dqlock_nowait( xfs_dquot_t *dqp) { return (mutex_trylock(&((dqp)->q_qlock))); } void xfs_dqlock( xfs_dquot_t *dqp) { mutex_lock(&(dqp->q_qlock), PINOD); } void xfs_dqunlock( xfs_dquot_t *dqp) { mutex_unlock(&(dqp->q_qlock)); if (dqp->q_logitem.qli_dquot == dqp) { /* Once was dqp->q_mount, but might just have been cleared */ xfs_trans_unlocked_item(dqp->q_logitem.qli_item.li_mountp, (xfs_log_item_t*)&(dqp->q_logitem)); } } void xfs_dqunlock_nonotify( xfs_dquot_t *dqp) { mutex_unlock(&(dqp->q_qlock)); } void xfs_dqlock2( xfs_dquot_t *d1, xfs_dquot_t *d2) { if (d1 && d2) { ASSERT(d1 != d2); if (INT_GET(d1->q_core.d_id, ARCH_CONVERT) > INT_GET(d2->q_core.d_id, ARCH_CONVERT)) { xfs_dqlock(d2); xfs_dqlock(d1); } else { xfs_dqlock(d1); xfs_dqlock(d2); } } else { if (d1) { xfs_dqlock(d1); } else if (d2) { xfs_dqlock(d2); } } } /* * Take a dquot out of the mount's dqlist as well as the hashlist. * This is called via unmount as well as quotaoff, and the purge * will always succeed unless there are soft (temp) references * outstanding. * * This returns 0 if it was purged, 1 if it wasn't. It's not an error code * that we're returning! XXXsup - not cool. */ /* ARGSUSED */ int xfs_qm_dqpurge( xfs_dquot_t *dqp, uint flags) { xfs_dqhash_t *thishash; xfs_mount_t *mp; mp = dqp->q_mount; ASSERT(XFS_QM_IS_MPLIST_LOCKED(mp)); ASSERT(XFS_DQ_IS_HASH_LOCKED(dqp->q_hash)); xfs_dqlock(dqp); /* * We really can't afford to purge a dquot that is * referenced, because these are hard refs. * It shouldn't happen in general because we went thru _all_ inodes in * dqrele_all_inodes before calling this and didn't let the mountlock go. * However it is possible that we have dquots with temporary * references that are not attached to an inode. e.g. see xfs_setattr(). */ if (dqp->q_nrefs != 0) { xfs_dqunlock(dqp); XFS_DQ_HASH_UNLOCK(dqp->q_hash); return (1); } ASSERT(XFS_DQ_IS_ON_FREELIST(dqp)); /* * If we're turning off quotas, we have to make sure that, for * example, we don't delete quota disk blocks while dquots are * in the process of getting written to those disk blocks. * This dquot might well be on AIL, and we can't leave it there * if we're turning off quotas. Basically, we need this flush * lock, and are willing to block on it. */ if (! xfs_qm_dqflock_nowait(dqp)) { /* * Block on the flush lock after nudging dquot buffer, * if it is incore. */ xfs_qm_dqflock_pushbuf_wait(dqp); } /* * XXXIf we're turning this type of quotas off, we don't care * about the dirty metadata sitting in this dquot. OTOH, if * we're unmounting, we do care, so we flush it and wait. */ if (XFS_DQ_IS_DIRTY(dqp)) { xfs_dqtrace_entry(dqp, "DQPURGE ->DQFLUSH: DQDIRTY"); /* dqflush unlocks dqflock */ /* * Given that dqpurge is a very rare occurrence, it is OK * that we're holding the hashlist and mplist locks * across the disk write. But, ... XXXsup * * We don't care about getting disk errors here. We need * to purge this dquot anyway, so we go ahead regardless. */ (void) xfs_qm_dqflush(dqp, XFS_QMOPT_SYNC); xfs_dqflock(dqp); } ASSERT(dqp->q_pincount == 0); ASSERT(XFS_FORCED_SHUTDOWN(mp) || !(dqp->q_logitem.qli_item.li_flags & XFS_LI_IN_AIL)); thishash = dqp->q_hash; XQM_HASHLIST_REMOVE(thishash, dqp); XQM_MPLIST_REMOVE(&(XFS_QI_MPL_LIST(mp)), dqp); /* * XXX Move this to the front of the freelist, if we can get the * freelist lock. */ ASSERT(XFS_DQ_IS_ON_FREELIST(dqp)); dqp->q_mount = NULL; dqp->q_hash = NULL; dqp->dq_flags = XFS_DQ_INACTIVE; memset(&dqp->q_core, 0, sizeof(dqp->q_core)); xfs_dqfunlock(dqp); xfs_dqunlock(dqp); XFS_DQ_HASH_UNLOCK(thishash); return (0); } #ifdef QUOTADEBUG void xfs_qm_dqprint(xfs_dquot_t *dqp) { cmn_err(CE_DEBUG, "-----------KERNEL DQUOT----------------"); cmn_err(CE_DEBUG, "---- dquotID = %d", (int)INT_GET(dqp->q_core.d_id, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- type = %s", XFS_QM_ISUDQ(dqp) ? "USR" : "GRP"); cmn_err(CE_DEBUG, "---- fs = 0x%p", dqp->q_mount); cmn_err(CE_DEBUG, "---- blkno = 0x%x", (int) dqp->q_blkno); cmn_err(CE_DEBUG, "---- boffset = 0x%x", (int) dqp->q_bufoffset); cmn_err(CE_DEBUG, "---- blkhlimit = %Lu (0x%x)", INT_GET(dqp->q_core.d_blk_hardlimit, ARCH_CONVERT), (int) INT_GET(dqp->q_core.d_blk_hardlimit, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- blkslimit = %Lu (0x%x)", INT_GET(dqp->q_core.d_blk_softlimit, ARCH_CONVERT), (int)INT_GET(dqp->q_core.d_blk_softlimit, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- inohlimit = %Lu (0x%x)", INT_GET(dqp->q_core.d_ino_hardlimit, ARCH_CONVERT), (int)INT_GET(dqp->q_core.d_ino_hardlimit, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- inoslimit = %Lu (0x%x)", INT_GET(dqp->q_core.d_ino_softlimit, ARCH_CONVERT), (int)INT_GET(dqp->q_core.d_ino_softlimit, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- bcount = %Lu (0x%x)", INT_GET(dqp->q_core.d_bcount, ARCH_CONVERT), (int)INT_GET(dqp->q_core.d_bcount, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- icount = %Lu (0x%x)", INT_GET(dqp->q_core.d_icount, ARCH_CONVERT), (int)INT_GET(dqp->q_core.d_icount, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- btimer = %d", (int)INT_GET(dqp->q_core.d_btimer, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---- itimer = %d", (int)INT_GET(dqp->q_core.d_itimer, ARCH_CONVERT)); cmn_err(CE_DEBUG, "---------------------------"); } #endif /* * Give the buffer a little push if it is incore and * wait on the flush lock. */ void xfs_qm_dqflock_pushbuf_wait( xfs_dquot_t *dqp) { xfs_buf_t *bp; /* * Check to see if the dquot has been flushed delayed * write. If so, grab its buffer and send it * out immediately. We'll be able to acquire * the flush lock when the I/O completes. */ bp = xfs_incore(dqp->q_mount->m_ddev_targp, dqp->q_blkno, XFS_QI_DQCHUNKLEN(dqp->q_mount), XFS_INCORE_TRYLOCK); if (bp != NULL) { if (XFS_BUF_ISDELAYWRITE(bp)) { if (XFS_BUF_ISPINNED(bp)) { xfs_log_force(dqp->q_mount, (xfs_lsn_t)0, XFS_LOG_FORCE); } xfs_bawrite(dqp->q_mount, bp); } else { xfs_buf_relse(bp); } } xfs_dqflock(dqp); }
gpl-2.0
BreakawayConsulting/gcc
libgfortran/generated/minloc0_8_i8.c
25
9123
/* Implementation of the MINLOC intrinsic Copyright 2002, 2007, 2009 Free Software Foundation, Inc. Contributed by Paul Brook <paul@nowt.org> This file is part of the GNU Fortran 95 runtime library (libgfortran). Libgfortran is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Libgfortran is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ #include "libgfortran.h" #include <stdlib.h> #include <assert.h> #include <limits.h> #if defined (HAVE_GFC_INTEGER_8) && defined (HAVE_GFC_INTEGER_8) extern void minloc0_8_i8 (gfc_array_i8 * const restrict retarray, gfc_array_i8 * const restrict array); export_proto(minloc0_8_i8); void minloc0_8_i8 (gfc_array_i8 * const restrict retarray, gfc_array_i8 * const restrict array) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type sstride[GFC_MAX_DIMENSIONS]; index_type dstride; const GFC_INTEGER_8 *base; GFC_INTEGER_8 * restrict dest; index_type rank; index_type n; rank = GFC_DESCRIPTOR_RANK (array); if (rank <= 0) runtime_error ("Rank of array needs to be > 0"); if (retarray->data == NULL) { GFC_DIMENSION_SET(retarray->dim[0], 0, rank-1, 1); retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1; retarray->offset = 0; retarray->data = internal_malloc_size (sizeof (GFC_INTEGER_8) * rank); } else { if (unlikely (compile_options.bounds_check)) bounds_iforeach_return ((array_t *) retarray, (array_t *) array, "MINLOC"); } dstride = GFC_DESCRIPTOR_STRIDE(retarray,0); dest = retarray->data; for (n = 0; n < rank; n++) { sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n); extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); count[n] = 0; if (extent[n] <= 0) { /* Set the return value. */ for (n = 0; n < rank; n++) dest[n * dstride] = 0; return; } } base = array->data; /* Initialize the return value. */ for (n = 0; n < rank; n++) dest[n * dstride] = 1; { GFC_INTEGER_8 minval; #if defined(GFC_INTEGER_8_QUIET_NAN) int fast = 0; #endif #if defined(GFC_INTEGER_8_INFINITY) minval = GFC_INTEGER_8_INFINITY; #else minval = GFC_INTEGER_8_HUGE; #endif while (base) { do { /* Implementation start. */ #if defined(GFC_INTEGER_8_QUIET_NAN) } while (0); if (unlikely (!fast)) { do { if (*base <= minval) { fast = 1; minval = *base; for (n = 0; n < rank; n++) dest[n * dstride] = count[n] + 1; break; } base += sstride[0]; } while (++count[0] != extent[0]); if (likely (fast)) continue; } else do { #endif if (*base < minval) { minval = *base; for (n = 0; n < rank; n++) dest[n * dstride] = count[n] + 1; } /* Implementation end. */ /* Advance to the next element. */ base += sstride[0]; } while (++count[0] != extent[0]); n = 0; do { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ base -= sstride[n] * extent[n]; n++; if (n == rank) { /* Break out of the loop. */ base = NULL; break; } else { count[n]++; base += sstride[n]; } } while (count[n] == extent[n]); } } } extern void mminloc0_8_i8 (gfc_array_i8 * const restrict, gfc_array_i8 * const restrict, gfc_array_l1 * const restrict); export_proto(mminloc0_8_i8); void mminloc0_8_i8 (gfc_array_i8 * const restrict retarray, gfc_array_i8 * const restrict array, gfc_array_l1 * const restrict mask) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type sstride[GFC_MAX_DIMENSIONS]; index_type mstride[GFC_MAX_DIMENSIONS]; index_type dstride; GFC_INTEGER_8 *dest; const GFC_INTEGER_8 *base; GFC_LOGICAL_1 *mbase; int rank; index_type n; int mask_kind; rank = GFC_DESCRIPTOR_RANK (array); if (rank <= 0) runtime_error ("Rank of array needs to be > 0"); if (retarray->data == NULL) { GFC_DIMENSION_SET(retarray->dim[0], 0, rank - 1, 1); retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1; retarray->offset = 0; retarray->data = internal_malloc_size (sizeof (GFC_INTEGER_8) * rank); } else { if (unlikely (compile_options.bounds_check)) { bounds_iforeach_return ((array_t *) retarray, (array_t *) array, "MINLOC"); bounds_equal_extents ((array_t *) mask, (array_t *) array, "MASK argument", "MINLOC"); } } mask_kind = GFC_DESCRIPTOR_SIZE (mask); mbase = mask->data; if (mask_kind == 1 || mask_kind == 2 || mask_kind == 4 || mask_kind == 8 #ifdef HAVE_GFC_LOGICAL_16 || mask_kind == 16 #endif ) mbase = GFOR_POINTER_TO_L1 (mbase, mask_kind); else runtime_error ("Funny sized logical array"); dstride = GFC_DESCRIPTOR_STRIDE(retarray,0); dest = retarray->data; for (n = 0; n < rank; n++) { sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n); mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask,n); extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); count[n] = 0; if (extent[n] <= 0) { /* Set the return value. */ for (n = 0; n < rank; n++) dest[n * dstride] = 0; return; } } base = array->data; /* Initialize the return value. */ for (n = 0; n < rank; n++) dest[n * dstride] = 0; { GFC_INTEGER_8 minval; int fast = 0; #if defined(GFC_INTEGER_8_INFINITY) minval = GFC_INTEGER_8_INFINITY; #else minval = GFC_INTEGER_8_HUGE; #endif while (base) { do { /* Implementation start. */ } while (0); if (unlikely (!fast)) { do { if (*mbase) { #if defined(GFC_INTEGER_8_QUIET_NAN) if (unlikely (dest[0] == 0)) for (n = 0; n < rank; n++) dest[n * dstride] = count[n] + 1; if (*base <= minval) #endif { fast = 1; minval = *base; for (n = 0; n < rank; n++) dest[n * dstride] = count[n] + 1; break; } } base += sstride[0]; mbase += mstride[0]; } while (++count[0] != extent[0]); if (likely (fast)) continue; } else do { if (*mbase && *base < minval) { minval = *base; for (n = 0; n < rank; n++) dest[n * dstride] = count[n] + 1; } /* Implementation end. */ /* Advance to the next element. */ base += sstride[0]; mbase += mstride[0]; } while (++count[0] != extent[0]); n = 0; do { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ base -= sstride[n] * extent[n]; mbase -= mstride[n] * extent[n]; n++; if (n == rank) { /* Break out of the loop. */ base = NULL; break; } else { count[n]++; base += sstride[n]; mbase += mstride[n]; } } while (count[n] == extent[n]); } } } extern void sminloc0_8_i8 (gfc_array_i8 * const restrict, gfc_array_i8 * const restrict, GFC_LOGICAL_4 *); export_proto(sminloc0_8_i8); void sminloc0_8_i8 (gfc_array_i8 * const restrict retarray, gfc_array_i8 * const restrict array, GFC_LOGICAL_4 * mask) { index_type rank; index_type dstride; index_type n; GFC_INTEGER_8 *dest; if (*mask) { minloc0_8_i8 (retarray, array); return; } rank = GFC_DESCRIPTOR_RANK (array); if (rank <= 0) runtime_error ("Rank of array needs to be > 0"); if (retarray->data == NULL) { GFC_DIMENSION_SET(retarray->dim[0], 0, rank-1, 1); retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1; retarray->offset = 0; retarray->data = internal_malloc_size (sizeof (GFC_INTEGER_8) * rank); } else if (unlikely (compile_options.bounds_check)) { bounds_iforeach_return ((array_t *) retarray, (array_t *) array, "MINLOC"); } dstride = GFC_DESCRIPTOR_STRIDE(retarray,0); dest = retarray->data; for (n = 0; n<rank; n++) dest[n * dstride] = 0 ; } #endif
gpl-2.0
tomzhang/pdsh
src/common/split.c
25
4374
/*****************************************************************************\ * $Id$ ***************************************************************************** * Copyright (C) 2006 The Regents of the University of California. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). * Written by Jim Garlick <garlick@llnl.gov>. * UCRL-CODE-2003-005. * * This file is part of Pdsh, a parallel remote shell program. * For details, see <http://www.llnl.gov/linux/pdsh/>. * * Pdsh 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. * * Pdsh 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 Pdsh; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. \*****************************************************************************/ #if HAVE_CONFIG_H # include <config.h> #endif #include <string.h> #include <stdio.h> #include <stdlib.h> #include "xmalloc.h" #include "split.h" /* * Helper function for list_split(). Extract tokens from str. * Return a pointer to the next token; at the same time, advance * *str to point to the next separator. * sep (IN) string containing list of separator characters * str (IN) double-pointer to string containing tokens and separators * RETURN next token */ static char *_next_tok(char *sep, char **str) { char *tok; int level = 0; /* push str past any leading separators */ while (**str != '\0' && strchr(sep, **str) != NULL) (*str)++; if (**str == '\0') return NULL; /* assign token pointer */ tok = *str; /* push str past token and leave pointing to first separator, ignoring separators between any '[]' */ while (**str != '\0' && (level != 0 || strchr(sep, **str) == NULL)) { if (**str == '[') level++; else if (**str == ']') level--; (*str)++; } /* nullify consecutive separators and push str beyond them */ while (**str != '\0' && strchr(sep, **str) != NULL) *(*str)++ = '\0'; return tok; } static void free_f (char *str) { Free ((void **) &str); } /* * Given a list of separators and a string, generate a list * sep (IN) string containing separater characters * str (IN) string containing tokens and separators * RETURN new list containing all tokens */ List list_split(char *sep, char *str) { List new = list_create((ListDelF) free_f); char *tok; if (sep == NULL) sep = " \t"; while ((tok = _next_tok(sep, &str)) != NULL) { if (strlen(tok) > 0) list_append(new, Strdup(tok)); } return new; } List list_split_append (List l, char *sep, char *str) { char *tok; if (l == NULL) return (list_split (sep, str)); if (sep == NULL) sep = " \t"; while ((tok = _next_tok(sep, &str)) != NULL) { if (strlen(tok) > 0) list_append(l, Strdup(tok)); } return l; } int list_join (char *result, size_t len, const char *sep, List l) { char *str = NULL; int n = 0; int truncated = 0; ListIterator i; memset (result, 0, len); if (list_count(l) == 0) return (0); i = list_iterator_create(l); while ((str = list_next(i))) { int count; if (!truncated) { count = snprintf(result + n, len - n, "%s%s", str, sep); if ((count >= (len - n)) || (count < 0)) truncated = 1; else n += count; } else n += strlen (str) + strlen (sep); } list_iterator_destroy(i); if (truncated) result [len - 1] = '\0'; else { /* * Delete final separator */ result[strlen(result) - strlen(sep)] = '\0'; } return (n); } /* vi: ts=4 sw=4 expandtab */
gpl-2.0
cyox93/s3c-linux-2.6.21
arch/sh64/kernel/irq.c
25
2478
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * arch/sh64/kernel/irq.c * * Copyright (C) 2000, 2001 Paolo Alberelli * Copyright (C) 2003 Paul Mundt * */ /* * IRQs are in fact implemented a bit like signal handlers for the kernel. * Naturally it's not a 1:1 relation, but there are similarities. */ #include <linux/errno.h> #include <linux/kernel_stat.h> #include <linux/signal.h> #include <linux/rwsem.h> #include <linux/sched.h> #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/timex.h> #include <linux/slab.h> #include <linux/random.h> #include <linux/smp.h> #include <linux/smp_lock.h> #include <linux/init.h> #include <linux/seq_file.h> #include <linux/bitops.h> #include <asm/system.h> #include <asm/io.h> #include <asm/smp.h> #include <asm/pgalloc.h> #include <asm/delay.h> #include <asm/irq.h> #include <linux/irq.h> void ack_bad_irq(unsigned int irq) { printk("unexpected IRQ trap at irq %02x\n", irq); } #if defined(CONFIG_PROC_FS) int show_interrupts(struct seq_file *p, void *v) { int i = *(loff_t *) v, j; struct irqaction * action; unsigned long flags; if (i == 0) { seq_puts(p, " "); for_each_online_cpu(j) seq_printf(p, "CPU%d ",j); seq_putc(p, '\n'); } if (i < NR_IRQS) { spin_lock_irqsave(&irq_desc[i].lock, flags); action = irq_desc[i].action; if (!action) goto unlock; seq_printf(p, "%3d: ",i); seq_printf(p, "%10u ", kstat_irqs(i)); seq_printf(p, " %14s", irq_desc[i].chip->typename); seq_printf(p, " %s", action->name); for (action=action->next; action; action = action->next) seq_printf(p, ", %s", action->name); seq_putc(p, '\n'); unlock: spin_unlock_irqrestore(&irq_desc[i].lock, flags); } return 0; } #endif /* * do_NMI handles all Non-Maskable Interrupts. */ asmlinkage void do_NMI(unsigned long vector_num, struct pt_regs * regs) { if (regs->sr & 0x40000000) printk("unexpected NMI trap in system mode\n"); else printk("unexpected NMI trap in user mode\n"); /* No statistics */ } /* * do_IRQ handles all normal device IRQ's. */ asmlinkage int do_IRQ(unsigned long vector_num, struct pt_regs * regs) { int irq; irq_enter(); irq = irq_demux(vector_num); if (irq >= 0) { __do_IRQ(irq, regs); } else { printk("unexpected IRQ trap at vector %03lx\n", vector_num); } irq_exit(); return 1; }
gpl-2.0
cooler-SAI/TrinityCore434
src/tools/mesh_extractor/WorldModelHandler.cpp
25
9414
/* * Copyright (C) 2008-2014 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 "WorldModelHandler.h" #include "WorldModelRoot.h" #include "Chunk.h" #include "Cache.h" #include "Model.h" #include "Define.h" #include "G3D/Matrix4.h" #include "G3D/Quat.h" #include <cstdio> WorldModelDefinition WorldModelDefinition::Read( FILE* file ) { WorldModelDefinition ret; int count = 0; count += fread(&ret.MwidIndex, sizeof(uint32), 1, file); count += fread(&ret.UniqueId, sizeof(uint32), 1, file); ret.Position = Vector3::Read(file); ret.Rotation = Vector3::Read(file); ret.UpperExtents = Vector3::Read(file); ret.LowerExtents = Vector3::Read(file); count += fread(&ret.Flags, sizeof(uint16), 1, file); count += fread(&ret.DoodadSet, sizeof(uint16), 1, file); uint32 discard; count += fread(&discard, sizeof(uint32), 1, file); if (count != 5) printf("WorldModelDefinition::Read: Error reading data, expected 5, read %d\n", count); return ret; } WorldModelHandler::WorldModelHandler( ADT* adt ) : ObjectDataHandler(adt), _definitions(NULL), _paths(NULL) { ReadModelPaths(); ReadDefinitions(); } void WorldModelHandler::ProcessInternal( MapChunk* mcnk ) { if (!IsSane()) return; uint32 refCount = mcnk->Header.MapObjectRefs; FILE* stream = mcnk->Source->GetStream(); fseek(stream, mcnk->Source->Offset + mcnk->Header.OffsetMCRF, SEEK_SET); // Start looping at the last Doodad Ref index for (uint32 i = mcnk->Header.DoodadRefs; i < refCount; i++) { int32 index; if (fread(&index, sizeof(int32), 1, stream) != 1) printf("WorldModelDefinition::Read: Error reading data, expected 1, read 0\n"); if (index < 0 || uint32(index) >= _definitions->size()) continue; WorldModelDefinition wmo = (*_definitions)[index]; if (_drawn.find(wmo.UniqueId) != _drawn.end()) continue; _drawn.insert(wmo.UniqueId); if (wmo.MwidIndex >= _paths->size()) continue; std::string path = (*_paths)[wmo.MwidIndex]; WorldModelRoot* model = Cache->WorldModelCache.Get(path); if (!model) { model = new WorldModelRoot(path); Cache->WorldModelCache.Insert(path, model); } Vertices.reserve(1000); Triangles.reserve(1000); InsertModelGeometry(Vertices, Triangles, wmo, model); } // Restore the stream position fseek(stream, mcnk->Source->Offset, SEEK_SET); } void WorldModelHandler::InsertModelGeometry( std::vector<Vector3>& verts, std::vector<Triangle<uint32> >& tris, const WorldModelDefinition& def, WorldModelRoot* root, bool translate ) { for (std::vector<WorldModelGroup>::iterator group = root->Groups.begin(); group != root->Groups.end(); ++group) { uint32 vertOffset = verts.size(); for (std::vector<Vector3>::iterator itr2 = group->Vertices.begin(); itr2 != group->Vertices.end(); ++itr2) { Vector3 v = Utils::TransformDoodadVertex(def, *itr2, translate); // If translate is false, then we were called directly from the TileBuilder to add data to it's _Geometry member, hence, we have to manually convert the vertices to Recast format. verts.push_back(translate ? v : Utils::ToRecast(v)); // Transform the vertex to world space } for (uint32 i = 0; i < group->Triangles.size(); ++i) { // only include colliding tris if ((group->TriangleFlags[i] & 0x04) != 0 && group->TriangleMaterials[i] != 0xFF) continue; Triangle<uint16> tri = group->Triangles[i]; tris.push_back(Triangle<uint32>(Constants::TRIANGLE_TYPE_WMO, tri.V0 + vertOffset, tri.V1 + vertOffset, tri.V2 + vertOffset)); } } if (def.DoodadSet < root->DoodadSets.size()) { DoodadSet set = root->DoodadSets[def.DoodadSet]; std::vector<DoodadInstance> instances; instances.reserve(set.CountInstances); for (uint32 i = set.FirstInstanceIndex; i < (set.CountInstances + set.FirstInstanceIndex); i++) { if (i >= root->DoodadInstances.size()) break; instances.push_back(root->DoodadInstances[i]); } for (std::vector<DoodadInstance>::iterator instance = instances.begin(); instance != instances.end(); ++instance) { Model* model = Cache->ModelCache.Get(instance->File); if (!model) { model = new Model(instance->File); Cache->ModelCache.Insert(instance->File, model); } if (!model->IsCollidable) continue; int vertOffset = verts.size(); for (std::vector<Vector3>::iterator itr2 = model->Vertices.begin(); itr2 != model->Vertices.end(); ++itr2) { Vector3 v = Utils::TransformDoodadVertex(def, Utils::TransformWmoDoodad(*instance, def, *itr2, false), translate); verts.push_back(translate ? v : Utils::ToRecast(v)); } for (std::vector<Triangle<uint16> >::iterator itr2 = model->Triangles.begin(); itr2 != model->Triangles.end(); ++itr2) tris.push_back(Triangle<uint32>(Constants::TRIANGLE_TYPE_WMO, itr2->V0 + vertOffset, itr2->V1 + vertOffset, itr2->V2 + vertOffset)); } for (std::vector<WorldModelGroup>::iterator group = root->Groups.begin(); group != root->Groups.end(); ++group) { if (!group->HasLiquidData) continue; const LiquidHeader& liquidHeader = group->LiquidDataHeader; LiquidData& liquidDataGeometry = group->LiquidDataGeometry; for (uint32 y = 0; y < liquidHeader.Height; y++) { for (uint32 x = 0; x < liquidHeader.Width; x++) { if (!liquidDataGeometry.ShouldRender(x, y)) continue; uint32 vertOffset = verts.size(); Vector3 v1 = Utils::GetLiquidVert(def, liquidHeader.BaseLocation, liquidDataGeometry.HeightMap[x][y], x, y, translate); Vector3 v2 = Utils::GetLiquidVert(def, liquidHeader.BaseLocation, liquidDataGeometry.HeightMap[x + 1][y], x + 1, y, translate); Vector3 v3 = Utils::GetLiquidVert(def, liquidHeader.BaseLocation, liquidDataGeometry.HeightMap[x][y + 1], x, y + 1, translate); Vector3 v4 = Utils::GetLiquidVert(def, liquidHeader.BaseLocation, liquidDataGeometry.HeightMap[x + 1][y + 1], x + 1, y + 1, translate); verts.push_back(translate ? v1 : Utils::ToRecast(v1)); verts.push_back(translate ? v2 : Utils::ToRecast(v2)); verts.push_back(translate ? v3 : Utils::ToRecast(v3)); verts.push_back(translate ? v4 : Utils::ToRecast(v4)); tris.push_back(Triangle<uint32>(Constants::TRIANGLE_TYPE_WATER, vertOffset, vertOffset + 2, vertOffset + 1)); tris.push_back(Triangle<uint32>(Constants::TRIANGLE_TYPE_WATER, vertOffset + 2, vertOffset + 3, vertOffset + 1)); } } } } } void WorldModelHandler::ReadDefinitions() { Chunk* chunk = Source->ObjectData->GetChunkByName("MODF"); if (!chunk) return; const int32 definitionSize = 64; uint32 definitionCount = chunk->Length / definitionSize; _definitions = new std::vector<WorldModelDefinition>; _definitions->reserve(definitionCount); FILE* stream = chunk->GetStream(); for (uint32 i = 0; i < definitionCount; i++) _definitions->push_back(WorldModelDefinition::Read(stream)); } void WorldModelHandler::ReadModelPaths() { Chunk* mwid = Source->ObjectData->GetChunkByName("MWID"); Chunk* mwmo = Source->ObjectData->GetChunkByName("MWMO"); if (!mwid || !mwmo) return; uint32 paths = mwid->Length / 4; _paths = new std::vector<std::string>; _paths->reserve(paths); for (uint32 i = 0; i < paths; i++) { FILE* stream = mwid->GetStream(); fseek(stream, i * 4, SEEK_CUR); uint32 offset; if (fread(&offset, sizeof(uint32), 1, stream) != 1) printf("WorldModelDefinition::Read: Error reading data, expected 1, read 0\n"); FILE* dataStream = mwmo->GetStream(); fseek(dataStream, offset + mwmo->Offset, SEEK_SET); _paths->push_back(Utils::ReadString(dataStream)); } } WorldModelHandler::~WorldModelHandler() { delete _definitions; delete _paths; }
gpl-2.0
CyanHacker-Lollipop/kernel_moto_shamu
drivers/power/mmi-wls-charger.c
25
17226
/* * Copyright (C) 2012-2014 Motorola Mobility LLC * * 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 * */ #include <linux/debugfs.h> #include <linux/gpio.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/param.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/printk.h> #define MMI_WLS_CHRG_DRV_NAME "mmi-wls-charger" #define MMI_WLS_CHRG_PSY_NAME "wireless" #define MMI_WLS_CHRG_TEMP_HYS_COLD 2 #define MMI_WLS_CHRG_TEMP_HYS_HOT 5 #define MMI_WLS_CHRG_CHRG_CMPLT_SOC 100 #define MMI_WLS_NUM_GPIOS 3 struct mmi_wls_chrg_chip { struct i2c_client *client; struct device *dev; int num_gpios; struct gpio *list; unsigned int state; unsigned int irq_num; struct delayed_work mmi_wls_chrg_work; struct power_supply wl_psy; struct power_supply *batt_psy; struct power_supply *dc_psy; struct power_supply *usb_psy; int pad_det_n_gpio; int charge_cmplt_n_gpio; int charge_term_gpio; int priority; int resume_soc; int resume_vbatt; int hot_temp; int cold_temp; struct dentry *debug_root; u32 peek_poke_address; bool force_shutdown; }; enum mmi_wls_chrg_state { MMI_WLS_CHRG_WAIT = 0, MMI_WLS_CHRG_RUNNING, MMI_WLS_CHRG_OUT_OF_TEMP_HOT, MMI_WLS_CHRG_OUT_OF_TEMP_COLD, MMI_WLS_CHRG_CHRG_CMPLT, MMI_WLS_CHRG_WIRED_CONN, }; enum mmi_wls_charger_priority { MMI_WLS_CHRG_WIRELESS = 0, MMI_WLS_CHRG_WIRED, }; #define DEFAULT_PRIORITY MMI_WLS_CHRG_WIRED #define DEFAULT_RESUME_SOC 99 #define DEFAULT_RESUME_VBATT 0 #define DEFAULT_HOT_TEMP 60 #define DEFAULT_COLD_TEMP -20 static int mmi_wls_chrg_write_reg(struct i2c_client *client, u8 reg, u16 value) { int ret = i2c_smbus_write_word_data(client, reg, value); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } static int mmi_wls_chrg_read_reg(struct i2c_client *client, u8 reg) { int ret = i2c_smbus_read_word_data(client, reg); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } static int get_reg(void *data, u64 *val) { struct mmi_wls_chrg_chip *chip = data; int temp; temp = mmi_wls_chrg_read_reg(chip->client, chip->peek_poke_address); *val = temp; return 0; } static int set_reg(void *data, u64 val) { struct mmi_wls_chrg_chip *chip = data; int rc; u16 temp; temp = (u8) val; rc = mmi_wls_chrg_write_reg(chip->client, chip->peek_poke_address, temp); return 0; } DEFINE_SIMPLE_ATTRIBUTE(poke_poke_debug_ops, get_reg, set_reg, "0x%02llx\n"); static int mmi_wls_chrg_get_psy_info(struct power_supply *psy, enum power_supply_property psp, int *data) { union power_supply_propval ret = {0,}; if (psy) { if (psy->get_property) { if (!psy->get_property(psy, psp, &ret)) { *data = ret.intval; return 0; } } } pr_err("mmi_wls_chrg_get_psy_info: get_prop Fail!\n"); return 1; } static void mmi_wls_chrg_get_psys(struct mmi_wls_chrg_chip *chip) { int i = 0; struct power_supply *psy; if (!chip) { pr_err_once("Chip not ready\n"); return; } for (i = 0; i < chip->wl_psy.num_supplies; i++) { psy = power_supply_get_by_name(chip->wl_psy.supplied_from[i]); if (psy) switch (psy->type) { case POWER_SUPPLY_TYPE_BATTERY: case POWER_SUPPLY_TYPE_BMS: chip->batt_psy = psy; break; case POWER_SUPPLY_TYPE_MAINS: case POWER_SUPPLY_TYPE_WIRELESS: chip->dc_psy = psy; break; case POWER_SUPPLY_TYPE_USB: case POWER_SUPPLY_TYPE_USB_DCP: case POWER_SUPPLY_TYPE_USB_CDP: case POWER_SUPPLY_TYPE_USB_ACA: default: /* USB type dynamically changes so default */ chip->usb_psy = psy; } } if (!chip->batt_psy) pr_err("BATT PSY Not Found\n"); if (!chip->dc_psy) pr_err("DC PSY Not Found\n"); if (!chip->usb_psy) pr_err("USB PSY Not Found\n"); } static void mmi_wls_chrg_worker(struct work_struct *work) { int batt_temp; int batt_volt; int batt_soc; int powered = 0; int wired = 0; struct delayed_work *dwork; struct mmi_wls_chrg_chip *chip; dwork = to_delayed_work(work); chip = container_of(dwork, struct mmi_wls_chrg_chip, mmi_wls_chrg_work); if (!chip->dc_psy || !chip->usb_psy || !chip->batt_psy) { mmi_wls_chrg_get_psys(chip); if (!chip->dc_psy || !chip->usb_psy || !chip->batt_psy) return; } if (mmi_wls_chrg_get_psy_info(chip->dc_psy, POWER_SUPPLY_PROP_PRESENT, &powered)) { dev_err(chip->dev, "Error Reading DC Present\n"); return; } if (mmi_wls_chrg_get_psy_info(chip->usb_psy, POWER_SUPPLY_PROP_PRESENT, &wired)) { dev_err(chip->dev, "Error Reading USB Present\n"); return; } if (mmi_wls_chrg_get_psy_info(chip->batt_psy, POWER_SUPPLY_PROP_TEMP, &batt_temp)) { dev_err(chip->dev, "Error Reading Temperature\n"); return; } /* Convert Units to Celsius */ batt_temp /= 10; if (mmi_wls_chrg_get_psy_info(chip->batt_psy, POWER_SUPPLY_PROP_VOLTAGE_NOW, &batt_volt)) { dev_err(chip->dev, "Error Reading Voltage\n"); return; } if (mmi_wls_chrg_get_psy_info(chip->batt_psy, POWER_SUPPLY_PROP_CAPACITY, &batt_soc)) { dev_err(chip->dev, "Error Reading Capacity\n"); return; } if (batt_soc == 0) chip->force_shutdown = true; dev_dbg(chip->dev, "State Before = %d\n", chip->state); switch (chip->state) { case MMI_WLS_CHRG_WAIT: if (wired && (chip->priority == MMI_WLS_CHRG_WIRED)) { gpio_set_value(chip->charge_cmplt_n_gpio, 0); chip->state = MMI_WLS_CHRG_WIRED_CONN; } else if (powered) { chip->state = MMI_WLS_CHRG_RUNNING; } break; case MMI_WLS_CHRG_WIRED_CONN: if (!wired) { gpio_set_value(chip->charge_cmplt_n_gpio, 1); chip->state = MMI_WLS_CHRG_WAIT; } break; case MMI_WLS_CHRG_RUNNING: if (wired && (chip->priority == MMI_WLS_CHRG_WIRED)) { gpio_set_value(chip->charge_cmplt_n_gpio, 0); chip->state = MMI_WLS_CHRG_WIRED_CONN; } else if (!powered) { gpio_set_value(chip->charge_cmplt_n_gpio, 1); gpio_set_value(chip->charge_term_gpio, 0); chip->state = MMI_WLS_CHRG_WAIT; } else if (batt_temp >= chip->hot_temp) { gpio_set_value(chip->charge_term_gpio, 1); chip->state = MMI_WLS_CHRG_OUT_OF_TEMP_HOT; } else if (batt_temp <= chip->cold_temp) { gpio_set_value(chip->charge_term_gpio, 1); chip->state = MMI_WLS_CHRG_OUT_OF_TEMP_COLD; } else if (batt_soc >= MMI_WLS_CHRG_CHRG_CMPLT_SOC) { gpio_set_value(chip->charge_cmplt_n_gpio, 0); chip->state = MMI_WLS_CHRG_CHRG_CMPLT; } break; case MMI_WLS_CHRG_OUT_OF_TEMP_HOT: if (wired && (chip->priority == MMI_WLS_CHRG_WIRED)) { gpio_set_value(chip->charge_cmplt_n_gpio, 0); chip->state = MMI_WLS_CHRG_WIRED_CONN; } else if (batt_temp < (chip->hot_temp - MMI_WLS_CHRG_TEMP_HYS_HOT)) { gpio_set_value(chip->charge_cmplt_n_gpio, 1); gpio_set_value(chip->charge_term_gpio, 0); chip->state = MMI_WLS_CHRG_WAIT; } break; case MMI_WLS_CHRG_OUT_OF_TEMP_COLD: if (wired && (chip->priority == MMI_WLS_CHRG_WIRED)) { gpio_set_value(chip->charge_cmplt_n_gpio, 0); chip->state = MMI_WLS_CHRG_WIRED_CONN; } else if (batt_temp > (chip->cold_temp + MMI_WLS_CHRG_TEMP_HYS_COLD)) { gpio_set_value(chip->charge_cmplt_n_gpio, 1); gpio_set_value(chip->charge_term_gpio, 0); chip->state = MMI_WLS_CHRG_WAIT; } break; case MMI_WLS_CHRG_CHRG_CMPLT: if (wired && (chip->priority == MMI_WLS_CHRG_WIRED)) { gpio_set_value(chip->charge_cmplt_n_gpio, 0); chip->state = MMI_WLS_CHRG_WIRED_CONN; } else if ((batt_soc <= chip->resume_soc) || (batt_volt <= chip->resume_vbatt)) { gpio_set_value(chip->charge_cmplt_n_gpio, 1); gpio_set_value(chip->charge_term_gpio, 0); chip->state = MMI_WLS_CHRG_WAIT; } break; } dev_dbg(chip->dev, "State After = %d\n", chip->state); return; } static enum power_supply_property mmi_wls_chrg_props[] = { POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, }; static int mmi_wls_chrg_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct mmi_wls_chrg_chip *chip; int powered = 0; if (!psy || !psy->dev || !val) { pr_err("mmi_wls_chrg_get_property NO dev!\n"); return -ENODEV; } chip = dev_get_drvdata(psy->dev->parent); if (!chip) { pr_err("mmi_wls_chrg_get_property NO dev chip!\n"); return -ENODEV; } val->intval = 0; switch (psp) { case POWER_SUPPLY_PROP_PRESENT: val->intval = !gpio_get_value(chip->pad_det_n_gpio); if (chip->force_shutdown) val->intval = 0; break; case POWER_SUPPLY_PROP_ONLINE: if (chip->dc_psy) { mmi_wls_chrg_get_psy_info(chip->dc_psy, POWER_SUPPLY_PROP_PRESENT, &powered); val->intval = powered; } else { val->intval = (!gpio_get_value(chip->pad_det_n_gpio) && gpio_get_value(chip->charge_cmplt_n_gpio) && !gpio_get_value(chip->charge_term_gpio)); } if (chip->force_shutdown) val->intval = 0; break; default: return -EINVAL; } return 0; } static void mmi_wls_charger_external_power_changed(struct power_supply *psy) { struct mmi_wls_chrg_chip *chip = container_of(psy, struct mmi_wls_chrg_chip, wl_psy); dev_dbg(chip->dev, "mmi_wls_charger External Change Reported!\n"); schedule_delayed_work(&chip->mmi_wls_chrg_work, msecs_to_jiffies(100)); return; } static irqreturn_t pad_det_handler(int irq, void *dev_id) { struct mmi_wls_chrg_chip *chip = dev_id; if (gpio_get_value(chip->pad_det_n_gpio)) power_supply_changed(&chip->wl_psy); dev_dbg(chip->dev, "pad_det_handler pad_det_n =%x\n", gpio_get_value(chip->pad_det_n_gpio)); return IRQ_HANDLED; } static const struct of_device_id mmi_wls_chrg_of_tbl[] = { { .compatible = "mmi,wls-charger-bq51021", .data = NULL}, {}, }; static int mmi_wls_chrg_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; int i; int gpio_count; char **sf; enum of_gpio_flags flags; const struct of_device_id *match; struct mmi_wls_chrg_chip *chip; struct device_node *np = client->dev.of_node; dev_info(&client->dev, "Probe of mmi_wls_charger\n"); if (!np) { dev_err(&client->dev, "No OF DT node found.\n"); return -ENODEV; } match = of_match_device(mmi_wls_chrg_of_tbl, &client->dev); if (!match) { dev_err(&client->dev, "No Match found\n"); return -ENODEV; } if (match && match->compatible) dev_info(&client->dev, "Using %s\n", match->compatible); chip = devm_kzalloc(&client->dev, sizeof(*chip), GFP_KERNEL); if (!chip) { dev_err(&client->dev, "Unable to allocate memory\n"); return -ENOMEM; } chip->client = client; chip->dev = &client->dev; gpio_count = of_gpio_count(np); if (!gpio_count) { dev_err(&client->dev, "No GPIOS defined.\n"); return -ENODEV; } /* Make sure number of GPIOs defined matches the supplied number of * GPIO name strings. */ if (gpio_count != of_property_count_strings(np, "gpio-names")) { dev_err(&client->dev, "GPIO info and name mismatch\n"); return -ENODEV; } chip->list = devm_kzalloc(&client->dev, sizeof(struct gpio) * gpio_count, GFP_KERNEL); if (!chip->list) { dev_err(&client->dev, "GPIO List allocate failure\n"); return -ENOMEM; } chip->num_gpios = gpio_count; for (i = 0; i < gpio_count; i++) { chip->list[i].gpio = of_get_gpio_flags(np, i, &flags); chip->list[i].flags = flags; of_property_read_string_index(np, "gpio-names", i, &chip->list[i].label); dev_dbg(&client->dev, "GPIO: %d FLAGS: %ld LABEL: %s\n", chip->list[i].gpio, chip->list[i].flags, chip->list[i].label); } ret = gpio_request_array(chip->list, chip->num_gpios); if (ret) { dev_err(&client->dev, "failed to request GPIOs\n"); return -ENODEV; } for (i = 0; i < chip->num_gpios; i++) { ret = gpio_export(chip->list[i].gpio, 1); if (ret) { dev_err(&client->dev, "Failed to export GPIO %s: %d\n", chip->list[i].label, chip->list[i].gpio); goto fail_gpios; } ret = gpio_export_link(&client->dev, chip->list[i].label, chip->list[i].gpio); if (ret) { dev_err(&client->dev, "Failed to link GPIO %s: %d\n", chip->list[i].label, chip->list[i].gpio); goto fail_gpios; } } if (chip->num_gpios == MMI_WLS_NUM_GPIOS) { chip->pad_det_n_gpio = chip->list[0].gpio; chip->charge_cmplt_n_gpio = chip->list[1].gpio; chip->charge_term_gpio = chip->list[2].gpio; } if (chip->pad_det_n_gpio) { int irq; irq = gpio_to_irq(chip->pad_det_n_gpio); if (irq < 0) { dev_err(&client->dev, " gpio_to_irq failed\n"); ret = -ENODEV; goto fail_gpios; } ret = devm_request_irq(&client->dev, irq, pad_det_handler, IRQF_TRIGGER_RISING, "pad_det_n", chip); if (ret < 0) { dev_err(&client->dev, "request pad_det irq failed\n"); goto fail_gpios; } } ret = of_property_read_u32(np, "mmi,priority", &chip->priority); if ((ret < 0) || (chip->priority == 0)) chip->priority = DEFAULT_PRIORITY; ret = of_property_read_u32(np, "mmi,resume-soc", &chip->resume_soc); if ((ret < 0) || (chip->resume_soc == 0)) chip->resume_soc = DEFAULT_RESUME_SOC; ret = of_property_read_u32(np, "mmi,resume-vbatt-mv", &chip->resume_vbatt); if ((ret < 0) || (chip->resume_vbatt == 0)) chip->resume_vbatt = DEFAULT_RESUME_VBATT; ret = of_property_read_u32(np, "mmi,hot-temp-thresh", &chip->hot_temp); if ((ret < 0) || (chip->hot_temp == 0)) chip->hot_temp = DEFAULT_HOT_TEMP; ret = of_property_read_u32(np, "mmi,cold-temp-thresh", (u32 *)&chip->cold_temp); if ((ret < 0) || (chip->cold_temp == 0)) chip->cold_temp = DEFAULT_COLD_TEMP; chip->state = MMI_WLS_CHRG_WAIT; INIT_DELAYED_WORK(&chip->mmi_wls_chrg_work, mmi_wls_chrg_worker); chip->wl_psy.num_supplies = of_property_count_strings(np, "supply-names"); chip->wl_psy.supplied_from = devm_kzalloc(&client->dev, sizeof(char *) * chip->wl_psy.num_supplies, GFP_KERNEL); if (!chip->wl_psy.supplied_from) { dev_err(&client->dev, "mmi_wls fail create supplied_from\n"); goto fail_gpios; } for (i = 0; i < chip->wl_psy.num_supplies; i++) { sf = &chip->wl_psy.supplied_from[i]; of_property_read_string_index(np, "supply-names", i, (const char **)sf); dev_info(&client->dev, "supply name: %s\n", chip->wl_psy.supplied_from[i]); } chip->wl_psy.name = MMI_WLS_CHRG_PSY_NAME; chip->wl_psy.type = POWER_SUPPLY_TYPE_WIRELESS; chip->wl_psy.properties = mmi_wls_chrg_props; chip->wl_psy.num_properties = ARRAY_SIZE(mmi_wls_chrg_props); chip->wl_psy.get_property = mmi_wls_chrg_get_property; chip->wl_psy.external_power_changed = mmi_wls_charger_external_power_changed; ret = power_supply_register(&client->dev, &chip->wl_psy); if (ret < 0) { dev_err(&client->dev, "power_supply_register wireless failed ret = %d\n", ret); goto fail_gpios; } mmi_wls_chrg_get_psys(chip); chip->debug_root = debugfs_create_dir("mmi_wls_chrg", NULL); if (!chip->debug_root) dev_err(&client->dev, "Couldn't create debug dir\n"); if (chip->debug_root) { struct dentry *ent; ent = debugfs_create_x32("address", S_IFREG | S_IWUSR | S_IRUGO, chip->debug_root, &(chip->peek_poke_address)); if (!ent) dev_err(&client->dev, "Couldn't create address debug file\n"); ent = debugfs_create_file("data", S_IFREG | S_IWUSR | S_IRUGO, chip->debug_root, chip, &poke_poke_debug_ops); if (!ent) dev_err(&client->dev, "Couldn't create data debug file\n"); } i2c_set_clientdata(client, chip); chip->force_shutdown = false; schedule_delayed_work(&chip->mmi_wls_chrg_work, msecs_to_jiffies(100)); return 0; fail_gpios: gpio_free_array(chip->list, chip->num_gpios); return ret; } static int mmi_wls_chrg_remove(struct i2c_client *client) { struct mmi_wls_chrg_chip *chip = i2c_get_clientdata(client); if (chip) gpio_free_array(chip->list, chip->num_gpios); return 0; } static const struct i2c_device_id mmi_wls_charger_id[] = { {"mmi-wls-charger", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, mmi_wls_charger_charger_id); static struct i2c_driver mmi_wls_charger_driver = { .driver = { .name = MMI_WLS_CHRG_DRV_NAME, .owner = THIS_MODULE, .of_match_table = mmi_wls_chrg_of_tbl, }, .probe = mmi_wls_chrg_probe, .remove = mmi_wls_chrg_remove, .id_table = mmi_wls_charger_id, }; module_i2c_driver(mmi_wls_charger_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Motorola Mobility LLC"); MODULE_DESCRIPTION("mmi-wls-charger driver"); MODULE_ALIAS("i2c:mmi-wls-charger");
gpl-2.0
ScienceXChina/linux-jetson-tk1
kernel/events/core.c
25
193699
/* * Performance events core code: * * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de> * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com> * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com> * * For licensing details see kernel-base/COPYING */ #include <linux/fs.h> #include <linux/mm.h> #include <linux/cpu.h> #include <linux/smp.h> #include <linux/idr.h> #include <linux/file.h> #include <linux/poll.h> #include <linux/slab.h> #include <linux/hash.h> #include <linux/tick.h> #include <linux/sysfs.h> #include <linux/dcache.h> #include <linux/percpu.h> #include <linux/ptrace.h> #include <linux/reboot.h> #include <linux/vmstat.h> #include <linux/device.h> #include <linux/export.h> #include <linux/vmalloc.h> #include <linux/hardirq.h> #include <linux/rculist.h> #include <linux/uaccess.h> #include <linux/syscalls.h> #include <linux/anon_inodes.h> #include <linux/kernel_stat.h> #include <linux/perf_event.h> #include <linux/ftrace_event.h> #include <linux/hw_breakpoint.h> #include <linux/mm_types.h> #include <linux/cgroup.h> #include <linux/module.h> #include <linux/mman.h> #include "internal.h" #include <asm/irq_regs.h> struct remote_function_call { struct task_struct *p; int (*func)(void *info); void *info; int ret; }; static void remote_function(void *data) { struct remote_function_call *tfc = data; struct task_struct *p = tfc->p; if (p) { tfc->ret = -EAGAIN; if (task_cpu(p) != smp_processor_id() || !task_curr(p)) return; } tfc->ret = tfc->func(tfc->info); } /** * task_function_call - call a function on the cpu on which a task runs * @p: the task to evaluate * @func: the function to be called * @info: the function call argument * * Calls the function @func when the task is currently running. This might * be on the current CPU, which just calls the function directly * * returns: @func return value, or * -ESRCH - when the process isn't running * -EAGAIN - when the process moved away */ static int task_function_call(struct task_struct *p, int (*func) (void *info), void *info) { struct remote_function_call data = { .p = p, .func = func, .info = info, .ret = -ESRCH, /* No such (running) process */ }; if (task_curr(p)) smp_call_function_single(task_cpu(p), remote_function, &data, 1); return data.ret; } /** * cpu_function_call - call a function on the cpu * @func: the function to be called * @info: the function call argument * * Calls the function @func on the remote cpu. * * returns: @func return value or -ENXIO when the cpu is offline */ static int cpu_function_call(int cpu, int (*func) (void *info), void *info) { struct remote_function_call data = { .p = NULL, .func = func, .info = info, .ret = -ENXIO, /* No such CPU */ }; smp_call_function_single(cpu, remote_function, &data, 1); return data.ret; } #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\ PERF_FLAG_FD_OUTPUT |\ PERF_FLAG_PID_CGROUP |\ PERF_FLAG_FD_CLOEXEC) /* * branch priv levels that need permission checks */ #define PERF_SAMPLE_BRANCH_PERM_PLM \ (PERF_SAMPLE_BRANCH_KERNEL |\ PERF_SAMPLE_BRANCH_HV) enum event_type_t { EVENT_FLEXIBLE = 0x1, EVENT_PINNED = 0x2, EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED, }; /* * perf_sched_events : >0 events exist * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu */ struct static_key_deferred perf_sched_events __read_mostly; static DEFINE_PER_CPU(atomic_t, perf_cgroup_events); static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events); static atomic_t nr_mmap_events __read_mostly; static atomic_t nr_comm_events __read_mostly; static atomic_t nr_task_events __read_mostly; static atomic_t nr_freq_events __read_mostly; static LIST_HEAD(pmus); static DEFINE_MUTEX(pmus_lock); static struct srcu_struct pmus_srcu; /* * perf event paranoia level: * -1 - not paranoid at all * 0 - disallow raw tracepoint access for unpriv * 1 - disallow cpu events for unpriv * 2 - disallow kernel profiling for unpriv */ int sysctl_perf_event_paranoid __read_mostly = 1; /* Minimum for 512 kiB + 1 user control page */ int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */ /* * max perf event sample rate */ #define DEFAULT_MAX_SAMPLE_RATE 100000 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE) #define DEFAULT_CPU_TIME_MAX_PERCENT 25 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE; static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ); static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS; static int perf_sample_allowed_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100; void update_perf_cpu_limits(void) { u64 tmp = perf_sample_period_ns; tmp *= sysctl_perf_cpu_time_max_percent; do_div(tmp, 100); ACCESS_ONCE(perf_sample_allowed_ns) = tmp; } static int perf_rotate_context(struct perf_cpu_context *cpuctx); int perf_proc_update_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret || !write) return ret; max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ); perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; update_perf_cpu_limits(); return 0; } int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT; int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec(table, write, buffer, lenp, ppos); if (ret || !write) return ret; update_perf_cpu_limits(); return 0; } /* * perf samples are done in some very critical code paths (NMIs). * If they take too much CPU time, the system can lock up and not * get any real work done. This will drop the sample rate when * we detect that events are taking too long. */ #define NR_ACCUMULATED_SAMPLES 128 static DEFINE_PER_CPU(u64, running_sample_length); static void perf_duration_warn(struct irq_work *w) { u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns); u64 avg_local_sample_len; u64 local_samples_len; local_samples_len = __get_cpu_var(running_sample_length); avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES; printk_ratelimited(KERN_WARNING "perf interrupt took too long (%lld > %lld), lowering " "kernel.perf_event_max_sample_rate to %d\n", avg_local_sample_len, allowed_ns >> 1, sysctl_perf_event_sample_rate); } static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn); void perf_sample_event_took(u64 sample_len_ns) { u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns); u64 avg_local_sample_len; u64 local_samples_len; if (allowed_ns == 0) return; /* decay the counter by 1 average sample */ local_samples_len = __get_cpu_var(running_sample_length); local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES; local_samples_len += sample_len_ns; __get_cpu_var(running_sample_length) = local_samples_len; /* * note: this will be biased artifically low until we have * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us * from having to maintain a count. */ avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES; if (avg_local_sample_len <= allowed_ns) return; if (max_samples_per_tick <= 1) return; max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2); sysctl_perf_event_sample_rate = max_samples_per_tick * HZ; perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; update_perf_cpu_limits(); if (!irq_work_queue(&perf_duration_work)) { early_printk("perf interrupt took too long (%lld > %lld), lowering " "kernel.perf_event_max_sample_rate to %d\n", avg_local_sample_len, allowed_ns >> 1, sysctl_perf_event_sample_rate); } } static atomic64_t perf_event_id; static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx, enum event_type_t event_type); static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task); static void update_context_time(struct perf_event_context *ctx); static u64 perf_event_time(struct perf_event *event); void __weak perf_event_print_debug(void) { } extern __weak const char *perf_pmu_name(void) { return "pmu"; } static inline u64 perf_clock(void) { return local_clock(); } static inline struct perf_cpu_context * __get_cpu_context(struct perf_event_context *ctx) { return this_cpu_ptr(ctx->pmu->pmu_cpu_context); } static void perf_ctx_lock(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { raw_spin_lock(&cpuctx->ctx.lock); if (ctx) raw_spin_lock(&ctx->lock); } static void perf_ctx_unlock(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { if (ctx) raw_spin_unlock(&ctx->lock); raw_spin_unlock(&cpuctx->ctx.lock); } #ifdef CONFIG_CGROUP_PERF /* * perf_cgroup_info keeps track of time_enabled for a cgroup. * This is a per-cpu dynamically allocated data structure. */ struct perf_cgroup_info { u64 time; u64 timestamp; }; struct perf_cgroup { struct cgroup_subsys_state css; struct perf_cgroup_info __percpu *info; }; /* * Must ensure cgroup is pinned (css_get) before calling * this function. In other words, we cannot call this function * if there is no cgroup event for the current CPU context. */ static inline struct perf_cgroup * perf_cgroup_from_task(struct task_struct *task) { return container_of(task_css(task, perf_event_cgrp_id), struct perf_cgroup, css); } static inline bool perf_cgroup_match(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); /* @event doesn't care about cgroup */ if (!event->cgrp) return true; /* wants specific cgroup scope but @cpuctx isn't associated with any */ if (!cpuctx->cgrp) return false; /* * Cgroup scoping is recursive. An event enabled for a cgroup is * also enabled for all its descendant cgroups. If @cpuctx's * cgroup is a descendant of @event's (the test covers identity * case), it's a match. */ return cgroup_is_descendant(cpuctx->cgrp->css.cgroup, event->cgrp->css.cgroup); } static inline void perf_put_cgroup(struct perf_event *event) { css_put(&event->cgrp->css); } static inline void perf_detach_cgroup(struct perf_event *event) { perf_put_cgroup(event); event->cgrp = NULL; } static inline int is_cgroup_event(struct perf_event *event) { return event->cgrp != NULL; } static inline u64 perf_cgroup_event_time(struct perf_event *event) { struct perf_cgroup_info *t; t = per_cpu_ptr(event->cgrp->info, event->cpu); return t->time; } static inline void __update_cgrp_time(struct perf_cgroup *cgrp) { struct perf_cgroup_info *info; u64 now; now = perf_clock(); info = this_cpu_ptr(cgrp->info); info->time += now - info->timestamp; info->timestamp = now; } static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx) { struct perf_cgroup *cgrp_out = cpuctx->cgrp; if (cgrp_out) __update_cgrp_time(cgrp_out); } static inline void update_cgrp_time_from_event(struct perf_event *event) { struct perf_cgroup *cgrp; /* * ensure we access cgroup data only when needed and * when we know the cgroup is pinned (css_get) */ if (!is_cgroup_event(event)) return; cgrp = perf_cgroup_from_task(current); /* * Do not update time when cgroup is not active */ if (cgrp == event->cgrp) __update_cgrp_time(event->cgrp); } static inline void perf_cgroup_set_timestamp(struct task_struct *task, struct perf_event_context *ctx) { struct perf_cgroup *cgrp; struct perf_cgroup_info *info; /* * ctx->lock held by caller * ensure we do not access cgroup data * unless we have the cgroup pinned (css_get) */ if (!task || !ctx->nr_cgroups) return; cgrp = perf_cgroup_from_task(task); info = this_cpu_ptr(cgrp->info); info->timestamp = ctx->timestamp; } #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */ #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */ /* * reschedule events based on the cgroup constraint of task. * * mode SWOUT : schedule out everything * mode SWIN : schedule in based on cgroup for next */ void perf_cgroup_switch(struct task_struct *task, int mode) { struct perf_cpu_context *cpuctx; struct pmu *pmu; unsigned long flags; /* * disable interrupts to avoid geting nr_cgroup * changes via __perf_event_disable(). Also * avoids preemption. */ local_irq_save(flags); /* * we reschedule only in the presence of cgroup * constrained events. */ rcu_read_lock(); list_for_each_entry_rcu(pmu, &pmus, entry) { cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); if (cpuctx->unique_pmu != pmu) continue; /* ensure we process each cpuctx once */ /* * perf_cgroup_events says at least one * context on this CPU has cgroup events. * * ctx->nr_cgroups reports the number of cgroup * events for a context. */ if (cpuctx->ctx.nr_cgroups > 0) { perf_ctx_lock(cpuctx, cpuctx->task_ctx); perf_pmu_disable(cpuctx->ctx.pmu); if (mode & PERF_CGROUP_SWOUT) { cpu_ctx_sched_out(cpuctx, EVENT_ALL); /* * must not be done before ctxswout due * to event_filter_match() in event_sched_out() */ cpuctx->cgrp = NULL; } if (mode & PERF_CGROUP_SWIN) { WARN_ON_ONCE(cpuctx->cgrp); /* * set cgrp before ctxsw in to allow * event_filter_match() to not have to pass * task around */ cpuctx->cgrp = perf_cgroup_from_task(task); cpu_ctx_sched_in(cpuctx, EVENT_ALL, task); } perf_pmu_enable(cpuctx->ctx.pmu); perf_ctx_unlock(cpuctx, cpuctx->task_ctx); } } rcu_read_unlock(); local_irq_restore(flags); } static inline void perf_cgroup_sched_out(struct task_struct *task, struct task_struct *next) { struct perf_cgroup *cgrp1; struct perf_cgroup *cgrp2 = NULL; /* * we come here when we know perf_cgroup_events > 0 */ cgrp1 = perf_cgroup_from_task(task); /* * next is NULL when called from perf_event_enable_on_exec() * that will systematically cause a cgroup_switch() */ if (next) cgrp2 = perf_cgroup_from_task(next); /* * only schedule out current cgroup events if we know * that we are switching to a different cgroup. Otherwise, * do no touch the cgroup events. */ if (cgrp1 != cgrp2) perf_cgroup_switch(task, PERF_CGROUP_SWOUT); } static inline void perf_cgroup_sched_in(struct task_struct *prev, struct task_struct *task) { struct perf_cgroup *cgrp1; struct perf_cgroup *cgrp2 = NULL; /* * we come here when we know perf_cgroup_events > 0 */ cgrp1 = perf_cgroup_from_task(task); /* prev can never be NULL */ cgrp2 = perf_cgroup_from_task(prev); /* * only need to schedule in cgroup events if we are changing * cgroup during ctxsw. Cgroup events were not scheduled * out of ctxsw out if that was not the case. */ if (cgrp1 != cgrp2) perf_cgroup_switch(task, PERF_CGROUP_SWIN); } static inline int perf_cgroup_connect(int fd, struct perf_event *event, struct perf_event_attr *attr, struct perf_event *group_leader) { struct perf_cgroup *cgrp; struct cgroup_subsys_state *css; struct fd f = fdget(fd); int ret = 0; if (!f.file) return -EBADF; css = css_tryget_online_from_dir(f.file->f_dentry, &perf_event_cgrp_subsys); if (IS_ERR(css)) { ret = PTR_ERR(css); goto out; } cgrp = container_of(css, struct perf_cgroup, css); event->cgrp = cgrp; /* * all events in a group must monitor * the same cgroup because a task belongs * to only one perf cgroup at a time */ if (group_leader && group_leader->cgrp != cgrp) { perf_detach_cgroup(event); ret = -EINVAL; } out: fdput(f); return ret; } static inline void perf_cgroup_set_shadow_time(struct perf_event *event, u64 now) { struct perf_cgroup_info *t; t = per_cpu_ptr(event->cgrp->info, event->cpu); event->shadow_ctx_time = now - t->timestamp; } static inline void perf_cgroup_defer_enabled(struct perf_event *event) { /* * when the current task's perf cgroup does not match * the event's, we need to remember to call the * perf_mark_enable() function the first time a task with * a matching perf cgroup is scheduled in. */ if (is_cgroup_event(event) && !perf_cgroup_match(event)) event->cgrp_defer_enabled = 1; } static inline void perf_cgroup_mark_enabled(struct perf_event *event, struct perf_event_context *ctx) { struct perf_event *sub; u64 tstamp = perf_event_time(event); if (!event->cgrp_defer_enabled) return; event->cgrp_defer_enabled = 0; event->tstamp_enabled = tstamp - event->total_time_enabled; list_for_each_entry(sub, &event->sibling_list, group_entry) { if (sub->state >= PERF_EVENT_STATE_INACTIVE) { sub->tstamp_enabled = tstamp - sub->total_time_enabled; sub->cgrp_defer_enabled = 0; } } } #else /* !CONFIG_CGROUP_PERF */ static inline bool perf_cgroup_match(struct perf_event *event) { return true; } static inline void perf_detach_cgroup(struct perf_event *event) {} static inline int is_cgroup_event(struct perf_event *event) { return 0; } static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event) { return 0; } static inline void update_cgrp_time_from_event(struct perf_event *event) { } static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx) { } static inline void perf_cgroup_sched_out(struct task_struct *task, struct task_struct *next) { } static inline void perf_cgroup_sched_in(struct task_struct *prev, struct task_struct *task) { } static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event, struct perf_event_attr *attr, struct perf_event *group_leader) { return -EINVAL; } static inline void perf_cgroup_set_timestamp(struct task_struct *task, struct perf_event_context *ctx) { } void perf_cgroup_switch(struct task_struct *task, struct task_struct *next) { } static inline void perf_cgroup_set_shadow_time(struct perf_event *event, u64 now) { } static inline u64 perf_cgroup_event_time(struct perf_event *event) { return 0; } static inline void perf_cgroup_defer_enabled(struct perf_event *event) { } static inline void perf_cgroup_mark_enabled(struct perf_event *event, struct perf_event_context *ctx) { } #endif /* * set default to be dependent on timer tick just * like original code */ #define PERF_CPU_HRTIMER (1000 / HZ) /* * function must be called with interrupts disbled */ static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr) { struct perf_cpu_context *cpuctx; enum hrtimer_restart ret = HRTIMER_NORESTART; int rotations = 0; WARN_ON(!irqs_disabled()); cpuctx = container_of(hr, struct perf_cpu_context, hrtimer); rotations = perf_rotate_context(cpuctx); /* * arm timer if needed */ if (rotations) { hrtimer_forward_now(hr, cpuctx->hrtimer_interval); ret = HRTIMER_RESTART; } return ret; } /* CPU is going down */ void perf_cpu_hrtimer_cancel(int cpu) { struct perf_cpu_context *cpuctx; struct pmu *pmu; unsigned long flags; if (WARN_ON(cpu != smp_processor_id())) return; local_irq_save(flags); rcu_read_lock(); list_for_each_entry_rcu(pmu, &pmus, entry) { cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); if (pmu->task_ctx_nr == perf_sw_context) continue; hrtimer_cancel(&cpuctx->hrtimer); } rcu_read_unlock(); local_irq_restore(flags); } static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu) { struct hrtimer *hr = &cpuctx->hrtimer; struct pmu *pmu = cpuctx->ctx.pmu; int timer; /* no multiplexing needed for SW PMU */ if (pmu->task_ctx_nr == perf_sw_context) return; /* * check default is sane, if not set then force to * default interval (1/tick) */ timer = pmu->hrtimer_interval_ms; if (timer < 1) timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED); hr->function = perf_cpu_hrtimer_handler; } static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx) { struct hrtimer *hr = &cpuctx->hrtimer; struct pmu *pmu = cpuctx->ctx.pmu; /* not for SW PMU */ if (pmu->task_ctx_nr == perf_sw_context) return; if (hrtimer_active(hr)) return; if (!hrtimer_callback_running(hr)) __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval, 0, HRTIMER_MODE_REL_PINNED, 0); } void perf_pmu_disable(struct pmu *pmu) { int *count = this_cpu_ptr(pmu->pmu_disable_count); if (!(*count)++) pmu->pmu_disable(pmu); } void perf_pmu_enable(struct pmu *pmu) { int *count = this_cpu_ptr(pmu->pmu_disable_count); if (!--(*count)) pmu->pmu_enable(pmu); } static DEFINE_PER_CPU(struct list_head, rotation_list); /* * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized * because they're strictly cpu affine and rotate_start is called with IRQs * disabled, while rotate_context is called from IRQ context. */ static void perf_pmu_rotate_start(struct pmu *pmu) { struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); struct list_head *head = &__get_cpu_var(rotation_list); WARN_ON(!irqs_disabled()); if (list_empty(&cpuctx->rotation_list)) list_add(&cpuctx->rotation_list, head); } static void get_ctx(struct perf_event_context *ctx) { WARN_ON(!atomic_inc_not_zero(&ctx->refcount)); } static void put_ctx(struct perf_event_context *ctx) { if (atomic_dec_and_test(&ctx->refcount)) { if (ctx->parent_ctx) put_ctx(ctx->parent_ctx); if (ctx->task) put_task_struct(ctx->task); kfree_rcu(ctx, rcu_head); } } static void unclone_ctx(struct perf_event_context *ctx) { if (ctx->parent_ctx) { put_ctx(ctx->parent_ctx); ctx->parent_ctx = NULL; } ctx->generation++; } static u32 perf_event_pid(struct perf_event *event, struct task_struct *p) { /* * only top level events have the pid namespace they were created in */ if (event->parent) event = event->parent; return task_tgid_nr_ns(p, event->ns); } static u32 perf_event_tid(struct perf_event *event, struct task_struct *p) { /* * only top level events have the pid namespace they were created in */ if (event->parent) event = event->parent; return task_pid_nr_ns(p, event->ns); } /* * If we inherit events we want to return the parent event id * to userspace. */ static u64 primary_event_id(struct perf_event *event) { u64 id = event->id; if (event->parent) id = event->parent->id; return id; } /* * Get the perf_event_context for a task and lock it. * This has to cope with with the fact that until it is locked, * the context could get moved to another task. */ static struct perf_event_context * perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags) { struct perf_event_context *ctx; retry: /* * One of the few rules of preemptible RCU is that one cannot do * rcu_read_unlock() while holding a scheduler (or nested) lock when * part of the read side critical section was preemptible -- see * rcu_read_unlock_special(). * * Since ctx->lock nests under rq->lock we must ensure the entire read * side critical section is non-preemptible. */ preempt_disable(); rcu_read_lock(); ctx = rcu_dereference(task->perf_event_ctxp[ctxn]); if (ctx) { /* * If this context is a clone of another, it might * get swapped for another underneath us by * perf_event_task_sched_out, though the * rcu_read_lock() protects us from any context * getting freed. Lock the context and check if it * got swapped before we could get the lock, and retry * if so. If we locked the right context, then it * can't get swapped on us any more. */ raw_spin_lock_irqsave(&ctx->lock, *flags); if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) { raw_spin_unlock_irqrestore(&ctx->lock, *flags); rcu_read_unlock(); preempt_enable(); goto retry; } if (!atomic_inc_not_zero(&ctx->refcount)) { raw_spin_unlock_irqrestore(&ctx->lock, *flags); ctx = NULL; } } rcu_read_unlock(); preempt_enable(); return ctx; } /* * Get the context for a task and increment its pin_count so it * can't get swapped to another task. This also increments its * reference count so that the context can't get freed. */ static struct perf_event_context * perf_pin_task_context(struct task_struct *task, int ctxn) { struct perf_event_context *ctx; unsigned long flags; ctx = perf_lock_task_context(task, ctxn, &flags); if (ctx) { ++ctx->pin_count; raw_spin_unlock_irqrestore(&ctx->lock, flags); } return ctx; } static void perf_unpin_context(struct perf_event_context *ctx) { unsigned long flags; raw_spin_lock_irqsave(&ctx->lock, flags); --ctx->pin_count; raw_spin_unlock_irqrestore(&ctx->lock, flags); } /* * Update the record of the current time in a context. */ static void update_context_time(struct perf_event_context *ctx) { u64 now = perf_clock(); ctx->time += now - ctx->timestamp; ctx->timestamp = now; } static u64 perf_event_time(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; if (is_cgroup_event(event)) return perf_cgroup_event_time(event); return ctx ? ctx->time : 0; } /* * Update the total_time_enabled and total_time_running fields for a event. * The caller of this function needs to hold the ctx->lock. */ static void update_event_times(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; u64 run_end; if (event->state < PERF_EVENT_STATE_INACTIVE || event->group_leader->state < PERF_EVENT_STATE_INACTIVE) return; /* * in cgroup mode, time_enabled represents * the time the event was enabled AND active * tasks were in the monitored cgroup. This is * independent of the activity of the context as * there may be a mix of cgroup and non-cgroup events. * * That is why we treat cgroup events differently * here. */ if (is_cgroup_event(event)) run_end = perf_cgroup_event_time(event); else if (ctx->is_active) run_end = ctx->time; else run_end = event->tstamp_stopped; event->total_time_enabled = run_end - event->tstamp_enabled; if (event->state == PERF_EVENT_STATE_INACTIVE) run_end = event->tstamp_stopped; else run_end = perf_event_time(event); event->total_time_running = run_end - event->tstamp_running; } /* * Update total_time_enabled and total_time_running for all events in a group. */ static void update_group_times(struct perf_event *leader) { struct perf_event *event; update_event_times(leader); list_for_each_entry(event, &leader->sibling_list, group_entry) update_event_times(event); } static struct list_head * ctx_group_list(struct perf_event *event, struct perf_event_context *ctx) { if (event->attr.pinned) return &ctx->pinned_groups; else return &ctx->flexible_groups; } /* * Add a event from the lists for its context. * Must be called with ctx->mutex and ctx->lock held. */ static void list_add_event(struct perf_event *event, struct perf_event_context *ctx) { WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); event->attach_state |= PERF_ATTACH_CONTEXT; /* * If we're a stand alone event or group leader, we go to the context * list, group events are kept attached to the group so that * perf_group_detach can, at all times, locate all siblings. */ if (event->group_leader == event) { struct list_head *list; if (is_software_event(event)) event->group_flags |= PERF_GROUP_SOFTWARE; list = ctx_group_list(event, ctx); list_add_tail(&event->group_entry, list); } if (is_cgroup_event(event)) ctx->nr_cgroups++; if (has_branch_stack(event)) ctx->nr_branch_stack++; list_add_rcu(&event->event_entry, &ctx->event_list); if (!ctx->nr_events) perf_pmu_rotate_start(ctx->pmu); ctx->nr_events++; if (event->attr.inherit_stat) ctx->nr_stat++; ctx->generation++; } /* * Initialize event state based on the perf_event_attr::disabled. */ static inline void perf_event__state_init(struct perf_event *event) { event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF : PERF_EVENT_STATE_INACTIVE; } /* * Called at perf_event creation and when events are attached/detached from a * group. */ static void perf_event__read_size(struct perf_event *event) { int entry = sizeof(u64); /* value */ int size = 0; int nr = 1; if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) size += sizeof(u64); if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) size += sizeof(u64); if (event->attr.read_format & PERF_FORMAT_ID) entry += sizeof(u64); if (event->attr.read_format & PERF_FORMAT_GROUP) { nr += event->group_leader->nr_siblings; size += sizeof(u64); } size += entry * nr; event->read_size = size; } static void perf_event__header_size(struct perf_event *event) { struct perf_sample_data *data; u64 sample_type = event->attr.sample_type; u16 size = 0; perf_event__read_size(event); if (sample_type & PERF_SAMPLE_IP) size += sizeof(data->ip); if (sample_type & PERF_SAMPLE_ADDR) size += sizeof(data->addr); if (sample_type & PERF_SAMPLE_PERIOD) size += sizeof(data->period); if (sample_type & PERF_SAMPLE_WEIGHT) size += sizeof(data->weight); if (sample_type & PERF_SAMPLE_READ) size += event->read_size; if (sample_type & PERF_SAMPLE_DATA_SRC) size += sizeof(data->data_src.val); if (sample_type & PERF_SAMPLE_TRANSACTION) size += sizeof(data->txn); event->header_size = size; } static void perf_event__id_header_size(struct perf_event *event) { struct perf_sample_data *data; u64 sample_type = event->attr.sample_type; u16 size = 0; if (sample_type & PERF_SAMPLE_TID) size += sizeof(data->tid_entry); if (sample_type & PERF_SAMPLE_TIME) size += sizeof(data->time); if (sample_type & PERF_SAMPLE_IDENTIFIER) size += sizeof(data->id); if (sample_type & PERF_SAMPLE_ID) size += sizeof(data->id); if (sample_type & PERF_SAMPLE_STREAM_ID) size += sizeof(data->stream_id); if (sample_type & PERF_SAMPLE_CPU) size += sizeof(data->cpu_entry); event->id_header_size = size; } static void perf_group_attach(struct perf_event *event) { struct perf_event *group_leader = event->group_leader, *pos; /* * We can have double attach due to group movement in perf_event_open. */ if (event->attach_state & PERF_ATTACH_GROUP) return; event->attach_state |= PERF_ATTACH_GROUP; if (group_leader == event) return; if (group_leader->group_flags & PERF_GROUP_SOFTWARE && !is_software_event(event)) group_leader->group_flags &= ~PERF_GROUP_SOFTWARE; list_add_tail(&event->group_entry, &group_leader->sibling_list); group_leader->nr_siblings++; perf_event__header_size(group_leader); list_for_each_entry(pos, &group_leader->sibling_list, group_entry) perf_event__header_size(pos); } /* * Remove a event from the lists for its context. * Must be called with ctx->mutex and ctx->lock held. */ static void list_del_event(struct perf_event *event, struct perf_event_context *ctx) { struct perf_cpu_context *cpuctx; /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_CONTEXT)) return; event->attach_state &= ~PERF_ATTACH_CONTEXT; if (is_cgroup_event(event)) { ctx->nr_cgroups--; cpuctx = __get_cpu_context(ctx); /* * if there are no more cgroup events * then cler cgrp to avoid stale pointer * in update_cgrp_time_from_cpuctx() */ if (!ctx->nr_cgroups) cpuctx->cgrp = NULL; } if (has_branch_stack(event)) ctx->nr_branch_stack--; ctx->nr_events--; if (event->attr.inherit_stat) ctx->nr_stat--; list_del_rcu(&event->event_entry); if (event->group_leader == event) list_del_init(&event->group_entry); update_group_times(event); /* * If event was in error state, then keep it * that way, otherwise bogus counts will be * returned on read(). The only way to get out * of error state is by explicit re-enabling * of the event */ if (event->state > PERF_EVENT_STATE_OFF) event->state = PERF_EVENT_STATE_OFF; ctx->generation++; } static void perf_group_detach(struct perf_event *event) { struct perf_event *sibling, *tmp; struct list_head *list = NULL; /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_GROUP)) return; event->attach_state &= ~PERF_ATTACH_GROUP; /* * If this is a sibling, remove it from its group. */ if (event->group_leader != event) { list_del_init(&event->group_entry); event->group_leader->nr_siblings--; goto out; } if (!list_empty(&event->group_entry)) list = &event->group_entry; /* * If this was a group event with sibling events then * upgrade the siblings to singleton events by adding them * to whatever list we are on. */ list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) { if (list) list_move_tail(&sibling->group_entry, list); sibling->group_leader = sibling; /* Inherit group flags from the previous leader */ sibling->group_flags = event->group_flags; } out: perf_event__header_size(event->group_leader); list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry) perf_event__header_size(tmp); } static inline int event_filter_match(struct perf_event *event) { return (event->cpu == -1 || event->cpu == smp_processor_id()) && perf_cgroup_match(event); } static void event_sched_out(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); u64 delta; /* * An event which could not be activated because of * filter mismatch still needs to have its timings * maintained, otherwise bogus information is return * via read() for time_enabled, time_running: */ if (event->state == PERF_EVENT_STATE_INACTIVE && !event_filter_match(event)) { delta = tstamp - event->tstamp_stopped; event->tstamp_running += delta; event->tstamp_stopped = tstamp; } if (event->state != PERF_EVENT_STATE_ACTIVE) return; perf_pmu_disable(event->pmu); event->state = PERF_EVENT_STATE_INACTIVE; if (event->pending_disable) { event->pending_disable = 0; event->state = PERF_EVENT_STATE_OFF; } event->tstamp_stopped = tstamp; event->pmu->del(event, 0); event->oncpu = -1; if (!is_software_event(event)) cpuctx->active_oncpu--; ctx->nr_active--; if (event->attr.freq && event->attr.sample_freq) ctx->nr_freq--; if (event->attr.exclusive || !cpuctx->active_oncpu) cpuctx->exclusive = 0; perf_pmu_enable(event->pmu); } static void group_sched_out(struct perf_event *group_event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { struct perf_event *event; int state = group_event->state; event_sched_out(group_event, cpuctx, ctx); /* * Schedule out siblings (if any): */ list_for_each_entry(event, &group_event->sibling_list, group_entry) event_sched_out(event, cpuctx, ctx); if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive) cpuctx->exclusive = 0; } struct remove_event { struct perf_event *event; bool detach_group; }; /* * Cross CPU call to remove a performance event * * We disable the event on the hardware level first. After that we * remove it from the context list. */ static int __perf_remove_from_context(void *info) { struct remove_event *re = info; struct perf_event *event = re->event; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); raw_spin_lock(&ctx->lock); event_sched_out(event, cpuctx, ctx); if (re->detach_group) perf_group_detach(event); list_del_event(event, ctx); if (!ctx->nr_events && cpuctx->task_ctx == ctx) { ctx->is_active = 0; cpuctx->task_ctx = NULL; } raw_spin_unlock(&ctx->lock); return 0; } /* * Remove the event from a task's (or a CPU's) list of events. * * CPU events are removed with a smp call. For task events we only * call when the task is on a CPU. * * If event->ctx is a cloned context, callers must make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This is OK when called from perf_release since * that only calls us on the top-level context, which can't be a clone. * When called from perf_event_exit_task, it's OK because the * context has been detached from its task. */ static void perf_remove_from_context(struct perf_event *event, bool detach_group) { struct perf_event_context *ctx = event->ctx; struct task_struct *task = ctx->task; struct remove_event re = { .event = event, .detach_group = detach_group, }; lockdep_assert_held(&ctx->mutex); if (!task) { /* * Per cpu events are removed via an smp call and * the removal is always successful. */ cpu_function_call(event->cpu, __perf_remove_from_context, &re); return; } retry: if (!task_function_call(task, __perf_remove_from_context, &re)) return; raw_spin_lock_irq(&ctx->lock); /* * If we failed to find a running task, but find the context active now * that we've acquired the ctx->lock, retry. */ if (ctx->is_active) { raw_spin_unlock_irq(&ctx->lock); goto retry; } /* * Since the task isn't running, its safe to remove the event, us * holding the ctx->lock ensures the task won't get scheduled in. */ if (detach_group) perf_group_detach(event); list_del_event(event, ctx); raw_spin_unlock_irq(&ctx->lock); } /* * Cross CPU call to disable a performance event */ int __perf_event_disable(void *info) { struct perf_event *event = info; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); /* * If this is a per-task event, need to check whether this * event's task is the current task on this cpu. * * Can trigger due to concurrent perf_event_context_sched_out() * flipping contexts around. */ if (ctx->task && cpuctx->task_ctx != ctx) return -EINVAL; raw_spin_lock(&ctx->lock); /* * If the event is on, turn it off. * If it is in error state, leave it in error state. */ if (event->state >= PERF_EVENT_STATE_INACTIVE) { update_context_time(ctx); update_cgrp_time_from_event(event); update_group_times(event); if (event == event->group_leader) group_sched_out(event, cpuctx, ctx); else event_sched_out(event, cpuctx, ctx); event->state = PERF_EVENT_STATE_OFF; } raw_spin_unlock(&ctx->lock); return 0; } /* * Disable a event. * * If event->ctx is a cloned context, callers must make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This condition is satisifed when called through * perf_event_for_each_child or perf_event_for_each because they * hold the top-level event's child_mutex, so any descendant that * goes to exit will block in sync_child_event. * When called from perf_pending_event it's OK because event->ctx * is the current context on this CPU and preemption is disabled, * hence we can't get into perf_event_task_sched_out for this context. */ void perf_event_disable(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct task_struct *task = ctx->task; if (!task) { /* * Disable the event on the cpu that it's on */ cpu_function_call(event->cpu, __perf_event_disable, event); return; } retry: if (!task_function_call(task, __perf_event_disable, event)) return; raw_spin_lock_irq(&ctx->lock); /* * If the event is still active, we need to retry the cross-call. */ if (event->state == PERF_EVENT_STATE_ACTIVE) { raw_spin_unlock_irq(&ctx->lock); /* * Reload the task pointer, it might have been changed by * a concurrent perf_event_context_sched_out(). */ task = ctx->task; goto retry; } /* * Since we have the lock this context can't be scheduled * in, so we can change the state safely. */ if (event->state == PERF_EVENT_STATE_INACTIVE) { update_group_times(event); event->state = PERF_EVENT_STATE_OFF; } raw_spin_unlock_irq(&ctx->lock); } EXPORT_SYMBOL_GPL(perf_event_disable); static void perf_set_shadow_time(struct perf_event *event, struct perf_event_context *ctx, u64 tstamp) { /* * use the correct time source for the time snapshot * * We could get by without this by leveraging the * fact that to get to this function, the caller * has most likely already called update_context_time() * and update_cgrp_time_xx() and thus both timestamp * are identical (or very close). Given that tstamp is, * already adjusted for cgroup, we could say that: * tstamp - ctx->timestamp * is equivalent to * tstamp - cgrp->timestamp. * * Then, in perf_output_read(), the calculation would * work with no changes because: * - event is guaranteed scheduled in * - no scheduled out in between * - thus the timestamp would be the same * * But this is a bit hairy. * * So instead, we have an explicit cgroup call to remain * within the time time source all along. We believe it * is cleaner and simpler to understand. */ if (is_cgroup_event(event)) perf_cgroup_set_shadow_time(event, tstamp); else event->shadow_ctx_time = tstamp - ctx->timestamp; } #define MAX_INTERRUPTS (~0ULL) static void perf_log_throttle(struct perf_event *event, int enable); static int event_sched_in(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); int ret = 0; lockdep_assert_held(&ctx->lock); if (event->state <= PERF_EVENT_STATE_OFF) return 0; event->state = PERF_EVENT_STATE_ACTIVE; event->oncpu = smp_processor_id(); /* * Unthrottle events, since we scheduled we might have missed several * ticks already, also for a heavily scheduling task there is little * guarantee it'll get a tick in a timely manner. */ if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) { perf_log_throttle(event, 1); event->hw.interrupts = 0; } /* * The new state must be visible before we turn it on in the hardware: */ smp_wmb(); perf_pmu_disable(event->pmu); if (event->pmu->add(event, PERF_EF_START)) { event->state = PERF_EVENT_STATE_INACTIVE; event->oncpu = -1; ret = -EAGAIN; goto out; } event->tstamp_running += tstamp - event->tstamp_stopped; perf_set_shadow_time(event, ctx, tstamp); if (!is_software_event(event)) cpuctx->active_oncpu++; ctx->nr_active++; if (event->attr.freq && event->attr.sample_freq) ctx->nr_freq++; if (event->attr.exclusive) cpuctx->exclusive = 1; out: perf_pmu_enable(event->pmu); return ret; } static int group_sched_in(struct perf_event *group_event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { struct perf_event *event, *partial_group = NULL; struct pmu *pmu = ctx->pmu; u64 now = ctx->time; bool simulate = false; if (group_event->state == PERF_EVENT_STATE_OFF) return 0; pmu->start_txn(pmu); if (event_sched_in(group_event, cpuctx, ctx)) { pmu->cancel_txn(pmu); perf_cpu_hrtimer_restart(cpuctx); return -EAGAIN; } /* * Schedule in siblings as one group (if any): */ list_for_each_entry(event, &group_event->sibling_list, group_entry) { if (event_sched_in(event, cpuctx, ctx)) { partial_group = event; goto group_error; } } if (!pmu->commit_txn(pmu)) return 0; group_error: /* * Groups can be scheduled in as one unit only, so undo any * partial group before returning: * The events up to the failed event are scheduled out normally, * tstamp_stopped will be updated. * * The failed events and the remaining siblings need to have * their timings updated as if they had gone thru event_sched_in() * and event_sched_out(). This is required to get consistent timings * across the group. This also takes care of the case where the group * could never be scheduled by ensuring tstamp_stopped is set to mark * the time the event was actually stopped, such that time delta * calculation in update_event_times() is correct. */ list_for_each_entry(event, &group_event->sibling_list, group_entry) { if (event == partial_group) simulate = true; if (simulate) { event->tstamp_running += now - event->tstamp_stopped; event->tstamp_stopped = now; } else { event_sched_out(event, cpuctx, ctx); } } event_sched_out(group_event, cpuctx, ctx); pmu->cancel_txn(pmu); perf_cpu_hrtimer_restart(cpuctx); return -EAGAIN; } /* * Work out whether we can put this event group on the CPU now. */ static int group_can_go_on(struct perf_event *event, struct perf_cpu_context *cpuctx, int can_add_hw) { /* * Groups consisting entirely of software events can always go on. */ if (event->group_flags & PERF_GROUP_SOFTWARE) return 1; /* * If an exclusive group is already on, no other hardware * events can go on. */ if (cpuctx->exclusive) return 0; /* * If this group is exclusive and there are already * events on the CPU, it can't go on. */ if (event->attr.exclusive && cpuctx->active_oncpu) return 0; /* * Otherwise, try to add it if all previous groups were able * to go on. */ return can_add_hw; } static void add_event_to_ctx(struct perf_event *event, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); list_add_event(event, ctx); perf_group_attach(event); event->tstamp_enabled = tstamp; event->tstamp_running = tstamp; event->tstamp_stopped = tstamp; } static void task_ctx_sched_out(struct perf_event_context *ctx); static void ctx_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task); static void perf_event_sched_in(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, struct task_struct *task) { cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task); if (ctx) ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task); cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task); if (ctx) ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task); } /* * Cross CPU call to install and enable a performance event * * Must be called with ctx->mutex held */ static int __perf_install_in_context(void *info) { struct perf_event *event = info; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); struct perf_event_context *task_ctx = cpuctx->task_ctx; struct task_struct *task = current; perf_ctx_lock(cpuctx, task_ctx); perf_pmu_disable(cpuctx->ctx.pmu); /* * If there was an active task_ctx schedule it out. */ if (task_ctx) task_ctx_sched_out(task_ctx); /* * If the context we're installing events in is not the * active task_ctx, flip them. */ if (ctx->task && task_ctx != ctx) { if (task_ctx) raw_spin_unlock(&task_ctx->lock); raw_spin_lock(&ctx->lock); task_ctx = ctx; } if (task_ctx) { cpuctx->task_ctx = task_ctx; task = task_ctx->task; } cpu_ctx_sched_out(cpuctx, EVENT_ALL); update_context_time(ctx); /* * update cgrp time only if current cgrp * matches event->cgrp. Must be done before * calling add_event_to_ctx() */ update_cgrp_time_from_event(event); add_event_to_ctx(event, ctx); /* * Schedule everything back in */ perf_event_sched_in(cpuctx, task_ctx, task); perf_pmu_enable(cpuctx->ctx.pmu); perf_ctx_unlock(cpuctx, task_ctx); return 0; } /* * Attach a performance event to a context * * First we add the event to the list with the hardware enable bit * in event->hw_config cleared. * * If the event is attached to a task which is on a CPU we use a smp * call to enable it in the task context. The task might have been * scheduled away, but we check this in the smp call again. */ static void perf_install_in_context(struct perf_event_context *ctx, struct perf_event *event, int cpu) { struct task_struct *task = ctx->task; lockdep_assert_held(&ctx->mutex); event->ctx = ctx; if (event->cpu != -1) event->cpu = cpu; if (!task) { /* * Per cpu events are installed via an smp call and * the install is always successful. */ cpu_function_call(cpu, __perf_install_in_context, event); return; } retry: if (!task_function_call(task, __perf_install_in_context, event)) return; raw_spin_lock_irq(&ctx->lock); /* * If we failed to find a running task, but find the context active now * that we've acquired the ctx->lock, retry. */ if (ctx->is_active) { raw_spin_unlock_irq(&ctx->lock); goto retry; } /* * Since the task isn't running, its safe to add the event, us holding * the ctx->lock ensures the task won't get scheduled in. */ add_event_to_ctx(event, ctx); raw_spin_unlock_irq(&ctx->lock); } /* * Put a event into inactive state and update time fields. * Enabling the leader of a group effectively enables all * the group members that aren't explicitly disabled, so we * have to update their ->tstamp_enabled also. * Note: this works for group members as well as group leaders * since the non-leader members' sibling_lists will be empty. */ static void __perf_event_mark_enabled(struct perf_event *event) { struct perf_event *sub; u64 tstamp = perf_event_time(event); event->state = PERF_EVENT_STATE_INACTIVE; event->tstamp_enabled = tstamp - event->total_time_enabled; list_for_each_entry(sub, &event->sibling_list, group_entry) { if (sub->state >= PERF_EVENT_STATE_INACTIVE) sub->tstamp_enabled = tstamp - sub->total_time_enabled; } } /* * Cross CPU call to enable a performance event */ static int __perf_event_enable(void *info) { struct perf_event *event = info; struct perf_event_context *ctx = event->ctx; struct perf_event *leader = event->group_leader; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); int err; /* * There's a time window between 'ctx->is_active' check * in perf_event_enable function and this place having: * - IRQs on * - ctx->lock unlocked * * where the task could be killed and 'ctx' deactivated * by perf_event_exit_task. */ if (!ctx->is_active) return -EINVAL; raw_spin_lock(&ctx->lock); update_context_time(ctx); if (event->state >= PERF_EVENT_STATE_INACTIVE) goto unlock; /* * set current task's cgroup time reference point */ perf_cgroup_set_timestamp(current, ctx); __perf_event_mark_enabled(event); if (!event_filter_match(event)) { if (is_cgroup_event(event)) perf_cgroup_defer_enabled(event); goto unlock; } /* * If the event is in a group and isn't the group leader, * then don't put it on unless the group is on. */ if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) goto unlock; if (!group_can_go_on(event, cpuctx, 1)) { err = -EEXIST; } else { if (event == leader) err = group_sched_in(event, cpuctx, ctx); else err = event_sched_in(event, cpuctx, ctx); } if (err) { /* * If this event can't go on and it's part of a * group, then the whole group has to come off. */ if (leader != event) { group_sched_out(leader, cpuctx, ctx); perf_cpu_hrtimer_restart(cpuctx); } if (leader->attr.pinned) { update_group_times(leader); leader->state = PERF_EVENT_STATE_ERROR; } } unlock: raw_spin_unlock(&ctx->lock); return 0; } /* * Enable a event. * * If event->ctx is a cloned context, callers must make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This condition is satisfied when called through * perf_event_for_each_child or perf_event_for_each as described * for perf_event_disable. */ void perf_event_enable(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct task_struct *task = ctx->task; if (!task) { /* * Enable the event on the cpu that it's on */ cpu_function_call(event->cpu, __perf_event_enable, event); return; } raw_spin_lock_irq(&ctx->lock); if (event->state >= PERF_EVENT_STATE_INACTIVE) goto out; /* * If the event is in error state, clear that first. * That way, if we see the event in error state below, we * know that it has gone back into error state, as distinct * from the task having been scheduled away before the * cross-call arrived. */ if (event->state == PERF_EVENT_STATE_ERROR) event->state = PERF_EVENT_STATE_OFF; retry: if (!ctx->is_active) { __perf_event_mark_enabled(event); goto out; } raw_spin_unlock_irq(&ctx->lock); if (!task_function_call(task, __perf_event_enable, event)) return; raw_spin_lock_irq(&ctx->lock); /* * If the context is active and the event is still off, * we need to retry the cross-call. */ if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) { /* * task could have been flipped by a concurrent * perf_event_context_sched_out() */ task = ctx->task; goto retry; } out: raw_spin_unlock_irq(&ctx->lock); } EXPORT_SYMBOL_GPL(perf_event_enable); int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } EXPORT_SYMBOL_GPL(perf_event_refresh); static void ctx_sched_out(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type) { struct perf_event *event; int is_active = ctx->is_active; ctx->is_active &= ~event_type; if (likely(!ctx->nr_events)) return; update_context_time(ctx); update_cgrp_time_from_cpuctx(cpuctx); if (!ctx->nr_active) return; perf_pmu_disable(ctx->pmu); if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) { list_for_each_entry(event, &ctx->pinned_groups, group_entry) group_sched_out(event, cpuctx, ctx); } if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) { list_for_each_entry(event, &ctx->flexible_groups, group_entry) group_sched_out(event, cpuctx, ctx); } perf_pmu_enable(ctx->pmu); } /* * Test whether two contexts are equivalent, i.e. whether they have both been * cloned from the same version of the same context. * * Equivalence is measured using a generation number in the context that is * incremented on each modification to it; see unclone_ctx(), list_add_event() * and list_del_event(). */ static int context_equiv(struct perf_event_context *ctx1, struct perf_event_context *ctx2) { /* Pinning disables the swap optimization */ if (ctx1->pin_count || ctx2->pin_count) return 0; /* If ctx1 is the parent of ctx2 */ if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen) return 1; /* If ctx2 is the parent of ctx1 */ if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation) return 1; /* * If ctx1 and ctx2 have the same parent; we flatten the parent * hierarchy, see perf_event_init_context(). */ if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx && ctx1->parent_gen == ctx2->parent_gen) return 1; /* Unmatched */ return 0; } static void __perf_event_sync_stat(struct perf_event *event, struct perf_event *next_event) { u64 value; if (!event->attr.inherit_stat) return; /* * Update the event value, we cannot use perf_event_read() * because we're in the middle of a context switch and have IRQs * disabled, which upsets smp_call_function_single(), however * we know the event must be on the current CPU, therefore we * don't need to use it. */ switch (event->state) { case PERF_EVENT_STATE_ACTIVE: event->pmu->read(event); /* fall-through */ case PERF_EVENT_STATE_INACTIVE: update_event_times(event); break; default: break; } /* * In order to keep per-task stats reliable we need to flip the event * values when we flip the contexts. */ value = local64_read(&next_event->count); value = local64_xchg(&event->count, value); local64_set(&next_event->count, value); swap(event->total_time_enabled, next_event->total_time_enabled); swap(event->total_time_running, next_event->total_time_running); /* * Since we swizzled the values, update the user visible data too. */ perf_event_update_userpage(event); perf_event_update_userpage(next_event); } static void perf_event_sync_stat(struct perf_event_context *ctx, struct perf_event_context *next_ctx) { struct perf_event *event, *next_event; if (!ctx->nr_stat) return; update_context_time(ctx); event = list_first_entry(&ctx->event_list, struct perf_event, event_entry); next_event = list_first_entry(&next_ctx->event_list, struct perf_event, event_entry); while (&event->event_entry != &ctx->event_list && &next_event->event_entry != &next_ctx->event_list) { __perf_event_sync_stat(event, next_event); event = list_next_entry(event, event_entry); next_event = list_next_entry(next_event, event_entry); } } static void perf_event_context_sched_out(struct task_struct *task, int ctxn, struct task_struct *next) { struct perf_event_context *ctx = task->perf_event_ctxp[ctxn]; struct perf_event_context *next_ctx; struct perf_event_context *parent, *next_parent; struct perf_cpu_context *cpuctx; int do_switch = 1; if (likely(!ctx)) return; cpuctx = __get_cpu_context(ctx); if (!cpuctx->task_ctx) return; rcu_read_lock(); next_ctx = next->perf_event_ctxp[ctxn]; if (!next_ctx) goto unlock; parent = rcu_dereference(ctx->parent_ctx); next_parent = rcu_dereference(next_ctx->parent_ctx); /* If neither context have a parent context; they cannot be clones. */ if (!parent || !next_parent) goto unlock; if (next_parent == ctx || next_ctx == parent || next_parent == parent) { /* * Looks like the two contexts are clones, so we might be * able to optimize the context switch. We lock both * contexts and check that they are clones under the * lock (including re-checking that neither has been * uncloned in the meantime). It doesn't matter which * order we take the locks because no other cpu could * be trying to lock both of these tasks. */ raw_spin_lock(&ctx->lock); raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING); if (context_equiv(ctx, next_ctx)) { /* * XXX do we need a memory barrier of sorts * wrt to rcu_dereference() of perf_event_ctxp */ task->perf_event_ctxp[ctxn] = next_ctx; next->perf_event_ctxp[ctxn] = ctx; ctx->task = next; next_ctx->task = task; do_switch = 0; perf_event_sync_stat(ctx, next_ctx); } raw_spin_unlock(&next_ctx->lock); raw_spin_unlock(&ctx->lock); } unlock: rcu_read_unlock(); if (do_switch) { raw_spin_lock(&ctx->lock); ctx_sched_out(ctx, cpuctx, EVENT_ALL); cpuctx->task_ctx = NULL; raw_spin_unlock(&ctx->lock); } } #define for_each_task_context_nr(ctxn) \ for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++) /* * Called from scheduler to remove the events of the current task, * with interrupts disabled. * * We stop each event and update the event value in event->count. * * This does not protect us against NMI, but disable() * sets the disabled bit in the control field of event _before_ * accessing the event control register. If a NMI hits, then it will * not restart the event. */ void __perf_event_task_sched_out(struct task_struct *task, struct task_struct *next) { int ctxn; for_each_task_context_nr(ctxn) perf_event_context_sched_out(task, ctxn, next); /* * if cgroup events exist on this CPU, then we need * to check if we have to switch out PMU state. * cgroup event are system-wide mode only */ if (atomic_read(&__get_cpu_var(perf_cgroup_events))) perf_cgroup_sched_out(task, next); } static void task_ctx_sched_out(struct perf_event_context *ctx) { struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); if (!cpuctx->task_ctx) return; if (WARN_ON_ONCE(ctx != cpuctx->task_ctx)) return; ctx_sched_out(ctx, cpuctx, EVENT_ALL); cpuctx->task_ctx = NULL; } /* * Called with IRQs disabled */ static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx, enum event_type_t event_type) { ctx_sched_out(&cpuctx->ctx, cpuctx, event_type); } static void ctx_pinned_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx) { struct perf_event *event; list_for_each_entry(event, &ctx->pinned_groups, group_entry) { if (event->state <= PERF_EVENT_STATE_OFF) continue; if (!event_filter_match(event)) continue; /* may need to reset tstamp_enabled */ if (is_cgroup_event(event)) perf_cgroup_mark_enabled(event, ctx); if (group_can_go_on(event, cpuctx, 1)) group_sched_in(event, cpuctx, ctx); /* * If this pinned group hasn't been scheduled, * put it in error state. */ if (event->state == PERF_EVENT_STATE_INACTIVE) { update_group_times(event); event->state = PERF_EVENT_STATE_ERROR; } } } static void ctx_flexible_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx) { struct perf_event *event; int can_add_hw = 1; list_for_each_entry(event, &ctx->flexible_groups, group_entry) { /* Ignore events in OFF or ERROR state */ if (event->state <= PERF_EVENT_STATE_OFF) continue; /* * Listen to the 'cpu' scheduling filter constraint * of events: */ if (!event_filter_match(event)) continue; /* may need to reset tstamp_enabled */ if (is_cgroup_event(event)) perf_cgroup_mark_enabled(event, ctx); if (group_can_go_on(event, cpuctx, can_add_hw)) { if (group_sched_in(event, cpuctx, ctx)) can_add_hw = 0; } } } static void ctx_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task) { u64 now; int is_active = ctx->is_active; ctx->is_active |= event_type; if (likely(!ctx->nr_events)) return; now = perf_clock(); ctx->timestamp = now; perf_cgroup_set_timestamp(task, ctx); /* * First go through the list and put on any pinned groups * in order to give them the best chance of going on. */ if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) ctx_pinned_sched_in(ctx, cpuctx); /* Then walk through the lower prio flexible groups */ if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) ctx_flexible_sched_in(ctx, cpuctx); } static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task) { struct perf_event_context *ctx = &cpuctx->ctx; ctx_sched_in(ctx, cpuctx, event_type, task); } static void perf_event_context_sched_in(struct perf_event_context *ctx, struct task_struct *task) { struct perf_cpu_context *cpuctx; cpuctx = __get_cpu_context(ctx); if (cpuctx->task_ctx == ctx) return; perf_ctx_lock(cpuctx, ctx); perf_pmu_disable(ctx->pmu); /* * We want to keep the following priority order: * cpu pinned (that don't need to move), task pinned, * cpu flexible, task flexible. */ cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); if (ctx->nr_events) cpuctx->task_ctx = ctx; perf_event_sched_in(cpuctx, cpuctx->task_ctx, task); perf_pmu_enable(ctx->pmu); perf_ctx_unlock(cpuctx, ctx); /* * Since these rotations are per-cpu, we need to ensure the * cpu-context we got scheduled on is actually rotating. */ perf_pmu_rotate_start(ctx->pmu); } /* * When sampling the branck stack in system-wide, it may be necessary * to flush the stack on context switch. This happens when the branch * stack does not tag its entries with the pid of the current task. * Otherwise it becomes impossible to associate a branch entry with a * task. This ambiguity is more likely to appear when the branch stack * supports priv level filtering and the user sets it to monitor only * at the user level (which could be a useful measurement in system-wide * mode). In that case, the risk is high of having a branch stack with * branch from multiple tasks. Flushing may mean dropping the existing * entries or stashing them somewhere in the PMU specific code layer. * * This function provides the context switch callback to the lower code * layer. It is invoked ONLY when there is at least one system-wide context * with at least one active event using taken branch sampling. */ static void perf_branch_stack_sched_in(struct task_struct *prev, struct task_struct *task) { struct perf_cpu_context *cpuctx; struct pmu *pmu; unsigned long flags; /* no need to flush branch stack if not changing task */ if (prev == task) return; local_irq_save(flags); rcu_read_lock(); list_for_each_entry_rcu(pmu, &pmus, entry) { cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); /* * check if the context has at least one * event using PERF_SAMPLE_BRANCH_STACK */ if (cpuctx->ctx.nr_branch_stack > 0 && pmu->flush_branch_stack) { perf_ctx_lock(cpuctx, cpuctx->task_ctx); perf_pmu_disable(pmu); pmu->flush_branch_stack(); perf_pmu_enable(pmu); perf_ctx_unlock(cpuctx, cpuctx->task_ctx); } } rcu_read_unlock(); local_irq_restore(flags); } /* * Called from scheduler to add the events of the current task * with interrupts disabled. * * We restore the event value and then enable it. * * This does not protect us against NMI, but enable() * sets the enabled bit in the control field of event _before_ * accessing the event control register. If a NMI hits, then it will * keep the event running. */ void __perf_event_task_sched_in(struct task_struct *prev, struct task_struct *task) { struct perf_event_context *ctx; int ctxn; for_each_task_context_nr(ctxn) { ctx = task->perf_event_ctxp[ctxn]; if (likely(!ctx)) continue; perf_event_context_sched_in(ctx, task); } /* * if cgroup events exist on this CPU, then we need * to check if we have to switch in PMU state. * cgroup event are system-wide mode only */ if (atomic_read(&__get_cpu_var(perf_cgroup_events))) perf_cgroup_sched_in(prev, task); /* check for system-wide branch_stack events */ if (atomic_read(&__get_cpu_var(perf_branch_stack_events))) perf_branch_stack_sched_in(prev, task); } static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count) { u64 frequency = event->attr.sample_freq; u64 sec = NSEC_PER_SEC; u64 divisor, dividend; int count_fls, nsec_fls, frequency_fls, sec_fls; count_fls = fls64(count); nsec_fls = fls64(nsec); frequency_fls = fls64(frequency); sec_fls = 30; /* * We got @count in @nsec, with a target of sample_freq HZ * the target period becomes: * * @count * 10^9 * period = ------------------- * @nsec * sample_freq * */ /* * Reduce accuracy by one bit such that @a and @b converge * to a similar magnitude. */ #define REDUCE_FLS(a, b) \ do { \ if (a##_fls > b##_fls) { \ a >>= 1; \ a##_fls--; \ } else { \ b >>= 1; \ b##_fls--; \ } \ } while (0) /* * Reduce accuracy until either term fits in a u64, then proceed with * the other, so that finally we can do a u64/u64 division. */ while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) { REDUCE_FLS(nsec, frequency); REDUCE_FLS(sec, count); } if (count_fls + sec_fls > 64) { divisor = nsec * frequency; while (count_fls + sec_fls > 64) { REDUCE_FLS(count, sec); divisor >>= 1; } dividend = count * sec; } else { dividend = count * sec; while (nsec_fls + frequency_fls > 64) { REDUCE_FLS(nsec, frequency); dividend >>= 1; } divisor = nsec * frequency; } if (!divisor) return dividend; return div64_u64(dividend, divisor); } static DEFINE_PER_CPU(int, perf_throttled_count); static DEFINE_PER_CPU(u64, perf_throttled_seq); static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable) { struct hw_perf_event *hwc = &event->hw; s64 period, sample_period; s64 delta; period = perf_calculate_period(event, nsec, count); delta = (s64)(period - hwc->sample_period); delta = (delta + 7) / 8; /* low pass filter */ sample_period = hwc->sample_period + delta; if (!sample_period) sample_period = 1; hwc->sample_period = sample_period; if (local64_read(&hwc->period_left) > 8*sample_period) { if (disable) event->pmu->stop(event, PERF_EF_UPDATE); local64_set(&hwc->period_left, 0); if (disable) event->pmu->start(event, PERF_EF_RELOAD); } } /* * combine freq adjustment with unthrottling to avoid two passes over the * events. At the same time, make sure, having freq events does not change * the rate of unthrottling as that would introduce bias. */ static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx, int needs_unthr) { struct perf_event *event; struct hw_perf_event *hwc; u64 now, period = TICK_NSEC; s64 delta; /* * only need to iterate over all events iff: * - context have events in frequency mode (needs freq adjust) * - there are events to unthrottle on this cpu */ if (!(ctx->nr_freq || needs_unthr)) return; raw_spin_lock(&ctx->lock); perf_pmu_disable(ctx->pmu); list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->state != PERF_EVENT_STATE_ACTIVE) continue; if (!event_filter_match(event)) continue; perf_pmu_disable(event->pmu); hwc = &event->hw; if (hwc->interrupts == MAX_INTERRUPTS) { hwc->interrupts = 0; perf_log_throttle(event, 1); event->pmu->start(event, 0); } if (!event->attr.freq || !event->attr.sample_freq) goto next; /* * stop the event and update event->count */ event->pmu->stop(event, PERF_EF_UPDATE); now = local64_read(&event->count); delta = now - hwc->freq_count_stamp; hwc->freq_count_stamp = now; /* * restart the event * reload only if value has changed * we have stopped the event so tell that * to perf_adjust_period() to avoid stopping it * twice. */ if (delta > 0) perf_adjust_period(event, period, delta, false); event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0); next: perf_pmu_enable(event->pmu); } perf_pmu_enable(ctx->pmu); raw_spin_unlock(&ctx->lock); } /* * Round-robin a context's events: */ static void rotate_ctx(struct perf_event_context *ctx) { /* * Rotate the first entry last of non-pinned groups. Rotation might be * disabled by the inheritance code. */ if (!ctx->rotate_disable) list_rotate_left(&ctx->flexible_groups); } /* * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized * because they're strictly cpu affine and rotate_start is called with IRQs * disabled, while rotate_context is called from IRQ context. */ static int perf_rotate_context(struct perf_cpu_context *cpuctx) { struct perf_event_context *ctx = NULL; int rotate = 0, remove = 1; if (cpuctx->ctx.nr_events) { remove = 0; if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active) rotate = 1; } ctx = cpuctx->task_ctx; if (ctx && ctx->nr_events) { remove = 0; if (ctx->nr_events != ctx->nr_active) rotate = 1; } if (!rotate) goto done; perf_ctx_lock(cpuctx, cpuctx->task_ctx); perf_pmu_disable(cpuctx->ctx.pmu); cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); if (ctx) ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE); rotate_ctx(&cpuctx->ctx); if (ctx) rotate_ctx(ctx); perf_event_sched_in(cpuctx, ctx, current); perf_pmu_enable(cpuctx->ctx.pmu); perf_ctx_unlock(cpuctx, cpuctx->task_ctx); done: if (remove) list_del_init(&cpuctx->rotation_list); return rotate; } #ifdef CONFIG_NO_HZ_FULL bool perf_event_can_stop_tick(void) { if (atomic_read(&nr_freq_events) || __this_cpu_read(perf_throttled_count)) return false; else return true; } #endif void perf_event_task_tick(void) { struct list_head *head = &__get_cpu_var(rotation_list); struct perf_cpu_context *cpuctx, *tmp; struct perf_event_context *ctx; int throttled; WARN_ON(!irqs_disabled()); __this_cpu_inc(perf_throttled_seq); throttled = __this_cpu_xchg(perf_throttled_count, 0); list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) { ctx = &cpuctx->ctx; perf_adjust_freq_unthr_context(ctx, throttled); ctx = cpuctx->task_ctx; if (ctx) perf_adjust_freq_unthr_context(ctx, throttled); } } static int event_enable_on_exec(struct perf_event *event, struct perf_event_context *ctx) { if (!event->attr.enable_on_exec) return 0; event->attr.enable_on_exec = 0; if (event->state >= PERF_EVENT_STATE_INACTIVE) return 0; __perf_event_mark_enabled(event); return 1; } /* * Enable all of a task's events that have been marked enable-on-exec. * This expects task == current. */ static void perf_event_enable_on_exec(struct perf_event_context *ctx) { struct perf_event *event; unsigned long flags; int enabled = 0; int ret; local_irq_save(flags); if (!ctx || !ctx->nr_events) goto out; /* * We must ctxsw out cgroup events to avoid conflict * when invoking perf_task_event_sched_in() later on * in this function. Otherwise we end up trying to * ctxswin cgroup events which are already scheduled * in. */ perf_cgroup_sched_out(current, NULL); raw_spin_lock(&ctx->lock); task_ctx_sched_out(ctx); list_for_each_entry(event, &ctx->event_list, event_entry) { ret = event_enable_on_exec(event, ctx); if (ret) enabled = 1; } /* * Unclone this context if we enabled any event. */ if (enabled) unclone_ctx(ctx); raw_spin_unlock(&ctx->lock); /* * Also calls ctxswin for cgroup events, if any: */ perf_event_context_sched_in(ctx, ctx->task); out: local_irq_restore(flags); } void perf_event_exec(void) { struct perf_event_context *ctx; int ctxn; rcu_read_lock(); for_each_task_context_nr(ctxn) { ctx = current->perf_event_ctxp[ctxn]; if (!ctx) continue; perf_event_enable_on_exec(ctx); } rcu_read_unlock(); } /* * Cross CPU call to read the hardware event */ static void __perf_event_read(void *info) { struct perf_event *event = info; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); /* * If this is a task context, we need to check whether it is * the current task context of this cpu. If not it has been * scheduled out before the smp call arrived. In that case * event->count would have been updated to a recent sample * when the event was scheduled out. */ if (ctx->task && cpuctx->task_ctx != ctx) return; raw_spin_lock(&ctx->lock); if (ctx->is_active) { update_context_time(ctx); update_cgrp_time_from_event(event); } update_event_times(event); if (event->state == PERF_EVENT_STATE_ACTIVE) event->pmu->read(event); raw_spin_unlock(&ctx->lock); } static inline u64 perf_event_count(struct perf_event *event) { return local64_read(&event->count) + atomic64_read(&event->child_count); } static u64 perf_event_read(struct perf_event *event) { /* * If event is enabled and currently active on a CPU, update the * value in the event structure: */ if (event->state == PERF_EVENT_STATE_ACTIVE) { smp_call_function_single(event->oncpu, __perf_event_read, event, 1); } else if (event->state == PERF_EVENT_STATE_INACTIVE) { struct perf_event_context *ctx = event->ctx; unsigned long flags; raw_spin_lock_irqsave(&ctx->lock, flags); /* * may read while context is not active * (e.g., thread is blocked), in that case * we cannot update context time */ if (ctx->is_active) { update_context_time(ctx); update_cgrp_time_from_event(event); } update_event_times(event); raw_spin_unlock_irqrestore(&ctx->lock, flags); } return perf_event_count(event); } /* * Initialize the perf_event context in a task_struct: */ static void __perf_event_init_context(struct perf_event_context *ctx) { raw_spin_lock_init(&ctx->lock); mutex_init(&ctx->mutex); INIT_LIST_HEAD(&ctx->pinned_groups); INIT_LIST_HEAD(&ctx->flexible_groups); INIT_LIST_HEAD(&ctx->event_list); atomic_set(&ctx->refcount, 1); } static struct perf_event_context * alloc_perf_context(struct pmu *pmu, struct task_struct *task) { struct perf_event_context *ctx; ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL); if (!ctx) return NULL; __perf_event_init_context(ctx); if (task) { ctx->task = task; get_task_struct(task); } ctx->pmu = pmu; return ctx; } static struct task_struct * find_lively_task_by_vpid(pid_t vpid) { struct task_struct *task; int err; rcu_read_lock(); if (!vpid) task = current; else task = find_task_by_vpid(vpid); if (task) get_task_struct(task); rcu_read_unlock(); if (!task) return ERR_PTR(-ESRCH); /* Reuse ptrace permission checks for now. */ err = -EACCES; if (!ptrace_may_access(task, PTRACE_MODE_READ)) goto errout; return task; errout: put_task_struct(task); return ERR_PTR(err); } /* * Returns a matching context with refcount and pincount. */ static struct perf_event_context * find_get_context(struct pmu *pmu, struct task_struct *task, int cpu) { struct perf_event_context *ctx; struct perf_cpu_context *cpuctx; unsigned long flags; int ctxn, err; if (!task) { /* Must be root to operate on a CPU event: */ if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN)) return ERR_PTR(-EACCES); /* * We could be clever and allow to attach a event to an * offline CPU and activate it when the CPU comes up, but * that's for later. */ if (!cpu_online(cpu)) return ERR_PTR(-ENODEV); cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); ctx = &cpuctx->ctx; get_ctx(ctx); ++ctx->pin_count; return ctx; } err = -EINVAL; ctxn = pmu->task_ctx_nr; if (ctxn < 0) goto errout; retry: ctx = perf_lock_task_context(task, ctxn, &flags); if (ctx) { unclone_ctx(ctx); ++ctx->pin_count; raw_spin_unlock_irqrestore(&ctx->lock, flags); } else { ctx = alloc_perf_context(pmu, task); err = -ENOMEM; if (!ctx) goto errout; err = 0; mutex_lock(&task->perf_event_mutex); /* * If it has already passed perf_event_exit_task(). * we must see PF_EXITING, it takes this mutex too. */ if (task->flags & PF_EXITING) err = -ESRCH; else if (task->perf_event_ctxp[ctxn]) err = -EAGAIN; else { get_ctx(ctx); ++ctx->pin_count; rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx); } mutex_unlock(&task->perf_event_mutex); if (unlikely(err)) { put_ctx(ctx); if (err == -EAGAIN) goto retry; goto errout; } } return ctx; errout: return ERR_PTR(err); } static void perf_event_free_filter(struct perf_event *event); static void free_event_rcu(struct rcu_head *head) { struct perf_event *event; event = container_of(head, struct perf_event, rcu_head); if (event->ns) put_pid_ns(event->ns); perf_event_free_filter(event); kfree(event); } static void ring_buffer_put(struct ring_buffer *rb); static void ring_buffer_attach(struct perf_event *event, struct ring_buffer *rb); static void unaccount_event_cpu(struct perf_event *event, int cpu) { if (event->parent) return; if (has_branch_stack(event)) { if (!(event->attach_state & PERF_ATTACH_TASK)) atomic_dec(&per_cpu(perf_branch_stack_events, cpu)); } if (is_cgroup_event(event)) atomic_dec(&per_cpu(perf_cgroup_events, cpu)); } static void unaccount_event(struct perf_event *event) { if (event->parent) return; if (event->attach_state & PERF_ATTACH_TASK) static_key_slow_dec_deferred(&perf_sched_events); if (event->attr.mmap || event->attr.mmap_data) atomic_dec(&nr_mmap_events); if (event->attr.comm) atomic_dec(&nr_comm_events); if (event->attr.task) atomic_dec(&nr_task_events); if (event->attr.freq) atomic_dec(&nr_freq_events); if (is_cgroup_event(event)) static_key_slow_dec_deferred(&perf_sched_events); if (has_branch_stack(event)) static_key_slow_dec_deferred(&perf_sched_events); unaccount_event_cpu(event, event->cpu); } static void __free_event(struct perf_event *event) { if (!event->parent) { if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) put_callchain_buffers(); } if (event->destroy) event->destroy(event); if (event->ctx) put_ctx(event->ctx); if (event->pmu) module_put(event->pmu->module); call_rcu(&event->rcu_head, free_event_rcu); } static void _free_event(struct perf_event *event) { irq_work_sync(&event->pending); unaccount_event(event); if (event->rb) { /* * Can happen when we close an event with re-directed output. * * Since we have a 0 refcount, perf_mmap_close() will skip * over us; possibly making our ring_buffer_put() the last. */ mutex_lock(&event->mmap_mutex); ring_buffer_attach(event, NULL); mutex_unlock(&event->mmap_mutex); } if (is_cgroup_event(event)) perf_detach_cgroup(event); __free_event(event); } /* * Used to free events which have a known refcount of 1, such as in error paths * where the event isn't exposed yet and inherited events. */ static void free_event(struct perf_event *event) { if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, "unexpected event refcount: %ld; ptr=%p\n", atomic_long_read(&event->refcount), event)) { /* leak to avoid use-after-free */ return; } _free_event(event); } /* * Called when the last reference to the file is gone. */ static void put_event(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct task_struct *owner; if (!atomic_long_dec_and_test(&event->refcount)) return; rcu_read_lock(); owner = ACCESS_ONCE(event->owner); /* * Matches the smp_wmb() in perf_event_exit_task(). If we observe * !owner it means the list deletion is complete and we can indeed * free this event, otherwise we need to serialize on * owner->perf_event_mutex. */ smp_read_barrier_depends(); if (owner) { /* * Since delayed_put_task_struct() also drops the last * task reference we can safely take a new reference * while holding the rcu_read_lock(). */ get_task_struct(owner); } rcu_read_unlock(); if (owner) { mutex_lock(&owner->perf_event_mutex); /* * We have to re-check the event->owner field, if it is cleared * we raced with perf_event_exit_task(), acquiring the mutex * ensured they're done, and we can proceed with freeing the * event. */ if (event->owner) list_del_init(&event->owner_entry); mutex_unlock(&owner->perf_event_mutex); put_task_struct(owner); } WARN_ON_ONCE(ctx->parent_ctx); /* * There are two ways this annotation is useful: * * 1) there is a lock recursion from perf_event_exit_task * see the comment there. * * 2) there is a lock-inversion with mmap_sem through * perf_event_read_group(), which takes faults while * holding ctx->mutex, however this is called after * the last filedesc died, so there is no possibility * to trigger the AB-BA case. */ mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING); perf_remove_from_context(event, true); mutex_unlock(&ctx->mutex); _free_event(event); } int perf_event_release_kernel(struct perf_event *event) { put_event(event); return 0; } EXPORT_SYMBOL_GPL(perf_event_release_kernel); static int perf_release(struct inode *inode, struct file *file) { put_event(file->private_data); return 0; } u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) { struct perf_event *child; u64 total = 0; *enabled = 0; *running = 0; mutex_lock(&event->child_mutex); total += perf_event_read(event); *enabled += event->total_time_enabled + atomic64_read(&event->child_total_time_enabled); *running += event->total_time_running + atomic64_read(&event->child_total_time_running); list_for_each_entry(child, &event->child_list, child_list) { total += perf_event_read(child); *enabled += child->total_time_enabled; *running += child->total_time_running; } mutex_unlock(&event->child_mutex); return total; } EXPORT_SYMBOL_GPL(perf_event_read_value); static int perf_event_read_group(struct perf_event *event, u64 read_format, char __user *buf) { struct perf_event *leader = event->group_leader, *sub; int n = 0, size = 0, ret = -EFAULT; struct perf_event_context *ctx = leader->ctx; u64 values[5]; u64 count, enabled, running; mutex_lock(&ctx->mutex); count = perf_event_read_value(leader, &enabled, &running); values[n++] = 1 + leader->nr_siblings; if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) values[n++] = enabled; if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) values[n++] = running; values[n++] = count; if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(leader); size = n * sizeof(u64); if (copy_to_user(buf, values, size)) goto unlock; ret = size; list_for_each_entry(sub, &leader->sibling_list, group_entry) { n = 0; values[n++] = perf_event_read_value(sub, &enabled, &running); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(sub); size = n * sizeof(u64); if (copy_to_user(buf + ret, values, size)) { ret = -EFAULT; goto unlock; } ret += size; } unlock: mutex_unlock(&ctx->mutex); return ret; } static int perf_event_read_one(struct perf_event *event, u64 read_format, char __user *buf) { u64 enabled, running; u64 values[4]; int n = 0; values[n++] = perf_event_read_value(event, &enabled, &running); if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) values[n++] = enabled; if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) values[n++] = running; if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(event); if (copy_to_user(buf, values, n * sizeof(u64))) return -EFAULT; return n * sizeof(u64); } /* * Read the performance event - simple non blocking version for now */ static ssize_t perf_read_hw(struct perf_event *event, char __user *buf, size_t count) { u64 read_format = event->attr.read_format; int ret; /* * Return end-of-file for a read on a event that is in * error state (i.e. because it was pinned but it couldn't be * scheduled on to the CPU at some point). */ if (event->state == PERF_EVENT_STATE_ERROR) return 0; if (count < event->read_size) return -ENOSPC; WARN_ON_ONCE(event->ctx->parent_ctx); if (read_format & PERF_FORMAT_GROUP) ret = perf_event_read_group(event, read_format, buf); else ret = perf_event_read_one(event, read_format, buf); return ret; } static ssize_t perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct perf_event *event = file->private_data; return perf_read_hw(event, buf, count); } static unsigned int perf_poll(struct file *file, poll_table *wait) { struct perf_event *event = file->private_data; struct ring_buffer *rb; unsigned int events = POLL_HUP; /* * Pin the event->rb by taking event->mmap_mutex; otherwise * perf_event_set_output() can swizzle our rb and make us miss wakeups. */ mutex_lock(&event->mmap_mutex); rb = event->rb; if (rb) events = atomic_xchg(&rb->poll, 0); mutex_unlock(&event->mmap_mutex); poll_wait(file, &event->waitq, wait); return events; } static void perf_event_reset(struct perf_event *event) { (void)perf_event_read(event); local64_set(&event->count, 0); perf_event_update_userpage(event); } /* * Holding the top-level event's child_mutex means that any * descendant process that has inherited this event will block * in sync_child_event if it goes to exit, thus satisfying the * task existence requirements of perf_event_enable/disable. */ static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); } static void perf_event_for_each(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event_context *ctx = event->ctx; struct perf_event *sibling; WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); event = event->group_leader; perf_event_for_each_child(event, func); list_for_each_entry(sibling, &event->sibling_list, group_entry) perf_event_for_each_child(sibling, func); mutex_unlock(&ctx->mutex); } static int perf_event_period(struct perf_event *event, u64 __user *arg) { struct perf_event_context *ctx = event->ctx; int ret = 0, active; u64 value; if (!is_sampling_event(event)) return -EINVAL; if (copy_from_user(&value, arg, sizeof(value))) return -EFAULT; if (!value) return -EINVAL; raw_spin_lock_irq(&ctx->lock); if (event->attr.freq) { if (value > sysctl_perf_event_sample_rate) { ret = -EINVAL; goto unlock; } event->attr.sample_freq = value; } else { event->attr.sample_period = value; event->hw.sample_period = value; } active = (event->state == PERF_EVENT_STATE_ACTIVE); if (active) { perf_pmu_disable(ctx->pmu); event->pmu->stop(event, PERF_EF_UPDATE); } local64_set(&event->hw.period_left, 0); if (active) { event->pmu->start(event, PERF_EF_RELOAD); perf_pmu_enable(ctx->pmu); } unlock: raw_spin_unlock_irq(&ctx->lock); return ret; } static const struct file_operations perf_fops; static inline int perf_fget_light(int fd, struct fd *p) { struct fd f = fdget(fd); if (!f.file) return -EBADF; if (f.file->f_op != &perf_fops) { fdput(f); return -EBADF; } *p = f; return 0; } static int perf_event_set_output(struct perf_event *event, struct perf_event *output_event); static int perf_event_set_filter(struct perf_event *event, void __user *arg); static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct perf_event *event = file->private_data; void (*func)(struct perf_event *); u32 flags = arg; switch (cmd) { case PERF_EVENT_IOC_ENABLE: func = perf_event_enable; break; case PERF_EVENT_IOC_DISABLE: func = perf_event_disable; break; case PERF_EVENT_IOC_RESET: func = perf_event_reset; break; case PERF_EVENT_IOC_REFRESH: return perf_event_refresh(event, arg); case PERF_EVENT_IOC_PERIOD: return perf_event_period(event, (u64 __user *)arg); case PERF_EVENT_IOC_ID: { u64 id = primary_event_id(event); if (copy_to_user((void __user *)arg, &id, sizeof(id))) return -EFAULT; return 0; } case PERF_EVENT_IOC_SET_OUTPUT: { int ret; if (arg != -1) { struct perf_event *output_event; struct fd output; ret = perf_fget_light(arg, &output); if (ret) return ret; output_event = output.file->private_data; ret = perf_event_set_output(event, output_event); fdput(output); } else { ret = perf_event_set_output(event, NULL); } return ret; } case PERF_EVENT_IOC_SET_FILTER: return perf_event_set_filter(event, (void __user *)arg); default: return -ENOTTY; } if (flags & PERF_IOC_FLAG_GROUP) perf_event_for_each(event, func); else perf_event_for_each_child(event, func); return 0; } int perf_event_task_enable(void) { struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) perf_event_for_each_child(event, perf_event_enable); mutex_unlock(&current->perf_event_mutex); return 0; } int perf_event_task_disable(void) { struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) perf_event_for_each_child(event, perf_event_disable); mutex_unlock(&current->perf_event_mutex); return 0; } static int perf_event_index(struct perf_event *event) { if (event->hw.state & PERF_HES_STOPPED) return 0; if (event->state != PERF_EVENT_STATE_ACTIVE) return 0; return event->pmu->event_idx(event); } static void calc_timer_values(struct perf_event *event, u64 *now, u64 *enabled, u64 *running) { u64 ctx_time; *now = perf_clock(); ctx_time = event->shadow_ctx_time + *now; *enabled = ctx_time - event->tstamp_enabled; *running = ctx_time - event->tstamp_running; } static void perf_event_init_userpage(struct perf_event *event) { struct perf_event_mmap_page *userpg; struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb) goto unlock; userpg = rb->user_page; /* Allow new userspace to detect that bit 0 is deprecated */ userpg->cap_bit0_is_deprecated = 1; userpg->size = offsetof(struct perf_event_mmap_page, __reserved); unlock: rcu_read_unlock(); } void __weak arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now) { } /* * Callers need to ensure there can be no nesting of this function, otherwise * the seqlock logic goes bad. We can not serialize this because the arch * code calls this from NMI context. */ void perf_event_update_userpage(struct perf_event *event) { struct perf_event_mmap_page *userpg; struct ring_buffer *rb; u64 enabled, running, now; rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb) goto unlock; /* * compute total_time_enabled, total_time_running * based on snapshot values taken when the event * was last scheduled in. * * we cannot simply called update_context_time() * because of locking issue as we can be called in * NMI context */ calc_timer_values(event, &now, &enabled, &running); userpg = rb->user_page; /* * Disable preemption so as to not let the corresponding user-space * spin too long if we get preempted. */ preempt_disable(); ++userpg->lock; barrier(); userpg->index = perf_event_index(event); userpg->offset = perf_event_count(event); if (userpg->index) userpg->offset -= local64_read(&event->hw.prev_count); userpg->time_enabled = enabled + atomic64_read(&event->child_total_time_enabled); userpg->time_running = running + atomic64_read(&event->child_total_time_running); arch_perf_update_userpage(userpg, now); barrier(); ++userpg->lock; preempt_enable(); unlock: rcu_read_unlock(); } static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct perf_event *event = vma->vm_file->private_data; struct ring_buffer *rb; int ret = VM_FAULT_SIGBUS; if (vmf->flags & FAULT_FLAG_MKWRITE) { if (vmf->pgoff == 0) ret = 0; return ret; } rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb) goto unlock; if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE)) goto unlock; vmf->page = perf_mmap_to_page(rb, vmf->pgoff); if (!vmf->page) goto unlock; get_page(vmf->page); vmf->page->mapping = vma->vm_file->f_mapping; vmf->page->index = vmf->pgoff; ret = 0; unlock: rcu_read_unlock(); return ret; } static void ring_buffer_attach(struct perf_event *event, struct ring_buffer *rb) { struct ring_buffer *old_rb = NULL; unsigned long flags; if (event->rb) { /* * Should be impossible, we set this when removing * event->rb_entry and wait/clear when adding event->rb_entry. */ WARN_ON_ONCE(event->rcu_pending); old_rb = event->rb; event->rcu_batches = get_state_synchronize_rcu(); event->rcu_pending = 1; spin_lock_irqsave(&old_rb->event_lock, flags); list_del_rcu(&event->rb_entry); spin_unlock_irqrestore(&old_rb->event_lock, flags); } if (event->rcu_pending && rb) { cond_synchronize_rcu(event->rcu_batches); event->rcu_pending = 0; } if (rb) { spin_lock_irqsave(&rb->event_lock, flags); list_add_rcu(&event->rb_entry, &rb->event_list); spin_unlock_irqrestore(&rb->event_lock, flags); } rcu_assign_pointer(event->rb, rb); if (old_rb) { ring_buffer_put(old_rb); /* * Since we detached before setting the new rb, so that we * could attach the new rb, we could have missed a wakeup. * Provide it now. */ wake_up_all(&event->waitq); } } static void ring_buffer_wakeup(struct perf_event *event) { struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (rb) { list_for_each_entry_rcu(event, &rb->event_list, rb_entry) wake_up_all(&event->waitq); } rcu_read_unlock(); } static void rb_free_rcu(struct rcu_head *rcu_head) { struct ring_buffer *rb; rb = container_of(rcu_head, struct ring_buffer, rcu_head); rb_free(rb); } static struct ring_buffer *ring_buffer_get(struct perf_event *event) { struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (rb) { if (!atomic_inc_not_zero(&rb->refcount)) rb = NULL; } rcu_read_unlock(); return rb; } static void ring_buffer_put(struct ring_buffer *rb) { if (!atomic_dec_and_test(&rb->refcount)) return; WARN_ON_ONCE(!list_empty(&rb->event_list)); call_rcu(&rb->rcu_head, rb_free_rcu); } static void perf_mmap_open(struct vm_area_struct *vma) { struct perf_event *event = vma->vm_file->private_data; atomic_inc(&event->mmap_count); atomic_inc(&event->rb->mmap_count); } /* * A buffer can be mmap()ed multiple times; either directly through the same * event, or through other events by use of perf_event_set_output(). * * In order to undo the VM accounting done by perf_mmap() we need to destroy * the buffer here, where we still have a VM context. This means we need * to detach all events redirecting to us. */ static void perf_mmap_close(struct vm_area_struct *vma) { struct perf_event *event = vma->vm_file->private_data; struct ring_buffer *rb = ring_buffer_get(event); struct user_struct *mmap_user = rb->mmap_user; int mmap_locked = rb->mmap_locked; unsigned long size = perf_data_size(rb); atomic_dec(&rb->mmap_count); if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) goto out_put; ring_buffer_attach(event, NULL); mutex_unlock(&event->mmap_mutex); /* If there's still other mmap()s of this buffer, we're done. */ if (atomic_read(&rb->mmap_count)) goto out_put; /* * No other mmap()s, detach from all other events that might redirect * into the now unreachable buffer. Somewhat complicated by the * fact that rb::event_lock otherwise nests inside mmap_mutex. */ again: rcu_read_lock(); list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { if (!atomic_long_inc_not_zero(&event->refcount)) { /* * This event is en-route to free_event() which will * detach it and remove it from the list. */ continue; } rcu_read_unlock(); mutex_lock(&event->mmap_mutex); /* * Check we didn't race with perf_event_set_output() which can * swizzle the rb from under us while we were waiting to * acquire mmap_mutex. * * If we find a different rb; ignore this event, a next * iteration will no longer find it on the list. We have to * still restart the iteration to make sure we're not now * iterating the wrong list. */ if (event->rb == rb) ring_buffer_attach(event, NULL); mutex_unlock(&event->mmap_mutex); put_event(event); /* * Restart the iteration; either we're on the wrong list or * destroyed its integrity by doing a deletion. */ goto again; } rcu_read_unlock(); /* * It could be there's still a few 0-ref events on the list; they'll * get cleaned up by free_event() -- they'll also still have their * ref on the rb and will free it whenever they are done with it. * * Aside from that, this buffer is 'fully' detached and unmapped, * undo the VM accounting. */ atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm); vma->vm_mm->pinned_vm -= mmap_locked; free_uid(mmap_user); out_put: ring_buffer_put(rb); /* could be last */ } static const struct vm_operations_struct perf_mmap_vmops = { .open = perf_mmap_open, .close = perf_mmap_close, .fault = perf_mmap_fault, .page_mkwrite = perf_mmap_fault, }; static int perf_mmap(struct file *file, struct vm_area_struct *vma) { struct perf_event *event = file->private_data; unsigned long user_locked, user_lock_limit; struct user_struct *user = current_user(); unsigned long locked, lock_limit; struct ring_buffer *rb; unsigned long vma_size; unsigned long nr_pages; long user_extra, extra; int ret = 0, flags = 0; /* * Don't allow mmap() of inherited per-task counters. This would * create a performance issue due to all children writing to the * same rb. */ if (event->cpu == -1 && event->attr.inherit) return -EINVAL; if (!(vma->vm_flags & VM_SHARED)) return -EINVAL; vma_size = vma->vm_end - vma->vm_start; nr_pages = (vma_size / PAGE_SIZE) - 1; /* * If we have rb pages ensure they're a power-of-two number, so we * can do bitmasks instead of modulo. */ if (nr_pages != 0 && !is_power_of_2(nr_pages)) return -EINVAL; if (vma_size != PAGE_SIZE * (1 + nr_pages)) return -EINVAL; if (vma->vm_pgoff != 0) return -EINVAL; WARN_ON_ONCE(event->ctx->parent_ctx); again: mutex_lock(&event->mmap_mutex); if (event->rb) { if (event->rb->nr_pages != nr_pages) { ret = -EINVAL; goto unlock; } if (!atomic_inc_not_zero(&event->rb->mmap_count)) { /* * Raced against perf_mmap_close() through * perf_event_set_output(). Try again, hope for better * luck. */ mutex_unlock(&event->mmap_mutex); goto again; } goto unlock; } user_extra = nr_pages + 1; user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); /* * Increase the limit linearly with more CPUs: */ user_lock_limit *= num_online_cpus(); user_locked = atomic_long_read(&user->locked_vm) + user_extra; extra = 0; if (user_locked > user_lock_limit) extra = user_locked - user_lock_limit; lock_limit = rlimit(RLIMIT_MEMLOCK); lock_limit >>= PAGE_SHIFT; locked = vma->vm_mm->pinned_vm + extra; if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() && !capable(CAP_IPC_LOCK)) { ret = -EPERM; goto unlock; } WARN_ON(event->rb); if (vma->vm_flags & VM_WRITE) flags |= RING_BUFFER_WRITABLE; rb = rb_alloc(nr_pages, event->attr.watermark ? event->attr.wakeup_watermark : 0, event->cpu, flags); if (!rb) { ret = -ENOMEM; goto unlock; } atomic_set(&rb->mmap_count, 1); rb->mmap_locked = extra; rb->mmap_user = get_current_user(); atomic_long_add(user_extra, &user->locked_vm); vma->vm_mm->pinned_vm += extra; ring_buffer_attach(event, rb); perf_event_init_userpage(event); perf_event_update_userpage(event); unlock: if (!ret) atomic_inc(&event->mmap_count); mutex_unlock(&event->mmap_mutex); /* * Since pinned accounting is per vm we cannot allow fork() to copy our * vma. */ vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP; vma->vm_ops = &perf_mmap_vmops; return ret; } static int perf_fasync(int fd, struct file *filp, int on) { struct inode *inode = file_inode(filp); struct perf_event *event = filp->private_data; int retval; mutex_lock(&inode->i_mutex); retval = fasync_helper(fd, filp, on, &event->fasync); mutex_unlock(&inode->i_mutex); if (retval < 0) return retval; return 0; } static const struct file_operations perf_fops = { .llseek = no_llseek, .release = perf_release, .read = perf_read, .poll = perf_poll, .unlocked_ioctl = perf_ioctl, .compat_ioctl = perf_ioctl, .mmap = perf_mmap, .fasync = perf_fasync, }; /* * Perf event wakeup * * If there's data, ensure we set the poll() state and publish everything * to user-space before waking everybody up. */ void perf_event_wakeup(struct perf_event *event) { ring_buffer_wakeup(event); if (event->pending_kill) { kill_fasync(&event->fasync, SIGIO, event->pending_kill); event->pending_kill = 0; } } static void perf_pending_event(struct irq_work *entry) { struct perf_event *event = container_of(entry, struct perf_event, pending); if (event->pending_disable) { event->pending_disable = 0; __perf_event_disable(event); } if (event->pending_wakeup) { event->pending_wakeup = 0; perf_event_wakeup(event); } } /* * We assume there is only KVM supporting the callbacks. * Later on, we might change it to a list if there is * another virtualization implementation supporting the callbacks. */ struct perf_guest_info_callbacks *perf_guest_cbs; int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) { perf_guest_cbs = cbs; return 0; } EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) { perf_guest_cbs = NULL; return 0; } EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); static void perf_output_sample_regs(struct perf_output_handle *handle, struct pt_regs *regs, u64 mask) { int bit; for_each_set_bit(bit, (const unsigned long *) &mask, sizeof(mask) * BITS_PER_BYTE) { u64 val; val = perf_reg_value(regs, bit); perf_output_put(handle, val); } } static void perf_sample_regs_user(struct perf_regs_user *regs_user, struct pt_regs *regs) { if (!user_mode(regs)) { if (current->mm) regs = task_pt_regs(current); else regs = NULL; } if (regs) { regs_user->regs = regs; regs_user->abi = perf_reg_abi(current); } } /* * Get remaining task size from user stack pointer. * * It'd be better to take stack vma map and limit this more * precisly, but there's no way to get it safely under interrupt, * so using TASK_SIZE as limit. */ static u64 perf_ustack_task_size(struct pt_regs *regs) { unsigned long addr = perf_user_stack_pointer(regs); if (!addr || addr >= TASK_SIZE) return 0; return TASK_SIZE - addr; } static u16 perf_sample_ustack_size(u16 stack_size, u16 header_size, struct pt_regs *regs) { u64 task_size; /* No regs, no stack pointer, no dump. */ if (!regs) return 0; /* * Check if we fit in with the requested stack size into the: * - TASK_SIZE * If we don't, we limit the size to the TASK_SIZE. * * - remaining sample size * If we don't, we customize the stack size to * fit in to the remaining sample size. */ task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); stack_size = min(stack_size, (u16) task_size); /* Current header size plus static size and dynamic size. */ header_size += 2 * sizeof(u64); /* Do we fit in with the current stack dump size? */ if ((u16) (header_size + stack_size) < header_size) { /* * If we overflow the maximum size for the sample, * we customize the stack dump size to fit in. */ stack_size = USHRT_MAX - header_size - sizeof(u64); stack_size = round_up(stack_size, sizeof(u64)); } return stack_size; } static void perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, struct pt_regs *regs) { /* Case of a kernel thread, nothing to dump */ if (!regs) { u64 size = 0; perf_output_put(handle, size); } else { unsigned long sp; unsigned int rem; u64 dyn_size; /* * We dump: * static size * - the size requested by user or the best one we can fit * in to the sample max size * data * - user stack dump data * dynamic size * - the actual dumped size */ /* Static size. */ perf_output_put(handle, dump_size); /* Data. */ sp = perf_user_stack_pointer(regs); rem = __output_copy_user(handle, (void *) sp, dump_size); dyn_size = dump_size - rem; perf_output_skip(handle, rem); /* Dynamic size. */ perf_output_put(handle, dyn_size); } } static void __perf_event_header__init_id(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { u64 sample_type = event->attr.sample_type; data->type = sample_type; header->size += event->id_header_size; if (sample_type & PERF_SAMPLE_TID) { /* namespace issues */ data->tid_entry.pid = perf_event_pid(event, current); data->tid_entry.tid = perf_event_tid(event, current); } if (sample_type & PERF_SAMPLE_TIME) data->time = perf_clock(); if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) data->id = primary_event_id(event); if (sample_type & PERF_SAMPLE_STREAM_ID) data->stream_id = event->id; if (sample_type & PERF_SAMPLE_CPU) { data->cpu_entry.cpu = raw_smp_processor_id(); data->cpu_entry.reserved = 0; } } void perf_event_header__init_id(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { if (event->attr.sample_id_all) __perf_event_header__init_id(header, data, event); } static void __perf_event__output_id_sample(struct perf_output_handle *handle, struct perf_sample_data *data) { u64 sample_type = data->type; if (sample_type & PERF_SAMPLE_TID) perf_output_put(handle, data->tid_entry); if (sample_type & PERF_SAMPLE_TIME) perf_output_put(handle, data->time); if (sample_type & PERF_SAMPLE_ID) perf_output_put(handle, data->id); if (sample_type & PERF_SAMPLE_STREAM_ID) perf_output_put(handle, data->stream_id); if (sample_type & PERF_SAMPLE_CPU) perf_output_put(handle, data->cpu_entry); if (sample_type & PERF_SAMPLE_IDENTIFIER) perf_output_put(handle, data->id); } void perf_event__output_id_sample(struct perf_event *event, struct perf_output_handle *handle, struct perf_sample_data *sample) { if (event->attr.sample_id_all) __perf_event__output_id_sample(handle, sample); } static void perf_output_read_one(struct perf_output_handle *handle, struct perf_event *event, u64 enabled, u64 running) { u64 read_format = event->attr.read_format; u64 values[4]; int n = 0; values[n++] = perf_event_count(event); if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { values[n++] = enabled + atomic64_read(&event->child_total_time_enabled); } if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { values[n++] = running + atomic64_read(&event->child_total_time_running); } if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(event); __output_copy(handle, values, n * sizeof(u64)); } /* * XXX PERF_FORMAT_GROUP vs inherited events seems difficult. */ static void perf_output_read_group(struct perf_output_handle *handle, struct perf_event *event, u64 enabled, u64 running) { struct perf_event *leader = event->group_leader, *sub; u64 read_format = event->attr.read_format; u64 values[5]; int n = 0; values[n++] = 1 + leader->nr_siblings; if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) values[n++] = enabled; if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) values[n++] = running; if (leader != event) leader->pmu->read(leader); values[n++] = perf_event_count(leader); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(leader); __output_copy(handle, values, n * sizeof(u64)); list_for_each_entry(sub, &leader->sibling_list, group_entry) { n = 0; if ((sub != event) && (sub->state == PERF_EVENT_STATE_ACTIVE)) sub->pmu->read(sub); values[n++] = perf_event_count(sub); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(sub); __output_copy(handle, values, n * sizeof(u64)); } } #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ PERF_FORMAT_TOTAL_TIME_RUNNING) static void perf_output_read(struct perf_output_handle *handle, struct perf_event *event) { u64 enabled = 0, running = 0, now; u64 read_format = event->attr.read_format; /* * compute total_time_enabled, total_time_running * based on snapshot values taken when the event * was last scheduled in. * * we cannot simply called update_context_time() * because of locking issue as we are called in * NMI context */ if (read_format & PERF_FORMAT_TOTAL_TIMES) calc_timer_values(event, &now, &enabled, &running); if (event->attr.read_format & PERF_FORMAT_GROUP) perf_output_read_group(handle, event, enabled, running); else perf_output_read_one(handle, event, enabled, running); } void perf_output_sample(struct perf_output_handle *handle, struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { u64 sample_type = data->type; perf_output_put(handle, *header); if (sample_type & PERF_SAMPLE_IDENTIFIER) perf_output_put(handle, data->id); if (sample_type & PERF_SAMPLE_IP) perf_output_put(handle, data->ip); if (sample_type & PERF_SAMPLE_TID) perf_output_put(handle, data->tid_entry); if (sample_type & PERF_SAMPLE_TIME) perf_output_put(handle, data->time); if (sample_type & PERF_SAMPLE_ADDR) perf_output_put(handle, data->addr); if (sample_type & PERF_SAMPLE_ID) perf_output_put(handle, data->id); if (sample_type & PERF_SAMPLE_STREAM_ID) perf_output_put(handle, data->stream_id); if (sample_type & PERF_SAMPLE_CPU) perf_output_put(handle, data->cpu_entry); if (sample_type & PERF_SAMPLE_PERIOD) perf_output_put(handle, data->period); if (sample_type & PERF_SAMPLE_READ) perf_output_read(handle, event); if (sample_type & PERF_SAMPLE_CALLCHAIN) { if (data->callchain) { int size = 1; if (data->callchain) size += data->callchain->nr; size *= sizeof(u64); __output_copy(handle, data->callchain, size); } else { u64 nr = 0; perf_output_put(handle, nr); } } if (sample_type & PERF_SAMPLE_RAW) { if (data->raw) { perf_output_put(handle, data->raw->size); __output_copy(handle, data->raw->data, data->raw->size); } else { struct { u32 size; u32 data; } raw = { .size = sizeof(u32), .data = 0, }; perf_output_put(handle, raw); } } if (sample_type & PERF_SAMPLE_BRANCH_STACK) { if (data->br_stack) { size_t size; size = data->br_stack->nr * sizeof(struct perf_branch_entry); perf_output_put(handle, data->br_stack->nr); perf_output_copy(handle, data->br_stack->entries, size); } else { /* * we always store at least the value of nr */ u64 nr = 0; perf_output_put(handle, nr); } } if (sample_type & PERF_SAMPLE_REGS_USER) { u64 abi = data->regs_user.abi; /* * If there are no regs to dump, notice it through * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). */ perf_output_put(handle, abi); if (abi) { u64 mask = event->attr.sample_regs_user; perf_output_sample_regs(handle, data->regs_user.regs, mask); } } if (sample_type & PERF_SAMPLE_STACK_USER) { perf_output_sample_ustack(handle, data->stack_user_size, data->regs_user.regs); } if (sample_type & PERF_SAMPLE_WEIGHT) perf_output_put(handle, data->weight); if (sample_type & PERF_SAMPLE_DATA_SRC) perf_output_put(handle, data->data_src.val); if (sample_type & PERF_SAMPLE_TRANSACTION) perf_output_put(handle, data->txn); if (!event->attr.watermark) { int wakeup_events = event->attr.wakeup_events; if (wakeup_events) { struct ring_buffer *rb = handle->rb; int events = local_inc_return(&rb->events); if (events >= wakeup_events) { local_sub(wakeup_events, &rb->events); local_inc(&rb->wakeup); } } } } void perf_prepare_sample(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event, struct pt_regs *regs) { u64 sample_type = event->attr.sample_type; header->type = PERF_RECORD_SAMPLE; header->size = sizeof(*header) + event->header_size; header->misc = 0; header->misc |= perf_misc_flags(regs); __perf_event_header__init_id(header, data, event); if (sample_type & PERF_SAMPLE_IP) data->ip = perf_instruction_pointer(regs); if (sample_type & PERF_SAMPLE_CALLCHAIN) { int size = 1; data->callchain = perf_callchain(event, regs); if (data->callchain) size += data->callchain->nr; header->size += size * sizeof(u64); } if (sample_type & PERF_SAMPLE_RAW) { int size = sizeof(u32); if (data->raw) size += data->raw->size; else size += sizeof(u32); WARN_ON_ONCE(size & (sizeof(u64)-1)); header->size += size; } if (sample_type & PERF_SAMPLE_BRANCH_STACK) { int size = sizeof(u64); /* nr */ if (data->br_stack) { size += data->br_stack->nr * sizeof(struct perf_branch_entry); } header->size += size; } if (sample_type & PERF_SAMPLE_REGS_USER) { /* regs dump ABI info */ int size = sizeof(u64); perf_sample_regs_user(&data->regs_user, regs); if (data->regs_user.regs) { u64 mask = event->attr.sample_regs_user; size += hweight64(mask) * sizeof(u64); } header->size += size; } if (sample_type & PERF_SAMPLE_STACK_USER) { /* * Either we need PERF_SAMPLE_STACK_USER bit to be allways * processed as the last one or have additional check added * in case new sample type is added, because we could eat * up the rest of the sample size. */ struct perf_regs_user *uregs = &data->regs_user; u16 stack_size = event->attr.sample_stack_user; u16 size = sizeof(u64); if (!uregs->abi) perf_sample_regs_user(uregs, regs); stack_size = perf_sample_ustack_size(stack_size, header->size, uregs->regs); /* * If there is something to dump, add space for the dump * itself and for the field that tells the dynamic size, * which is how many have been actually dumped. */ if (stack_size) size += sizeof(u64) + stack_size; data->stack_user_size = stack_size; header->size += size; } } static void perf_event_output(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { struct perf_output_handle handle; struct perf_event_header header; /* protect the callchain buffers */ rcu_read_lock(); perf_prepare_sample(&header, data, event, regs); if (perf_output_begin(&handle, event, header.size)) goto exit; perf_output_sample(&handle, &header, data, event); perf_output_end(&handle); exit: rcu_read_unlock(); } /* * read event_id */ struct perf_read_event { struct perf_event_header header; u32 pid; u32 tid; }; static void perf_event_read_event(struct perf_event *event, struct task_struct *task) { struct perf_output_handle handle; struct perf_sample_data sample; struct perf_read_event read_event = { .header = { .type = PERF_RECORD_READ, .misc = 0, .size = sizeof(read_event) + event->read_size, }, .pid = perf_event_pid(event, task), .tid = perf_event_tid(event, task), }; int ret; perf_event_header__init_id(&read_event.header, &sample, event); ret = perf_output_begin(&handle, event, read_event.header.size); if (ret) return; perf_output_put(&handle, read_event); perf_output_read(&handle, event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data); static void perf_event_aux_ctx(struct perf_event_context *ctx, perf_event_aux_output_cb output, void *data) { struct perf_event *event; list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->state < PERF_EVENT_STATE_INACTIVE) continue; if (!event_filter_match(event)) continue; output(event, data); } } static void perf_event_aux(perf_event_aux_output_cb output, void *data, struct perf_event_context *task_ctx) { struct perf_cpu_context *cpuctx; struct perf_event_context *ctx; struct pmu *pmu; int ctxn; rcu_read_lock(); list_for_each_entry_rcu(pmu, &pmus, entry) { cpuctx = get_cpu_ptr(pmu->pmu_cpu_context); if (cpuctx->unique_pmu != pmu) goto next; perf_event_aux_ctx(&cpuctx->ctx, output, data); if (task_ctx) goto next; ctxn = pmu->task_ctx_nr; if (ctxn < 0) goto next; ctx = rcu_dereference(current->perf_event_ctxp[ctxn]); if (ctx) perf_event_aux_ctx(ctx, output, data); next: put_cpu_ptr(pmu->pmu_cpu_context); } if (task_ctx) { preempt_disable(); perf_event_aux_ctx(task_ctx, output, data); preempt_enable(); } rcu_read_unlock(); } /* * task tracking -- fork/exit * * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task */ struct perf_task_event { struct task_struct *task; struct perf_event_context *task_ctx; struct { struct perf_event_header header; u32 pid; u32 ppid; u32 tid; u32 ptid; u64 time; } event_id; }; static int perf_event_task_match(struct perf_event *event) { return event->attr.comm || event->attr.mmap || event->attr.mmap2 || event->attr.mmap_data || event->attr.task; } static void perf_event_task_output(struct perf_event *event, void *data) { struct perf_task_event *task_event = data; struct perf_output_handle handle; struct perf_sample_data sample; struct task_struct *task = task_event->task; int ret, size = task_event->event_id.header.size; if (!perf_event_task_match(event)) return; perf_event_header__init_id(&task_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, task_event->event_id.header.size); if (ret) goto out; task_event->event_id.pid = perf_event_pid(event, task); task_event->event_id.ppid = perf_event_pid(event, current); task_event->event_id.tid = perf_event_tid(event, task); task_event->event_id.ptid = perf_event_tid(event, current); perf_output_put(&handle, task_event->event_id); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: task_event->event_id.header.size = size; } static void perf_event_task(struct task_struct *task, struct perf_event_context *task_ctx, int new) { struct perf_task_event task_event; if (!atomic_read(&nr_comm_events) && !atomic_read(&nr_mmap_events) && !atomic_read(&nr_task_events)) return; task_event = (struct perf_task_event){ .task = task, .task_ctx = task_ctx, .event_id = { .header = { .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, .misc = 0, .size = sizeof(task_event.event_id), }, /* .pid */ /* .ppid */ /* .tid */ /* .ptid */ .time = perf_clock(), }, }; perf_event_aux(perf_event_task_output, &task_event, task_ctx); } void perf_event_fork(struct task_struct *task) { perf_event_task(task, NULL, 1); } /* * comm tracking */ struct perf_comm_event { struct task_struct *task; char *comm; int comm_size; struct { struct perf_event_header header; u32 pid; u32 tid; } event_id; }; static int perf_event_comm_match(struct perf_event *event) { return event->attr.comm; } static void perf_event_comm_output(struct perf_event *event, void *data) { struct perf_comm_event *comm_event = data; struct perf_output_handle handle; struct perf_sample_data sample; int size = comm_event->event_id.header.size; int ret; if (!perf_event_comm_match(event)) return; perf_event_header__init_id(&comm_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, comm_event->event_id.header.size); if (ret) goto out; comm_event->event_id.pid = perf_event_pid(event, comm_event->task); comm_event->event_id.tid = perf_event_tid(event, comm_event->task); perf_output_put(&handle, comm_event->event_id); __output_copy(&handle, comm_event->comm, comm_event->comm_size); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: comm_event->event_id.header.size = size; } static void perf_event_comm_event(struct perf_comm_event *comm_event) { char comm[TASK_COMM_LEN]; unsigned int size; memset(comm, 0, sizeof(comm)); strlcpy(comm, comm_event->task->comm, sizeof(comm)); size = ALIGN(strlen(comm)+1, sizeof(u64)); comm_event->comm = comm; comm_event->comm_size = size; comm_event->event_id.header.size = sizeof(comm_event->event_id) + size; perf_event_aux(perf_event_comm_output, comm_event, NULL); } void perf_event_comm(struct task_struct *task, bool exec) { struct perf_comm_event comm_event; if (!atomic_read(&nr_comm_events)) return; comm_event = (struct perf_comm_event){ .task = task, /* .comm */ /* .comm_size */ .event_id = { .header = { .type = PERF_RECORD_COMM, .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0, /* .size */ }, /* .pid */ /* .tid */ }, }; perf_event_comm_event(&comm_event); } /* * mmap tracking */ struct perf_mmap_event { struct vm_area_struct *vma; const char *file_name; int file_size; int maj, min; u64 ino; u64 ino_generation; u32 prot, flags; struct { struct perf_event_header header; u32 pid; u32 tid; u64 start; u64 len; u64 pgoff; } event_id; }; static int perf_event_mmap_match(struct perf_event *event, void *data) { struct perf_mmap_event *mmap_event = data; struct vm_area_struct *vma = mmap_event->vma; int executable = vma->vm_flags & VM_EXEC; return (!executable && event->attr.mmap_data) || (executable && (event->attr.mmap || event->attr.mmap2)); } static void perf_event_mmap_output(struct perf_event *event, void *data) { struct perf_mmap_event *mmap_event = data; struct perf_output_handle handle; struct perf_sample_data sample; int size = mmap_event->event_id.header.size; int ret; if (!perf_event_mmap_match(event, data)) return; if (event->attr.mmap2) { mmap_event->event_id.header.type = PERF_RECORD_MMAP2; mmap_event->event_id.header.size += sizeof(mmap_event->maj); mmap_event->event_id.header.size += sizeof(mmap_event->min); mmap_event->event_id.header.size += sizeof(mmap_event->ino); mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation); mmap_event->event_id.header.size += sizeof(mmap_event->prot); mmap_event->event_id.header.size += sizeof(mmap_event->flags); } perf_event_header__init_id(&mmap_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, mmap_event->event_id.header.size); if (ret) goto out; mmap_event->event_id.pid = perf_event_pid(event, current); mmap_event->event_id.tid = perf_event_tid(event, current); perf_output_put(&handle, mmap_event->event_id); if (event->attr.mmap2) { perf_output_put(&handle, mmap_event->maj); perf_output_put(&handle, mmap_event->min); perf_output_put(&handle, mmap_event->ino); perf_output_put(&handle, mmap_event->ino_generation); perf_output_put(&handle, mmap_event->prot); perf_output_put(&handle, mmap_event->flags); } __output_copy(&handle, mmap_event->file_name, mmap_event->file_size); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: mmap_event->event_id.header.size = size; } static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) { struct vm_area_struct *vma = mmap_event->vma; struct file *file = vma->vm_file; int maj = 0, min = 0; u64 ino = 0, gen = 0; u32 prot = 0, flags = 0; unsigned int size; char tmp[16]; char *buf = NULL; char *name; if (file) { struct inode *inode; dev_t dev; buf = kmalloc(PATH_MAX, GFP_KERNEL); if (!buf) { name = "//enomem"; goto cpy_name; } /* * d_path() works from the end of the rb backwards, so we * need to add enough zero bytes after the string to handle * the 64bit alignment we do later. */ name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64)); if (IS_ERR(name)) { name = "//toolong"; goto cpy_name; } inode = file_inode(vma->vm_file); dev = inode->i_sb->s_dev; ino = inode->i_ino; gen = inode->i_generation; maj = MAJOR(dev); min = MINOR(dev); if (vma->vm_flags & VM_READ) prot |= PROT_READ; if (vma->vm_flags & VM_WRITE) prot |= PROT_WRITE; if (vma->vm_flags & VM_EXEC) prot |= PROT_EXEC; if (vma->vm_flags & VM_MAYSHARE) flags = MAP_SHARED; else flags = MAP_PRIVATE; if (vma->vm_flags & VM_DENYWRITE) flags |= MAP_DENYWRITE; if (vma->vm_flags & VM_MAYEXEC) flags |= MAP_EXECUTABLE; if (vma->vm_flags & VM_LOCKED) flags |= MAP_LOCKED; if (vma->vm_flags & VM_HUGETLB) flags |= MAP_HUGETLB; goto got_name; } else { if (vma->vm_ops && vma->vm_ops->name) { name = (char *) vma->vm_ops->name(vma); if (name) goto cpy_name; } name = (char *)arch_vma_name(vma); if (name) goto cpy_name; if (vma->vm_start <= vma->vm_mm->start_brk && vma->vm_end >= vma->vm_mm->brk) { name = "[heap]"; goto cpy_name; } if (vma->vm_start <= vma->vm_mm->start_stack && vma->vm_end >= vma->vm_mm->start_stack) { name = "[stack]"; goto cpy_name; } name = "//anon"; goto cpy_name; } cpy_name: strlcpy(tmp, name, sizeof(tmp)); name = tmp; got_name: /* * Since our buffer works in 8 byte units we need to align our string * size to a multiple of 8. However, we must guarantee the tail end is * zero'd out to avoid leaking random bits to userspace. */ size = strlen(name)+1; while (!IS_ALIGNED(size, sizeof(u64))) name[size++] = '\0'; mmap_event->file_name = name; mmap_event->file_size = size; mmap_event->maj = maj; mmap_event->min = min; mmap_event->ino = ino; mmap_event->ino_generation = gen; mmap_event->prot = prot; mmap_event->flags = flags; if (!(vma->vm_flags & VM_EXEC)) mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA; mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size; perf_event_aux(perf_event_mmap_output, mmap_event, NULL); kfree(buf); } void perf_event_mmap(struct vm_area_struct *vma) { struct perf_mmap_event mmap_event; if (!atomic_read(&nr_mmap_events)) return; mmap_event = (struct perf_mmap_event){ .vma = vma, /* .file_name */ /* .file_size */ .event_id = { .header = { .type = PERF_RECORD_MMAP, .misc = PERF_RECORD_MISC_USER, /* .size */ }, /* .pid */ /* .tid */ .start = vma->vm_start, .len = vma->vm_end - vma->vm_start, .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT, }, /* .maj (attr_mmap2 only) */ /* .min (attr_mmap2 only) */ /* .ino (attr_mmap2 only) */ /* .ino_generation (attr_mmap2 only) */ /* .prot (attr_mmap2 only) */ /* .flags (attr_mmap2 only) */ }; perf_event_mmap_event(&mmap_event); } /* * IRQ throttle logging */ static void perf_log_throttle(struct perf_event *event, int enable) { struct perf_output_handle handle; struct perf_sample_data sample; int ret; struct { struct perf_event_header header; u64 time; u64 id; u64 stream_id; } throttle_event = { .header = { .type = PERF_RECORD_THROTTLE, .misc = 0, .size = sizeof(throttle_event), }, .time = perf_clock(), .id = primary_event_id(event), .stream_id = event->id, }; if (enable) throttle_event.header.type = PERF_RECORD_UNTHROTTLE; perf_event_header__init_id(&throttle_event.header, &sample, event); ret = perf_output_begin(&handle, event, throttle_event.header.size); if (ret) return; perf_output_put(&handle, throttle_event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } /* * Generic event overflow handling, sampling. */ static int __perf_event_overflow(struct perf_event *event, int throttle, struct perf_sample_data *data, struct pt_regs *regs) { int events = atomic_read(&event->event_limit); struct hw_perf_event *hwc = &event->hw; u64 seq; int ret = 0; /* * Non-sampling counters might still use the PMI to fold short * hardware counters, ignore those. */ if (unlikely(!is_sampling_event(event))) return 0; seq = __this_cpu_read(perf_throttled_seq); if (seq != hwc->interrupts_seq) { hwc->interrupts_seq = seq; hwc->interrupts = 1; } else { hwc->interrupts++; if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { __this_cpu_inc(perf_throttled_count); hwc->interrupts = MAX_INTERRUPTS; perf_log_throttle(event, 0); tick_nohz_full_kick(); ret = 1; } } if (event->attr.freq) { u64 now = perf_clock(); s64 delta = now - hwc->freq_time_stamp; hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) perf_adjust_period(event, delta, hwc->last_period, true); } /* * XXX event_limit might not quite work as expected on inherited * events */ event->pending_kill = POLL_IN; if (events && atomic_dec_and_test(&event->event_limit)) { ret = 1; event->pending_kill = POLL_HUP; event->pending_disable = 1; irq_work_queue(&event->pending); } if (event->overflow_handler) event->overflow_handler(event, data, regs); else perf_event_output(event, data, regs); if (event->fasync && event->pending_kill) { event->pending_wakeup = 1; irq_work_queue(&event->pending); } return ret; } int perf_event_overflow(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { return __perf_event_overflow(event, 1, data, regs); } /* * Generic software event infrastructure */ struct swevent_htable { struct swevent_hlist *swevent_hlist; struct mutex hlist_mutex; int hlist_refcount; /* Recursion avoidance in each contexts */ int recursion[PERF_NR_CONTEXTS]; /* Keeps track of cpu being initialized/exited */ bool online; }; static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); /* * We directly increment event->count and keep a second value in * event->hw.period_left to count intervals. This period event * is kept in the range [-sample_period, 0] so that we can use the * sign as trigger. */ u64 perf_swevent_set_period(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 period = hwc->last_period; u64 nr, offset; s64 old, val; hwc->last_period = hwc->sample_period; again: old = val = local64_read(&hwc->period_left); if (val < 0) return 0; nr = div64_u64(period + val, period); offset = nr * period; val -= offset; if (local64_cmpxchg(&hwc->period_left, old, val) != old) goto again; return nr; } static void perf_swevent_overflow(struct perf_event *event, u64 overflow, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; int throttle = 0; if (!overflow) overflow = perf_swevent_set_period(event); if (hwc->interrupts == MAX_INTERRUPTS) return; for (; overflow; overflow--) { if (__perf_event_overflow(event, throttle, data, regs)) { /* * We inhibit the overflow from happening when * hwc->interrupts == MAX_INTERRUPTS. */ break; } throttle = 1; } } static void perf_swevent_event(struct perf_event *event, u64 nr, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; local64_add(nr, &event->count); if (!regs) return; if (!is_sampling_event(event)) return; if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { data->period = nr; return perf_swevent_overflow(event, 1, data, regs); } else data->period = event->hw.last_period; if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) return perf_swevent_overflow(event, 1, data, regs); if (local64_add_negative(nr, &hwc->period_left)) return; perf_swevent_overflow(event, 0, data, regs); } static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) { if (event->hw.state & PERF_HES_STOPPED) return 1; if (regs) { if (event->attr.exclude_user && user_mode(regs)) return 1; if (event->attr.exclude_kernel && !user_mode(regs)) return 1; } return 0; } static int perf_swevent_match(struct perf_event *event, enum perf_type_id type, u32 event_id, struct perf_sample_data *data, struct pt_regs *regs) { if (event->attr.type != type) return 0; if (event->attr.config != event_id) return 0; if (perf_exclude_event(event, regs)) return 0; return 1; } static inline u64 swevent_hash(u64 type, u32 event_id) { u64 val = event_id | (type << 32); return hash_64(val, SWEVENT_HLIST_BITS); } static inline struct hlist_head * __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) { u64 hash = swevent_hash(type, event_id); return &hlist->heads[hash]; } /* For the read side: events when they trigger */ static inline struct hlist_head * find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) { struct swevent_hlist *hlist; hlist = rcu_dereference(swhash->swevent_hlist); if (!hlist) return NULL; return __find_swevent_head(hlist, type, event_id); } /* For the event head insertion and removal in the hlist */ static inline struct hlist_head * find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) { struct swevent_hlist *hlist; u32 event_id = event->attr.config; u64 type = event->attr.type; /* * Event scheduling is always serialized against hlist allocation * and release. Which makes the protected version suitable here. * The context lock guarantees that. */ hlist = rcu_dereference_protected(swhash->swevent_hlist, lockdep_is_held(&event->ctx->lock)); if (!hlist) return NULL; return __find_swevent_head(hlist, type, event_id); } static void do_perf_sw_event(enum perf_type_id type, u32 event_id, u64 nr, struct perf_sample_data *data, struct pt_regs *regs) { struct swevent_htable *swhash = &__get_cpu_var(swevent_htable); struct perf_event *event; struct hlist_head *head; rcu_read_lock(); head = find_swevent_head_rcu(swhash, type, event_id); if (!head) goto end; hlist_for_each_entry_rcu(event, head, hlist_entry) { if (perf_swevent_match(event, type, event_id, data, regs)) perf_swevent_event(event, nr, data, regs); } end: rcu_read_unlock(); } int perf_swevent_get_recursion_context(void) { struct swevent_htable *swhash = &__get_cpu_var(swevent_htable); return get_recursion_context(swhash->recursion); } EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); inline void perf_swevent_put_recursion_context(int rctx) { struct swevent_htable *swhash = &__get_cpu_var(swevent_htable); put_recursion_context(swhash->recursion, rctx); } void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) { struct perf_sample_data data; int rctx; preempt_disable_notrace(); rctx = perf_swevent_get_recursion_context(); if (rctx < 0) return; perf_sample_data_init(&data, addr, 0); do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); perf_swevent_put_recursion_context(rctx); preempt_enable_notrace(); } static void perf_swevent_read(struct perf_event *event) { } static int perf_swevent_add(struct perf_event *event, int flags) { struct swevent_htable *swhash = &__get_cpu_var(swevent_htable); struct hw_perf_event *hwc = &event->hw; struct hlist_head *head; if (is_sampling_event(event)) { hwc->last_period = hwc->sample_period; perf_swevent_set_period(event); } hwc->state = !(flags & PERF_EF_START); head = find_swevent_head(swhash, event); if (!head) { /* * We can race with cpu hotplug code. Do not * WARN if the cpu just got unplugged. */ WARN_ON_ONCE(swhash->online); return -EINVAL; } hlist_add_head_rcu(&event->hlist_entry, head); return 0; } static void perf_swevent_del(struct perf_event *event, int flags) { hlist_del_rcu(&event->hlist_entry); } static void perf_swevent_start(struct perf_event *event, int flags) { event->hw.state = 0; } static void perf_swevent_stop(struct perf_event *event, int flags) { event->hw.state = PERF_HES_STOPPED; } /* Deref the hlist from the update side */ static inline struct swevent_hlist * swevent_hlist_deref(struct swevent_htable *swhash) { return rcu_dereference_protected(swhash->swevent_hlist, lockdep_is_held(&swhash->hlist_mutex)); } static void swevent_hlist_release(struct swevent_htable *swhash) { struct swevent_hlist *hlist = swevent_hlist_deref(swhash); if (!hlist) return; rcu_assign_pointer(swhash->swevent_hlist, NULL); kfree_rcu(hlist, rcu_head); } static void swevent_hlist_put_cpu(struct perf_event *event, int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); if (!--swhash->hlist_refcount) swevent_hlist_release(swhash); mutex_unlock(&swhash->hlist_mutex); } static void swevent_hlist_put(struct perf_event *event) { int cpu; for_each_possible_cpu(cpu) swevent_hlist_put_cpu(event, cpu); } static int swevent_hlist_get_cpu(struct perf_event *event, int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); int err = 0; mutex_lock(&swhash->hlist_mutex); if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) { struct swevent_hlist *hlist; hlist = kzalloc(sizeof(*hlist), GFP_KERNEL); if (!hlist) { err = -ENOMEM; goto exit; } rcu_assign_pointer(swhash->swevent_hlist, hlist); } swhash->hlist_refcount++; exit: mutex_unlock(&swhash->hlist_mutex); return err; } static int swevent_hlist_get(struct perf_event *event) { int err; int cpu, failed_cpu; get_online_cpus(); for_each_possible_cpu(cpu) { err = swevent_hlist_get_cpu(event, cpu); if (err) { failed_cpu = cpu; goto fail; } } put_online_cpus(); return 0; fail: for_each_possible_cpu(cpu) { if (cpu == failed_cpu) break; swevent_hlist_put_cpu(event, cpu); } put_online_cpus(); return err; } struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; static void sw_perf_event_destroy(struct perf_event *event) { u64 event_id = event->attr.config; WARN_ON(event->parent); static_key_slow_dec(&perf_swevent_enabled[event_id]); swevent_hlist_put(event); } static int perf_swevent_init(struct perf_event *event) { u64 event_id = event->attr.config; if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; switch (event_id) { case PERF_COUNT_SW_CPU_CLOCK: case PERF_COUNT_SW_TASK_CLOCK: return -ENOENT; default: break; } if (event_id >= PERF_COUNT_SW_MAX) return -ENOENT; if (!event->parent) { int err; err = swevent_hlist_get(event); if (err) return err; static_key_slow_inc(&perf_swevent_enabled[event_id]); event->destroy = sw_perf_event_destroy; } return 0; } static int perf_swevent_event_idx(struct perf_event *event) { return 0; } static struct pmu perf_swevent = { .task_ctx_nr = perf_sw_context, .event_init = perf_swevent_init, .add = perf_swevent_add, .del = perf_swevent_del, .start = perf_swevent_start, .stop = perf_swevent_stop, .read = perf_swevent_read, .event_idx = perf_swevent_event_idx, }; #ifdef CONFIG_EVENT_TRACING static int perf_tp_filter_match(struct perf_event *event, struct perf_sample_data *data) { void *record = data->raw->data; if (likely(!event->filter) || filter_match_preds(event->filter, record)) return 1; return 0; } static int perf_tp_event_match(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { if (event->hw.state & PERF_HES_STOPPED) return 0; /* * All tracepoints are from kernel-space. */ if (event->attr.exclude_kernel) return 0; if (!perf_tp_filter_match(event, data)) return 0; return 1; } void perf_tp_event(u64 addr, u64 count, void *record, int entry_size, struct pt_regs *regs, struct hlist_head *head, int rctx, struct task_struct *task) { struct perf_sample_data data; struct perf_event *event; struct perf_raw_record raw = { .size = entry_size, .data = record, }; perf_sample_data_init(&data, addr, 0); data.raw = &raw; hlist_for_each_entry_rcu(event, head, hlist_entry) { if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } /* * If we got specified a target task, also iterate its context and * deliver this event there too. */ if (task && task != current) { struct perf_event_context *ctx; struct trace_entry *entry = record; rcu_read_lock(); ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]); if (!ctx) goto unlock; list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->attr.type != PERF_TYPE_TRACEPOINT) continue; if (event->attr.config != entry->type) continue; if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } unlock: rcu_read_unlock(); } perf_swevent_put_recursion_context(rctx); } EXPORT_SYMBOL_GPL(perf_tp_event); static void tp_perf_event_destroy(struct perf_event *event) { perf_trace_destroy(event); } static int perf_tp_event_init(struct perf_event *event) { int err; if (event->attr.type != PERF_TYPE_TRACEPOINT) return -ENOENT; /* * no branch sampling for tracepoint events */ if (has_branch_stack(event)) return -EOPNOTSUPP; err = perf_trace_init(event); if (err) return err; event->destroy = tp_perf_event_destroy; return 0; } static struct pmu perf_tracepoint = { .task_ctx_nr = perf_sw_context, .event_init = perf_tp_event_init, .add = perf_trace_add, .del = perf_trace_del, .start = perf_swevent_start, .stop = perf_swevent_stop, .read = perf_swevent_read, .event_idx = perf_swevent_event_idx, }; static inline void perf_tp_register(void) { perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); } static int perf_event_set_filter(struct perf_event *event, void __user *arg) { char *filter_str; int ret; if (event->attr.type != PERF_TYPE_TRACEPOINT) return -EINVAL; filter_str = strndup_user(arg, PAGE_SIZE); if (IS_ERR(filter_str)) return PTR_ERR(filter_str); ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); kfree(filter_str); return ret; } static void perf_event_free_filter(struct perf_event *event) { ftrace_profile_free_filter(event); } #else static inline void perf_tp_register(void) { } static int perf_event_set_filter(struct perf_event *event, void __user *arg) { return -ENOENT; } static void perf_event_free_filter(struct perf_event *event) { } #endif /* CONFIG_EVENT_TRACING */ #ifdef CONFIG_HAVE_HW_BREAKPOINT void perf_bp_event(struct perf_event *bp, void *data) { struct perf_sample_data sample; struct pt_regs *regs = data; perf_sample_data_init(&sample, bp->attr.bp_addr, 0); if (!bp->hw.state && !perf_exclude_event(bp, regs)) perf_swevent_event(bp, 1, &sample, regs); } #endif /* * hrtimer based swevent callback */ static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) { enum hrtimer_restart ret = HRTIMER_RESTART; struct perf_sample_data data; struct pt_regs *regs; struct perf_event *event; u64 period; event = container_of(hrtimer, struct perf_event, hw.hrtimer); if (event->state != PERF_EVENT_STATE_ACTIVE) return HRTIMER_NORESTART; event->pmu->read(event); perf_sample_data_init(&data, 0, event->hw.last_period); regs = get_irq_regs(); if (regs && !perf_exclude_event(event, regs)) { if (!(event->attr.exclude_idle && is_idle_task(current))) if (__perf_event_overflow(event, 1, &data, regs)) ret = HRTIMER_NORESTART; } period = max_t(u64, 10000, event->hw.sample_period); hrtimer_forward_now(hrtimer, ns_to_ktime(period)); return ret; } static void perf_swevent_start_hrtimer(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; s64 period; if (!is_sampling_event(event)) return; period = local64_read(&hwc->period_left); if (period) { if (period < 0) period = 10000; local64_set(&hwc->period_left, 0); } else { period = max_t(u64, 10000, hwc->sample_period); } __hrtimer_start_range_ns(&hwc->hrtimer, ns_to_ktime(period), 0, HRTIMER_MODE_REL_PINNED, 0); } static void perf_swevent_cancel_hrtimer(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (is_sampling_event(event)) { ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); local64_set(&hwc->period_left, ktime_to_ns(remaining)); hrtimer_cancel(&hwc->hrtimer); } } static void perf_swevent_init_hrtimer(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!is_sampling_event(event)) return; hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); hwc->hrtimer.function = perf_swevent_hrtimer; /* * Since hrtimers have a fixed rate, we can do a static freq->period * mapping and avoid the whole period adjust feedback stuff. */ if (event->attr.freq) { long freq = event->attr.sample_freq; event->attr.sample_period = NSEC_PER_SEC / freq; hwc->sample_period = event->attr.sample_period; local64_set(&hwc->period_left, hwc->sample_period); hwc->last_period = hwc->sample_period; event->attr.freq = 0; } } /* * Software event: cpu wall time clock */ static void cpu_clock_event_update(struct perf_event *event) { s64 prev; u64 now; now = local_clock(); prev = local64_xchg(&event->hw.prev_count, now); local64_add(now - prev, &event->count); } static void cpu_clock_event_start(struct perf_event *event, int flags) { local64_set(&event->hw.prev_count, local_clock()); perf_swevent_start_hrtimer(event); } static void cpu_clock_event_stop(struct perf_event *event, int flags) { perf_swevent_cancel_hrtimer(event); cpu_clock_event_update(event); } static int cpu_clock_event_add(struct perf_event *event, int flags) { if (flags & PERF_EF_START) cpu_clock_event_start(event, flags); return 0; } static void cpu_clock_event_del(struct perf_event *event, int flags) { cpu_clock_event_stop(event, flags); } static void cpu_clock_event_read(struct perf_event *event) { cpu_clock_event_update(event); } static int cpu_clock_event_init(struct perf_event *event) { if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; perf_swevent_init_hrtimer(event); return 0; } static struct pmu perf_cpu_clock = { .task_ctx_nr = perf_sw_context, .event_init = cpu_clock_event_init, .add = cpu_clock_event_add, .del = cpu_clock_event_del, .start = cpu_clock_event_start, .stop = cpu_clock_event_stop, .read = cpu_clock_event_read, .event_idx = perf_swevent_event_idx, }; /* * Software event: task time clock */ static void task_clock_event_update(struct perf_event *event, u64 now) { u64 prev; s64 delta; prev = local64_xchg(&event->hw.prev_count, now); delta = now - prev; local64_add(delta, &event->count); } static void task_clock_event_start(struct perf_event *event, int flags) { local64_set(&event->hw.prev_count, event->ctx->time); perf_swevent_start_hrtimer(event); } static void task_clock_event_stop(struct perf_event *event, int flags) { perf_swevent_cancel_hrtimer(event); task_clock_event_update(event, event->ctx->time); } static int task_clock_event_add(struct perf_event *event, int flags) { if (flags & PERF_EF_START) task_clock_event_start(event, flags); return 0; } static void task_clock_event_del(struct perf_event *event, int flags) { task_clock_event_stop(event, PERF_EF_UPDATE); } static void task_clock_event_read(struct perf_event *event) { u64 now = perf_clock(); u64 delta = now - event->ctx->timestamp; u64 time = event->ctx->time + delta; task_clock_event_update(event, time); } static int task_clock_event_init(struct perf_event *event) { if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; perf_swevent_init_hrtimer(event); return 0; } static struct pmu perf_task_clock = { .task_ctx_nr = perf_sw_context, .event_init = task_clock_event_init, .add = task_clock_event_add, .del = task_clock_event_del, .start = task_clock_event_start, .stop = task_clock_event_stop, .read = task_clock_event_read, .event_idx = perf_swevent_event_idx, }; static void perf_pmu_nop_void(struct pmu *pmu) { } static int perf_pmu_nop_int(struct pmu *pmu) { return 0; } static void perf_pmu_start_txn(struct pmu *pmu) { perf_pmu_disable(pmu); } static int perf_pmu_commit_txn(struct pmu *pmu) { perf_pmu_enable(pmu); return 0; } static void perf_pmu_cancel_txn(struct pmu *pmu) { perf_pmu_enable(pmu); } static int perf_event_idx_default(struct perf_event *event) { return event->hw.idx + 1; } /* * Ensures all contexts with the same task_ctx_nr have the same * pmu_cpu_context too. */ static struct perf_cpu_context __percpu *find_pmu_context(int ctxn) { struct pmu *pmu; if (ctxn < 0) return NULL; list_for_each_entry(pmu, &pmus, entry) { if (pmu->task_ctx_nr == ctxn) return pmu->pmu_cpu_context; } return NULL; } static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu) { int cpu; for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); if (cpuctx->unique_pmu == old_pmu) cpuctx->unique_pmu = pmu; } } static void free_pmu_context(struct pmu *pmu) { struct pmu *i; mutex_lock(&pmus_lock); /* * Like a real lame refcount. */ list_for_each_entry(i, &pmus, entry) { if (i->pmu_cpu_context == pmu->pmu_cpu_context) { update_pmu_context(i, pmu); goto out; } } free_percpu(pmu->pmu_cpu_context); out: mutex_unlock(&pmus_lock); } static struct idr pmu_idr; static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *page) { struct pmu *pmu = dev_get_drvdata(dev); return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type); } static DEVICE_ATTR_RO(type); static ssize_t perf_event_mux_interval_ms_show(struct device *dev, struct device_attribute *attr, char *page) { struct pmu *pmu = dev_get_drvdata(dev); return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms); } static ssize_t perf_event_mux_interval_ms_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pmu *pmu = dev_get_drvdata(dev); int timer, cpu, ret; ret = kstrtoint(buf, 0, &timer); if (ret) return ret; if (timer < 1) return -EINVAL; /* same value, noting to do */ if (timer == pmu->hrtimer_interval_ms) return count; pmu->hrtimer_interval_ms = timer; /* update all cpuctx for this PMU */ for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); if (hrtimer_active(&cpuctx->hrtimer)) hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval); } return count; } static DEVICE_ATTR_RW(perf_event_mux_interval_ms); static struct attribute *pmu_dev_attrs[] = { &dev_attr_type.attr, &dev_attr_perf_event_mux_interval_ms.attr, NULL, }; ATTRIBUTE_GROUPS(pmu_dev); static int pmu_bus_running; static struct bus_type pmu_bus = { .name = "event_source", .dev_groups = pmu_dev_groups, }; static void pmu_dev_release(struct device *dev) { kfree(dev); } static int pmu_dev_alloc(struct pmu *pmu) { int ret = -ENOMEM; pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL); if (!pmu->dev) goto out; pmu->dev->groups = pmu->attr_groups; device_initialize(pmu->dev); ret = dev_set_name(pmu->dev, "%s", pmu->name); if (ret) goto free_dev; dev_set_drvdata(pmu->dev, pmu); pmu->dev->bus = &pmu_bus; pmu->dev->release = pmu_dev_release; ret = device_add(pmu->dev); if (ret) goto free_dev; out: return ret; free_dev: put_device(pmu->dev); goto out; } static struct lock_class_key cpuctx_mutex; static struct lock_class_key cpuctx_lock; int perf_pmu_register(struct pmu *pmu, const char *name, int type) { int cpu, ret; mutex_lock(&pmus_lock); ret = -ENOMEM; pmu->pmu_disable_count = alloc_percpu(int); if (!pmu->pmu_disable_count) goto unlock; pmu->type = -1; if (!name) goto skip_type; pmu->name = name; if (type < 0) { type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL); if (type < 0) { ret = type; goto free_pdc; } } pmu->type = type; if (pmu_bus_running) { ret = pmu_dev_alloc(pmu); if (ret) goto free_idr; } skip_type: pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr); if (pmu->pmu_cpu_context) goto got_cpu_context; ret = -ENOMEM; pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context); if (!pmu->pmu_cpu_context) goto free_dev; for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); __perf_event_init_context(&cpuctx->ctx); lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); cpuctx->ctx.type = cpu_context; cpuctx->ctx.pmu = pmu; __perf_cpu_hrtimer_init(cpuctx, cpu); INIT_LIST_HEAD(&cpuctx->rotation_list); cpuctx->unique_pmu = pmu; } got_cpu_context: if (!pmu->start_txn) { if (pmu->pmu_enable) { /* * If we have pmu_enable/pmu_disable calls, install * transaction stubs that use that to try and batch * hardware accesses. */ pmu->start_txn = perf_pmu_start_txn; pmu->commit_txn = perf_pmu_commit_txn; pmu->cancel_txn = perf_pmu_cancel_txn; } else { pmu->start_txn = perf_pmu_nop_void; pmu->commit_txn = perf_pmu_nop_int; pmu->cancel_txn = perf_pmu_nop_void; } } if (!pmu->pmu_enable) { pmu->pmu_enable = perf_pmu_nop_void; pmu->pmu_disable = perf_pmu_nop_void; } if (!pmu->event_idx) pmu->event_idx = perf_event_idx_default; list_add_rcu(&pmu->entry, &pmus); ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; free_dev: device_del(pmu->dev); put_device(pmu->dev); free_idr: if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); free_pdc: free_percpu(pmu->pmu_disable_count); goto unlock; } EXPORT_SYMBOL_GPL(perf_pmu_register); void perf_pmu_unregister(struct pmu *pmu) { mutex_lock(&pmus_lock); list_del_rcu(&pmu->entry); mutex_unlock(&pmus_lock); /* * We dereference the pmu list under both SRCU and regular RCU, so * synchronize against both of those. */ synchronize_srcu(&pmus_srcu); synchronize_rcu(); free_percpu(pmu->pmu_disable_count); if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); device_del(pmu->dev); put_device(pmu->dev); free_pmu_context(pmu); } EXPORT_SYMBOL_GPL(perf_pmu_unregister); struct pmu *perf_init_event(struct perf_event *event) { struct pmu *pmu = NULL; int idx; int ret; idx = srcu_read_lock(&pmus_srcu); rcu_read_lock(); pmu = idr_find(&pmu_idr, event->attr.type); rcu_read_unlock(); if (pmu) { if (!try_module_get(pmu->module)) { pmu = ERR_PTR(-ENODEV); goto unlock; } event->pmu = pmu; ret = pmu->event_init(event); if (ret) pmu = ERR_PTR(ret); goto unlock; } list_for_each_entry_rcu(pmu, &pmus, entry) { if (!try_module_get(pmu->module)) { pmu = ERR_PTR(-ENODEV); goto unlock; } event->pmu = pmu; ret = pmu->event_init(event); if (!ret) goto unlock; if (ret != -ENOENT) { pmu = ERR_PTR(ret); goto unlock; } } pmu = ERR_PTR(-ENOENT); unlock: srcu_read_unlock(&pmus_srcu, idx); return pmu; } static void account_event_cpu(struct perf_event *event, int cpu) { if (event->parent) return; if (has_branch_stack(event)) { if (!(event->attach_state & PERF_ATTACH_TASK)) atomic_inc(&per_cpu(perf_branch_stack_events, cpu)); } if (is_cgroup_event(event)) atomic_inc(&per_cpu(perf_cgroup_events, cpu)); } static void account_event(struct perf_event *event) { if (event->parent) return; if (event->attach_state & PERF_ATTACH_TASK) static_key_slow_inc(&perf_sched_events.key); if (event->attr.mmap || event->attr.mmap_data) atomic_inc(&nr_mmap_events); if (event->attr.comm) atomic_inc(&nr_comm_events); if (event->attr.task) atomic_inc(&nr_task_events); if (event->attr.freq) { if (atomic_inc_return(&nr_freq_events) == 1) tick_nohz_full_kick_all(); } if (has_branch_stack(event)) static_key_slow_inc(&perf_sched_events.key); if (is_cgroup_event(event)) static_key_slow_inc(&perf_sched_events.key); account_event_cpu(event, event->cpu); } /* * Allocate and initialize a event structure */ static struct perf_event * perf_event_alloc(struct perf_event_attr *attr, int cpu, struct task_struct *task, struct perf_event *group_leader, struct perf_event *parent_event, perf_overflow_handler_t overflow_handler, void *context) { struct pmu *pmu; struct perf_event *event; struct hw_perf_event *hwc; long err = -EINVAL; if ((unsigned)cpu >= nr_cpu_ids) { if (!task || cpu != -1) return ERR_PTR(-EINVAL); } event = kzalloc(sizeof(*event), GFP_KERNEL); if (!event) return ERR_PTR(-ENOMEM); /* * Single events are their own group leaders, with an * empty sibling list: */ if (!group_leader) group_leader = event; mutex_init(&event->child_mutex); INIT_LIST_HEAD(&event->child_list); INIT_LIST_HEAD(&event->group_entry); INIT_LIST_HEAD(&event->event_entry); INIT_LIST_HEAD(&event->sibling_list); INIT_LIST_HEAD(&event->rb_entry); INIT_LIST_HEAD(&event->active_entry); INIT_HLIST_NODE(&event->hlist_entry); init_waitqueue_head(&event->waitq); init_irq_work(&event->pending, perf_pending_event); mutex_init(&event->mmap_mutex); atomic_long_set(&event->refcount, 1); event->cpu = cpu; event->attr = *attr; event->group_leader = group_leader; event->pmu = NULL; event->oncpu = -1; event->parent = parent_event; event->ns = get_pid_ns(task_active_pid_ns(current)); event->id = atomic64_inc_return(&perf_event_id); event->state = PERF_EVENT_STATE_INACTIVE; if (task) { event->attach_state = PERF_ATTACH_TASK; if (attr->type == PERF_TYPE_TRACEPOINT) event->hw.tp_target = task; #ifdef CONFIG_HAVE_HW_BREAKPOINT /* * hw_breakpoint is a bit difficult here.. */ else if (attr->type == PERF_TYPE_BREAKPOINT) event->hw.bp_target = task; #endif } if (!overflow_handler && parent_event) { overflow_handler = parent_event->overflow_handler; context = parent_event->overflow_handler_context; } event->overflow_handler = overflow_handler; event->overflow_handler_context = context; perf_event__state_init(event); pmu = NULL; hwc = &event->hw; hwc->sample_period = attr->sample_period; if (attr->freq && attr->sample_freq) hwc->sample_period = 1; hwc->last_period = hwc->sample_period; local64_set(&hwc->period_left, hwc->sample_period); /* * we currently do not support PERF_FORMAT_GROUP on inherited events */ if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP)) goto err_ns; pmu = perf_init_event(event); if (!pmu) goto err_ns; else if (IS_ERR(pmu)) { err = PTR_ERR(pmu); goto err_ns; } if (!event->parent) { if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { err = get_callchain_buffers(); if (err) goto err_pmu; } } return event; err_pmu: if (event->destroy) event->destroy(event); module_put(pmu->module); err_ns: if (event->ns) put_pid_ns(event->ns); kfree(event); return ERR_PTR(err); } static int perf_copy_attr(struct perf_event_attr __user *uattr, struct perf_event_attr *attr) { u32 size; int ret; if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0)) return -EFAULT; /* * zero the full structure, so that a short copy will be nice. */ memset(attr, 0, sizeof(*attr)); ret = get_user(size, &uattr->size); if (ret) return ret; if (size > PAGE_SIZE) /* silly large */ goto err_size; if (!size) /* abi compat */ size = PERF_ATTR_SIZE_VER0; if (size < PERF_ATTR_SIZE_VER0) goto err_size; /* * If we're handed a bigger struct than we know of, * ensure all the unknown bits are 0 - i.e. new * user-space does not rely on any kernel feature * extensions we dont know about yet. */ if (size > sizeof(*attr)) { unsigned char __user *addr; unsigned char __user *end; unsigned char val; addr = (void __user *)uattr + sizeof(*attr); end = (void __user *)uattr + size; for (; addr < end; addr++) { ret = get_user(val, addr); if (ret) return ret; if (val) goto err_size; } size = sizeof(*attr); } ret = copy_from_user(attr, uattr, size); if (ret) return -EFAULT; if (attr->__reserved_1) return -EINVAL; if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) return -EINVAL; if (attr->read_format & ~(PERF_FORMAT_MAX-1)) return -EINVAL; if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { u64 mask = attr->branch_sample_type; /* only using defined bits */ if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) return -EINVAL; /* at least one branch bit must be set */ if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) return -EINVAL; /* propagate priv level, when not set for branch */ if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { /* exclude_kernel checked on syscall entry */ if (!attr->exclude_kernel) mask |= PERF_SAMPLE_BRANCH_KERNEL; if (!attr->exclude_user) mask |= PERF_SAMPLE_BRANCH_USER; if (!attr->exclude_hv) mask |= PERF_SAMPLE_BRANCH_HV; /* * adjust user setting (for HW filter setup) */ attr->branch_sample_type = mask; } /* privileged levels capture (kernel, hv): check permissions */ if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM) && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr->sample_type & PERF_SAMPLE_REGS_USER) { ret = perf_reg_validate(attr->sample_regs_user); if (ret) return ret; } if (attr->sample_type & PERF_SAMPLE_STACK_USER) { if (!arch_perf_have_user_stack_dump()) return -ENOSYS; /* * We have __u32 type for the size, but so far * we can only use __u16 as maximum due to the * __u16 sample size limit. */ if (attr->sample_stack_user >= USHRT_MAX) ret = -EINVAL; else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) ret = -EINVAL; } out: return ret; err_size: put_user(sizeof(*attr), &uattr->size); ret = -E2BIG; goto out; } static int perf_event_set_output(struct perf_event *event, struct perf_event *output_event) { struct ring_buffer *rb = NULL; int ret = -EINVAL; if (!output_event) goto set; /* don't allow circular references */ if (event == output_event) goto out; /* * Don't allow cross-cpu buffers */ if (output_event->cpu != event->cpu) goto out; /* * If its not a per-cpu rb, it must be the same task. */ if (output_event->cpu == -1 && output_event->ctx != event->ctx) goto out; set: mutex_lock(&event->mmap_mutex); /* Can't redirect output if we've got an active mmap() */ if (atomic_read(&event->mmap_count)) goto unlock; if (output_event) { /* get the rb we want to redirect to */ rb = ring_buffer_get(output_event); if (!rb) goto unlock; } ring_buffer_attach(event, rb); ret = 0; unlock: mutex_unlock(&event->mmap_mutex); out: return ret; } /** * sys_perf_event_open - open a performance event, associate it to a task/cpu * * @attr_uptr: event_id type attributes for monitoring/sampling * @pid: target pid * @cpu: target cpu * @group_fd: group leader event fd */ SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx; struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cpus; } if (flags & PERF_FLAG_PID_CGROUP) { err = perf_cgroup_connect(pid, event, &attr, group_leader); if (err) { __free_event(event); goto err_cpus; } } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -ENOTSUPP; goto err_alloc; } } account_event(event); /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_flags & PERF_GROUP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event->cpu); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if (task) { put_task_struct(task); task = NULL; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { if (group_leader->ctx->type != ctx->type) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); goto err_context; } if (move_group) { struct perf_event_context *gctx = group_leader->ctx; mutex_lock(&gctx->mutex); perf_remove_from_context(group_leader, false); /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, false); perf_event__state_init(sibling); put_ctx(gctx); } mutex_unlock(&gctx->mutex); put_ctx(gctx); } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); if (move_group) { synchronize_rcu(); perf_install_in_context(ctx, group_leader, event->cpu); get_ctx(ctx); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_install_in_context(ctx, sibling, event->cpu); get_ctx(ctx); } } perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); put_online_cpus(); event->owner = current; mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Precalculate sample_data sizes */ perf_event__header_size(event); perf_event__id_header_size(event); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: free_event(event); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; } /** * perf_event_create_kernel_counter * * @attr: attributes of the counter to create * @cpu: cpu in which the counter is bound * @task: task to profile (NULL for percpu) */ struct perf_event * perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, struct task_struct *task, perf_overflow_handler_t overflow_handler, void *context) { struct perf_event_context *ctx; struct perf_event *event; int err; /* * Get the target context (task or percpu): */ event = perf_event_alloc(attr, cpu, task, NULL, NULL, overflow_handler, context); if (IS_ERR(event)) { err = PTR_ERR(event); goto err; } account_event(event); ctx = find_get_context(event->pmu, task, cpu); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_free; } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); perf_install_in_context(ctx, event, cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); return event; err_free: free_event(event); err: return ERR_PTR(err); } EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) { struct perf_event_context *src_ctx; struct perf_event_context *dst_ctx; struct perf_event *event, *tmp; LIST_HEAD(events); src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx; dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx; mutex_lock(&src_ctx->mutex); list_for_each_entry_safe(event, tmp, &src_ctx->event_list, event_entry) { perf_remove_from_context(event, false); unaccount_event_cpu(event, src_cpu); put_ctx(src_ctx); list_add(&event->migrate_entry, &events); } mutex_unlock(&src_ctx->mutex); synchronize_rcu(); mutex_lock(&dst_ctx->mutex); list_for_each_entry_safe(event, tmp, &events, migrate_entry) { list_del(&event->migrate_entry); if (event->state >= PERF_EVENT_STATE_OFF) event->state = PERF_EVENT_STATE_INACTIVE; account_event_cpu(event, dst_cpu); perf_install_in_context(dst_ctx, event, dst_cpu); get_ctx(dst_ctx); } mutex_unlock(&dst_ctx->mutex); } EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); static void sync_child_event(struct perf_event *child_event, struct task_struct *child) { struct perf_event *parent_event = child_event->parent; u64 child_val; if (child_event->attr.inherit_stat) perf_event_read_event(child_event, child); child_val = perf_event_count(child_event); /* * Add back the child's count to the parent's count: */ atomic64_add(child_val, &parent_event->child_count); atomic64_add(child_event->total_time_enabled, &parent_event->child_total_time_enabled); atomic64_add(child_event->total_time_running, &parent_event->child_total_time_running); /* * Remove this event from the parent's list */ WARN_ON_ONCE(parent_event->ctx->parent_ctx); mutex_lock(&parent_event->child_mutex); list_del_init(&child_event->child_list); mutex_unlock(&parent_event->child_mutex); /* * Release the parent event, if this was the last * reference to it. */ put_event(parent_event); } static void __perf_event_exit_task(struct perf_event *child_event, struct perf_event_context *child_ctx, struct task_struct *child) { /* * Do not destroy the 'original' grouping; because of the context * switch optimization the original events could've ended up in a * random child task. * * If we were to destroy the original group, all group related * operations would cease to function properly after this random * child dies. * * Do destroy all inherited groups, we don't care about those * and being thorough is better. */ perf_remove_from_context(child_event, !!child_event->parent); /* * It can happen that the parent exits first, and has events * that are still around due to the child reference. These * events need to be zapped. */ if (child_event->parent) { sync_child_event(child_event, child); free_event(child_event); } } static void perf_event_exit_task_context(struct task_struct *child, int ctxn) { struct perf_event *child_event, *next; struct perf_event_context *child_ctx, *parent_ctx; unsigned long flags; if (likely(!child->perf_event_ctxp[ctxn])) { perf_event_task(child, NULL, 0); return; } local_irq_save(flags); /* * We can't reschedule here because interrupts are disabled, * and either child is current or it is a task that can't be * scheduled, so we are now safe from rescheduling changing * our context. */ child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]); /* * Take the context lock here so that if find_get_context is * reading child->perf_event_ctxp, we wait until it has * incremented the context's refcount before we do put_ctx below. */ raw_spin_lock(&child_ctx->lock); task_ctx_sched_out(child_ctx); child->perf_event_ctxp[ctxn] = NULL; /* * In order to avoid freeing: child_ctx->parent_ctx->task * under perf_event_context::lock, grab another reference. */ parent_ctx = child_ctx->parent_ctx; if (parent_ctx) get_ctx(parent_ctx); /* * If this context is a clone; unclone it so it can't get * swapped to another process while we're removing all * the events from it. */ unclone_ctx(child_ctx); update_context_time(child_ctx); raw_spin_unlock_irqrestore(&child_ctx->lock, flags); /* * Now that we no longer hold perf_event_context::lock, drop * our extra child_ctx->parent_ctx reference. */ if (parent_ctx) put_ctx(parent_ctx); /* * Report the task dead after unscheduling the events so that we * won't get any samples after PERF_RECORD_EXIT. We can however still * get a few PERF_RECORD_READ events. */ perf_event_task(child, child_ctx, 0); /* * We can recurse on the same lock type through: * * __perf_event_exit_task() * sync_child_event() * put_event() * mutex_lock(&ctx->mutex) * * But since its the parent context it won't be the same instance. */ mutex_lock(&child_ctx->mutex); list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry) __perf_event_exit_task(child_event, child_ctx, child); mutex_unlock(&child_ctx->mutex); put_ctx(child_ctx); } /* * When a child task exits, feed back event values to parent events. */ void perf_event_exit_task(struct task_struct *child) { struct perf_event *event, *tmp; int ctxn; mutex_lock(&child->perf_event_mutex); list_for_each_entry_safe(event, tmp, &child->perf_event_list, owner_entry) { list_del_init(&event->owner_entry); /* * Ensure the list deletion is visible before we clear * the owner, closes a race against perf_release() where * we need to serialize on the owner->perf_event_mutex. */ smp_wmb(); event->owner = NULL; } mutex_unlock(&child->perf_event_mutex); for_each_task_context_nr(ctxn) perf_event_exit_task_context(child, ctxn); } static void perf_free_event(struct perf_event *event, struct perf_event_context *ctx) { struct perf_event *parent = event->parent; if (WARN_ON_ONCE(!parent)) return; mutex_lock(&parent->child_mutex); list_del_init(&event->child_list); mutex_unlock(&parent->child_mutex); put_event(parent); perf_group_detach(event); list_del_event(event, ctx); free_event(event); } /* * free an unexposed, unused context as created by inheritance by * perf_event_init_task below, used by fork() in case of fail. */ void perf_event_free_task(struct task_struct *task) { struct perf_event_context *ctx; struct perf_event *event, *tmp; int ctxn; for_each_task_context_nr(ctxn) { ctx = task->perf_event_ctxp[ctxn]; if (!ctx) continue; mutex_lock(&ctx->mutex); again: list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry) perf_free_event(event, ctx); list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry) perf_free_event(event, ctx); if (!list_empty(&ctx->pinned_groups) || !list_empty(&ctx->flexible_groups)) goto again; mutex_unlock(&ctx->mutex); put_ctx(ctx); } } void perf_event_delayed_put(struct task_struct *task) { int ctxn; for_each_task_context_nr(ctxn) WARN_ON_ONCE(task->perf_event_ctxp[ctxn]); } /* * inherit a event from parent task to child task: */ static struct perf_event * inherit_event(struct perf_event *parent_event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, struct perf_event *group_leader, struct perf_event_context *child_ctx) { struct perf_event *child_event; unsigned long flags; /* * Instead of creating recursive hierarchies of events, * we link inherited events back to the original parent, * which has a filp for sure, which we use as the reference * count: */ if (parent_event->parent) parent_event = parent_event->parent; child_event = perf_event_alloc(&parent_event->attr, parent_event->cpu, child, group_leader, parent_event, NULL, NULL); if (IS_ERR(child_event)) return child_event; if (!atomic_long_inc_not_zero(&parent_event->refcount)) { free_event(child_event); return NULL; } get_ctx(child_ctx); /* * Make the child state follow the state of the parent event, * not its attr.disabled bit. We hold the parent's mutex, * so we won't race with perf_event_{en, dis}able_family. */ if (parent_event->state >= PERF_EVENT_STATE_INACTIVE) child_event->state = PERF_EVENT_STATE_INACTIVE; else child_event->state = PERF_EVENT_STATE_OFF; if (parent_event->attr.freq) { u64 sample_period = parent_event->hw.sample_period; struct hw_perf_event *hwc = &child_event->hw; hwc->sample_period = sample_period; hwc->last_period = sample_period; local64_set(&hwc->period_left, sample_period); } child_event->ctx = child_ctx; child_event->overflow_handler = parent_event->overflow_handler; child_event->overflow_handler_context = parent_event->overflow_handler_context; /* * Precalculate sample_data sizes */ perf_event__header_size(child_event); perf_event__id_header_size(child_event); /* * Link it up in the child's context: */ raw_spin_lock_irqsave(&child_ctx->lock, flags); add_event_to_ctx(child_event, child_ctx); raw_spin_unlock_irqrestore(&child_ctx->lock, flags); /* * Link this into the parent event's child list */ WARN_ON_ONCE(parent_event->ctx->parent_ctx); mutex_lock(&parent_event->child_mutex); list_add_tail(&child_event->child_list, &parent_event->child_list); mutex_unlock(&parent_event->child_mutex); return child_event; } static int inherit_group(struct perf_event *parent_event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, struct perf_event_context *child_ctx) { struct perf_event *leader; struct perf_event *sub; struct perf_event *child_ctr; leader = inherit_event(parent_event, parent, parent_ctx, child, NULL, child_ctx); if (IS_ERR(leader)) return PTR_ERR(leader); list_for_each_entry(sub, &parent_event->sibling_list, group_entry) { child_ctr = inherit_event(sub, parent, parent_ctx, child, leader, child_ctx); if (IS_ERR(child_ctr)) return PTR_ERR(child_ctr); } return 0; } static int inherit_task_group(struct perf_event *event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, int ctxn, int *inherited_all) { int ret; struct perf_event_context *child_ctx; if (!event->attr.inherit) { *inherited_all = 0; return 0; } child_ctx = child->perf_event_ctxp[ctxn]; if (!child_ctx) { /* * This is executed from the parent task context, so * inherit events that have been marked for cloning. * First allocate and initialize a context for the * child. */ child_ctx = alloc_perf_context(parent_ctx->pmu, child); if (!child_ctx) return -ENOMEM; child->perf_event_ctxp[ctxn] = child_ctx; } ret = inherit_group(event, parent, parent_ctx, child, child_ctx); if (ret) *inherited_all = 0; return ret; } /* * Initialize the perf_event context in task_struct */ static int perf_event_init_context(struct task_struct *child, int ctxn) { struct perf_event_context *child_ctx, *parent_ctx; struct perf_event_context *cloned_ctx; struct perf_event *event; struct task_struct *parent = current; int inherited_all = 1; unsigned long flags; int ret = 0; if (likely(!parent->perf_event_ctxp[ctxn])) return 0; /* * If the parent's context is a clone, pin it so it won't get * swapped under us. */ parent_ctx = perf_pin_task_context(parent, ctxn); if (!parent_ctx) return 0; /* * No need to check if parent_ctx != NULL here; since we saw * it non-NULL earlier, the only reason for it to become NULL * is if we exit, and since we're currently in the middle of * a fork we can't be exiting at the same time. */ /* * Lock the parent list. No need to lock the child - not PID * hashed yet and not running, so nobody can access it. */ mutex_lock(&parent_ctx->mutex); /* * We dont have to disable NMIs - we are only looking at * the list, not manipulating it: */ list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) { ret = inherit_task_group(event, parent, parent_ctx, child, ctxn, &inherited_all); if (ret) break; } /* * We can't hold ctx->lock when iterating the ->flexible_group list due * to allocations, but we need to prevent rotation because * rotate_ctx() will change the list from interrupt context. */ raw_spin_lock_irqsave(&parent_ctx->lock, flags); parent_ctx->rotate_disable = 1; raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) { ret = inherit_task_group(event, parent, parent_ctx, child, ctxn, &inherited_all); if (ret) break; } raw_spin_lock_irqsave(&parent_ctx->lock, flags); parent_ctx->rotate_disable = 0; child_ctx = child->perf_event_ctxp[ctxn]; if (child_ctx && inherited_all) { /* * Mark the child context as a clone of the parent * context, or of whatever the parent is a clone of. * * Note that if the parent is a clone, the holding of * parent_ctx->lock avoids it from being uncloned. */ cloned_ctx = parent_ctx->parent_ctx; if (cloned_ctx) { child_ctx->parent_ctx = cloned_ctx; child_ctx->parent_gen = parent_ctx->parent_gen; } else { child_ctx->parent_ctx = parent_ctx; child_ctx->parent_gen = parent_ctx->generation; } get_ctx(child_ctx->parent_ctx); } raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); mutex_unlock(&parent_ctx->mutex); perf_unpin_context(parent_ctx); put_ctx(parent_ctx); return ret; } /* * Initialize the perf_event context in task_struct */ int perf_event_init_task(struct task_struct *child) { int ctxn, ret; memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp)); mutex_init(&child->perf_event_mutex); INIT_LIST_HEAD(&child->perf_event_list); for_each_task_context_nr(ctxn) { ret = perf_event_init_context(child, ctxn); if (ret) return ret; } return 0; } static void __init perf_event_init_all_cpus(void) { struct swevent_htable *swhash; int cpu; for_each_possible_cpu(cpu) { swhash = &per_cpu(swevent_htable, cpu); mutex_init(&swhash->hlist_mutex); INIT_LIST_HEAD(&per_cpu(rotation_list, cpu)); } } static void perf_event_init_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); swhash->online = true; if (swhash->hlist_refcount > 0) { struct swevent_hlist *hlist; hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); WARN_ON(!hlist); rcu_assign_pointer(swhash->swevent_hlist, hlist); } mutex_unlock(&swhash->hlist_mutex); } #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC static void perf_pmu_rotate_stop(struct pmu *pmu) { struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); WARN_ON(!irqs_disabled()); list_del_init(&cpuctx->rotation_list); } static void __perf_event_exit_context(void *__info) { struct remove_event re = { .detach_group = false }; struct perf_event_context *ctx = __info; perf_pmu_rotate_stop(ctx->pmu); rcu_read_lock(); list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry) __perf_remove_from_context(&re); rcu_read_unlock(); } static void perf_event_exit_cpu_context(int cpu) { struct perf_event_context *ctx; struct pmu *pmu; int idx; idx = srcu_read_lock(&pmus_srcu); list_for_each_entry_rcu(pmu, &pmus, entry) { ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx; mutex_lock(&ctx->mutex); smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); mutex_unlock(&ctx->mutex); } srcu_read_unlock(&pmus_srcu, idx); } static void perf_event_exit_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); perf_event_exit_cpu_context(cpu); mutex_lock(&swhash->hlist_mutex); swhash->online = false; swevent_hlist_release(swhash); mutex_unlock(&swhash->hlist_mutex); } #else static inline void perf_event_exit_cpu(int cpu) { } #endif static int perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) { int cpu; for_each_online_cpu(cpu) perf_event_exit_cpu(cpu); return NOTIFY_OK; } /* * Run the perf reboot notifier at the very last possible moment so that * the generic watchdog code runs as long as possible. */ static struct notifier_block perf_reboot_notifier = { .notifier_call = perf_reboot, .priority = INT_MIN, }; static int perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu) { unsigned int cpu = (long)hcpu; switch (action & ~CPU_TASKS_FROZEN) { case CPU_UP_PREPARE: case CPU_DOWN_FAILED: perf_event_init_cpu(cpu); break; case CPU_UP_CANCELED: case CPU_DOWN_PREPARE: perf_event_exit_cpu(cpu); break; default: break; } return NOTIFY_OK; } void __init perf_event_init(void) { int ret; idr_init(&pmu_idr); perf_event_init_all_cpus(); init_srcu_struct(&pmus_srcu); perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); perf_pmu_register(&perf_cpu_clock, NULL, -1); perf_pmu_register(&perf_task_clock, NULL, -1); perf_tp_register(); perf_cpu_notifier(perf_cpu_notify); register_reboot_notifier(&perf_reboot_notifier); ret = init_hw_breakpoint(); WARN(ret, "hw_breakpoint initialization failed with: %d", ret); /* do not patch jump label more than once per second */ jump_label_rate_limit(&perf_sched_events, HZ); /* * Build time assertion that we keep the data_head at the intended * location. IOW, validation we got the __reserved[] size right. */ BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) != 1024); } static int __init perf_event_sysfs_init(void) { struct pmu *pmu; int ret; mutex_lock(&pmus_lock); ret = bus_register(&pmu_bus); if (ret) goto unlock; list_for_each_entry(pmu, &pmus, entry) { if (!pmu->name || pmu->type < 0) continue; ret = pmu_dev_alloc(pmu); WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); } pmu_bus_running = 1; ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; } device_initcall(perf_event_sysfs_init); #ifdef CONFIG_CGROUP_PERF static struct cgroup_subsys_state * perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) { struct perf_cgroup *jc; jc = kzalloc(sizeof(*jc), GFP_KERNEL); if (!jc) return ERR_PTR(-ENOMEM); jc->info = alloc_percpu(struct perf_cgroup_info); if (!jc->info) { kfree(jc); return ERR_PTR(-ENOMEM); } return &jc->css; } static void perf_cgroup_css_free(struct cgroup_subsys_state *css) { struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); free_percpu(jc->info); kfree(jc); } static int __perf_cgroup_move(void *info) { struct task_struct *task = info; perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN); return 0; } static void perf_cgroup_attach(struct cgroup_subsys_state *css, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, tset) task_function_call(task, __perf_cgroup_move, task); } static void perf_cgroup_exit(struct cgroup_subsys_state *css, struct cgroup_subsys_state *old_css, struct task_struct *task) { /* * cgroup_exit() is called in the copy_process() failure path. * Ignore this case since the task hasn't ran yet, this avoids * trying to poke a half freed task state from generic code. */ if (!(task->flags & PF_EXITING)) return; task_function_call(task, __perf_cgroup_move, task); } struct cgroup_subsys perf_event_cgrp_subsys = { .css_alloc = perf_cgroup_css_alloc, .css_free = perf_cgroup_css_free, .exit = perf_cgroup_exit, .attach = perf_cgroup_attach, }; #endif /* CONFIG_CGROUP_PERF */
gpl-2.0
xenserver/syslinux
gpxe/src/core/main.c
25
2239
/************************************************************************** gPXE - Network Bootstrap Program Literature dealing with the network protocols: ARP - RFC826 RARP - RFC903 UDP - RFC768 BOOTP - RFC951, RFC2132 (vendor extensions) DHCP - RFC2131, RFC2132 (options) TFTP - RFC1350, RFC2347 (options), RFC2348 (blocksize), RFC2349 (tsize) RPC - RFC1831, RFC1832 (XDR), RFC1833 (rpcbind/portmapper) **************************************************************************/ FILE_LICENCE ( GPL2_OR_LATER ); #include <stdio.h> #include <gpxe/init.h> #include <gpxe/features.h> #include <gpxe/shell.h> #include <gpxe/shell_banner.h> #include <gpxe/image.h> #include <usr/autoboot.h> #include <config/general.h> #define NORMAL "\033[0m" #define BOLD "\033[1m" #define CYAN "\033[36m" /** * Main entry point * * @ret rc Return status code */ __asmcall int main ( void ) { struct feature *feature; struct image *image; /* Some devices take an unreasonably long time to initialise */ printf ( PRODUCT_SHORT_NAME " initialising devices...\n" ); initialise(); startup(); /* * Print welcome banner * * * If you wish to brand this build of gPXE, please do so by * defining the string PRODUCT_NAME in config/general.h. * * While nothing in the GPL prevents you from removing all * references to gPXE or http://etherboot.org, we prefer you * not to do so. * */ printf ( NORMAL "\n\n" PRODUCT_NAME "\n" BOLD "gPXE " VERSION NORMAL " -- Open Source Boot Firmware -- " CYAN "http://etherboot.org" NORMAL "\n" "Features:" ); for_each_table_entry ( feature, FEATURES ) printf ( " %s", feature->name ); printf ( "\n" ); /* Prompt for shell */ if ( shell_banner() ) { /* User wants shell; just give them a shell */ shell(); } else { /* User doesn't want shell; load and execute the first * image, or autoboot() if we have no images. If * booting fails for any reason, offer a second chance * to enter the shell for diagnostics. */ if ( have_images() ) { for_each_image ( image ) { image_exec ( image ); break; } } else { autoboot(); } if ( shell_banner() ) shell(); } shutdown ( SHUTDOWN_EXIT | shutdown_exit_flags ); return 0; }
gpl-2.0
xapp-le/kernel
drivers/net/wireless/actions/rtl8723bs/core/rtw_ieee80211.c
25
56432
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #define _IEEE80211_C #ifdef CONFIG_PLATFORM_INTEL_BYT #include <linux/fs.h> #endif #include <drv_types.h> u8 RTW_WPA_OUI_TYPE[] = { 0x00, 0x50, 0xf2, 1 }; u16 RTW_WPA_VERSION = 1; u8 WPA_AUTH_KEY_MGMT_NONE[] = { 0x00, 0x50, 0xf2, 0 }; u8 WPA_AUTH_KEY_MGMT_UNSPEC_802_1X[] = { 0x00, 0x50, 0xf2, 1 }; u8 WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X[] = { 0x00, 0x50, 0xf2, 2 }; u8 WPA_CIPHER_SUITE_NONE[] = { 0x00, 0x50, 0xf2, 0 }; u8 WPA_CIPHER_SUITE_WEP40[] = { 0x00, 0x50, 0xf2, 1 }; u8 WPA_CIPHER_SUITE_TKIP[] = { 0x00, 0x50, 0xf2, 2 }; u8 WPA_CIPHER_SUITE_WRAP[] = { 0x00, 0x50, 0xf2, 3 }; u8 WPA_CIPHER_SUITE_CCMP[] = { 0x00, 0x50, 0xf2, 4 }; u8 WPA_CIPHER_SUITE_WEP104[] = { 0x00, 0x50, 0xf2, 5 }; u16 RSN_VERSION_BSD = 1; u8 RSN_AUTH_KEY_MGMT_UNSPEC_802_1X[] = { 0x00, 0x0f, 0xac, 1 }; u8 RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X[] = { 0x00, 0x0f, 0xac, 2 }; u8 RSN_CIPHER_SUITE_NONE[] = { 0x00, 0x0f, 0xac, 0 }; u8 RSN_CIPHER_SUITE_WEP40[] = { 0x00, 0x0f, 0xac, 1 }; u8 RSN_CIPHER_SUITE_TKIP[] = { 0x00, 0x0f, 0xac, 2 }; u8 RSN_CIPHER_SUITE_WRAP[] = { 0x00, 0x0f, 0xac, 3 }; u8 RSN_CIPHER_SUITE_CCMP[] = { 0x00, 0x0f, 0xac, 4 }; u8 RSN_CIPHER_SUITE_WEP104[] = { 0x00, 0x0f, 0xac, 5 }; //----------------------------------------------------------- // for adhoc-master to generate ie and provide supported-rate to fw //----------------------------------------------------------- static u8 WIFI_CCKRATES[] = {(IEEE80211_CCK_RATE_1MB | IEEE80211_BASIC_RATE_MASK), (IEEE80211_CCK_RATE_2MB | IEEE80211_BASIC_RATE_MASK), (IEEE80211_CCK_RATE_5MB | IEEE80211_BASIC_RATE_MASK), (IEEE80211_CCK_RATE_11MB | IEEE80211_BASIC_RATE_MASK)}; static u8 WIFI_OFDMRATES[] = {(IEEE80211_OFDM_RATE_6MB), (IEEE80211_OFDM_RATE_9MB), (IEEE80211_OFDM_RATE_12MB), (IEEE80211_OFDM_RATE_18MB), (IEEE80211_OFDM_RATE_24MB), IEEE80211_OFDM_RATE_36MB, IEEE80211_OFDM_RATE_48MB, IEEE80211_OFDM_RATE_54MB}; int rtw_get_bit_value_from_ieee_value(u8 val) { unsigned char dot11_rate_table[]={2,4,11,22,12,18,24,36,48,72,96,108,0}; // last element must be zero!! int i=0; while(dot11_rate_table[i] != 0) { if (dot11_rate_table[i] == val) return BIT(i); i++; } return 0; } uint rtw_is_cckrates_included(u8 *rate) { u32 i = 0; while(rate[i]!=0) { if ( (((rate[i]) & 0x7f) == 2) || (((rate[i]) & 0x7f) == 4) || (((rate[i]) & 0x7f) == 11) || (((rate[i]) & 0x7f) == 22) ) return _TRUE; i++; } return _FALSE; } uint rtw_is_cckratesonly_included(u8 *rate) { u32 i = 0; while(rate[i]!=0) { if ( (((rate[i]) & 0x7f) != 2) && (((rate[i]) & 0x7f) != 4) && (((rate[i]) & 0x7f) != 11) && (((rate[i]) & 0x7f) != 22) ) return _FALSE; i++; } return _TRUE; } int rtw_check_network_type(unsigned char *rate, int ratelen, int channel) { if (channel > 14) { if ((rtw_is_cckrates_included(rate)) == _TRUE) return WIRELESS_INVALID; else return WIRELESS_11A; } else // could be pure B, pure G, or B/G { if ((rtw_is_cckratesonly_included(rate)) == _TRUE) return WIRELESS_11B; else if((rtw_is_cckrates_included(rate)) == _TRUE) return WIRELESS_11BG; else return WIRELESS_11G; } } u8 *rtw_set_fixed_ie(unsigned char *pbuf, unsigned int len, unsigned char *source, unsigned int *frlen) { _rtw_memcpy((void *)pbuf, (void *)source, len); *frlen = *frlen + len; return (pbuf + len); } // rtw_set_ie will update frame length u8 *rtw_set_ie ( u8 *pbuf, sint index, uint len, u8 *source, uint *frlen //frame length ) { *pbuf = (u8)index; *(pbuf + 1) = (u8)len; if (len > 0) _rtw_memcpy((void *)(pbuf + 2), (void *)source, len); *frlen = *frlen + (len + 2); return (pbuf + len + 2); } inline u8 *rtw_set_ie_ch_switch(u8 *buf, u32 *buf_len, u8 ch_switch_mode, u8 new_ch, u8 ch_switch_cnt) { u8 ie_data[3]; ie_data[0] = ch_switch_mode; ie_data[1] = new_ch; ie_data[2] = ch_switch_cnt; return rtw_set_ie(buf, WLAN_EID_CHANNEL_SWITCH, 3, ie_data, buf_len); } inline u8 secondary_ch_offset_to_hal_ch_offset(u8 ch_offset) { if (ch_offset == SCN) return HAL_PRIME_CHNL_OFFSET_DONT_CARE; else if(ch_offset == SCA) return HAL_PRIME_CHNL_OFFSET_UPPER; else if(ch_offset == SCB) return HAL_PRIME_CHNL_OFFSET_LOWER; return HAL_PRIME_CHNL_OFFSET_DONT_CARE; } inline u8 hal_ch_offset_to_secondary_ch_offset(u8 ch_offset) { if (ch_offset == HAL_PRIME_CHNL_OFFSET_DONT_CARE) return SCN; else if(ch_offset == HAL_PRIME_CHNL_OFFSET_LOWER) return SCB; else if(ch_offset == HAL_PRIME_CHNL_OFFSET_UPPER) return SCA; return SCN; } inline u8 *rtw_set_ie_secondary_ch_offset(u8 *buf, u32 *buf_len, u8 secondary_ch_offset) { return rtw_set_ie(buf, WLAN_EID_SECONDARY_CHANNEL_OFFSET, 1, &secondary_ch_offset, buf_len); } inline u8 *rtw_set_ie_mesh_ch_switch_parm(u8 *buf, u32 *buf_len, u8 ttl, u8 flags, u16 reason, u16 precedence) { u8 ie_data[6]; ie_data[0] = ttl; ie_data[1] = flags; RTW_PUT_LE16((u8*)&ie_data[2], reason); RTW_PUT_LE16((u8*)&ie_data[4], precedence); return rtw_set_ie(buf, 0x118, 6, ie_data, buf_len); } /*---------------------------------------------------------------------------- index: the information element id index, limit is the limit for search -----------------------------------------------------------------------------*/ u8 *rtw_get_ie(u8 *pbuf, sint index, sint *len, sint limit) { sint tmp,i; u8 *p; _func_enter_; if (limit < 1){ _func_exit_; return NULL; } p = pbuf; i = 0; *len = 0; while(1) { if (*p == index) { *len = *(p + 1); return (p); } else { tmp = *(p + 1); p += (tmp + 2); i += (tmp + 2); } if (i >= limit) break; } _func_exit_; return NULL; } /** * rtw_get_ie_ex - Search specific IE from a series of IEs * @in_ie: Address of IEs to search * @in_len: Length limit from in_ie * @eid: Element ID to match * @oui: OUI to match * @oui_len: OUI length * @ie: If not NULL and the specific IE is found, the IE will be copied to the buf starting from the specific IE * @ielen: If not NULL and the specific IE is found, will set to the length of the entire IE * * Returns: The address of the specific IE found, or NULL */ u8 *rtw_get_ie_ex(u8 *in_ie, uint in_len, u8 eid, u8 *oui, u8 oui_len, u8 *ie, uint *ielen) { uint cnt; u8 *target_ie = NULL; if(ielen) *ielen = 0; if(!in_ie || in_len<=0) return target_ie; cnt = 0; while(cnt<in_len) { if(eid == in_ie[cnt] && ( !oui || _rtw_memcmp(&in_ie[cnt+2], oui, oui_len) == _TRUE)) { target_ie = &in_ie[cnt]; if(ie) _rtw_memcpy(ie, &in_ie[cnt], in_ie[cnt+1]+2); if(ielen) *ielen = in_ie[cnt+1]+2; break; } else { cnt+=in_ie[cnt+1]+2; //goto next } } return target_ie; } /** * rtw_ies_remove_ie - Find matching IEs and remove * @ies: Address of IEs to search * @ies_len: Pointer of length of ies, will update to new length * @offset: The offset to start scarch * @eid: Element ID to match * @oui: OUI to match * @oui_len: OUI length * * Returns: _SUCCESS: ies is updated, _FAIL: not updated */ int rtw_ies_remove_ie(u8 *ies, uint *ies_len, uint offset, u8 eid, u8 *oui, u8 oui_len) { int ret = _FAIL; u8 *target_ie; u32 target_ielen; u8 *start; uint search_len; if(!ies || !ies_len || *ies_len <= offset) goto exit; start = ies + offset; search_len = *ies_len - offset; while (1) { target_ie = rtw_get_ie_ex(start, search_len, eid, oui, oui_len, NULL, &target_ielen); if (target_ie && target_ielen) { u8 buf[MAX_IE_SZ] = {0}; u8 *remain_ies = target_ie + target_ielen; uint remain_len = search_len - (remain_ies - start); _rtw_memcpy(buf, remain_ies, remain_len); _rtw_memcpy(target_ie, buf, remain_len); *ies_len = *ies_len - target_ielen; ret = _SUCCESS; start = target_ie; search_len = remain_len; } else { break; } } exit: return ret; } void rtw_set_supported_rate(u8* SupportedRates, uint mode) { _func_enter_; _rtw_memset(SupportedRates, 0, NDIS_802_11_LENGTH_RATES_EX); switch (mode) { case WIRELESS_11B: _rtw_memcpy(SupportedRates, WIFI_CCKRATES, IEEE80211_CCK_RATE_LEN); break; case WIRELESS_11G: case WIRELESS_11A: case WIRELESS_11_5N: case WIRELESS_11A_5N://Todo: no basic rate for ofdm ? case WIRELESS_11_5AC: _rtw_memcpy(SupportedRates, WIFI_OFDMRATES, IEEE80211_NUM_OFDM_RATESLEN); break; case WIRELESS_11BG: case WIRELESS_11G_24N: case WIRELESS_11_24N: case WIRELESS_11BG_24N: _rtw_memcpy(SupportedRates, WIFI_CCKRATES, IEEE80211_CCK_RATE_LEN); _rtw_memcpy(SupportedRates + IEEE80211_CCK_RATE_LEN, WIFI_OFDMRATES, IEEE80211_NUM_OFDM_RATESLEN); break; } _func_exit_; } uint rtw_get_rateset_len(u8 *rateset) { uint i = 0; _func_enter_; while(1) { if ((rateset[i]) == 0) break; if (i > 12) break; i++; } _func_exit_; return i; } int rtw_generate_ie(struct registry_priv *pregistrypriv) { u8 wireless_mode; int sz = 0, rateLen; WLAN_BSSID_EX* pdev_network = &pregistrypriv->dev_network; u8* ie = pdev_network->IEs; _func_enter_; //timestamp will be inserted by hardware sz += 8; ie += sz; //beacon interval : 2bytes *(u16*)ie = cpu_to_le16((u16)pdev_network->Configuration.BeaconPeriod);//BCN_INTERVAL; sz += 2; ie += 2; //capability info *(u16*)ie = 0; *(u16*)ie |= cpu_to_le16(cap_IBSS); if(pregistrypriv->preamble == PREAMBLE_SHORT) *(u16*)ie |= cpu_to_le16(cap_ShortPremble); if (pdev_network->Privacy) *(u16*)ie |= cpu_to_le16(cap_Privacy); sz += 2; ie += 2; //SSID ie = rtw_set_ie(ie, _SSID_IE_, pdev_network->Ssid.SsidLength, pdev_network->Ssid.Ssid, &sz); //supported rates if(pregistrypriv->wireless_mode == WIRELESS_11ABGN) { if(pdev_network->Configuration.DSConfig > 14) wireless_mode = WIRELESS_11A_5N; else wireless_mode = WIRELESS_11BG_24N; } else { wireless_mode = pregistrypriv->wireless_mode; } rtw_set_supported_rate(pdev_network->SupportedRates, wireless_mode) ; rateLen = rtw_get_rateset_len(pdev_network->SupportedRates); if (rateLen > 8) { ie = rtw_set_ie(ie, _SUPPORTEDRATES_IE_, 8, pdev_network->SupportedRates, &sz); //ie = rtw_set_ie(ie, _EXT_SUPPORTEDRATES_IE_, (rateLen - 8), (pdev_network->SupportedRates + 8), &sz); } else { ie = rtw_set_ie(ie, _SUPPORTEDRATES_IE_, rateLen, pdev_network->SupportedRates, &sz); } //DS parameter set ie = rtw_set_ie(ie, _DSSET_IE_, 1, (u8 *)&(pdev_network->Configuration.DSConfig), &sz); //IBSS Parameter Set ie = rtw_set_ie(ie, _IBSS_PARA_IE_, 2, (u8 *)&(pdev_network->Configuration.ATIMWindow), &sz); if (rateLen > 8) { ie = rtw_set_ie(ie, _EXT_SUPPORTEDRATES_IE_, (rateLen - 8), (pdev_network->SupportedRates + 8), &sz); } #ifdef CONFIG_80211N_HT //HT Cap. if(((pregistrypriv->wireless_mode&WIRELESS_11_5N)||(pregistrypriv->wireless_mode&WIRELESS_11_24N)) && (pregistrypriv->ht_enable==_TRUE)) { //todo: } #endif //CONFIG_80211N_HT //pdev_network->IELength = sz; //update IELength _func_exit_; //return _SUCCESS; return sz; } unsigned char *rtw_get_wpa_ie(unsigned char *pie, int *wpa_ie_len, int limit) { int len; u16 val16; unsigned char wpa_oui_type[] = {0x00, 0x50, 0xf2, 0x01}; u8 *pbuf = pie; int limit_new = limit; while(1) { pbuf = rtw_get_ie(pbuf, _WPA_IE_ID_, &len, limit_new); if (pbuf) { //check if oui matches... if (_rtw_memcmp((pbuf + 2), wpa_oui_type, sizeof (wpa_oui_type)) == _FALSE) { goto check_next_ie; } //check version... _rtw_memcpy((u8 *)&val16, (pbuf + 6), sizeof(val16)); val16 = le16_to_cpu(val16); if (val16 != 0x0001) goto check_next_ie; *wpa_ie_len = *(pbuf + 1); return pbuf; } else { *wpa_ie_len = 0; return NULL; } check_next_ie: limit_new = limit - (pbuf - pie) - 2 - len; if (limit_new <= 0) break; pbuf += (2 + len); } *wpa_ie_len = 0; return NULL; } unsigned char *rtw_get_wpa2_ie(unsigned char *pie, int *rsn_ie_len, int limit) { return rtw_get_ie(pie, _WPA2_IE_ID_,rsn_ie_len, limit); } int rtw_get_wpa_cipher_suite(u8 *s) { if (_rtw_memcmp(s, WPA_CIPHER_SUITE_NONE, WPA_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_NONE; if (_rtw_memcmp(s, WPA_CIPHER_SUITE_WEP40, WPA_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_WEP40; if (_rtw_memcmp(s, WPA_CIPHER_SUITE_TKIP, WPA_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_TKIP; if (_rtw_memcmp(s, WPA_CIPHER_SUITE_CCMP, WPA_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_CCMP; if (_rtw_memcmp(s, WPA_CIPHER_SUITE_WEP104, WPA_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_WEP104; return 0; } int rtw_get_wpa2_cipher_suite(u8 *s) { if (_rtw_memcmp(s, RSN_CIPHER_SUITE_NONE, RSN_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_NONE; if (_rtw_memcmp(s, RSN_CIPHER_SUITE_WEP40, RSN_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_WEP40; if (_rtw_memcmp(s, RSN_CIPHER_SUITE_TKIP, RSN_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_TKIP; if (_rtw_memcmp(s, RSN_CIPHER_SUITE_CCMP, RSN_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_CCMP; if (_rtw_memcmp(s, RSN_CIPHER_SUITE_WEP104, RSN_SELECTOR_LEN) == _TRUE) return WPA_CIPHER_WEP104; return 0; } int rtw_parse_wpa_ie(u8* wpa_ie, int wpa_ie_len, int *group_cipher, int *pairwise_cipher, int *is_8021x) { int i, ret=_SUCCESS; int left, count; u8 *pos; u8 SUITE_1X[4] = {0x00, 0x50, 0xf2, 1}; if (wpa_ie_len <= 0) { /* No WPA IE - fail silently */ return _FAIL; } if ((*wpa_ie != _WPA_IE_ID_) || (*(wpa_ie+1) != (u8)(wpa_ie_len - 2)) || (_rtw_memcmp(wpa_ie+2, RTW_WPA_OUI_TYPE, WPA_SELECTOR_LEN) != _TRUE) ) { return _FAIL; } pos = wpa_ie; pos += 8; left = wpa_ie_len - 8; //group_cipher if (left >= WPA_SELECTOR_LEN) { *group_cipher = rtw_get_wpa_cipher_suite(pos); pos += WPA_SELECTOR_LEN; left -= WPA_SELECTOR_LEN; } else if (left > 0) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_err_,("%s: ie length mismatch, %u too much", __FUNCTION__, left)); return _FAIL; } //pairwise_cipher if (left >= 2) { //count = le16_to_cpu(*(u16*)pos); count = RTW_GET_LE16(pos); pos += 2; left -= 2; if (count == 0 || left < count * WPA_SELECTOR_LEN) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_err_,("%s: ie count botch (pairwise), " "count %u left %u", __FUNCTION__, count, left)); return _FAIL; } for (i = 0; i < count; i++) { *pairwise_cipher |= rtw_get_wpa_cipher_suite(pos); pos += WPA_SELECTOR_LEN; left -= WPA_SELECTOR_LEN; } } else if (left == 1) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_err_,("%s: ie too short (for key mgmt)", __FUNCTION__)); return _FAIL; } if (is_8021x) { if (left >= 6) { pos += 2; if (_rtw_memcmp(pos, SUITE_1X, 4) == 1) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("%s : there has 802.1x auth\n", __FUNCTION__)); *is_8021x = 1; } } } return ret; } int rtw_parse_wpa2_ie(u8* rsn_ie, int rsn_ie_len, int *group_cipher, int *pairwise_cipher, int *is_8021x) { int i, ret=_SUCCESS; int left, count; u8 *pos; u8 SUITE_1X[4] = {0x00,0x0f, 0xac, 0x01}; if (rsn_ie_len <= 0) { /* No RSN IE - fail silently */ return _FAIL; } if ((*rsn_ie!= _WPA2_IE_ID_) || (*(rsn_ie+1) != (u8)(rsn_ie_len - 2))) { return _FAIL; } pos = rsn_ie; pos += 4; left = rsn_ie_len - 4; //group_cipher if (left >= RSN_SELECTOR_LEN) { *group_cipher = rtw_get_wpa2_cipher_suite(pos); pos += RSN_SELECTOR_LEN; left -= RSN_SELECTOR_LEN; } else if (left > 0) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_err_,("%s: ie length mismatch, %u too much", __FUNCTION__, left)); return _FAIL; } //pairwise_cipher if (left >= 2) { //count = le16_to_cpu(*(u16*)pos); count = RTW_GET_LE16(pos); pos += 2; left -= 2; if (count == 0 || left < count * RSN_SELECTOR_LEN) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_err_,("%s: ie count botch (pairwise), " "count %u left %u", __FUNCTION__, count, left)); return _FAIL; } for (i = 0; i < count; i++) { *pairwise_cipher |= rtw_get_wpa2_cipher_suite(pos); pos += RSN_SELECTOR_LEN; left -= RSN_SELECTOR_LEN; } } else if (left == 1) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_err_,("%s: ie too short (for key mgmt)", __FUNCTION__)); return _FAIL; } if (is_8021x) { if (left >= 6) { pos += 2; if (_rtw_memcmp(pos, SUITE_1X, 4) == 1) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("%s (): there has 802.1x auth\n", __FUNCTION__)); *is_8021x = 1; } } } return ret; } //#ifdef CONFIG_WAPI_SUPPORT int rtw_get_wapi_ie(u8 *in_ie,uint in_len,u8 *wapi_ie,u16 *wapi_len) { int len = 0; u8 authmode, i; uint cnt; u8 wapi_oui1[4]={0x0,0x14,0x72,0x01}; u8 wapi_oui2[4]={0x0,0x14,0x72,0x02}; _func_enter_; if(wapi_len) *wapi_len = 0; if(!in_ie || in_len<=0) return len; cnt = (_TIMESTAMP_ + _BEACON_ITERVAL_ + _CAPABILITY_); while(cnt<in_len) { authmode=in_ie[cnt]; //if(authmode==_WAPI_IE_) if(authmode==_WAPI_IE_ && (_rtw_memcmp(&in_ie[cnt+6], wapi_oui1,4)==_TRUE || _rtw_memcmp(&in_ie[cnt+6], wapi_oui2,4)==_TRUE)) { if (wapi_ie) { _rtw_memcpy(wapi_ie, &in_ie[cnt],in_ie[cnt+1]+2); for(i=0;i<(in_ie[cnt+1]+2);i=i+8){ RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("\n %2x,%2x,%2x,%2x,%2x,%2x,%2x,%2x\n", wapi_ie[i],wapi_ie[i+1],wapi_ie[i+2],wapi_ie[i+3],wapi_ie[i+4], wapi_ie[i+5],wapi_ie[i+6],wapi_ie[i+7])); } } if(wapi_len) *wapi_len=in_ie[cnt+1]+2; cnt+=in_ie[cnt+1]+2; //get next } else { cnt+=in_ie[cnt+1]+2; //get next } } if(wapi_len) len = *wapi_len; _func_exit_; return len; } //#endif int rtw_get_sec_ie(u8 *in_ie,uint in_len,u8 *rsn_ie,u16 *rsn_len,u8 *wpa_ie,u16 *wpa_len) { u8 authmode, sec_idx, i; u8 wpa_oui[4]={0x0,0x50,0xf2,0x01}; uint cnt; _func_enter_; //Search required WPA or WPA2 IE and copy to sec_ie[ ] cnt = (_TIMESTAMP_ + _BEACON_ITERVAL_ + _CAPABILITY_); sec_idx=0; while(cnt<in_len) { authmode=in_ie[cnt]; if((authmode==_WPA_IE_ID_)&&(_rtw_memcmp(&in_ie[cnt+2], &wpa_oui[0],4)==_TRUE)) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("\n rtw_get_wpa_ie: sec_idx=%d in_ie[cnt+1]+2=%d\n",sec_idx,in_ie[cnt+1]+2)); if (wpa_ie) { _rtw_memcpy(wpa_ie, &in_ie[cnt],in_ie[cnt+1]+2); for(i=0;i<(in_ie[cnt+1]+2);i=i+8){ RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("\n %2x,%2x,%2x,%2x,%2x,%2x,%2x,%2x\n", wpa_ie[i],wpa_ie[i+1],wpa_ie[i+2],wpa_ie[i+3],wpa_ie[i+4], wpa_ie[i+5],wpa_ie[i+6],wpa_ie[i+7])); } } *wpa_len=in_ie[cnt+1]+2; cnt+=in_ie[cnt+1]+2; //get next } else { if(authmode==_WPA2_IE_ID_) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("\n get_rsn_ie: sec_idx=%d in_ie[cnt+1]+2=%d\n",sec_idx,in_ie[cnt+1]+2)); if (rsn_ie) { _rtw_memcpy(rsn_ie, &in_ie[cnt],in_ie[cnt+1]+2); for(i=0;i<(in_ie[cnt+1]+2);i=i+8){ RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("\n %2x,%2x,%2x,%2x,%2x,%2x,%2x,%2x\n", rsn_ie[i],rsn_ie[i+1],rsn_ie[i+2],rsn_ie[i+3],rsn_ie[i+4], rsn_ie[i+5],rsn_ie[i+6],rsn_ie[i+7])); } } *rsn_len=in_ie[cnt+1]+2; cnt+=in_ie[cnt+1]+2; //get next } else { cnt+=in_ie[cnt+1]+2; //get next } } } _func_exit_; return (*rsn_len+*wpa_len); } u8 rtw_is_wps_ie(u8 *ie_ptr, uint *wps_ielen) { u8 match = _FALSE; u8 eid, wps_oui[4]={0x0,0x50,0xf2,0x04}; if(ie_ptr == NULL) return match; eid = ie_ptr[0]; if((eid==_WPA_IE_ID_)&&(_rtw_memcmp(&ie_ptr[2], wps_oui, 4)==_TRUE)) { //DBG_8192C("==> found WPS_IE.....\n"); *wps_ielen = ie_ptr[1]+2; match=_TRUE; } return match; } u8 *rtw_get_wps_ie_from_scan_queue(u8 *in_ie, uint in_len, u8 *wps_ie, uint *wps_ielen, u8 frame_type) { u8* wps = NULL; DBG_871X( "[%s] frame_type = %d\n", __FUNCTION__, frame_type ); switch( frame_type ) { case 1: case 3: { // Beacon or Probe Response wps = rtw_get_wps_ie(in_ie + _PROBERSP_IE_OFFSET_, in_len - _PROBERSP_IE_OFFSET_, wps_ie, wps_ielen); break; } case 2: { // Probe Request wps = rtw_get_wps_ie(in_ie + _PROBEREQ_IE_OFFSET_ , in_len - _PROBEREQ_IE_OFFSET_ , wps_ie, wps_ielen); break; } } return wps; } /** * rtw_get_wps_ie - Search WPS IE from a series of IEs * @in_ie: Address of IEs to search * @in_len: Length limit from in_ie * @wps_ie: If not NULL and WPS IE is found, WPS IE will be copied to the buf starting from wps_ie * @wps_ielen: If not NULL and WPS IE is found, will set to the length of the entire WPS IE * * Returns: The address of the WPS IE found, or NULL */ u8 *rtw_get_wps_ie(u8 *in_ie, uint in_len, u8 *wps_ie, uint *wps_ielen) { uint cnt; u8 *wpsie_ptr = NULL; u8 eid, wps_oui[4] = {0x00, 0x50, 0xf2, 0x04}; if (wps_ielen) *wps_ielen = 0; if (!in_ie) { rtw_warn_on(1); return wpsie_ptr; } if (in_len <= 0) return wpsie_ptr; cnt = 0; while (cnt + 1 + 4 < in_len) { eid = in_ie[cnt]; if (cnt + 1 + 4 >= MAX_IE_SZ) { rtw_warn_on(1); return NULL; } if (eid == WLAN_EID_VENDOR_SPECIFIC && _rtw_memcmp(&in_ie[cnt + 2], wps_oui, 4) == _TRUE) { wpsie_ptr = in_ie + cnt; if (wps_ie) _rtw_memcpy(wps_ie, &in_ie[cnt], in_ie[cnt + 1] + 2); if (wps_ielen) *wps_ielen = in_ie[cnt + 1] + 2; break; } else { cnt += in_ie[cnt + 1] + 2; } } return wpsie_ptr; } /** * rtw_get_wps_attr - Search a specific WPS attribute from a given WPS IE * @wps_ie: Address of WPS IE to search * @wps_ielen: Length limit from wps_ie * @target_attr_id: The attribute ID of WPS attribute to search * @buf_attr: If not NULL and the WPS attribute is found, WPS attribute will be copied to the buf starting from buf_attr * @len_attr: If not NULL and the WPS attribute is found, will set to the length of the entire WPS attribute * * Returns: the address of the specific WPS attribute found, or NULL */ u8 *rtw_get_wps_attr(u8 *wps_ie, uint wps_ielen, u16 target_attr_id ,u8 *buf_attr, u32 *len_attr) { u8 *attr_ptr = NULL; u8 * target_attr_ptr = NULL; u8 wps_oui[4]={0x00,0x50,0xF2,0x04}; if(len_attr) *len_attr = 0; if ( ( wps_ie[0] != _VENDOR_SPECIFIC_IE_ ) || ( _rtw_memcmp( wps_ie + 2, wps_oui , 4 ) != _TRUE ) ) { return attr_ptr; } // 6 = 1(Element ID) + 1(Length) + 4(WPS OUI) attr_ptr = wps_ie + 6; //goto first attr while(attr_ptr - wps_ie < wps_ielen) { // 4 = 2(Attribute ID) + 2(Length) u16 attr_id = RTW_GET_BE16(attr_ptr); u16 attr_data_len = RTW_GET_BE16(attr_ptr + 2); u16 attr_len = attr_data_len + 4; //DBG_871X("%s attr_ptr:%p, id:%u, length:%u\n", __FUNCTION__, attr_ptr, attr_id, attr_data_len); if( attr_id == target_attr_id ) { target_attr_ptr = attr_ptr; if(buf_attr) _rtw_memcpy(buf_attr, attr_ptr, attr_len); if(len_attr) *len_attr = attr_len; break; } else { attr_ptr += attr_len; //goto next } } return target_attr_ptr; } /** * rtw_get_wps_attr_content - Search a specific WPS attribute content from a given WPS IE * @wps_ie: Address of WPS IE to search * @wps_ielen: Length limit from wps_ie * @target_attr_id: The attribute ID of WPS attribute to search * @buf_content: If not NULL and the WPS attribute is found, WPS attribute content will be copied to the buf starting from buf_content * @len_content: If not NULL and the WPS attribute is found, will set to the length of the WPS attribute content * * Returns: the address of the specific WPS attribute content found, or NULL */ u8 *rtw_get_wps_attr_content(u8 *wps_ie, uint wps_ielen, u16 target_attr_id ,u8 *buf_content, uint *len_content) { u8 *attr_ptr; u32 attr_len; if(len_content) *len_content = 0; attr_ptr = rtw_get_wps_attr(wps_ie, wps_ielen, target_attr_id, NULL, &attr_len); if(attr_ptr && attr_len) { if(buf_content) _rtw_memcpy(buf_content, attr_ptr+4, attr_len-4); if(len_content) *len_content = attr_len-4; return attr_ptr+4; } return NULL; } static int rtw_ieee802_11_parse_vendor_specific(u8 *pos, uint elen, struct rtw_ieee802_11_elems *elems, int show_errors) { unsigned int oui; /* first 3 bytes in vendor specific information element are the IEEE * OUI of the vendor. The following byte is used a vendor specific * sub-type. */ if (elen < 4) { if (show_errors) { DBG_871X("short vendor specific " "information element ignored (len=%lu)\n", (unsigned long) elen); } return -1; } oui = RTW_GET_BE24(pos); switch (oui) { case OUI_MICROSOFT: /* Microsoft/Wi-Fi information elements are further typed and * subtyped */ switch (pos[3]) { case 1: /* Microsoft OUI (00:50:F2) with OUI Type 1: * real WPA information element */ elems->wpa_ie = pos; elems->wpa_ie_len = elen; break; case WME_OUI_TYPE: /* this is a Wi-Fi WME info. element */ if (elen < 5) { DBG_871X("short WME " "information element ignored " "(len=%lu)\n", (unsigned long) elen); return -1; } switch (pos[4]) { case WME_OUI_SUBTYPE_INFORMATION_ELEMENT: case WME_OUI_SUBTYPE_PARAMETER_ELEMENT: elems->wme = pos; elems->wme_len = elen; break; case WME_OUI_SUBTYPE_TSPEC_ELEMENT: elems->wme_tspec = pos; elems->wme_tspec_len = elen; break; default: DBG_871X_LEVEL(_drv_warning_, "unknown WME " "information element ignored " "(subtype=%d len=%lu)\n", pos[4], (unsigned long) elen); return -1; } break; case 4: /* Wi-Fi Protected Setup (WPS) IE */ elems->wps_ie = pos; elems->wps_ie_len = elen; break; default: DBG_871X_LEVEL(_drv_warning_, "Unknown Microsoft " "information element ignored " "(type=%d len=%lu)\n", pos[3], (unsigned long) elen); return -1; } break; case OUI_BROADCOM: switch (pos[3]) { case VENDOR_HT_CAPAB_OUI_TYPE: elems->vendor_ht_cap = pos; elems->vendor_ht_cap_len = elen; break; default: DBG_871X_LEVEL(_drv_warning_, "Unknown Broadcom " "information element ignored " "(type=%d len=%lu)\n", pos[3], (unsigned long) elen); return -1; } break; default: DBG_871X_LEVEL(_drv_warning_, "unknown vendor specific information " "element ignored (vendor OUI %02x:%02x:%02x " "len=%lu)\n", pos[0], pos[1], pos[2], (unsigned long) elen); return -1; } return 0; } /** * ieee802_11_parse_elems - Parse information elements in management frames * @start: Pointer to the start of IEs * @len: Length of IE buffer in octets * @elems: Data structure for parsed elements * @show_errors: Whether to show parsing errors in debug log * Returns: Parsing result */ ParseRes rtw_ieee802_11_parse_elems(u8 *start, uint len, struct rtw_ieee802_11_elems *elems, int show_errors) { uint left = len; u8 *pos = start; int unknown = 0; _rtw_memset(elems, 0, sizeof(*elems)); while (left >= 2) { u8 id, elen; id = *pos++; elen = *pos++; left -= 2; if (elen > left) { if (show_errors) { DBG_871X("IEEE 802.11 element " "parse failed (id=%d elen=%d " "left=%lu)\n", id, elen, (unsigned long) left); } return ParseFailed; } switch (id) { case WLAN_EID_SSID: elems->ssid = pos; elems->ssid_len = elen; break; case WLAN_EID_SUPP_RATES: elems->supp_rates = pos; elems->supp_rates_len = elen; break; case WLAN_EID_FH_PARAMS: elems->fh_params = pos; elems->fh_params_len = elen; break; case WLAN_EID_DS_PARAMS: elems->ds_params = pos; elems->ds_params_len = elen; break; case WLAN_EID_CF_PARAMS: elems->cf_params = pos; elems->cf_params_len = elen; break; case WLAN_EID_TIM: elems->tim = pos; elems->tim_len = elen; break; case WLAN_EID_IBSS_PARAMS: elems->ibss_params = pos; elems->ibss_params_len = elen; break; case WLAN_EID_CHALLENGE: elems->challenge = pos; elems->challenge_len = elen; break; case WLAN_EID_ERP_INFO: elems->erp_info = pos; elems->erp_info_len = elen; break; case WLAN_EID_EXT_SUPP_RATES: elems->ext_supp_rates = pos; elems->ext_supp_rates_len = elen; break; case WLAN_EID_VENDOR_SPECIFIC: if (rtw_ieee802_11_parse_vendor_specific(pos, elen, elems, show_errors)) unknown++; break; case WLAN_EID_RSN: elems->rsn_ie = pos; elems->rsn_ie_len = elen; break; case WLAN_EID_PWR_CAPABILITY: elems->power_cap = pos; elems->power_cap_len = elen; break; case WLAN_EID_SUPPORTED_CHANNELS: elems->supp_channels = pos; elems->supp_channels_len = elen; break; case WLAN_EID_MOBILITY_DOMAIN: elems->mdie = pos; elems->mdie_len = elen; break; case WLAN_EID_FAST_BSS_TRANSITION: elems->ftie = pos; elems->ftie_len = elen; break; case WLAN_EID_TIMEOUT_INTERVAL: elems->timeout_int = pos; elems->timeout_int_len = elen; break; case WLAN_EID_HT_CAP: elems->ht_capabilities = pos; elems->ht_capabilities_len = elen; break; case WLAN_EID_HT_OPERATION: elems->ht_operation = pos; elems->ht_operation_len = elen; break; case WLAN_EID_VHT_CAPABILITY: elems->vht_capabilities = pos; elems->vht_capabilities_len = elen; break; case WLAN_EID_VHT_OPERATION: elems->vht_operation = pos; elems->vht_operation_len = elen; break; case WLAN_EID_VHT_OP_MODE_NOTIFY: elems->vht_op_mode_notify = pos; elems->vht_op_mode_notify_len = elen; break; default: unknown++; if (!show_errors) break; DBG_871X_LEVEL(_drv_warning_, "IEEE 802.11 element parse " "ignored unknown element (id=%d elen=%d)\n", id, elen); break; } left -= elen; pos += elen; } if (left) return ParseFailed; return unknown ? ParseUnknown : ParseOK; } static u8 key_char2num(u8 ch); static u8 key_char2num(u8 ch) { if((ch>='0')&&(ch<='9')) return ch - '0'; else if ((ch>='a')&&(ch<='f')) return ch - 'a' + 10; else if ((ch>='A')&&(ch<='F')) return ch - 'A' + 10; else return 0xff; } u8 str_2char2num(u8 hch, u8 lch); u8 str_2char2num(u8 hch, u8 lch) { return ((key_char2num(hch) * 10 ) + key_char2num(lch)); } u8 key_2char2num(u8 hch, u8 lch); u8 key_2char2num(u8 hch, u8 lch) { return ((key_char2num(hch) << 4) | key_char2num(lch)); } void macstr2num(u8 *dst, u8 *src); void macstr2num(u8 *dst, u8 *src) { int jj, kk; for (jj = 0, kk = 0; jj < ETH_ALEN; jj++, kk += 3) { dst[jj] = key_2char2num(src[kk], src[kk + 1]); } } u8 convert_ip_addr(u8 hch, u8 mch, u8 lch) { return ((key_char2num(hch) * 100) + (key_char2num(mch) * 10 ) + key_char2num(lch)); } #ifdef CONFIG_PLATFORM_INTEL_BYT #define MAC_ADDRESS_LEN 12 int rtw_get_mac_addr_intel(unsigned char *buf) { int ret = 0; int i; struct file *fp = NULL; mm_segment_t oldfs; unsigned char c_mac[MAC_ADDRESS_LEN]; char fname[]="/config/wifi/mac.txt"; int jj,kk; DBG_871X("%s Enter\n", __FUNCTION__); ret = rtw_retrive_from_file(fname, c_mac, MAC_ADDRESS_LEN); if(ret < MAC_ADDRESS_LEN) { return -1; } for( jj = 0, kk = 0; jj < ETH_ALEN; jj++, kk += 2 ) { buf[jj] = key_2char2num(c_mac[kk], c_mac[kk+ 1]); } DBG_871X("%s: read from file mac address: "MAC_FMT"\n", __FUNCTION__, MAC_ARG(buf)); return 0; } #endif //CONFIG_PLATFORM_INTEL_BYT /* * Description: * rtw_check_invalid_mac_address: * This is only used for checking mac address valid or not. * * Input: * adapter: mac_address pointer. * * Output: * _TRUE: The mac address is invalid. * _FALSE: The mac address is valid. * * Auther: Isaac.Li */ u8 rtw_check_invalid_mac_address(u8 *mac_addr) { u8 null_mac_addr[ETH_ALEN] = {0, 0, 0, 0, 0, 0}; u8 multi_mac_addr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; u8 res = _FALSE; if (_rtw_memcmp(mac_addr, null_mac_addr, ETH_ALEN)) { res = _TRUE; goto func_exit; } if (_rtw_memcmp(mac_addr, multi_mac_addr, ETH_ALEN)) { res = _TRUE; goto func_exit; } if (mac_addr[0] & BIT0) { res = _TRUE; goto func_exit; } if (mac_addr[0] & BIT1) { res = _TRUE; goto func_exit; } func_exit: return res; } extern char* rtw_initmac; /** * rtw_macaddr_cfg - Decide the mac address used * @out: buf to store mac address decided * @hw_mac_addr: mac address from efuse/epprom */ void rtw_macaddr_cfg(u8 *out, const u8 *hw_mac_addr) { u8 mac[ETH_ALEN]; if (out == NULL) { rtw_warn_on(1); return; } /* Users specify the mac address */ if (rtw_initmac) { int jj,kk; for (jj = 0, kk = 0; jj < ETH_ALEN; jj++, kk += 3) mac[jj] = key_2char2num(rtw_initmac[kk], rtw_initmac[kk + 1]); goto err_chk; } #ifdef CONFIG_PLATFORM_INTEL_BYT if (rtw_get_mac_addr_intel(mac) == 0) goto err_chk; #endif /* Use the mac address stored in the Efuse */ if (hw_mac_addr) { _rtw_memcpy(mac, hw_mac_addr, ETH_ALEN); goto err_chk; } err_chk: if (rtw_check_invalid_mac_address(mac) == _TRUE) { DBG_871X_LEVEL(_drv_err_, "invalid mac addr:"MAC_FMT", assign default one!!!\n", MAC_ARG(mac)); /* use default mac address */ mac[0] = 0x00; mac[1] = 0xe0; mac[2] = 0x4c; mac[3] = 0x87; mac[4] = 0x00; mac[5] = 0x00; } _rtw_memcpy(out, mac, ETH_ALEN); DBG_871X("%s mac addr:"MAC_FMT"\n", __func__, MAC_ARG(out)); } #ifdef CONFIG_80211N_HT void dump_ht_cap_ie_content(void *sel, u8 *buf, u32 buf_len) { if (buf_len != 26) { DBG_871X_SEL_NL(sel, "Invalid HT capability IE len:%d != %d\n", buf_len, 26); return; } DBG_871X_SEL_NL(sel, "HT Capabilities Info:%02x%02x\n", *(buf), *(buf+1)); DBG_871X_SEL_NL(sel, "A-MPDU Parameters:"HT_AMPDU_PARA_FMT"\n" , HT_AMPDU_PARA_ARG(HT_CAP_ELE_AMPDU_PARA(buf))); DBG_871X_SEL_NL(sel, "Supported MCS Set:"HT_SUP_MCS_SET_FMT"\n" , HT_SUP_MCS_SET_ARG(HT_CAP_ELE_SUP_MCS_SET(buf))); } void dump_ht_cap_ie(void *sel, u8 *ie, u32 ie_len) { u8* pos = (u8*)ie; u16 id; u16 len; u8 *ht_cap_ie; sint ht_cap_ielen; ht_cap_ie = rtw_get_ie(ie, _HT_CAPABILITY_IE_, &ht_cap_ielen, ie_len); if(!ie || ht_cap_ie != ie) return; dump_ht_cap_ie_content(sel, ht_cap_ie+2, ht_cap_ielen); } #endif /* CONFIG_80211N_HT */ void dump_ies(void *sel, u8 *buf, u32 buf_len) { u8* pos = (u8*)buf; u8 id, len; while(pos-buf+1<buf_len){ id = *pos; len = *(pos+1); DBG_871X_SEL_NL(sel, "%s ID:%u, LEN:%u\n", __FUNCTION__, id, len); #ifdef CONFIG_80211N_HT dump_ht_cap_ie(sel, pos, len); #endif dump_wps_ie(sel, pos, len); #ifdef CONFIG_P2P dump_p2p_ie(sel, pos, len); #ifdef CONFIG_WFD dump_wfd_ie(sel, pos, len); #endif #endif pos+=(2+len); } } void dump_wps_ie(void *sel, u8 *ie, u32 ie_len) { u8* pos = (u8*)ie; u16 id; u16 len; u8 *wps_ie; uint wps_ielen; wps_ie = rtw_get_wps_ie(ie, ie_len, NULL, &wps_ielen); if(wps_ie != ie || wps_ielen == 0) return; pos+=6; while(pos-ie < ie_len){ id = RTW_GET_BE16(pos); len = RTW_GET_BE16(pos + 2); DBG_871X_SEL_NL(sel, "%s ID:0x%04x, LEN:%u\n", __FUNCTION__, id, len); pos+=(4+len); } } #ifdef CONFIG_P2P /** * rtw_get_p2p_merged_len - Get merged ie length from muitiple p2p ies. * @in_ie: Pointer of the first p2p ie * @in_len: Total len of muiltiple p2p ies * Returns: Length of merged p2p ie length */ u32 rtw_get_p2p_merged_ies_len(u8 *in_ie, u32 in_len) { PNDIS_802_11_VARIABLE_IEs pIE; u8 OUI[4] = { 0x50, 0x6f, 0x9a, 0x09 }; int i=0; int j=0, len=0; while( i < in_len) { pIE = (PNDIS_802_11_VARIABLE_IEs)(in_ie+ i); if( pIE->ElementID == _VENDOR_SPECIFIC_IE_ && _rtw_memcmp(pIE->data, OUI, 4) ) { len += pIE->Length-4; // 4 is P2P OUI length, don't count it in this loop } i += (pIE->Length + 2); } return len + 4; // Append P2P OUI length at last. } /** * rtw_p2p_merge_ies - Merge muitiple p2p ies into one * @in_ie: Pointer of the first p2p ie * @in_len: Total len of muiltiple p2p ies * @merge_ie: Pointer of merged ie * Returns: Length of merged p2p ie */ int rtw_p2p_merge_ies(u8 *in_ie, u32 in_len, u8 *merge_ie) { PNDIS_802_11_VARIABLE_IEs pIE; u8 len = 0; u8 OUI[4] = { 0x50, 0x6f, 0x9a, 0x09 }; u8 ELOUI[6] = { 0xDD, 0x00, 0x50, 0x6f, 0x9a, 0x09 }; //EID;Len;OUI, Len would copy at the end of function int i=0; if( merge_ie != NULL) { //Set first P2P OUI _rtw_memcpy(merge_ie, ELOUI, 6); merge_ie += 6; while( i < in_len) { pIE = (PNDIS_802_11_VARIABLE_IEs)(in_ie+ i); // Take out the rest of P2P OUIs if( pIE->ElementID == _VENDOR_SPECIFIC_IE_ && _rtw_memcmp(pIE->data, OUI, 4) ) { _rtw_memcpy( merge_ie, pIE->data +4, pIE->Length -4); len += pIE->Length-4; merge_ie += pIE->Length-4; } i += (pIE->Length + 2); } return len + 4; // 4 is for P2P OUI } return 0; } void dump_p2p_ie(void *sel, u8 *ie, u32 ie_len) { u8* pos = (u8*)ie; u8 id; u16 len; u8 *p2p_ie; uint p2p_ielen; p2p_ie = rtw_get_p2p_ie(ie, ie_len, NULL, &p2p_ielen); if(p2p_ie != ie || p2p_ielen == 0) return; pos+=6; while(pos-ie < ie_len){ id = *pos; len = RTW_GET_LE16(pos+1); DBG_871X_SEL_NL(sel, "%s ID:%u, LEN:%u\n", __FUNCTION__, id, len); pos+=(3+len); } } u8 *rtw_get_p2p_ie_from_scan_queue(u8 *in_ie, int in_len, u8 *p2p_ie, uint *p2p_ielen, u8 frame_type) { u8* p2p = NULL; DBG_871X( "[%s] frame_type = %d\n", __FUNCTION__, frame_type ); switch( frame_type ) { case 1: case 3: { // Beacon or Probe Response p2p = rtw_get_p2p_ie(in_ie + _PROBERSP_IE_OFFSET_, in_len - _PROBERSP_IE_OFFSET_, p2p_ie, p2p_ielen); break; } case 2: { // Probe Request p2p = rtw_get_p2p_ie(in_ie + _PROBEREQ_IE_OFFSET_ , in_len - _PROBEREQ_IE_OFFSET_ , p2p_ie, p2p_ielen); break; } } return p2p; } /** * rtw_get_p2p_ie - Search P2P IE from a series of IEs * @in_ie: Address of IEs to search * @in_len: Length limit from in_ie * @p2p_ie: If not NULL and P2P IE is found, P2P IE will be copied to the buf starting from p2p_ie * @p2p_ielen: If not NULL and P2P IE is found, will set to the length of the entire P2P IE * * Returns: The address of the P2P IE found, or NULL */ u8 *rtw_get_p2p_ie(u8 *in_ie, int in_len, u8 *p2p_ie, uint *p2p_ielen) { uint cnt; u8 *p2p_ie_ptr = NULL; u8 eid, p2p_oui[4] = {0x50, 0x6F, 0x9A, 0x09}; if (p2p_ielen) *p2p_ielen = 0; if (!in_ie || in_len < 0) { rtw_warn_on(1); return p2p_ie_ptr; } if (in_len <= 0) return p2p_ie_ptr; cnt = 0; while (cnt + 1 + 4 < in_len) { eid = in_ie[cnt]; if (cnt + 1 + 4 >= MAX_IE_SZ) { rtw_warn_on(1); return NULL; } if (eid == WLAN_EID_VENDOR_SPECIFIC && _rtw_memcmp(&in_ie[cnt + 2], p2p_oui, 4) == _TRUE) { p2p_ie_ptr = in_ie + cnt; if (p2p_ie) _rtw_memcpy(p2p_ie, &in_ie[cnt], in_ie[cnt + 1] + 2); if (p2p_ielen) *p2p_ielen = in_ie[cnt + 1] + 2; break; } else { cnt += in_ie[cnt + 1] + 2; } } return p2p_ie_ptr; } /** * rtw_get_p2p_attr - Search a specific P2P attribute from a given P2P IE * @p2p_ie: Address of P2P IE to search * @p2p_ielen: Length limit from p2p_ie * @target_attr_id: The attribute ID of P2P attribute to search * @buf_attr: If not NULL and the P2P attribute is found, P2P attribute will be copied to the buf starting from buf_attr * @len_attr: If not NULL and the P2P attribute is found, will set to the length of the entire P2P attribute * * Returns: the address of the specific WPS attribute found, or NULL */ u8 *rtw_get_p2p_attr(u8 *p2p_ie, uint p2p_ielen, u8 target_attr_id ,u8 *buf_attr, u32 *len_attr) { u8 *attr_ptr = NULL; u8 *target_attr_ptr = NULL; u8 p2p_oui[4]={0x50,0x6F,0x9A,0x09}; if(len_attr) *len_attr = 0; if ( !p2p_ie || ( p2p_ie[0] != _VENDOR_SPECIFIC_IE_ ) || ( _rtw_memcmp( p2p_ie + 2, p2p_oui , 4 ) != _TRUE ) ) { return attr_ptr; } // 6 = 1(Element ID) + 1(Length) + 3 (OUI) + 1(OUI Type) attr_ptr = p2p_ie + 6; //goto first attr while(attr_ptr - p2p_ie < p2p_ielen) { // 3 = 1(Attribute ID) + 2(Length) u8 attr_id = *attr_ptr; u16 attr_data_len = RTW_GET_LE16(attr_ptr + 1); u16 attr_len = attr_data_len + 3; //DBG_871X("%s attr_ptr:%p, id:%u, length:%u\n", __FUNCTION__, attr_ptr, attr_id, attr_data_len); if( attr_id == target_attr_id ) { target_attr_ptr = attr_ptr; if(buf_attr) _rtw_memcpy(buf_attr, attr_ptr, attr_len); if(len_attr) *len_attr = attr_len; break; } else { attr_ptr += attr_len; //goto next } } return target_attr_ptr; } /** * rtw_get_p2p_attr_content - Search a specific P2P attribute content from a given P2P IE * @p2p_ie: Address of P2P IE to search * @p2p_ielen: Length limit from p2p_ie * @target_attr_id: The attribute ID of P2P attribute to search * @buf_content: If not NULL and the P2P attribute is found, P2P attribute content will be copied to the buf starting from buf_content * @len_content: If not NULL and the P2P attribute is found, will set to the length of the P2P attribute content * * Returns: the address of the specific P2P attribute content found, or NULL */ u8 *rtw_get_p2p_attr_content(u8 *p2p_ie, uint p2p_ielen, u8 target_attr_id ,u8 *buf_content, uint *len_content) { u8 *attr_ptr; u32 attr_len; if(len_content) *len_content = 0; attr_ptr = rtw_get_p2p_attr(p2p_ie, p2p_ielen, target_attr_id, NULL, &attr_len); if(attr_ptr && attr_len) { if(buf_content) _rtw_memcpy(buf_content, attr_ptr+3, attr_len-3); if(len_content) *len_content = attr_len-3; return attr_ptr+3; } return NULL; } u32 rtw_set_p2p_attr_content(u8 *pbuf, u8 attr_id, u16 attr_len, u8 *pdata_attr) { u32 a_len; *pbuf = attr_id; //*(u16*)(pbuf + 1) = cpu_to_le16(attr_len); RTW_PUT_LE16(pbuf + 1, attr_len); if(pdata_attr) _rtw_memcpy(pbuf + 3, pdata_attr, attr_len); a_len = attr_len + 3; return a_len; } static uint rtw_p2p_attr_remove(u8 *ie, uint ielen_ori, u8 attr_id) { u8 *target_attr; u32 target_attr_len; uint ielen = ielen_ori; int index=0; while(1) { target_attr=rtw_get_p2p_attr(ie, ielen, attr_id, NULL, &target_attr_len); if(target_attr && target_attr_len) { u8 *next_attr = target_attr+target_attr_len; uint remain_len = ielen-(next_attr-ie); //dump_ies(RTW_DBGDUMP, ie, ielen); #if 0 DBG_871X("[%d] ie:%p, ielen:%u\n" "target_attr:%p, target_attr_len:%u\n" "next_attr:%p, remain_len:%u\n" , index++ , ie, ielen , target_attr, target_attr_len , next_attr, remain_len ); #endif _rtw_memset(target_attr, 0, target_attr_len); _rtw_memcpy(target_attr, next_attr, remain_len); _rtw_memset(target_attr+remain_len, 0, target_attr_len); *(ie+1) -= target_attr_len; ielen-=target_attr_len; } else { //if(index>0) // dump_ies(RTW_DBGDUMP, ie, ielen); break; } } return ielen; } void rtw_WLAN_BSSID_EX_remove_p2p_attr(WLAN_BSSID_EX *bss_ex, u8 attr_id) { u8 *p2p_ie; uint p2p_ielen, p2p_ielen_ori; int cnt; if( (p2p_ie=rtw_get_p2p_ie(bss_ex->IEs+_FIXED_IE_LENGTH_, bss_ex->IELength-_FIXED_IE_LENGTH_, NULL, &p2p_ielen_ori)) ) { if (0) if(rtw_get_p2p_attr(p2p_ie, p2p_ielen_ori, attr_id, NULL, NULL)) { DBG_871X("rtw_get_p2p_attr: GOT P2P_ATTR:%u!!!!!!!!\n", attr_id); dump_ies(RTW_DBGDUMP, bss_ex->IEs+_FIXED_IE_LENGTH_, bss_ex->IELength-_FIXED_IE_LENGTH_); } p2p_ielen=rtw_p2p_attr_remove(p2p_ie, p2p_ielen_ori, attr_id); if(p2p_ielen != p2p_ielen_ori) { u8 *next_ie_ori = p2p_ie+p2p_ielen_ori; u8 *next_ie = p2p_ie+p2p_ielen; uint remain_len = bss_ex->IELength-(next_ie_ori-bss_ex->IEs); _rtw_memcpy(next_ie, next_ie_ori, remain_len); _rtw_memset(next_ie+remain_len, 0, p2p_ielen_ori-p2p_ielen); bss_ex->IELength -= p2p_ielen_ori-p2p_ielen; if (0) { DBG_871X("remove P2P_ATTR:%u!\n", attr_id); dump_ies(RTW_DBGDUMP, bss_ex->IEs+_FIXED_IE_LENGTH_, bss_ex->IELength-_FIXED_IE_LENGTH_); } } } } #endif //CONFIG_P2P #ifdef CONFIG_WFD void dump_wfd_ie(void *sel, u8 *ie, u32 ie_len) { u8* pos = (u8*)ie; u8 id; u16 len; u8 *wfd_ie; uint wfd_ielen; if(rtw_get_wfd_ie(ie, ie_len, NULL, &wfd_ielen) == _FALSE) return; pos+=6; while(pos-ie < ie_len){ id = *pos; len = RTW_GET_BE16(pos+1); DBG_871X_SEL_NL(sel, "%s ID:%u, LEN:%u\n", __FUNCTION__, id, len); pos+=(3+len); } } int rtw_get_wfd_ie(u8 *in_ie, int in_len, u8 *wfd_ie, uint *wfd_ielen) { int match; uint cnt = 0; u8 eid, wfd_oui[4]={0x50,0x6F,0x9A,0x0A}; match=_FALSE; if ( in_len < 0 ) { return match; } while(cnt<in_len) { eid = in_ie[cnt]; if( ( eid == _VENDOR_SPECIFIC_IE_ ) && ( _rtw_memcmp( &in_ie[cnt+2], wfd_oui, 4) == _TRUE ) ) { if ( wfd_ie != NULL ) { _rtw_memcpy( wfd_ie, &in_ie[ cnt ], in_ie[ cnt + 1 ] + 2 ); } else { if ( wfd_ielen != NULL ) { *wfd_ielen = 0; } } if ( wfd_ielen != NULL ) { *wfd_ielen = in_ie[ cnt + 1 ] + 2; } cnt += in_ie[ cnt + 1 ] + 2; match = _TRUE; break; } else { cnt += in_ie[ cnt + 1 ] +2; //goto next } } if ( match == _TRUE ) { match = cnt; } return match; } int rtw_get_wfd_ie_from_scan_queue(u8 *in_ie, int in_len, u8 *wfd_ie, uint *wfd_ielen, u8 frame_type) { int match; match=_FALSE; DBG_871X( "[%s] frame_type = %d\n", __FUNCTION__, frame_type ); switch( frame_type ) { case 1: case 3: { // Beacon or Probe Response match = rtw_get_wfd_ie(in_ie + _PROBERSP_IE_OFFSET_, in_len - _PROBERSP_IE_OFFSET_, wfd_ie, wfd_ielen); break; } case 2: { // Probe Request match = rtw_get_wfd_ie(in_ie + _PROBEREQ_IE_OFFSET_ , in_len - _PROBEREQ_IE_OFFSET_ , wfd_ie, wfd_ielen); break; } } return match; } // attr_content: The output buffer, contains the "body field" of WFD attribute. // attr_contentlen: The data length of the "body field" of WFD attribute. int rtw_get_wfd_attr_content(u8 *wfd_ie, uint wfd_ielen, u8 target_attr_id ,u8 *attr_content, uint *attr_contentlen) { int match; uint cnt = 0; u8 attr_id, wfd_oui[4]={0x50,0x6F,0x9A,0x0A}; match=_FALSE; if ( ( wfd_ie[ 0 ] != _VENDOR_SPECIFIC_IE_ ) || ( _rtw_memcmp( wfd_ie + 2, wfd_oui , 4 ) != _TRUE ) ) { return( match ); } // 1 ( WFD IE ) + 1 ( Length ) + 3 ( OUI ) + 1 ( OUI Type ) cnt = 6; while( cnt < wfd_ielen ) { u16 attrlen = RTW_GET_BE16(wfd_ie + cnt + 1); attr_id = wfd_ie[cnt]; if( attr_id == target_attr_id ) { // 3 -> 1 byte for attribute ID field, 2 bytes for length field if(attr_content) _rtw_memcpy( attr_content, &wfd_ie[ cnt + 3 ], attrlen ); if(attr_contentlen) *attr_contentlen = attrlen; cnt += attrlen + 3; match = _TRUE; break; } else { cnt += attrlen + 3; //goto next } } return match; } #endif // CONFIG_WFD //Baron adds to avoid FreeBSD warning int ieee80211_is_empty_essid(const char *essid, int essid_len) { /* Single white space is for Linksys APs */ if (essid_len == 1 && essid[0] == ' ') return 1; /* Otherwise, if the entire essid is 0, we assume it is hidden */ while (essid_len) { essid_len--; if (essid[essid_len] != '\0') return 0; } return 1; } int ieee80211_get_hdrlen(u16 fc) { int hdrlen = 24; switch (WLAN_FC_GET_TYPE(fc)) { case RTW_IEEE80211_FTYPE_DATA: if (fc & RTW_IEEE80211_STYPE_QOS_DATA) hdrlen += 2; if ((fc & RTW_IEEE80211_FCTL_FROMDS) && (fc & RTW_IEEE80211_FCTL_TODS)) hdrlen += 6; /* Addr4 */ break; case RTW_IEEE80211_FTYPE_CTL: switch (WLAN_FC_GET_STYPE(fc)) { case RTW_IEEE80211_STYPE_CTS: case RTW_IEEE80211_STYPE_ACK: hdrlen = 10; break; default: hdrlen = 16; break; } break; } return hdrlen; } int rtw_get_cipher_info(struct wlan_network *pnetwork) { u32 wpa_ielen; unsigned char *pbuf; int group_cipher = 0, pairwise_cipher = 0, is8021x = 0; int ret = _FAIL; pbuf = rtw_get_wpa_ie(&pnetwork->network.IEs[12], &wpa_ielen, pnetwork->network.IELength-12); if(pbuf && (wpa_ielen>0)) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_cipher_info: wpa_ielen: %d", wpa_ielen)); if (_SUCCESS == rtw_parse_wpa_ie(pbuf, wpa_ielen+2, &group_cipher, &pairwise_cipher, &is8021x)) { pnetwork->BcnInfo.pairwise_cipher = pairwise_cipher; pnetwork->BcnInfo.group_cipher = group_cipher; pnetwork->BcnInfo.is_8021x = is8021x; RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("%s: pnetwork->pairwise_cipher: %d, is_8021x is %d", __func__, pnetwork->BcnInfo.pairwise_cipher, pnetwork->BcnInfo.is_8021x)); ret = _SUCCESS; } } else { pbuf = rtw_get_wpa2_ie(&pnetwork->network.IEs[12], &wpa_ielen, pnetwork->network.IELength-12); if(pbuf && (wpa_ielen>0)) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("get RSN IE\n")); if (_SUCCESS == rtw_parse_wpa2_ie(pbuf, wpa_ielen+2, &group_cipher, &pairwise_cipher, &is8021x)) { RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("get RSN IE OK!!!\n")); pnetwork->BcnInfo.pairwise_cipher = pairwise_cipher; pnetwork->BcnInfo.group_cipher = group_cipher; pnetwork->BcnInfo.is_8021x = is8021x; RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("%s: pnetwork->pairwise_cipher: %d," "pnetwork->group_cipher is %d, is_8021x is %d", __func__, pnetwork->BcnInfo.pairwise_cipher, pnetwork->BcnInfo.group_cipher,pnetwork->BcnInfo.is_8021x)); ret = _SUCCESS; } } } return ret; } void rtw_get_bcn_info(struct wlan_network *pnetwork) { unsigned short cap = 0; u8 bencrypt = 0; //u8 wpa_ie[255],rsn_ie[255]; u16 wpa_len=0,rsn_len=0; struct HT_info_element *pht_info = NULL; struct rtw_ieee80211_ht_cap *pht_cap = NULL; unsigned int len; unsigned char *p; _rtw_memcpy((u8 *)&cap, rtw_get_capability_from_ie(pnetwork->network.IEs), 2); cap = le16_to_cpu(cap); if (cap & WLAN_CAPABILITY_PRIVACY) { bencrypt = 1; pnetwork->network.Privacy = 1; } else { pnetwork->BcnInfo.encryp_protocol = ENCRYP_PROTOCOL_OPENSYS; } rtw_get_sec_ie(pnetwork->network.IEs ,pnetwork->network.IELength,NULL,&rsn_len,NULL,&wpa_len); RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_bcn_info: ssid=%s\n",pnetwork->network.Ssid.Ssid)); RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_bcn_info: wpa_len=%d rsn_len=%d\n",wpa_len,rsn_len)); RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_bcn_info: ssid=%s\n",pnetwork->network.Ssid.Ssid)); RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_bcn_info: wpa_len=%d rsn_len=%d\n",wpa_len,rsn_len)); if (rsn_len > 0) { pnetwork->BcnInfo.encryp_protocol = ENCRYP_PROTOCOL_WPA2; } else if (wpa_len > 0) { pnetwork->BcnInfo.encryp_protocol = ENCRYP_PROTOCOL_WPA; } else { if (bencrypt) pnetwork->BcnInfo.encryp_protocol = ENCRYP_PROTOCOL_WEP; } RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_bcn_info: pnetwork->encryp_protocol is %x\n", pnetwork->BcnInfo.encryp_protocol)); RT_TRACE(_module_rtl871x_mlme_c_,_drv_info_,("rtw_get_bcn_info: pnetwork->encryp_protocol is %x\n", pnetwork->BcnInfo.encryp_protocol)); rtw_get_cipher_info(pnetwork); /* get bwmode and ch_offset */ /* parsing HT_CAP_IE */ p = rtw_get_ie(pnetwork->network.IEs + _FIXED_IE_LENGTH_, _HT_CAPABILITY_IE_, &len, pnetwork->network.IELength - _FIXED_IE_LENGTH_); if(p && len>0) { pht_cap = (struct rtw_ieee80211_ht_cap *)(p + 2); pnetwork->BcnInfo.ht_cap_info = pht_cap->cap_info; } else { pnetwork->BcnInfo.ht_cap_info = 0; } /* parsing HT_INFO_IE */ p = rtw_get_ie(pnetwork->network.IEs + _FIXED_IE_LENGTH_, _HT_ADD_INFO_IE_, &len, pnetwork->network.IELength - _FIXED_IE_LENGTH_); if(p && len>0) { pht_info = (struct HT_info_element *)(p + 2); pnetwork->BcnInfo.ht_info_infos_0 = pht_info->infos[0]; } else { pnetwork->BcnInfo.ht_info_infos_0 = 0; } } //show MCS rate, unit: 100Kbps u16 rtw_mcs_rate(u8 rf_type, u8 bw_40MHz, u8 short_GI, unsigned char * MCS_rate) { u16 max_rate = 0; if(rf_type == RF_1T1R) { if(MCS_rate[0] & BIT(7)) max_rate = (bw_40MHz) ? ((short_GI)?1500:1350):((short_GI)?722:650); else if(MCS_rate[0] & BIT(6)) max_rate = (bw_40MHz) ? ((short_GI)?1350:1215):((short_GI)?650:585); else if(MCS_rate[0] & BIT(5)) max_rate = (bw_40MHz) ? ((short_GI)?1200:1080):((short_GI)?578:520); else if(MCS_rate[0] & BIT(4)) max_rate = (bw_40MHz) ? ((short_GI)?900:810):((short_GI)?433:390); else if(MCS_rate[0] & BIT(3)) max_rate = (bw_40MHz) ? ((short_GI)?600:540):((short_GI)?289:260); else if(MCS_rate[0] & BIT(2)) max_rate = (bw_40MHz) ? ((short_GI)?450:405):((short_GI)?217:195); else if(MCS_rate[0] & BIT(1)) max_rate = (bw_40MHz) ? ((short_GI)?300:270):((short_GI)?144:130); else if(MCS_rate[0] & BIT(0)) max_rate = (bw_40MHz) ? ((short_GI)?150:135):((short_GI)?72:65); } else { if(MCS_rate[1]) { if(MCS_rate[1] & BIT(7)) max_rate = (bw_40MHz) ? ((short_GI)?3000:2700):((short_GI)?1444:1300); else if(MCS_rate[1] & BIT(6)) max_rate = (bw_40MHz) ? ((short_GI)?2700:2430):((short_GI)?1300:1170); else if(MCS_rate[1] & BIT(5)) max_rate = (bw_40MHz) ? ((short_GI)?2400:2160):((short_GI)?1156:1040); else if(MCS_rate[1] & BIT(4)) max_rate = (bw_40MHz) ? ((short_GI)?1800:1620):((short_GI)?867:780); else if(MCS_rate[1] & BIT(3)) max_rate = (bw_40MHz) ? ((short_GI)?1200:1080):((short_GI)?578:520); else if(MCS_rate[1] & BIT(2)) max_rate = (bw_40MHz) ? ((short_GI)?900:810):((short_GI)?433:390); else if(MCS_rate[1] & BIT(1)) max_rate = (bw_40MHz) ? ((short_GI)?600:540):((short_GI)?289:260); else if(MCS_rate[1] & BIT(0)) max_rate = (bw_40MHz) ? ((short_GI)?300:270):((short_GI)?144:130); } else { if(MCS_rate[0] & BIT(7)) max_rate = (bw_40MHz) ? ((short_GI)?1500:1350):((short_GI)?722:650); else if(MCS_rate[0] & BIT(6)) max_rate = (bw_40MHz) ? ((short_GI)?1350:1215):((short_GI)?650:585); else if(MCS_rate[0] & BIT(5)) max_rate = (bw_40MHz) ? ((short_GI)?1200:1080):((short_GI)?578:520); else if(MCS_rate[0] & BIT(4)) max_rate = (bw_40MHz) ? ((short_GI)?900:810):((short_GI)?433:390); else if(MCS_rate[0] & BIT(3)) max_rate = (bw_40MHz) ? ((short_GI)?600:540):((short_GI)?289:260); else if(MCS_rate[0] & BIT(2)) max_rate = (bw_40MHz) ? ((short_GI)?450:405):((short_GI)?217:195); else if(MCS_rate[0] & BIT(1)) max_rate = (bw_40MHz) ? ((short_GI)?300:270):((short_GI)?144:130); else if(MCS_rate[0] & BIT(0)) max_rate = (bw_40MHz) ? ((short_GI)?150:135):((short_GI)?72:65); } } return max_rate; } int rtw_action_frame_parse(const u8 *frame, u32 frame_len, u8* category, u8 *action) { const u8 *frame_body = frame + sizeof(struct rtw_ieee80211_hdr_3addr); u16 fc; u8 c; u8 a = ACT_PUBLIC_MAX; fc = le16_to_cpu(((struct rtw_ieee80211_hdr_3addr *)frame)->frame_ctl); if ((fc & (RTW_IEEE80211_FCTL_FTYPE|RTW_IEEE80211_FCTL_STYPE)) != (RTW_IEEE80211_FTYPE_MGMT|RTW_IEEE80211_STYPE_ACTION) ) { return _FALSE; } c = frame_body[0]; switch(c) { case RTW_WLAN_CATEGORY_P2P: /* vendor-specific */ break; default: a = frame_body[1]; } if (category) *category = c; if (action) *action = a; return _TRUE; } static const char *_action_public_str[] = { "ACT_PUB_BSSCOEXIST", "ACT_PUB_DSE_ENABLE", "ACT_PUB_DSE_DEENABLE", "ACT_PUB_DSE_REG_LOCATION", "ACT_PUB_EXT_CHL_SWITCH", "ACT_PUB_DSE_MSR_REQ", "ACT_PUB_DSE_MSR_RPRT", "ACT_PUB_MP", "ACT_PUB_DSE_PWR_CONSTRAINT", "ACT_PUB_VENDOR", "ACT_PUB_GAS_INITIAL_REQ", "ACT_PUB_GAS_INITIAL_RSP", "ACT_PUB_GAS_COMEBACK_REQ", "ACT_PUB_GAS_COMEBACK_RSP", "ACT_PUB_TDLS_DISCOVERY_RSP", "ACT_PUB_LOCATION_TRACK", "ACT_PUB_RSVD", }; const char *action_public_str(u8 action) { action = (action >= ACT_PUBLIC_MAX) ? ACT_PUBLIC_MAX : action; return _action_public_str[action]; }
gpl-2.0
dohmain/qmk_firmware
layouts/community/ergodox/romanzolotarev-norman-qwerty-osx/keymap.c
25
2760
#include QMK_KEYBOARD_H #include "debug.h" #include "action_layer.h" #define BASE 0 #define QWRT 1 const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [BASE] = LAYOUT_ergodox( KC_GRV, KC_1, KC_2, KC_3, KC_4, KC_5, KC_F5, KC_TAB, KC_Q, KC_W, KC_D, KC_F, KC_K, KC_BSLS, KC_LCTL, KC_A, KC_S, KC_E, KC_T, KC_G, KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_LBRC, KC_F1, KC_F2, KC_F3, KC_F4, KC_LGUI, /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ KC_VOLD, KC_MUTE, /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ KC_VOLU, /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ KC_BSPC, CTL_T(KC_ESC), KC_LALT, // /*-*/ KC_F6, KC_6, KC_7, KC_8, KC_9, KC_0, KC_EQL, /*-*/ TG(QWRT), KC_J, KC_U, KC_R, KC_L, KC_SCLN, KC_MINS, /*-*/ /*-*/ KC_Y, KC_N, KC_I, KC_O, KC_H, KC_ENT, /*-*/ KC_RBRC, KC_P, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, /*-*/ /*-*/ /*-*/ KC_RGUI, KC_LEFT, KC_DOWN, KC_UP, KC_RGHT, KC_MPLY, KC_MNXT, KC_MPRV, KC_RALT, KC_QUOT, KC_SPC ), [QWRT] = LAYOUT_ergodox( KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_E, KC_R, KC_T, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_D, KC_F, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ KC_TRNS, KC_TRNS, /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ /*-*/ KC_TRNS, /*-*/ /*-*/ /*-*/ /*-*/ KC_TRNS, KC_TRNS, KC_TRNS, // /*-*/ KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, /*-*/ KC_TRNS, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_TRNS, /*-*/ /*-*/ KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_TRNS, /*-*/ KC_TRNS, KC_N, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, /*-*/ /*-*/ /*-*/ KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS ), }; const uint16_t PROGMEM fn_actions[] = { }; const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt) { return MACRO_NONE; }; // Runs just one time when the keyboard initializes. void matrix_init_user(void) { }; // Runs constantly in the background, in a loop. void matrix_scan_user(void) { uint8_t layer = biton32(layer_state); ergodox_board_led_off(); ergodox_right_led_1_off(); ergodox_right_led_2_off(); ergodox_right_led_3_off(); switch (layer) { case QWRT: ergodox_right_led_1_on(); break; default: break; } };
gpl-2.0
zhenyw/linux
drivers/gpu/drm/nouveau/nvkm/engine/disp/vga.c
1561
6449
/* * Copyright 2012 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Ben Skeggs */ #include <subdev/vga.h> u8 nvkm_rdport(struct nvkm_device *device, int head, u16 port) { if (device->card_type >= NV_50) return nvkm_rd08(device, 0x601000 + port); if (port == 0x03c0 || port == 0x03c1 || /* AR */ port == 0x03c2 || port == 0x03da || /* INP0 */ port == 0x03d4 || port == 0x03d5) /* CR */ return nvkm_rd08(device, 0x601000 + (head * 0x2000) + port); if (port == 0x03c2 || port == 0x03cc || /* MISC */ port == 0x03c4 || port == 0x03c5 || /* SR */ port == 0x03ce || port == 0x03cf) { /* GR */ if (device->card_type < NV_40) head = 0; /* CR44 selects head */ return nvkm_rd08(device, 0x0c0000 + (head * 0x2000) + port); } return 0x00; } void nvkm_wrport(struct nvkm_device *device, int head, u16 port, u8 data) { if (device->card_type >= NV_50) nvkm_wr08(device, 0x601000 + port, data); else if (port == 0x03c0 || port == 0x03c1 || /* AR */ port == 0x03c2 || port == 0x03da || /* INP0 */ port == 0x03d4 || port == 0x03d5) /* CR */ nvkm_wr08(device, 0x601000 + (head * 0x2000) + port, data); else if (port == 0x03c2 || port == 0x03cc || /* MISC */ port == 0x03c4 || port == 0x03c5 || /* SR */ port == 0x03ce || port == 0x03cf) { /* GR */ if (device->card_type < NV_40) head = 0; /* CR44 selects head */ nvkm_wr08(device, 0x0c0000 + (head * 0x2000) + port, data); } } u8 nvkm_rdvgas(struct nvkm_device *device, int head, u8 index) { nvkm_wrport(device, head, 0x03c4, index); return nvkm_rdport(device, head, 0x03c5); } void nvkm_wrvgas(struct nvkm_device *device, int head, u8 index, u8 value) { nvkm_wrport(device, head, 0x03c4, index); nvkm_wrport(device, head, 0x03c5, value); } u8 nvkm_rdvgag(struct nvkm_device *device, int head, u8 index) { nvkm_wrport(device, head, 0x03ce, index); return nvkm_rdport(device, head, 0x03cf); } void nvkm_wrvgag(struct nvkm_device *device, int head, u8 index, u8 value) { nvkm_wrport(device, head, 0x03ce, index); nvkm_wrport(device, head, 0x03cf, value); } u8 nvkm_rdvgac(struct nvkm_device *device, int head, u8 index) { nvkm_wrport(device, head, 0x03d4, index); return nvkm_rdport(device, head, 0x03d5); } void nvkm_wrvgac(struct nvkm_device *device, int head, u8 index, u8 value) { nvkm_wrport(device, head, 0x03d4, index); nvkm_wrport(device, head, 0x03d5, value); } u8 nvkm_rdvgai(struct nvkm_device *device, int head, u16 port, u8 index) { if (port == 0x03c4) return nvkm_rdvgas(device, head, index); if (port == 0x03ce) return nvkm_rdvgag(device, head, index); if (port == 0x03d4) return nvkm_rdvgac(device, head, index); return 0x00; } void nvkm_wrvgai(struct nvkm_device *device, int head, u16 port, u8 index, u8 value) { if (port == 0x03c4) nvkm_wrvgas(device, head, index, value); else if (port == 0x03ce) nvkm_wrvgag(device, head, index, value); else if (port == 0x03d4) nvkm_wrvgac(device, head, index, value); } bool nvkm_lockvgac(struct nvkm_device *device, bool lock) { bool locked = !nvkm_rdvgac(device, 0, 0x1f); u8 data = lock ? 0x99 : 0x57; if (device->card_type < NV_50) nvkm_wrvgac(device, 0, 0x1f, data); else nvkm_wrvgac(device, 0, 0x3f, data); if (device->chipset == 0x11) { if (!(nvkm_rd32(device, 0x001084) & 0x10000000)) nvkm_wrvgac(device, 1, 0x1f, data); } return locked; } /* CR44 takes values 0 (head A), 3 (head B) and 4 (heads tied) * it affects only the 8 bit vga io regs, which we access using mmio at * 0xc{0,2}3c*, 0x60{1,3}3*, and 0x68{1,3}3d* * in general, the set value of cr44 does not matter: reg access works as * expected and values can be set for the appropriate head by using a 0x2000 * offset as required * however: * a) pre nv40, the head B range of PRMVIO regs at 0xc23c* was not exposed and * cr44 must be set to 0 or 3 for accessing values on the correct head * through the common 0xc03c* addresses * b) in tied mode (4) head B is programmed to the values set on head A, and * access using the head B addresses can have strange results, ergo we leave * tied mode in init once we know to what cr44 should be restored on exit * * the owner parameter is slightly abused: * 0 and 1 are treated as head values and so the set value is (owner * 3) * other values are treated as literal values to set */ u8 nvkm_rdvgaowner(struct nvkm_device *device) { if (device->card_type < NV_50) { if (device->chipset == 0x11) { u32 tied = nvkm_rd32(device, 0x001084) & 0x10000000; if (tied == 0) { u8 slA = nvkm_rdvgac(device, 0, 0x28) & 0x80; u8 tvA = nvkm_rdvgac(device, 0, 0x33) & 0x01; u8 slB = nvkm_rdvgac(device, 1, 0x28) & 0x80; u8 tvB = nvkm_rdvgac(device, 1, 0x33) & 0x01; if (slA && !tvA) return 0x00; if (slB && !tvB) return 0x03; if (slA) return 0x00; if (slB) return 0x03; return 0x00; } return 0x04; } return nvkm_rdvgac(device, 0, 0x44); } return 0x00; } void nvkm_wrvgaowner(struct nvkm_device *device, u8 select) { if (device->card_type < NV_50) { u8 owner = (select == 1) ? 3 : select; if (device->chipset == 0x11) { /* workaround hw lockup bug */ nvkm_rdvgac(device, 0, 0x1f); nvkm_rdvgac(device, 1, 0x1f); } nvkm_wrvgac(device, 0, 0x44, owner); if (device->chipset == 0x11) { nvkm_wrvgac(device, 0, 0x2e, owner); nvkm_wrvgac(device, 0, 0x2e, owner); } } }
gpl-2.0
gianogli/boeffla-kernel-cm-s3-7
arch/sparc/kernel/pci.c
2329
30023
/* pci.c: UltraSparc PCI controller support. * * Copyright (C) 1997, 1998, 1999 David S. Miller (davem@redhat.com) * Copyright (C) 1998, 1999 Eddie C. Dost (ecd@skynet.be) * Copyright (C) 1999 Jakub Jelinek (jj@ultra.linux.cz) * * OF tree based PCI bus probing taken from the PowerPC port * with minor modifications, see there for credits. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/sched.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/pci.h> #include <linux/msi.h> #include <linux/irq.h> #include <linux/init.h> #include <linux/of.h> #include <linux/of_device.h> #include <asm/uaccess.h> #include <asm/pgtable.h> #include <asm/irq.h> #include <asm/prom.h> #include <asm/apb.h> #include "pci_impl.h" /* List of all PCI controllers found in the system. */ struct pci_pbm_info *pci_pbm_root = NULL; /* Each PBM found gets a unique index. */ int pci_num_pbms = 0; volatile int pci_poke_in_progress; volatile int pci_poke_cpu = -1; volatile int pci_poke_faulted; static DEFINE_SPINLOCK(pci_poke_lock); void pci_config_read8(u8 *addr, u8 *ret) { unsigned long flags; u8 byte; spin_lock_irqsave(&pci_poke_lock, flags); pci_poke_cpu = smp_processor_id(); pci_poke_in_progress = 1; pci_poke_faulted = 0; __asm__ __volatile__("membar #Sync\n\t" "lduba [%1] %2, %0\n\t" "membar #Sync" : "=r" (byte) : "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E_L) : "memory"); pci_poke_in_progress = 0; pci_poke_cpu = -1; if (!pci_poke_faulted) *ret = byte; spin_unlock_irqrestore(&pci_poke_lock, flags); } void pci_config_read16(u16 *addr, u16 *ret) { unsigned long flags; u16 word; spin_lock_irqsave(&pci_poke_lock, flags); pci_poke_cpu = smp_processor_id(); pci_poke_in_progress = 1; pci_poke_faulted = 0; __asm__ __volatile__("membar #Sync\n\t" "lduha [%1] %2, %0\n\t" "membar #Sync" : "=r" (word) : "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E_L) : "memory"); pci_poke_in_progress = 0; pci_poke_cpu = -1; if (!pci_poke_faulted) *ret = word; spin_unlock_irqrestore(&pci_poke_lock, flags); } void pci_config_read32(u32 *addr, u32 *ret) { unsigned long flags; u32 dword; spin_lock_irqsave(&pci_poke_lock, flags); pci_poke_cpu = smp_processor_id(); pci_poke_in_progress = 1; pci_poke_faulted = 0; __asm__ __volatile__("membar #Sync\n\t" "lduwa [%1] %2, %0\n\t" "membar #Sync" : "=r" (dword) : "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E_L) : "memory"); pci_poke_in_progress = 0; pci_poke_cpu = -1; if (!pci_poke_faulted) *ret = dword; spin_unlock_irqrestore(&pci_poke_lock, flags); } void pci_config_write8(u8 *addr, u8 val) { unsigned long flags; spin_lock_irqsave(&pci_poke_lock, flags); pci_poke_cpu = smp_processor_id(); pci_poke_in_progress = 1; pci_poke_faulted = 0; __asm__ __volatile__("membar #Sync\n\t" "stba %0, [%1] %2\n\t" "membar #Sync" : /* no outputs */ : "r" (val), "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E_L) : "memory"); pci_poke_in_progress = 0; pci_poke_cpu = -1; spin_unlock_irqrestore(&pci_poke_lock, flags); } void pci_config_write16(u16 *addr, u16 val) { unsigned long flags; spin_lock_irqsave(&pci_poke_lock, flags); pci_poke_cpu = smp_processor_id(); pci_poke_in_progress = 1; pci_poke_faulted = 0; __asm__ __volatile__("membar #Sync\n\t" "stha %0, [%1] %2\n\t" "membar #Sync" : /* no outputs */ : "r" (val), "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E_L) : "memory"); pci_poke_in_progress = 0; pci_poke_cpu = -1; spin_unlock_irqrestore(&pci_poke_lock, flags); } void pci_config_write32(u32 *addr, u32 val) { unsigned long flags; spin_lock_irqsave(&pci_poke_lock, flags); pci_poke_cpu = smp_processor_id(); pci_poke_in_progress = 1; pci_poke_faulted = 0; __asm__ __volatile__("membar #Sync\n\t" "stwa %0, [%1] %2\n\t" "membar #Sync" : /* no outputs */ : "r" (val), "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E_L) : "memory"); pci_poke_in_progress = 0; pci_poke_cpu = -1; spin_unlock_irqrestore(&pci_poke_lock, flags); } static int ofpci_verbose; static int __init ofpci_debug(char *str) { int val = 0; get_option(&str, &val); if (val) ofpci_verbose = 1; return 1; } __setup("ofpci_debug=", ofpci_debug); static unsigned long pci_parse_of_flags(u32 addr0) { unsigned long flags = 0; if (addr0 & 0x02000000) { flags = IORESOURCE_MEM | PCI_BASE_ADDRESS_SPACE_MEMORY; flags |= (addr0 >> 22) & PCI_BASE_ADDRESS_MEM_TYPE_64; flags |= (addr0 >> 28) & PCI_BASE_ADDRESS_MEM_TYPE_1M; if (addr0 & 0x40000000) flags |= IORESOURCE_PREFETCH | PCI_BASE_ADDRESS_MEM_PREFETCH; } else if (addr0 & 0x01000000) flags = IORESOURCE_IO | PCI_BASE_ADDRESS_SPACE_IO; return flags; } /* The of_device layer has translated all of the assigned-address properties * into physical address resources, we only have to figure out the register * mapping. */ static void pci_parse_of_addrs(struct platform_device *op, struct device_node *node, struct pci_dev *dev) { struct resource *op_res; const u32 *addrs; int proplen; addrs = of_get_property(node, "assigned-addresses", &proplen); if (!addrs) return; if (ofpci_verbose) printk(" parse addresses (%d bytes) @ %p\n", proplen, addrs); op_res = &op->resource[0]; for (; proplen >= 20; proplen -= 20, addrs += 5, op_res++) { struct resource *res; unsigned long flags; int i; flags = pci_parse_of_flags(addrs[0]); if (!flags) continue; i = addrs[0] & 0xff; if (ofpci_verbose) printk(" start: %llx, end: %llx, i: %x\n", op_res->start, op_res->end, i); if (PCI_BASE_ADDRESS_0 <= i && i <= PCI_BASE_ADDRESS_5) { res = &dev->resource[(i - PCI_BASE_ADDRESS_0) >> 2]; } else if (i == dev->rom_base_reg) { res = &dev->resource[PCI_ROM_RESOURCE]; flags |= IORESOURCE_READONLY | IORESOURCE_CACHEABLE; } else { printk(KERN_ERR "PCI: bad cfg reg num 0x%x\n", i); continue; } res->start = op_res->start; res->end = op_res->end; res->flags = flags; res->name = pci_name(dev); } } static struct pci_dev *of_create_pci_dev(struct pci_pbm_info *pbm, struct device_node *node, struct pci_bus *bus, int devfn) { struct dev_archdata *sd; struct pci_slot *slot; struct platform_device *op; struct pci_dev *dev; const char *type; u32 class; dev = alloc_pci_dev(); if (!dev) return NULL; sd = &dev->dev.archdata; sd->iommu = pbm->iommu; sd->stc = &pbm->stc; sd->host_controller = pbm; sd->op = op = of_find_device_by_node(node); sd->numa_node = pbm->numa_node; sd = &op->dev.archdata; sd->iommu = pbm->iommu; sd->stc = &pbm->stc; sd->numa_node = pbm->numa_node; if (!strcmp(node->name, "ebus")) of_propagate_archdata(op); type = of_get_property(node, "device_type", NULL); if (type == NULL) type = ""; if (ofpci_verbose) printk(" create device, devfn: %x, type: %s\n", devfn, type); dev->bus = bus; dev->sysdata = node; dev->dev.parent = bus->bridge; dev->dev.bus = &pci_bus_type; dev->dev.of_node = node; dev->devfn = devfn; dev->multifunction = 0; /* maybe a lie? */ set_pcie_port_type(dev); list_for_each_entry(slot, &dev->bus->slots, list) if (PCI_SLOT(dev->devfn) == slot->number) dev->slot = slot; dev->vendor = of_getintprop_default(node, "vendor-id", 0xffff); dev->device = of_getintprop_default(node, "device-id", 0xffff); dev->subsystem_vendor = of_getintprop_default(node, "subsystem-vendor-id", 0); dev->subsystem_device = of_getintprop_default(node, "subsystem-id", 0); dev->cfg_size = pci_cfg_space_size(dev); /* We can't actually use the firmware value, we have * to read what is in the register right now. One * reason is that in the case of IDE interfaces the * firmware can sample the value before the the IDE * interface is programmed into native mode. */ pci_read_config_dword(dev, PCI_CLASS_REVISION, &class); dev->class = class >> 8; dev->revision = class & 0xff; dev_set_name(&dev->dev, "%04x:%02x:%02x.%d", pci_domain_nr(bus), dev->bus->number, PCI_SLOT(devfn), PCI_FUNC(devfn)); if (ofpci_verbose) printk(" class: 0x%x device name: %s\n", dev->class, pci_name(dev)); /* I have seen IDE devices which will not respond to * the bmdma simplex check reads if bus mastering is * disabled. */ if ((dev->class >> 8) == PCI_CLASS_STORAGE_IDE) pci_set_master(dev); dev->current_state = 4; /* unknown power state */ dev->error_state = pci_channel_io_normal; dev->dma_mask = 0xffffffff; if (!strcmp(node->name, "pci")) { /* a PCI-PCI bridge */ dev->hdr_type = PCI_HEADER_TYPE_BRIDGE; dev->rom_base_reg = PCI_ROM_ADDRESS1; } else if (!strcmp(type, "cardbus")) { dev->hdr_type = PCI_HEADER_TYPE_CARDBUS; } else { dev->hdr_type = PCI_HEADER_TYPE_NORMAL; dev->rom_base_reg = PCI_ROM_ADDRESS; dev->irq = sd->op->archdata.irqs[0]; if (dev->irq == 0xffffffff) dev->irq = PCI_IRQ_NONE; } pci_parse_of_addrs(sd->op, node, dev); if (ofpci_verbose) printk(" adding to system ...\n"); pci_device_add(dev, bus); return dev; } static void __devinit apb_calc_first_last(u8 map, u32 *first_p, u32 *last_p) { u32 idx, first, last; first = 8; last = 0; for (idx = 0; idx < 8; idx++) { if ((map & (1 << idx)) != 0) { if (first > idx) first = idx; if (last < idx) last = idx; } } *first_p = first; *last_p = last; } static void pci_resource_adjust(struct resource *res, struct resource *root) { res->start += root->start; res->end += root->start; } /* For PCI bus devices which lack a 'ranges' property we interrogate * the config space values to set the resources, just like the generic * Linux PCI probing code does. */ static void __devinit pci_cfg_fake_ranges(struct pci_dev *dev, struct pci_bus *bus, struct pci_pbm_info *pbm) { struct resource *res; u8 io_base_lo, io_limit_lo; u16 mem_base_lo, mem_limit_lo; unsigned long base, limit; pci_read_config_byte(dev, PCI_IO_BASE, &io_base_lo); pci_read_config_byte(dev, PCI_IO_LIMIT, &io_limit_lo); base = (io_base_lo & PCI_IO_RANGE_MASK) << 8; limit = (io_limit_lo & PCI_IO_RANGE_MASK) << 8; if ((io_base_lo & PCI_IO_RANGE_TYPE_MASK) == PCI_IO_RANGE_TYPE_32) { u16 io_base_hi, io_limit_hi; pci_read_config_word(dev, PCI_IO_BASE_UPPER16, &io_base_hi); pci_read_config_word(dev, PCI_IO_LIMIT_UPPER16, &io_limit_hi); base |= (io_base_hi << 16); limit |= (io_limit_hi << 16); } res = bus->resource[0]; if (base <= limit) { res->flags = (io_base_lo & PCI_IO_RANGE_TYPE_MASK) | IORESOURCE_IO; if (!res->start) res->start = base; if (!res->end) res->end = limit + 0xfff; pci_resource_adjust(res, &pbm->io_space); } pci_read_config_word(dev, PCI_MEMORY_BASE, &mem_base_lo); pci_read_config_word(dev, PCI_MEMORY_LIMIT, &mem_limit_lo); base = (mem_base_lo & PCI_MEMORY_RANGE_MASK) << 16; limit = (mem_limit_lo & PCI_MEMORY_RANGE_MASK) << 16; res = bus->resource[1]; if (base <= limit) { res->flags = ((mem_base_lo & PCI_MEMORY_RANGE_TYPE_MASK) | IORESOURCE_MEM); res->start = base; res->end = limit + 0xfffff; pci_resource_adjust(res, &pbm->mem_space); } pci_read_config_word(dev, PCI_PREF_MEMORY_BASE, &mem_base_lo); pci_read_config_word(dev, PCI_PREF_MEMORY_LIMIT, &mem_limit_lo); base = (mem_base_lo & PCI_PREF_RANGE_MASK) << 16; limit = (mem_limit_lo & PCI_PREF_RANGE_MASK) << 16; if ((mem_base_lo & PCI_PREF_RANGE_TYPE_MASK) == PCI_PREF_RANGE_TYPE_64) { u32 mem_base_hi, mem_limit_hi; pci_read_config_dword(dev, PCI_PREF_BASE_UPPER32, &mem_base_hi); pci_read_config_dword(dev, PCI_PREF_LIMIT_UPPER32, &mem_limit_hi); /* * Some bridges set the base > limit by default, and some * (broken) BIOSes do not initialize them. If we find * this, just assume they are not being used. */ if (mem_base_hi <= mem_limit_hi) { base |= ((long) mem_base_hi) << 32; limit |= ((long) mem_limit_hi) << 32; } } res = bus->resource[2]; if (base <= limit) { res->flags = ((mem_base_lo & PCI_MEMORY_RANGE_TYPE_MASK) | IORESOURCE_MEM | IORESOURCE_PREFETCH); res->start = base; res->end = limit + 0xfffff; pci_resource_adjust(res, &pbm->mem_space); } } /* Cook up fake bus resources for SUNW,simba PCI bridges which lack * a proper 'ranges' property. */ static void __devinit apb_fake_ranges(struct pci_dev *dev, struct pci_bus *bus, struct pci_pbm_info *pbm) { struct resource *res; u32 first, last; u8 map; pci_read_config_byte(dev, APB_IO_ADDRESS_MAP, &map); apb_calc_first_last(map, &first, &last); res = bus->resource[0]; res->start = (first << 21); res->end = (last << 21) + ((1 << 21) - 1); res->flags = IORESOURCE_IO; pci_resource_adjust(res, &pbm->io_space); pci_read_config_byte(dev, APB_MEM_ADDRESS_MAP, &map); apb_calc_first_last(map, &first, &last); res = bus->resource[1]; res->start = (first << 21); res->end = (last << 21) + ((1 << 21) - 1); res->flags = IORESOURCE_MEM; pci_resource_adjust(res, &pbm->mem_space); } static void __devinit pci_of_scan_bus(struct pci_pbm_info *pbm, struct device_node *node, struct pci_bus *bus); #define GET_64BIT(prop, i) ((((u64) (prop)[(i)]) << 32) | (prop)[(i)+1]) static void __devinit of_scan_pci_bridge(struct pci_pbm_info *pbm, struct device_node *node, struct pci_dev *dev) { struct pci_bus *bus; const u32 *busrange, *ranges; int len, i, simba; struct resource *res; unsigned int flags; u64 size; if (ofpci_verbose) printk("of_scan_pci_bridge(%s)\n", node->full_name); /* parse bus-range property */ busrange = of_get_property(node, "bus-range", &len); if (busrange == NULL || len != 8) { printk(KERN_DEBUG "Can't get bus-range for PCI-PCI bridge %s\n", node->full_name); return; } ranges = of_get_property(node, "ranges", &len); simba = 0; if (ranges == NULL) { const char *model = of_get_property(node, "model", NULL); if (model && !strcmp(model, "SUNW,simba")) simba = 1; } bus = pci_add_new_bus(dev->bus, dev, busrange[0]); if (!bus) { printk(KERN_ERR "Failed to create pci bus for %s\n", node->full_name); return; } bus->primary = dev->bus->number; bus->subordinate = busrange[1]; bus->bridge_ctl = 0; /* parse ranges property, or cook one up by hand for Simba */ /* PCI #address-cells == 3 and #size-cells == 2 always */ res = &dev->resource[PCI_BRIDGE_RESOURCES]; for (i = 0; i < PCI_NUM_RESOURCES - PCI_BRIDGE_RESOURCES; ++i) { res->flags = 0; bus->resource[i] = res; ++res; } if (simba) { apb_fake_ranges(dev, bus, pbm); goto after_ranges; } else if (ranges == NULL) { pci_cfg_fake_ranges(dev, bus, pbm); goto after_ranges; } i = 1; for (; len >= 32; len -= 32, ranges += 8) { struct resource *root; flags = pci_parse_of_flags(ranges[0]); size = GET_64BIT(ranges, 6); if (flags == 0 || size == 0) continue; if (flags & IORESOURCE_IO) { res = bus->resource[0]; if (res->flags) { printk(KERN_ERR "PCI: ignoring extra I/O range" " for bridge %s\n", node->full_name); continue; } root = &pbm->io_space; } else { if (i >= PCI_NUM_RESOURCES - PCI_BRIDGE_RESOURCES) { printk(KERN_ERR "PCI: too many memory ranges" " for bridge %s\n", node->full_name); continue; } res = bus->resource[i]; ++i; root = &pbm->mem_space; } res->start = GET_64BIT(ranges, 1); res->end = res->start + size - 1; res->flags = flags; /* Another way to implement this would be to add an of_device * layer routine that can calculate a resource for a given * range property value in a PCI device. */ pci_resource_adjust(res, root); } after_ranges: sprintf(bus->name, "PCI Bus %04x:%02x", pci_domain_nr(bus), bus->number); if (ofpci_verbose) printk(" bus name: %s\n", bus->name); pci_of_scan_bus(pbm, node, bus); } static void __devinit pci_of_scan_bus(struct pci_pbm_info *pbm, struct device_node *node, struct pci_bus *bus) { struct device_node *child; const u32 *reg; int reglen, devfn, prev_devfn; struct pci_dev *dev; if (ofpci_verbose) printk("PCI: scan_bus[%s] bus no %d\n", node->full_name, bus->number); child = NULL; prev_devfn = -1; while ((child = of_get_next_child(node, child)) != NULL) { if (ofpci_verbose) printk(" * %s\n", child->full_name); reg = of_get_property(child, "reg", &reglen); if (reg == NULL || reglen < 20) continue; devfn = (reg[0] >> 8) & 0xff; /* This is a workaround for some device trees * which list PCI devices twice. On the V100 * for example, device number 3 is listed twice. * Once as "pm" and once again as "lomp". */ if (devfn == prev_devfn) continue; prev_devfn = devfn; /* create a new pci_dev for this device */ dev = of_create_pci_dev(pbm, child, bus, devfn); if (!dev) continue; if (ofpci_verbose) printk("PCI: dev header type: %x\n", dev->hdr_type); if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE || dev->hdr_type == PCI_HEADER_TYPE_CARDBUS) of_scan_pci_bridge(pbm, child, dev); } } static ssize_t show_pciobppath_attr(struct device * dev, struct device_attribute * attr, char * buf) { struct pci_dev *pdev; struct device_node *dp; pdev = to_pci_dev(dev); dp = pdev->dev.of_node; return snprintf (buf, PAGE_SIZE, "%s\n", dp->full_name); } static DEVICE_ATTR(obppath, S_IRUSR | S_IRGRP | S_IROTH, show_pciobppath_attr, NULL); static void __devinit pci_bus_register_of_sysfs(struct pci_bus *bus) { struct pci_dev *dev; struct pci_bus *child_bus; int err; list_for_each_entry(dev, &bus->devices, bus_list) { /* we don't really care if we can create this file or * not, but we need to assign the result of the call * or the world will fall under alien invasion and * everybody will be frozen on a spaceship ready to be * eaten on alpha centauri by some green and jelly * humanoid. */ err = sysfs_create_file(&dev->dev.kobj, &dev_attr_obppath.attr); (void) err; } list_for_each_entry(child_bus, &bus->children, node) pci_bus_register_of_sysfs(child_bus); } struct pci_bus * __devinit pci_scan_one_pbm(struct pci_pbm_info *pbm, struct device *parent) { struct device_node *node = pbm->op->dev.of_node; struct pci_bus *bus; printk("PCI: Scanning PBM %s\n", node->full_name); bus = pci_create_bus(parent, pbm->pci_first_busno, pbm->pci_ops, pbm); if (!bus) { printk(KERN_ERR "Failed to create bus for %s\n", node->full_name); return NULL; } bus->secondary = pbm->pci_first_busno; bus->subordinate = pbm->pci_last_busno; bus->resource[0] = &pbm->io_space; bus->resource[1] = &pbm->mem_space; pci_of_scan_bus(pbm, node, bus); pci_bus_add_devices(bus); pci_bus_register_of_sysfs(bus); return bus; } void __devinit pcibios_fixup_bus(struct pci_bus *pbus) { struct pci_pbm_info *pbm = pbus->sysdata; /* Generic PCI bus probing sets these to point at * &io{port,mem}_resouce which is wrong for us. */ pbus->resource[0] = &pbm->io_space; pbus->resource[1] = &pbm->mem_space; } void pcibios_update_irq(struct pci_dev *pdev, int irq) { } resource_size_t pcibios_align_resource(void *data, const struct resource *res, resource_size_t size, resource_size_t align) { return res->start; } int pcibios_enable_device(struct pci_dev *dev, int mask) { u16 cmd, oldcmd; int i; pci_read_config_word(dev, PCI_COMMAND, &cmd); oldcmd = cmd; for (i = 0; i < PCI_NUM_RESOURCES; i++) { struct resource *res = &dev->resource[i]; /* Only set up the requested stuff */ if (!(mask & (1<<i))) continue; if (res->flags & IORESOURCE_IO) cmd |= PCI_COMMAND_IO; if (res->flags & IORESOURCE_MEM) cmd |= PCI_COMMAND_MEMORY; } if (cmd != oldcmd) { printk(KERN_DEBUG "PCI: Enabling device: (%s), cmd %x\n", pci_name(dev), cmd); /* Enable the appropriate bits in the PCI command register. */ pci_write_config_word(dev, PCI_COMMAND, cmd); } return 0; } void pcibios_resource_to_bus(struct pci_dev *pdev, struct pci_bus_region *region, struct resource *res) { struct pci_pbm_info *pbm = pdev->bus->sysdata; struct resource zero_res, *root; zero_res.start = 0; zero_res.end = 0; zero_res.flags = res->flags; if (res->flags & IORESOURCE_IO) root = &pbm->io_space; else root = &pbm->mem_space; pci_resource_adjust(&zero_res, root); region->start = res->start - zero_res.start; region->end = res->end - zero_res.start; } EXPORT_SYMBOL(pcibios_resource_to_bus); void pcibios_bus_to_resource(struct pci_dev *pdev, struct resource *res, struct pci_bus_region *region) { struct pci_pbm_info *pbm = pdev->bus->sysdata; struct resource *root; res->start = region->start; res->end = region->end; if (res->flags & IORESOURCE_IO) root = &pbm->io_space; else root = &pbm->mem_space; pci_resource_adjust(res, root); } EXPORT_SYMBOL(pcibios_bus_to_resource); char * __devinit pcibios_setup(char *str) { return str; } /* Platform support for /proc/bus/pci/X/Y mmap()s. */ /* If the user uses a host-bridge as the PCI device, he may use * this to perform a raw mmap() of the I/O or MEM space behind * that controller. * * This can be useful for execution of x86 PCI bios initialization code * on a PCI card, like the xfree86 int10 stuff does. */ static int __pci_mmap_make_offset_bus(struct pci_dev *pdev, struct vm_area_struct *vma, enum pci_mmap_state mmap_state) { struct pci_pbm_info *pbm = pdev->dev.archdata.host_controller; unsigned long space_size, user_offset, user_size; if (mmap_state == pci_mmap_io) { space_size = (pbm->io_space.end - pbm->io_space.start) + 1; } else { space_size = (pbm->mem_space.end - pbm->mem_space.start) + 1; } /* Make sure the request is in range. */ user_offset = vma->vm_pgoff << PAGE_SHIFT; user_size = vma->vm_end - vma->vm_start; if (user_offset >= space_size || (user_offset + user_size) > space_size) return -EINVAL; if (mmap_state == pci_mmap_io) { vma->vm_pgoff = (pbm->io_space.start + user_offset) >> PAGE_SHIFT; } else { vma->vm_pgoff = (pbm->mem_space.start + user_offset) >> PAGE_SHIFT; } return 0; } /* Adjust vm_pgoff of VMA such that it is the physical page offset * corresponding to the 32-bit pci bus offset for DEV requested by the user. * * Basically, the user finds the base address for his device which he wishes * to mmap. They read the 32-bit value from the config space base register, * add whatever PAGE_SIZE multiple offset they wish, and feed this into the * offset parameter of mmap on /proc/bus/pci/XXX for that device. * * Returns negative error code on failure, zero on success. */ static int __pci_mmap_make_offset(struct pci_dev *pdev, struct vm_area_struct *vma, enum pci_mmap_state mmap_state) { unsigned long user_paddr, user_size; int i, err; /* First compute the physical address in vma->vm_pgoff, * making sure the user offset is within range in the * appropriate PCI space. */ err = __pci_mmap_make_offset_bus(pdev, vma, mmap_state); if (err) return err; /* If this is a mapping on a host bridge, any address * is OK. */ if ((pdev->class >> 8) == PCI_CLASS_BRIDGE_HOST) return err; /* Otherwise make sure it's in the range for one of the * device's resources. */ user_paddr = vma->vm_pgoff << PAGE_SHIFT; user_size = vma->vm_end - vma->vm_start; for (i = 0; i <= PCI_ROM_RESOURCE; i++) { struct resource *rp = &pdev->resource[i]; resource_size_t aligned_end; /* Active? */ if (!rp->flags) continue; /* Same type? */ if (i == PCI_ROM_RESOURCE) { if (mmap_state != pci_mmap_mem) continue; } else { if ((mmap_state == pci_mmap_io && (rp->flags & IORESOURCE_IO) == 0) || (mmap_state == pci_mmap_mem && (rp->flags & IORESOURCE_MEM) == 0)) continue; } /* Align the resource end to the next page address. * PAGE_SIZE intentionally added instead of (PAGE_SIZE - 1), * because actually we need the address of the next byte * after rp->end. */ aligned_end = (rp->end + PAGE_SIZE) & PAGE_MASK; if ((rp->start <= user_paddr) && (user_paddr + user_size) <= aligned_end) break; } if (i > PCI_ROM_RESOURCE) return -EINVAL; return 0; } /* Set vm_flags of VMA, as appropriate for this architecture, for a pci device * mapping. */ static void __pci_mmap_set_flags(struct pci_dev *dev, struct vm_area_struct *vma, enum pci_mmap_state mmap_state) { vma->vm_flags |= (VM_IO | VM_RESERVED); } /* Set vm_page_prot of VMA, as appropriate for this architecture, for a pci * device mapping. */ static void __pci_mmap_set_pgprot(struct pci_dev *dev, struct vm_area_struct *vma, enum pci_mmap_state mmap_state) { /* Our io_remap_pfn_range takes care of this, do nothing. */ } /* Perform the actual remap of the pages for a PCI device mapping, as appropriate * for this architecture. The region in the process to map is described by vm_start * and vm_end members of VMA, the base physical address is found in vm_pgoff. * The pci device structure is provided so that architectures may make mapping * decisions on a per-device or per-bus basis. * * Returns a negative error code on failure, zero on success. */ int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma, enum pci_mmap_state mmap_state, int write_combine) { int ret; ret = __pci_mmap_make_offset(dev, vma, mmap_state); if (ret < 0) return ret; __pci_mmap_set_flags(dev, vma, mmap_state); __pci_mmap_set_pgprot(dev, vma, mmap_state); vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); ret = io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, vma->vm_end - vma->vm_start, vma->vm_page_prot); if (ret) return ret; return 0; } #ifdef CONFIG_NUMA int pcibus_to_node(struct pci_bus *pbus) { struct pci_pbm_info *pbm = pbus->sysdata; return pbm->numa_node; } EXPORT_SYMBOL(pcibus_to_node); #endif /* Return the domain number for this pci bus */ int pci_domain_nr(struct pci_bus *pbus) { struct pci_pbm_info *pbm = pbus->sysdata; int ret; if (!pbm) { ret = -ENXIO; } else { ret = pbm->index; } return ret; } EXPORT_SYMBOL(pci_domain_nr); #ifdef CONFIG_PCI_MSI int arch_setup_msi_irq(struct pci_dev *pdev, struct msi_desc *desc) { struct pci_pbm_info *pbm = pdev->dev.archdata.host_controller; unsigned int irq; if (!pbm->setup_msi_irq) return -EINVAL; return pbm->setup_msi_irq(&irq, pdev, desc); } void arch_teardown_msi_irq(unsigned int irq) { struct msi_desc *entry = irq_get_msi_desc(irq); struct pci_dev *pdev = entry->dev; struct pci_pbm_info *pbm = pdev->dev.archdata.host_controller; if (pbm->teardown_msi_irq) pbm->teardown_msi_irq(irq, pdev); } #endif /* !(CONFIG_PCI_MSI) */ struct device_node *pci_device_to_OF_node(struct pci_dev *pdev) { return pdev->dev.of_node; } EXPORT_SYMBOL(pci_device_to_OF_node); static void ali_sound_dma_hack(struct pci_dev *pdev, int set_bit) { struct pci_dev *ali_isa_bridge; u8 val; /* ALI sound chips generate 31-bits of DMA, a special register * determines what bit 31 is emitted as. */ ali_isa_bridge = pci_get_device(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, NULL); pci_read_config_byte(ali_isa_bridge, 0x7e, &val); if (set_bit) val |= 0x01; else val &= ~0x01; pci_write_config_byte(ali_isa_bridge, 0x7e, val); pci_dev_put(ali_isa_bridge); } int pci64_dma_supported(struct pci_dev *pdev, u64 device_mask) { u64 dma_addr_mask; if (pdev == NULL) { dma_addr_mask = 0xffffffff; } else { struct iommu *iommu = pdev->dev.archdata.iommu; dma_addr_mask = iommu->dma_addr_mask; if (pdev->vendor == PCI_VENDOR_ID_AL && pdev->device == PCI_DEVICE_ID_AL_M5451 && device_mask == 0x7fffffff) { ali_sound_dma_hack(pdev, (dma_addr_mask & 0x80000000) != 0); return 1; } } if (device_mask >= (1UL << 32UL)) return 0; return (device_mask & dma_addr_mask) == dma_addr_mask; } void pci_resource_to_user(const struct pci_dev *pdev, int bar, const struct resource *rp, resource_size_t *start, resource_size_t *end) { struct pci_pbm_info *pbm = pdev->dev.archdata.host_controller; unsigned long offset; if (rp->flags & IORESOURCE_IO) offset = pbm->io_space.start; else offset = pbm->mem_space.start; *start = rp->start - offset; *end = rp->end - offset; } static int __init pcibios_init(void) { pci_dfl_cache_line_size = 64 >> 2; return 0; } subsys_initcall(pcibios_init); #ifdef CONFIG_SYSFS static void __devinit pci_bus_slot_names(struct device_node *node, struct pci_bus *bus) { const struct pci_slot_names { u32 slot_mask; char names[0]; } *prop; const char *sp; int len, i; u32 mask; prop = of_get_property(node, "slot-names", &len); if (!prop) return; mask = prop->slot_mask; sp = prop->names; if (ofpci_verbose) printk("PCI: Making slots for [%s] mask[0x%02x]\n", node->full_name, mask); i = 0; while (mask) { struct pci_slot *pci_slot; u32 this_bit = 1 << i; if (!(mask & this_bit)) { i++; continue; } if (ofpci_verbose) printk("PCI: Making slot [%s]\n", sp); pci_slot = pci_create_slot(bus, i, sp, NULL); if (IS_ERR(pci_slot)) printk(KERN_ERR "PCI: pci_create_slot returned %ld\n", PTR_ERR(pci_slot)); sp += strlen(sp) + 1; mask &= ~this_bit; i++; } } static int __init of_pci_slot_init(void) { struct pci_bus *pbus = NULL; while ((pbus = pci_find_next_bus(pbus)) != NULL) { struct device_node *node; if (pbus->self) { /* PCI->PCI bridge */ node = pbus->self->dev.of_node; } else { struct pci_pbm_info *pbm = pbus->sysdata; /* Host PCI controller */ node = pbm->op->dev.of_node; } pci_bus_slot_names(node, pbus); } return 0; } module_init(of_pci_slot_init); #endif
gpl-2.0
maxwen/enrc2b-kernel-BLADE
arch/powerpc/platforms/cell/setup.c
2585
7003
/* * linux/arch/powerpc/platforms/cell/cell_setup.c * * Copyright (C) 1995 Linus Torvalds * Adapted from 'alpha' version by Gary Thomas * Modified by Cort Dougan (cort@cs.nmt.edu) * Modified by PPC64 Team, IBM Corp * Modified by Cell Team, IBM Deutschland Entwicklung GmbH * * 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. */ #undef DEBUG #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/user.h> #include <linux/reboot.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/seq_file.h> #include <linux/root_dev.h> #include <linux/console.h> #include <linux/mutex.h> #include <linux/memory_hotplug.h> #include <linux/of_platform.h> #include <asm/mmu.h> #include <asm/processor.h> #include <asm/io.h> #include <asm/pgtable.h> #include <asm/prom.h> #include <asm/rtas.h> #include <asm/pci-bridge.h> #include <asm/iommu.h> #include <asm/dma.h> #include <asm/machdep.h> #include <asm/time.h> #include <asm/nvram.h> #include <asm/cputable.h> #include <asm/ppc-pci.h> #include <asm/irq.h> #include <asm/spu.h> #include <asm/spu_priv1.h> #include <asm/udbg.h> #include <asm/mpic.h> #include <asm/cell-regs.h> #include <asm/io-workarounds.h> #include "interrupt.h" #include "pervasive.h" #include "ras.h" #ifdef DEBUG #define DBG(fmt...) udbg_printf(fmt) #else #define DBG(fmt...) #endif static void cell_show_cpuinfo(struct seq_file *m) { struct device_node *root; const char *model = ""; root = of_find_node_by_path("/"); if (root) model = of_get_property(root, "model", NULL); seq_printf(m, "machine\t\t: CHRP %s\n", model); of_node_put(root); } static void cell_progress(char *s, unsigned short hex) { printk("*** %04x : %s\n", hex, s ? s : ""); } static void cell_fixup_pcie_rootcomplex(struct pci_dev *dev) { struct pci_controller *hose; const char *s; int i; if (!machine_is(cell)) return; /* We're searching for a direct child of the PHB */ if (dev->bus->self != NULL || dev->devfn != 0) return; hose = pci_bus_to_host(dev->bus); if (hose == NULL) return; /* Only on PCIE */ if (!of_device_is_compatible(hose->dn, "pciex")) return; /* And only on axon */ s = of_get_property(hose->dn, "model", NULL); if (!s || strcmp(s, "Axon") != 0) return; for (i = 0; i < PCI_BRIDGE_RESOURCES; i++) { dev->resource[i].start = dev->resource[i].end = 0; dev->resource[i].flags = 0; } printk(KERN_DEBUG "PCI: Hiding resources on Axon PCIE RC %s\n", pci_name(dev)); } DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, cell_fixup_pcie_rootcomplex); static int __devinit cell_setup_phb(struct pci_controller *phb) { const char *model; struct device_node *np; int rc = rtas_setup_phb(phb); if (rc) return rc; np = phb->dn; model = of_get_property(np, "model", NULL); if (model == NULL || strcmp(np->name, "pci")) return 0; /* Setup workarounds for spider */ if (strcmp(model, "Spider")) return 0; iowa_register_bus(phb, &spiderpci_ops, &spiderpci_iowa_init, (void *)SPIDER_PCI_REG_BASE); return 0; } static const struct of_device_id cell_bus_ids[] __initdata = { { .type = "soc", }, { .compatible = "soc", }, { .type = "spider", }, { .type = "axon", }, { .type = "plb5", }, { .type = "plb4", }, { .type = "opb", }, { .type = "ebc", }, {}, }; static int __init cell_publish_devices(void) { struct device_node *root = of_find_node_by_path("/"); struct device_node *np; int node; /* Publish OF platform devices for southbridge IOs */ of_platform_bus_probe(NULL, cell_bus_ids, NULL); /* On spider based blades, we need to manually create the OF * platform devices for the PCI host bridges */ for_each_child_of_node(root, np) { if (np->type == NULL || (strcmp(np->type, "pci") != 0 && strcmp(np->type, "pciex") != 0)) continue; of_platform_device_create(np, NULL, NULL); } /* There is no device for the MIC memory controller, thus we create * a platform device for it to attach the EDAC driver to. */ for_each_online_node(node) { if (cbe_get_cpu_mic_tm_regs(cbe_node_to_cpu(node)) == NULL) continue; platform_device_register_simple("cbe-mic", node, NULL, 0); } return 0; } machine_subsys_initcall(cell, cell_publish_devices); static void cell_mpic_cascade(unsigned int irq, struct irq_desc *desc) { struct irq_chip *chip = irq_desc_get_chip(desc); struct mpic *mpic = irq_desc_get_handler_data(desc); unsigned int virq; virq = mpic_get_one_irq(mpic); if (virq != NO_IRQ) generic_handle_irq(virq); chip->irq_eoi(&desc->irq_data); } static void __init mpic_init_IRQ(void) { struct device_node *dn; struct mpic *mpic; unsigned int virq; for (dn = NULL; (dn = of_find_node_by_name(dn, "interrupt-controller"));) { if (!of_device_is_compatible(dn, "CBEA,platform-open-pic")) continue; /* The MPIC driver will get everything it needs from the * device-tree, just pass 0 to all arguments */ mpic = mpic_alloc(dn, 0, 0, 0, 0, " MPIC "); if (mpic == NULL) continue; mpic_init(mpic); virq = irq_of_parse_and_map(dn, 0); if (virq == NO_IRQ) continue; printk(KERN_INFO "%s : hooking up to IRQ %d\n", dn->full_name, virq); irq_set_handler_data(virq, mpic); irq_set_chained_handler(virq, cell_mpic_cascade); } } static void __init cell_init_irq(void) { iic_init_IRQ(); spider_init_IRQ(); mpic_init_IRQ(); } static void __init cell_set_dabrx(void) { mtspr(SPRN_DABRX, DABRX_KERNEL | DABRX_USER); } static void __init cell_setup_arch(void) { #ifdef CONFIG_SPU_BASE spu_priv1_ops = &spu_priv1_mmio_ops; spu_management_ops = &spu_management_of_ops; #endif cbe_regs_init(); cell_set_dabrx(); #ifdef CONFIG_CBE_RAS cbe_ras_init(); #endif #ifdef CONFIG_SMP smp_init_cell(); #endif /* init to some ~sane value until calibrate_delay() runs */ loops_per_jiffy = 50000000; /* Find and initialize PCI host bridges */ init_pci_config_tokens(); cbe_pervasive_init(); #ifdef CONFIG_DUMMY_CONSOLE conswitchp = &dummy_con; #endif mmio_nvram_init(); } static int __init cell_probe(void) { unsigned long root = of_get_flat_dt_root(); if (!of_flat_dt_is_compatible(root, "IBM,CBEA") && !of_flat_dt_is_compatible(root, "IBM,CPBW-1.0")) return 0; hpte_init_native(); return 1; } define_machine(cell) { .name = "Cell", .probe = cell_probe, .setup_arch = cell_setup_arch, .show_cpuinfo = cell_show_cpuinfo, .restart = rtas_restart, .power_off = rtas_power_off, .halt = rtas_halt, .get_boot_time = rtas_get_boot_time, .get_rtc_time = rtas_get_rtc_time, .set_rtc_time = rtas_set_rtc_time, .calibrate_decr = generic_calibrate_decr, .progress = cell_progress, .init_IRQ = cell_init_irq, .pci_setup_phb = cell_setup_phb, };
gpl-2.0
aquarism5-dev/android_kernel_bq_piccolo
drivers/input/touchscreen/ad7879-i2c.c
3865
2419
/* * AD7879-1/AD7889-1 touchscreen (I2C bus) * * Copyright (C) 2008-2010 Michael Hennerich, Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #include <linux/input.h> /* BUS_I2C */ #include <linux/i2c.h> #include <linux/module.h> #include <linux/types.h> #include <linux/pm.h> #include "ad7879.h" #define AD7879_DEVID 0x79 /* AD7879-1/AD7889-1 */ /* All registers are word-sized. * AD7879 uses a high-byte first convention. */ static int ad7879_i2c_read(struct device *dev, u8 reg) { struct i2c_client *client = to_i2c_client(dev); return i2c_smbus_read_word_swapped(client, reg); } static int ad7879_i2c_multi_read(struct device *dev, u8 first_reg, u8 count, u16 *buf) { struct i2c_client *client = to_i2c_client(dev); u8 idx; i2c_smbus_read_i2c_block_data(client, first_reg, count * 2, (u8 *)buf); for (idx = 0; idx < count; ++idx) buf[idx] = swab16(buf[idx]); return 0; } static int ad7879_i2c_write(struct device *dev, u8 reg, u16 val) { struct i2c_client *client = to_i2c_client(dev); return i2c_smbus_write_word_swapped(client, reg, val); } static const struct ad7879_bus_ops ad7879_i2c_bus_ops = { .bustype = BUS_I2C, .read = ad7879_i2c_read, .multi_read = ad7879_i2c_multi_read, .write = ad7879_i2c_write, }; static int ad7879_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct ad7879 *ts; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WORD_DATA)) { dev_err(&client->dev, "SMBUS Word Data not Supported\n"); return -EIO; } ts = ad7879_probe(&client->dev, AD7879_DEVID, client->irq, &ad7879_i2c_bus_ops); if (IS_ERR(ts)) return PTR_ERR(ts); i2c_set_clientdata(client, ts); return 0; } static int ad7879_i2c_remove(struct i2c_client *client) { struct ad7879 *ts = i2c_get_clientdata(client); ad7879_remove(ts); return 0; } static const struct i2c_device_id ad7879_id[] = { { "ad7879", 0 }, { "ad7889", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ad7879_id); static struct i2c_driver ad7879_i2c_driver = { .driver = { .name = "ad7879", .owner = THIS_MODULE, .pm = &ad7879_pm_ops, }, .probe = ad7879_i2c_probe, .remove = ad7879_i2c_remove, .id_table = ad7879_id, }; module_i2c_driver(ad7879_i2c_driver); MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>"); MODULE_DESCRIPTION("AD7879(-1) touchscreen I2C bus driver"); MODULE_LICENSE("GPL");
gpl-2.0
Tasssadar/kernel_nexus
drivers/net/tokenring/skisa.c
4889
9833
/* * skisa.c: A network driver for SK-NET TMS380-based ISA token ring cards. * * Based on tmspci written 1999 by Adam Fritzler * * Written 2000 by Jochen Friedrich * Dedicated to my girlfriend Steffi Bopp * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * This driver module supports the following cards: * - SysKonnect TR4/16(+) ISA (SK-4190) * * Maintainer(s): * AF Adam Fritzler * JF Jochen Friedrich jochen@scram.de * * Modification History: * 14-Jan-01 JF Created * 28-Oct-02 JF Fixed probe of card for static compilation. * Fixed module init to not make hotplug go wild. * 09-Nov-02 JF Fixed early bail out on out of memory * situations if multiple cards are found. * Cleaned up some unnecessary console SPAM. * 09-Dec-02 JF Fixed module reference counting. * 02-Jan-03 JF Renamed to skisa.c * */ static const char version[] = "skisa.c: v1.03 09/12/2002 by Jochen Friedrich\n"; #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/trdevice.h> #include <linux/platform_device.h> #include <asm/system.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/pci.h> #include <asm/dma.h> #include "tms380tr.h" #define SK_ISA_IO_EXTENT 32 /* A zero-terminated list of I/O addresses to be probed. */ static unsigned int portlist[] __initdata = { 0x0A20, 0x1A20, 0x0B20, 0x1B20, 0x0980, 0x1980, 0x0900, 0x1900,// SK 0 }; /* A zero-terminated list of IRQs to be probed. * Used again after initial probe for sktr_chipset_init, called from sktr_open. */ static const unsigned short irqlist[] = { 3, 5, 9, 10, 11, 12, 15, 0 }; /* A zero-terminated list of DMAs to be probed. */ static int dmalist[] __initdata = { 5, 6, 7, 0 }; static char isa_cardname[] = "SK NET TR 4/16 ISA\0"; static u64 dma_mask = ISA_MAX_ADDRESS; static int sk_isa_open(struct net_device *dev); static void sk_isa_read_eeprom(struct net_device *dev); static unsigned short sk_isa_setnselout_pins(struct net_device *dev); static unsigned short sk_isa_sifreadb(struct net_device *dev, unsigned short reg) { return inb(dev->base_addr + reg); } static unsigned short sk_isa_sifreadw(struct net_device *dev, unsigned short reg) { return inw(dev->base_addr + reg); } static void sk_isa_sifwriteb(struct net_device *dev, unsigned short val, unsigned short reg) { outb(val, dev->base_addr + reg); } static void sk_isa_sifwritew(struct net_device *dev, unsigned short val, unsigned short reg) { outw(val, dev->base_addr + reg); } static int __init sk_isa_probe1(struct net_device *dev, int ioaddr) { unsigned char old, chk1, chk2; if (!request_region(ioaddr, SK_ISA_IO_EXTENT, isa_cardname)) return -ENODEV; old = inb(ioaddr + SIFADR); /* Get the old SIFADR value */ chk1 = 0; /* Begin with check value 0 */ do { /* Write new SIFADR value */ outb(chk1, ioaddr + SIFADR); /* Read, invert and write */ chk2 = inb(ioaddr + SIFADD); chk2 ^= 0x0FE; outb(chk2, ioaddr + SIFADR); /* Read, invert and compare */ chk2 = inb(ioaddr + SIFADD); chk2 ^= 0x0FE; if(chk1 != chk2) { release_region(ioaddr, SK_ISA_IO_EXTENT); return -ENODEV; } chk1 -= 2; } while(chk1 != 0); /* Repeat 128 times (all byte values) */ /* Restore the SIFADR value */ outb(old, ioaddr + SIFADR); dev->base_addr = ioaddr; return 0; } static struct net_device_ops sk_isa_netdev_ops __read_mostly; static int __init setup_card(struct net_device *dev, struct device *pdev) { struct net_local *tp; static int versionprinted; const unsigned *port; int j, err = 0; if (!dev) return -ENOMEM; if (dev->base_addr) /* probe specific location */ err = sk_isa_probe1(dev, dev->base_addr); else { for (port = portlist; *port; port++) { err = sk_isa_probe1(dev, *port); if (!err) break; } } if (err) goto out5; /* At this point we have found a valid card. */ if (versionprinted++ == 0) printk(KERN_DEBUG "%s", version); err = -EIO; pdev->dma_mask = &dma_mask; if (tmsdev_init(dev, pdev)) goto out4; dev->base_addr &= ~3; sk_isa_read_eeprom(dev); printk(KERN_DEBUG "skisa.c: Ring Station Address: %pM\n", dev->dev_addr); tp = netdev_priv(dev); tp->setnselout = sk_isa_setnselout_pins; tp->sifreadb = sk_isa_sifreadb; tp->sifreadw = sk_isa_sifreadw; tp->sifwriteb = sk_isa_sifwriteb; tp->sifwritew = sk_isa_sifwritew; memcpy(tp->ProductID, isa_cardname, PROD_ID_SIZE + 1); tp->tmspriv = NULL; dev->netdev_ops = &sk_isa_netdev_ops; if (dev->irq == 0) { for(j = 0; irqlist[j] != 0; j++) { dev->irq = irqlist[j]; if (!request_irq(dev->irq, tms380tr_interrupt, 0, isa_cardname, dev)) break; } if(irqlist[j] == 0) { printk(KERN_INFO "skisa.c: AutoSelect no IRQ available\n"); goto out3; } } else { for(j = 0; irqlist[j] != 0; j++) if (irqlist[j] == dev->irq) break; if (irqlist[j] == 0) { printk(KERN_INFO "skisa.c: Illegal IRQ %d specified\n", dev->irq); goto out3; } if (request_irq(dev->irq, tms380tr_interrupt, 0, isa_cardname, dev)) { printk(KERN_INFO "skisa.c: Selected IRQ %d not available\n", dev->irq); goto out3; } } if (dev->dma == 0) { for(j = 0; dmalist[j] != 0; j++) { dev->dma = dmalist[j]; if (!request_dma(dev->dma, isa_cardname)) break; } if(dmalist[j] == 0) { printk(KERN_INFO "skisa.c: AutoSelect no DMA available\n"); goto out2; } } else { for(j = 0; dmalist[j] != 0; j++) if (dmalist[j] == dev->dma) break; if (dmalist[j] == 0) { printk(KERN_INFO "skisa.c: Illegal DMA %d specified\n", dev->dma); goto out2; } if (request_dma(dev->dma, isa_cardname)) { printk(KERN_INFO "skisa.c: Selected DMA %d not available\n", dev->dma); goto out2; } } err = register_netdev(dev); if (err) goto out; printk(KERN_DEBUG "%s: IO: %#4lx IRQ: %d DMA: %d\n", dev->name, dev->base_addr, dev->irq, dev->dma); return 0; out: free_dma(dev->dma); out2: free_irq(dev->irq, dev); out3: tmsdev_term(dev); out4: release_region(dev->base_addr, SK_ISA_IO_EXTENT); out5: return err; } /* * Reads MAC address from adapter RAM, which should've read it from * the onboard ROM. * * Calling this on a board that does not support it can be a very * dangerous thing. The Madge board, for instance, will lock your * machine hard when this is called. Luckily, its supported in a * separate driver. --ASF */ static void sk_isa_read_eeprom(struct net_device *dev) { int i; /* Address: 0000:0000 */ sk_isa_sifwritew(dev, 0, SIFADX); sk_isa_sifwritew(dev, 0, SIFADR); /* Read six byte MAC address data */ dev->addr_len = 6; for(i = 0; i < 6; i++) dev->dev_addr[i] = sk_isa_sifreadw(dev, SIFINC) >> 8; } static unsigned short sk_isa_setnselout_pins(struct net_device *dev) { return 0; } static int sk_isa_open(struct net_device *dev) { struct net_local *tp = netdev_priv(dev); unsigned short val = 0; unsigned short oldval; int i; val = 0; for(i = 0; irqlist[i] != 0; i++) { if(irqlist[i] == dev->irq) break; } val |= CYCLE_TIME << 2; val |= i << 4; i = dev->dma - 5; val |= i; if(tp->DataRate == SPEED_4) val |= LINE_SPEED_BIT; else val &= ~LINE_SPEED_BIT; oldval = sk_isa_sifreadb(dev, POSREG); /* Leave cycle bits alone */ oldval |= 0xf3; val &= oldval; sk_isa_sifwriteb(dev, val, POSREG); return tms380tr_open(dev); } #define ISATR_MAX_ADAPTERS 3 static int io[ISATR_MAX_ADAPTERS]; static int irq[ISATR_MAX_ADAPTERS]; static int dma[ISATR_MAX_ADAPTERS]; MODULE_LICENSE("GPL"); module_param_array(io, int, NULL, 0); module_param_array(irq, int, NULL, 0); module_param_array(dma, int, NULL, 0); static struct platform_device *sk_isa_dev[ISATR_MAX_ADAPTERS]; static struct platform_driver sk_isa_driver = { .driver = { .name = "skisa", }, }; static int __init sk_isa_init(void) { struct net_device *dev; struct platform_device *pdev; int i, num = 0, err = 0; sk_isa_netdev_ops = tms380tr_netdev_ops; sk_isa_netdev_ops.ndo_open = sk_isa_open; sk_isa_netdev_ops.ndo_stop = tms380tr_close; err = platform_driver_register(&sk_isa_driver); if (err) return err; for (i = 0; i < ISATR_MAX_ADAPTERS ; i++) { dev = alloc_trdev(sizeof(struct net_local)); if (!dev) continue; dev->base_addr = io[i]; dev->irq = irq[i]; dev->dma = dma[i]; pdev = platform_device_register_simple("skisa", i, NULL, 0); if (IS_ERR(pdev)) { free_netdev(dev); continue; } err = setup_card(dev, &pdev->dev); if (!err) { sk_isa_dev[i] = pdev; platform_set_drvdata(sk_isa_dev[i], dev); ++num; } else { platform_device_unregister(pdev); free_netdev(dev); } } printk(KERN_NOTICE "skisa.c: %d cards found.\n", num); /* Probe for cards. */ if (num == 0) { printk(KERN_NOTICE "skisa.c: No cards found.\n"); platform_driver_unregister(&sk_isa_driver); return -ENODEV; } return 0; } static void __exit sk_isa_cleanup(void) { struct net_device *dev; int i; for (i = 0; i < ISATR_MAX_ADAPTERS ; i++) { struct platform_device *pdev = sk_isa_dev[i]; if (!pdev) continue; dev = platform_get_drvdata(pdev); unregister_netdev(dev); release_region(dev->base_addr, SK_ISA_IO_EXTENT); free_irq(dev->irq, dev); free_dma(dev->dma); tmsdev_term(dev); free_netdev(dev); platform_set_drvdata(pdev, NULL); platform_device_unregister(pdev); } platform_driver_unregister(&sk_isa_driver); } module_init(sk_isa_init); module_exit(sk_isa_cleanup);
gpl-2.0
MyAOSP/kernel_htc_m7
drivers/i2c/busses/i2c-ixp2000.c
4889
4165
/* * drivers/i2c/busses/i2c-ixp2000.c * * I2C adapter for IXP2000 systems using GPIOs for I2C bus * * Author: Deepak Saxena <dsaxena@plexity.net> * Based on IXDP2400 code by: Naeem M. Afzal <naeem.m.afzal@intel.com> * Made generic by: Jeff Daly <jeffrey.daly@intel.com> * * Copyright (c) 2003-2004 MontaVista Software Inc. * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. * * From Jeff Daly: * * I2C adapter driver for Intel IXDP2xxx platforms. This should work for any * IXP2000 platform if it uses the HW GPIO in the same manner. Basically, * SDA and SCL GPIOs have external pullups. Setting the respective GPIO to * an input will make the signal a '1' via the pullup. Setting them to * outputs will pull them down. * * The GPIOs are open drain signals and are used as configuration strap inputs * during power-up so there's generally a buffer on the board that needs to be * 'enabled' to drive the GPIOs. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/i2c-algo-bit.h> #include <linux/slab.h> #include <mach/hardware.h> /* Pick up IXP2000-specific bits */ #include <mach/gpio-ixp2000.h> static inline int ixp2000_scl_pin(void *data) { return ((struct ixp2000_i2c_pins*)data)->scl_pin; } static inline int ixp2000_sda_pin(void *data) { return ((struct ixp2000_i2c_pins*)data)->sda_pin; } static void ixp2000_bit_setscl(void *data, int val) { int i = 5000; if (val) { gpio_line_config(ixp2000_scl_pin(data), GPIO_IN); while(!gpio_line_get(ixp2000_scl_pin(data)) && i--); } else { gpio_line_config(ixp2000_scl_pin(data), GPIO_OUT); } } static void ixp2000_bit_setsda(void *data, int val) { if (val) { gpio_line_config(ixp2000_sda_pin(data), GPIO_IN); } else { gpio_line_config(ixp2000_sda_pin(data), GPIO_OUT); } } static int ixp2000_bit_getscl(void *data) { return gpio_line_get(ixp2000_scl_pin(data)); } static int ixp2000_bit_getsda(void *data) { return gpio_line_get(ixp2000_sda_pin(data)); } struct ixp2000_i2c_data { struct ixp2000_i2c_pins *gpio_pins; struct i2c_adapter adapter; struct i2c_algo_bit_data algo_data; }; static int ixp2000_i2c_remove(struct platform_device *plat_dev) { struct ixp2000_i2c_data *drv_data = platform_get_drvdata(plat_dev); platform_set_drvdata(plat_dev, NULL); i2c_del_adapter(&drv_data->adapter); kfree(drv_data); return 0; } static int ixp2000_i2c_probe(struct platform_device *plat_dev) { int err; struct ixp2000_i2c_pins *gpio = plat_dev->dev.platform_data; struct ixp2000_i2c_data *drv_data = kzalloc(sizeof(struct ixp2000_i2c_data), GFP_KERNEL); if (!drv_data) return -ENOMEM; drv_data->gpio_pins = gpio; drv_data->algo_data.data = gpio; drv_data->algo_data.setsda = ixp2000_bit_setsda; drv_data->algo_data.setscl = ixp2000_bit_setscl; drv_data->algo_data.getsda = ixp2000_bit_getsda; drv_data->algo_data.getscl = ixp2000_bit_getscl; drv_data->algo_data.udelay = 6; drv_data->algo_data.timeout = HZ; strlcpy(drv_data->adapter.name, plat_dev->dev.driver->name, sizeof(drv_data->adapter.name)); drv_data->adapter.algo_data = &drv_data->algo_data, drv_data->adapter.dev.parent = &plat_dev->dev; gpio_line_config(gpio->sda_pin, GPIO_IN); gpio_line_config(gpio->scl_pin, GPIO_IN); gpio_line_set(gpio->scl_pin, 0); gpio_line_set(gpio->sda_pin, 0); if ((err = i2c_bit_add_bus(&drv_data->adapter)) != 0) { dev_err(&plat_dev->dev, "Could not install, error %d\n", err); kfree(drv_data); return err; } platform_set_drvdata(plat_dev, drv_data); return 0; } static struct platform_driver ixp2000_i2c_driver = { .probe = ixp2000_i2c_probe, .remove = ixp2000_i2c_remove, .driver = { .name = "IXP2000-I2C", .owner = THIS_MODULE, }, }; module_platform_driver(ixp2000_i2c_driver); MODULE_AUTHOR ("Deepak Saxena <dsaxena@plexity.net>"); MODULE_DESCRIPTION("IXP2000 GPIO-based I2C bus driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:IXP2000-I2C");
gpl-2.0
omega-roms/N7100_Stock_Kernel_JB_4.3
drivers/gpu/drm/r128/r128_cce.c
5657
24244
/* r128_cce.c -- ATI Rage 128 driver -*- linux-c -*- * Created: Wed Apr 5 19:24:19 2000 by kevin@precisioninsight.com */ /* * Copyright 2000 Precision Insight, Inc., Cedar Park, Texas. * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: * Gareth Hughes <gareth@valinux.com> */ #include <linux/firmware.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/module.h> #include "drmP.h" #include "drm.h" #include "r128_drm.h" #include "r128_drv.h" #define R128_FIFO_DEBUG 0 #define FIRMWARE_NAME "r128/r128_cce.bin" MODULE_FIRMWARE(FIRMWARE_NAME); static int R128_READ_PLL(struct drm_device *dev, int addr) { drm_r128_private_t *dev_priv = dev->dev_private; R128_WRITE8(R128_CLOCK_CNTL_INDEX, addr & 0x1f); return R128_READ(R128_CLOCK_CNTL_DATA); } #if R128_FIFO_DEBUG static void r128_status(drm_r128_private_t *dev_priv) { printk("GUI_STAT = 0x%08x\n", (unsigned int)R128_READ(R128_GUI_STAT)); printk("PM4_STAT = 0x%08x\n", (unsigned int)R128_READ(R128_PM4_STAT)); printk("PM4_BUFFER_DL_WPTR = 0x%08x\n", (unsigned int)R128_READ(R128_PM4_BUFFER_DL_WPTR)); printk("PM4_BUFFER_DL_RPTR = 0x%08x\n", (unsigned int)R128_READ(R128_PM4_BUFFER_DL_RPTR)); printk("PM4_MICRO_CNTL = 0x%08x\n", (unsigned int)R128_READ(R128_PM4_MICRO_CNTL)); printk("PM4_BUFFER_CNTL = 0x%08x\n", (unsigned int)R128_READ(R128_PM4_BUFFER_CNTL)); } #endif /* ================================================================ * Engine, FIFO control */ static int r128_do_pixcache_flush(drm_r128_private_t *dev_priv) { u32 tmp; int i; tmp = R128_READ(R128_PC_NGUI_CTLSTAT) | R128_PC_FLUSH_ALL; R128_WRITE(R128_PC_NGUI_CTLSTAT, tmp); for (i = 0; i < dev_priv->usec_timeout; i++) { if (!(R128_READ(R128_PC_NGUI_CTLSTAT) & R128_PC_BUSY)) return 0; DRM_UDELAY(1); } #if R128_FIFO_DEBUG DRM_ERROR("failed!\n"); #endif return -EBUSY; } static int r128_do_wait_for_fifo(drm_r128_private_t *dev_priv, int entries) { int i; for (i = 0; i < dev_priv->usec_timeout; i++) { int slots = R128_READ(R128_GUI_STAT) & R128_GUI_FIFOCNT_MASK; if (slots >= entries) return 0; DRM_UDELAY(1); } #if R128_FIFO_DEBUG DRM_ERROR("failed!\n"); #endif return -EBUSY; } static int r128_do_wait_for_idle(drm_r128_private_t *dev_priv) { int i, ret; ret = r128_do_wait_for_fifo(dev_priv, 64); if (ret) return ret; for (i = 0; i < dev_priv->usec_timeout; i++) { if (!(R128_READ(R128_GUI_STAT) & R128_GUI_ACTIVE)) { r128_do_pixcache_flush(dev_priv); return 0; } DRM_UDELAY(1); } #if R128_FIFO_DEBUG DRM_ERROR("failed!\n"); #endif return -EBUSY; } /* ================================================================ * CCE control, initialization */ /* Load the microcode for the CCE */ static int r128_cce_load_microcode(drm_r128_private_t *dev_priv) { struct platform_device *pdev; const struct firmware *fw; const __be32 *fw_data; int rc, i; DRM_DEBUG("\n"); pdev = platform_device_register_simple("r128_cce", 0, NULL, 0); if (IS_ERR(pdev)) { printk(KERN_ERR "r128_cce: Failed to register firmware\n"); return PTR_ERR(pdev); } rc = request_firmware(&fw, FIRMWARE_NAME, &pdev->dev); platform_device_unregister(pdev); if (rc) { printk(KERN_ERR "r128_cce: Failed to load firmware \"%s\"\n", FIRMWARE_NAME); return rc; } if (fw->size != 256 * 8) { printk(KERN_ERR "r128_cce: Bogus length %zu in firmware \"%s\"\n", fw->size, FIRMWARE_NAME); rc = -EINVAL; goto out_release; } r128_do_wait_for_idle(dev_priv); fw_data = (const __be32 *)fw->data; R128_WRITE(R128_PM4_MICROCODE_ADDR, 0); for (i = 0; i < 256; i++) { R128_WRITE(R128_PM4_MICROCODE_DATAH, be32_to_cpup(&fw_data[i * 2])); R128_WRITE(R128_PM4_MICROCODE_DATAL, be32_to_cpup(&fw_data[i * 2 + 1])); } out_release: release_firmware(fw); return rc; } /* Flush any pending commands to the CCE. This should only be used just * prior to a wait for idle, as it informs the engine that the command * stream is ending. */ static void r128_do_cce_flush(drm_r128_private_t *dev_priv) { u32 tmp; tmp = R128_READ(R128_PM4_BUFFER_DL_WPTR) | R128_PM4_BUFFER_DL_DONE; R128_WRITE(R128_PM4_BUFFER_DL_WPTR, tmp); } /* Wait for the CCE to go idle. */ int r128_do_cce_idle(drm_r128_private_t *dev_priv) { int i; for (i = 0; i < dev_priv->usec_timeout; i++) { if (GET_RING_HEAD(dev_priv) == dev_priv->ring.tail) { int pm4stat = R128_READ(R128_PM4_STAT); if (((pm4stat & R128_PM4_FIFOCNT_MASK) >= dev_priv->cce_fifo_size) && !(pm4stat & (R128_PM4_BUSY | R128_PM4_GUI_ACTIVE))) { return r128_do_pixcache_flush(dev_priv); } } DRM_UDELAY(1); } #if R128_FIFO_DEBUG DRM_ERROR("failed!\n"); r128_status(dev_priv); #endif return -EBUSY; } /* Start the Concurrent Command Engine. */ static void r128_do_cce_start(drm_r128_private_t *dev_priv) { r128_do_wait_for_idle(dev_priv); R128_WRITE(R128_PM4_BUFFER_CNTL, dev_priv->cce_mode | dev_priv->ring.size_l2qw | R128_PM4_BUFFER_CNTL_NOUPDATE); R128_READ(R128_PM4_BUFFER_ADDR); /* as per the sample code */ R128_WRITE(R128_PM4_MICRO_CNTL, R128_PM4_MICRO_FREERUN); dev_priv->cce_running = 1; } /* Reset the Concurrent Command Engine. This will not flush any pending * commands, so you must wait for the CCE command stream to complete * before calling this routine. */ static void r128_do_cce_reset(drm_r128_private_t *dev_priv) { R128_WRITE(R128_PM4_BUFFER_DL_WPTR, 0); R128_WRITE(R128_PM4_BUFFER_DL_RPTR, 0); dev_priv->ring.tail = 0; } /* Stop the Concurrent Command Engine. This will not flush any pending * commands, so you must flush the command stream and wait for the CCE * to go idle before calling this routine. */ static void r128_do_cce_stop(drm_r128_private_t *dev_priv) { R128_WRITE(R128_PM4_MICRO_CNTL, 0); R128_WRITE(R128_PM4_BUFFER_CNTL, R128_PM4_NONPM4 | R128_PM4_BUFFER_CNTL_NOUPDATE); dev_priv->cce_running = 0; } /* Reset the engine. This will stop the CCE if it is running. */ static int r128_do_engine_reset(struct drm_device *dev) { drm_r128_private_t *dev_priv = dev->dev_private; u32 clock_cntl_index, mclk_cntl, gen_reset_cntl; r128_do_pixcache_flush(dev_priv); clock_cntl_index = R128_READ(R128_CLOCK_CNTL_INDEX); mclk_cntl = R128_READ_PLL(dev, R128_MCLK_CNTL); R128_WRITE_PLL(R128_MCLK_CNTL, mclk_cntl | R128_FORCE_GCP | R128_FORCE_PIPE3D_CP); gen_reset_cntl = R128_READ(R128_GEN_RESET_CNTL); /* Taken from the sample code - do not change */ R128_WRITE(R128_GEN_RESET_CNTL, gen_reset_cntl | R128_SOFT_RESET_GUI); R128_READ(R128_GEN_RESET_CNTL); R128_WRITE(R128_GEN_RESET_CNTL, gen_reset_cntl & ~R128_SOFT_RESET_GUI); R128_READ(R128_GEN_RESET_CNTL); R128_WRITE_PLL(R128_MCLK_CNTL, mclk_cntl); R128_WRITE(R128_CLOCK_CNTL_INDEX, clock_cntl_index); R128_WRITE(R128_GEN_RESET_CNTL, gen_reset_cntl); /* Reset the CCE ring */ r128_do_cce_reset(dev_priv); /* The CCE is no longer running after an engine reset */ dev_priv->cce_running = 0; /* Reset any pending vertex, indirect buffers */ r128_freelist_reset(dev); return 0; } static void r128_cce_init_ring_buffer(struct drm_device *dev, drm_r128_private_t *dev_priv) { u32 ring_start; u32 tmp; DRM_DEBUG("\n"); /* The manual (p. 2) says this address is in "VM space". This * means it's an offset from the start of AGP space. */ #if __OS_HAS_AGP if (!dev_priv->is_pci) ring_start = dev_priv->cce_ring->offset - dev->agp->base; else #endif ring_start = dev_priv->cce_ring->offset - (unsigned long)dev->sg->virtual; R128_WRITE(R128_PM4_BUFFER_OFFSET, ring_start | R128_AGP_OFFSET); R128_WRITE(R128_PM4_BUFFER_DL_WPTR, 0); R128_WRITE(R128_PM4_BUFFER_DL_RPTR, 0); /* Set watermark control */ R128_WRITE(R128_PM4_BUFFER_WM_CNTL, ((R128_WATERMARK_L / 4) << R128_WMA_SHIFT) | ((R128_WATERMARK_M / 4) << R128_WMB_SHIFT) | ((R128_WATERMARK_N / 4) << R128_WMC_SHIFT) | ((R128_WATERMARK_K / 64) << R128_WB_WM_SHIFT)); /* Force read. Why? Because it's in the examples... */ R128_READ(R128_PM4_BUFFER_ADDR); /* Turn on bus mastering */ tmp = R128_READ(R128_BUS_CNTL) & ~R128_BUS_MASTER_DIS; R128_WRITE(R128_BUS_CNTL, tmp); } static int r128_do_init_cce(struct drm_device *dev, drm_r128_init_t *init) { drm_r128_private_t *dev_priv; int rc; DRM_DEBUG("\n"); if (dev->dev_private) { DRM_DEBUG("called when already initialized\n"); return -EINVAL; } dev_priv = kzalloc(sizeof(drm_r128_private_t), GFP_KERNEL); if (dev_priv == NULL) return -ENOMEM; dev_priv->is_pci = init->is_pci; if (dev_priv->is_pci && !dev->sg) { DRM_ERROR("PCI GART memory not allocated!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } dev_priv->usec_timeout = init->usec_timeout; if (dev_priv->usec_timeout < 1 || dev_priv->usec_timeout > R128_MAX_USEC_TIMEOUT) { DRM_DEBUG("TIMEOUT problem!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } dev_priv->cce_mode = init->cce_mode; /* GH: Simple idle check. */ atomic_set(&dev_priv->idle_count, 0); /* We don't support anything other than bus-mastering ring mode, * but the ring can be in either AGP or PCI space for the ring * read pointer. */ if ((init->cce_mode != R128_PM4_192BM) && (init->cce_mode != R128_PM4_128BM_64INDBM) && (init->cce_mode != R128_PM4_64BM_128INDBM) && (init->cce_mode != R128_PM4_64BM_64VCBM_64INDBM)) { DRM_DEBUG("Bad cce_mode!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } switch (init->cce_mode) { case R128_PM4_NONPM4: dev_priv->cce_fifo_size = 0; break; case R128_PM4_192PIO: case R128_PM4_192BM: dev_priv->cce_fifo_size = 192; break; case R128_PM4_128PIO_64INDBM: case R128_PM4_128BM_64INDBM: dev_priv->cce_fifo_size = 128; break; case R128_PM4_64PIO_128INDBM: case R128_PM4_64BM_128INDBM: case R128_PM4_64PIO_64VCBM_64INDBM: case R128_PM4_64BM_64VCBM_64INDBM: case R128_PM4_64PIO_64VCPIO_64INDPIO: dev_priv->cce_fifo_size = 64; break; } switch (init->fb_bpp) { case 16: dev_priv->color_fmt = R128_DATATYPE_RGB565; break; case 32: default: dev_priv->color_fmt = R128_DATATYPE_ARGB8888; break; } dev_priv->front_offset = init->front_offset; dev_priv->front_pitch = init->front_pitch; dev_priv->back_offset = init->back_offset; dev_priv->back_pitch = init->back_pitch; switch (init->depth_bpp) { case 16: dev_priv->depth_fmt = R128_DATATYPE_RGB565; break; case 24: case 32: default: dev_priv->depth_fmt = R128_DATATYPE_ARGB8888; break; } dev_priv->depth_offset = init->depth_offset; dev_priv->depth_pitch = init->depth_pitch; dev_priv->span_offset = init->span_offset; dev_priv->front_pitch_offset_c = (((dev_priv->front_pitch / 8) << 21) | (dev_priv->front_offset >> 5)); dev_priv->back_pitch_offset_c = (((dev_priv->back_pitch / 8) << 21) | (dev_priv->back_offset >> 5)); dev_priv->depth_pitch_offset_c = (((dev_priv->depth_pitch / 8) << 21) | (dev_priv->depth_offset >> 5) | R128_DST_TILE); dev_priv->span_pitch_offset_c = (((dev_priv->depth_pitch / 8) << 21) | (dev_priv->span_offset >> 5)); dev_priv->sarea = drm_getsarea(dev); if (!dev_priv->sarea) { DRM_ERROR("could not find sarea!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } dev_priv->mmio = drm_core_findmap(dev, init->mmio_offset); if (!dev_priv->mmio) { DRM_ERROR("could not find mmio region!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } dev_priv->cce_ring = drm_core_findmap(dev, init->ring_offset); if (!dev_priv->cce_ring) { DRM_ERROR("could not find cce ring region!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } dev_priv->ring_rptr = drm_core_findmap(dev, init->ring_rptr_offset); if (!dev_priv->ring_rptr) { DRM_ERROR("could not find ring read pointer!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } dev->agp_buffer_token = init->buffers_offset; dev->agp_buffer_map = drm_core_findmap(dev, init->buffers_offset); if (!dev->agp_buffer_map) { DRM_ERROR("could not find dma buffer region!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } if (!dev_priv->is_pci) { dev_priv->agp_textures = drm_core_findmap(dev, init->agp_textures_offset); if (!dev_priv->agp_textures) { DRM_ERROR("could not find agp texture region!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -EINVAL; } } dev_priv->sarea_priv = (drm_r128_sarea_t *) ((u8 *) dev_priv->sarea->handle + init->sarea_priv_offset); #if __OS_HAS_AGP if (!dev_priv->is_pci) { drm_core_ioremap_wc(dev_priv->cce_ring, dev); drm_core_ioremap_wc(dev_priv->ring_rptr, dev); drm_core_ioremap_wc(dev->agp_buffer_map, dev); if (!dev_priv->cce_ring->handle || !dev_priv->ring_rptr->handle || !dev->agp_buffer_map->handle) { DRM_ERROR("Could not ioremap agp regions!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -ENOMEM; } } else #endif { dev_priv->cce_ring->handle = (void *)(unsigned long)dev_priv->cce_ring->offset; dev_priv->ring_rptr->handle = (void *)(unsigned long)dev_priv->ring_rptr->offset; dev->agp_buffer_map->handle = (void *)(unsigned long)dev->agp_buffer_map->offset; } #if __OS_HAS_AGP if (!dev_priv->is_pci) dev_priv->cce_buffers_offset = dev->agp->base; else #endif dev_priv->cce_buffers_offset = (unsigned long)dev->sg->virtual; dev_priv->ring.start = (u32 *) dev_priv->cce_ring->handle; dev_priv->ring.end = ((u32 *) dev_priv->cce_ring->handle + init->ring_size / sizeof(u32)); dev_priv->ring.size = init->ring_size; dev_priv->ring.size_l2qw = drm_order(init->ring_size / 8); dev_priv->ring.tail_mask = (dev_priv->ring.size / sizeof(u32)) - 1; dev_priv->ring.high_mark = 128; dev_priv->sarea_priv->last_frame = 0; R128_WRITE(R128_LAST_FRAME_REG, dev_priv->sarea_priv->last_frame); dev_priv->sarea_priv->last_dispatch = 0; R128_WRITE(R128_LAST_DISPATCH_REG, dev_priv->sarea_priv->last_dispatch); #if __OS_HAS_AGP if (dev_priv->is_pci) { #endif dev_priv->gart_info.table_mask = DMA_BIT_MASK(32); dev_priv->gart_info.gart_table_location = DRM_ATI_GART_MAIN; dev_priv->gart_info.table_size = R128_PCIGART_TABLE_SIZE; dev_priv->gart_info.addr = NULL; dev_priv->gart_info.bus_addr = 0; dev_priv->gart_info.gart_reg_if = DRM_ATI_GART_PCI; if (!drm_ati_pcigart_init(dev, &dev_priv->gart_info)) { DRM_ERROR("failed to init PCI GART!\n"); dev->dev_private = (void *)dev_priv; r128_do_cleanup_cce(dev); return -ENOMEM; } R128_WRITE(R128_PCI_GART_PAGE, dev_priv->gart_info.bus_addr); #if __OS_HAS_AGP } #endif r128_cce_init_ring_buffer(dev, dev_priv); rc = r128_cce_load_microcode(dev_priv); dev->dev_private = (void *)dev_priv; r128_do_engine_reset(dev); if (rc) { DRM_ERROR("Failed to load firmware!\n"); r128_do_cleanup_cce(dev); } return rc; } int r128_do_cleanup_cce(struct drm_device *dev) { /* Make sure interrupts are disabled here because the uninstall ioctl * may not have been called from userspace and after dev_private * is freed, it's too late. */ if (dev->irq_enabled) drm_irq_uninstall(dev); if (dev->dev_private) { drm_r128_private_t *dev_priv = dev->dev_private; #if __OS_HAS_AGP if (!dev_priv->is_pci) { if (dev_priv->cce_ring != NULL) drm_core_ioremapfree(dev_priv->cce_ring, dev); if (dev_priv->ring_rptr != NULL) drm_core_ioremapfree(dev_priv->ring_rptr, dev); if (dev->agp_buffer_map != NULL) { drm_core_ioremapfree(dev->agp_buffer_map, dev); dev->agp_buffer_map = NULL; } } else #endif { if (dev_priv->gart_info.bus_addr) if (!drm_ati_pcigart_cleanup(dev, &dev_priv->gart_info)) DRM_ERROR ("failed to cleanup PCI GART!\n"); } kfree(dev->dev_private); dev->dev_private = NULL; } return 0; } int r128_cce_init(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_r128_init_t *init = data; DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); switch (init->func) { case R128_INIT_CCE: return r128_do_init_cce(dev, init); case R128_CLEANUP_CCE: return r128_do_cleanup_cce(dev); } return -EINVAL; } int r128_cce_start(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_r128_private_t *dev_priv = dev->dev_private; DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); DEV_INIT_TEST_WITH_RETURN(dev_priv); if (dev_priv->cce_running || dev_priv->cce_mode == R128_PM4_NONPM4) { DRM_DEBUG("while CCE running\n"); return 0; } r128_do_cce_start(dev_priv); return 0; } /* Stop the CCE. The engine must have been idled before calling this * routine. */ int r128_cce_stop(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_r128_private_t *dev_priv = dev->dev_private; drm_r128_cce_stop_t *stop = data; int ret; DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); DEV_INIT_TEST_WITH_RETURN(dev_priv); /* Flush any pending CCE commands. This ensures any outstanding * commands are exectuted by the engine before we turn it off. */ if (stop->flush) r128_do_cce_flush(dev_priv); /* If we fail to make the engine go idle, we return an error * code so that the DRM ioctl wrapper can try again. */ if (stop->idle) { ret = r128_do_cce_idle(dev_priv); if (ret) return ret; } /* Finally, we can turn off the CCE. If the engine isn't idle, * we will get some dropped triangles as they won't be fully * rendered before the CCE is shut down. */ r128_do_cce_stop(dev_priv); /* Reset the engine */ r128_do_engine_reset(dev); return 0; } /* Just reset the CCE ring. Called as part of an X Server engine reset. */ int r128_cce_reset(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_r128_private_t *dev_priv = dev->dev_private; DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); DEV_INIT_TEST_WITH_RETURN(dev_priv); r128_do_cce_reset(dev_priv); /* The CCE is no longer running after an engine reset */ dev_priv->cce_running = 0; return 0; } int r128_cce_idle(struct drm_device *dev, void *data, struct drm_file *file_priv) { drm_r128_private_t *dev_priv = dev->dev_private; DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); DEV_INIT_TEST_WITH_RETURN(dev_priv); if (dev_priv->cce_running) r128_do_cce_flush(dev_priv); return r128_do_cce_idle(dev_priv); } int r128_engine_reset(struct drm_device *dev, void *data, struct drm_file *file_priv) { DRM_DEBUG("\n"); LOCK_TEST_WITH_RETURN(dev, file_priv); DEV_INIT_TEST_WITH_RETURN(dev->dev_private); return r128_do_engine_reset(dev); } int r128_fullscreen(struct drm_device *dev, void *data, struct drm_file *file_priv) { return -EINVAL; } /* ================================================================ * Freelist management */ #define R128_BUFFER_USED 0xffffffff #define R128_BUFFER_FREE 0 #if 0 static int r128_freelist_init(struct drm_device *dev) { struct drm_device_dma *dma = dev->dma; drm_r128_private_t *dev_priv = dev->dev_private; struct drm_buf *buf; drm_r128_buf_priv_t *buf_priv; drm_r128_freelist_t *entry; int i; dev_priv->head = kzalloc(sizeof(drm_r128_freelist_t), GFP_KERNEL); if (dev_priv->head == NULL) return -ENOMEM; dev_priv->head->age = R128_BUFFER_USED; for (i = 0; i < dma->buf_count; i++) { buf = dma->buflist[i]; buf_priv = buf->dev_private; entry = kmalloc(sizeof(drm_r128_freelist_t), GFP_KERNEL); if (!entry) return -ENOMEM; entry->age = R128_BUFFER_FREE; entry->buf = buf; entry->prev = dev_priv->head; entry->next = dev_priv->head->next; if (!entry->next) dev_priv->tail = entry; buf_priv->discard = 0; buf_priv->dispatched = 0; buf_priv->list_entry = entry; dev_priv->head->next = entry; if (dev_priv->head->next) dev_priv->head->next->prev = entry; } return 0; } #endif static struct drm_buf *r128_freelist_get(struct drm_device * dev) { struct drm_device_dma *dma = dev->dma; drm_r128_private_t *dev_priv = dev->dev_private; drm_r128_buf_priv_t *buf_priv; struct drm_buf *buf; int i, t; /* FIXME: Optimize -- use freelist code */ for (i = 0; i < dma->buf_count; i++) { buf = dma->buflist[i]; buf_priv = buf->dev_private; if (!buf->file_priv) return buf; } for (t = 0; t < dev_priv->usec_timeout; t++) { u32 done_age = R128_READ(R128_LAST_DISPATCH_REG); for (i = 0; i < dma->buf_count; i++) { buf = dma->buflist[i]; buf_priv = buf->dev_private; if (buf->pending && buf_priv->age <= done_age) { /* The buffer has been processed, so it * can now be used. */ buf->pending = 0; return buf; } } DRM_UDELAY(1); } DRM_DEBUG("returning NULL!\n"); return NULL; } void r128_freelist_reset(struct drm_device *dev) { struct drm_device_dma *dma = dev->dma; int i; for (i = 0; i < dma->buf_count; i++) { struct drm_buf *buf = dma->buflist[i]; drm_r128_buf_priv_t *buf_priv = buf->dev_private; buf_priv->age = 0; } } /* ================================================================ * CCE command submission */ int r128_wait_ring(drm_r128_private_t *dev_priv, int n) { drm_r128_ring_buffer_t *ring = &dev_priv->ring; int i; for (i = 0; i < dev_priv->usec_timeout; i++) { r128_update_ring_snapshot(dev_priv); if (ring->space >= n) return 0; DRM_UDELAY(1); } /* FIXME: This is being ignored... */ DRM_ERROR("failed!\n"); return -EBUSY; } static int r128_cce_get_buffers(struct drm_device *dev, struct drm_file *file_priv, struct drm_dma *d) { int i; struct drm_buf *buf; for (i = d->granted_count; i < d->request_count; i++) { buf = r128_freelist_get(dev); if (!buf) return -EAGAIN; buf->file_priv = file_priv; if (DRM_COPY_TO_USER(&d->request_indices[i], &buf->idx, sizeof(buf->idx))) return -EFAULT; if (DRM_COPY_TO_USER(&d->request_sizes[i], &buf->total, sizeof(buf->total))) return -EFAULT; d->granted_count++; } return 0; } int r128_cce_buffers(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_device_dma *dma = dev->dma; int ret = 0; struct drm_dma *d = data; LOCK_TEST_WITH_RETURN(dev, file_priv); /* Please don't send us buffers. */ if (d->send_count != 0) { DRM_ERROR("Process %d trying to send %d buffers via drmDMA\n", DRM_CURRENTPID, d->send_count); return -EINVAL; } /* We'll send you buffers. */ if (d->request_count < 0 || d->request_count > dma->buf_count) { DRM_ERROR("Process %d trying to get %d buffers (of %d max)\n", DRM_CURRENTPID, d->request_count, dma->buf_count); return -EINVAL; } d->granted_count = 0; if (d->request_count) ret = r128_cce_get_buffers(dev, file_priv, d); return ret; }
gpl-2.0
alivanov79/spkernel
drivers/gpu/ion/ion_system_mapper.c
6937
3192
/* * drivers/gpu/ion/ion_system_mapper.c * * Copyright (C) 2011 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/err.h> #include <linux/ion.h> #include <linux/memory.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include "ion_priv.h" /* * This mapper is valid for any heap that allocates memory that already has * a kernel mapping, this includes vmalloc'd memory, kmalloc'd memory, * pages obtained via io_remap, etc. */ static void *ion_kernel_mapper_map(struct ion_mapper *mapper, struct ion_buffer *buffer, struct ion_mapping **mapping) { if (!((1 << buffer->heap->type) & mapper->heap_mask)) { pr_err("%s: attempting to map an unsupported heap\n", __func__); return ERR_PTR(-EINVAL); } /* XXX REVISIT ME!!! */ *((unsigned long *)mapping) = (unsigned long)buffer->priv; return buffer->priv; } static void ion_kernel_mapper_unmap(struct ion_mapper *mapper, struct ion_buffer *buffer, struct ion_mapping *mapping) { if (!((1 << buffer->heap->type) & mapper->heap_mask)) pr_err("%s: attempting to unmap an unsupported heap\n", __func__); } static void *ion_kernel_mapper_map_kernel(struct ion_mapper *mapper, struct ion_buffer *buffer, struct ion_mapping *mapping) { if (!((1 << buffer->heap->type) & mapper->heap_mask)) { pr_err("%s: attempting to unmap an unsupported heap\n", __func__); return ERR_PTR(-EINVAL); } return buffer->priv; } static int ion_kernel_mapper_map_user(struct ion_mapper *mapper, struct ion_buffer *buffer, struct vm_area_struct *vma, struct ion_mapping *mapping) { int ret; switch (buffer->heap->type) { case ION_HEAP_KMALLOC: { unsigned long pfn = __phys_to_pfn(virt_to_phys(buffer->priv)); ret = remap_pfn_range(vma, vma->vm_start, pfn + vma->vm_pgoff, vma->vm_end - vma->vm_start, vma->vm_page_prot); break; } case ION_HEAP_VMALLOC: ret = remap_vmalloc_range(vma, buffer->priv, vma->vm_pgoff); break; default: pr_err("%s: attempting to map unsupported heap to userspace\n", __func__); return -EINVAL; } return ret; } static struct ion_mapper_ops ops = { .map = ion_kernel_mapper_map, .map_kernel = ion_kernel_mapper_map_kernel, .map_user = ion_kernel_mapper_map_user, .unmap = ion_kernel_mapper_unmap, }; struct ion_mapper *ion_system_mapper_create(void) { struct ion_mapper *mapper; mapper = kzalloc(sizeof(struct ion_mapper), GFP_KERNEL); if (!mapper) return ERR_PTR(-ENOMEM); mapper->type = ION_SYSTEM_MAPPER; mapper->ops = &ops; mapper->heap_mask = (1 << ION_HEAP_VMALLOC) | (1 << ION_HEAP_KMALLOC); return mapper; } void ion_system_mapper_destroy(struct ion_mapper *mapper) { kfree(mapper); }
gpl-2.0
qhh7812/android_kernel_htc_ville-lp
drivers/usb/host/imx21-dbg.c
7449
12821
/* * Copyright (c) 2009 by Martin Fuzzey * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* this file is part of imx21-hcd.c */ #ifndef DEBUG static inline void create_debug_files(struct imx21 *imx21) { } static inline void remove_debug_files(struct imx21 *imx21) { } static inline void debug_urb_submitted(struct imx21 *imx21, struct urb *urb) {} static inline void debug_urb_completed(struct imx21 *imx21, struct urb *urb, int status) {} static inline void debug_urb_unlinked(struct imx21 *imx21, struct urb *urb) {} static inline void debug_urb_queued_for_etd(struct imx21 *imx21, struct urb *urb) {} static inline void debug_urb_queued_for_dmem(struct imx21 *imx21, struct urb *urb) {} static inline void debug_etd_allocated(struct imx21 *imx21) {} static inline void debug_etd_freed(struct imx21 *imx21) {} static inline void debug_dmem_allocated(struct imx21 *imx21, int size) {} static inline void debug_dmem_freed(struct imx21 *imx21, int size) {} static inline void debug_isoc_submitted(struct imx21 *imx21, int frame, struct td *td) {} static inline void debug_isoc_completed(struct imx21 *imx21, int frame, struct td *td, int cc, int len) {} #else #include <linux/debugfs.h> #include <linux/seq_file.h> static const char *dir_labels[] = { "TD 0", "OUT", "IN", "TD 1" }; static const char *speed_labels[] = { "Full", "Low" }; static const char *format_labels[] = { "Control", "ISO", "Bulk", "Interrupt" }; static inline struct debug_stats *stats_for_urb(struct imx21 *imx21, struct urb *urb) { return usb_pipeisoc(urb->pipe) ? &imx21->isoc_stats : &imx21->nonisoc_stats; } static void debug_urb_submitted(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->submitted++; } static void debug_urb_completed(struct imx21 *imx21, struct urb *urb, int st) { if (st) stats_for_urb(imx21, urb)->completed_failed++; else stats_for_urb(imx21, urb)->completed_ok++; } static void debug_urb_unlinked(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->unlinked++; } static void debug_urb_queued_for_etd(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->queue_etd++; } static void debug_urb_queued_for_dmem(struct imx21 *imx21, struct urb *urb) { stats_for_urb(imx21, urb)->queue_dmem++; } static inline void debug_etd_allocated(struct imx21 *imx21) { imx21->etd_usage.maximum = max( ++(imx21->etd_usage.value), imx21->etd_usage.maximum); } static inline void debug_etd_freed(struct imx21 *imx21) { imx21->etd_usage.value--; } static inline void debug_dmem_allocated(struct imx21 *imx21, int size) { imx21->dmem_usage.value += size; imx21->dmem_usage.maximum = max( imx21->dmem_usage.value, imx21->dmem_usage.maximum); } static inline void debug_dmem_freed(struct imx21 *imx21, int size) { imx21->dmem_usage.value -= size; } static void debug_isoc_submitted(struct imx21 *imx21, int frame, struct td *td) { struct debug_isoc_trace *trace = &imx21->isoc_trace[ imx21->isoc_trace_index++]; imx21->isoc_trace_index %= ARRAY_SIZE(imx21->isoc_trace); trace->schedule_frame = td->frame; trace->submit_frame = frame; trace->request_len = td->len; trace->td = td; } static inline void debug_isoc_completed(struct imx21 *imx21, int frame, struct td *td, int cc, int len) { struct debug_isoc_trace *trace, *trace_failed; int i; int found = 0; trace = imx21->isoc_trace; for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace); i++, trace++) { if (trace->td == td) { trace->done_frame = frame; trace->done_len = len; trace->cc = cc; trace->td = NULL; found = 1; break; } } if (found && cc) { trace_failed = &imx21->isoc_trace_failed[ imx21->isoc_trace_index_failed++]; imx21->isoc_trace_index_failed %= ARRAY_SIZE( imx21->isoc_trace_failed); *trace_failed = *trace; } } static char *format_ep(struct usb_host_endpoint *ep, char *buf, int bufsize) { if (ep) snprintf(buf, bufsize, "ep_%02x (type:%02X kaddr:%p)", ep->desc.bEndpointAddress, usb_endpoint_type(&ep->desc), ep); else snprintf(buf, bufsize, "none"); return buf; } static char *format_etd_dword0(u32 value, char *buf, int bufsize) { snprintf(buf, bufsize, "addr=%d ep=%d dir=%s speed=%s format=%s halted=%d", value & 0x7F, (value >> DW0_ENDPNT) & 0x0F, dir_labels[(value >> DW0_DIRECT) & 0x03], speed_labels[(value >> DW0_SPEED) & 0x01], format_labels[(value >> DW0_FORMAT) & 0x03], (value >> DW0_HALTED) & 0x01); return buf; } static int debug_status_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; int etds_allocated = 0; int etds_sw_busy = 0; int etds_hw_busy = 0; int dmem_blocks = 0; int queued_for_etd = 0; int queued_for_dmem = 0; unsigned int dmem_bytes = 0; int i; struct etd_priv *etd; u32 etd_enable_mask; unsigned long flags; struct imx21_dmem_area *dmem; struct ep_priv *ep_priv; spin_lock_irqsave(&imx21->lock, flags); etd_enable_mask = readl(imx21->regs + USBH_ETDENSET); for (i = 0, etd = imx21->etd; i < USB_NUM_ETD; i++, etd++) { if (etd->alloc) etds_allocated++; if (etd->urb) etds_sw_busy++; if (etd_enable_mask & (1<<i)) etds_hw_busy++; } list_for_each_entry(dmem, &imx21->dmem_list, list) { dmem_bytes += dmem->size; dmem_blocks++; } list_for_each_entry(ep_priv, &imx21->queue_for_etd, queue) queued_for_etd++; list_for_each_entry(etd, &imx21->queue_for_dmem, queue) queued_for_dmem++; spin_unlock_irqrestore(&imx21->lock, flags); seq_printf(s, "Frame: %d\n" "ETDs allocated: %d/%d (max=%d)\n" "ETDs in use sw: %d\n" "ETDs in use hw: %d\n" "DMEM allocated: %d/%d (max=%d)\n" "DMEM blocks: %d\n" "Queued waiting for ETD: %d\n" "Queued waiting for DMEM: %d\n", readl(imx21->regs + USBH_FRMNUB) & 0xFFFF, etds_allocated, USB_NUM_ETD, imx21->etd_usage.maximum, etds_sw_busy, etds_hw_busy, dmem_bytes, DMEM_SIZE, imx21->dmem_usage.maximum, dmem_blocks, queued_for_etd, queued_for_dmem); return 0; } static int debug_dmem_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; struct imx21_dmem_area *dmem; unsigned long flags; char ep_text[40]; spin_lock_irqsave(&imx21->lock, flags); list_for_each_entry(dmem, &imx21->dmem_list, list) seq_printf(s, "%04X: size=0x%X " "ep=%s\n", dmem->offset, dmem->size, format_ep(dmem->ep, ep_text, sizeof(ep_text))); spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static int debug_etd_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; struct etd_priv *etd; char buf[60]; u32 dword; int i, j; unsigned long flags; spin_lock_irqsave(&imx21->lock, flags); for (i = 0, etd = imx21->etd; i < USB_NUM_ETD; i++, etd++) { int state = -1; struct urb_priv *urb_priv; if (etd->urb) { urb_priv = etd->urb->hcpriv; if (urb_priv) state = urb_priv->state; } seq_printf(s, "etd_num: %d\n" "ep: %s\n" "alloc: %d\n" "len: %d\n" "busy sw: %d\n" "busy hw: %d\n" "urb state: %d\n" "current urb: %p\n", i, format_ep(etd->ep, buf, sizeof(buf)), etd->alloc, etd->len, etd->urb != NULL, (readl(imx21->regs + USBH_ETDENSET) & (1 << i)) > 0, state, etd->urb); for (j = 0; j < 4; j++) { dword = etd_readl(imx21, i, j); switch (j) { case 0: format_etd_dword0(dword, buf, sizeof(buf)); break; case 2: snprintf(buf, sizeof(buf), "cc=0X%02X", dword >> DW2_COMPCODE); break; default: *buf = 0; break; } seq_printf(s, "dword %d: submitted=%08X cur=%08X [%s]\n", j, etd->submitted_dwords[j], dword, buf); } seq_printf(s, "\n"); } spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static void debug_statistics_show_one(struct seq_file *s, const char *name, struct debug_stats *stats) { seq_printf(s, "%s:\n" "submitted URBs: %lu\n" "completed OK: %lu\n" "completed failed: %lu\n" "unlinked: %lu\n" "queued for ETD: %lu\n" "queued for DMEM: %lu\n\n", name, stats->submitted, stats->completed_ok, stats->completed_failed, stats->unlinked, stats->queue_etd, stats->queue_dmem); } static int debug_statistics_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; unsigned long flags; spin_lock_irqsave(&imx21->lock, flags); debug_statistics_show_one(s, "nonisoc", &imx21->nonisoc_stats); debug_statistics_show_one(s, "isoc", &imx21->isoc_stats); seq_printf(s, "unblock kludge triggers: %lu\n", imx21->debug_unblocks); spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static void debug_isoc_show_one(struct seq_file *s, const char *name, int index, struct debug_isoc_trace *trace) { seq_printf(s, "%s %d:\n" "cc=0X%02X\n" "scheduled frame %d (%d)\n" "submitted frame %d (%d)\n" "completed frame %d (%d)\n" "requested length=%d\n" "completed length=%d\n\n", name, index, trace->cc, trace->schedule_frame, trace->schedule_frame & 0xFFFF, trace->submit_frame, trace->submit_frame & 0xFFFF, trace->done_frame, trace->done_frame & 0xFFFF, trace->request_len, trace->done_len); } static int debug_isoc_show(struct seq_file *s, void *v) { struct imx21 *imx21 = s->private; struct debug_isoc_trace *trace; unsigned long flags; int i; spin_lock_irqsave(&imx21->lock, flags); trace = imx21->isoc_trace_failed; for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace_failed); i++, trace++) debug_isoc_show_one(s, "isoc failed", i, trace); trace = imx21->isoc_trace; for (i = 0; i < ARRAY_SIZE(imx21->isoc_trace); i++, trace++) debug_isoc_show_one(s, "isoc", i, trace); spin_unlock_irqrestore(&imx21->lock, flags); return 0; } static int debug_status_open(struct inode *inode, struct file *file) { return single_open(file, debug_status_show, inode->i_private); } static int debug_dmem_open(struct inode *inode, struct file *file) { return single_open(file, debug_dmem_show, inode->i_private); } static int debug_etd_open(struct inode *inode, struct file *file) { return single_open(file, debug_etd_show, inode->i_private); } static int debug_statistics_open(struct inode *inode, struct file *file) { return single_open(file, debug_statistics_show, inode->i_private); } static int debug_isoc_open(struct inode *inode, struct file *file) { return single_open(file, debug_isoc_show, inode->i_private); } static const struct file_operations debug_status_fops = { .open = debug_status_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_dmem_fops = { .open = debug_dmem_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_etd_fops = { .open = debug_etd_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_statistics_fops = { .open = debug_statistics_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static const struct file_operations debug_isoc_fops = { .open = debug_isoc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void create_debug_files(struct imx21 *imx21) { imx21->debug_root = debugfs_create_dir(dev_name(imx21->dev), NULL); if (!imx21->debug_root) goto failed_create_rootdir; if (!debugfs_create_file("status", S_IRUGO, imx21->debug_root, imx21, &debug_status_fops)) goto failed_create; if (!debugfs_create_file("dmem", S_IRUGO, imx21->debug_root, imx21, &debug_dmem_fops)) goto failed_create; if (!debugfs_create_file("etd", S_IRUGO, imx21->debug_root, imx21, &debug_etd_fops)) goto failed_create; if (!debugfs_create_file("statistics", S_IRUGO, imx21->debug_root, imx21, &debug_statistics_fops)) goto failed_create; if (!debugfs_create_file("isoc", S_IRUGO, imx21->debug_root, imx21, &debug_isoc_fops)) goto failed_create; return; failed_create: debugfs_remove_recursive(imx21->debug_root); failed_create_rootdir: imx21->debug_root = NULL; } static void remove_debug_files(struct imx21 *imx21) { if (imx21->debug_root) { debugfs_remove_recursive(imx21->debug_root); imx21->debug_root = NULL; } } #endif
gpl-2.0
Jimmyk422/android_kernel_samsung_iconvmu
arch/sh/boards/mach-se/770x/irq.c
13081
2392
/* * linux/arch/sh/boards/se/770x/irq.c * * Copyright (C) 2000 Kazumoto Kojima * Copyright (C) 2006 Nobuhiro Iwamatsu * * Hitachi SolutionEngine Support. * */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <asm/irq.h> #include <asm/io.h> #include <mach-se/mach/se.h> static struct ipr_data ipr_irq_table[] = { /* * Super I/O (Just mimic PC): * 1: keyboard * 3: serial 0 * 4: serial 1 * 5: printer * 6: floppy * 8: rtc * 12: mouse * 14: ide0 */ #if defined(CONFIG_CPU_SUBTYPE_SH7705) /* This is default value */ { 13, 0, 8, 0x0f-13, }, { 5 , 0, 4, 0x0f- 5, }, { 10, 1, 0, 0x0f-10, }, { 7 , 2, 4, 0x0f- 7, }, { 3 , 2, 0, 0x0f- 3, }, { 1 , 3, 12, 0x0f- 1, }, { 12, 3, 4, 0x0f-12, }, /* LAN */ { 2 , 4, 8, 0x0f- 2, }, /* PCIRQ2 */ { 6 , 4, 4, 0x0f- 6, }, /* PCIRQ1 */ { 14, 4, 0, 0x0f-14, }, /* PCIRQ0 */ { 0 , 5, 12, 0x0f , }, { 4 , 5, 4, 0x0f- 4, }, { 8 , 6, 12, 0x0f- 8, }, { 9 , 6, 8, 0x0f- 9, }, { 11, 6, 4, 0x0f-11, }, #else { 14, 0, 8, 0x0f-14, }, { 12, 0, 4, 0x0f-12, }, { 8, 1, 4, 0x0f- 8, }, { 6, 2, 12, 0x0f- 6, }, { 5, 2, 8, 0x0f- 5, }, { 4, 2, 4, 0x0f- 4, }, { 3, 2, 0, 0x0f- 3, }, { 1, 3, 12, 0x0f- 1, }, #if defined(CONFIG_STNIC) /* ST NIC */ { 10, 3, 4, 0x0f-10, }, /* LAN */ #endif /* MRSHPC IRQs setting */ { 0, 4, 12, 0x0f- 0, }, /* PCIRQ3 */ { 11, 4, 8, 0x0f-11, }, /* PCIRQ2 */ { 9, 4, 4, 0x0f- 9, }, /* PCIRQ1 */ { 7, 4, 0, 0x0f- 7, }, /* PCIRQ0 */ /* #2, #13 are allocated for SLOT IRQ #1 and #2 (for now) */ /* NOTE: #2 and #13 are not used on PC */ { 13, 6, 4, 0x0f-13, }, /* SLOTIRQ2 */ { 2, 6, 0, 0x0f- 2, }, /* SLOTIRQ1 */ #endif }; static unsigned long ipr_offsets[] = { BCR_ILCRA, BCR_ILCRB, BCR_ILCRC, BCR_ILCRD, BCR_ILCRE, BCR_ILCRF, BCR_ILCRG, }; static struct ipr_desc ipr_irq_desc = { .ipr_offsets = ipr_offsets, .nr_offsets = ARRAY_SIZE(ipr_offsets), .ipr_data = ipr_irq_table, .nr_irqs = ARRAY_SIZE(ipr_irq_table), .chip = { .name = "IPR-se770x", }, }; /* * Initialize IRQ setting */ void __init init_se_IRQ(void) { /* Disable all interrupts */ __raw_writew(0, BCR_ILCRA); __raw_writew(0, BCR_ILCRB); __raw_writew(0, BCR_ILCRC); __raw_writew(0, BCR_ILCRD); __raw_writew(0, BCR_ILCRE); __raw_writew(0, BCR_ILCRF); __raw_writew(0, BCR_ILCRG); register_ipr_controller(&ipr_irq_desc); }
gpl-2.0
JaganTeki/streak_4.05_kernel
arch/x86/math-emu/reg_constant.c
14361
3807
/*---------------------------------------------------------------------------+ | reg_constant.c | | | | All of the constant FPU_REGs | | | | Copyright (C) 1992,1993,1994,1997 | | W. Metzenthen, 22 Parker St, Ormond, Vic 3163, | | Australia. E-mail billm@suburbia.net | | | | | +---------------------------------------------------------------------------*/ #include "fpu_system.h" #include "fpu_emu.h" #include "status_w.h" #include "reg_constant.h" #include "control_w.h" #define MAKE_REG(s, e, l, h) { l, h, \ ((EXTENDED_Ebias+(e)) | ((SIGN_##s != 0)*0x8000)) } FPU_REG const CONST_1 = MAKE_REG(POS, 0, 0x00000000, 0x80000000); #if 0 FPU_REG const CONST_2 = MAKE_REG(POS, 1, 0x00000000, 0x80000000); FPU_REG const CONST_HALF = MAKE_REG(POS, -1, 0x00000000, 0x80000000); #endif /* 0 */ static FPU_REG const CONST_L2T = MAKE_REG(POS, 1, 0xcd1b8afe, 0xd49a784b); static FPU_REG const CONST_L2E = MAKE_REG(POS, 0, 0x5c17f0bc, 0xb8aa3b29); FPU_REG const CONST_PI = MAKE_REG(POS, 1, 0x2168c235, 0xc90fdaa2); FPU_REG const CONST_PI2 = MAKE_REG(POS, 0, 0x2168c235, 0xc90fdaa2); FPU_REG const CONST_PI4 = MAKE_REG(POS, -1, 0x2168c235, 0xc90fdaa2); static FPU_REG const CONST_LG2 = MAKE_REG(POS, -2, 0xfbcff799, 0x9a209a84); static FPU_REG const CONST_LN2 = MAKE_REG(POS, -1, 0xd1cf79ac, 0xb17217f7); /* Extra bits to take pi/2 to more than 128 bits precision. */ FPU_REG const CONST_PI2extra = MAKE_REG(NEG, -66, 0xfc8f8cbb, 0xece675d1); /* Only the sign (and tag) is used in internal zeroes */ FPU_REG const CONST_Z = MAKE_REG(POS, EXP_UNDER, 0x0, 0x0); /* Only the sign and significand (and tag) are used in internal NaNs */ /* The 80486 never generates one of these FPU_REG const CONST_SNAN = MAKE_REG(POS, EXP_OVER, 0x00000001, 0x80000000); */ /* This is the real indefinite QNaN */ FPU_REG const CONST_QNaN = MAKE_REG(NEG, EXP_OVER, 0x00000000, 0xC0000000); /* Only the sign (and tag) is used in internal infinities */ FPU_REG const CONST_INF = MAKE_REG(POS, EXP_OVER, 0x00000000, 0x80000000); static void fld_const(FPU_REG const * c, int adj, u_char tag) { FPU_REG *st_new_ptr; if (STACK_OVERFLOW) { FPU_stack_overflow(); return; } push(); reg_copy(c, st_new_ptr); st_new_ptr->sigl += adj; /* For all our fldxxx constants, we don't need to borrow or carry. */ FPU_settag0(tag); clear_C1(); } /* A fast way to find out whether x is one of RC_DOWN or RC_CHOP (and not one of RC_RND or RC_UP). */ #define DOWN_OR_CHOP(x) (x & RC_DOWN) static void fld1(int rc) { fld_const(&CONST_1, 0, TAG_Valid); } static void fldl2t(int rc) { fld_const(&CONST_L2T, (rc == RC_UP) ? 1 : 0, TAG_Valid); } static void fldl2e(int rc) { fld_const(&CONST_L2E, DOWN_OR_CHOP(rc) ? -1 : 0, TAG_Valid); } static void fldpi(int rc) { fld_const(&CONST_PI, DOWN_OR_CHOP(rc) ? -1 : 0, TAG_Valid); } static void fldlg2(int rc) { fld_const(&CONST_LG2, DOWN_OR_CHOP(rc) ? -1 : 0, TAG_Valid); } static void fldln2(int rc) { fld_const(&CONST_LN2, DOWN_OR_CHOP(rc) ? -1 : 0, TAG_Valid); } static void fldz(int rc) { fld_const(&CONST_Z, 0, TAG_Zero); } typedef void (*FUNC_RC) (int); static FUNC_RC constants_table[] = { fld1, fldl2t, fldl2e, fldpi, fldlg2, fldln2, fldz, (FUNC_RC) FPU_illegal }; void fconst(void) { (constants_table[FPU_rm]) (control_word & CW_RC); }
gpl-2.0
5victor/linux
sound/isa/gus/gus_irq.c
14617
4770
/* * Routine for IRQ handling from GF1/InterWave chip * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <sound/core.h> #include <sound/info.h> #include <sound/gus.h> #ifdef CONFIG_SND_DEBUG #define STAT_ADD(x) ((x)++) #else #define STAT_ADD(x) while (0) { ; } #endif irqreturn_t snd_gus_interrupt(int irq, void *dev_id) { struct snd_gus_card * gus = dev_id; unsigned char status; int loop = 100; int handled = 0; __again: status = inb(gus->gf1.reg_irqstat); if (status == 0) return IRQ_RETVAL(handled); handled = 1; /* snd_printk(KERN_DEBUG "IRQ: status = 0x%x\n", status); */ if (status & 0x02) { STAT_ADD(gus->gf1.interrupt_stat_midi_in); if (gus->gf1.interrupt_handler_midi_in) gus->gf1.interrupt_handler_midi_in(gus); } if (status & 0x01) { STAT_ADD(gus->gf1.interrupt_stat_midi_out); if (gus->gf1.interrupt_handler_midi_out) gus->gf1.interrupt_handler_midi_out(gus); } if (status & (0x20 | 0x40)) { unsigned int already, _current_; unsigned char voice_status, voice; struct snd_gus_voice *pvoice; already = 0; while (((voice_status = snd_gf1_i_read8(gus, SNDRV_GF1_GB_VOICES_IRQ)) & 0xc0) != 0xc0) { voice = voice_status & 0x1f; _current_ = 1 << voice; if (already & _current_) continue; /* multi request */ already |= _current_; /* mark request */ #if 0 printk(KERN_DEBUG "voice = %i, voice_status = 0x%x, " "voice_verify = %i\n", voice, voice_status, inb(GUSP(gus, GF1PAGE))); #endif pvoice = &gus->gf1.voices[voice]; if (pvoice->use) { if (!(voice_status & 0x80)) { /* voice position IRQ */ STAT_ADD(pvoice->interrupt_stat_wave); pvoice->handler_wave(gus, pvoice); } if (!(voice_status & 0x40)) { /* volume ramp IRQ */ STAT_ADD(pvoice->interrupt_stat_volume); pvoice->handler_volume(gus, pvoice); } } else { STAT_ADD(gus->gf1.interrupt_stat_voice_lost); snd_gf1_i_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); snd_gf1_i_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); } } } if (status & 0x04) { STAT_ADD(gus->gf1.interrupt_stat_timer1); if (gus->gf1.interrupt_handler_timer1) gus->gf1.interrupt_handler_timer1(gus); } if (status & 0x08) { STAT_ADD(gus->gf1.interrupt_stat_timer2); if (gus->gf1.interrupt_handler_timer2) gus->gf1.interrupt_handler_timer2(gus); } if (status & 0x80) { if (snd_gf1_i_look8(gus, SNDRV_GF1_GB_DRAM_DMA_CONTROL) & 0x40) { STAT_ADD(gus->gf1.interrupt_stat_dma_write); if (gus->gf1.interrupt_handler_dma_write) gus->gf1.interrupt_handler_dma_write(gus); } if (snd_gf1_i_look8(gus, SNDRV_GF1_GB_REC_DMA_CONTROL) & 0x40) { STAT_ADD(gus->gf1.interrupt_stat_dma_read); if (gus->gf1.interrupt_handler_dma_read) gus->gf1.interrupt_handler_dma_read(gus); } } if (--loop > 0) goto __again; return IRQ_NONE; } #ifdef CONFIG_SND_DEBUG static void snd_gus_irq_info_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_gus_card *gus; struct snd_gus_voice *pvoice; int idx; gus = entry->private_data; snd_iprintf(buffer, "midi out = %u\n", gus->gf1.interrupt_stat_midi_out); snd_iprintf(buffer, "midi in = %u\n", gus->gf1.interrupt_stat_midi_in); snd_iprintf(buffer, "timer1 = %u\n", gus->gf1.interrupt_stat_timer1); snd_iprintf(buffer, "timer2 = %u\n", gus->gf1.interrupt_stat_timer2); snd_iprintf(buffer, "dma write = %u\n", gus->gf1.interrupt_stat_dma_write); snd_iprintf(buffer, "dma read = %u\n", gus->gf1.interrupt_stat_dma_read); snd_iprintf(buffer, "voice lost = %u\n", gus->gf1.interrupt_stat_voice_lost); for (idx = 0; idx < 32; idx++) { pvoice = &gus->gf1.voices[idx]; snd_iprintf(buffer, "voice %i: wave = %u, volume = %u\n", idx, pvoice->interrupt_stat_wave, pvoice->interrupt_stat_volume); } } void snd_gus_irq_profile_init(struct snd_gus_card *gus) { struct snd_info_entry *entry; if (! snd_card_proc_new(gus->card, "gusirq", &entry)) snd_info_set_text_ops(entry, gus, snd_gus_irq_info_read); } #endif
gpl-2.0
ryo-on/gcc-4.2.4-SCO-OpenServer5
gcc/config/soft-fp/gesf2.c
26
1952
/* Software floating-point emulation. Return 0 iff a == b, 1 iff a > b, -2 iff a ? b, -1 iff a < b Copyright (C) 1997,1999,2006 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Richard Henderson (rth@cygnus.com) and Jakub Jelinek (jj@ultra.linux.cz). The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. In addition to the permissions in the GNU Lesser General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file into combinations with other programs, and to distribute those combinations without any restriction coming from the use of this file. (The Lesser General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into a combine executable.) The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "soft-fp.h" #include "single.h" int __gesf2(SFtype a, SFtype b) { FP_DECL_EX; FP_DECL_S(A); FP_DECL_S(B); int r; FP_UNPACK_RAW_S(A, a); FP_UNPACK_RAW_S(B, b); FP_CMP_S(r, A, B, -2); if (r == -2 && (FP_ISSIGNAN_S(A) || FP_ISSIGNAN_S(B))) FP_SET_EXCEPTION(FP_EX_INVALID); FP_HANDLE_EXCEPTIONS; return r; } strong_alias(__gesf2, __gtsf2);
gpl-2.0
loverlucia/linux-2.6.24
drivers/edac/edac_pci.c
26
11741
/* * EDAC PCI component * * Author: Dave Jiang <djiang@mvista.com> * * 2007 (c) MontaVista Software, Inc. This file is licensed under * the terms of the GNU General Public License version 2. This program * is licensed "as is" without any warranty of any kind, whether express * or implied. * */ #include <linux/module.h> #include <linux/types.h> #include <linux/smp.h> #include <linux/init.h> #include <linux/sysctl.h> #include <linux/highmem.h> #include <linux/timer.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/list.h> #include <linux/sysdev.h> #include <linux/ctype.h> #include <linux/workqueue.h> #include <asm/uaccess.h> #include <asm/page.h> #include "edac_core.h" #include "edac_module.h" static DEFINE_MUTEX(edac_pci_ctls_mutex); static struct list_head edac_pci_list = LIST_HEAD_INIT(edac_pci_list); /* * edac_pci_alloc_ctl_info * * The alloc() function for the 'edac_pci' control info * structure. The chip driver will allocate one of these for each * edac_pci it is going to control/register with the EDAC CORE. */ struct edac_pci_ctl_info *edac_pci_alloc_ctl_info(unsigned int sz_pvt, const char *edac_pci_name) { struct edac_pci_ctl_info *pci; void *pvt; unsigned int size; debugf1("%s()\n", __func__); pci = (struct edac_pci_ctl_info *)0; pvt = edac_align_ptr(&pci[1], sz_pvt); size = ((unsigned long)pvt) + sz_pvt; /* Alloc the needed control struct memory */ pci = kzalloc(size, GFP_KERNEL); if (pci == NULL) return NULL; /* Now much private space */ pvt = sz_pvt ? ((char *)pci) + ((unsigned long)pvt) : NULL; pci->pvt_info = pvt; pci->op_state = OP_ALLOC; snprintf(pci->name, strlen(edac_pci_name) + 1, "%s", edac_pci_name); return pci; } EXPORT_SYMBOL_GPL(edac_pci_alloc_ctl_info); /* * edac_pci_free_ctl_info() * * Last action on the pci control structure. * * call the remove sysfs informaton, which will unregister * this control struct's kobj. When that kobj's ref count * goes to zero, its release function will be call and then * kfree() the memory. */ void edac_pci_free_ctl_info(struct edac_pci_ctl_info *pci) { debugf1("%s()\n", __func__); edac_pci_remove_sysfs(pci); } EXPORT_SYMBOL_GPL(edac_pci_free_ctl_info); /* * find_edac_pci_by_dev() * scans the edac_pci list for a specific 'struct device *' * * return NULL if not found, or return control struct pointer */ static struct edac_pci_ctl_info *find_edac_pci_by_dev(struct device *dev) { struct edac_pci_ctl_info *pci; struct list_head *item; debugf1("%s()\n", __func__); list_for_each(item, &edac_pci_list) { pci = list_entry(item, struct edac_pci_ctl_info, link); if (pci->dev == dev) return pci; } return NULL; } /* * add_edac_pci_to_global_list * Before calling this function, caller must assign a unique value to * edac_dev->pci_idx. * Return: * 0 on success * 1 on failure */ static int add_edac_pci_to_global_list(struct edac_pci_ctl_info *pci) { struct list_head *item, *insert_before; struct edac_pci_ctl_info *rover; debugf1("%s()\n", __func__); insert_before = &edac_pci_list; /* Determine if already on the list */ rover = find_edac_pci_by_dev(pci->dev); if (unlikely(rover != NULL)) goto fail0; /* Insert in ascending order by 'pci_idx', so find position */ list_for_each(item, &edac_pci_list) { rover = list_entry(item, struct edac_pci_ctl_info, link); if (rover->pci_idx >= pci->pci_idx) { if (unlikely(rover->pci_idx == pci->pci_idx)) goto fail1; insert_before = item; break; } } list_add_tail_rcu(&pci->link, insert_before); return 0; fail0: edac_printk(KERN_WARNING, EDAC_PCI, "%s (%s) %s %s already assigned %d\n", rover->dev->bus_id, dev_name(rover), rover->mod_name, rover->ctl_name, rover->pci_idx); return 1; fail1: edac_printk(KERN_WARNING, EDAC_PCI, "but in low-level driver: attempt to assign\n" "\tduplicate pci_idx %d in %s()\n", rover->pci_idx, __func__); return 1; } /* * complete_edac_pci_list_del * * RCU completion callback to indicate item is deleted */ static void complete_edac_pci_list_del(struct rcu_head *head) { struct edac_pci_ctl_info *pci; pci = container_of(head, struct edac_pci_ctl_info, rcu); INIT_LIST_HEAD(&pci->link); complete(&pci->complete); } /* * del_edac_pci_from_global_list * * remove the PCI control struct from the global list */ static void del_edac_pci_from_global_list(struct edac_pci_ctl_info *pci) { list_del_rcu(&pci->link); init_completion(&pci->complete); call_rcu(&pci->rcu, complete_edac_pci_list_del); wait_for_completion(&pci->complete); } /* * edac_pci_find() * Search for an edac_pci_ctl_info structure whose index is 'idx' * * If found, return a pointer to the structure * Else return NULL. * * Caller must hold pci_ctls_mutex. */ struct edac_pci_ctl_info *edac_pci_find(int idx) { struct list_head *item; struct edac_pci_ctl_info *pci; /* Iterage over list, looking for exact match of ID */ list_for_each(item, &edac_pci_list) { pci = list_entry(item, struct edac_pci_ctl_info, link); if (pci->pci_idx >= idx) { if (pci->pci_idx == idx) return pci; /* not on list, so terminate early */ break; } } return NULL; } EXPORT_SYMBOL_GPL(edac_pci_find); /* * edac_pci_workq_function() * * periodic function that performs the operation * scheduled by a workq request, for a given PCI control struct */ static void edac_pci_workq_function(struct work_struct *work_req) { struct delayed_work *d_work = (struct delayed_work *)work_req; struct edac_pci_ctl_info *pci = to_edac_pci_ctl_work(d_work); int msec; unsigned long delay; debugf3("%s() checking\n", __func__); mutex_lock(&edac_pci_ctls_mutex); if (pci->op_state == OP_RUNNING_POLL) { /* we might be in POLL mode, but there may NOT be a poll func */ if ((pci->edac_check != NULL) && edac_pci_get_check_errors()) pci->edac_check(pci); /* if we are on a one second period, then use round */ msec = edac_pci_get_poll_msec(); if (msec == 1000) delay = round_jiffies(msecs_to_jiffies(msec)); else delay = msecs_to_jiffies(msec); /* Reschedule only if we are in POLL mode */ queue_delayed_work(edac_workqueue, &pci->work, delay); } mutex_unlock(&edac_pci_ctls_mutex); } /* * edac_pci_workq_setup() * initialize a workq item for this edac_pci instance * passing in the new delay period in msec * * locking model: * called when 'edac_pci_ctls_mutex' is locked */ static void edac_pci_workq_setup(struct edac_pci_ctl_info *pci, unsigned int msec) { debugf0("%s()\n", __func__); INIT_DELAYED_WORK(&pci->work, edac_pci_workq_function); queue_delayed_work(edac_workqueue, &pci->work, msecs_to_jiffies(edac_pci_get_poll_msec())); } /* * edac_pci_workq_teardown() * stop the workq processing on this edac_pci instance */ static void edac_pci_workq_teardown(struct edac_pci_ctl_info *pci) { int status; debugf0("%s()\n", __func__); status = cancel_delayed_work(&pci->work); if (status == 0) flush_workqueue(edac_workqueue); } /* * edac_pci_reset_delay_period * * called with a new period value for the workq period * a) stop current workq timer * b) restart workq timer with new value */ void edac_pci_reset_delay_period(struct edac_pci_ctl_info *pci, unsigned long value) { debugf0("%s()\n", __func__); edac_pci_workq_teardown(pci); /* need to lock for the setup */ mutex_lock(&edac_pci_ctls_mutex); edac_pci_workq_setup(pci, value); mutex_unlock(&edac_pci_ctls_mutex); } EXPORT_SYMBOL_GPL(edac_pci_reset_delay_period); /* * edac_pci_add_device: Insert the 'edac_dev' structure into the * edac_pci global list and create sysfs entries associated with * edac_pci structure. * @pci: pointer to the edac_device structure to be added to the list * @edac_idx: A unique numeric identifier to be assigned to the * 'edac_pci' structure. * * Return: * 0 Success * !0 Failure */ int edac_pci_add_device(struct edac_pci_ctl_info *pci, int edac_idx) { debugf0("%s()\n", __func__); pci->pci_idx = edac_idx; pci->start_time = jiffies; mutex_lock(&edac_pci_ctls_mutex); if (add_edac_pci_to_global_list(pci)) goto fail0; if (edac_pci_create_sysfs(pci)) { edac_pci_printk(pci, KERN_WARNING, "failed to create sysfs pci\n"); goto fail1; } if (pci->edac_check != NULL) { pci->op_state = OP_RUNNING_POLL; edac_pci_workq_setup(pci, 1000); } else { pci->op_state = OP_RUNNING_INTERRUPT; } edac_pci_printk(pci, KERN_INFO, "Giving out device to module '%s' controller '%s':" " DEV '%s' (%s)\n", pci->mod_name, pci->ctl_name, dev_name(pci), edac_op_state_to_string(pci->op_state)); mutex_unlock(&edac_pci_ctls_mutex); return 0; /* error unwind stack */ fail1: del_edac_pci_from_global_list(pci); fail0: mutex_unlock(&edac_pci_ctls_mutex); return 1; } EXPORT_SYMBOL_GPL(edac_pci_add_device); /* * edac_pci_del_device() * Remove sysfs entries for specified edac_pci structure and * then remove edac_pci structure from global list * * @dev: * Pointer to 'struct device' representing edac_pci structure * to remove * * Return: * Pointer to removed edac_pci structure, * or NULL if device not found */ struct edac_pci_ctl_info *edac_pci_del_device(struct device *dev) { struct edac_pci_ctl_info *pci; debugf0("%s()\n", __func__); mutex_lock(&edac_pci_ctls_mutex); /* ensure the control struct is on the global list * if not, then leave */ pci = find_edac_pci_by_dev(dev); if (pci == NULL) { mutex_unlock(&edac_pci_ctls_mutex); return NULL; } pci->op_state = OP_OFFLINE; del_edac_pci_from_global_list(pci); mutex_unlock(&edac_pci_ctls_mutex); /* stop the workq timer */ edac_pci_workq_teardown(pci); edac_printk(KERN_INFO, EDAC_PCI, "Removed device %d for %s %s: DEV %s\n", pci->pci_idx, pci->mod_name, pci->ctl_name, dev_name(pci)); return pci; } EXPORT_SYMBOL_GPL(edac_pci_del_device); /* * edac_pci_generic_check * * a Generic parity check API */ void edac_pci_generic_check(struct edac_pci_ctl_info *pci) { debugf4("%s()\n", __func__); edac_pci_do_parity_check(); } /* free running instance index counter */ static int edac_pci_idx; #define EDAC_PCI_GENCTL_NAME "EDAC PCI controller" struct edac_pci_gen_data { int edac_idx; }; /* * edac_pci_create_generic_ctl * * A generic constructor for a PCI parity polling device * Some systems have more than one domain of PCI busses. * For systems with one domain, then this API will * provide for a generic poller. * * This routine calls the edac_pci_alloc_ctl_info() for * the generic device, with default values */ struct edac_pci_ctl_info *edac_pci_create_generic_ctl(struct device *dev, const char *mod_name) { struct edac_pci_ctl_info *pci; struct edac_pci_gen_data *pdata; pci = edac_pci_alloc_ctl_info(sizeof(*pdata), EDAC_PCI_GENCTL_NAME); if (!pci) return NULL; pdata = pci->pvt_info; pci->dev = dev; dev_set_drvdata(pci->dev, pci); pci->dev_name = pci_name(to_pci_dev(dev)); pci->mod_name = mod_name; pci->ctl_name = EDAC_PCI_GENCTL_NAME; pci->edac_check = edac_pci_generic_check; pdata->edac_idx = edac_pci_idx++; if (edac_pci_add_device(pci, pdata->edac_idx) > 0) { debugf3("%s(): failed edac_pci_add_device()\n", __func__); edac_pci_free_ctl_info(pci); return NULL; } return pci; } EXPORT_SYMBOL_GPL(edac_pci_create_generic_ctl); /* * edac_pci_release_generic_ctl * * The release function of a generic EDAC PCI polling device */ void edac_pci_release_generic_ctl(struct edac_pci_ctl_info *pci) { debugf0("%s() pci mod=%s\n", __func__, pci->mod_name); edac_pci_del_device(pci->dev); edac_pci_free_ctl_info(pci); } EXPORT_SYMBOL_GPL(edac_pci_release_generic_ctl);
gpl-2.0
dgarnier/barebox
arch/arm/mach-imx/clk-pfd.c
26
3100
/* * Copyright 2012 Freescale Semiconductor, Inc. * Copyright 2012 Linaro Ltd. * * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ #include <common.h> #include <init.h> #include <driver.h> #include <linux/clk.h> #include <io.h> #include <linux/clkdev.h> #include <linux/err.h> #include <malloc.h> #include <asm-generic/div64.h> #include "clk.h" /** * struct clk_pfd - IMX PFD clock * @clk_hw: clock source * @reg: PFD register address * @idx: the index of PFD encoded in the register * * PFD clock found on i.MX6 series. Each register for PFD has 4 clk_pfd * data encoded, and member idx is used to specify the one. And each * register has SET, CLR and TOG registers at offset 0x4 0x8 and 0xc. */ struct clk_pfd { struct clk clk; void __iomem *reg; u8 idx; const char *parent; }; #define to_clk_pfd(_clk) container_of(_clk, struct clk_pfd, clk) #define SET 0x4 #define CLR 0x8 #define OTG 0xc static int clk_pfd_enable(struct clk *clk) { struct clk_pfd *pfd = to_clk_pfd(clk); writel(1 << ((pfd->idx + 1) * 8 - 1), pfd->reg + CLR); return 0; } static void clk_pfd_disable(struct clk *clk) { struct clk_pfd *pfd = to_clk_pfd(clk); writel(1 << ((pfd->idx + 1) * 8 - 1), pfd->reg + SET); } static unsigned long clk_pfd_recalc_rate(struct clk *clk, unsigned long parent_rate) { struct clk_pfd *pfd = to_clk_pfd(clk); u64 tmp = parent_rate; u8 frac = (readl(pfd->reg) >> (pfd->idx * 8)) & 0x3f; tmp *= 18; do_div(tmp, frac); return tmp; } static long clk_pfd_round_rate(struct clk *clk, unsigned long rate, unsigned long *prate) { u64 tmp = *prate; u8 frac; tmp = tmp * 18 + rate / 2; do_div(tmp, rate); frac = tmp; if (frac < 12) frac = 12; else if (frac > 35) frac = 35; tmp = *prate; tmp *= 18; do_div(tmp, frac); return tmp; } static int clk_pfd_set_rate(struct clk *clk, unsigned long rate, unsigned long parent_rate) { struct clk_pfd *pfd = to_clk_pfd(clk); u64 tmp = parent_rate; u8 frac; tmp = tmp * 18 + rate / 2; do_div(tmp, rate); frac = tmp; if (frac < 12) frac = 12; else if (frac > 35) frac = 35; writel(0x3f << (pfd->idx * 8), pfd->reg + CLR); writel(frac << (pfd->idx * 8), pfd->reg + SET); return 0; } static const struct clk_ops clk_pfd_ops = { .enable = clk_pfd_enable, .disable = clk_pfd_disable, .recalc_rate = clk_pfd_recalc_rate, .round_rate = clk_pfd_round_rate, .set_rate = clk_pfd_set_rate, }; struct clk *imx_clk_pfd(const char *name, const char *parent, void __iomem *reg, u8 idx) { struct clk_pfd *pfd; int ret; pfd = xzalloc(sizeof(*pfd)); pfd->reg = reg; pfd->idx = idx; pfd->parent = parent; pfd->clk.name = name; pfd->clk.ops = &clk_pfd_ops; pfd->clk.parent_names = &pfd->parent; pfd->clk.num_parents = 1; ret = clk_register(&pfd->clk); if (ret) { free(pfd); return ERR_PTR(ret); } return &pfd->clk; }
gpl-2.0
lizhm82/if30x-kernel
sound/isa/gus/interwave.c
26
27216
/* * Driver for AMD InterWave soundcard * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * 1999/07/22 Erik Inge Bolso <knan@mo.himolde.no> * * mixer group handlers * */ #include <linux/init.h> #include <linux/err.h> #include <linux/isa.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/pnp.h> #include <linux/moduleparam.h> #include <asm/dma.h> #include <sound/core.h> #include <sound/gus.h> #include <sound/cs4231.h> #ifdef SNDRV_STB #include <sound/tea6330t.h> #endif #define SNDRV_LEGACY_FIND_FREE_IRQ #define SNDRV_LEGACY_FIND_FREE_DMA #include <sound/initval.h> MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>"); MODULE_LICENSE("GPL"); #ifndef SNDRV_STB MODULE_DESCRIPTION("AMD InterWave"); MODULE_SUPPORTED_DEVICE("{{Gravis,UltraSound Plug & Play}," "{STB,SoundRage32}," "{MED,MED3210}," "{Dynasonix,Dynasonix Pro}," "{Panasonic,PCA761AW}}"); #else MODULE_DESCRIPTION("AMD InterWave STB with TEA6330T"); MODULE_SUPPORTED_DEVICE("{{AMD,InterWave STB with TEA6330T}}"); #endif static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */ #ifdef CONFIG_PNP static int isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1}; #endif static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x210,0x220,0x230,0x240,0x250,0x260 */ #ifdef SNDRV_STB static long port_tc[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x350,0x360,0x370,0x380 */ #endif static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 2,3,5,9,11,12,15 */ static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */ static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */ static int joystick_dac[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 29}; /* 0 to 31, (0.59V-4.52V or 0.389V-2.98V) */ static int midi[SNDRV_CARDS]; static int pcm_channels[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2}; static int effect[SNDRV_CARDS]; #ifdef SNDRV_STB #define PFX "interwave-stb: " #define INTERWAVE_DRIVER "snd_interwave_stb" #define INTERWAVE_PNP_DRIVER "interwave-stb" #else #define PFX "interwave: " #define INTERWAVE_DRIVER "snd_interwave" #define INTERWAVE_PNP_DRIVER "interwave" #endif module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for InterWave soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for InterWave soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable InterWave soundcard."); #ifdef CONFIG_PNP module_param_array(isapnp, bool, NULL, 0444); MODULE_PARM_DESC(isapnp, "ISA PnP detection for specified soundcard."); #endif module_param_array(port, long, NULL, 0444); MODULE_PARM_DESC(port, "Port # for InterWave driver."); #ifdef SNDRV_STB module_param_array(port_tc, long, NULL, 0444); MODULE_PARM_DESC(port_tc, "Tone control (TEA6330T - i2c bus) port # for InterWave driver."); #endif module_param_array(irq, int, NULL, 0444); MODULE_PARM_DESC(irq, "IRQ # for InterWave driver."); module_param_array(dma1, int, NULL, 0444); MODULE_PARM_DESC(dma1, "DMA1 # for InterWave driver."); module_param_array(dma2, int, NULL, 0444); MODULE_PARM_DESC(dma2, "DMA2 # for InterWave driver."); module_param_array(joystick_dac, int, NULL, 0444); MODULE_PARM_DESC(joystick_dac, "Joystick DAC level 0.59V-4.52V or 0.389V-2.98V for InterWave driver."); module_param_array(midi, int, NULL, 0444); MODULE_PARM_DESC(midi, "MIDI UART enable for InterWave driver."); module_param_array(pcm_channels, int, NULL, 0444); MODULE_PARM_DESC(pcm_channels, "Reserved PCM channels for InterWave driver."); module_param_array(effect, int, NULL, 0444); MODULE_PARM_DESC(effect, "Effects enable for InterWave driver."); struct snd_interwave { int irq; struct snd_card *card; struct snd_gus_card *gus; struct snd_cs4231 *cs4231; #ifdef SNDRV_STB struct resource *i2c_res; #endif unsigned short gus_status_reg; unsigned short pcm_status_reg; #ifdef CONFIG_PNP struct pnp_dev *dev; #ifdef SNDRV_STB struct pnp_dev *devtc; #endif #endif }; #ifdef CONFIG_PNP static int isa_registered; static int pnp_registered; static struct pnp_card_device_id snd_interwave_pnpids[] = { #ifndef SNDRV_STB /* Gravis UltraSound Plug & Play */ { .id = "GRV0001", .devs = { { .id = "GRV0000" } } }, /* STB SoundRage32 */ { .id = "STB011a", .devs = { { .id = "STB0010" } } }, /* MED3210 */ { .id = "DXP3201", .devs = { { .id = "DXP0010" } } }, /* Dynasonic Pro */ /* This device also have CDC1117:DynaSonix Pro Audio Effects Processor */ { .id = "CDC1111", .devs = { { .id = "CDC1112" } } }, /* Panasonic PCA761AW Audio Card */ { .id = "ADV55ff", .devs = { { .id = "ADV0010" } } }, /* InterWave STB without TEA6330T */ { .id = "ADV550a", .devs = { { .id = "ADV0010" } } }, #else /* InterWave STB with TEA6330T */ { .id = "ADV550a", .devs = { { .id = "ADV0010" }, { .id = "ADV0015" } } }, #endif { .id = "" } }; MODULE_DEVICE_TABLE(pnp_card, snd_interwave_pnpids); #endif /* CONFIG_PNP */ #ifdef SNDRV_STB static void snd_interwave_i2c_setlines(struct snd_i2c_bus *bus, int ctrl, int data) { unsigned long port = bus->private_value; #if 0 printk("i2c_setlines - 0x%lx <- %i,%i\n", port, ctrl, data); #endif outb((data << 1) | ctrl, port); udelay(10); } static int snd_interwave_i2c_getclockline(struct snd_i2c_bus *bus) { unsigned long port = bus->private_value; unsigned char res; res = inb(port) & 1; #if 0 printk("i2c_getclockline - 0x%lx -> %i\n", port, res); #endif return res; } static int snd_interwave_i2c_getdataline(struct snd_i2c_bus *bus, int ack) { unsigned long port = bus->private_value; unsigned char res; if (ack) udelay(10); res = (inb(port) & 2) >> 1; #if 0 printk("i2c_getdataline - 0x%lx -> %i\n", port, res); #endif return res; } static struct snd_i2c_bit_ops snd_interwave_i2c_bit_ops = { .setlines = snd_interwave_i2c_setlines, .getclock = snd_interwave_i2c_getclockline, .getdata = snd_interwave_i2c_getdataline, }; static int __devinit snd_interwave_detect_stb(struct snd_interwave *iwcard, struct snd_gus_card * gus, int dev, struct snd_i2c_bus **rbus) { unsigned long port; struct snd_i2c_bus *bus; struct snd_card *card = iwcard->card; char name[32]; int err; *rbus = NULL; port = port_tc[dev]; if (port == SNDRV_AUTO_PORT) { port = 0x350; if (gus->gf1.port == 0x250) { port = 0x360; } while (port <= 0x380) { if ((iwcard->i2c_res = request_region(port, 1, "InterWave (I2C bus)")) != NULL) break; port += 0x10; } } else { iwcard->i2c_res = request_region(port, 1, "InterWave (I2C bus)"); } if (iwcard->i2c_res == NULL) { snd_printk(KERN_ERR "interwave: can't grab i2c bus port\n"); return -ENODEV; } sprintf(name, "InterWave-%i", card->number); if ((err = snd_i2c_bus_create(card, name, NULL, &bus)) < 0) return err; bus->private_value = port; bus->hw_ops.bit = &snd_interwave_i2c_bit_ops; if ((err = snd_tea6330t_detect(bus, 0)) < 0) return err; *rbus = bus; return 0; } #endif static int __devinit snd_interwave_detect(struct snd_interwave *iwcard, struct snd_gus_card * gus, int dev #ifdef SNDRV_STB , struct snd_i2c_bus **rbus #endif ) { unsigned long flags; unsigned char rev1, rev2; int d; snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 0); /* reset GF1 */ if (((d = snd_gf1_i_look8(gus, SNDRV_GF1_GB_RESET)) & 0x07) != 0) { snd_printdd("[0x%lx] check 1 failed - 0x%x\n", gus->gf1.port, d); return -ENODEV; } udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* release reset */ udelay(160); if (((d = snd_gf1_i_look8(gus, SNDRV_GF1_GB_RESET)) & 0x07) != 1) { snd_printdd("[0x%lx] check 2 failed - 0x%x\n", gus->gf1.port, d); return -ENODEV; } spin_lock_irqsave(&gus->reg_lock, flags); rev1 = snd_gf1_look8(gus, SNDRV_GF1_GB_VERSION_NUMBER); snd_gf1_write8(gus, SNDRV_GF1_GB_VERSION_NUMBER, ~rev1); rev2 = snd_gf1_look8(gus, SNDRV_GF1_GB_VERSION_NUMBER); snd_gf1_write8(gus, SNDRV_GF1_GB_VERSION_NUMBER, rev1); spin_unlock_irqrestore(&gus->reg_lock, flags); snd_printdd("[0x%lx] InterWave check - rev1=0x%x, rev2=0x%x\n", gus->gf1.port, rev1, rev2); if ((rev1 & 0xf0) == (rev2 & 0xf0) && (rev1 & 0x0f) != (rev2 & 0x0f)) { snd_printdd("[0x%lx] InterWave check - passed\n", gus->gf1.port); gus->interwave = 1; strcpy(gus->card->shortname, "AMD InterWave"); gus->revision = rev1 >> 4; #ifndef SNDRV_STB return 0; /* ok.. We have an InterWave board */ #else return snd_interwave_detect_stb(iwcard, gus, dev, rbus); #endif } snd_printdd("[0x%lx] InterWave check - failed\n", gus->gf1.port); return -ENODEV; } static irqreturn_t snd_interwave_interrupt(int irq, void *dev_id) { struct snd_interwave *iwcard = dev_id; int loop, max = 5; int handled = 0; do { loop = 0; if (inb(iwcard->gus_status_reg)) { handled = 1; snd_gus_interrupt(irq, iwcard->gus); loop++; } if (inb(iwcard->pcm_status_reg) & 0x01) { /* IRQ bit is set? */ handled = 1; snd_cs4231_interrupt(irq, iwcard->cs4231); loop++; } } while (loop && --max > 0); return IRQ_RETVAL(handled); } static void __devinit snd_interwave_reset(struct snd_gus_card * gus) { snd_gf1_write8(gus, SNDRV_GF1_GB_RESET, 0x00); udelay(160); snd_gf1_write8(gus, SNDRV_GF1_GB_RESET, 0x01); udelay(160); } static void __devinit snd_interwave_bank_sizes(struct snd_gus_card * gus, int *sizes) { unsigned int idx; unsigned int local; unsigned char d; for (idx = 0; idx < 4; idx++) { sizes[idx] = 0; d = 0x55; for (local = idx << 22; local < (idx << 22) + 0x400000; local += 0x40000, d++) { snd_gf1_poke(gus, local, d); snd_gf1_poke(gus, local + 1, d + 1); #if 0 printk("d = 0x%x, local = 0x%x, local + 1 = 0x%x, idx << 22 = 0x%x\n", d, snd_gf1_peek(gus, local), snd_gf1_peek(gus, local + 1), snd_gf1_peek(gus, idx << 22)); #endif if (snd_gf1_peek(gus, local) != d || snd_gf1_peek(gus, local + 1) != d + 1 || snd_gf1_peek(gus, idx << 22) != 0x55) break; sizes[idx]++; } } #if 0 printk("sizes: %i %i %i %i\n", sizes[0], sizes[1], sizes[2], sizes[3]); #endif } struct rom_hdr { /* 000 */ unsigned char iwave[8]; /* 008 */ unsigned char rom_hdr_revision; /* 009 */ unsigned char series_number; /* 010 */ unsigned char series_name[16]; /* 026 */ unsigned char date[10]; /* 036 */ unsigned short vendor_revision_major; /* 038 */ unsigned short vendor_revision_minor; /* 040 */ unsigned int rom_size; /* 044 */ unsigned char copyright[128]; /* 172 */ unsigned char vendor_name[64]; /* 236 */ unsigned char rom_description[128]; /* 364 */ unsigned char pad[147]; /* 511 */ unsigned char csum; }; static void __devinit snd_interwave_detect_memory(struct snd_gus_card * gus) { static unsigned int lmc[13] = { 0x00000001, 0x00000101, 0x01010101, 0x00000401, 0x04040401, 0x00040101, 0x04040101, 0x00000004, 0x00000404, 0x04040404, 0x00000010, 0x00001010, 0x10101010 }; int bank_pos, pages; unsigned int i, lmct; int psizes[4]; unsigned char iwave[8]; unsigned char csum; snd_interwave_reset(gus); snd_gf1_write8(gus, SNDRV_GF1_GB_GLOBAL_MODE, snd_gf1_read8(gus, SNDRV_GF1_GB_GLOBAL_MODE) | 0x01); /* enhanced mode */ snd_gf1_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x01); /* DRAM I/O cycles selected */ snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xff10) | 0x004c); /* ok.. simple test of memory size */ pages = 0; snd_gf1_poke(gus, 0, 0x55); snd_gf1_poke(gus, 1, 0xaa); #if 1 if (snd_gf1_peek(gus, 0) == 0x55 && snd_gf1_peek(gus, 1) == 0xaa) #else if (0) /* ok.. for testing of 0k RAM */ #endif { snd_interwave_bank_sizes(gus, psizes); lmct = (psizes[3] << 24) | (psizes[2] << 16) | (psizes[1] << 8) | psizes[0]; #if 0 printk("lmct = 0x%08x\n", lmct); #endif for (i = 0; i < ARRAY_SIZE(lmc); i++) if (lmct == lmc[i]) { #if 0 printk("found !!! %i\n", i); #endif snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xfff0) | i); snd_interwave_bank_sizes(gus, psizes); break; } if (i >= ARRAY_SIZE(lmc) && !gus->gf1.enh_mode) snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xfff0) | 2); for (i = 0; i < 4; i++) { gus->gf1.mem_alloc.banks_8[i].address = gus->gf1.mem_alloc.banks_16[i].address = i << 22; gus->gf1.mem_alloc.banks_8[i].size = gus->gf1.mem_alloc.banks_16[i].size = psizes[i] << 18; pages += psizes[i]; } } pages <<= 18; gus->gf1.memory = pages; snd_gf1_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x03); /* select ROM */ snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xff1f) | (4 << 5)); gus->gf1.rom_banks = 0; gus->gf1.rom_memory = 0; for (bank_pos = 0; bank_pos < 16L * 1024L * 1024L; bank_pos += 4L * 1024L * 1024L) { for (i = 0; i < 8; ++i) iwave[i] = snd_gf1_peek(gus, bank_pos + i); #ifdef CONFIG_SND_DEBUG_ROM printk(KERN_DEBUG "ROM at 0x%06x = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", bank_pos, iwave[0], iwave[1], iwave[2], iwave[3], iwave[4], iwave[5], iwave[6], iwave[7]); #endif if (strncmp(iwave, "INTRWAVE", 8)) continue; /* first check */ csum = 0; for (i = 0; i < sizeof(struct rom_hdr); i++) csum += snd_gf1_peek(gus, bank_pos + i); #ifdef CONFIG_SND_DEBUG_ROM printk(KERN_DEBUG "ROM checksum = 0x%x (computed)\n", csum); #endif if (csum != 0) continue; /* not valid rom */ gus->gf1.rom_banks++; gus->gf1.rom_present |= 1 << (bank_pos >> 22); gus->gf1.rom_memory = snd_gf1_peek(gus, bank_pos + 40) | (snd_gf1_peek(gus, bank_pos + 41) << 8) | (snd_gf1_peek(gus, bank_pos + 42) << 16) | (snd_gf1_peek(gus, bank_pos + 43) << 24); } #if 0 if (gus->gf1.rom_memory > 0) { if (gus->gf1.rom_banks == 1 && gus->gf1.rom_present == 8) gus->card->type = SNDRV_CARD_TYPE_IW_DYNASONIC; } #endif snd_gf1_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x00); /* select RAM */ if (!gus->gf1.enh_mode) snd_interwave_reset(gus); } static void __devinit snd_interwave_init(int dev, struct snd_gus_card * gus) { unsigned long flags; /* ok.. some InterWave specific initialization */ spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, 0x00); snd_gf1_write8(gus, SNDRV_GF1_GB_COMPATIBILITY, 0x1f); snd_gf1_write8(gus, SNDRV_GF1_GB_DECODE_CONTROL, 0x49); snd_gf1_write8(gus, SNDRV_GF1_GB_VERSION_NUMBER, 0x11); snd_gf1_write8(gus, SNDRV_GF1_GB_MPU401_CONTROL_A, 0x00); snd_gf1_write8(gus, SNDRV_GF1_GB_MPU401_CONTROL_B, 0x30); snd_gf1_write8(gus, SNDRV_GF1_GB_EMULATION_IRQ, 0x00); spin_unlock_irqrestore(&gus->reg_lock, flags); gus->equal_irq = 1; gus->codec_flag = 1; gus->interwave = 1; gus->max_flag = 1; gus->joystick_dac = joystick_dac[dev]; } static struct snd_kcontrol_new snd_interwave_controls[] = { CS4231_DOUBLE("Master Playback Switch", 0, CS4231_LINE_LEFT_OUTPUT, CS4231_LINE_RIGHT_OUTPUT, 7, 7, 1, 1), CS4231_DOUBLE("Master Playback Volume", 0, CS4231_LINE_LEFT_OUTPUT, CS4231_LINE_RIGHT_OUTPUT, 0, 0, 31, 1), CS4231_DOUBLE("Mic Playback Switch", 0, CS4231_LEFT_MIC_INPUT, CS4231_RIGHT_MIC_INPUT, 7, 7, 1, 1), CS4231_DOUBLE("Mic Playback Volume", 0, CS4231_LEFT_MIC_INPUT, CS4231_RIGHT_MIC_INPUT, 0, 0, 31, 1) }; static int __devinit snd_interwave_mixer(struct snd_cs4231 *chip) { struct snd_card *card = chip->card; struct snd_ctl_elem_id id1, id2; unsigned int idx; int err; memset(&id1, 0, sizeof(id1)); memset(&id2, 0, sizeof(id2)); id1.iface = id2.iface = SNDRV_CTL_ELEM_IFACE_MIXER; #if 0 /* remove mono microphone controls */ strcpy(id1.name, "Mic Playback Switch"); if ((err = snd_ctl_remove_id(card, &id1)) < 0) return err; strcpy(id1.name, "Mic Playback Volume"); if ((err = snd_ctl_remove_id(card, &id1)) < 0) return err; #endif /* add new master and mic controls */ for (idx = 0; idx < ARRAY_SIZE(snd_interwave_controls); idx++) if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_interwave_controls[idx], chip))) < 0) return err; snd_cs4231_out(chip, CS4231_LINE_LEFT_OUTPUT, 0x9f); snd_cs4231_out(chip, CS4231_LINE_RIGHT_OUTPUT, 0x9f); snd_cs4231_out(chip, CS4231_LEFT_MIC_INPUT, 0x9f); snd_cs4231_out(chip, CS4231_RIGHT_MIC_INPUT, 0x9f); /* reassign AUXA to SYNTHESIZER */ strcpy(id1.name, "Aux Playback Switch"); strcpy(id2.name, "Synth Playback Switch"); if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) return err; strcpy(id1.name, "Aux Playback Volume"); strcpy(id2.name, "Synth Playback Volume"); if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) return err; /* reassign AUXB to CD */ strcpy(id1.name, "Aux Playback Switch"); id1.index = 1; strcpy(id2.name, "CD Playback Switch"); if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) return err; strcpy(id1.name, "Aux Playback Volume"); strcpy(id2.name, "CD Playback Volume"); if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) return err; return 0; } #ifdef CONFIG_PNP static int __devinit snd_interwave_pnp(int dev, struct snd_interwave *iwcard, struct pnp_card_link *card, const struct pnp_card_device_id *id) { struct pnp_dev *pdev; int err; iwcard->dev = pnp_request_card_device(card, id->devs[0].id, NULL); if (iwcard->dev == NULL) return -EBUSY; #ifdef SNDRV_STB iwcard->devtc = pnp_request_card_device(card, id->devs[1].id, NULL); if (iwcard->devtc == NULL) return -EBUSY; #endif /* Synth & Codec initialization */ pdev = iwcard->dev; err = pnp_activate_dev(pdev); if (err < 0) { snd_printk(KERN_ERR "InterWave PnP configure failure (out of resources?)\n"); return err; } if (pnp_port_start(pdev, 0) + 0x100 != pnp_port_start(pdev, 1) || pnp_port_start(pdev, 0) + 0x10c != pnp_port_start(pdev, 2)) { snd_printk(KERN_ERR "PnP configure failure (wrong ports)\n"); return -ENOENT; } port[dev] = pnp_port_start(pdev, 0); dma1[dev] = pnp_dma(pdev, 0); if (dma2[dev] >= 0) dma2[dev] = pnp_dma(pdev, 1); irq[dev] = pnp_irq(pdev, 0); snd_printdd("isapnp IW: sb port=0x%llx, gf1 port=0x%llx, codec port=0x%llx\n", (unsigned long long)pnp_port_start(pdev, 0), (unsigned long long)pnp_port_start(pdev, 1), (unsigned long long)pnp_port_start(pdev, 2)); snd_printdd("isapnp IW: dma1=%i, dma2=%i, irq=%i\n", dma1[dev], dma2[dev], irq[dev]); #ifdef SNDRV_STB /* Tone Control initialization */ pdev = iwcard->devtc; err = pnp_activate_dev(pdev); if (err < 0) { snd_printk(KERN_ERR "InterWave ToneControl PnP configure failure (out of resources?)\n"); return err; } port_tc[dev] = pnp_port_start(pdev, 0); snd_printdd("isapnp IW: tone control port=0x%lx\n", port_tc[dev]); #endif return 0; } #endif /* CONFIG_PNP */ static void snd_interwave_free(struct snd_card *card) { struct snd_interwave *iwcard = card->private_data; if (iwcard == NULL) return; #ifdef SNDRV_STB release_and_free_resource(iwcard->i2c_res); #endif if (iwcard->irq >= 0) free_irq(iwcard->irq, (void *)iwcard); } static struct snd_card *snd_interwave_card_new(int dev) { struct snd_card *card; struct snd_interwave *iwcard; card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(struct snd_interwave)); if (card == NULL) return NULL; iwcard = card->private_data; iwcard->card = card; iwcard->irq = -1; card->private_free = snd_interwave_free; return card; } static int __devinit snd_interwave_probe(struct snd_card *card, int dev) { int xirq, xdma1, xdma2; struct snd_interwave *iwcard = card->private_data; struct snd_cs4231 *cs4231; struct snd_gus_card *gus; #ifdef SNDRV_STB struct snd_i2c_bus *i2c_bus; #endif struct snd_pcm *pcm; char *str; int err; xirq = irq[dev]; xdma1 = dma1[dev]; xdma2 = dma2[dev]; if ((err = snd_gus_create(card, port[dev], -xirq, xdma1, xdma2, 0, 32, pcm_channels[dev], effect[dev], &gus)) < 0) return err; if ((err = snd_interwave_detect(iwcard, gus, dev #ifdef SNDRV_STB , &i2c_bus #endif )) < 0) return err; iwcard->gus_status_reg = gus->gf1.reg_irqstat; iwcard->pcm_status_reg = gus->gf1.port + 0x10c + 2; snd_interwave_init(dev, gus); snd_interwave_detect_memory(gus); if ((err = snd_gus_initialize(gus)) < 0) return err; if (request_irq(xirq, snd_interwave_interrupt, IRQF_DISABLED, "InterWave", iwcard)) { snd_printk(KERN_ERR PFX "unable to grab IRQ %d\n", xirq); return -EBUSY; } iwcard->irq = xirq; if ((err = snd_cs4231_create(card, gus->gf1.port + 0x10c, -1, xirq, xdma2 < 0 ? xdma1 : xdma2, xdma1, CS4231_HW_INTERWAVE, CS4231_HWSHARE_IRQ | CS4231_HWSHARE_DMA1 | CS4231_HWSHARE_DMA2, &cs4231)) < 0) return err; if ((err = snd_cs4231_pcm(cs4231, 0, &pcm)) < 0) return err; sprintf(pcm->name + strlen(pcm->name), " rev %c", gus->revision + 'A'); strcat(pcm->name, " (codec)"); if ((err = snd_cs4231_timer(cs4231, 2, NULL)) < 0) return err; if ((err = snd_cs4231_mixer(cs4231)) < 0) return err; if (pcm_channels[dev] > 0) { if ((err = snd_gf1_pcm_new(gus, 1, 1, NULL)) < 0) return err; } if ((err = snd_interwave_mixer(cs4231)) < 0) return err; #ifdef SNDRV_STB { struct snd_ctl_elem_id id1, id2; memset(&id1, 0, sizeof(id1)); memset(&id2, 0, sizeof(id2)); id1.iface = id2.iface = SNDRV_CTL_ELEM_IFACE_MIXER; strcpy(id1.name, "Master Playback Switch"); strcpy(id2.name, id1.name); id2.index = 1; if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) return err; strcpy(id1.name, "Master Playback Volume"); strcpy(id2.name, id1.name); if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0) return err; if ((err = snd_tea6330t_update_mixer(card, i2c_bus, 0, 1)) < 0) return err; } #endif gus->uart_enable = midi[dev]; if ((err = snd_gf1_rawmidi_new(gus, 0, NULL)) < 0) return err; #ifndef SNDRV_STB str = "AMD InterWave"; if (gus->gf1.rom_banks == 1 && gus->gf1.rom_present == 8) str = "Dynasonic 3-D"; #else str = "InterWave STB"; #endif strcpy(card->driver, str); strcpy(card->shortname, str); sprintf(card->longname, "%s at 0x%lx, irq %i, dma %d", str, gus->gf1.port, xirq, xdma1); if (xdma2 >= 0) sprintf(card->longname + strlen(card->longname), "&%d", xdma2); if ((err = snd_card_register(card)) < 0) return err; iwcard->cs4231 = cs4231; iwcard->gus = gus; return 0; } static int __devinit snd_interwave_isa_probe1(int dev, struct device *devptr) { struct snd_card *card; int err; card = snd_interwave_card_new(dev); if (! card) return -ENOMEM; snd_card_set_dev(card, devptr); if ((err = snd_interwave_probe(card, dev)) < 0) { snd_card_free(card); return err; } dev_set_drvdata(devptr, card); return 0; } static int __devinit snd_interwave_isa_match(struct device *pdev, unsigned int dev) { if (!enable[dev]) return 0; #ifdef CONFIG_PNP if (isapnp[dev]) return 0; #endif return 1; } static int __devinit snd_interwave_isa_probe(struct device *pdev, unsigned int dev) { int err; static int possible_irqs[] = {5, 11, 12, 9, 7, 15, 3, -1}; static int possible_dmas[] = {0, 1, 3, 5, 6, 7, -1}; if (irq[dev] == SNDRV_AUTO_IRQ) { if ((irq[dev] = snd_legacy_find_free_irq(possible_irqs)) < 0) { snd_printk(KERN_ERR PFX "unable to find a free IRQ\n"); return -EBUSY; } } if (dma1[dev] == SNDRV_AUTO_DMA) { if ((dma1[dev] = snd_legacy_find_free_dma(possible_dmas)) < 0) { snd_printk(KERN_ERR PFX "unable to find a free DMA1\n"); return -EBUSY; } } if (dma2[dev] == SNDRV_AUTO_DMA) { if ((dma2[dev] = snd_legacy_find_free_dma(possible_dmas)) < 0) { snd_printk(KERN_ERR PFX "unable to find a free DMA2\n"); return -EBUSY; } } if (port[dev] != SNDRV_AUTO_PORT) return snd_interwave_isa_probe1(dev, pdev); else { static long possible_ports[] = {0x210, 0x220, 0x230, 0x240, 0x250, 0x260}; int i; for (i = 0; i < ARRAY_SIZE(possible_ports); i++) { port[dev] = possible_ports[i]; err = snd_interwave_isa_probe1(dev, pdev); if (! err) return 0; } return err; } } static int __devexit snd_interwave_isa_remove(struct device *devptr, unsigned int dev) { snd_card_free(dev_get_drvdata(devptr)); dev_set_drvdata(devptr, NULL); return 0; } static struct isa_driver snd_interwave_driver = { .match = snd_interwave_isa_match, .probe = snd_interwave_isa_probe, .remove = __devexit_p(snd_interwave_isa_remove), /* FIXME: suspend,resume */ .driver = { .name = INTERWAVE_DRIVER }, }; #ifdef CONFIG_PNP static int __devinit snd_interwave_pnp_detect(struct pnp_card_link *pcard, const struct pnp_card_device_id *pid) { static int dev; struct snd_card *card; int res; for ( ; dev < SNDRV_CARDS; dev++) { if (enable[dev] && isapnp[dev]) break; } if (dev >= SNDRV_CARDS) return -ENODEV; card = snd_interwave_card_new(dev); if (! card) return -ENOMEM; if ((res = snd_interwave_pnp(dev, card->private_data, pcard, pid)) < 0) { snd_card_free(card); return res; } snd_card_set_dev(card, &pcard->card->dev); if ((res = snd_interwave_probe(card, dev)) < 0) { snd_card_free(card); return res; } pnp_set_card_drvdata(pcard, card); dev++; return 0; } static void __devexit snd_interwave_pnp_remove(struct pnp_card_link * pcard) { snd_card_free(pnp_get_card_drvdata(pcard)); pnp_set_card_drvdata(pcard, NULL); } static struct pnp_card_driver interwave_pnpc_driver = { .flags = PNP_DRIVER_RES_DISABLE, .name = INTERWAVE_PNP_DRIVER, .id_table = snd_interwave_pnpids, .probe = snd_interwave_pnp_detect, .remove = __devexit_p(snd_interwave_pnp_remove), /* FIXME: suspend,resume */ }; #endif /* CONFIG_PNP */ static int __init alsa_card_interwave_init(void) { int err; err = isa_register_driver(&snd_interwave_driver, SNDRV_CARDS); #ifdef CONFIG_PNP if (!err) isa_registered = 1; err = pnp_register_card_driver(&interwave_pnpc_driver); if (!err) pnp_registered = 1; if (isa_registered) err = 0; #endif return err; } static void __exit alsa_card_interwave_exit(void) { #ifdef CONFIG_PNP if (pnp_registered) pnp_unregister_card_driver(&interwave_pnpc_driver); if (isa_registered) #endif isa_unregister_driver(&snd_interwave_driver); } module_init(alsa_card_interwave_init) module_exit(alsa_card_interwave_exit)
gpl-2.0
ssanglee/capstone
Linux-Kernel/drivers/gpu/drm/nouveau/core/subdev/device/nvc0.c
26
14734
/* * Copyright 2012 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Authors: Ben Skeggs */ #include <subdev/device.h> #include <subdev/bios.h> #include <subdev/bus.h> #include <subdev/gpio.h> #include <subdev/i2c.h> #include <subdev/clock.h> #include <subdev/therm.h> #include <subdev/mxm.h> #include <subdev/devinit.h> #include <subdev/mc.h> #include <subdev/timer.h> #include <subdev/fb.h> #include <subdev/ltcg.h> #include <subdev/ibus.h> #include <subdev/instmem.h> #include <subdev/vm.h> #include <subdev/bar.h> #include <engine/dmaobj.h> #include <engine/fifo.h> #include <engine/software.h> #include <engine/graph.h> #include <engine/vp.h> #include <engine/bsp.h> #include <engine/ppp.h> #include <engine/copy.h> #include <engine/disp.h> int nvc0_identify(struct nouveau_device *device) { switch (device->chipset) { case 0xc0: device->cname = "GF100"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_COPY1 ] = &nvc0_copy1_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xc4: device->cname = "GF104"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_COPY1 ] = &nvc0_copy1_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xc3: device->cname = "GF106"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xce: device->cname = "GF114"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_COPY1 ] = &nvc0_copy1_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xcf: device->cname = "GF116"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_COPY1 ] = &nvc0_copy1_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xc1: device->cname = "GF108"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xc8: device->cname = "GF110"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nv50_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nv94_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nva3_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvc0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_COPY1 ] = &nvc0_copy1_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nva3_disp_oclass; break; case 0xd9: device->cname = "GF119"; device->oclass[NVDEV_SUBDEV_VBIOS ] = &nouveau_bios_oclass; device->oclass[NVDEV_SUBDEV_GPIO ] = &nvd0_gpio_oclass; device->oclass[NVDEV_SUBDEV_I2C ] = &nvd0_i2c_oclass; device->oclass[NVDEV_SUBDEV_CLOCK ] = &nvc0_clock_oclass; device->oclass[NVDEV_SUBDEV_THERM ] = &nvd0_therm_oclass; device->oclass[NVDEV_SUBDEV_MXM ] = &nv50_mxm_oclass; device->oclass[NVDEV_SUBDEV_DEVINIT] = &nv50_devinit_oclass; device->oclass[NVDEV_SUBDEV_MC ] = &nvc0_mc_oclass; device->oclass[NVDEV_SUBDEV_BUS ] = &nvc0_bus_oclass; device->oclass[NVDEV_SUBDEV_TIMER ] = &nv04_timer_oclass; device->oclass[NVDEV_SUBDEV_FB ] = &nvc0_fb_oclass; device->oclass[NVDEV_SUBDEV_LTCG ] = &nvc0_ltcg_oclass; device->oclass[NVDEV_SUBDEV_IBUS ] = &nvc0_ibus_oclass; device->oclass[NVDEV_SUBDEV_INSTMEM] = &nv50_instmem_oclass; device->oclass[NVDEV_SUBDEV_VM ] = &nvc0_vmmgr_oclass; device->oclass[NVDEV_SUBDEV_BAR ] = &nvc0_bar_oclass; device->oclass[NVDEV_ENGINE_DMAOBJ ] = &nvd0_dmaeng_oclass; device->oclass[NVDEV_ENGINE_FIFO ] = &nvc0_fifo_oclass; device->oclass[NVDEV_ENGINE_SW ] = &nvc0_software_oclass; device->oclass[NVDEV_ENGINE_GR ] = &nvc0_graph_oclass; device->oclass[NVDEV_ENGINE_VP ] = &nvc0_vp_oclass; device->oclass[NVDEV_ENGINE_BSP ] = &nvc0_bsp_oclass; device->oclass[NVDEV_ENGINE_PPP ] = &nvc0_ppp_oclass; device->oclass[NVDEV_ENGINE_COPY0 ] = &nvc0_copy0_oclass; device->oclass[NVDEV_ENGINE_DISP ] = &nvd0_disp_oclass; break; default: nv_fatal(device, "unknown Fermi chipset\n"); return -EINVAL; } return 0; }
gpl-2.0
free5ty1e/reicast-emulator
shell/linux-deps/include/X11/Xtrans/transport.c
26
2778
/* Copyright 1993, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * Copyright 1993, 1994 NCR Corporation - Dayton, Ohio, USA * * All Rights Reserved * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name NCR not be used in advertising * or publicity pertaining to distribution of the software without specific, * written prior permission. NCR makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * NCR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN * NO EVENT SHALL NCR BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifdef XSERV_t #include "os.h" #else #include <stdlib.h> #define xalloc(_size) malloc(_size) #define xcalloc(_num,_size) calloc(_num,_size) #define xrealloc(_ptr,_size) realloc(_ptr,_size) #define xfree(_ptr) free(_ptr) #endif #include "Xtransint.h" #ifdef LOCALCONN #include "Xtranslcl.c" #endif #if defined(TCPCONN) || defined(UNIXCONN) #include "Xtranssock.c" #endif #ifdef STREAMSCONN #include "Xtranstli.c" #endif #include "Xtrans.c" #include "Xtransutil.c"
gpl-2.0
xobs/barebox-novena
common/s_record.c
26
4167
/* * (C) Copyright 2000 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <common.h> #include <s_record.h> static int hex1_bin (char c); static int hex2_bin (char *s); int srec_decode (char *input, int *count, ulong *addr, char *data) { int i; int v; /* conversion buffer */ int srec_type; /* S-Record type */ unsigned char chksum; /* buffer for checksum */ chksum = 0; /* skip anything before 'S', and the 'S' itself. * Return error if not found */ for (; *input; ++input) { if (*input == 'S') { /* skip 'S' */ ++input; break; } } if (*input == '\0') { /* no more data? */ return (SREC_EMPTY); } v = *input++; /* record type */ if ((*count = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } chksum += *count; input += 2; switch (v) { /* record type */ case '0': /* start record */ srec_type = SREC_START; /* 2 byte addr field */ *count -= 3; /* - checksum and addr */ break; case '1': srec_type = SREC_DATA2; /* 2 byte addr field */ *count -= 3; /* - checksum and addr */ break; case '2': srec_type = SREC_DATA3; /* 3 byte addr field */ *count -= 4; /* - checksum and addr */ break; case '3': /* data record with a */ srec_type = SREC_DATA4; /* 4 byte addr field */ *count -= 5; /* - checksum and addr */ break; /*** case '4' ***/ case '5': /* count record, addr field contains */ srec_type = SREC_COUNT; /* a 2 byte record counter */ *count = 0; /* no data */ break; /*** case '6' -- not used ***/ case '7': /* end record with a */ srec_type = SREC_END4; /* 4 byte addr field */ *count -= 5; /* - checksum and addr */ break; case '8': /* end record with a */ srec_type = SREC_END3; /* 3 byte addr field */ *count -= 4; /* - checksum and addr */ break; case '9': /* end record with a */ srec_type = SREC_END2; /* 2 byte addr field */ *count -= 3; /* - checksum and addr */ break; default: return (SREC_E_BADTYPE); } /* read address field */ *addr = 0; switch (v) { case '3': /* 4 byte addr field */ case '7': if ((v = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } *addr += v; chksum += v; input += 2; /* FALL THRU */ case '2': /* 3 byte addr field */ case '8': if ((v = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } *addr <<= 8; *addr += v; chksum += v; input += 2; /* FALL THRU */ case '0': /* 2 byte addr field */ case '1': case '5': case '9': if ((v = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } *addr <<= 8; *addr += v; chksum += v; input += 2; if ((v = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } *addr <<= 8; *addr += v; chksum += v; input += 2; break; default: return (SREC_E_BADTYPE); } /* convert data and calculate checksum */ for (i=0; i < *count; ++i) { if ((v = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } data[i] = v; chksum += v; input += 2; } /* read anc check checksum */ if ((v = hex2_bin(input)) < 0) { return (SREC_E_NOSREC); } if ((unsigned char)v != (unsigned char)~chksum) { return (SREC_E_BADCHKS); } return (srec_type); } static int hex1_bin (char c) { if (c >= '0' && c <= '9') return (c - '0'); if (c >= 'a' && c <= 'f') return (c + 10 - 'a'); if (c >= 'A' && c <= 'F') return (c + 10 - 'A'); return (-1); } static int hex2_bin (char *s) { int i, j; if ((i = hex1_bin(*s++)) < 0) { return (-1); } if ((j = hex1_bin(*s)) < 0) { return (-1); } return ((i<<4) + j); }
gpl-2.0
librae8226/linux-2.6.30.4
drivers/char/tty_ldisc.c
26
18152
#include <linux/types.h> #include <linux/major.h> #include <linux/errno.h> #include <linux/signal.h> #include <linux/fcntl.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/devpts_fs.h> #include <linux/file.h> #include <linux/console.h> #include <linux/timer.h> #include <linux/ctype.h> #include <linux/kd.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/module.h> #include <linux/smp_lock.h> #include <linux/device.h> #include <linux/wait.h> #include <linux/bitops.h> #include <linux/delay.h> #include <linux/seq_file.h> #include <linux/uaccess.h> #include <asm/system.h> #include <linux/kbd_kern.h> #include <linux/vt_kern.h> #include <linux/selection.h> #include <linux/kmod.h> #include <linux/nsproxy.h> /* * This guards the refcounted line discipline lists. The lock * must be taken with irqs off because there are hangup path * callers who will do ldisc lookups and cannot sleep. */ static DEFINE_SPINLOCK(tty_ldisc_lock); static DECLARE_WAIT_QUEUE_HEAD(tty_ldisc_wait); /* Line disc dispatch table */ static struct tty_ldisc_ops *tty_ldiscs[NR_LDISCS]; /** * tty_register_ldisc - install a line discipline * @disc: ldisc number * @new_ldisc: pointer to the ldisc object * * Installs a new line discipline into the kernel. The discipline * is set up as unreferenced and then made available to the kernel * from this point onwards. * * Locking: * takes tty_ldisc_lock to guard against ldisc races */ int tty_register_ldisc(int disc, struct tty_ldisc_ops *new_ldisc) { unsigned long flags; int ret = 0; if (disc < N_TTY || disc >= NR_LDISCS) return -EINVAL; spin_lock_irqsave(&tty_ldisc_lock, flags); tty_ldiscs[disc] = new_ldisc; new_ldisc->num = disc; new_ldisc->refcount = 0; spin_unlock_irqrestore(&tty_ldisc_lock, flags); return ret; } EXPORT_SYMBOL(tty_register_ldisc); /** * tty_unregister_ldisc - unload a line discipline * @disc: ldisc number * @new_ldisc: pointer to the ldisc object * * Remove a line discipline from the kernel providing it is not * currently in use. * * Locking: * takes tty_ldisc_lock to guard against ldisc races */ int tty_unregister_ldisc(int disc) { unsigned long flags; int ret = 0; if (disc < N_TTY || disc >= NR_LDISCS) return -EINVAL; spin_lock_irqsave(&tty_ldisc_lock, flags); if (tty_ldiscs[disc]->refcount) ret = -EBUSY; else tty_ldiscs[disc] = NULL; spin_unlock_irqrestore(&tty_ldisc_lock, flags); return ret; } EXPORT_SYMBOL(tty_unregister_ldisc); /** * tty_ldisc_try_get - try and reference an ldisc * @disc: ldisc number * @ld: tty ldisc structure to complete * * Attempt to open and lock a line discipline into place. Return * the line discipline refcounted and assigned in ld. On an error * report the error code back */ static int tty_ldisc_try_get(int disc, struct tty_ldisc *ld) { unsigned long flags; struct tty_ldisc_ops *ldops; int err = -EINVAL; spin_lock_irqsave(&tty_ldisc_lock, flags); ld->ops = NULL; ldops = tty_ldiscs[disc]; /* Check the entry is defined */ if (ldops) { /* If the module is being unloaded we can't use it */ if (!try_module_get(ldops->owner)) err = -EAGAIN; else { /* lock it */ ldops->refcount++; ld->ops = ldops; err = 0; } } spin_unlock_irqrestore(&tty_ldisc_lock, flags); return err; } /** * tty_ldisc_get - take a reference to an ldisc * @disc: ldisc number * @ld: tty line discipline structure to use * * Takes a reference to a line discipline. Deals with refcounts and * module locking counts. Returns NULL if the discipline is not available. * Returns a pointer to the discipline and bumps the ref count if it is * available * * Locking: * takes tty_ldisc_lock to guard against ldisc races */ static int tty_ldisc_get(int disc, struct tty_ldisc *ld) { int err; if (disc < N_TTY || disc >= NR_LDISCS) return -EINVAL; err = tty_ldisc_try_get(disc, ld); if (err < 0) { request_module("tty-ldisc-%d", disc); err = tty_ldisc_try_get(disc, ld); } return err; } /** * tty_ldisc_put - drop ldisc reference * @disc: ldisc number * * Drop a reference to a line discipline. Manage refcounts and * module usage counts * * Locking: * takes tty_ldisc_lock to guard against ldisc races */ static void tty_ldisc_put(struct tty_ldisc_ops *ld) { unsigned long flags; int disc = ld->num; BUG_ON(disc < N_TTY || disc >= NR_LDISCS); spin_lock_irqsave(&tty_ldisc_lock, flags); ld = tty_ldiscs[disc]; BUG_ON(ld->refcount == 0); ld->refcount--; module_put(ld->owner); spin_unlock_irqrestore(&tty_ldisc_lock, flags); } static void * tty_ldiscs_seq_start(struct seq_file *m, loff_t *pos) { return (*pos < NR_LDISCS) ? pos : NULL; } static void * tty_ldiscs_seq_next(struct seq_file *m, void *v, loff_t *pos) { (*pos)++; return (*pos < NR_LDISCS) ? pos : NULL; } static void tty_ldiscs_seq_stop(struct seq_file *m, void *v) { } static int tty_ldiscs_seq_show(struct seq_file *m, void *v) { int i = *(loff_t *)v; struct tty_ldisc ld; if (tty_ldisc_get(i, &ld) < 0) return 0; seq_printf(m, "%-10s %2d\n", ld.ops->name ? ld.ops->name : "???", i); tty_ldisc_put(ld.ops); return 0; } static const struct seq_operations tty_ldiscs_seq_ops = { .start = tty_ldiscs_seq_start, .next = tty_ldiscs_seq_next, .stop = tty_ldiscs_seq_stop, .show = tty_ldiscs_seq_show, }; static int proc_tty_ldiscs_open(struct inode *inode, struct file *file) { return seq_open(file, &tty_ldiscs_seq_ops); } const struct file_operations tty_ldiscs_proc_fops = { .owner = THIS_MODULE, .open = proc_tty_ldiscs_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /** * tty_ldisc_assign - set ldisc on a tty * @tty: tty to assign * @ld: line discipline * * Install an instance of a line discipline into a tty structure. The * ldisc must have a reference count above zero to ensure it remains/ * The tty instance refcount starts at zero. * * Locking: * Caller must hold references */ static void tty_ldisc_assign(struct tty_struct *tty, struct tty_ldisc *ld) { ld->refcount = 0; tty->ldisc = *ld; } /** * tty_ldisc_try - internal helper * @tty: the tty * * Make a single attempt to grab and bump the refcount on * the tty ldisc. Return 0 on failure or 1 on success. This is * used to implement both the waiting and non waiting versions * of tty_ldisc_ref * * Locking: takes tty_ldisc_lock */ static int tty_ldisc_try(struct tty_struct *tty) { unsigned long flags; struct tty_ldisc *ld; int ret = 0; spin_lock_irqsave(&tty_ldisc_lock, flags); ld = &tty->ldisc; if (test_bit(TTY_LDISC, &tty->flags)) { ld->refcount++; ret = 1; } spin_unlock_irqrestore(&tty_ldisc_lock, flags); return ret; } /** * tty_ldisc_ref_wait - wait for the tty ldisc * @tty: tty device * * Dereference the line discipline for the terminal and take a * reference to it. If the line discipline is in flux then * wait patiently until it changes. * * Note: Must not be called from an IRQ/timer context. The caller * must also be careful not to hold other locks that will deadlock * against a discipline change, such as an existing ldisc reference * (which we check for) * * Locking: call functions take tty_ldisc_lock */ struct tty_ldisc *tty_ldisc_ref_wait(struct tty_struct *tty) { /* wait_event is a macro */ wait_event(tty_ldisc_wait, tty_ldisc_try(tty)); WARN_ON(tty->ldisc.refcount == 0); return &tty->ldisc; } EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait); /** * tty_ldisc_ref - get the tty ldisc * @tty: tty device * * Dereference the line discipline for the terminal and take a * reference to it. If the line discipline is in flux then * return NULL. Can be called from IRQ and timer functions. * * Locking: called functions take tty_ldisc_lock */ struct tty_ldisc *tty_ldisc_ref(struct tty_struct *tty) { if (tty_ldisc_try(tty)) return &tty->ldisc; return NULL; } EXPORT_SYMBOL_GPL(tty_ldisc_ref); /** * tty_ldisc_deref - free a tty ldisc reference * @ld: reference to free up * * Undoes the effect of tty_ldisc_ref or tty_ldisc_ref_wait. May * be called in IRQ context. * * Locking: takes tty_ldisc_lock */ void tty_ldisc_deref(struct tty_ldisc *ld) { unsigned long flags; BUG_ON(ld == NULL); spin_lock_irqsave(&tty_ldisc_lock, flags); if (ld->refcount == 0) printk(KERN_ERR "tty_ldisc_deref: no references.\n"); else ld->refcount--; if (ld->refcount == 0) wake_up(&tty_ldisc_wait); spin_unlock_irqrestore(&tty_ldisc_lock, flags); } EXPORT_SYMBOL_GPL(tty_ldisc_deref); /** * tty_ldisc_enable - allow ldisc use * @tty: terminal to activate ldisc on * * Set the TTY_LDISC flag when the line discipline can be called * again. Do necessary wakeups for existing sleepers. Clear the LDISC * changing flag to indicate any ldisc change is now over. * * Note: nobody should set the TTY_LDISC bit except via this function. * Clearing directly is allowed. */ void tty_ldisc_enable(struct tty_struct *tty) { set_bit(TTY_LDISC, &tty->flags); clear_bit(TTY_LDISC_CHANGING, &tty->flags); wake_up(&tty_ldisc_wait); } /** * tty_set_termios_ldisc - set ldisc field * @tty: tty structure * @num: line discipline number * * This is probably overkill for real world processors but * they are not on hot paths so a little discipline won't do * any harm. * * Locking: takes termios_mutex */ static void tty_set_termios_ldisc(struct tty_struct *tty, int num) { mutex_lock(&tty->termios_mutex); tty->termios->c_line = num; mutex_unlock(&tty->termios_mutex); } /** * tty_ldisc_restore - helper for tty ldisc change * @tty: tty to recover * @old: previous ldisc * * Restore the previous line discipline or N_TTY when a line discipline * change fails due to an open error */ static void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old) { char buf[64]; struct tty_ldisc new_ldisc; /* There is an outstanding reference here so this is safe */ tty_ldisc_get(old->ops->num, old); tty_ldisc_assign(tty, old); tty_set_termios_ldisc(tty, old->ops->num); if (old->ops->open && (old->ops->open(tty) < 0)) { tty_ldisc_put(old->ops); /* This driver is always present */ if (tty_ldisc_get(N_TTY, &new_ldisc) < 0) panic("n_tty: get"); tty_ldisc_assign(tty, &new_ldisc); tty_set_termios_ldisc(tty, N_TTY); if (new_ldisc.ops->open) { int r = new_ldisc.ops->open(tty); if (r < 0) panic("Couldn't open N_TTY ldisc for " "%s --- error %d.", tty_name(tty, buf), r); } } } /** * tty_set_ldisc - set line discipline * @tty: the terminal to set * @ldisc: the line discipline * * Set the discipline of a tty line. Must be called from a process * context. * * Locking: takes tty_ldisc_lock. * called functions take termios_mutex */ int tty_set_ldisc(struct tty_struct *tty, int ldisc) { int retval; struct tty_ldisc o_ldisc, new_ldisc; int work; unsigned long flags; struct tty_struct *o_tty; restart: /* This is a bit ugly for now but means we can break the 'ldisc is part of the tty struct' assumption later */ retval = tty_ldisc_get(ldisc, &new_ldisc); if (retval) return retval; /* * Problem: What do we do if this blocks ? */ tty_wait_until_sent(tty, 0); if (tty->ldisc.ops->num == ldisc) { tty_ldisc_put(new_ldisc.ops); return 0; } /* * No more input please, we are switching. The new ldisc * will update this value in the ldisc open function */ tty->receive_room = 0; o_ldisc = tty->ldisc; o_tty = tty->link; /* * Make sure we don't change while someone holds a * reference to the line discipline. The TTY_LDISC bit * prevents anyone taking a reference once it is clear. * We need the lock to avoid racing reference takers. * * We must clear the TTY_LDISC bit here to avoid a livelock * with a userspace app continually trying to use the tty in * parallel to the change and re-referencing the tty. */ clear_bit(TTY_LDISC, &tty->flags); if (o_tty) clear_bit(TTY_LDISC, &o_tty->flags); spin_lock_irqsave(&tty_ldisc_lock, flags); if (tty->ldisc.refcount || (o_tty && o_tty->ldisc.refcount)) { if (tty->ldisc.refcount) { /* Free the new ldisc we grabbed. Must drop the lock first. */ spin_unlock_irqrestore(&tty_ldisc_lock, flags); tty_ldisc_put(o_ldisc.ops); /* * There are several reasons we may be busy, including * random momentary I/O traffic. We must therefore * retry. We could distinguish between blocking ops * and retries if we made tty_ldisc_wait() smarter. * That is up for discussion. */ if (wait_event_interruptible(tty_ldisc_wait, tty->ldisc.refcount == 0) < 0) return -ERESTARTSYS; goto restart; } if (o_tty && o_tty->ldisc.refcount) { spin_unlock_irqrestore(&tty_ldisc_lock, flags); tty_ldisc_put(o_tty->ldisc.ops); if (wait_event_interruptible(tty_ldisc_wait, o_tty->ldisc.refcount == 0) < 0) return -ERESTARTSYS; goto restart; } } /* * If the TTY_LDISC bit is set, then we are racing against * another ldisc change */ if (test_bit(TTY_LDISC_CHANGING, &tty->flags)) { struct tty_ldisc *ld; spin_unlock_irqrestore(&tty_ldisc_lock, flags); tty_ldisc_put(new_ldisc.ops); ld = tty_ldisc_ref_wait(tty); tty_ldisc_deref(ld); goto restart; } /* * This flag is used to avoid two parallel ldisc changes. Once * open and close are fine grained locked this may work better * as a mutex shared with the open/close/hup paths */ set_bit(TTY_LDISC_CHANGING, &tty->flags); if (o_tty) set_bit(TTY_LDISC_CHANGING, &o_tty->flags); spin_unlock_irqrestore(&tty_ldisc_lock, flags); /* * From this point on we know nobody has an ldisc * usage reference, nor can they obtain one until * we say so later on. */ work = cancel_delayed_work(&tty->buf.work); /* * Wait for ->hangup_work and ->buf.work handlers to terminate * MUST NOT hold locks here. */ flush_scheduled_work(); /* Shutdown the current discipline. */ if (o_ldisc.ops->close) (o_ldisc.ops->close)(tty); /* Now set up the new line discipline. */ tty_ldisc_assign(tty, &new_ldisc); tty_set_termios_ldisc(tty, ldisc); if (new_ldisc.ops->open) retval = (new_ldisc.ops->open)(tty); if (retval < 0) { tty_ldisc_put(new_ldisc.ops); tty_ldisc_restore(tty, &o_ldisc); } /* At this point we hold a reference to the new ldisc and a a reference to the old ldisc. If we ended up flipping back to the existing ldisc we have two references to it */ if (tty->ldisc.ops->num != o_ldisc.ops->num && tty->ops->set_ldisc) tty->ops->set_ldisc(tty); tty_ldisc_put(o_ldisc.ops); /* * Allow ldisc referencing to occur as soon as the driver * ldisc callback completes. */ tty_ldisc_enable(tty); if (o_tty) tty_ldisc_enable(o_tty); /* Restart it in case no characters kick it off. Safe if already running */ if (work) schedule_delayed_work(&tty->buf.work, 1); return retval; } /** * tty_ldisc_setup - open line discipline * @tty: tty being shut down * @o_tty: pair tty for pty/tty pairs * * Called during the initial open of a tty/pty pair in order to set up the * line discplines and bind them to the tty. */ int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty) { struct tty_ldisc *ld = &tty->ldisc; int retval; if (ld->ops->open) { retval = (ld->ops->open)(tty); if (retval) return retval; } if (o_tty && o_tty->ldisc.ops->open) { retval = (o_tty->ldisc.ops->open)(o_tty); if (retval) { if (ld->ops->close) (ld->ops->close)(tty); return retval; } tty_ldisc_enable(o_tty); } tty_ldisc_enable(tty); return 0; } /** * tty_ldisc_release - release line discipline * @tty: tty being shut down * @o_tty: pair tty for pty/tty pairs * * Called during the final close of a tty/pty pair in order to shut down the * line discpline layer. */ void tty_ldisc_release(struct tty_struct *tty, struct tty_struct *o_tty) { unsigned long flags; struct tty_ldisc ld; /* * Prevent flush_to_ldisc() from rescheduling the work for later. Then * kill any delayed work. As this is the final close it does not * race with the set_ldisc code path. */ clear_bit(TTY_LDISC, &tty->flags); cancel_delayed_work(&tty->buf.work); /* * Wait for ->hangup_work and ->buf.work handlers to terminate */ flush_scheduled_work(); /* * Wait for any short term users (we know they are just driver * side waiters as the file is closing so user count on the file * side is zero. */ spin_lock_irqsave(&tty_ldisc_lock, flags); while (tty->ldisc.refcount) { spin_unlock_irqrestore(&tty_ldisc_lock, flags); wait_event(tty_ldisc_wait, tty->ldisc.refcount == 0); spin_lock_irqsave(&tty_ldisc_lock, flags); } spin_unlock_irqrestore(&tty_ldisc_lock, flags); /* * Shutdown the current line discipline, and reset it to N_TTY. * * FIXME: this MUST get fixed for the new reflocking */ if (tty->ldisc.ops->close) (tty->ldisc.ops->close)(tty); tty_ldisc_put(tty->ldisc.ops); /* * Switch the line discipline back */ WARN_ON(tty_ldisc_get(N_TTY, &ld)); tty_ldisc_assign(tty, &ld); tty_set_termios_ldisc(tty, N_TTY); if (o_tty) { /* FIXME: could o_tty be in setldisc here ? */ clear_bit(TTY_LDISC, &o_tty->flags); if (o_tty->ldisc.ops->close) (o_tty->ldisc.ops->close)(o_tty); tty_ldisc_put(o_tty->ldisc.ops); WARN_ON(tty_ldisc_get(N_TTY, &ld)); tty_ldisc_assign(o_tty, &ld); tty_set_termios_ldisc(o_tty, N_TTY); } } /** * tty_ldisc_init - ldisc setup for new tty * @tty: tty being allocated * * Set up the line discipline objects for a newly allocated tty. Note that * the tty structure is not completely set up when this call is made. */ void tty_ldisc_init(struct tty_struct *tty) { struct tty_ldisc ld; if (tty_ldisc_get(N_TTY, &ld) < 0) panic("n_tty: init_tty"); tty_ldisc_assign(tty, &ld); } void tty_ldisc_begin(void) { /* Setup the default TTY line discipline. */ (void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY); }
gpl-2.0
kodibrasil/xbmc
tools/EventClients/Clients/WiiRemote/wiiuse_v0.12/src/nunchuk.c
282
5687
/* * wiiuse * * Written By: * Michael Laforest < para > * Email: < thepara (--AT--) g m a i l [--DOT--] com > * * Copyright 2006-2007 * * This file is part of wiiuse. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * $Header$ * */ /** * @file * @brief Nunchuk expansion device. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "definitions.h" #include "wiiuse_internal.h" #include "dynamics.h" #include "events.h" #include "nunchuk.h" static void nunchuk_pressed_buttons(struct nunchuk_t* nc, byte now); /** * @brief Handle the handshake data from the nunchuk. * * @param nc A pointer to a nunchuk_t structure. * @param data The data read in from the device. * @param len The length of the data block, in bytes. * * @return Returns 1 if handshake was successful, 0 if not. */ int nunchuk_handshake(struct wiimote_t* wm, struct nunchuk_t* nc, byte* data, unsigned short len) { int i; int offset = 0; nc->btns = 0; nc->btns_held = 0; nc->btns_released = 0; /* set the smoothing to the same as the wiimote */ nc->flags = &wm->flags; nc->accel_calib.st_alpha = wm->accel_calib.st_alpha; /* decrypt data */ for (i = 0; i < len; ++i) data[i] = (data[i] ^ 0x17) + 0x17; if (data[offset] == 0xFF) { /* * Sometimes the data returned here is not correct. * This might happen because the wiimote is lagging * behind our initialization sequence. * To fix this just request the handshake again. * * Other times it's just the first 16 bytes are 0xFF, * but since the next 16 bytes are the same, just use * those. */ if (data[offset + 16] == 0xFF) { /* get the calibration data */ byte* handshake_buf = malloc(EXP_HANDSHAKE_LEN * sizeof(byte)); WIIUSE_DEBUG("Nunchuk handshake appears invalid, trying again."); wiiuse_read_data_cb(wm, handshake_expansion, handshake_buf, WM_EXP_MEM_CALIBR, EXP_HANDSHAKE_LEN); return 0; } else offset += 16; } nc->accel_calib.cal_zero.x = data[offset + 0]; nc->accel_calib.cal_zero.y = data[offset + 1]; nc->accel_calib.cal_zero.z = data[offset + 2]; nc->accel_calib.cal_g.x = data[offset + 4]; nc->accel_calib.cal_g.y = data[offset + 5]; nc->accel_calib.cal_g.z = data[offset + 6]; nc->js.max.x = data[offset + 8]; nc->js.min.x = data[offset + 9]; nc->js.center.x = data[offset + 10]; nc->js.max.y = data[offset + 11]; nc->js.min.y = data[offset + 12]; nc->js.center.y = data[offset + 13]; /* default the thresholds to the same as the wiimote */ nc->orient_threshold = wm->orient_threshold; nc->accel_threshold = wm->accel_threshold; /* handshake done */ wm->exp.type = EXP_NUNCHUK; #ifdef WIN32 wm->timeout = WIIMOTE_DEFAULT_TIMEOUT; #endif return 1; } /** * @brief The nunchuk disconnected. * * @param nc A pointer to a nunchuk_t structure. */ void nunchuk_disconnected(struct nunchuk_t* nc) { memset(nc, 0, sizeof(struct nunchuk_t)); } /** * @brief Handle nunchuk event. * * @param nc A pointer to a nunchuk_t structure. * @param msg The message specified in the event packet. */ void nunchuk_event(struct nunchuk_t* nc, byte* msg) { int i; /* decrypt data */ for (i = 0; i < 6; ++i) msg[i] = (msg[i] ^ 0x17) + 0x17; /* get button states */ nunchuk_pressed_buttons(nc, msg[5]); /* calculate joystick state */ calc_joystick_state(&nc->js, msg[0], msg[1]); /* calculate orientation */ nc->accel.x = msg[2]; nc->accel.y = msg[3]; nc->accel.z = msg[4]; calculate_orientation(&nc->accel_calib, &nc->accel, &nc->orient, NUNCHUK_IS_FLAG_SET(nc, WIIUSE_SMOOTHING)); calculate_gforce(&nc->accel_calib, &nc->accel, &nc->gforce); } /** * @brief Find what buttons are pressed. * * @param nc Pointer to a nunchuk_t structure. * @param msg The message byte specified in the event packet. */ static void nunchuk_pressed_buttons(struct nunchuk_t* nc, byte now) { /* message is inverted (0 is active, 1 is inactive) */ now = ~now & NUNCHUK_BUTTON_ALL; /* pressed now & were pressed, then held */ nc->btns_held = (now & nc->btns); /* were pressed or were held & not pressed now, then released */ nc->btns_released = ((nc->btns | nc->btns_held) & ~now); /* buttons pressed now */ nc->btns = now; } /** * @brief Set the orientation event threshold for the nunchuk. * * @param wm Pointer to a wiimote_t structure with a nunchuk attached. * @param threshold The decimal place that should be considered a significant change. * * See wiiuse_set_orient_threshold() for details. */ void wiiuse_set_nunchuk_orient_threshold(struct wiimote_t* wm, float threshold) { if (!wm) return; wm->exp.nunchuk.orient_threshold = threshold; } /** * @brief Set the accelerometer event threshold for the nunchuk. * * @param wm Pointer to a wiimote_t structure with a nunchuk attached. * @param threshold The decimal place that should be considered a significant change. * * See wiiuse_set_orient_threshold() for details. */ void wiiuse_set_nunchuk_accel_threshold(struct wiimote_t* wm, int threshold) { if (!wm) return; wm->exp.nunchuk.accel_threshold = threshold; }
gpl-2.0
raden/Lekiu-CM-kernel
drivers/char/diag/diagfwd_cntl.c
282
9359
/* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/slab.h> #include <linux/diagchar.h> #include <linux/platform_device.h> #include <linux/kmemleak.h> #include <linux/delay.h> #include "diagchar.h" #include "diagfwd.h" #include "diagfwd_cntl.h" /* tracks which peripheral is undergoing SSR */ static uint16_t reg_dirty; #define HDR_SIZ 8 void diag_clean_reg_fn(struct work_struct *work) { struct diag_smd_info *smd_info = container_of(work, struct diag_smd_info, diag_notify_update_smd_work); if (!smd_info) return; pr_debug("diag: clean registration for peripheral: %d\n", smd_info->peripheral); reg_dirty |= smd_info->peripheral_mask; diag_clear_reg(smd_info->peripheral); reg_dirty ^= smd_info->peripheral_mask; smd_info->notify_context = 0; } /* Process the data read from the smd control channel */ int diag_process_smd_cntl_read_data(struct diag_smd_info *smd_info, void *buf, int total_recd) { int data_len = 0, type = -1, count_bytes = 0, j, flag = 0; struct bindpkt_params_per_process *pkt_params = kzalloc(sizeof(struct bindpkt_params_per_process), GFP_KERNEL); struct diag_ctrl_msg *msg; struct cmd_code_range *range; struct bindpkt_params *temp; if (pkt_params == NULL) { pr_alert("diag: In %s, Memory allocation failure\n", __func__); return 0; } if (!smd_info) { pr_err("diag: In %s, No smd info. Not able to read.\n", __func__); kfree(pkt_params); return 0; } while (count_bytes + HDR_SIZ <= total_recd) { type = *(uint32_t *)(buf); data_len = *(uint32_t *)(buf + 4); if (type < DIAG_CTRL_MSG_REG || type > DIAG_CTRL_MSG_LAST) { pr_alert("diag: In %s, Invalid Msg type %d proc %d", __func__, type, smd_info->peripheral); break; } if (data_len < 0 || data_len > total_recd) { pr_alert("diag: In %s, Invalid data len %d, total_recd: %d, proc %d", __func__, data_len, total_recd, smd_info->peripheral); break; } count_bytes = count_bytes+HDR_SIZ+data_len; if (type == DIAG_CTRL_MSG_REG && total_recd >= count_bytes) { msg = buf+HDR_SIZ; range = buf+HDR_SIZ+ sizeof(struct diag_ctrl_msg); pkt_params->count = msg->count_entries; pkt_params->params = kzalloc(pkt_params->count * sizeof(struct bindpkt_params), GFP_KERNEL); if (ZERO_OR_NULL_PTR(pkt_params->params)) { pr_alert("diag: In %s, Memory alloc fail\n", __func__); kfree(pkt_params); return flag; } temp = pkt_params->params; for (j = 0; j < pkt_params->count; j++) { temp->cmd_code = msg->cmd_code; temp->subsys_id = msg->subsysid; temp->client_id = smd_info->peripheral; temp->proc_id = NON_APPS_PROC; temp->cmd_code_lo = range->cmd_code_lo; temp->cmd_code_hi = range->cmd_code_hi; range++; temp++; } flag = 1; /* peripheral undergoing SSR should not * record new registration */ if (!(reg_dirty & smd_info->peripheral_mask)) diagchar_ioctl(NULL, DIAG_IOCTL_COMMAND_REG, (unsigned long)pkt_params); else pr_err("diag: drop reg proc %d\n", smd_info->peripheral); kfree(pkt_params->params); } else if (type == DIAG_CTRL_MSG_FEATURE && total_recd >= count_bytes) { uint8_t feature_mask = 0; int feature_mask_len = *(int *)(buf+8); if (feature_mask_len > 0) { feature_mask = *(uint8_t *)(buf+12); if (smd_info->peripheral == MODEM_DATA) driver->log_on_demand_support = feature_mask & F_DIAG_LOG_ON_DEMAND_RSP_ON_MASTER; /* * If apps supports separate cmd/rsp channels * and the peripheral supports separate cmd/rsp * channels */ if (driver->supports_separate_cmdrsp && (feature_mask & F_DIAG_REQ_RSP_CHANNEL)) driver->separate_cmdrsp [smd_info->peripheral] = ENABLE_SEPARATE_CMDRSP; else driver->separate_cmdrsp [smd_info->peripheral] = DISABLE_SEPARATE_CMDRSP; } flag = 1; } else if (type != DIAG_CTRL_MSG_REG) { flag = 1; } buf = buf + HDR_SIZ + data_len; } kfree(pkt_params); return flag; } void diag_send_diag_mode_update(int real_time) { int i; for (i = 0; i < NUM_SMD_CONTROL_CHANNELS; i++) diag_send_diag_mode_update_by_smd(&driver->smd_cntl[i], real_time); } void diag_send_diag_mode_update_by_smd(struct diag_smd_info *smd_info, int real_time) { struct diag_ctrl_msg_diagmode diagmode; char buf[sizeof(struct diag_ctrl_msg_diagmode)]; int msg_size = sizeof(struct diag_ctrl_msg_diagmode); int wr_size = -ENOMEM, retry_count = 0, timer; /* For now only allow the modem to receive the message */ if (!smd_info || smd_info->type != SMD_CNTL_TYPE || (smd_info->peripheral != MODEM_DATA)) return; mutex_lock(&driver->diag_cntl_mutex); diagmode.ctrl_pkt_id = DIAG_CTRL_MSG_DIAGMODE; diagmode.ctrl_pkt_data_len = 36; diagmode.version = 1; diagmode.sleep_vote = real_time ? 1 : 0; /* * 0 - Disables real-time logging (to prevent * frequent APPS wake-ups, etc.). * 1 - Enable real-time logging */ diagmode.real_time = real_time; diagmode.use_nrt_values = 0; diagmode.commit_threshold = 0; diagmode.sleep_threshold = 0; diagmode.sleep_time = 0; diagmode.drain_timer_val = 0; diagmode.event_stale_timer_val = 0; memcpy(buf, &diagmode, msg_size); if (smd_info->ch) { while (retry_count < 3) { wr_size = smd_write(smd_info->ch, buf, msg_size); if (wr_size == -ENOMEM) { /* * The smd channel is full. Delay while * smd processes existing data and smd * has memory become available. The delay * of 2000 was determined empirically as * best value to use. */ retry_count++; for (timer = 0; timer < 5; timer++) udelay(2000); } else { struct diag_smd_info *data = &driver->smd_data[smd_info->peripheral]; driver->real_time_mode = real_time; process_lock_enabling(&data->nrt_lock, real_time); break; } } if (wr_size != msg_size) pr_err("diag: proc %d fail feature update %d, tried %d", smd_info->peripheral, wr_size, msg_size); } else { pr_err("diag: ch invalid, feature update on proc %d\n", smd_info->peripheral); } mutex_unlock(&driver->diag_cntl_mutex); } static int diag_smd_cntl_probe(struct platform_device *pdev) { int r = 0; int index = -1; const char *channel_name = NULL; /* open control ports only on 8960 & newer targets */ if (chk_apps_only()) { if (pdev->id == SMD_APPS_MODEM) { index = MODEM_DATA; channel_name = "DIAG_CNTL"; } #if defined(CONFIG_MSM_N_WAY_SMD) else if (pdev->id == SMD_APPS_QDSP) { index = LPASS_DATA; channel_name = "DIAG_CNTL"; } #endif else if (pdev->id == SMD_APPS_WCNSS) { index = WCNSS_DATA; channel_name = "APPS_RIVA_CTRL"; } if (index != -1) { r = smd_named_open_on_edge(channel_name, pdev->id, &driver->smd_cntl[index].ch, &driver->smd_cntl[index], diag_smd_notify); driver->smd_cntl[index].ch_save = driver->smd_cntl[index].ch; } pr_debug("diag: In %s, open SMD CNTL port, Id = %d, r = %d\n", __func__, pdev->id, r); } return 0; } static int diagfwd_cntl_runtime_suspend(struct device *dev) { dev_dbg(dev, "pm_runtime: suspending...\n"); return 0; } static int diagfwd_cntl_runtime_resume(struct device *dev) { dev_dbg(dev, "pm_runtime: resuming...\n"); return 0; } static const struct dev_pm_ops diagfwd_cntl_dev_pm_ops = { .runtime_suspend = diagfwd_cntl_runtime_suspend, .runtime_resume = diagfwd_cntl_runtime_resume, }; static struct platform_driver msm_smd_ch1_cntl_driver = { .probe = diag_smd_cntl_probe, .driver = { .name = "DIAG_CNTL", .owner = THIS_MODULE, .pm = &diagfwd_cntl_dev_pm_ops, }, }; static struct platform_driver diag_smd_lite_cntl_driver = { .probe = diag_smd_cntl_probe, .driver = { .name = "APPS_RIVA_CTRL", .owner = THIS_MODULE, .pm = &diagfwd_cntl_dev_pm_ops, }, }; void diagfwd_cntl_init(void) { int success; int i; reg_dirty = 0; driver->polling_reg_flag = 0; driver->log_on_demand_support = 1; driver->diag_cntl_wq = create_singlethread_workqueue("diag_cntl_wq"); for (i = 0; i < NUM_SMD_CONTROL_CHANNELS; i++) { success = diag_smd_constructor(&driver->smd_cntl[i], i, SMD_CNTL_TYPE); if (!success) goto err; } platform_driver_register(&msm_smd_ch1_cntl_driver); platform_driver_register(&diag_smd_lite_cntl_driver); return; err: pr_err("diag: Could not initialize diag buffers"); for (i = 0; i < NUM_SMD_CONTROL_CHANNELS; i++) diag_smd_destructor(&driver->smd_cntl[i]); if (driver->diag_cntl_wq) destroy_workqueue(driver->diag_cntl_wq); } void diagfwd_cntl_exit(void) { int i; for (i = 0; i < NUM_SMD_CONTROL_CHANNELS; i++) diag_smd_destructor(&driver->smd_cntl[i]); destroy_workqueue(driver->diag_cntl_wq); platform_driver_unregister(&msm_smd_ch1_cntl_driver); platform_driver_unregister(&diag_smd_lite_cntl_driver); }
gpl-2.0
AOSP-TEAM/android_kernel_google_tuna
drivers/input/evdev.c
282
23641
/* * Event char devices, giving access to raw input device events. * * Copyright (c) 1999-2002 Vojtech Pavlik * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define EVDEV_MINOR_BASE 64 #define EVDEV_MINORS 32 #define EVDEV_MIN_BUFFER_SIZE 64U #define EVDEV_BUF_PACKETS 8 #include <linux/poll.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/input.h> #include <linux/major.h> #include <linux/device.h> #include <linux/wakelock.h> #include "input-compat.h" struct evdev { int open; int minor; struct input_handle handle; wait_queue_head_t wait; struct evdev_client __rcu *grab; struct list_head client_list; spinlock_t client_lock; /* protects client_list */ struct mutex mutex; struct device dev; bool exist; }; struct evdev_client { unsigned int head; unsigned int tail; unsigned int packet_head; /* [future] position of the first element of next packet */ spinlock_t buffer_lock; /* protects access to buffer, head and tail */ struct wake_lock wake_lock; char name[28]; struct fasync_struct *fasync; struct evdev *evdev; struct list_head node; unsigned int bufsize; struct input_event buffer[]; }; static struct evdev *evdev_table[EVDEV_MINORS]; static DEFINE_MUTEX(evdev_table_mutex); static void evdev_pass_event(struct evdev_client *client, struct input_event *event) { /* Interrupts are disabled, just acquire the lock. */ spin_lock(&client->buffer_lock); wake_lock_timeout(&client->wake_lock, 5 * HZ); client->buffer[client->head++] = *event; client->head &= client->bufsize - 1; if (unlikely(client->head == client->tail)) { /* * This effectively "drops" all unconsumed events, leaving * EV_SYN/SYN_DROPPED plus the newest event in the queue. */ client->tail = (client->head - 2) & (client->bufsize - 1); client->buffer[client->tail].time = event->time; client->buffer[client->tail].type = EV_SYN; client->buffer[client->tail].code = SYN_DROPPED; client->buffer[client->tail].value = 0; client->packet_head = client->tail; } if (event->type == EV_SYN && event->code == SYN_REPORT) { client->packet_head = client->head; kill_fasync(&client->fasync, SIGIO, POLL_IN); } spin_unlock(&client->buffer_lock); } /* * Pass incoming event to all connected clients. */ static void evdev_event(struct input_handle *handle, unsigned int type, unsigned int code, int value) { struct evdev *evdev = handle->private; struct evdev_client *client; struct input_event event; struct timespec ts; ktime_get_ts(&ts); event.time.tv_sec = ts.tv_sec; event.time.tv_usec = ts.tv_nsec / NSEC_PER_USEC; event.type = type; event.code = code; event.value = value; rcu_read_lock(); client = rcu_dereference(evdev->grab); if (client) evdev_pass_event(client, &event); else list_for_each_entry_rcu(client, &evdev->client_list, node) evdev_pass_event(client, &event); rcu_read_unlock(); if (type == EV_SYN && code == SYN_REPORT) wake_up_interruptible(&evdev->wait); } static int evdev_fasync(int fd, struct file *file, int on) { struct evdev_client *client = file->private_data; return fasync_helper(fd, file, on, &client->fasync); } static int evdev_flush(struct file *file, fl_owner_t id) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; int retval; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist) retval = -ENODEV; else retval = input_flush_device(&evdev->handle, file); mutex_unlock(&evdev->mutex); return retval; } static void evdev_free(struct device *dev) { struct evdev *evdev = container_of(dev, struct evdev, dev); input_put_device(evdev->handle.dev); kfree(evdev); } /* * Grabs an event device (along with underlying input device). * This function is called with evdev->mutex taken. */ static int evdev_grab(struct evdev *evdev, struct evdev_client *client) { int error; if (evdev->grab) return -EBUSY; error = input_grab_device(&evdev->handle); if (error) return error; rcu_assign_pointer(evdev->grab, client); return 0; } static int evdev_ungrab(struct evdev *evdev, struct evdev_client *client) { if (evdev->grab != client) return -EINVAL; rcu_assign_pointer(evdev->grab, NULL); synchronize_rcu(); input_release_device(&evdev->handle); return 0; } static void evdev_attach_client(struct evdev *evdev, struct evdev_client *client) { spin_lock(&evdev->client_lock); list_add_tail_rcu(&client->node, &evdev->client_list); spin_unlock(&evdev->client_lock); } static void evdev_detach_client(struct evdev *evdev, struct evdev_client *client) { spin_lock(&evdev->client_lock); list_del_rcu(&client->node); spin_unlock(&evdev->client_lock); synchronize_rcu(); } static int evdev_open_device(struct evdev *evdev) { int retval; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist) retval = -ENODEV; else if (!evdev->open++) { retval = input_open_device(&evdev->handle); if (retval) evdev->open--; } mutex_unlock(&evdev->mutex); return retval; } static void evdev_close_device(struct evdev *evdev) { mutex_lock(&evdev->mutex); if (evdev->exist && !--evdev->open) input_close_device(&evdev->handle); mutex_unlock(&evdev->mutex); } /* * Wake up users waiting for IO so they can disconnect from * dead device. */ static void evdev_hangup(struct evdev *evdev) { struct evdev_client *client; spin_lock(&evdev->client_lock); list_for_each_entry(client, &evdev->client_list, node) kill_fasync(&client->fasync, SIGIO, POLL_HUP); spin_unlock(&evdev->client_lock); wake_up_interruptible(&evdev->wait); } static int evdev_release(struct inode *inode, struct file *file) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; mutex_lock(&evdev->mutex); if (evdev->grab == client) evdev_ungrab(evdev, client); mutex_unlock(&evdev->mutex); evdev_detach_client(evdev, client); wake_lock_destroy(&client->wake_lock); kfree(client); evdev_close_device(evdev); put_device(&evdev->dev); return 0; } static unsigned int evdev_compute_buffer_size(struct input_dev *dev) { unsigned int n_events = max(dev->hint_events_per_packet * EVDEV_BUF_PACKETS, EVDEV_MIN_BUFFER_SIZE); return roundup_pow_of_two(n_events); } static int evdev_open(struct inode *inode, struct file *file) { struct evdev *evdev; struct evdev_client *client; int i = iminor(inode) - EVDEV_MINOR_BASE; unsigned int bufsize; int error; if (i >= EVDEV_MINORS) return -ENODEV; error = mutex_lock_interruptible(&evdev_table_mutex); if (error) return error; evdev = evdev_table[i]; if (evdev) get_device(&evdev->dev); mutex_unlock(&evdev_table_mutex); if (!evdev) return -ENODEV; bufsize = evdev_compute_buffer_size(evdev->handle.dev); client = kzalloc(sizeof(struct evdev_client) + bufsize * sizeof(struct input_event), GFP_KERNEL); if (!client) { error = -ENOMEM; goto err_put_evdev; } client->bufsize = bufsize; spin_lock_init(&client->buffer_lock); snprintf(client->name, sizeof(client->name), "%s-%d", dev_name(&evdev->dev), task_tgid_vnr(current)); wake_lock_init(&client->wake_lock, WAKE_LOCK_SUSPEND, client->name); client->evdev = evdev; evdev_attach_client(evdev, client); error = evdev_open_device(evdev); if (error) goto err_free_client; file->private_data = client; nonseekable_open(inode, file); return 0; err_free_client: evdev_detach_client(evdev, client); wake_lock_destroy(&client->wake_lock); kfree(client); err_put_evdev: put_device(&evdev->dev); return error; } static ssize_t evdev_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; struct input_event event; int retval; if (count < input_event_size()) return -EINVAL; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist) { retval = -ENODEV; goto out; } do { if (input_event_from_user(buffer + retval, &event)) { retval = -EFAULT; goto out; } retval += input_event_size(); input_inject_event(&evdev->handle, event.type, event.code, event.value); } while (retval + input_event_size() <= count); out: mutex_unlock(&evdev->mutex); return retval; } static int evdev_fetch_next_event(struct evdev_client *client, struct input_event *event) { int have_event; spin_lock_irq(&client->buffer_lock); have_event = client->packet_head != client->tail; if (have_event) { *event = client->buffer[client->tail++]; client->tail &= client->bufsize - 1; if (client->head == client->tail) wake_unlock(&client->wake_lock); } spin_unlock_irq(&client->buffer_lock); return have_event; } static ssize_t evdev_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; struct input_event event; int retval; if (count < input_event_size()) return -EINVAL; if (!(file->f_flags & O_NONBLOCK)) { retval = wait_event_interruptible(evdev->wait, client->packet_head != client->tail || !evdev->exist); if (retval) return retval; } if (!evdev->exist) return -ENODEV; while (retval + input_event_size() <= count && evdev_fetch_next_event(client, &event)) { if (input_event_to_user(buffer + retval, &event)) return -EFAULT; retval += input_event_size(); } if (retval == 0 && file->f_flags & O_NONBLOCK) retval = -EAGAIN; return retval; } /* No kernel lock - fine */ static unsigned int evdev_poll(struct file *file, poll_table *wait) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; unsigned int mask; poll_wait(file, &evdev->wait, wait); mask = evdev->exist ? POLLOUT | POLLWRNORM : POLLHUP | POLLERR; if (client->packet_head != client->tail) mask |= POLLIN | POLLRDNORM; return mask; } #ifdef CONFIG_COMPAT #define BITS_PER_LONG_COMPAT (sizeof(compat_long_t) * 8) #define BITS_TO_LONGS_COMPAT(x) ((((x) - 1) / BITS_PER_LONG_COMPAT) + 1) #ifdef __BIG_ENDIAN static int bits_to_user(unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int len, i; if (compat) { len = BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t); if (len > maxlen) len = maxlen; for (i = 0; i < len / sizeof(compat_long_t); i++) if (copy_to_user((compat_long_t __user *) p + i, (compat_long_t *) bits + i + 1 - ((i % 2) << 1), sizeof(compat_long_t))) return -EFAULT; } else { len = BITS_TO_LONGS(maxbit) * sizeof(long); if (len > maxlen) len = maxlen; if (copy_to_user(p, bits, len)) return -EFAULT; } return len; } #else static int bits_to_user(unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int len = compat ? BITS_TO_LONGS_COMPAT(maxbit) * sizeof(compat_long_t) : BITS_TO_LONGS(maxbit) * sizeof(long); if (len > maxlen) len = maxlen; return copy_to_user(p, bits, len) ? -EFAULT : len; } #endif /* __BIG_ENDIAN */ #else static int bits_to_user(unsigned long *bits, unsigned int maxbit, unsigned int maxlen, void __user *p, int compat) { int len = BITS_TO_LONGS(maxbit) * sizeof(long); if (len > maxlen) len = maxlen; return copy_to_user(p, bits, len) ? -EFAULT : len; } #endif /* CONFIG_COMPAT */ static int str_to_user(const char *str, unsigned int maxlen, void __user *p) { int len; if (!str) return -ENOENT; len = strlen(str) + 1; if (len > maxlen) len = maxlen; return copy_to_user(p, str, len) ? -EFAULT : len; } #define OLD_KEY_MAX 0x1ff static int handle_eviocgbit(struct input_dev *dev, unsigned int type, unsigned int size, void __user *p, int compat_mode) { static unsigned long keymax_warn_time; unsigned long *bits; int len; switch (type) { case 0: bits = dev->evbit; len = EV_MAX; break; case EV_KEY: bits = dev->keybit; len = KEY_MAX; break; case EV_REL: bits = dev->relbit; len = REL_MAX; break; case EV_ABS: bits = dev->absbit; len = ABS_MAX; break; case EV_MSC: bits = dev->mscbit; len = MSC_MAX; break; case EV_LED: bits = dev->ledbit; len = LED_MAX; break; case EV_SND: bits = dev->sndbit; len = SND_MAX; break; case EV_FF: bits = dev->ffbit; len = FF_MAX; break; case EV_SW: bits = dev->swbit; len = SW_MAX; break; default: return -EINVAL; } /* * Work around bugs in userspace programs that like to do * EVIOCGBIT(EV_KEY, KEY_MAX) and not realize that 'len' * should be in bytes, not in bits. */ if (type == EV_KEY && size == OLD_KEY_MAX) { len = OLD_KEY_MAX; if (printk_timed_ratelimit(&keymax_warn_time, 10 * 1000)) pr_warning("(EVIOCGBIT): Suspicious buffer size %u, " "limiting output to %zu bytes. See " "http://userweb.kernel.org/~dtor/eviocgbit-bug.html\n", OLD_KEY_MAX, BITS_TO_LONGS(OLD_KEY_MAX) * sizeof(long)); } return bits_to_user(bits, len, size, p, compat_mode); } #undef OLD_KEY_MAX static int evdev_handle_get_keycode(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke = { .len = sizeof(unsigned int), .flags = 0, }; int __user *ip = (int __user *)p; int error; /* legacy case */ if (copy_from_user(ke.scancode, p, sizeof(unsigned int))) return -EFAULT; error = input_get_keycode(dev, &ke); if (error) return error; if (put_user(ke.keycode, ip + 1)) return -EFAULT; return 0; } static int evdev_handle_get_keycode_v2(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke; int error; if (copy_from_user(&ke, p, sizeof(ke))) return -EFAULT; error = input_get_keycode(dev, &ke); if (error) return error; if (copy_to_user(p, &ke, sizeof(ke))) return -EFAULT; return 0; } static int evdev_handle_set_keycode(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke = { .len = sizeof(unsigned int), .flags = 0, }; int __user *ip = (int __user *)p; if (copy_from_user(ke.scancode, p, sizeof(unsigned int))) return -EFAULT; if (get_user(ke.keycode, ip + 1)) return -EFAULT; return input_set_keycode(dev, &ke); } static int evdev_handle_set_keycode_v2(struct input_dev *dev, void __user *p) { struct input_keymap_entry ke; if (copy_from_user(&ke, p, sizeof(ke))) return -EFAULT; if (ke.len > sizeof(ke.scancode)) return -EINVAL; return input_set_keycode(dev, &ke); } static long evdev_do_ioctl(struct file *file, unsigned int cmd, void __user *p, int compat_mode) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; struct input_dev *dev = evdev->handle.dev; struct input_absinfo abs; struct ff_effect effect; int __user *ip = (int __user *)p; unsigned int i, t, u, v; unsigned int size; int error; /* First we check for fixed-length commands */ switch (cmd) { case EVIOCGVERSION: return put_user(EV_VERSION, ip); case EVIOCGID: if (copy_to_user(p, &dev->id, sizeof(struct input_id))) return -EFAULT; return 0; case EVIOCGREP: if (!test_bit(EV_REP, dev->evbit)) return -ENOSYS; if (put_user(dev->rep[REP_DELAY], ip)) return -EFAULT; if (put_user(dev->rep[REP_PERIOD], ip + 1)) return -EFAULT; return 0; case EVIOCSREP: if (!test_bit(EV_REP, dev->evbit)) return -ENOSYS; if (get_user(u, ip)) return -EFAULT; if (get_user(v, ip + 1)) return -EFAULT; input_inject_event(&evdev->handle, EV_REP, REP_DELAY, u); input_inject_event(&evdev->handle, EV_REP, REP_PERIOD, v); return 0; case EVIOCRMFF: return input_ff_erase(dev, (int)(unsigned long) p, file); case EVIOCGEFFECTS: i = test_bit(EV_FF, dev->evbit) ? dev->ff->max_effects : 0; if (put_user(i, ip)) return -EFAULT; return 0; case EVIOCGRAB: if (p) return evdev_grab(evdev, client); else return evdev_ungrab(evdev, client); case EVIOCGKEYCODE: return evdev_handle_get_keycode(dev, p); case EVIOCSKEYCODE: return evdev_handle_set_keycode(dev, p); case EVIOCGKEYCODE_V2: return evdev_handle_get_keycode_v2(dev, p); case EVIOCSKEYCODE_V2: return evdev_handle_set_keycode_v2(dev, p); } size = _IOC_SIZE(cmd); /* Now check variable-length commands */ #define EVIOC_MASK_SIZE(nr) ((nr) & ~(_IOC_SIZEMASK << _IOC_SIZESHIFT)) switch (EVIOC_MASK_SIZE(cmd)) { case EVIOCGPROP(0): return bits_to_user(dev->propbit, INPUT_PROP_MAX, size, p, compat_mode); case EVIOCGKEY(0): return bits_to_user(dev->key, KEY_MAX, size, p, compat_mode); case EVIOCGLED(0): return bits_to_user(dev->led, LED_MAX, size, p, compat_mode); case EVIOCGSND(0): return bits_to_user(dev->snd, SND_MAX, size, p, compat_mode); case EVIOCGSW(0): return bits_to_user(dev->sw, SW_MAX, size, p, compat_mode); case EVIOCGNAME(0): return str_to_user(dev->name, size, p); case EVIOCGPHYS(0): return str_to_user(dev->phys, size, p); case EVIOCGUNIQ(0): return str_to_user(dev->uniq, size, p); case EVIOC_MASK_SIZE(EVIOCSFF): if (input_ff_effect_from_user(p, size, &effect)) return -EFAULT; error = input_ff_upload(dev, &effect, file); if (put_user(effect.id, &(((struct ff_effect __user *)p)->id))) return -EFAULT; return error; } /* Multi-number variable-length handlers */ if (_IOC_TYPE(cmd) != 'E') return -EINVAL; if (_IOC_DIR(cmd) == _IOC_READ) { if ((_IOC_NR(cmd) & ~EV_MAX) == _IOC_NR(EVIOCGBIT(0, 0))) return handle_eviocgbit(dev, _IOC_NR(cmd) & EV_MAX, size, p, compat_mode); if ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCGABS(0))) { if (!dev->absinfo) return -EINVAL; t = _IOC_NR(cmd) & ABS_MAX; abs = dev->absinfo[t]; if (copy_to_user(p, &abs, min_t(size_t, size, sizeof(struct input_absinfo)))) return -EFAULT; return 0; } } if (_IOC_DIR(cmd) == _IOC_WRITE) { if ((_IOC_NR(cmd) & ~ABS_MAX) == _IOC_NR(EVIOCSABS(0))) { if (!dev->absinfo) return -EINVAL; t = _IOC_NR(cmd) & ABS_MAX; if (copy_from_user(&abs, p, min_t(size_t, size, sizeof(struct input_absinfo)))) return -EFAULT; if (size < sizeof(struct input_absinfo)) abs.resolution = 0; /* We can't change number of reserved MT slots */ if (t == ABS_MT_SLOT) return -EINVAL; /* * Take event lock to ensure that we are not * changing device parameters in the middle * of event. */ spin_lock_irq(&dev->event_lock); dev->absinfo[t] = abs; spin_unlock_irq(&dev->event_lock); return 0; } } return -EINVAL; } static long evdev_ioctl_handler(struct file *file, unsigned int cmd, void __user *p, int compat_mode) { struct evdev_client *client = file->private_data; struct evdev *evdev = client->evdev; int retval; retval = mutex_lock_interruptible(&evdev->mutex); if (retval) return retval; if (!evdev->exist) { retval = -ENODEV; goto out; } retval = evdev_do_ioctl(file, cmd, p, compat_mode); out: mutex_unlock(&evdev->mutex); return retval; } static long evdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return evdev_ioctl_handler(file, cmd, (void __user *)arg, 0); } #ifdef CONFIG_COMPAT static long evdev_ioctl_compat(struct file *file, unsigned int cmd, unsigned long arg) { return evdev_ioctl_handler(file, cmd, compat_ptr(arg), 1); } #endif static const struct file_operations evdev_fops = { .owner = THIS_MODULE, .read = evdev_read, .write = evdev_write, .poll = evdev_poll, .open = evdev_open, .release = evdev_release, .unlocked_ioctl = evdev_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = evdev_ioctl_compat, #endif .fasync = evdev_fasync, .flush = evdev_flush, .llseek = no_llseek, }; static int evdev_install_chrdev(struct evdev *evdev) { /* * No need to do any locking here as calls to connect and * disconnect are serialized by the input core */ evdev_table[evdev->minor] = evdev; return 0; } static void evdev_remove_chrdev(struct evdev *evdev) { /* * Lock evdev table to prevent race with evdev_open() */ mutex_lock(&evdev_table_mutex); evdev_table[evdev->minor] = NULL; mutex_unlock(&evdev_table_mutex); } /* * Mark device non-existent. This disables writes, ioctls and * prevents new users from opening the device. Already posted * blocking reads will stay, however new ones will fail. */ static void evdev_mark_dead(struct evdev *evdev) { mutex_lock(&evdev->mutex); evdev->exist = false; mutex_unlock(&evdev->mutex); } static void evdev_cleanup(struct evdev *evdev) { struct input_handle *handle = &evdev->handle; evdev_mark_dead(evdev); evdev_hangup(evdev); evdev_remove_chrdev(evdev); /* evdev is marked dead so no one else accesses evdev->open */ if (evdev->open) { input_flush_device(handle, NULL); input_close_device(handle); } } /* * Create new evdev device. Note that input core serializes calls * to connect and disconnect so we don't need to lock evdev_table here. */ static int evdev_connect(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id) { struct evdev *evdev; int minor; int error; for (minor = 0; minor < EVDEV_MINORS; minor++) if (!evdev_table[minor]) break; if (minor == EVDEV_MINORS) { pr_err("no more free evdev devices\n"); return -ENFILE; } evdev = kzalloc(sizeof(struct evdev), GFP_KERNEL); if (!evdev) return -ENOMEM; INIT_LIST_HEAD(&evdev->client_list); spin_lock_init(&evdev->client_lock); mutex_init(&evdev->mutex); init_waitqueue_head(&evdev->wait); dev_set_name(&evdev->dev, "event%d", minor); evdev->exist = true; evdev->minor = minor; evdev->handle.dev = input_get_device(dev); evdev->handle.name = dev_name(&evdev->dev); evdev->handle.handler = handler; evdev->handle.private = evdev; evdev->dev.devt = MKDEV(INPUT_MAJOR, EVDEV_MINOR_BASE + minor); evdev->dev.class = &input_class; evdev->dev.parent = &dev->dev; evdev->dev.release = evdev_free; device_initialize(&evdev->dev); error = input_register_handle(&evdev->handle); if (error) goto err_free_evdev; error = evdev_install_chrdev(evdev); if (error) goto err_unregister_handle; error = device_add(&evdev->dev); if (error) goto err_cleanup_evdev; return 0; err_cleanup_evdev: evdev_cleanup(evdev); err_unregister_handle: input_unregister_handle(&evdev->handle); err_free_evdev: put_device(&evdev->dev); return error; } static void evdev_disconnect(struct input_handle *handle) { struct evdev *evdev = handle->private; device_del(&evdev->dev); evdev_cleanup(evdev); input_unregister_handle(handle); put_device(&evdev->dev); } static const struct input_device_id evdev_ids[] = { { .driver_info = 1 }, /* Matches all devices */ { }, /* Terminating zero entry */ }; MODULE_DEVICE_TABLE(input, evdev_ids); static struct input_handler evdev_handler = { .event = evdev_event, .connect = evdev_connect, .disconnect = evdev_disconnect, .fops = &evdev_fops, .minor = EVDEV_MINOR_BASE, .name = "evdev", .id_table = evdev_ids, }; static int __init evdev_init(void) { return input_register_handler(&evdev_handler); } static void __exit evdev_exit(void) { input_unregister_handler(&evdev_handler); } module_init(evdev_init); module_exit(evdev_exit); MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>"); MODULE_DESCRIPTION("Input driver event char devices"); MODULE_LICENSE("GPL");
gpl-2.0
sunnyden/ubuntu_kernel
drivers/ata/sata_rcar.c
538
27418
/* * Renesas R-Car SATA driver * * Author: Vladimir Barinov <source@cogentembedded.com> * Copyright (C) 2013-2015 Cogent Embedded, Inc. * Copyright (C) 2013-2015 Renesas Solutions Corp. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/ata.h> #include <linux/libata.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/err.h> #define DRV_NAME "sata_rcar" /* SH-Navi2G/ATAPI-ATA compatible task registers */ #define DATA_REG 0x100 #define SDEVCON_REG 0x138 /* SH-Navi2G/ATAPI module compatible control registers */ #define ATAPI_CONTROL1_REG 0x180 #define ATAPI_STATUS_REG 0x184 #define ATAPI_INT_ENABLE_REG 0x188 #define ATAPI_DTB_ADR_REG 0x198 #define ATAPI_DMA_START_ADR_REG 0x19C #define ATAPI_DMA_TRANS_CNT_REG 0x1A0 #define ATAPI_CONTROL2_REG 0x1A4 #define ATAPI_SIG_ST_REG 0x1B0 #define ATAPI_BYTE_SWAP_REG 0x1BC /* ATAPI control 1 register (ATAPI_CONTROL1) bits */ #define ATAPI_CONTROL1_ISM BIT(16) #define ATAPI_CONTROL1_DTA32M BIT(11) #define ATAPI_CONTROL1_RESET BIT(7) #define ATAPI_CONTROL1_DESE BIT(3) #define ATAPI_CONTROL1_RW BIT(2) #define ATAPI_CONTROL1_STOP BIT(1) #define ATAPI_CONTROL1_START BIT(0) /* ATAPI status register (ATAPI_STATUS) bits */ #define ATAPI_STATUS_SATAINT BIT(11) #define ATAPI_STATUS_DNEND BIT(6) #define ATAPI_STATUS_DEVTRM BIT(5) #define ATAPI_STATUS_DEVINT BIT(4) #define ATAPI_STATUS_ERR BIT(2) #define ATAPI_STATUS_NEND BIT(1) #define ATAPI_STATUS_ACT BIT(0) /* Interrupt enable register (ATAPI_INT_ENABLE) bits */ #define ATAPI_INT_ENABLE_SATAINT BIT(11) #define ATAPI_INT_ENABLE_DNEND BIT(6) #define ATAPI_INT_ENABLE_DEVTRM BIT(5) #define ATAPI_INT_ENABLE_DEVINT BIT(4) #define ATAPI_INT_ENABLE_ERR BIT(2) #define ATAPI_INT_ENABLE_NEND BIT(1) #define ATAPI_INT_ENABLE_ACT BIT(0) /* Access control registers for physical layer control register */ #define SATAPHYADDR_REG 0x200 #define SATAPHYWDATA_REG 0x204 #define SATAPHYACCEN_REG 0x208 #define SATAPHYRESET_REG 0x20C #define SATAPHYRDATA_REG 0x210 #define SATAPHYACK_REG 0x214 /* Physical layer control address command register (SATAPHYADDR) bits */ #define SATAPHYADDR_PHYRATEMODE BIT(10) #define SATAPHYADDR_PHYCMD_READ BIT(9) #define SATAPHYADDR_PHYCMD_WRITE BIT(8) /* Physical layer control enable register (SATAPHYACCEN) bits */ #define SATAPHYACCEN_PHYLANE BIT(0) /* Physical layer control reset register (SATAPHYRESET) bits */ #define SATAPHYRESET_PHYRST BIT(1) #define SATAPHYRESET_PHYSRES BIT(0) /* Physical layer control acknowledge register (SATAPHYACK) bits */ #define SATAPHYACK_PHYACK BIT(0) /* Serial-ATA HOST control registers */ #define BISTCONF_REG 0x102C #define SDATA_REG 0x1100 #define SSDEVCON_REG 0x1204 #define SCRSSTS_REG 0x1400 #define SCRSERR_REG 0x1404 #define SCRSCON_REG 0x1408 #define SCRSACT_REG 0x140C #define SATAINTSTAT_REG 0x1508 #define SATAINTMASK_REG 0x150C /* SATA INT status register (SATAINTSTAT) bits */ #define SATAINTSTAT_SERR BIT(3) #define SATAINTSTAT_ATA BIT(0) /* SATA INT mask register (SATAINTSTAT) bits */ #define SATAINTMASK_SERRMSK BIT(3) #define SATAINTMASK_ERRMSK BIT(2) #define SATAINTMASK_ERRCRTMSK BIT(1) #define SATAINTMASK_ATAMSK BIT(0) #define SATA_RCAR_INT_MASK (SATAINTMASK_SERRMSK | \ SATAINTMASK_ATAMSK) /* Physical Layer Control Registers */ #define SATAPCTLR1_REG 0x43 #define SATAPCTLR2_REG 0x52 #define SATAPCTLR3_REG 0x5A #define SATAPCTLR4_REG 0x60 /* Descriptor table word 0 bit (when DTA32M = 1) */ #define SATA_RCAR_DTEND BIT(0) #define SATA_RCAR_DMA_BOUNDARY 0x1FFFFFFEUL /* Gen2 Physical Layer Control Registers */ #define RCAR_GEN2_PHY_CTL1_REG 0x1704 #define RCAR_GEN2_PHY_CTL1 0x34180002 #define RCAR_GEN2_PHY_CTL1_SS 0xC180 /* Spread Spectrum */ #define RCAR_GEN2_PHY_CTL2_REG 0x170C #define RCAR_GEN2_PHY_CTL2 0x00002303 #define RCAR_GEN2_PHY_CTL3_REG 0x171C #define RCAR_GEN2_PHY_CTL3 0x000B0194 #define RCAR_GEN2_PHY_CTL4_REG 0x1724 #define RCAR_GEN2_PHY_CTL4 0x00030994 #define RCAR_GEN2_PHY_CTL5_REG 0x1740 #define RCAR_GEN2_PHY_CTL5 0x03004001 #define RCAR_GEN2_PHY_CTL5_DC BIT(1) /* DC connection */ #define RCAR_GEN2_PHY_CTL5_TR BIT(2) /* Termination Resistor */ enum sata_rcar_type { RCAR_GEN1_SATA, RCAR_GEN2_SATA, RCAR_R8A7790_ES1_SATA, }; struct sata_rcar_priv { void __iomem *base; struct clk *clk; enum sata_rcar_type type; }; static void sata_rcar_gen1_phy_preinit(struct sata_rcar_priv *priv) { void __iomem *base = priv->base; /* idle state */ iowrite32(0, base + SATAPHYADDR_REG); /* reset */ iowrite32(SATAPHYRESET_PHYRST, base + SATAPHYRESET_REG); udelay(10); /* deassert reset */ iowrite32(0, base + SATAPHYRESET_REG); } static void sata_rcar_gen1_phy_write(struct sata_rcar_priv *priv, u16 reg, u32 val, int group) { void __iomem *base = priv->base; int timeout; /* deassert reset */ iowrite32(0, base + SATAPHYRESET_REG); /* lane 1 */ iowrite32(SATAPHYACCEN_PHYLANE, base + SATAPHYACCEN_REG); /* write phy register value */ iowrite32(val, base + SATAPHYWDATA_REG); /* set register group */ if (group) reg |= SATAPHYADDR_PHYRATEMODE; /* write command */ iowrite32(SATAPHYADDR_PHYCMD_WRITE | reg, base + SATAPHYADDR_REG); /* wait for ack */ for (timeout = 0; timeout < 100; timeout++) { val = ioread32(base + SATAPHYACK_REG); if (val & SATAPHYACK_PHYACK) break; } if (timeout >= 100) pr_err("%s timeout\n", __func__); /* idle state */ iowrite32(0, base + SATAPHYADDR_REG); } static void sata_rcar_gen1_phy_init(struct sata_rcar_priv *priv) { sata_rcar_gen1_phy_preinit(priv); sata_rcar_gen1_phy_write(priv, SATAPCTLR1_REG, 0x00200188, 0); sata_rcar_gen1_phy_write(priv, SATAPCTLR1_REG, 0x00200188, 1); sata_rcar_gen1_phy_write(priv, SATAPCTLR3_REG, 0x0000A061, 0); sata_rcar_gen1_phy_write(priv, SATAPCTLR2_REG, 0x20000000, 0); sata_rcar_gen1_phy_write(priv, SATAPCTLR2_REG, 0x20000000, 1); sata_rcar_gen1_phy_write(priv, SATAPCTLR4_REG, 0x28E80000, 0); } static void sata_rcar_gen2_phy_init(struct sata_rcar_priv *priv) { void __iomem *base = priv->base; iowrite32(RCAR_GEN2_PHY_CTL1, base + RCAR_GEN2_PHY_CTL1_REG); iowrite32(RCAR_GEN2_PHY_CTL2, base + RCAR_GEN2_PHY_CTL2_REG); iowrite32(RCAR_GEN2_PHY_CTL3, base + RCAR_GEN2_PHY_CTL3_REG); iowrite32(RCAR_GEN2_PHY_CTL4, base + RCAR_GEN2_PHY_CTL4_REG); iowrite32(RCAR_GEN2_PHY_CTL5 | RCAR_GEN2_PHY_CTL5_DC | RCAR_GEN2_PHY_CTL5_TR, base + RCAR_GEN2_PHY_CTL5_REG); } static void sata_rcar_freeze(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; /* mask */ iowrite32(0x7ff, priv->base + SATAINTMASK_REG); ata_sff_freeze(ap); } static void sata_rcar_thaw(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; /* ack */ iowrite32(~(u32)SATA_RCAR_INT_MASK, base + SATAINTSTAT_REG); ata_sff_thaw(ap); /* unmask */ iowrite32(0x7ff & ~SATA_RCAR_INT_MASK, base + SATAINTMASK_REG); } static void sata_rcar_ioread16_rep(void __iomem *reg, void *buffer, int count) { u16 *ptr = buffer; while (count--) { u16 data = ioread32(reg); *ptr++ = data; } } static void sata_rcar_iowrite16_rep(void __iomem *reg, void *buffer, int count) { const u16 *ptr = buffer; while (count--) iowrite32(*ptr++, reg); } static u8 sata_rcar_check_status(struct ata_port *ap) { return ioread32(ap->ioaddr.status_addr); } static u8 sata_rcar_check_altstatus(struct ata_port *ap) { return ioread32(ap->ioaddr.altstatus_addr); } static void sata_rcar_set_devctl(struct ata_port *ap, u8 ctl) { iowrite32(ctl, ap->ioaddr.ctl_addr); } static void sata_rcar_dev_select(struct ata_port *ap, unsigned int device) { iowrite32(ATA_DEVICE_OBS, ap->ioaddr.device_addr); ata_sff_pause(ap); /* needed; also flushes, for mmio */ } static unsigned int sata_rcar_ata_devchk(struct ata_port *ap, unsigned int device) { struct ata_ioports *ioaddr = &ap->ioaddr; u8 nsect, lbal; sata_rcar_dev_select(ap, device); iowrite32(0x55, ioaddr->nsect_addr); iowrite32(0xaa, ioaddr->lbal_addr); iowrite32(0xaa, ioaddr->nsect_addr); iowrite32(0x55, ioaddr->lbal_addr); iowrite32(0x55, ioaddr->nsect_addr); iowrite32(0xaa, ioaddr->lbal_addr); nsect = ioread32(ioaddr->nsect_addr); lbal = ioread32(ioaddr->lbal_addr); if (nsect == 0x55 && lbal == 0xaa) return 1; /* found a device */ return 0; /* nothing found */ } static int sata_rcar_wait_after_reset(struct ata_link *link, unsigned long deadline) { struct ata_port *ap = link->ap; ata_msleep(ap, ATA_WAIT_AFTER_RESET); return ata_sff_wait_ready(link, deadline); } static int sata_rcar_bus_softreset(struct ata_port *ap, unsigned long deadline) { struct ata_ioports *ioaddr = &ap->ioaddr; DPRINTK("ata%u: bus reset via SRST\n", ap->print_id); /* software reset. causes dev0 to be selected */ iowrite32(ap->ctl, ioaddr->ctl_addr); udelay(20); iowrite32(ap->ctl | ATA_SRST, ioaddr->ctl_addr); udelay(20); iowrite32(ap->ctl, ioaddr->ctl_addr); ap->last_ctl = ap->ctl; /* wait the port to become ready */ return sata_rcar_wait_after_reset(&ap->link, deadline); } static int sata_rcar_softreset(struct ata_link *link, unsigned int *classes, unsigned long deadline) { struct ata_port *ap = link->ap; unsigned int devmask = 0; int rc; u8 err; /* determine if device 0 is present */ if (sata_rcar_ata_devchk(ap, 0)) devmask |= 1 << 0; /* issue bus reset */ DPRINTK("about to softreset, devmask=%x\n", devmask); rc = sata_rcar_bus_softreset(ap, deadline); /* if link is occupied, -ENODEV too is an error */ if (rc && (rc != -ENODEV || sata_scr_valid(link))) { ata_link_err(link, "SRST failed (errno=%d)\n", rc); return rc; } /* determine by signature whether we have ATA or ATAPI devices */ classes[0] = ata_sff_dev_classify(&link->device[0], devmask, &err); DPRINTK("classes[0]=%u\n", classes[0]); return 0; } static void sata_rcar_tf_load(struct ata_port *ap, const struct ata_taskfile *tf) { struct ata_ioports *ioaddr = &ap->ioaddr; unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR; if (tf->ctl != ap->last_ctl) { iowrite32(tf->ctl, ioaddr->ctl_addr); ap->last_ctl = tf->ctl; ata_wait_idle(ap); } if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) { iowrite32(tf->hob_feature, ioaddr->feature_addr); iowrite32(tf->hob_nsect, ioaddr->nsect_addr); iowrite32(tf->hob_lbal, ioaddr->lbal_addr); iowrite32(tf->hob_lbam, ioaddr->lbam_addr); iowrite32(tf->hob_lbah, ioaddr->lbah_addr); VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n", tf->hob_feature, tf->hob_nsect, tf->hob_lbal, tf->hob_lbam, tf->hob_lbah); } if (is_addr) { iowrite32(tf->feature, ioaddr->feature_addr); iowrite32(tf->nsect, ioaddr->nsect_addr); iowrite32(tf->lbal, ioaddr->lbal_addr); iowrite32(tf->lbam, ioaddr->lbam_addr); iowrite32(tf->lbah, ioaddr->lbah_addr); VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n", tf->feature, tf->nsect, tf->lbal, tf->lbam, tf->lbah); } if (tf->flags & ATA_TFLAG_DEVICE) { iowrite32(tf->device, ioaddr->device_addr); VPRINTK("device 0x%X\n", tf->device); } ata_wait_idle(ap); } static void sata_rcar_tf_read(struct ata_port *ap, struct ata_taskfile *tf) { struct ata_ioports *ioaddr = &ap->ioaddr; tf->command = sata_rcar_check_status(ap); tf->feature = ioread32(ioaddr->error_addr); tf->nsect = ioread32(ioaddr->nsect_addr); tf->lbal = ioread32(ioaddr->lbal_addr); tf->lbam = ioread32(ioaddr->lbam_addr); tf->lbah = ioread32(ioaddr->lbah_addr); tf->device = ioread32(ioaddr->device_addr); if (tf->flags & ATA_TFLAG_LBA48) { iowrite32(tf->ctl | ATA_HOB, ioaddr->ctl_addr); tf->hob_feature = ioread32(ioaddr->error_addr); tf->hob_nsect = ioread32(ioaddr->nsect_addr); tf->hob_lbal = ioread32(ioaddr->lbal_addr); tf->hob_lbam = ioread32(ioaddr->lbam_addr); tf->hob_lbah = ioread32(ioaddr->lbah_addr); iowrite32(tf->ctl, ioaddr->ctl_addr); ap->last_ctl = tf->ctl; } } static void sata_rcar_exec_command(struct ata_port *ap, const struct ata_taskfile *tf) { DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command); iowrite32(tf->command, ap->ioaddr.command_addr); ata_sff_pause(ap); } static unsigned int sata_rcar_data_xfer(struct ata_device *dev, unsigned char *buf, unsigned int buflen, int rw) { struct ata_port *ap = dev->link->ap; void __iomem *data_addr = ap->ioaddr.data_addr; unsigned int words = buflen >> 1; /* Transfer multiple of 2 bytes */ if (rw == READ) sata_rcar_ioread16_rep(data_addr, buf, words); else sata_rcar_iowrite16_rep(data_addr, buf, words); /* Transfer trailing byte, if any. */ if (unlikely(buflen & 0x01)) { unsigned char pad[2] = { }; /* Point buf to the tail of buffer */ buf += buflen - 1; /* * Use io*16_rep() accessors here as well to avoid pointlessly * swapping bytes to and from on the big endian machines... */ if (rw == READ) { sata_rcar_ioread16_rep(data_addr, pad, 1); *buf = pad[0]; } else { pad[0] = *buf; sata_rcar_iowrite16_rep(data_addr, pad, 1); } words++; } return words << 1; } static void sata_rcar_drain_fifo(struct ata_queued_cmd *qc) { int count; struct ata_port *ap; /* We only need to flush incoming data when a command was running */ if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE) return; ap = qc->ap; /* Drain up to 64K of data before we give up this recovery method */ for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ) && count < 65536; count += 2) ioread32(ap->ioaddr.data_addr); /* Can become DEBUG later */ if (count) ata_port_dbg(ap, "drained %d bytes to clear DRQ\n", count); } static int sata_rcar_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val) { if (sc_reg > SCR_ACTIVE) return -EINVAL; *val = ioread32(link->ap->ioaddr.scr_addr + (sc_reg << 2)); return 0; } static int sata_rcar_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val) { if (sc_reg > SCR_ACTIVE) return -EINVAL; iowrite32(val, link->ap->ioaddr.scr_addr + (sc_reg << 2)); return 0; } static void sata_rcar_bmdma_fill_sg(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct ata_bmdma_prd *prd = ap->bmdma_prd; struct scatterlist *sg; unsigned int si; for_each_sg(qc->sg, sg, qc->n_elem, si) { u32 addr, sg_len; /* * Note: h/w doesn't support 64-bit, so we unconditionally * truncate dma_addr_t to u32. */ addr = (u32)sg_dma_address(sg); sg_len = sg_dma_len(sg); prd[si].addr = cpu_to_le32(addr); prd[si].flags_len = cpu_to_le32(sg_len); VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", si, addr, sg_len); } /* end-of-table flag */ prd[si - 1].addr |= cpu_to_le32(SATA_RCAR_DTEND); } static void sata_rcar_qc_prep(struct ata_queued_cmd *qc) { if (!(qc->flags & ATA_QCFLAG_DMAMAP)) return; sata_rcar_bmdma_fill_sg(qc); } static void sata_rcar_bmdma_setup(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; unsigned int rw = qc->tf.flags & ATA_TFLAG_WRITE; struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; u32 dmactl; /* load PRD table addr. */ mb(); /* make sure PRD table writes are visible to controller */ iowrite32(ap->bmdma_prd_dma, base + ATAPI_DTB_ADR_REG); /* specify data direction, triple-check start bit is clear */ dmactl = ioread32(base + ATAPI_CONTROL1_REG); dmactl &= ~(ATAPI_CONTROL1_RW | ATAPI_CONTROL1_STOP); if (dmactl & ATAPI_CONTROL1_START) { dmactl &= ~ATAPI_CONTROL1_START; dmactl |= ATAPI_CONTROL1_STOP; } if (!rw) dmactl |= ATAPI_CONTROL1_RW; iowrite32(dmactl, base + ATAPI_CONTROL1_REG); /* issue r/w command */ ap->ops->sff_exec_command(ap, &qc->tf); } static void sata_rcar_bmdma_start(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; u32 dmactl; /* start host DMA transaction */ dmactl = ioread32(base + ATAPI_CONTROL1_REG); dmactl &= ~ATAPI_CONTROL1_STOP; dmactl |= ATAPI_CONTROL1_START; iowrite32(dmactl, base + ATAPI_CONTROL1_REG); } static void sata_rcar_bmdma_stop(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; u32 dmactl; /* force termination of DMA transfer if active */ dmactl = ioread32(base + ATAPI_CONTROL1_REG); if (dmactl & ATAPI_CONTROL1_START) { dmactl &= ~ATAPI_CONTROL1_START; dmactl |= ATAPI_CONTROL1_STOP; iowrite32(dmactl, base + ATAPI_CONTROL1_REG); } /* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */ ata_sff_dma_pause(ap); } static u8 sata_rcar_bmdma_status(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; u8 host_stat = 0; u32 status; status = ioread32(priv->base + ATAPI_STATUS_REG); if (status & ATAPI_STATUS_DEVINT) host_stat |= ATA_DMA_INTR; if (status & ATAPI_STATUS_ACT) host_stat |= ATA_DMA_ACTIVE; return host_stat; } static struct scsi_host_template sata_rcar_sht = { ATA_BASE_SHT(DRV_NAME), /* * This controller allows transfer chunks up to 512MB which cross 64KB * boundaries, therefore the DMA limits are more relaxed than standard * ATA SFF. */ .sg_tablesize = ATA_MAX_PRD, .dma_boundary = SATA_RCAR_DMA_BOUNDARY, }; static struct ata_port_operations sata_rcar_port_ops = { .inherits = &ata_bmdma_port_ops, .freeze = sata_rcar_freeze, .thaw = sata_rcar_thaw, .softreset = sata_rcar_softreset, .scr_read = sata_rcar_scr_read, .scr_write = sata_rcar_scr_write, .sff_dev_select = sata_rcar_dev_select, .sff_set_devctl = sata_rcar_set_devctl, .sff_check_status = sata_rcar_check_status, .sff_check_altstatus = sata_rcar_check_altstatus, .sff_tf_load = sata_rcar_tf_load, .sff_tf_read = sata_rcar_tf_read, .sff_exec_command = sata_rcar_exec_command, .sff_data_xfer = sata_rcar_data_xfer, .sff_drain_fifo = sata_rcar_drain_fifo, .qc_prep = sata_rcar_qc_prep, .bmdma_setup = sata_rcar_bmdma_setup, .bmdma_start = sata_rcar_bmdma_start, .bmdma_stop = sata_rcar_bmdma_stop, .bmdma_status = sata_rcar_bmdma_status, }; static void sata_rcar_serr_interrupt(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; struct ata_eh_info *ehi = &ap->link.eh_info; int freeze = 0; u32 serror; serror = ioread32(priv->base + SCRSERR_REG); if (!serror) return; DPRINTK("SError @host_intr: 0x%x\n", serror); /* first, analyze and record host port events */ ata_ehi_clear_desc(ehi); if (serror & (SERR_DEV_XCHG | SERR_PHYRDY_CHG)) { /* Setup a soft-reset EH action */ ata_ehi_hotplugged(ehi); ata_ehi_push_desc(ehi, "%s", "hotplug"); freeze = serror & SERR_COMM_WAKE ? 0 : 1; } /* freeze or abort */ if (freeze) ata_port_freeze(ap); else ata_port_abort(ap); } static void sata_rcar_ata_interrupt(struct ata_port *ap) { struct ata_queued_cmd *qc; int handled = 0; qc = ata_qc_from_tag(ap, ap->link.active_tag); if (qc) handled |= ata_bmdma_port_intr(ap, qc); /* be sure to clear ATA interrupt */ if (!handled) sata_rcar_check_status(ap); } static irqreturn_t sata_rcar_interrupt(int irq, void *dev_instance) { struct ata_host *host = dev_instance; struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; unsigned int handled = 0; struct ata_port *ap; u32 sataintstat; unsigned long flags; spin_lock_irqsave(&host->lock, flags); sataintstat = ioread32(base + SATAINTSTAT_REG); sataintstat &= SATA_RCAR_INT_MASK; if (!sataintstat) goto done; /* ack */ iowrite32(~sataintstat & 0x7ff, base + SATAINTSTAT_REG); ap = host->ports[0]; if (sataintstat & SATAINTSTAT_ATA) sata_rcar_ata_interrupt(ap); if (sataintstat & SATAINTSTAT_SERR) sata_rcar_serr_interrupt(ap); handled = 1; done: spin_unlock_irqrestore(&host->lock, flags); return IRQ_RETVAL(handled); } static void sata_rcar_setup_port(struct ata_host *host) { struct ata_port *ap = host->ports[0]; struct ata_ioports *ioaddr = &ap->ioaddr; struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; ap->ops = &sata_rcar_port_ops; ap->pio_mask = ATA_PIO4; ap->udma_mask = ATA_UDMA6; ap->flags |= ATA_FLAG_SATA; if (priv->type == RCAR_R8A7790_ES1_SATA) ap->flags |= ATA_FLAG_NO_DIPM; ioaddr->cmd_addr = base + SDATA_REG; ioaddr->ctl_addr = base + SSDEVCON_REG; ioaddr->scr_addr = base + SCRSSTS_REG; ioaddr->altstatus_addr = ioaddr->ctl_addr; ioaddr->data_addr = ioaddr->cmd_addr + (ATA_REG_DATA << 2); ioaddr->error_addr = ioaddr->cmd_addr + (ATA_REG_ERR << 2); ioaddr->feature_addr = ioaddr->cmd_addr + (ATA_REG_FEATURE << 2); ioaddr->nsect_addr = ioaddr->cmd_addr + (ATA_REG_NSECT << 2); ioaddr->lbal_addr = ioaddr->cmd_addr + (ATA_REG_LBAL << 2); ioaddr->lbam_addr = ioaddr->cmd_addr + (ATA_REG_LBAM << 2); ioaddr->lbah_addr = ioaddr->cmd_addr + (ATA_REG_LBAH << 2); ioaddr->device_addr = ioaddr->cmd_addr + (ATA_REG_DEVICE << 2); ioaddr->status_addr = ioaddr->cmd_addr + (ATA_REG_STATUS << 2); ioaddr->command_addr = ioaddr->cmd_addr + (ATA_REG_CMD << 2); } static void sata_rcar_init_controller(struct ata_host *host) { struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; u32 val; /* reset and setup phy */ switch (priv->type) { case RCAR_GEN1_SATA: sata_rcar_gen1_phy_init(priv); break; case RCAR_GEN2_SATA: case RCAR_R8A7790_ES1_SATA: sata_rcar_gen2_phy_init(priv); break; default: dev_warn(host->dev, "SATA phy is not initialized\n"); break; } /* SATA-IP reset state */ val = ioread32(base + ATAPI_CONTROL1_REG); val |= ATAPI_CONTROL1_RESET; iowrite32(val, base + ATAPI_CONTROL1_REG); /* ISM mode, PRD mode, DTEND flag at bit 0 */ val = ioread32(base + ATAPI_CONTROL1_REG); val |= ATAPI_CONTROL1_ISM; val |= ATAPI_CONTROL1_DESE; val |= ATAPI_CONTROL1_DTA32M; iowrite32(val, base + ATAPI_CONTROL1_REG); /* Release the SATA-IP from the reset state */ val = ioread32(base + ATAPI_CONTROL1_REG); val &= ~ATAPI_CONTROL1_RESET; iowrite32(val, base + ATAPI_CONTROL1_REG); /* ack and mask */ iowrite32(0, base + SATAINTSTAT_REG); iowrite32(0x7ff, base + SATAINTMASK_REG); /* enable interrupts */ iowrite32(ATAPI_INT_ENABLE_SATAINT, base + ATAPI_INT_ENABLE_REG); } static struct of_device_id sata_rcar_match[] = { { /* Deprecated by "renesas,sata-r8a7779" */ .compatible = "renesas,rcar-sata", .data = (void *)RCAR_GEN1_SATA, }, { .compatible = "renesas,sata-r8a7779", .data = (void *)RCAR_GEN1_SATA, }, { .compatible = "renesas,sata-r8a7790", .data = (void *)RCAR_GEN2_SATA }, { .compatible = "renesas,sata-r8a7790-es1", .data = (void *)RCAR_R8A7790_ES1_SATA }, { .compatible = "renesas,sata-r8a7791", .data = (void *)RCAR_GEN2_SATA }, { .compatible = "renesas,sata-r8a7793", .data = (void *)RCAR_GEN2_SATA }, { }, }; MODULE_DEVICE_TABLE(of, sata_rcar_match); static const struct platform_device_id sata_rcar_id_table[] = { { "sata_rcar", RCAR_GEN1_SATA }, /* Deprecated by "sata-r8a7779" */ { "sata-r8a7779", RCAR_GEN1_SATA }, { "sata-r8a7790", RCAR_GEN2_SATA }, { "sata-r8a7790-es1", RCAR_R8A7790_ES1_SATA }, { "sata-r8a7791", RCAR_GEN2_SATA }, { "sata-r8a7793", RCAR_GEN2_SATA }, { }, }; MODULE_DEVICE_TABLE(platform, sata_rcar_id_table); static int sata_rcar_probe(struct platform_device *pdev) { const struct of_device_id *of_id; struct ata_host *host; struct sata_rcar_priv *priv; struct resource *mem; int irq; int ret = 0; irq = platform_get_irq(pdev, 0); if (irq <= 0) return -EINVAL; priv = devm_kzalloc(&pdev->dev, sizeof(struct sata_rcar_priv), GFP_KERNEL); if (!priv) return -ENOMEM; of_id = of_match_device(sata_rcar_match, &pdev->dev); if (of_id) priv->type = (enum sata_rcar_type)of_id->data; else priv->type = platform_get_device_id(pdev)->driver_data; priv->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(priv->clk)) { dev_err(&pdev->dev, "failed to get access to sata clock\n"); return PTR_ERR(priv->clk); } clk_prepare_enable(priv->clk); host = ata_host_alloc(&pdev->dev, 1); if (!host) { dev_err(&pdev->dev, "ata_host_alloc failed\n"); ret = -ENOMEM; goto cleanup; } host->private_data = priv; mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); priv->base = devm_ioremap_resource(&pdev->dev, mem); if (IS_ERR(priv->base)) { ret = PTR_ERR(priv->base); goto cleanup; } /* setup port */ sata_rcar_setup_port(host); /* initialize host controller */ sata_rcar_init_controller(host); ret = ata_host_activate(host, irq, sata_rcar_interrupt, 0, &sata_rcar_sht); if (!ret) return 0; cleanup: clk_disable_unprepare(priv->clk); return ret; } static int sata_rcar_remove(struct platform_device *pdev) { struct ata_host *host = platform_get_drvdata(pdev); struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; ata_host_detach(host); /* disable interrupts */ iowrite32(0, base + ATAPI_INT_ENABLE_REG); /* ack and mask */ iowrite32(0, base + SATAINTSTAT_REG); iowrite32(0x7ff, base + SATAINTMASK_REG); clk_disable_unprepare(priv->clk); return 0; } #ifdef CONFIG_PM_SLEEP static int sata_rcar_suspend(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; int ret; ret = ata_host_suspend(host, PMSG_SUSPEND); if (!ret) { /* disable interrupts */ iowrite32(0, base + ATAPI_INT_ENABLE_REG); /* mask */ iowrite32(0x7ff, base + SATAINTMASK_REG); clk_disable_unprepare(priv->clk); } return ret; } static int sata_rcar_resume(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; clk_prepare_enable(priv->clk); /* ack and mask */ iowrite32(0, base + SATAINTSTAT_REG); iowrite32(0x7ff, base + SATAINTMASK_REG); /* enable interrupts */ iowrite32(ATAPI_INT_ENABLE_SATAINT, base + ATAPI_INT_ENABLE_REG); ata_host_resume(host); return 0; } static int sata_rcar_restore(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct sata_rcar_priv *priv = host->private_data; clk_prepare_enable(priv->clk); sata_rcar_setup_port(host); /* initialize host controller */ sata_rcar_init_controller(host); ata_host_resume(host); return 0; } static const struct dev_pm_ops sata_rcar_pm_ops = { .suspend = sata_rcar_suspend, .resume = sata_rcar_resume, .freeze = sata_rcar_suspend, .thaw = sata_rcar_resume, .poweroff = sata_rcar_suspend, .restore = sata_rcar_restore, }; #endif static struct platform_driver sata_rcar_driver = { .probe = sata_rcar_probe, .remove = sata_rcar_remove, .id_table = sata_rcar_id_table, .driver = { .name = DRV_NAME, .of_match_table = sata_rcar_match, #ifdef CONFIG_PM_SLEEP .pm = &sata_rcar_pm_ops, #endif }, }; module_platform_driver(sata_rcar_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Vladimir Barinov"); MODULE_DESCRIPTION("Renesas R-Car SATA controller low level driver");
gpl-2.0
DIGImend/linux
drivers/ata/sata_rcar.c
538
27418
/* * Renesas R-Car SATA driver * * Author: Vladimir Barinov <source@cogentembedded.com> * Copyright (C) 2013-2015 Cogent Embedded, Inc. * Copyright (C) 2013-2015 Renesas Solutions Corp. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/ata.h> #include <linux/libata.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/err.h> #define DRV_NAME "sata_rcar" /* SH-Navi2G/ATAPI-ATA compatible task registers */ #define DATA_REG 0x100 #define SDEVCON_REG 0x138 /* SH-Navi2G/ATAPI module compatible control registers */ #define ATAPI_CONTROL1_REG 0x180 #define ATAPI_STATUS_REG 0x184 #define ATAPI_INT_ENABLE_REG 0x188 #define ATAPI_DTB_ADR_REG 0x198 #define ATAPI_DMA_START_ADR_REG 0x19C #define ATAPI_DMA_TRANS_CNT_REG 0x1A0 #define ATAPI_CONTROL2_REG 0x1A4 #define ATAPI_SIG_ST_REG 0x1B0 #define ATAPI_BYTE_SWAP_REG 0x1BC /* ATAPI control 1 register (ATAPI_CONTROL1) bits */ #define ATAPI_CONTROL1_ISM BIT(16) #define ATAPI_CONTROL1_DTA32M BIT(11) #define ATAPI_CONTROL1_RESET BIT(7) #define ATAPI_CONTROL1_DESE BIT(3) #define ATAPI_CONTROL1_RW BIT(2) #define ATAPI_CONTROL1_STOP BIT(1) #define ATAPI_CONTROL1_START BIT(0) /* ATAPI status register (ATAPI_STATUS) bits */ #define ATAPI_STATUS_SATAINT BIT(11) #define ATAPI_STATUS_DNEND BIT(6) #define ATAPI_STATUS_DEVTRM BIT(5) #define ATAPI_STATUS_DEVINT BIT(4) #define ATAPI_STATUS_ERR BIT(2) #define ATAPI_STATUS_NEND BIT(1) #define ATAPI_STATUS_ACT BIT(0) /* Interrupt enable register (ATAPI_INT_ENABLE) bits */ #define ATAPI_INT_ENABLE_SATAINT BIT(11) #define ATAPI_INT_ENABLE_DNEND BIT(6) #define ATAPI_INT_ENABLE_DEVTRM BIT(5) #define ATAPI_INT_ENABLE_DEVINT BIT(4) #define ATAPI_INT_ENABLE_ERR BIT(2) #define ATAPI_INT_ENABLE_NEND BIT(1) #define ATAPI_INT_ENABLE_ACT BIT(0) /* Access control registers for physical layer control register */ #define SATAPHYADDR_REG 0x200 #define SATAPHYWDATA_REG 0x204 #define SATAPHYACCEN_REG 0x208 #define SATAPHYRESET_REG 0x20C #define SATAPHYRDATA_REG 0x210 #define SATAPHYACK_REG 0x214 /* Physical layer control address command register (SATAPHYADDR) bits */ #define SATAPHYADDR_PHYRATEMODE BIT(10) #define SATAPHYADDR_PHYCMD_READ BIT(9) #define SATAPHYADDR_PHYCMD_WRITE BIT(8) /* Physical layer control enable register (SATAPHYACCEN) bits */ #define SATAPHYACCEN_PHYLANE BIT(0) /* Physical layer control reset register (SATAPHYRESET) bits */ #define SATAPHYRESET_PHYRST BIT(1) #define SATAPHYRESET_PHYSRES BIT(0) /* Physical layer control acknowledge register (SATAPHYACK) bits */ #define SATAPHYACK_PHYACK BIT(0) /* Serial-ATA HOST control registers */ #define BISTCONF_REG 0x102C #define SDATA_REG 0x1100 #define SSDEVCON_REG 0x1204 #define SCRSSTS_REG 0x1400 #define SCRSERR_REG 0x1404 #define SCRSCON_REG 0x1408 #define SCRSACT_REG 0x140C #define SATAINTSTAT_REG 0x1508 #define SATAINTMASK_REG 0x150C /* SATA INT status register (SATAINTSTAT) bits */ #define SATAINTSTAT_SERR BIT(3) #define SATAINTSTAT_ATA BIT(0) /* SATA INT mask register (SATAINTSTAT) bits */ #define SATAINTMASK_SERRMSK BIT(3) #define SATAINTMASK_ERRMSK BIT(2) #define SATAINTMASK_ERRCRTMSK BIT(1) #define SATAINTMASK_ATAMSK BIT(0) #define SATA_RCAR_INT_MASK (SATAINTMASK_SERRMSK | \ SATAINTMASK_ATAMSK) /* Physical Layer Control Registers */ #define SATAPCTLR1_REG 0x43 #define SATAPCTLR2_REG 0x52 #define SATAPCTLR3_REG 0x5A #define SATAPCTLR4_REG 0x60 /* Descriptor table word 0 bit (when DTA32M = 1) */ #define SATA_RCAR_DTEND BIT(0) #define SATA_RCAR_DMA_BOUNDARY 0x1FFFFFFEUL /* Gen2 Physical Layer Control Registers */ #define RCAR_GEN2_PHY_CTL1_REG 0x1704 #define RCAR_GEN2_PHY_CTL1 0x34180002 #define RCAR_GEN2_PHY_CTL1_SS 0xC180 /* Spread Spectrum */ #define RCAR_GEN2_PHY_CTL2_REG 0x170C #define RCAR_GEN2_PHY_CTL2 0x00002303 #define RCAR_GEN2_PHY_CTL3_REG 0x171C #define RCAR_GEN2_PHY_CTL3 0x000B0194 #define RCAR_GEN2_PHY_CTL4_REG 0x1724 #define RCAR_GEN2_PHY_CTL4 0x00030994 #define RCAR_GEN2_PHY_CTL5_REG 0x1740 #define RCAR_GEN2_PHY_CTL5 0x03004001 #define RCAR_GEN2_PHY_CTL5_DC BIT(1) /* DC connection */ #define RCAR_GEN2_PHY_CTL5_TR BIT(2) /* Termination Resistor */ enum sata_rcar_type { RCAR_GEN1_SATA, RCAR_GEN2_SATA, RCAR_R8A7790_ES1_SATA, }; struct sata_rcar_priv { void __iomem *base; struct clk *clk; enum sata_rcar_type type; }; static void sata_rcar_gen1_phy_preinit(struct sata_rcar_priv *priv) { void __iomem *base = priv->base; /* idle state */ iowrite32(0, base + SATAPHYADDR_REG); /* reset */ iowrite32(SATAPHYRESET_PHYRST, base + SATAPHYRESET_REG); udelay(10); /* deassert reset */ iowrite32(0, base + SATAPHYRESET_REG); } static void sata_rcar_gen1_phy_write(struct sata_rcar_priv *priv, u16 reg, u32 val, int group) { void __iomem *base = priv->base; int timeout; /* deassert reset */ iowrite32(0, base + SATAPHYRESET_REG); /* lane 1 */ iowrite32(SATAPHYACCEN_PHYLANE, base + SATAPHYACCEN_REG); /* write phy register value */ iowrite32(val, base + SATAPHYWDATA_REG); /* set register group */ if (group) reg |= SATAPHYADDR_PHYRATEMODE; /* write command */ iowrite32(SATAPHYADDR_PHYCMD_WRITE | reg, base + SATAPHYADDR_REG); /* wait for ack */ for (timeout = 0; timeout < 100; timeout++) { val = ioread32(base + SATAPHYACK_REG); if (val & SATAPHYACK_PHYACK) break; } if (timeout >= 100) pr_err("%s timeout\n", __func__); /* idle state */ iowrite32(0, base + SATAPHYADDR_REG); } static void sata_rcar_gen1_phy_init(struct sata_rcar_priv *priv) { sata_rcar_gen1_phy_preinit(priv); sata_rcar_gen1_phy_write(priv, SATAPCTLR1_REG, 0x00200188, 0); sata_rcar_gen1_phy_write(priv, SATAPCTLR1_REG, 0x00200188, 1); sata_rcar_gen1_phy_write(priv, SATAPCTLR3_REG, 0x0000A061, 0); sata_rcar_gen1_phy_write(priv, SATAPCTLR2_REG, 0x20000000, 0); sata_rcar_gen1_phy_write(priv, SATAPCTLR2_REG, 0x20000000, 1); sata_rcar_gen1_phy_write(priv, SATAPCTLR4_REG, 0x28E80000, 0); } static void sata_rcar_gen2_phy_init(struct sata_rcar_priv *priv) { void __iomem *base = priv->base; iowrite32(RCAR_GEN2_PHY_CTL1, base + RCAR_GEN2_PHY_CTL1_REG); iowrite32(RCAR_GEN2_PHY_CTL2, base + RCAR_GEN2_PHY_CTL2_REG); iowrite32(RCAR_GEN2_PHY_CTL3, base + RCAR_GEN2_PHY_CTL3_REG); iowrite32(RCAR_GEN2_PHY_CTL4, base + RCAR_GEN2_PHY_CTL4_REG); iowrite32(RCAR_GEN2_PHY_CTL5 | RCAR_GEN2_PHY_CTL5_DC | RCAR_GEN2_PHY_CTL5_TR, base + RCAR_GEN2_PHY_CTL5_REG); } static void sata_rcar_freeze(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; /* mask */ iowrite32(0x7ff, priv->base + SATAINTMASK_REG); ata_sff_freeze(ap); } static void sata_rcar_thaw(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; /* ack */ iowrite32(~(u32)SATA_RCAR_INT_MASK, base + SATAINTSTAT_REG); ata_sff_thaw(ap); /* unmask */ iowrite32(0x7ff & ~SATA_RCAR_INT_MASK, base + SATAINTMASK_REG); } static void sata_rcar_ioread16_rep(void __iomem *reg, void *buffer, int count) { u16 *ptr = buffer; while (count--) { u16 data = ioread32(reg); *ptr++ = data; } } static void sata_rcar_iowrite16_rep(void __iomem *reg, void *buffer, int count) { const u16 *ptr = buffer; while (count--) iowrite32(*ptr++, reg); } static u8 sata_rcar_check_status(struct ata_port *ap) { return ioread32(ap->ioaddr.status_addr); } static u8 sata_rcar_check_altstatus(struct ata_port *ap) { return ioread32(ap->ioaddr.altstatus_addr); } static void sata_rcar_set_devctl(struct ata_port *ap, u8 ctl) { iowrite32(ctl, ap->ioaddr.ctl_addr); } static void sata_rcar_dev_select(struct ata_port *ap, unsigned int device) { iowrite32(ATA_DEVICE_OBS, ap->ioaddr.device_addr); ata_sff_pause(ap); /* needed; also flushes, for mmio */ } static unsigned int sata_rcar_ata_devchk(struct ata_port *ap, unsigned int device) { struct ata_ioports *ioaddr = &ap->ioaddr; u8 nsect, lbal; sata_rcar_dev_select(ap, device); iowrite32(0x55, ioaddr->nsect_addr); iowrite32(0xaa, ioaddr->lbal_addr); iowrite32(0xaa, ioaddr->nsect_addr); iowrite32(0x55, ioaddr->lbal_addr); iowrite32(0x55, ioaddr->nsect_addr); iowrite32(0xaa, ioaddr->lbal_addr); nsect = ioread32(ioaddr->nsect_addr); lbal = ioread32(ioaddr->lbal_addr); if (nsect == 0x55 && lbal == 0xaa) return 1; /* found a device */ return 0; /* nothing found */ } static int sata_rcar_wait_after_reset(struct ata_link *link, unsigned long deadline) { struct ata_port *ap = link->ap; ata_msleep(ap, ATA_WAIT_AFTER_RESET); return ata_sff_wait_ready(link, deadline); } static int sata_rcar_bus_softreset(struct ata_port *ap, unsigned long deadline) { struct ata_ioports *ioaddr = &ap->ioaddr; DPRINTK("ata%u: bus reset via SRST\n", ap->print_id); /* software reset. causes dev0 to be selected */ iowrite32(ap->ctl, ioaddr->ctl_addr); udelay(20); iowrite32(ap->ctl | ATA_SRST, ioaddr->ctl_addr); udelay(20); iowrite32(ap->ctl, ioaddr->ctl_addr); ap->last_ctl = ap->ctl; /* wait the port to become ready */ return sata_rcar_wait_after_reset(&ap->link, deadline); } static int sata_rcar_softreset(struct ata_link *link, unsigned int *classes, unsigned long deadline) { struct ata_port *ap = link->ap; unsigned int devmask = 0; int rc; u8 err; /* determine if device 0 is present */ if (sata_rcar_ata_devchk(ap, 0)) devmask |= 1 << 0; /* issue bus reset */ DPRINTK("about to softreset, devmask=%x\n", devmask); rc = sata_rcar_bus_softreset(ap, deadline); /* if link is occupied, -ENODEV too is an error */ if (rc && (rc != -ENODEV || sata_scr_valid(link))) { ata_link_err(link, "SRST failed (errno=%d)\n", rc); return rc; } /* determine by signature whether we have ATA or ATAPI devices */ classes[0] = ata_sff_dev_classify(&link->device[0], devmask, &err); DPRINTK("classes[0]=%u\n", classes[0]); return 0; } static void sata_rcar_tf_load(struct ata_port *ap, const struct ata_taskfile *tf) { struct ata_ioports *ioaddr = &ap->ioaddr; unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR; if (tf->ctl != ap->last_ctl) { iowrite32(tf->ctl, ioaddr->ctl_addr); ap->last_ctl = tf->ctl; ata_wait_idle(ap); } if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) { iowrite32(tf->hob_feature, ioaddr->feature_addr); iowrite32(tf->hob_nsect, ioaddr->nsect_addr); iowrite32(tf->hob_lbal, ioaddr->lbal_addr); iowrite32(tf->hob_lbam, ioaddr->lbam_addr); iowrite32(tf->hob_lbah, ioaddr->lbah_addr); VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n", tf->hob_feature, tf->hob_nsect, tf->hob_lbal, tf->hob_lbam, tf->hob_lbah); } if (is_addr) { iowrite32(tf->feature, ioaddr->feature_addr); iowrite32(tf->nsect, ioaddr->nsect_addr); iowrite32(tf->lbal, ioaddr->lbal_addr); iowrite32(tf->lbam, ioaddr->lbam_addr); iowrite32(tf->lbah, ioaddr->lbah_addr); VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n", tf->feature, tf->nsect, tf->lbal, tf->lbam, tf->lbah); } if (tf->flags & ATA_TFLAG_DEVICE) { iowrite32(tf->device, ioaddr->device_addr); VPRINTK("device 0x%X\n", tf->device); } ata_wait_idle(ap); } static void sata_rcar_tf_read(struct ata_port *ap, struct ata_taskfile *tf) { struct ata_ioports *ioaddr = &ap->ioaddr; tf->command = sata_rcar_check_status(ap); tf->feature = ioread32(ioaddr->error_addr); tf->nsect = ioread32(ioaddr->nsect_addr); tf->lbal = ioread32(ioaddr->lbal_addr); tf->lbam = ioread32(ioaddr->lbam_addr); tf->lbah = ioread32(ioaddr->lbah_addr); tf->device = ioread32(ioaddr->device_addr); if (tf->flags & ATA_TFLAG_LBA48) { iowrite32(tf->ctl | ATA_HOB, ioaddr->ctl_addr); tf->hob_feature = ioread32(ioaddr->error_addr); tf->hob_nsect = ioread32(ioaddr->nsect_addr); tf->hob_lbal = ioread32(ioaddr->lbal_addr); tf->hob_lbam = ioread32(ioaddr->lbam_addr); tf->hob_lbah = ioread32(ioaddr->lbah_addr); iowrite32(tf->ctl, ioaddr->ctl_addr); ap->last_ctl = tf->ctl; } } static void sata_rcar_exec_command(struct ata_port *ap, const struct ata_taskfile *tf) { DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command); iowrite32(tf->command, ap->ioaddr.command_addr); ata_sff_pause(ap); } static unsigned int sata_rcar_data_xfer(struct ata_device *dev, unsigned char *buf, unsigned int buflen, int rw) { struct ata_port *ap = dev->link->ap; void __iomem *data_addr = ap->ioaddr.data_addr; unsigned int words = buflen >> 1; /* Transfer multiple of 2 bytes */ if (rw == READ) sata_rcar_ioread16_rep(data_addr, buf, words); else sata_rcar_iowrite16_rep(data_addr, buf, words); /* Transfer trailing byte, if any. */ if (unlikely(buflen & 0x01)) { unsigned char pad[2] = { }; /* Point buf to the tail of buffer */ buf += buflen - 1; /* * Use io*16_rep() accessors here as well to avoid pointlessly * swapping bytes to and from on the big endian machines... */ if (rw == READ) { sata_rcar_ioread16_rep(data_addr, pad, 1); *buf = pad[0]; } else { pad[0] = *buf; sata_rcar_iowrite16_rep(data_addr, pad, 1); } words++; } return words << 1; } static void sata_rcar_drain_fifo(struct ata_queued_cmd *qc) { int count; struct ata_port *ap; /* We only need to flush incoming data when a command was running */ if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE) return; ap = qc->ap; /* Drain up to 64K of data before we give up this recovery method */ for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ) && count < 65536; count += 2) ioread32(ap->ioaddr.data_addr); /* Can become DEBUG later */ if (count) ata_port_dbg(ap, "drained %d bytes to clear DRQ\n", count); } static int sata_rcar_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val) { if (sc_reg > SCR_ACTIVE) return -EINVAL; *val = ioread32(link->ap->ioaddr.scr_addr + (sc_reg << 2)); return 0; } static int sata_rcar_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val) { if (sc_reg > SCR_ACTIVE) return -EINVAL; iowrite32(val, link->ap->ioaddr.scr_addr + (sc_reg << 2)); return 0; } static void sata_rcar_bmdma_fill_sg(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct ata_bmdma_prd *prd = ap->bmdma_prd; struct scatterlist *sg; unsigned int si; for_each_sg(qc->sg, sg, qc->n_elem, si) { u32 addr, sg_len; /* * Note: h/w doesn't support 64-bit, so we unconditionally * truncate dma_addr_t to u32. */ addr = (u32)sg_dma_address(sg); sg_len = sg_dma_len(sg); prd[si].addr = cpu_to_le32(addr); prd[si].flags_len = cpu_to_le32(sg_len); VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", si, addr, sg_len); } /* end-of-table flag */ prd[si - 1].addr |= cpu_to_le32(SATA_RCAR_DTEND); } static void sata_rcar_qc_prep(struct ata_queued_cmd *qc) { if (!(qc->flags & ATA_QCFLAG_DMAMAP)) return; sata_rcar_bmdma_fill_sg(qc); } static void sata_rcar_bmdma_setup(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; unsigned int rw = qc->tf.flags & ATA_TFLAG_WRITE; struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; u32 dmactl; /* load PRD table addr. */ mb(); /* make sure PRD table writes are visible to controller */ iowrite32(ap->bmdma_prd_dma, base + ATAPI_DTB_ADR_REG); /* specify data direction, triple-check start bit is clear */ dmactl = ioread32(base + ATAPI_CONTROL1_REG); dmactl &= ~(ATAPI_CONTROL1_RW | ATAPI_CONTROL1_STOP); if (dmactl & ATAPI_CONTROL1_START) { dmactl &= ~ATAPI_CONTROL1_START; dmactl |= ATAPI_CONTROL1_STOP; } if (!rw) dmactl |= ATAPI_CONTROL1_RW; iowrite32(dmactl, base + ATAPI_CONTROL1_REG); /* issue r/w command */ ap->ops->sff_exec_command(ap, &qc->tf); } static void sata_rcar_bmdma_start(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; u32 dmactl; /* start host DMA transaction */ dmactl = ioread32(base + ATAPI_CONTROL1_REG); dmactl &= ~ATAPI_CONTROL1_STOP; dmactl |= ATAPI_CONTROL1_START; iowrite32(dmactl, base + ATAPI_CONTROL1_REG); } static void sata_rcar_bmdma_stop(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct sata_rcar_priv *priv = ap->host->private_data; void __iomem *base = priv->base; u32 dmactl; /* force termination of DMA transfer if active */ dmactl = ioread32(base + ATAPI_CONTROL1_REG); if (dmactl & ATAPI_CONTROL1_START) { dmactl &= ~ATAPI_CONTROL1_START; dmactl |= ATAPI_CONTROL1_STOP; iowrite32(dmactl, base + ATAPI_CONTROL1_REG); } /* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */ ata_sff_dma_pause(ap); } static u8 sata_rcar_bmdma_status(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; u8 host_stat = 0; u32 status; status = ioread32(priv->base + ATAPI_STATUS_REG); if (status & ATAPI_STATUS_DEVINT) host_stat |= ATA_DMA_INTR; if (status & ATAPI_STATUS_ACT) host_stat |= ATA_DMA_ACTIVE; return host_stat; } static struct scsi_host_template sata_rcar_sht = { ATA_BASE_SHT(DRV_NAME), /* * This controller allows transfer chunks up to 512MB which cross 64KB * boundaries, therefore the DMA limits are more relaxed than standard * ATA SFF. */ .sg_tablesize = ATA_MAX_PRD, .dma_boundary = SATA_RCAR_DMA_BOUNDARY, }; static struct ata_port_operations sata_rcar_port_ops = { .inherits = &ata_bmdma_port_ops, .freeze = sata_rcar_freeze, .thaw = sata_rcar_thaw, .softreset = sata_rcar_softreset, .scr_read = sata_rcar_scr_read, .scr_write = sata_rcar_scr_write, .sff_dev_select = sata_rcar_dev_select, .sff_set_devctl = sata_rcar_set_devctl, .sff_check_status = sata_rcar_check_status, .sff_check_altstatus = sata_rcar_check_altstatus, .sff_tf_load = sata_rcar_tf_load, .sff_tf_read = sata_rcar_tf_read, .sff_exec_command = sata_rcar_exec_command, .sff_data_xfer = sata_rcar_data_xfer, .sff_drain_fifo = sata_rcar_drain_fifo, .qc_prep = sata_rcar_qc_prep, .bmdma_setup = sata_rcar_bmdma_setup, .bmdma_start = sata_rcar_bmdma_start, .bmdma_stop = sata_rcar_bmdma_stop, .bmdma_status = sata_rcar_bmdma_status, }; static void sata_rcar_serr_interrupt(struct ata_port *ap) { struct sata_rcar_priv *priv = ap->host->private_data; struct ata_eh_info *ehi = &ap->link.eh_info; int freeze = 0; u32 serror; serror = ioread32(priv->base + SCRSERR_REG); if (!serror) return; DPRINTK("SError @host_intr: 0x%x\n", serror); /* first, analyze and record host port events */ ata_ehi_clear_desc(ehi); if (serror & (SERR_DEV_XCHG | SERR_PHYRDY_CHG)) { /* Setup a soft-reset EH action */ ata_ehi_hotplugged(ehi); ata_ehi_push_desc(ehi, "%s", "hotplug"); freeze = serror & SERR_COMM_WAKE ? 0 : 1; } /* freeze or abort */ if (freeze) ata_port_freeze(ap); else ata_port_abort(ap); } static void sata_rcar_ata_interrupt(struct ata_port *ap) { struct ata_queued_cmd *qc; int handled = 0; qc = ata_qc_from_tag(ap, ap->link.active_tag); if (qc) handled |= ata_bmdma_port_intr(ap, qc); /* be sure to clear ATA interrupt */ if (!handled) sata_rcar_check_status(ap); } static irqreturn_t sata_rcar_interrupt(int irq, void *dev_instance) { struct ata_host *host = dev_instance; struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; unsigned int handled = 0; struct ata_port *ap; u32 sataintstat; unsigned long flags; spin_lock_irqsave(&host->lock, flags); sataintstat = ioread32(base + SATAINTSTAT_REG); sataintstat &= SATA_RCAR_INT_MASK; if (!sataintstat) goto done; /* ack */ iowrite32(~sataintstat & 0x7ff, base + SATAINTSTAT_REG); ap = host->ports[0]; if (sataintstat & SATAINTSTAT_ATA) sata_rcar_ata_interrupt(ap); if (sataintstat & SATAINTSTAT_SERR) sata_rcar_serr_interrupt(ap); handled = 1; done: spin_unlock_irqrestore(&host->lock, flags); return IRQ_RETVAL(handled); } static void sata_rcar_setup_port(struct ata_host *host) { struct ata_port *ap = host->ports[0]; struct ata_ioports *ioaddr = &ap->ioaddr; struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; ap->ops = &sata_rcar_port_ops; ap->pio_mask = ATA_PIO4; ap->udma_mask = ATA_UDMA6; ap->flags |= ATA_FLAG_SATA; if (priv->type == RCAR_R8A7790_ES1_SATA) ap->flags |= ATA_FLAG_NO_DIPM; ioaddr->cmd_addr = base + SDATA_REG; ioaddr->ctl_addr = base + SSDEVCON_REG; ioaddr->scr_addr = base + SCRSSTS_REG; ioaddr->altstatus_addr = ioaddr->ctl_addr; ioaddr->data_addr = ioaddr->cmd_addr + (ATA_REG_DATA << 2); ioaddr->error_addr = ioaddr->cmd_addr + (ATA_REG_ERR << 2); ioaddr->feature_addr = ioaddr->cmd_addr + (ATA_REG_FEATURE << 2); ioaddr->nsect_addr = ioaddr->cmd_addr + (ATA_REG_NSECT << 2); ioaddr->lbal_addr = ioaddr->cmd_addr + (ATA_REG_LBAL << 2); ioaddr->lbam_addr = ioaddr->cmd_addr + (ATA_REG_LBAM << 2); ioaddr->lbah_addr = ioaddr->cmd_addr + (ATA_REG_LBAH << 2); ioaddr->device_addr = ioaddr->cmd_addr + (ATA_REG_DEVICE << 2); ioaddr->status_addr = ioaddr->cmd_addr + (ATA_REG_STATUS << 2); ioaddr->command_addr = ioaddr->cmd_addr + (ATA_REG_CMD << 2); } static void sata_rcar_init_controller(struct ata_host *host) { struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; u32 val; /* reset and setup phy */ switch (priv->type) { case RCAR_GEN1_SATA: sata_rcar_gen1_phy_init(priv); break; case RCAR_GEN2_SATA: case RCAR_R8A7790_ES1_SATA: sata_rcar_gen2_phy_init(priv); break; default: dev_warn(host->dev, "SATA phy is not initialized\n"); break; } /* SATA-IP reset state */ val = ioread32(base + ATAPI_CONTROL1_REG); val |= ATAPI_CONTROL1_RESET; iowrite32(val, base + ATAPI_CONTROL1_REG); /* ISM mode, PRD mode, DTEND flag at bit 0 */ val = ioread32(base + ATAPI_CONTROL1_REG); val |= ATAPI_CONTROL1_ISM; val |= ATAPI_CONTROL1_DESE; val |= ATAPI_CONTROL1_DTA32M; iowrite32(val, base + ATAPI_CONTROL1_REG); /* Release the SATA-IP from the reset state */ val = ioread32(base + ATAPI_CONTROL1_REG); val &= ~ATAPI_CONTROL1_RESET; iowrite32(val, base + ATAPI_CONTROL1_REG); /* ack and mask */ iowrite32(0, base + SATAINTSTAT_REG); iowrite32(0x7ff, base + SATAINTMASK_REG); /* enable interrupts */ iowrite32(ATAPI_INT_ENABLE_SATAINT, base + ATAPI_INT_ENABLE_REG); } static struct of_device_id sata_rcar_match[] = { { /* Deprecated by "renesas,sata-r8a7779" */ .compatible = "renesas,rcar-sata", .data = (void *)RCAR_GEN1_SATA, }, { .compatible = "renesas,sata-r8a7779", .data = (void *)RCAR_GEN1_SATA, }, { .compatible = "renesas,sata-r8a7790", .data = (void *)RCAR_GEN2_SATA }, { .compatible = "renesas,sata-r8a7790-es1", .data = (void *)RCAR_R8A7790_ES1_SATA }, { .compatible = "renesas,sata-r8a7791", .data = (void *)RCAR_GEN2_SATA }, { .compatible = "renesas,sata-r8a7793", .data = (void *)RCAR_GEN2_SATA }, { }, }; MODULE_DEVICE_TABLE(of, sata_rcar_match); static const struct platform_device_id sata_rcar_id_table[] = { { "sata_rcar", RCAR_GEN1_SATA }, /* Deprecated by "sata-r8a7779" */ { "sata-r8a7779", RCAR_GEN1_SATA }, { "sata-r8a7790", RCAR_GEN2_SATA }, { "sata-r8a7790-es1", RCAR_R8A7790_ES1_SATA }, { "sata-r8a7791", RCAR_GEN2_SATA }, { "sata-r8a7793", RCAR_GEN2_SATA }, { }, }; MODULE_DEVICE_TABLE(platform, sata_rcar_id_table); static int sata_rcar_probe(struct platform_device *pdev) { const struct of_device_id *of_id; struct ata_host *host; struct sata_rcar_priv *priv; struct resource *mem; int irq; int ret = 0; irq = platform_get_irq(pdev, 0); if (irq <= 0) return -EINVAL; priv = devm_kzalloc(&pdev->dev, sizeof(struct sata_rcar_priv), GFP_KERNEL); if (!priv) return -ENOMEM; of_id = of_match_device(sata_rcar_match, &pdev->dev); if (of_id) priv->type = (enum sata_rcar_type)of_id->data; else priv->type = platform_get_device_id(pdev)->driver_data; priv->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(priv->clk)) { dev_err(&pdev->dev, "failed to get access to sata clock\n"); return PTR_ERR(priv->clk); } clk_prepare_enable(priv->clk); host = ata_host_alloc(&pdev->dev, 1); if (!host) { dev_err(&pdev->dev, "ata_host_alloc failed\n"); ret = -ENOMEM; goto cleanup; } host->private_data = priv; mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); priv->base = devm_ioremap_resource(&pdev->dev, mem); if (IS_ERR(priv->base)) { ret = PTR_ERR(priv->base); goto cleanup; } /* setup port */ sata_rcar_setup_port(host); /* initialize host controller */ sata_rcar_init_controller(host); ret = ata_host_activate(host, irq, sata_rcar_interrupt, 0, &sata_rcar_sht); if (!ret) return 0; cleanup: clk_disable_unprepare(priv->clk); return ret; } static int sata_rcar_remove(struct platform_device *pdev) { struct ata_host *host = platform_get_drvdata(pdev); struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; ata_host_detach(host); /* disable interrupts */ iowrite32(0, base + ATAPI_INT_ENABLE_REG); /* ack and mask */ iowrite32(0, base + SATAINTSTAT_REG); iowrite32(0x7ff, base + SATAINTMASK_REG); clk_disable_unprepare(priv->clk); return 0; } #ifdef CONFIG_PM_SLEEP static int sata_rcar_suspend(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; int ret; ret = ata_host_suspend(host, PMSG_SUSPEND); if (!ret) { /* disable interrupts */ iowrite32(0, base + ATAPI_INT_ENABLE_REG); /* mask */ iowrite32(0x7ff, base + SATAINTMASK_REG); clk_disable_unprepare(priv->clk); } return ret; } static int sata_rcar_resume(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct sata_rcar_priv *priv = host->private_data; void __iomem *base = priv->base; clk_prepare_enable(priv->clk); /* ack and mask */ iowrite32(0, base + SATAINTSTAT_REG); iowrite32(0x7ff, base + SATAINTMASK_REG); /* enable interrupts */ iowrite32(ATAPI_INT_ENABLE_SATAINT, base + ATAPI_INT_ENABLE_REG); ata_host_resume(host); return 0; } static int sata_rcar_restore(struct device *dev) { struct ata_host *host = dev_get_drvdata(dev); struct sata_rcar_priv *priv = host->private_data; clk_prepare_enable(priv->clk); sata_rcar_setup_port(host); /* initialize host controller */ sata_rcar_init_controller(host); ata_host_resume(host); return 0; } static const struct dev_pm_ops sata_rcar_pm_ops = { .suspend = sata_rcar_suspend, .resume = sata_rcar_resume, .freeze = sata_rcar_suspend, .thaw = sata_rcar_resume, .poweroff = sata_rcar_suspend, .restore = sata_rcar_restore, }; #endif static struct platform_driver sata_rcar_driver = { .probe = sata_rcar_probe, .remove = sata_rcar_remove, .id_table = sata_rcar_id_table, .driver = { .name = DRV_NAME, .of_match_table = sata_rcar_match, #ifdef CONFIG_PM_SLEEP .pm = &sata_rcar_pm_ops, #endif }, }; module_platform_driver(sata_rcar_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Vladimir Barinov"); MODULE_DESCRIPTION("Renesas R-Car SATA controller low level driver");
gpl-2.0